Merge lp:~milo/linaro-image-tools/bug727776 into lp:linaro-image-tools/11.11

Proposed by Milo Casagrande
Status: Merged
Approved by: Данило Шеган
Approved revision: 528
Merged at revision: 529
Proposed branch: lp:~milo/linaro-image-tools/bug727776
Merge into: lp:linaro-image-tools/11.11
Diff against target: 266 lines (+81/-22)
2 files modified
linaro_image_tools/tests/test_utils.py (+52/-9)
linaro_image_tools/utils.py (+29/-13)
To merge this branch: bzr merge lp:~milo/linaro-image-tools/bug727776
Reviewer Review Type Date Requested Status
Данило Шеган (community) Approve
Review via email: mp+107724@code.launchpad.net

Description of the change

Hi,

as per bug 727776, I'm proposing the following branch for merge.

I added a new test case for the '--hwpack' argument, checking it against a temp directory and raising an InvalidHwpackFile exception. I added then a new check in additional_option_checkers to check that the argument passed for '--hwpack' is a regular file.

For the test case I based myself on the already defined test cases. I only had to define my Args class in order to pass the valid arguments.

I ran the tests suite and it runs without errors.
Thanks.

To post a comment you must log in.
Revision history for this message
Данило Шеган (danilo) wrote :
Download full text (4.4 KiB)

Hi Milo,

Thanks for working on this.

У уто, 29. 05 2012. у 07:40 +0000, Milo Casagrande пише:

> as per bug 727776, I'm proposing the following branch for merge.
>
> I added a new test case for the '--hwpack' argument, checking it
> against a temp directory and raising an InvalidHwpackFile exception. I
> added then a new check in additional_option_checkers to check that the
> argument passed for '--hwpack' is a regular file.
>
> For the test case I based myself on the already defined test cases. I
> only had to define my Args class in order to pass the valid arguments.

> I ran the tests suite and it runs without errors.
> Thanks.

Cool, it's worth running pep8 on the files you've modified as well:

$ pep8 linaro_image_tools/tests/test_utils.py linaro_image_tools/utils.py
linaro_image_tools/tests/test_utils.py:90:5: E303 too many blank lines (2)
linaro_image_tools/tests/test_utils.py:140:1: W293 blank line contains whitespace
linaro_image_tools/tests/test_utils.py:198:1: E302 expected 2 blank lines, found 1
linaro_image_tools/tests/test_utils.py:321:40: W291 trailing whitespace
linaro_image_tools/utils.py:46:80: E501 line too long (81 characters)
linaro_image_tools/utils.py:107:14: E111 indentation is not a multiple of four
linaro_image_tools/utils.py:221:24: E231 missing whitespace after ','
linaro_image_tools/utils.py:256:17: E261 at least two spaces before inline comment
linaro_image_tools/utils.py:297:1: W391 blank line at end of file

(most/all are probably not your faults, but they'd be nice to clean-up
so we work towards a cleaner looking code :)

> разлике међу датотекама прилог (review-diff.txt)
> === modified file 'linaro_image_tools/tests/test_utils.py'
> --- linaro_image_tools/tests/test_utils.py 2012-04-18 13:26:25 +0000
> +++ linaro_image_tools/tests/test_utils.py 2012-05-29 07:39:22 +0000
> @@ -44,6 +44,7 @@
> IncompatibleOptions,
> prep_media_path,
> additional_option_checks,
> + InvalidHwpackFile,
> )

It would be good to sort these alphabetically as well: that makes it
easier to see if an import is already there or not when one tries to add
something.

And if there are many problems like this (and pep8 stuff) that one
notices during development, it's usually better to leave them for after
the review (or review might be harder).

> sudo_args = " ".join(cmd_runner.SUDO_ARGS)
> @@ -286,6 +287,7 @@
> device="testdevice",
> board="testboard")))
>
> +

Thanks for fixing this one :)

> class TestPrepMediaPath(TestCaseWithFixtures):
>
> def test_additional_option_checks(self):
> @@ -303,3 +305,21 @@
> device="testdevice",
> board="testboard"))
> sys.argv.remove("--mmc")
> +
> +
> +class TestHwpackIsFile(TestCaseWithFixtures):
> +
> + """Testing '--hwpack' option only allows file."""

