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