Merge lp:~elopio/snapcraft/fix1477638-format_strings1 into lp:~snappy-dev/snapcraft/core

Proposed by Leo Arias
Status: Superseded
Proposed branch: lp:~elopio/snapcraft/fix1477638-format_strings1
Merge into: lp:~snappy-dev/snapcraft/core
Diff against target: 919 lines (+244/-110)
16 files modified
integration-tests/units/jobs.pxu (+4/-4)
snapcraft/__init__.py (+17/-7)
snapcraft/cmds.py (+29/-24)
snapcraft/common.py (+20/-10)
snapcraft/dirs.py (+3/-3)
snapcraft/main.py (+8/-0)
snapcraft/plugin.py (+17/-11)
snapcraft/plugins/ant_project.py (+7/-2)
snapcraft/plugins/copy.py (+5/-1)
snapcraft/plugins/ubuntu.py (+10/-4)
snapcraft/tests/__init__.py (+3/-3)
snapcraft/tests/test_cmds.py (+46/-8)
snapcraft/tests/test_copy_plugin.py (+15/-8)
snapcraft/tests/test_plugin.py (+17/-4)
snapcraft/tests/test_yaml.py (+30/-14)
snapcraft/yaml.py (+13/-7)
To merge this branch: bzr merge lp:~elopio/snapcraft/fix1477638-format_strings1
Reviewer Review Type Date Requested Status
Snappy Developers Pending
Review via email: mp+265702@code.launchpad.net

Commit message

Cleanups to prepare for changing the format strings safely.

To post a comment you must log in.
111. By Leo Arias

Add the missing file.

112. By Leo Arias

Moved the plugindir cleanup to the base test case.

113. By Leo Arias

Fixed the imports.