"only allows regular files." sounds a bit better and is more
descriptive.

Rest of the test looks good.

> === modified file 'linaro_image_tools/utils.py'
> --- linaro_image_tools/utils.py 2012-04-18 13:26:25 +0000
> +++ linaro_image_tools/utils.py ...

Read more...

review: Needs Fixing
526. By Milo Casagrande

Fixed typos and test description.

527. By Milo Casagrande

Fixed import sorting in alphabetical order.

528. By Milo Casagrande

Added a new test for additional hwpack checks.

 * Added new test checking multiple hwpacks, in order to prevent
   tweaking of the additional_option_checks.

Revision history for this message
Milo Casagrande (milo) wrote :

Hi Danilo,

I pushed some of the requested changes, following are my comments.

On Wed, May 30, 2012 at 5:32 PM, Данило Шеган <email address hidden> wrote:
>
> Cool, it's worth running pep8 on the files you've modified as well:
>
> (most/all are probably not your faults, but they'd be nice to clean-up
> so we work towards a cleaner looking code :)

I will work on this as a second step, I try to fix all the problems
introduced by my changes first, and then move to those.

The latest commit/push on my branch doesn't address these yet.

> It would be good to sort these alphabetically as well: that makes it
> easier to see if an import is already there or not when one tries to add
> something.

This should be fixed now.

> "only allows regular files." sounds a bit better and is more
> descriptive.
>
> Rest of the test looks good.
>
> Now that I am looking at this code, it'd be nice to fix the above typo:
>
>  s/incompatable/incompatible/

Typos and rewriting should be fixed now.

>> +
>> +    for hwpack in args.hwpacks:
>> +        if not os.path.isfile(hwpack):
>> +            raise InvalidHwpackFile(
>> +                "--hwpack argument (%s) is not a regular file" % hwpack)
>> +
>
> The code here actually brings up one point: it might be useful to add a
> test to ensure multiple hwpacks are handled properly as well.  I.e. we
> can have a hwpack pointing to a real file, and only the second one
> pointing to a directory or non-existing file.
>
> This would ensure that if someone touches this code and decides to just
> check for the first argument, they get told about how they've broke it
> by the test failing :)

I added a new test for this:

test_hwpacks_are_files

that tests a file and a directory, in that order, passed in a list. It
is basically the same as the test before, just with two arguments for
the hwpack option. I added it inside the same class defined for the
test before, without renaming the class (maybe would be better to
rename it to address the multiple tests it contains, maybe a general
'TestHwpack').

I will address the other changes in later commits.
Let me know.

--
Milo Casagrande

Revision history for this message
Milo Casagrande (milo) wrote :

The additional PEP8 fixes are in a separate branch: once the review for the new test is OK, I will merge that branch here too.

Cheers.

Revision history for this message
Данило Шеган (danilo) wrote :

Looks good, thanks for working on this.

  merge approve

review: Approve
529. By Milo Casagrande

Applied PEP8 changes.

Revision history for this message
Milo Casagrande (milo) wrote :

