chiark / gitweb /
make build reproducible by fixing sort order in docs
[fdroidserver.git] / tests / common.TestCase
1 #!/usr/bin/env python3
2
3 # http://www.drdobbs.com/testing/unit-testing-with-python/240165163
4
5 import inspect
6 import optparse
7 import os
8 import re
9 import shutil
10 import sys
11 import tempfile
12 import unittest
13
14 localmodule = os.path.realpath(
15     os.path.join(os.path.dirname(inspect.getfile(inspect.currentframe())), '..'))
16 print('localmodule: ' + localmodule)
17 if localmodule not in sys.path:
18     sys.path.insert(0, localmodule)
19
20 import fdroidserver.common
21 import fdroidserver.metadata
22
23
24 class CommonTest(unittest.TestCase):
25     '''fdroidserver/common.py'''
26
27     def _set_build_tools(self):
28         build_tools = os.path.join(fdroidserver.common.config['sdk_path'], 'build-tools')
29         if os.path.exists(build_tools):
30             fdroidserver.common.config['build_tools'] = ''
31             for f in sorted(os.listdir(build_tools), reverse=True):
32                 versioned = os.path.join(build_tools, f)
33                 if os.path.isdir(versioned) \
34                         and os.path.isfile(os.path.join(versioned, 'aapt')):
35                     fdroidserver.common.config['build_tools'] = versioned
36                     break
37             return True
38         else:
39             print('no build-tools found: ' + build_tools)
40             return False
41
42     def _find_all(self):
43         for cmd in ('aapt', 'adb', 'android', 'zipalign'):
44             path = fdroidserver.common.find_sdk_tools_cmd(cmd)
45             if path is not None:
46                 self.assertTrue(os.path.exists(path))
47                 self.assertTrue(os.path.isfile(path))
48
49     def test_find_sdk_tools_cmd(self):
50         fdroidserver.common.config = dict()
51         # TODO add this once everything works without sdk_path set in config
52         # self._find_all()
53         sdk_path = os.getenv('ANDROID_HOME')
54         if os.path.exists(sdk_path):
55             fdroidserver.common.config['sdk_path'] = sdk_path
56             if os.path.exists('/usr/bin/aapt'):
57                 # this test only works when /usr/bin/aapt is installed
58                 self._find_all()
59             build_tools = os.path.join(sdk_path, 'build-tools')
60             if self._set_build_tools():
61                 self._find_all()
62             else:
63                 print('no build-tools found: ' + build_tools)
64
65     def testIsApkDebuggable(self):
66         config = dict()
67         fdroidserver.common.fill_config_defaults(config)
68         fdroidserver.common.config = config
69         self._set_build_tools()
70         config['aapt'] = fdroidserver.common.find_sdk_tools_cmd('aapt')
71         # these are set debuggable
72         testfiles = []
73         testfiles.append(os.path.join(os.path.dirname(__file__), 'urzip.apk'))
74         testfiles.append(os.path.join(os.path.dirname(__file__), 'urzip-badsig.apk'))
75         testfiles.append(os.path.join(os.path.dirname(__file__), 'urzip-badcert.apk'))
76         for apkfile in testfiles:
77             debuggable = fdroidserver.common.isApkDebuggable(apkfile, config)
78             self.assertTrue(debuggable,
79                             "debuggable APK state was not properly parsed!")
80         # these are set NOT debuggable
81         testfiles = []
82         testfiles.append(os.path.join(os.path.dirname(__file__), 'urzip-release.apk'))
83         testfiles.append(os.path.join(os.path.dirname(__file__), 'urzip-release-unsigned.apk'))
84         for apkfile in testfiles:
85             debuggable = fdroidserver.common.isApkDebuggable(apkfile, config)
86             self.assertFalse(debuggable,
87                              "debuggable APK state was not properly parsed!")
88
89     def testPackageNameValidity(self):
90         for name in ["org.fdroid.fdroid",
91                      "org.f_droid.fdr0ID"]:
92             self.assertTrue(fdroidserver.common.is_valid_package_name(name),
93                             "{0} should be a valid package name".format(name))
94         for name in ["0rg.fdroid.fdroid",
95                      ".f_droid.fdr0ID",
96                      "org.fdroid/fdroid",
97                      "/org.fdroid.fdroid"]:
98             self.assertFalse(fdroidserver.common.is_valid_package_name(name),
99                              "{0} should not be a valid package name".format(name))
100
101     def test_prepare_sources(self):
102         testint = 99999999
103         teststr = 'FAKE_STR_FOR_TESTING'
104
105         tmpdir = os.path.join(os.path.dirname(__file__), '..', '.testfiles')
106         if not os.path.exists(tmpdir):
107             os.makedirs(tmpdir)
108         tmptestsdir = tempfile.mkdtemp(prefix='test_prepare_sources', dir=tmpdir)
109         shutil.copytree(os.path.join(os.path.dirname(__file__), 'source-files'),
110                         os.path.join(tmptestsdir, 'source-files'))
111
112         testdir = os.path.join(tmptestsdir, 'source-files', 'fdroid', 'fdroidclient')
113
114         config = dict()
115         config['sdk_path'] = os.getenv('ANDROID_HOME')
116         config['ndk_paths'] = {'r10d': os.getenv('ANDROID_NDK_HOME')}
117         config['build_tools'] = 'FAKE_BUILD_TOOLS_VERSION'
118         fdroidserver.common.config = config
119         app = fdroidserver.metadata.App()
120         app.id = 'org.fdroid.froid'
121         build = fdroidserver.metadata.Build()
122         build.commit = 'master'
123         build.forceversion = True
124         build.forcevercode = True
125         build.gradle = ['yes']
126         build.target = 'android-' + str(testint)
127         build.version = teststr
128         build.vercode = testint
129
130         class FakeVcs():
131             # no need to change to the correct commit here
132             def gotorevision(self, rev, refresh=True):
133                 pass
134
135             # no srclib info needed, but it could be added...
136             def getsrclib(self):
137                 return None
138
139         fdroidserver.common.prepare_source(FakeVcs(), app, build, testdir, testdir, testdir)
140
141         with open(os.path.join(testdir, 'build.gradle'), 'r') as f:
142             filedata = f.read()
143         self.assertIsNotNone(re.search("\s+compileSdkVersion %s\s+" % testint, filedata))
144
145         with open(os.path.join(testdir, 'AndroidManifest.xml')) as f:
146             filedata = f.read()
147         self.assertIsNone(re.search('android:debuggable', filedata))
148         self.assertIsNotNone(re.search('android:versionName="%s"' % build.version, filedata))
149         self.assertIsNotNone(re.search('android:versionCode="%s"' % build.vercode, filedata))
150
151     def test_fdroid_popen_stderr_redirect(self):
152         commands = ['sh', '-c', 'echo stdout message && echo stderr message 1>&2']
153
154         p = fdroidserver.common.FDroidPopen(commands)
155         self.assertEqual(p.output, 'stdout message\nstderr message\n')
156
157         p = fdroidserver.common.FDroidPopen(commands, stderr_to_stdout=False)
158         self.assertEqual(p.output, 'stdout message\n')
159
160 if __name__ == "__main__":
161     parser = optparse.OptionParser()
162     parser.add_option("-v", "--verbose", action="store_true", default=False,
163                       help="Spew out even more information than normal")
164     (fdroidserver.common.options, args) = parser.parse_args(['--verbose'])
165
166     newSuite = unittest.TestSuite()
167     newSuite.addTest(unittest.makeSuite(CommonTest))
168     unittest.main()