-
Notifications
You must be signed in to change notification settings - Fork 27
/
runtests.py
executable file
·2203 lines (1911 loc) · 88.9 KB
/
runtests.py
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This software is licensed as described in the file LICENSE, which
# you should have received as part of this distribution.
"""Functional tests for the Trac-GitHub plugin.
Trac's testing framework isn't well suited for plugins, so we NIH'd a bit.
"""
import argparse
import BaseHTTPServer
import ConfigParser
import json
import os
import random
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
import traceback
import unittest
import urllib2
import urlparse
from lxml import html
from trac.env import Environment
from trac.ticket.model import Ticket
from trac.util.translation import _
import requests
GIT = 'test-git-foo'
ALTGIT = 'test-git-bar'
NOGHGIT = 'test-git-nogithub'
TESTDIR = '.'
ENV = 'test-trac-github'
CONF = '%s/conf/trac.ini' % ENV
HTDIGEST = '%s/passwd' % ENV
URL = 'http://localhost:8765/%s' % ENV
SECRET = 'test-secret'
HEADERS = {'Content-Type': 'application/json', 'X-GitHub-Event': 'push'}
UPDATEHOOK = '%s-mirror/hooks/trac-github-update' % GIT
# Global variables overriden when running the module (see very bottom of file)
COVERAGE = False
SHOW_LOG = False
TRAC_ADMIN_BIN = 'trac-admin'
TRACD_BIN = 'tracd'
COVERAGE_BIN = 'coverage'
GIT_DEFAULT_BRANCH = 'main'
class HttpNoRedirectHandler(urllib2.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)
urllib2.install_opener(urllib2.build_opener(HttpNoRedirectHandler()))
def d(*args):
"""
Return an absolute path where the given arguments are joined and
prepended with the TESTDIR.
"""
return os.path.join(TESTDIR, *args)
def git_check_output(*args, **kwargs):
"""
Run the given git command (`*args`), optionally on the given
repository (`kwargs['repo']`), return the output of that command
as a string.
"""
repo = kwargs.pop('repo', None)
if repo is None:
cmdargs = ["git"] + list(args)
else:
cmdargs = ["git", "-C", d(repo)] + list(args)
return subprocess.check_output(cmdargs, **kwargs)
class TracGitHubTests(unittest.TestCase):
cached_git = False
@classmethod
def setUpClass(cls):
cls.createGitRepositories()
cls.createTracEnvironment()
cls.startTracd()
cls.env = Environment(d(ENV))
@classmethod
def tearDownClass(cls):
cls.env.shutdown()
cls.stopTracd()
cls.removeTracEnvironment()
cls.removeGitRepositories()
@classmethod
def createGitRepositories(cls):
git_check_output('init', d(GIT))
git_check_output('init', d(ALTGIT))
git_check_output('init', d(NOGHGIT))
cls.makeGitCommit(GIT, 'README', 'default git repository\n')
cls.makeGitCommit(ALTGIT, 'README', 'alternative git repository\n')
cls.makeGitCommit(NOGHGIT, 'README', 'git repository not on GitHub\n')
git_check_output('clone', '--quiet', '--mirror', d(GIT), d('%s-mirror' % GIT))
git_check_output('clone', '--quiet', '--mirror', d(ALTGIT), d('%s-mirror' % ALTGIT))
@classmethod
def removeGitRepositories(cls):
shutil.rmtree(d(GIT))
shutil.rmtree(d(ALTGIT))
shutil.rmtree(d(NOGHGIT))
shutil.rmtree(d('%s-mirror' % GIT))
shutil.rmtree(d('%s-mirror' % ALTGIT))
@classmethod
def createTracEnvironment(cls, **kwargs):
subprocess.check_output([TRAC_ADMIN_BIN, d(ENV), 'initenv',
'Trac - GitHub tests', 'sqlite:db/trac.db'])
subprocess.check_output([TRAC_ADMIN_BIN, d(ENV), 'permission',
'add', 'anonymous', 'TRAC_ADMIN'])
conf = ConfigParser.ConfigParser()
with open(d(CONF), 'rb') as fp:
conf.readfp(fp)
conf.add_section('components')
conf.set('components', 'trac.versioncontrol.web_ui.browser.BrowserModule', 'disabled')
conf.set('components', 'trac.versioncontrol.web_ui.changeset.ChangesetModule', 'disabled')
conf.set('components', 'trac.versioncontrol.web_ui.log.LogModule', 'disabled')
conf.set('components', 'trac.versioncontrol.svn_fs.*', 'disabled') # avoid spurious log messages
conf.set('components', 'tracext.git.*', 'enabled') # Trac 0.12.4
conf.set('components', 'tracext.github.*', 'enabled')
conf.set('components', 'tracopt.ticket.commit_updater.*', 'enabled')
conf.set('components', 'tracopt.versioncontrol.git.*', 'enabled') # Trac 1.0
cached_git = cls.cached_git
if 'cached_git' in kwargs:
cached_git = kwargs['cached_git']
if cached_git:
conf.add_section('git')
conf.set('git', 'cached_repository', 'true')
conf.set('git', 'persistent_cache', 'true')
if not conf.has_section('github'):
conf.add_section('github')
client_id = '01234567890123456789'
if 'client_id' in kwargs:
client_id = kwargs['client_id']
conf.set('github', 'client_id', client_id)
client_secret = '0123456789abcdef0123456789abcdef012345678'
if 'client_secret' in kwargs:
client_secret = kwargs['client_secret']
conf.set('github', 'client_secret', client_secret)
conf.set('github', 'repository', 'aaugustin/trac-github')
conf.set('github', 'alt.repository', 'follower/trac-github')
conf.set('github', 'alt.branches', '%s stable/*' % GIT_DEFAULT_BRANCH)
if 'request_email' in kwargs:
conf.set('github', 'request_email', kwargs['request_email'])
if 'preferred_email_domain' in kwargs:
conf.set('github', 'preferred_email_domain', kwargs['preferred_email_domain'])
if 'organization' in kwargs:
conf.set('github', 'organization', kwargs['organization'])
if 'username' in kwargs and 'access_token' in kwargs:
conf.set('github', 'username', kwargs['username'])
conf.set('github', 'access_token', kwargs['access_token'])
if 'webhook_secret' in kwargs:
conf.set('github', 'webhook_secret', kwargs['webhook_secret'])
if 'username_prefix' in kwargs:
conf.set('github', 'username_prefix', kwargs['username_prefix'])
if SHOW_LOG:
# The [logging] section already exists in the default trac.ini file.
conf.set('logging', 'log_type', 'stderr')
else:
# Write debug log so you can read it on crashes
conf.set('logging', 'log_type', 'file')
conf.set('logging', 'log_file', 'trac.log')
conf.set('logging', 'log_level', 'DEBUG')
conf.add_section('repositories')
conf.set('repositories', '.dir', d('%s-mirror' % GIT))
conf.set('repositories', '.type', 'git')
conf.set('repositories', 'alt.dir', d('%s-mirror' % ALTGIT))
conf.set('repositories', 'alt.type', 'git')
conf.set('repositories', 'nogh.dir', d(NOGHGIT, '.git'))
conf.set('repositories', 'nogh.type', 'git')
# Show changed files in timeline, which will trigger the
# IPermissionPolicy code paths
conf.set('timeline', 'changeset_show_files', '-1')
old_permission_policies = conf.get('trac', 'permission_policies')
if 'GitHubPolicy' not in old_permission_policies:
conf.set('trac', 'permission_policies',
'GitHubPolicy, %s' % old_permission_policies)
with open(d(CONF), 'wb') as fp:
conf.write(fp)
with open(d(HTDIGEST), 'w') as fp:
# user: user, pass: pass, realm: realm
fp.write("user:realm:8493fbc53ba582fb4c044c456bdc40eb\n")
run_resync = kwargs['resync'] if 'resync' in kwargs else True
if run_resync:
# Allow skipping resync for perfomance reasons if not required
subprocess.check_output([TRAC_ADMIN_BIN, d(ENV), 'repository', 'resync', ''])
subprocess.check_output([TRAC_ADMIN_BIN, d(ENV), 'repository', 'resync', 'alt'])
subprocess.check_output([TRAC_ADMIN_BIN, d(ENV), 'repository', 'resync', 'nogh'])
@classmethod
def removeTracEnvironment(cls):
shutil.rmtree(d(ENV))
@classmethod
def startTracd(cls, **kwargs):
if COVERAGE:
tracd = [COVERAGE_BIN, 'run', '--append', '--branch',
'--source=tracext.github', TRACD_BIN]
else:
tracd = [TRACD_BIN]
if SHOW_LOG:
kwargs['stdout'] = sys.stdout
kwargs['stderr'] = sys.stderr
cls.tracd = subprocess.Popen(tracd + ['--port', '8765', '--auth=*,%s,realm' % d(HTDIGEST), d(ENV)], **kwargs)
waittime = 0.1
for _ in range(5):
try:
urllib2.urlopen(URL)
except urllib2.URLError:
time.sleep(waittime)
waittime *= 2
else:
break
else:
raise RuntimeError("Can't communicate with tracd running on port 8765")
@classmethod
def stopTracd(cls):
cls.tracd.send_signal(signal.SIGINT)
cls.tracd.wait()
@staticmethod
def makeGitBranch(repo, branch):
git_check_output('branch', branch, repo=repo)
@staticmethod
def makeGitCommit(repo, path, content, message='edit', branch=None):
if branch is None:
branch = GIT_DEFAULT_BRANCH
if branch != GIT_DEFAULT_BRANCH:
git_check_output('checkout', branch, repo=repo)
with open(d(repo, path), 'wb') as fp:
fp.write(content)
git_check_output('add', path, repo=repo)
git_check_output('commit', '-m', message, repo=repo)
if branch != GIT_DEFAULT_BRANCH:
git_check_output('checkout', GIT_DEFAULT_BRANCH, repo=repo)
changeset = git_check_output('rev-parse', 'HEAD', repo=repo)
return changeset.strip()
@staticmethod
def makeGitHubHookPayload(n=1, reponame=''):
# See https://developer.github.com/v3/activity/events/types/#pushevent
# We don't reproduce the entire payload, only what the plugin needs.
repo = {'': GIT, 'alt': ALTGIT}[reponame]
commits = []
log = git_check_output(
'log',
'-%d' % n,
'--branches',
'--format=oneline',
'--topo-order',
repo=repo
)
for line in log.splitlines():
id, _, message = line.partition(' ')
commits.append({'id': id, 'message': message, 'distinct': True})
payload = {'commits': commits}
return payload
@staticmethod
def openGitHubHook(n=1, reponame='', payload=None):
if not payload:
payload = TracGitHubTests.makeGitHubHookPayload(n, reponame)
url = (URL + '/github/' + reponame) if reponame else URL + '/github'
request = urllib2.Request(url, json.dumps(payload), HEADERS)
return urllib2.urlopen(request)
class GitHubBrowserTests(TracGitHubTests):
def testLinkToChangeset(self):
self.makeGitCommit(GIT, 'myfile', 'for browser tests')
changeset = self.openGitHubHook().read().rstrip()[-40:]
try:
urllib2.urlopen(URL + '/changeset/' + changeset)
except urllib2.HTTPError as exc:
self.assertEqual(exc.code, 302)
self.assertEqual(exc.headers['Location'],
'https://github.com/aaugustin/trac-github/commit/%s' % changeset)
else:
self.fail("URL didn't redirect")
def testAlternateLinkToChangeset(self):
self.makeGitCommit(ALTGIT, 'myfile', 'for browser tests')
changeset = self.openGitHubHook(1, 'alt').read().rstrip()[-40:]
try:
urllib2.urlopen(URL + '/changeset/' + changeset + '/alt')
except urllib2.HTTPError as exc:
self.assertEqual(exc.code, 302)
self.assertEqual(exc.headers['Location'],
'https://github.com/follower/trac-github/commit/%s' % changeset)
else:
self.fail("URL didn't redirect")
def testNonGitHubLinkToChangeset(self):
changeset = self.makeGitCommit(NOGHGIT, 'myfile', 'for browser tests')
subprocess.check_output([TRAC_ADMIN_BIN, d(ENV), 'changeset', 'added', 'nogh', changeset])
response = requests.get(URL + '/changeset/' + changeset + '/nogh', allow_redirects=False)
self.assertEqual(response.status_code, 200)
def testLinkToPath(self):
self.makeGitCommit(GIT, 'myfile', 'for more browser tests')
changeset = self.openGitHubHook().read().rstrip()[-40:]
try:
urllib2.urlopen(URL + '/changeset/' + changeset + '/myfile')
except urllib2.HTTPError as exc:
self.assertEqual(exc.code, 302)
self.assertEqual(exc.headers['Location'],
'https://github.com/aaugustin/trac-github/blob/%s/myfile' % changeset)
else:
self.fail("URL didn't redirect")
def testAlternateLinkToPath(self):
self.makeGitCommit(ALTGIT, 'myfile', 'for more browser tests')
changeset = self.openGitHubHook(1, 'alt').read().rstrip()[-40:]
try:
urllib2.urlopen(URL + '/changeset/' + changeset + '/alt/myfile')
except urllib2.HTTPError as exc:
self.assertEqual(exc.code, 302)
self.assertEqual(exc.headers['Location'],
'https://github.com/follower/trac-github/blob/%s/myfile' % changeset)
else:
self.fail("URL didn't redirect")
def testNonGitHubLinkToPath(self):
changeset = self.makeGitCommit(NOGHGIT, 'myfile', 'for more browser tests')
subprocess.check_output([TRAC_ADMIN_BIN, d(ENV), 'changeset', 'added', 'nogh', changeset])
response = requests.get(URL + '/changeset/' + changeset + '/nogh/myfile', allow_redirects=False)
self.assertEqual(response.status_code, 200)
def testBadChangeset(self):
with self.assertRaisesRegexp(urllib2.HTTPError, r'^HTTP Error 404: Not Found$'):
urllib2.urlopen(URL + '/changeset/1234567890')
def testBadUrl(self):
with self.assertRaisesRegexp(urllib2.HTTPError, r'^HTTP Error 404: Not Found$'):
urllib2.urlopen(URL + '/changesetnosuchurl')
def testTimelineFiltering(self):
self.makeGitBranch(GIT, 'stable/2.0')
self.makeGitBranch(GIT, 'unstable/2.0')
self.makeGitBranch(ALTGIT, 'stable/2.0')
self.makeGitBranch(ALTGIT, 'unstable/2.0')
self.makeGitCommit(GIT, 'myfile', 'timeline 1\n', 'msg 1')
self.makeGitCommit(GIT, 'myfile', 'timeline 2\n', 'msg 2', 'stable/2.0')
self.makeGitCommit(GIT, 'myfile', 'timeline 3\n', 'msg 3', 'unstable/2.0')
self.makeGitCommit(ALTGIT, 'myfile', 'timeline 4\n', 'msg 4')
self.makeGitCommit(ALTGIT, 'myfile', 'timeline 5\n', 'msg 5', 'stable/2.0')
self.makeGitCommit(ALTGIT, 'myfile', 'timeline 6\n', 'msg 6', 'unstable/2.0')
self.openGitHubHook(3)
self.openGitHubHook(3, 'alt')
html = urllib2.urlopen(URL + '/timeline').read()
self.assertTrue('msg 1' in html)
self.assertTrue('msg 2' in html)
self.assertTrue('msg 3' in html)
self.assertTrue('msg 4' in html)
self.assertTrue('msg 5' in html)
self.assertFalse('msg 6' in html)
class GitHubLoginModuleTests(TracGitHubTests):
@classmethod
def startTracd(cls, **kwargs):
# Disable check for HTTPS to avoid adding complexity to the test setup.
kwargs['env'] = os.environ.copy()
kwargs['env']['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
super(GitHubLoginModuleTests, cls).startTracd(**kwargs)
def testLogin(self):
response = requests.get(URL + '/github/login', allow_redirects=False)
self.assertEqual(response.status_code, 302)
redirect_url = urlparse.urlparse(response.headers['Location'])
self.assertEqual(redirect_url.scheme, 'https')
self.assertEqual(redirect_url.netloc, 'github.com')
self.assertEqual(redirect_url.path, '/login/oauth/authorize')
params = urlparse.parse_qs(redirect_url.query, keep_blank_values=True)
state = params['state'][0] # this is a random value
self.assertEqual(params, {
'client_id': ['01234567890123456789'],
'redirect_uri': [URL + '/github/oauth'],
'response_type': ['code'],
'scope': [''],
'state': [state],
})
def testOauthInvalidState(self):
session = requests.Session()
# This adds a oauth_state parameter in the Trac session.
response = session.get(URL + '/github/login', allow_redirects=False)
self.assertEqual(response.status_code, 302)
response = session.get(
URL + '/github/oauth?code=01234567890123456789&state=wrong_state',
allow_redirects=False)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers['Location'], URL)
response = session.get(URL)
self.assertEqual(response.status_code, 200)
self.assertIn(
"Invalid request. Please try to login again.", response.text)
def testOauthInvalidStateWithoutSession(self):
session = requests.Session()
# There's no oauth_state parameter in the Trac session.
# OAuth callback requests without state must still fail.
response = session.get(
URL + '/github/oauth?code=01234567890123456789',
allow_redirects=False)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers['Location'], URL)
response = session.get(URL)
self.assertEqual(response.status_code, 200)
self.assertIn(
"Invalid request. Please try to login again.", response.text)
def testLogout(self):
response = requests.get(URL + '/github/logout', allow_redirects=False)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers['Location'], URL)
class GitHubLoginModuleConfigurationTests(TracGitHubTests):
# Append custom failure messages to the automatically generated ones
longMessage = True
@classmethod
def setUpClass(cls):
cls.createGitRepositories()
cls.mockdata = startAPIMock(8768)
trac_env = os.environ.copy()
trac_env.update({
'TRAC_GITHUB_OAUTH_URL': 'http://127.0.0.1:8768/',
'TRAC_GITHUB_API_URL': 'http://127.0.0.1:8768/',
'OAUTHLIB_INSECURE_TRANSPORT': '1'
})
trac_env_broken = trac_env.copy()
trac_env_broken.update({
'TRAC_GITHUB_OAUTH_URL': 'http://127.0.0.1:8769/',
'TRAC_GITHUB_API_URL': 'http://127.0.0.1:8769/',
})
trac_env_broken_api = trac_env.copy()
trac_env_broken_api.update({
'TRAC_GITHUB_API_URL': 'http://127.0.0.1:8769/',
})
cls.trac_env = trac_env
cls.trac_env_broken = trac_env_broken
cls.trac_env_broken_api = trac_env_broken_api
with open(d(SECRET), 'wb') as fp:
fp.write('98765432109876543210')
@classmethod
def tearDownClass(cls):
cls.removeGitRepositories()
os.remove(d(SECRET))
def testLoginWithReqEmail(self):
"""Test that configuring request_email = true requests the user:email scope from GitHub"""
with TracContext(self, request_email=True, resync=False):
response = requests.get(URL + '/github/login', allow_redirects=False)
self.assertEqual(response.status_code, 302)
redirect_url = urlparse.urlparse(response.headers['Location'])
self.assertEqual(redirect_url.scheme, 'https')
self.assertEqual(redirect_url.netloc, 'github.com')
self.assertEqual(redirect_url.path, '/login/oauth/authorize')
params = urlparse.parse_qs(redirect_url.query, keep_blank_values=True)
state = params['state'][0] # this is a random value
self.assertEqual(params, {
'client_id': ['01234567890123456789'],
'redirect_uri': [URL + '/github/oauth'],
'response_type': ['code'],
'scope': ['user:email'],
'state': [state],
})
def loginAndVerifyClientId(self, expected_client_id):
"""
Open the login page and check that the client_id in the redirect target
matches the expected value.
"""
response = requests.get(URL + '/github/login', allow_redirects=False)
self.assertEqual(response.status_code, 302)
redirect_url = urlparse.urlparse(response.headers['Location'])
self.assertEqual(redirect_url.scheme, 'https')
self.assertEqual(redirect_url.netloc, 'github.com')
self.assertEqual(redirect_url.path, '/login/oauth/authorize')
params = urlparse.parse_qs(redirect_url.query, keep_blank_values=True)
state = params['state'][0] # this is a random value
self.assertEqual(params, {
'client_id': [expected_client_id],
'redirect_uri': [URL + '/github/oauth'],
'response_type': ['code'],
'scope': [''],
'state': [state],
})
def testLoginWithSecretInEnvironment(self):
"""Test that passing client_id in environment works"""
secret_env = os.environ.copy()
secret_env.update({'TRAC_GITHUB_CLIENT_ID': '98765432109876543210'})
with TracContext(self, client_id='TRAC_GITHUB_CLIENT_ID', env=secret_env):
self.loginAndVerifyClientId('98765432109876543210')
def testLoginWithSecretInFile(self):
"""Test that passing client_id in absolute path works"""
path = d(SECRET)
with TracContext(self, client_id=path):
self.loginAndVerifyClientId('98765432109876543210')
def testLoginWithSecretInRelativeFile(self):
"""Test that passing client_id in relative path works"""
path = './' + os.path.relpath(d(SECRET))
with TracContext(self, client_id=path):
self.loginAndVerifyClientId('98765432109876543210')
def testLoginWithUnconfiguredClientId(self):
"""Test that leaving client_id unconfigured prints a warning"""
with TracContext(self, client_id=''):
session = requests.Session()
response = session.get(URL + '/github/login', allow_redirects=True)
self.assertEqual(response.status_code, 200)
tree = html.fromstring(response.content)
errmsg = ''.join(tree.xpath('//div[@id="warning"]/text()')).strip()
self.assertIn(
"GitHubLogin configuration incomplete, missing client_id or "
"client_secret", errmsg,
"An unconfigured GitHubLogin module should redirect and print "
"a warning on login attempts.")
def attemptHttpAuth(self, testenv, **kwargs):
"""
Helper method that attempts to log in using HTTP authentication in the
given testenv; returns a tuple where the first item is the error
message in the notification box on the trac page loaded after the login
attempt (or an empty string on success) and the second item is the
username as seen by trac.
"""
with TracContext(self, env=testenv, resync=False, **kwargs):
session = requests.Session()
# This logs into trac using HTTP authentication
# This adds a oauth_state parameter in the Trac session.
response = session.get(URL + '/login', auth=requests.auth.HTTPDigestAuth('user', 'pass'))
self.assertNotEqual(response.status_code, 403)
response = session.get(URL + '/newticket') # this should trigger IPermissionGroupProvider
self.assertEqual(response.status_code, 200)
tree = html.fromstring(response.content)
warning = ''.join(tree.xpath('//div[@id="warning"]/text()')).strip()
user = ''
match = re.match(r"logged in as (.*)",
', '.join(tree.xpath('//div[@id="metanav"]/ul/li[@class="first"]/text()')))
if match:
user = match.group(1)
return (warning, user)
def attemptValidOauth(self, testenv, callback, **kwargs):
"""
Helper method that runs a valid OAuth2 attempt in the given testenv
with the given callback; returns a tuple where the first item is the
error message in the notification box on the trac page loaded after the
login attempt (or an empty string on success), the second item is
a list of email addresses found in email fields of the preferences
after login and the third item is the username of the user that was
logged in as seen by trac..
"""
ctxt_kwargs = {}
other_kwargs = {}
for kwarg in kwargs:
if kwarg in TracContext._valid_attrs:
ctxt_kwargs[kwarg] = kwargs[kwarg]
else:
other_kwargs[kwarg] = kwargs[kwarg]
with TracContext(self, env=testenv, resync=False, **ctxt_kwargs):
updateMockData(self.mockdata, postcallback=callback, **other_kwargs)
try:
session = requests.Session()
# This adds a oauth_state parameter in the Trac session.
response = session.get(URL + '/github/login', allow_redirects=False)
self.assertEqual(response.status_code, 302)
# Extract the state from the redirect
redirect_url = urlparse.urlparse(response.headers['Location'])
params = urlparse.parse_qs(redirect_url.query, keep_blank_values=True)
state = params['state'][0] # this is a random value
response = session.get(
URL + '/github/oauth',
params={
'code': '01234567890123456789',
'state': state
},
allow_redirects=False)
self.assertEqual(response.status_code, 302)
response = session.get(URL + '/prefs')
self.assertEqual(response.status_code, 200)
tree = html.fromstring(response.content)
warning = ''.join(tree.xpath('//div[@id="warning"]/text()')).strip()
email = tree.xpath('//input[@id="email"]/@value')
user = ''
match = re.match(r"logged in as (.*)",
', '.join(tree.xpath('//div[@id="metanav"]/ul/li[@class="first"]/text()')))
if match:
user = match.group(1)
return (warning, email, user)
finally:
# disable callback again
updateMockData(self.mockdata, postcallback="")
def testOauthBackendUnavailable(self):
"""
Test that an OAuth backend that resets the connection does not crash
the login
"""
errmsg, emails, _ = self.attemptValidOauth(self.trac_env_broken, "")
self.assertIn(
"Invalid request. Please try to login again.",
errmsg,
"OAuth Authorization Request with unavailable backend should not succeed.")
def testOauthBackendFails(self):
"""Test that an OAuth backend that fails does not crash the login"""
def cb(path, args):
return 403, {}
errmsg, emails, _ = self.attemptValidOauth(self.trac_env, cb)
self.assertIn(
"Invalid request. Please try to login again.",
errmsg,
"OAuth Authorization Request with failing backend should not succeed.")
def oauthCallbackSuccess(self, path, args):
"""
GitHubAPIMock POST callback that contains a successful OAuth
Authentication Response
"""
return 200, {
'access_token': '190c20e9d87de41264749672ccacdd63a0ae2345a63b2703e26e651248c3b50e',
'token_type': 'bearer'
}
def testOauthValidButUnavailAPI(self):
"""
Test that accessing an unavailable GitHub API with what seems to be
a valid OAuth2 token does not crash the login
"""
errmsg, emails, _ = self.attemptValidOauth(self.trac_env_broken_api, self.oauthCallbackSuccess)
self.assertIn(
"An error occurred while communicating with the GitHub API",
errmsg,
"Request to unavailable API with valid OAuth token should print an error.")
def testOauthValidButBrokenAPI(self):
"""
Test that accessing an broken GitHub API with what seems to be a valid
OAuth2 token does not crash the login
"""
errmsg, emails, _ = self.attemptValidOauth(self.trac_env_broken_api,
self.oauthCallbackSuccess,
retcode=403)
self.assertIn(
"An error occurred while communicating with the GitHub API",
errmsg,
"Failing API request with valid OAuth token should print an error.")
def testOauthValidEmailAPIInvalid(self):
"""
Test that a login with a valid OAuth2 but invalid data returned from
the email request API does not crash
"""
answers = {
'/user': {
'user': 'trololol',
'email': '[email protected]',
'login': 'trololol'
},
'/user/email': {
'foo': 'bar'
}
}
errmsg, emails, _ = self.attemptValidOauth(
self.trac_env, self.oauthCallbackSuccess, retcode=200,
answers=answers, request_email=True)
self.assertIn(
"An error occurred while retrieving your email address from the GitHub API",
errmsg,
"Failing email API request with valid OAuth token should print an error.")
def getEmail(self, answers, **kwargs):
"""Get and return the email address the system has chosen for the given config and answers"""
errmsg, emails, _ = self.attemptValidOauth(
self.trac_env, self.oauthCallbackSuccess, retcode=200,
answers=answers, **kwargs)
self.assertEqual(len(errmsg), 0,
"Successful login should not print an error.")
return emails
def getUser(self, answers, **kwargs):
"""Get and return the user name the system has chosen for the given config and answers"""
errmsg, _, user = self.attemptValidOauth(
self.trac_env, self.oauthCallbackSuccess, retcode=200,
answers=answers, **kwargs)
self.assertEqual(len(errmsg), 0,
"Successful login should not print an error.")
return user
def testOauthValid(self):
"""Test that a login with a valid OAuth2 token succeeds"""
answers = {
'/user': {
'user': 'trololol',
'email': '[email protected]',
'login': 'trololol'
}
}
email = self.getEmail(answers)
self.assertEqual(email, ['[email protected]'])
user = self.getUser(answers)
self.assertEqual(user, 'trololol')
def testUsernamePrefix(self):
"""Test that setting a prefix for GitHub usernames works"""
answers = {
'/user': {
'user': 'trololol',
'email': '[email protected]',
'login': 'trololol'
}
}
user = self.getUser(answers, username_prefix='github-')
self.assertEqual(user, 'github-trololol')
errmsg, user = self.attemptHttpAuth(self.trac_env,
username_prefix='github-',
organization='org',
username='github-bot-user',
access_token='accesstoken')
self.assertEqual(len(errmsg), 0,
"HTTP authentication should still work.")
self.assertEqual(user, "user",
"Non-GitHub-authentication should yield unprefixed usernames")
def testOauthEmailIgnoresUnverified(self):
"""
Test that request_email=True ignores unverified email addresses and
prefers primary addresses
"""
answers = {
'/user': {
'user': 'trololol',
'login': 'trololol'
},
'/user/emails': [
{
'email': '[email protected]',
'verified': False,
'primary': True
},
{
'email': '[email protected]',
'verified': True,
'primary': False
},
{
'email': '[email protected]',
'verified': True,
'primary': True
},
]
}
email = self.getEmail(answers, request_email=True)
self.assertEqual(email, ['[email protected]'])
def testPreferredEmailDomain(self):
"""
Test that an email address matching the preferred email domain is
preferred to one marked primary.
"""
answers = {
'/user': {
'user': 'trololol',
'login': 'trololol'
},
'/user/emails': [
{
'email': '[email protected]',
'verified': False,
'primary': True
},
{
'email': '[email protected]',
'verified': True,
'primary': True
},
{
'email': '[email protected]',
'verified': True,
'primary': False
},
]
}
email = self.getEmail(answers, request_email=True,
preferred_email_domain='example.net')
self.assertEqual(email, ['[email protected]'])
def testPreferredEmailFallbackToPrimary(self):
"""
Test that the primary address is chosen if no address matches the
preferred email domain.
"""
answers = {
'/user': {
'user': 'trololol',
'login': 'trololol'
},
'/user/emails': [
{
'email': '[email protected]',
'verified': True,
'primary': True
},
{
'email': '[email protected]',
'verified': True,
'primary': False
},
]
}
email = self.getEmail(answers, request_email=True,
preferred_email_domain='example.org')
self.assertEqual(email, ['[email protected]'])
def testPreferredEmailCaseInsensitive(self):
"""
Test that the preferred email domain is honoured regardless of case.
"""
answers = {
'/user': {
'user': 'trololol',
'login': 'trololol'
},
'/user/emails': [
{
'email': '[email protected]',
'verified': True,
'primary': True
},
{
'email': '[email protected]',
'verified': True,
'primary': False
},
]
}
email = self.getEmail(answers, request_email=True,
preferred_email_domain='example.net')
self.assertEqual(email, ['[email protected]'])
class GitHubPostCommitHookTests(TracGitHubTests):
def testDefaultRepository(self):
output = self.openGitHubHook(0).read()
self.assertEqual(output, "Running hook on (default)\n"
"* Updating clone\n"
"* Synchronizing with clone\n")
def testAlternativeRepository(self):
output = self.openGitHubHook(0, 'alt').read()
self.assertEqual(output, "Running hook on alt\n"
"* Updating clone\n"
"* Synchronizing with clone\n")
def testCommit(self):
self.makeGitCommit(GIT, 'foo', 'foo content\n')
output = self.openGitHubHook().read()
self.assertRegexpMatches(output, r"Running hook on \(default\)\n"
r"\* Updating clone\n"
r"\* Synchronizing with clone\n"
r"\* Adding commit [0-9a-f]{40}\n")
def testMultipleCommits(self):
self.makeGitCommit(GIT, 'bar', 'bar content\n')
self.makeGitCommit(GIT, 'bar', 'more bar content\n')
output = self.openGitHubHook(2).read()
self.assertRegexpMatches(output, r"Running hook on \(default\)\n"
r"\* Updating clone\n"
r"\* Synchronizing with clone\n"
r"\* Adding commits [0-9a-f]{40}, [0-9a-f]{40}\n")
def testCommitOnBranch(self):
self.makeGitBranch(ALTGIT, 'stable/1.0')
self.makeGitCommit(ALTGIT, 'stable', 'stable branch\n', branch='stable/1.0')
self.makeGitBranch(ALTGIT, 'unstable/1.0')
self.makeGitCommit(ALTGIT, 'unstable', 'unstable branch\n', branch='unstable/1.0')
output = self.openGitHubHook(2, 'alt').read()
self.assertRegexpMatches(output, r"Running hook on alt\n"
r"\* Updating clone\n"
r"\* Synchronizing with clone\n"
r"\* Adding commit [0-9a-f]{40}\n"
r"\* Skipping commit [0-9a-f]{40}\n")
def testUnknownCommit(self):
# Emulate self.openGitHubHook to use a non-existent commit id
random_id = ''.join(random.choice('0123456789abcdef') for _ in range(40))
payload = {'commits': [{'id': random_id, 'message': '', 'distinct': True}]}
request = urllib2.Request(URL + '/github', json.dumps(payload), HEADERS)
output = urllib2.urlopen(request).read()
self.assertRegexpMatches(output, r"Running hook on \(default\)\n"
r"\* Updating clone\n"
r"\* Synchronizing with clone\n"
r"\* Unknown commit [0-9a-f]{40}\n")
def testNotification(self):
ticket = Ticket(self.env)
ticket['summary'] = 'I need a commit!'
ticket['status'] = 'new'
ticket['owner'] = ''
ticket_id = ticket.insert()
ticket = Ticket(self.env, ticket_id)
self.assertEqual(ticket['status'], 'new')
self.assertEqual(ticket['resolution'], '')
message = "Fix #%d: here you go." % ticket_id
self.makeGitCommit(GIT, 'newfile', 'with some new content', message)
self.openGitHubHook()
ticket = Ticket(self.env, ticket_id)
self.assertEqual(ticket['status'], 'closed')
self.assertEqual(ticket['resolution'], 'fixed')