I merged also the final bits to clean up PEP8 warnings: moslty spaces and white lines.

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'linaro_image_tools/tests/test_utils.py'
2--- linaro_image_tools/tests/test_utils.py 2012-04-18 13:26:25 +0000
3+++ linaro_image_tools/tests/test_utils.py 2012-06-06 14:02:18 +0000
4@@ -33,19 +33,21 @@
5 MockSomethingFixture,
6 )
7 from linaro_image_tools.utils import (
8+ IncompatibleOptions,
9+ InvalidHwpackFile,
10+ UnableToFindPackageProvidingCommand,
11+ additional_option_checks,
12+ check_file_integrity_and_log_errors,
13 ensure_command,
14 find_command,
15 install_package_providing,
16+ path_in_tarfile_exists,
17 preferred_tools_dir,
18- UnableToFindPackageProvidingCommand,
19+ prep_media_path,
20 verify_file_integrity,
21- check_file_integrity_and_log_errors,
22- path_in_tarfile_exists,
23- IncompatibleOptions,
24- prep_media_path,
25- additional_option_checks,
26 )
27
28+
29 sudo_args = " ".join(cmd_runner.SUDO_ARGS)
30
31
32@@ -85,7 +87,6 @@
33 def wait(self):
34 return self.returncode
35
36-
37 class MockCmdRunnerPopen_sha1sum_fail(object):
38 def __call__(self, cmd, *args, **kwargs):
39 self.returncode = 0
40@@ -99,7 +100,6 @@
41 def wait(self):
42 return self.returncode
43
44-
45 class MockCmdRunnerPopen_wait_fails(object):
46 def __call__(self, cmd, *args, **kwargs):
47 self.returncode = 0
48@@ -136,7 +136,7 @@
49 signature_filename),
50 'sha1sum -c %s' % hash_filename],
51 fixture.mock.commands_executed)
52-
53+
54 def test_verify_files_returns_files(self):
55 self.useFixture(MockSomethingFixture(cmd_runner, 'Popen',
56 self.MockCmdRunnerPopen()))
57@@ -194,6 +194,7 @@
58 self.assertFalse(result)
59 logging.getLogger().setLevel(logging.WARNING)
60
61+
62 class TestEnsureCommand(TestCaseWithFixtures):
63
64 install_pkg_providing_called = False
65@@ -286,6 +287,7 @@
66 device="testdevice",
67 board="testboard")))
68
69+
70 class TestPrepMediaPath(TestCaseWithFixtures):
71
72 def test_additional_option_checks(self):
73@@ -303,3 +305,44 @@
74 device="testdevice",
75 board="testboard"))
76 sys.argv.remove("--mmc")
77+
78+
79+class TestHwpackIsFile(TestCaseWithFixtures):
80+
81+ """Testing '--hwpack' option only allows regular files."""
82+
83+ def test_hwpack_is_file(self):
84+ class HwPackArgs:
85+ def __init__(self, hwpack):
86+ self.hwpacks = [hwpack]
87+ self.directory = None
88+
89+ try:
90+ tmpdir = tempfile.mkdtemp()
91+ self.assertRaises(InvalidHwpackFile, additional_option_checks,
92+ HwPackArgs(hwpack=tmpdir))
93+ finally:
94+ os.rmdir(tmpdir)
95+
96+ def test_hwpacks_are_files(self):
97+
98+ """
99+ Tests that multiple hwpacks are regular files.
100+
101+ Tests against a file and a directory, to avoid circumstances in which
102+ 'additional_option_checks' is tweaked.
103+ """
104+
105+ class HwPacksArgs:
106+ def __init__(self, hwpacks):
107+ self.hwpacks = hwpacks
108+ self.directory = None
109+
110+ try:
111+ tmpdir = tempfile.mkdtemp()
112+ _, tmpfile = tempfile.mkstemp()
113+ self.assertRaises(InvalidHwpackFile, additional_option_checks,
114+ HwPacksArgs([tmpfile, tmpdir]))
115+ finally:
116+ os.rmdir(tmpdir)
117+ os.remove(tmpfile)
118
119=== modified file 'linaro_image_tools/utils.py'
120--- linaro_image_tools/utils.py 2012-04-18 13:26:25 +0000
121+++ linaro_image_tools/utils.py 2012-06-06 14:02:18 +0000
122@@ -3,7 +3,7 @@
123 # Author: Guilherme Salgado <guilherme.salgado@linaro.org>
124 #
125 # This file is part of Linaro Image Tools.
126-#
127+#
128 # Linaro Image Tools is free software: you can redistribute it and/or modify
129 # it under the terms of the GNU General Public License as published by
130 # the Free Software Foundation, either version 3 of the License, or
131@@ -43,8 +43,8 @@
132 ``os.path.join``.
133 :param alternative: The value to return if no module can be imported.
134 Defaults to None.
135- :param error_callback: If non-None, a callable that is passed the ImportError
136- when the module cannot be loaded.
137+ :param error_callback: If non-None, a callable that is passed the
138+ ImportError when the module cannot be loaded.
139 """
140 module_segments = name.split('.')
141 last_error = None
142@@ -84,6 +84,7 @@
143 return False
144 tarinfo.close()
145
146+
147 def verify_file_integrity(sig_file_list):
148 """Verify a list of signature files.
149
150@@ -104,8 +105,8 @@
151 tmp = tempfile.NamedTemporaryFile()
152
153 try:
154- cmd_runner.run(['gpg', '--status-file={0}'.format(tmp.name),
155- '--verify', sig_file]).wait()
156+ cmd_runner.run(['gpg', '--status-file={0}'.format(tmp.name),
157+ '--verify', sig_file]).wait()
158 except cmd_runner.SubcommandNonZeroReturnValue:
159 gpg_sig_ok = False
160 gpg_out = gpg_out + tmp.read()
161@@ -134,6 +135,7 @@
162
163 return verified_files, gpg_sig_ok, gpg_out
164
165+
166 def check_file_integrity_and_log_errors(sig_file_list, binary, hwpacks):
167 """
168 Wrapper around verify_file_integrity that prints error messages to stderr
169@@ -147,22 +149,23 @@
170 if not gpg_sig_pass:
171 logging.error("GPG signature verification failed.")
172 return False, []
173-
174+
175 if not os.path.basename(binary) in verified_files:
176 logging.error("OS Binary verification failed")
177 return False, []
178-
179+
180 for hwpack in hwpacks:
181 if not os.path.basename(hwpack) in verified_files:
182 logging.error("Hwpack {0} verification failed".format(hwpack))
183 return False, []
184-
185+
186 for verified_file in verified_files:
187 logging.info('Hash verification of file {0} OK.'.format(
188 verified_file))
189-
190+
191 return True, verified_files
192
193+
194 def install_package_providing(command):
195 """Install a package which provides the given command.
196
197@@ -196,6 +199,7 @@
198 except cmd_runner.SubcommandNonZeroReturnValue:
199 return False
200
201+
202 def ensure_command(command):
203 """Ensure the given command is available.
204
205@@ -204,6 +208,7 @@
206 if not has_command(command):
207 install_package_providing(command)
208
209+
210 def find_command(name, prefer_dir=None):
211 """Finds a linaro-image-tools command.
212
213@@ -218,7 +223,7 @@
214
215 # default to searching in current directory when running from a bzr
216 # checkout
217- dirs = [os.getcwd(),]
218+ dirs = [os.getcwd(), ]
219 if os.path.isabs(__file__):
220 dirs = os.environ["PATH"].split(os.pathsep)
221 # empty dir in PATH means current directory
222@@ -253,7 +258,8 @@
223 try:
224 os.makedirs(loc)
225 except OSError:
226- pass # Directory exists.
227+ # Directory exists.
228+ pass
229
230 path = os.path.join(loc, args.device)
231 else:
232@@ -266,6 +272,10 @@
233 """We can't find a package which provides the given command."""
234
235
236+class InvalidHwpackFile(Exception):
237+ """The hwpack parameter is not a regular file."""
238+
239+
240 class IncompatibleOptions(Exception):
241 def __init__(self, value):
242 self.value = value
243@@ -273,15 +283,21 @@
244 def __str__(self):
245 return repr(self.value)
246
247+
248 def additional_option_checks(args):
249 if args.directory is not None:
250 # If args.device is a path to a device (/dev/) then this is an error
251 if "--mmc" in sys.argv:
252- raise IncompatibleOptions("--directory option incompatable with "
253+ raise IncompatibleOptions("--directory option incompatible with "
254 "option --mmc")
255
256 # If directory is used as well as having a full path (rather than just
257 # a file name or relative path) in args.device, this is an error.
258 if re.search(r"^/", args.device):
259- raise IncompatibleOptions("--directory option incompatable with "
260+ raise IncompatibleOptions("--directory option incompatible with "
261 "a full path in --image-file")
262+
263+ for hwpack in args.hwpacks:
264+ if not os.path.isfile(hwpack):
265+ raise InvalidHwpackFile(
266+ "--hwpack argument (%s) is not a regular file" % hwpack)

Subscribers

People subscribed via source and target branches