Unmerged revisions

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'integration-tests/units/jobs.pxu'
2--- integration-tests/units/jobs.pxu 2015-07-22 21:05:20 +0000
3+++ integration-tests/units/jobs.pxu 2015-07-23 17:20:28 +0000
4@@ -3,7 +3,7 @@
5 estimated_duration: 0.1
6 command:
7 set -x
8- OUTPUT=$(${SNAPCRAFT} pull)
9+ OUTPUT=$(${SNAPCRAFT} pull 2>&1)
10 test $? = 1 || exit 1
11 echo $OUTPUT | grep "Could not find snapcraft\.yaml\."
12
13@@ -13,7 +13,7 @@
14 command:
15 set -x
16 cp -rT $PLAINBOX_PROVIDER_DATA/assemble .
17- OUTPUT=$(${SNAPCRAFT} assemble)
18+ OUTPUT=$(${SNAPCRAFT} assemble 2>&1)
19 test $? = 1 || exit 1
20 echo $OUTPUT | grep "Missing snappy metadata file"
21
22@@ -117,7 +117,7 @@
23 command:
24 set -x
25 cp -rT $PLAINBOX_PROVIDER_DATA/conflicts .
26- OUTPUT=$(${SNAPCRAFT} stage)
27+ OUTPUT=$(${SNAPCRAFT} stage 2>&1)
28 test $? = 1 || exit 1
29 echo $OUTPUT | grep "Error: parts p1 and p2 have the following files in common: bin/test" # squished output by bash
30
31@@ -140,7 +140,7 @@
32 set -x
33 cp -rT $PLAINBOX_PROVIDER_DATA/dependencies .
34 sed -i "s/p1:/p1:\n after: [p3]/" snapcraft.yaml
35- OUTPUT=$(${SNAPCRAFT} pull)
36+ OUTPUT=$(${SNAPCRAFT} pull 2>&1)
37 test $? = 1 || exit 1
38 echo $OUTPUT | grep -i "circular dependency"
39
40
41=== modified file 'snapcraft/__init__.py'
42--- snapcraft/__init__.py 2015-07-22 18:59:28 +0000
43+++ snapcraft/__init__.py 2015-07-23 17:20:28 +0000
44@@ -14,11 +14,16 @@
45 # You should have received a copy of the GNU General Public License
46 # along with this program. If not, see <http://www.gnu.org/licenses/>.
47
48+import logging
49 import os
50-import snapcraft.common
51 import subprocess
52 import urllib.parse
53
54+import snapcraft.common
55+
56+
57+logger = logging.getLogger(__name__)
58+
59
60 class BasePlugin:
61
62@@ -53,7 +58,7 @@
63 if cwd is None:
64 cwd = self.builddir
65 if True:
66- print(' '.join(cmd))
67+ logger.info(' '.join(cmd))
68 return snapcraft.common.run(cmd, cwd=cwd, **kwargs)
69
70 def isurl(self, url):
71@@ -71,7 +76,8 @@
72
73 def pull_git(self, source, source_tag=None, source_branch=None):
74 if source_tag and source_branch:
75- snapcraft.common.fatal("You can't specify both source-tag and source-branch for a git source (part '%s')." % self.name)
76+ logger.error("You can't specify both source-tag and source-branch for a git source (part '%s')." % self.name)
77+ snapcraft.common.fatal()
78
79 if os.path.exists(os.path.join(self.sourcedir, ".git")):
80 refspec = 'HEAD'
81@@ -120,11 +126,13 @@
82 elif source.startswith("git:"):
83 source_type = 'git'
84 elif self.isurl(source):
85- snapcraft.common.fatal("Unrecognized source '%s' for part '%s'." % (source, self.name))
86+ logger.error("Unrecognized source '%s' for part '%s'." % (source, self.name))
87+ snapcraft.common.fatal()
88
89 if source_type == 'bzr':
90 if source_branch:
91- snapcraft.common.fatal("You can't specify source-branch for a bzr source (part '%s')." % self.name)
92+ logger.error("You can't specify source-branch for a bzr source (part '%s')." % self.name)
93+ snapcraft.common.fatal()
94 if not self.pull_bzr(source, source_tag=source_tag):
95 return False
96 if not self.run(['cp', '-Trfa', self.sourcedir, self.builddir]):
97@@ -136,9 +144,11 @@
98 return False
99 elif source_type == 'tar':
100 if source_branch:
101- snapcraft.common.fatal("You can't specify source-branch for a tar source (part '%s')." % self.name)
102+ logger.error("You can't specify source-branch for a tar source (part '%s')." % self.name)
103+ snapcraft.common.fatal()
104 if source_tag:
105- snapcraft.common.fatal("You can't specify source-tag for a tar source (part '%s')." % self.name)
106+ logger.error("You can't specify source-tag for a tar source (part '%s')." % self.name)
107+ snapcraft.common.fatal()
108 if not self.pull_tarball(source):
109 return False
110 if not self.extract_tarball(source):
111
112=== modified file 'snapcraft/cmds.py'
113--- snapcraft/cmds.py 2015-07-22 21:05:20 +0000
114+++ snapcraft/cmds.py 2015-07-23 17:20:28 +0000
115@@ -15,21 +15,27 @@
116 # along with this program. If not, see <http://www.gnu.org/licenses/>.
117
118 import glob
119+import logging
120 import os
121 import shlex
122-import snapcraft.common
123-import snapcraft.plugin
124-import snapcraft.yaml
125 import subprocess
126 import sys
127 import tempfile
128 import time
129+
130 import yaml
131
132+import snapcraft.plugin
133+import snapcraft.yaml
134+from snapcraft import common
135+
136+
137+logger = logging.getLogger(__name__)
138+
139
140 def init(args):
141 if os.path.exists("snapcraft.yaml"):
142- snapcraft.common.log("snapcraft.yaml already exists!", file=sys.stderr)
143+ logger.error('snapcraft.yaml already exists!')
144 sys.exit(1)
145 yaml = 'parts:\n'
146 for part_name in args.part:
147@@ -41,23 +47,22 @@
148 yaml = yaml.strip()
149 with open('snapcraft.yaml', mode='w+') as f:
150 f.write(yaml)
151- snapcraft.common.log("Wrote the following as snapcraft.yaml.")
152- print()
153- print(yaml)
154+ logger.info('Wrote the following as snapcraft.yaml:\n{}'.format(yaml))
155 sys.exit(0)
156
157
158 def shell(args):
159 config = snapcraft.yaml.Config()
160- snapcraft.common.env = config.stage_env()
161+ common.env = config.stage_env()
162 userCommand = args.userCommand
163 if not userCommand:
164 userCommand = ['/usr/bin/env', 'PS1=\[\e[1;32m\]snapcraft:\w\$\[\e[0m\] ', '/bin/bash', '--norc']
165- snapcraft.common.run(userCommand)
166+ common.run(userCommand)
167
168
169 def wrap_exe(relexepath):
170- exepath = os.path.join(snapcraft.common.snapdir, relexepath)
171+ snapdir = common.get_snapdir()
172+ exepath = os.path.join(snapdir, relexepath)
173 wrappath = exepath + '.wrapper'
174
175 try:
176@@ -65,13 +70,13 @@
177 except Exception:
178 pass
179
180- script = "#!/bin/sh\n%s\nexec %s $*" % (snapcraft.common.assemble_env().replace(snapcraft.common.snapdir, "$SNAP_APP_PATH"), '"$SNAP_APP_PATH/%s"' % relexepath)
181+ script = "#!/bin/sh\n%s\nexec %s $*" % (common.assemble_env().replace(snapdir, "$SNAP_APP_PATH"), '"$SNAP_APP_PATH/%s"' % relexepath)
182 with open(wrappath, 'w+') as f:
183 f.write(script)
184
185 os.chmod(wrappath, 0o755)
186
187- return os.path.relpath(wrappath, snapcraft.common.snapdir)
188+ return os.path.relpath(wrappath, snapdir)
189
190
191 def snap(args):
192@@ -81,17 +86,17 @@
193 config = snapcraft.yaml.Config()
194
195 if 'snappy-metadata' in config.data:
196- snapcraft.common.run(
197- ['cp', '-arvT', config.data['snappy-metadata'], snapcraft.common.snapdir + '/meta'])
198+ common.run(
199+ ['cp', '-arvT', config.data['snappy-metadata'], common.get_snapdir() + '/meta'])
200 if not os.path.exists('snap/meta/package.yaml'):
201- snapcraft.common.log("Missing snappy metadata file 'meta/package.yaml'. Try specifying 'snappy-metadata' in snapcraft.yaml, pointing to a meta directory in your source tree.")
202+ logger.error("Missing snappy metadata file 'meta/package.yaml'. Try specifying 'snappy-metadata' in snapcraft.yaml, pointing to a meta directory in your source tree.")
203 sys.exit(1)
204
205 # wrap all included commands
206 with open("snap/meta/package.yaml", 'r') as f:
207 package = yaml.load(f)
208
209- snapcraft.common.env = config.snap_env()
210+ common.env = config.snap_env()
211
212 def replace_cmd(execparts, cmd):
213 newparts = [cmd] + execparts[1:]
214@@ -125,7 +130,7 @@
215 def assemble(args):
216 args.cmd = 'snap'
217 snap(args)
218- snapcraft.common.run(['snappy', 'build', snapcraft.common.snapdir])
219+ common.run(['snappy', 'build', common.get_snapdir()])
220
221
222 def run(args):
223@@ -136,7 +141,7 @@
224 os.makedirs(qemudir)
225 except FileExistsError:
226 pass
227- snapcraft.common.run(
228+ common.run(
229 ['sudo', 'ubuntu-device-flash', 'core', '--developer-mode', '--enable-ssh', '15.04', '-o', qemu_img],
230 cwd=qemudir)
231 qemu = subprocess.Popen(
232@@ -186,7 +191,7 @@
233 for otherPartName in partsFiles:
234 common = partFiles & partsFiles[otherPartName]
235 if common:
236- snapcraft.common.log("Error: parts %s and %s have the following files in common:\n %s" % (otherPartName, part.names()[0], '\n '.join(sorted(common))))
237+ logger.error('Error: parts %s and %s have the following files in common:\n %s' % (otherPartName, part.names()[0], '\n '.join(sorted(common))))
238 return False
239
240 # And add our files to the list
241@@ -201,9 +206,9 @@
242
243 cmds = [args.cmd]
244
245- if cmds[0] in snapcraft.common.commandOrder:
246+ if cmds[0] in common.COMMAND_ORDER:
247 forceCommand = cmds[0]
248- cmds = snapcraft.common.commandOrder[0:snapcraft.common.commandOrder.index(cmds[0]) + 1]
249+ cmds = common.COMMAND_ORDER[0:common.COMMAND_ORDER.index(cmds[0]) + 1]
250
251 config = snapcraft.yaml.Config()
252
253@@ -214,7 +219,7 @@
254 if subprocess.call(['dpkg-query', '-s', checkpkg], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) != 0:
255 newPackages.append(checkpkg)
256 if newPackages:
257- print("Installing required packages on the host system: " + ", ".join(newPackages))
258+ logger.info('Installing required packages on the host system: ' + ', '.join(newPackages))
259 subprocess.call(['sudo', 'apt-get', '-y', 'install'] + newPackages, stdout=subprocess.DEVNULL)
260
261 for part in config.all_parts:
262@@ -229,8 +234,8 @@
263 if not check_for_collisions(config.all_parts):
264 sys.exit(1)
265
266- snapcraft.common.env = config.build_env_for_part(part)
267+ common.env = config.build_env_for_part(part)
268 force = forceAll or cmd == forceCommand
269 if not getattr(part, cmd)(force=force):
270- snapcraft.common.log("Failed doing %s for %s!" % (cmd, part.names()[0]))
271+ logger.error('Failed doing %s for %s!' % (cmd, part.names()[0]))
272 sys.exit(1)
273
274=== modified file 'snapcraft/common.py'
275--- snapcraft/common.py 2015-07-14 21:15:07 +0000
276+++ snapcraft/common.py 2015-07-23 17:20:28 +0000
277@@ -21,6 +21,11 @@
278 import sys
279 import tempfile
280
281+
282+COMMAND_ORDER = ["pull", "build", "stage", "snap"]
283+_DEFAULT_PLUGINDIR = '/usr/share/snapcraft/plugins'
284+_plugindir = _DEFAULT_PLUGINDIR
285+
286 env = []
287
288
289@@ -39,17 +44,22 @@
290 return subprocess.call(['/bin/sh', f.name] + cmd, **kwargs) == 0
291
292
293-def log(msg, file=None):
294- print('\033[01m' + msg + '\033[0m', file=None)
295-
296-
297 def fatal(msg):
298- log(msg, file=sys.stderr)
299 sys.exit(1)
300
301
302-commandOrder = ["pull", "build", "stage", "snap"]
303-stagedir = os.path.join(os.getcwd(), "stage")
304-snapdir = os.path.join(os.getcwd(), "snap")
305-
306-plugindir = '/usr/share/snapcraft/plugins'
307+def get_stagedir():
308+ return os.path.join(os.getcwd(), 'stage')
309+
310+
311+def get_snapdir():
312+ return os.path.join(os.getcwd(), 'snap')
313+
314+
315+def set_plugindir(plugindir):
316+ global _plugindir
317+ _plugindir = plugindir
318+
319+
320+def get_plugindir():
321+ return _plugindir
322
323=== modified file 'snapcraft/dirs.py'
324--- snapcraft/dirs.py 2015-07-20 13:53:07 +0000
325+++ snapcraft/dirs.py 2015-07-23 17:20:28 +0000
326@@ -19,11 +19,11 @@
327
328 def setup_dirs():
329 """
330- Ensure that snapcraft.common.plugindir are setup correctly
331+ Ensure that snapcraft.common plugindir is setup correctly
332 and support running out of a development snapshot
333 """
334- import snapcraft.common
335+ from snapcraft import common
336 topdir = os.path.abspath(os.path.join(__file__, "..", ".."))
337 # only change the default if we are running from a checkout
338 if os.path.exists(os.path.join(topdir, "setup.py")):
339- snapcraft.common.plugindir = os.path.join(topdir, 'plugins')
340+ common.set_plugindir(os.path.join(topdir, 'plugins'))
341
342=== modified file 'snapcraft/main.py'
343--- snapcraft/main.py 2015-07-17 17:19:04 +0000
344+++ snapcraft/main.py 2015-07-23 17:20:28 +0000
345@@ -16,12 +16,20 @@
346 # along with this program. If not, see <http://www.gnu.org/licenses/>.
347
348 import argparse
349+import logging
350 import sys
351
352 import snapcraft.cmds
353
354
355+_COLOR_BOLD = '\033[1m'
356+_COLOR_END = '\033[0m'
357+
358+
359 def main():
360+ logging.basicConfig(
361+ format=_COLOR_BOLD + '%(message)s' + _COLOR_END, level=logging.INFO)
362+
363 root_parser = argparse.ArgumentParser()
364 subparsers = root_parser.add_subparsers(dest='cmd')
365
366
367=== modified file 'snapcraft/plugin.py'
368--- snapcraft/plugin.py 2015-07-22 18:59:28 +0000
369+++ snapcraft/plugin.py 2015-07-23 17:20:28 +0000
370@@ -16,12 +16,18 @@
371
372 import glob
373 import importlib
374+import logging
375 import os
376-import snapcraft
377-import snapcraft.common
378 import sys
379+
380 import yaml
381
382+import snapcraft
383+from snapcraft import common
384+
385+
386+logger = logging.getLogger(__name__)
387+
388
389 def is_local_plugin(name):
390 return name.startswith("x-")
391@@ -31,7 +37,7 @@
392 if is_local_plugin(name):
393 return os.path.abspath(os.path.join('parts', 'plugins'))
394 else:
395- return snapcraft.common.plugindir
396+ return common.get_plugindir()
397
398
399 class PluginError(Exception):
400@@ -69,7 +75,7 @@
401 def _load_config(self, name):
402 configPath = os.path.join(plugindir(name), name + ".yaml")
403 if not os.path.exists(configPath):
404- snapcraft.common.log("Unknown plugin %s" % name, file=sys.stderr)
405+ logger.error("Unknown plugin %s" % name)
406 raise PluginError()
407 with open(configPath, 'r') as fp:
408 self.config = yaml.load(fp) or {}
409@@ -86,7 +92,7 @@
410 setattr(options, attrname, properties[opt])
411 else:
412 if opt_parameters.get('required', False):
413- snapcraft.common.log("Required field %s missing on part %s" % (opt, name), file=sys.stderr)
414+ logger.error("Required field %s missing on part %s" % (opt, name))
415 raise PluginError()
416 setattr(options, attrname, None)
417
418@@ -147,13 +153,13 @@
419 return self.part_names
420
421 def notify_stage(self, stage, hint=''):
422- snapcraft.common.log(stage + " " + self.part_names[0] + hint)
423+ logger.info(stage + " " + self.part_names[0] + hint)
424
425 def is_dirty(self, stage):
426 try:
427 with open(self.statefile, 'r') as f:
428 lastStep = f.read()
429- return snapcraft.common.commandOrder.index(stage) > snapcraft.common.commandOrder.index(lastStep)
430+ return common.COMMAND_ORDER.index(stage) > common.COMMAND_ORDER.index(lastStep)
431 except Exception:
432 return True
433
434@@ -197,7 +203,7 @@
435 return True
436
437 self.notify_stage("Staging")
438- snapcraft.common.run(['cp', '-arT', self.installdir, self.stagedir])
439+ common.run(['cp', '-arT', self.installdir, self.stagedir])
440 self.mark_done('stage')
441 return True
442
443@@ -213,9 +219,9 @@
444 snapDirs, snap_files = self.collect_snap_files(includes, excludes)
445
446 if snapDirs:
447- snapcraft.common.run(['mkdir', '-p'] + list(snapDirs), cwd=self.stagedir)
448+ common.run(['mkdir', '-p'] + list(snapDirs), cwd=self.stagedir)
449 if snap_files:
450- snapcraft.common.run(['cp', '-a', '--parent'] + list(snap_files) + [self.snapdir], cwd=self.stagedir)
451+ common.run(['cp', '-a', '--parent'] + list(snap_files) + [self.snapdir], cwd=self.stagedir)
452
453 self.mark_done('snap')
454 return True
455@@ -274,6 +280,6 @@
456 def load_plugin(part_name, plugin_name, properties={}, load_code=True):
457 part = PluginHandler(plugin_name, part_name, properties, load_code=load_code)
458 if not part.is_valid():
459- snapcraft.common.log("Could not load part %s" % plugin_name, file=sys.stderr)
460+ logger.error("Could not load part %s" % plugin_name)
461 sys.exit(1)
462 return part
463
464=== modified file 'snapcraft/plugins/ant_project.py'
465--- snapcraft/plugins/ant_project.py 2015-07-22 18:23:16 +0000
466+++ snapcraft/plugins/ant_project.py 2015-07-23 17:20:28 +0000
467@@ -15,10 +15,15 @@
468 # along with this program. If not, see <http://www.gnu.org/licenses/>.
469
470 import glob
471+import logging
472 import os
473+import sys
474+
475 import snapcraft
476 import snapcraft.common
477-import sys
478+
479+
480+logger = logging.getLogger(__name__)
481
482
483 class AntProjectPlugin(snapcraft.BasePlugin):
484@@ -31,7 +36,7 @@
485 return False
486 files = glob.glob(os.path.join(self.builddir, 'target', '*.jar'))
487 if not files:
488- snapcraft.common.log('Could not find any built jar files for part %s' % self.name)
489+ logger.error('Could not find any built jar files for part %s' % self.name)
490 sys.exit(1)
491 jardir = os.path.join(self.installdir, 'jar')
492 return self.run(['mkdir', '-p', jardir]) and \
493
494=== modified file 'snapcraft/plugins/copy.py'
495--- snapcraft/plugins/copy.py 2015-07-22 14:55:48 +0000
496+++ snapcraft/plugins/copy.py 2015-07-23 17:20:28 +0000
497@@ -14,11 +14,15 @@
498 # You should have received a copy of the GNU General Public License
499 # along with this program. If not, see <http://www.gnu.org/licenses/>.
500
501+import logging
502 import os
503
504 import snapcraft
505
506
507+logger = logging.getLogger(__name__)
508+
509+
510 class CopyPlugin(snapcraft.BasePlugin):
511
512 def build(self):
513@@ -26,7 +30,7 @@
514 for src in sorted(self.options.files):
515 dst = self.options.files[src]
516 if not os.path.lexists(src):
517- snapcraft.common.log("WARNING: file '%s' missing" % src)
518+ logger.warning("WARNING: file '%s' missing" % src)
519 res = False
520 continue
521 dst = os.path.join(self.installdir, dst)
522
523=== modified file 'snapcraft/plugins/ubuntu.py'
524--- snapcraft/plugins/ubuntu.py 2015-07-22 18:23:16 +0000
525+++ snapcraft/plugins/ubuntu.py 2015-07-23 17:20:28 +0000
526@@ -14,12 +14,18 @@
527 # You should have received a copy of the GNU General Public License
528 # along with this program. If not, see <http://www.gnu.org/licenses/>.
529
530-import apt
531+import logging
532 import os
533-import snapcraft.common
534 import subprocess
535 import sys
536
537+import apt
538+
539+import snapcraft.common
540+
541+
542+logger = logging.getLogger(__name__)
543+
544
545 class UbuntuPlugin(snapcraft.BasePlugin):
546
547@@ -32,7 +38,7 @@
548 else:
549 # User didn't specify a package, use the part name
550 if name == 'ubuntu':
551- snapcraft.common.log("Part %s needs either a package option or a name" % name)
552+ logger.error('Part %s needs either a package option or a name' % name)
553 sys.exit(1)
554 self.included_packages.append(name)
555
556@@ -83,7 +89,7 @@
557 for p in packages:
558 if p not in alldeps:
559 exit = True
560- snapcraft.common.log("Package %s not recognized" % p, file=sys.stderr)
561+ logger.error('Package %s not recognized' % p, file=sys.stderr)
562 if exit:
563 sys.exit(1)
564
565
566=== modified file 'snapcraft/tests/__init__.py'
567--- snapcraft/tests/__init__.py 2015-07-22 15:03:34 +0000
568+++ snapcraft/tests/__init__.py 2015-07-23 17:20:28 +0000
569@@ -16,7 +16,6 @@
570
571 import fixtures
572
573-import snapcraft.dirs
574 from snapcraft.tests import fixture_setup
575
576
577@@ -24,5 +23,6 @@
578
579 def setUp(self):
580 super().setUp()
581- snapcraft.dirs.setup_dirs()
582- self.useFixture(fixture_setup.TempCWD())
583+ temp_cwd_fixture = fixture_setup.TempCWD()
584+ self.useFixture(temp_cwd_fixture)
585+ self.path = temp_cwd_fixture.path
586
587=== modified file 'snapcraft/tests/test_cmds.py'
588--- snapcraft/tests/test_cmds.py 2015-07-15 09:00:46 +0000
589+++ snapcraft/tests/test_cmds.py 2015-07-23 17:20:28 +0000
590@@ -14,18 +14,23 @@
591 # You should have received a copy of the GNU General Public License
592 # along with this program. If not, see <http://www.gnu.org/licenses/>.
593
594+import logging
595 import os
596 import tempfile
597 from unittest import mock
598
599-from snapcraft.cmds import check_for_collisions
600+import fixtures
601+
602+from snapcraft import cmds
603 from snapcraft.tests import TestCase
604
605
606 class TestCommands(TestCase):
607
608- @mock.patch('snapcraft.common.log')
609- def test_check_for_collisions(self, logmock):
610+ def test_check_for_collisions(self):
611+ fake_logger = fixtures.FakeLogger(level=logging.ERROR)
612+ self.useFixture(fake_logger)
613+
614 tmpdirObject = tempfile.TemporaryDirectory()
615 self.addCleanup(tmpdirObject.cleanup)
616 tmpdir = tmpdirObject.name
617@@ -52,8 +57,41 @@
618 open(part3.installdir + '/1', mode='w').close()
619 open(part3.installdir + '/a/2', mode='w').close()
620
621- self.assertTrue(check_for_collisions([part1, part2]))
622- self.assertFalse(logmock.called)
623-
624- self.assertFalse(check_for_collisions([part1, part2, part3]))
625- logmock.assert_called_with("Error: parts part2 and part3 have the following files in common:\n 1\n a/2")
626+ self.assertTrue(cmds.check_for_collisions([part1, part2]))
627+ self.assertEqual('', fake_logger.output)
628+
629+ self.assertFalse(cmds.check_for_collisions([part1, part2, part3]))
630+ self.assertEqual(
631+ 'Error: parts part2 and part3 have the following files in common:\n'
632+ ' 1\n'
633+ ' a/2\n',
634+ fake_logger.output)
635+
636+
637+class InitTestCase(TestCase):
638+
639+ def test_init_with_existing_snapcraft_yaml_must_fail(self):
640+ fake_logger = fixtures.FakeLogger(level=logging.ERROR)
641+ self.useFixture(fake_logger)
642+
643+ open('snapcraft.yaml', 'w').close()
644+
645+ with self.assertRaises(SystemExit) as raised:
646+ cmds.init('dummy args')
647+ self.assertEqual(raised.exception.code, 1, 'Wrong exit code returned.')
648+ self.assertEqual(
649+ 'snapcraft.yaml already exists!\n', fake_logger.output)
650+
651+ def test_init_without_parts_must_write_snapcraft_yaml(self):
652+ fake_logger = fixtures.FakeLogger(level=logging.INFO)
653+ self.useFixture(fake_logger)
654+
655+ snap_without_parts = type('obj', (object, ), {'part': []})
656+ with self.assertRaises(SystemExit) as raised:
657+ cmds.init(snap_without_parts)
658+
659+ self.assertEqual(raised.exception.code, 0, 'Wrong exit code returned.')
660+ self.assertEqual(
661+ 'Wrote the following as snapcraft.yaml:\n'
662+ 'parts:\n',
663+ fake_logger.output)
664
665=== modified file 'snapcraft/tests/test_copy_plugin.py'
666--- snapcraft/tests/test_copy_plugin.py 2015-07-22 21:05:20 +0000
667+++ snapcraft/tests/test_copy_plugin.py 2015-07-23 17:20:28 +0000
668@@ -14,11 +14,11 @@
669 # You should have received a copy of the GNU General Public License
670 # along with this program. If not, see <http://www.gnu.org/licenses/>.
671
672+import logging
673 import os.path
674-from unittest.mock import (
675- Mock,
676- patch,
677-)
678+from unittest.mock import Mock
679+
680+import fixtures
681
682 from snapcraft.plugins.copy import CopyPlugin
683 from snapcraft.tests import TestCase
684@@ -43,12 +43,17 @@
685 }
686 open("zzz", "w").close()
687 c = CopyPlugin("copy", self.mock_options)
688- with patch("snapcraft.common.log") as mock_log:
689- res = c.build()
690- self.assertFalse(res)
691- mock_log.assert_called_with("WARNING: file 'src' missing")
692+
693+ fake_logger = fixtures.FakeLogger(level=logging.WARNING)
694+ self.useFixture(fake_logger)
695+
696+ res = c.build()
697+ self.assertFalse(res)
698+ self.assertEqual("WARNING: file 'src' missing\n", fake_logger.output)
699
700 def test_copy_plugin_copies(self):
701+ self.useFixture(fixtures.FakeLogger())
702+
703 self.mock_options.files = {
704 "src": "dst",
705 }
706@@ -59,6 +64,8 @@
707 self.assertTrue(os.path.exists(os.path.join(self.dst_prefix, "dst")))
708
709 def test_copy_plugin_creates_prefixes(self):
710+ self.useFixture(fixtures.FakeLogger())
711+
712 self.mock_options.files = {
713 "src": "dir/dst",
714 }
715
716=== modified file 'snapcraft/tests/test_plugin.py'
717--- snapcraft/tests/test_plugin.py 2015-07-22 21:05:20 +0000
718+++ snapcraft/tests/test_plugin.py 2015-07-23 17:20:28 +0000
719@@ -14,25 +14,29 @@
720 # You should have received a copy of the GNU General Public License
721 # along with this program. If not, see <http://www.gnu.org/licenses/>.
722
723+import logging
724 import os
725 import sys
726 import tempfile
727
728+import fixtures
729 from unittest.mock import (
730 Mock,
731 patch,
732 )
733
734+import snapcraft.tests.mock_plugin
735 from snapcraft.plugin import PluginHandler, PluginError
736 from snapcraft.tests import TestCase
737
738-import snapcraft.tests.mock_plugin
739-
740
741 class TestPlugin(TestCase):
742
743+ def get_test_plugin(self):
744+ return PluginHandler('mock', 'mock-part', {}, load_config=False, load_code=False)
745+
746 def test_is_dirty(self):
747- p = PluginHandler("mock", "mock-part", {}, load_config=False, load_code=False)
748+ p = self.get_test_plugin()
749 p.statefile = tempfile.NamedTemporaryFile().name
750 self.addCleanup(os.remove, p.statefile)
751 p.code = Mock()
752@@ -45,7 +49,7 @@
753 self.assertFalse(p.code.pull.called)
754
755 def test_collect_snap_files(self):
756- p = PluginHandler("mock", "mock-part", {}, load_config=False, load_code=False)
757+ p = self.get_test_plugin()
758
759 tmpdirObject = tempfile.TemporaryDirectory()
760 self.addCleanup(tmpdirObject.cleanup)
761@@ -92,6 +96,15 @@
762 set(['1', '1/1a', '1/1a/1b', '2', '2/2a']),
763 set()))
764
765+ def test_notify_stage_must_log_information(self):
766+ fake_logger = fixtures.FakeLogger(level=logging.INFO)
767+ self.useFixture(fake_logger)
768+
769+ plugin = self.get_test_plugin()
770+ plugin.notify_stage('test stage')
771+
772+ self.assertEqual('test stage mock-part\n', fake_logger.output)
773+
774 def test_local_plugins(self):
775 """Ensure local plugins are loaded from parts/plugins"""
776 def mock_import_modules(module_name):
777
778=== modified file 'snapcraft/tests/test_yaml.py'
779--- snapcraft/tests/test_yaml.py 2015-07-17 17:00:18 +0000
780+++ snapcraft/tests/test_yaml.py 2015-07-23 17:20:28 +0000
781@@ -14,15 +14,18 @@
782 # You should have received a copy of the GNU General Public License
783 # along with this program. If not, see <http://www.gnu.org/licenses/>.
784
785+import logging
786 import os
787 import tempfile
788 import unittest
789-from unittest.mock import (
790- patch,
791+
792+import fixtures
793+
794+from snapcraft import (
795+ common,
796+ dirs
797 )
798-
799 from snapcraft.yaml import Config
800-
801 from snapcraft.tests import TestCase
802
803
804@@ -46,16 +49,27 @@
805 "package": "fswebcam",
806 })
807
808- @patch("snapcraft.common.log")
809- def test_config_raises_on_missing_snapcraft_yaml(self, mock_log):
810+ def test_config_raises_on_missing_snapcraft_yaml(self):
811+ fake_logger = fixtures.FakeLogger(level=logging.ERROR)
812+ self.useFixture(fake_logger)
813+
814 # no snapcraft.yaml
815- with self.assertRaises(SystemExit):
816+ with self.assertRaises(SystemExit) as raised:
817 Config()
818- mock_log.assert_called_with("""Could not find snapcraft.yaml. Are you sure you're in the right directory?
819-To start a new project, use 'snapcraft init'""")
820-
821- @patch("snapcraft.common.log")
822- def test_config_loop(self, mock_log):
823+
824+ self.assertEqual(raised.exception.code, 1, 'Wrong exit code returned.')
825+ self.assertEqual(
826+ "Could not find snapcraft.yaml. Are you sure you're in the right directory?\n"
827+ "To start a new project, use 'snapcraft init'\n",
828+ fake_logger.output)
829+
830+ def test_config_loop(self):
831+ self.addCleanup(common.set_plugindir, common.get_plugindir())
832+ dirs.setup_dirs()
833+
834+ fake_logger = fixtures.FakeLogger(level=logging.ERROR)
835+ self.useFixture(fake_logger)
836+
837 self.make_snapcraft_yaml("""parts:
838 p1:
839 plugin: ubuntu
840@@ -64,6 +78,8 @@
841 plugin: ubuntu
842 after: [p1]
843 """)
844- with self.assertRaises(SystemExit):
845+ with self.assertRaises(SystemExit) as raised:
846 Config()
847- mock_log.assert_called_with("Circular dependency chain!")
848+
849+ self.assertEqual(raised.exception.code, 1, 'Wrong exit code returned.')
850+ self.assertEqual('Circular dependency chain!\n', fake_logger.output)
851
852=== modified file 'snapcraft/yaml.py'
853--- snapcraft/yaml.py 2015-07-22 13:57:19 +0000
854+++ snapcraft/yaml.py 2015-07-23 17:20:28 +0000
855@@ -14,11 +14,17 @@
856 # You should have received a copy of the GNU General Public License
857 # along with this program. If not, see <http://www.gnu.org/licenses/>.
858
859-import snapcraft.common
860-import snapcraft.plugin
861+import logging
862 import sys
863+
864 import yaml
865
866+import snapcraft.plugin
867+from snapcraft import common
868+
869+
870+logger = logging.getLogger(__name__)
871+
872
873 class Config:
874
875@@ -31,7 +37,7 @@
876 with open("snapcraft.yaml", 'r') as fp:
877 self.data = yaml.load(fp)
878 except FileNotFoundError:
879- snapcraft.common.log("Could not find snapcraft.yaml. Are you sure you're in the right directory?\nTo start a new project, use 'snapcraft init'")
880+ logger.error("Could not find snapcraft.yaml. Are you sure you're in the right directory?\nTo start a new project, use 'snapcraft init'")
881 sys.exit(1)
882 self.build_tools = self.data.get('build-tools', [])
883
884@@ -75,7 +81,7 @@
885 foundIt = True
886 break
887 if not foundIt:
888- snapcraft.common.log("Could not find part name %s" % dep)
889+ logger.error("Could not find part name %s" % dep)
890 sys.exit(1)
891
892 # Now sort them (this is super inefficient, but easy-ish to follow)
893@@ -92,7 +98,7 @@
894 topPart = part
895 break
896 if not topPart:
897- snapcraft.common.log("Circular dependency chain!")
898+ logger.error("Circular dependency chain!")
899 sys.exit(1)
900 sortedParts = [topPart] + sortedParts
901 self.all_parts.remove(topPart)
902@@ -132,7 +138,7 @@
903 return env
904
905 def stage_env(self):
906- root = snapcraft.common.stagedir
907+ root = common.get_stagedir()
908 env = []
909
910 env += self.runtime_env(root)
911@@ -143,7 +149,7 @@
912 return env
913
914 def snap_env(self):
915- root = snapcraft.common.snapdir
916+ root = common.get_snapdir()
917 env = []
918
919 env += self.runtime_env(root)

Subscribers

People subscribed via source and target branches

to all changes: