Merge lp:~milo/linaro-image-tools/hwpack-format-converter into lp:linaro-image-tools/11.11

Proposed by Milo Casagrande
Status: Merged
Merged at revision: 535
Proposed branch: lp:~milo/linaro-image-tools/hwpack-format-converter
Merge into: lp:linaro-image-tools/11.11
Diff against target: 657 lines (+617/-0)
6 files modified
linaro-hwpack-convert (+73/-0)
linaro_image_tools/hwpack/hwpack_convert.py (+297/-0)
linaro_image_tools/hwpack/hwpack_fields.py (+88/-0)
linaro_image_tools/hwpack/tests/__init__.py (+1/-0)
linaro_image_tools/hwpack/tests/test_hwpack_converter.py (+132/-0)
linaro_image_tools/tests/fixtures.py (+26/-0)
To merge this branch: bzr merge lp:~milo/linaro-image-tools/hwpack-format-converter
Reviewer Review Type Date Requested Status
Данило Шеган (community) Approve
Stevan Radaković Pending
Linaro Infrastructure Pending
Review via email: mp+115658@code.launchpad.net

Description of the change

Finally, a first merge.

I split it out into a smaller one, othere will follow. In this one there is only the hwpack format converter from INI style into YAML.

The script is called linaro-hwpack-convert and only one argument is necessary: the input file. If no output name is given, it will write in the same place of the input file, with the same name plus the '.yaml' suffix.

All the conversion logic is in the hwpack_converter.py file, a class called HwpackConverter. In the same file there are a series of methods that are used for the conversion itself, and that will be used also in other parts of l-i-t in order to create the new metadata file.

I added also another file, hwpack_fields, that holds all the fields that should be in a hwpack configuration file.
For the test part, tests are provided for the converter: I added a new mocking feature to create a temporary file (I had problems using StrinIO() in this case).

To post a comment you must log in.
Revision history for this message
Milo Casagrande (milo) wrote :
Revision history for this message
Данило Шеган (danilo) wrote :

As discussed on IRC, let's try out using

  yaml.dump(..., default_flow_style=False)

It should cut down on the code size significantly.

review: Needs Fixing
536. By Milo Casagrande

Used yaml.dump, cleaned up code and tests.

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

With the latest push this is now done.

--
Milo Casagrande
Infrastructure Engineer
Linaro.org <www.linaro.org> │ Open source software for ARM SoCs

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

New files are missing the license header.

It would be nice if get_logger (which exists in similar form in a few other files; though not named like that) was shared throughout, but it's not a requirement for this branch.

Also, why did we not reuse the code from hwpack/config.py that already does all of the parsing of the existing config files? I understand we do need some special handling, but not all of it needs it.

Tests have a few alignment problems, eg:

460 + self.assertRaises(HwpackConverterException, check_and_validate_args,
461 + Args(input_file=temp_file.name,
462 + output_file=temp_dir))

This should be:

460 + self.assertRaises(HwpackConverterException, check_and_validate_args,
461 + Args(input_file=temp_file.name,
462 + output_file=temp_dir))

or, even better:

460 + self.assertRaises(
461 + HwpackConverterException, check_and_validate_args,
462 + Args(input_file=temp_file.name, output_file=temp_dir))

With the small fixes for things that are mentioned (no need to switch over to the existing Config parser), this looks good to land.

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

ok, that didn't come out too well :) https://pastebin.linaro.org/694/

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

On Thu, Jul 19, 2012 at 1:54 PM, Данило Шеган <email address hidden> wrote:
>
> New files are missing the license header.
>
> It would be nice if get_logger (which exists in similar form in a few other files; though not named like that) was shared throughout, but it's not a requirement for this branch.

I can do that with the coming up merges, it shouldn't take much. Just
need to know which one to use.

> Also, why did we not reuse the code from hwpack/config.py that already does all of the parsing of the existing config files? I understand we do need some special handling, but not all of it needs it.

I though about using the Config, but then I would have had to go
through a long series of "if config.$PROPERTY is not None" (as we
already do in the metadata), but what we really need to pay attention
to and treat differently are just those values, not all of the Config
possible ones.
Also, if we get rid of V2 handling in the code, we might want to keep
the converter around if somebody still has those configs.

Switching is not that hard, indeed, just a little bit of if-clauses to write.

> Tests have a few alignment problems, eg:

These are fixed.

--
Milo Casagrande
Infrastructure Engineer
Linaro.org <www.linaro.org> │ Open source software for ARM SoCs

537. By Milo Casagrande

Added license header, fixed boolean values.

538. By Milo Casagrande

Fixed indentation, remove unused import.

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== added file 'linaro-hwpack-convert'
2--- linaro-hwpack-convert 1970-01-01 00:00:00 +0000
3+++ linaro-hwpack-convert 2012-07-19 15:36:20 +0000
4@@ -0,0 +1,73 @@
5+#!/usr/bin/python
6+# Copyright (C) 2010, 2011, 2012 Linaro
7+#
8+# Author: Milo Casagrande <milo.casagrande@linaro.org>
9+#
10+# This file is part of Linaro Image Tools.
11+#
12+# Linaro Image Tools is free software; you can redistribute it and/or
13+# modify it under the terms of the GNU General Public License
14+# as published by the Free Software Foundation; either version 2
15+# of the License, or (at your option) any later version.
16+#
17+# Linaro Image Tools is distributed in the hope that it will be useful,
18+# but WITHOUT ANY WARRANTY; without even the implied warranty of
19+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20+# GNU General Public License for more details.
21+#
22+# You should have received a copy of the GNU General Public License
23+# along with Linaro Image Tools; if not, write to the Free Software
24+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
25+# USA.
26+
27+
28+import argparse
29+import logging
30+import sys
31+import os
32+
33+from linaro_image_tools.hwpack.hwpack_convert import (
34+ HwpackConverter,
35+ HwpackConverterException,
36+ check_and_validate_args,
37+ )
38+from linaro_image_tools.__version__ import __version__
39+
40+
41+def get_logger(debug=False):
42+ ch = logging.StreamHandler()
43+ logger = logging.getLogger("linaro_hwpack_converter")
44+
45+ if debug:
46+ ch.setLevel(logging.DEBUG)
47+ formatter = logging.Formatter(
48+ "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
49+ ch.setFormatter(formatter)
50+ logger.setLevel(logging.DEBUG)
51+ else:
52+ ch.setLevel(logging.INFO)
53+ formatter = logging.Formatter("%(message)s")
54+ ch.setFormatter(formatter)
55+ logger.setLevel(logging.INFO)
56+ logger.addHandler(ch)
57+
58+if __name__ == '__main__':
59+ parser = argparse.ArgumentParser(version='%(prog)s ' + __version__)
60+ parser.add_argument("CONFIG_FILE",
61+ help="The configuration file to convert.")
62+ parser.add_argument("--out",
63+ help="The output file name to write. If none is "
64+ "given, the input file name (and path) will be "
65+ "used with the '.yaml' suffix.")
66+ parser.add_argument("--debug", action="store_true")
67+ args = parser.parse_args()
68+ logger = get_logger(debug=args.debug)
69+ try:
70+ input_file, output_file = check_and_validate_args(args)
71+ print "Converting '%s' into new YAML format..." % (input_file)
72+ converter = HwpackConverter(input_file, output_file)
73+ except HwpackConverterException, e:
74+ sys.stderr.write(str(e) + "\n")
75+ sys.exit(1)
76+ converter.convert()
77+ print "File '%s' converted in '%s'." % (input_file, output_file)
78
79=== added file 'linaro_image_tools/hwpack/hwpack_convert.py'
80--- linaro_image_tools/hwpack/hwpack_convert.py 1970-01-01 00:00:00 +0000
81+++ linaro_image_tools/hwpack/hwpack_convert.py 2012-07-19 15:36:20 +0000
82@@ -0,0 +1,297 @@
83+# Copyright (C) 2010, 2011, 2012 Linaro
84+#
85+# Author: Milo Casagrande <milo.casagrande@linaro.org>
86+#
87+# This file is part of Linaro Image Tools.
88+#
89+# Linaro Image Tools is free software; you can redistribute it and/or
90+# modify it under the terms of the GNU General Public License
91+# as published by the Free Software Foundation; either version 2
92+# of the License, or (at your option) any later version.
93+#
94+# Linaro Image Tools is distributed in the hope that it will be useful,
95+# but WITHOUT ANY WARRANTY; without even the implied warranty of
96+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
97+# GNU General Public License for more details.
98+#
99+# You should have received a copy of the GNU General Public License
100+# along with Linaro Image Tools; if not, write to the Free Software
101+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
102+# USA.
103+
104+import ConfigParser
105+import logging
106+import os
107+import os.path
108+import re
109+import yaml
110+
111+from hwpack_fields import (
112+ ARCHITECTURES_FIELD,
113+ ASSUME_INSTALLED_FIELD,
114+ BOOTLOADERS_FIELD,
115+ EXTRA_BOOT_OPTIONS_FIELD,
116+ EXTRA_SERIAL_OPTIONS_FIELD,
117+ SOURCES_FIELD,
118+ FORMAT_FIELD,
119+ PACKAGES_FIELD,
120+ PACKAGE_FIELD,
121+ FILE_FIELD,
122+ IN_BOOT_PART_FIELD,
123+ DD_FIELD,
124+ ENV_DD_FIELD,
125+ SPL_IN_BOOT_PART_FIELD,
126+ SPL_DD_FIELD,
127+ SPL_PACKAGE_FIELD,
128+ SPL_FILE_FIELD,
129+ WIRED_INTERFACES_FIELD,
130+ WIRELESS_INTERFACES_FIELD,
131+)
132+
133+# This is the main section of an INI-style hwpack config file.
134+MAIN_SECTION = 'hwpack'
135+# The suffix for the new file
136+NEW_FILE_SUFFIX = '.yaml'
137+# How many spaces should be used for indentation.
138+INDENT_STEP = 1
139+# Regular expression to convert from Yes/No values into Boolean.
140+YES_REGEX = '[Yy]es'
141+NO_REGEX = '[Nn]o'
142+# The default format number.
143+DEFAULT_FORMAT = '3.0'
144+# Old INI style u_boot keys name.
145+UBOOT_PACKAGE_KEY = "u_boot_package"
146+UBOOT_FILE_KEY = "u_boot_file"
147+UBOOT_IN_BOOT_PART_KEY = 'u_boot_in_boot_part'
148+UBOOT_DD_KEY = 'u_boot_dd'
149+# All the u_boot defined keys in a list.
150+UBOOT_KEYS = [UBOOT_PACKAGE_KEY, UBOOT_FILE_KEY, UBOOT_IN_BOOT_PART_KEY,
151+ UBOOT_DD_KEY]
152+
153+# Old field, the only one with a dash: since the format is new, convert it.
154+ASSUME_INSTALLED_OLD = 'assume-installed'
155+
156+# The default bootloader for the bootloaders section.
157+DEFAULT_BOOTLOADER = 'u_boot'
158+
159+# All the SPL keys
160+SPL_KEYS = [SPL_IN_BOOT_PART_FIELD, SPL_DD_FIELD, SPL_PACKAGE_FIELD,
161+ SPL_FILE_FIELD, ENV_DD_FIELD]
162+
163+logger = logging.getLogger("linaro_hwpack_converter")
164+
165+
166+class HwpackConverterException(Exception):
167+ """General exception class for the converter."""
168+
169+
170+class HwpackConverter(object):
171+ """Simple and basic class that converts an INI-style format file into the
172+ new YAML format.
173+
174+ The old format number is maintained.
175+
176+ :param input_file: the input file to parse, has to be an INI-style file.
177+ :param output_file: where to write the new file, if not given, the name
178+ of the input file will be used adding the 'yaml'
179+ suffix.
180+ """
181+ def __init__(self, input_file=None, output_file=None):
182+ """Initializie the class."""
183+ self.input_file = input_file
184+ self.output_file = output_file
185+
186+ # Where we store the list of sources.
187+ self.sources = {}
188+ # Where we store all the information of the hwpack config file
189+ # In this case we have one board per hwpack config file.
190+ self.hwpack = {}
191+ # List of supported architectures.
192+ self.architectures = []
193+ # Where we hold bootloaders info
194+ self.bootloaders = {}
195+ # List to store extra boot options.
196+ self.extra_boot_options = []
197+ # The list of packages.
198+ self.packages = []
199+ # List of the extra_serial_options.
200+ self.extra_serial_options = []
201+ # Lists for network interfaces.
202+ self.wired_interfaces = []
203+ self.wireless_interfaces = []
204+ # SPL entries
205+ self.spl = {}
206+
207+ def _parse(self):
208+ """Parses the config file and stores its values."""
209+ if self.input_file is not None:
210+ parser = ConfigParser.RawConfigParser()
211+ with open(self.input_file, 'r') as fp:
212+ parser.readfp(fp)
213+
214+ # Iterate through all the file sections.
215+ for section in parser.sections():
216+ if section == MAIN_SECTION:
217+ for key, value in parser.items(section):
218+ if value is not None:
219+ if re.match("[Yy]es", value):
220+ value = True
221+ elif re.match("[Nn]o", value):
222+ value = False
223+ if key == ARCHITECTURES_FIELD:
224+ self.parse_list_string(self.architectures,
225+ value)
226+ continue
227+ elif key == EXTRA_BOOT_OPTIONS_FIELD:
228+ self.parse_list_string(self.extra_boot_options,
229+ value)
230+ continue
231+ elif key == EXTRA_SERIAL_OPTIONS_FIELD:
232+ self.parse_list_string(
233+ self.extra_serial_options,
234+ value)
235+ continue
236+ elif key == WIRED_INTERFACES_FIELD:
237+ self.parse_list_string(self.wired_interfaces,
238+ value)
239+ continue
240+ elif key == WIRELESS_INTERFACES_FIELD:
241+ self.parse_list_string(
242+ self.wireless_interfaces,
243+ value)
244+ continue
245+ elif key in SPL_KEYS:
246+ self.spl[key] = value
247+ continue
248+ elif key == FORMAT_FIELD:
249+ value = DEFAULT_FORMAT
250+ elif key == PACKAGES_FIELD:
251+ self.parse_list_string(self.packages, value)
252+ continue
253+ elif key in UBOOT_KEYS:
254+ self._set_bootloaders(key, value)
255+ continue
256+ # Convert an old key into the new one.
257+ elif key == ASSUME_INSTALLED_OLD:
258+ key = ASSUME_INSTALLED_FIELD
259+ self.hwpack[key] = value
260+ else:
261+ # Here we have only sources sections.
262+ for _, value in parser.items(section):
263+ if value is not None:
264+ self.sources[section] = value
265+
266+ def _set_bootloaders(self, key, value):
267+ """Sets the bootloaders dictionary of a new YAML file. Converts from
268+ the old INI keys name into the new ones.
269+
270+ :param key: The key of the bootloader.
271+ :param value: The key value."""
272+ if key == UBOOT_PACKAGE_KEY:
273+ self.bootloaders[PACKAGE_FIELD] = value
274+ elif key == UBOOT_FILE_KEY:
275+ self.bootloaders[FILE_FIELD] = value
276+ elif key == UBOOT_IN_BOOT_PART_KEY:
277+ self.bootloaders[IN_BOOT_PART_FIELD] = value
278+ elif key == UBOOT_DD_KEY:
279+ self.bootloaders[DD_FIELD] = value
280+
281+ def parse_list_string(self, store, string, split=" "):
282+ """Parses a string of listed values, and stores the single splitted
283+ value in the provided list.
284+
285+ :param store: The list where to store the values.
286+ :param string: The string that should be splitted.
287+ :param split: The separator to use, defaults to empty space.
288+ """
289+ if not isinstance(store, list):
290+ raise HwpackConverterException("Can use this method only with "
291+ "list.")
292+ store.extend(string.split(" "))
293+
294+ def _to_file(self):
295+ """Writes the converted hwpack to file."""
296+ with open(self.output_file, 'w') as fp:
297+ fp.write(str(self))
298+
299+ def convert(self):
300+ """Converts the input file into the output file with the new format.
301+ """
302+ self._parse()
303+ self._to_file()
304+
305+ def __str__(self):
306+ """Readable representation of the converted hwpack.
307+
308+ :return A YAML-string representation of the hwpack configuration.
309+ """
310+ converted = ''
311+ if self.hwpack:
312+ converted += dump(self.hwpack)
313+ if self.architectures:
314+ archs = {ARCHITECTURES_FIELD: self.architectures}
315+ converted += dump(archs)
316+ if self.extra_serial_options:
317+ serial_options = {EXTRA_SERIAL_OPTIONS_FIELD:
318+ self.extra_serial_options}
319+ converted += dump(serial_options)
320+ if self.packages:
321+ packages = {PACKAGES_FIELD: self.packages}
322+ converted += dump(packages)
323+ if self.wired_interfaces:
324+ wired = {WIRED_INTERFACES_FIELD: self.wired_interfaces}
325+ converted += dump(wired)
326+ if self.wireless_interfaces:
327+ converted += dump(self.wireless_interfaces)
328+ if self.sources:
329+ sources = {SOURCES_FIELD: self.sources}
330+ converted += dump(sources)
331+ if self.bootloaders or self.extra_boot_options or self.spl:
332+ # The bootloaders section in the new YAML file is a dictionary
333+ # containing a dictionary which can contains also other
334+ # dictionaries. In this case we only have list and normal values.
335+ nested_value = {}
336+ if self.bootloaders:
337+ for key, value in self.bootloaders.iteritems():
338+ nested_value[key] = value
339+ if self.extra_boot_options:
340+ nested_value[EXTRA_BOOT_OPTIONS_FIELD] = \
341+ self.extra_boot_options
342+ if self.spl:
343+ for key, value in self.spl.iteritems():
344+ nested_value[key] = value
345+ default_bootloader = {DEFAULT_BOOTLOADER: nested_value}
346+ bootloaders = {BOOTLOADERS_FIELD: default_bootloader}
347+ converted += dump(bootloaders)
348+ return converted
349+
350+
351+def dump(python_object):
352+ """Serialize a Python object in a YAML string format.
353+
354+ :param python_object: The object to serialize.
355+ """
356+ return yaml.dump(python_object, default_flow_style=False, indent=True)
357+
358+
359+def check_and_validate_args(args):
360+ """Assures that the args passed are valid.
361+
362+ :param args: the args as defined in linaro-hwpack-convert.
363+ """
364+ input_file = args.CONFIG_FILE
365+ output_file = args.out
366+ if not os.path.exists(input_file) or not os.path.isfile(input_file):
367+ raise HwpackConverterException("The configuration file '%s' is not a "
368+ "regular file." % input_file)
369+ if output_file is not None:
370+ if os.path.exists(output_file) or os.path.isdir(output_file):
371+ raise HwpackConverterException("The output file name provided "
372+ "'%s' already exists, or is a "
373+ "directory." % output_file)
374+ elif not os.path.isabs(output_file):
375+ # If we output file is just a name, write it in the current dir.
376+ output_file = os.path.join(os.getcwd(), output_file)
377+ else:
378+ output_file = input_file + NEW_FILE_SUFFIX
379+ return (input_file, output_file)
380
381=== added file 'linaro_image_tools/hwpack/hwpack_fields.py'
382--- linaro_image_tools/hwpack/hwpack_fields.py 1970-01-01 00:00:00 +0000
383+++ linaro_image_tools/hwpack/hwpack_fields.py 2012-07-19 15:36:20 +0000
384@@ -0,0 +1,88 @@
385+# Copyright (C) 2010, 2011, 2012 Linaro
386+#
387+# Author: Milo Casagrande <milo.casagrande@linaro.org>
388+#
389+# This file is part of Linaro Image Tools.
390+#
391+# Linaro Image Tools is free software; you can redistribute it and/or
392+# modify it under the terms of the GNU General Public License
393+# as published by the Free Software Foundation; either version 2
394+# of the License, or (at your option) any later version.
395+#
396+# Linaro Image Tools is distributed in the hope that it will be useful,
397+# but WITHOUT ANY WARRANTY; without even the implied warranty of
398+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
399+# GNU General Public License for more details.
400+#
401+# You should have received a copy of the GNU General Public License
402+# along with Linaro Image Tools; if not, write to the Free Software
403+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
404+# USA.
405+
406+# This file contains all the valid fields for an hwpack v3.
407+# Reference wiki page: https://wiki.linaro.org/HardwarePacksV3
408+#
409+# Try to keep it alphabetically sorted per section.
410+#
411+ARCHITECTURES_FIELD = 'architectures'
412+ASSUME_INSTALLED_FIELD = 'assume_installed'
413+BOARDS_FIELD = 'boards'
414+BOOTLOADERS_FIELD = 'bootloaders'
415+BOOT_MIN_SIZE_FIELD = 'boot_min_size'
416+BOOT_SCRIPT_FIELD = 'boot_script'
417+COPY_FILES_FIELD = 'copy_files'
418+DTB_ADDR_FIELD = 'dtb_addr'
419+DTB_FILE_FIELD = 'dtb_file'
420+DTB_FILES_FIELD = 'dtb_files'
421+EXTRA_SERIAL_OPTIONS_FIELD = 'extra_serial_options'
422+FORMAT_FIELD = 'format'
423+INITRD_ADDR_FIELD = 'initrd_addr'
424+INITRD_FILE_FIELD = 'initrd_file'
425+KERNEL_ADDR_FIELD = 'kernel_addr'
426+KERNEL_FILE_FIELD = 'kernel_file'
427+LOAD_ADDR_FIELD = 'load_addr'
428+LOADER_MIN_SIZE_FIELD = 'loader_min_size'
429+LOADER_START_FIELD = 'loader_start'
430+MAINTAINER_FIELD = 'maintainer'
431+MMC_ID_FIELD = 'mmc_id'
432+NAME_FIELD = 'name'
433+ORIGIN_FIELD = 'origin'
434+PACKAGES_FIELD = 'packages'
435+PARTITION_LAYOUT_FIELD = 'partition_layout'
436+ROOT_MIN_SIZE_FIELD = 'root_min_size'
437+SERIAL_TTY_FIELD = 'serial_tty'
438+SOURCES_FIELD = 'sources'
439+SUPPORT_FIELD = 'support'
440+WIRED_INTERFACES_FIELD = 'wired_interfaces'
441+WIRELESS_INTERFACES_FIELD = 'wireless_interfaces'
442+
443+# Bootloaders specific fields
444+DD_FIELD = 'dd'
445+ENV_DD_FIELD = 'env_dd'
446+EXTRA_BOOT_OPTIONS_FIELD = 'extra_boot_options'
447+FILE_FIELD = 'file'
448+IN_BOOT_PART_FIELD = 'in_boot_part'
449+PACKAGE_FIELD = 'package'
450+SPL_DD_FIELD = 'spl_dd'
451+SPL_FILE_FIELD = 'spl_file'
452+SPL_IN_BOOT_PART_FIELD = 'spl_in_boot_part'
453+SPL_PACKAGE_FIELD = 'spl_package'
454+
455+# Samsung fields
456+SAMSUNG_BL1_LEN_FIELD = 'samsung_bl1_len'
457+SAMSUNG_BL1_START_FIELD = 'samsung_bl1_start'
458+SAMSUNG_BL2_LEN_FIELD = 'samsung_bl2_len'
459+SAMSUNG_ENV_LEN_FIELD = 'samsung_env_len'
460+
461+# Snowball fields
462+SNOWBALL_STARTUP_FILES_CONFIG_FIELD = 'snowball_startup_files_config'
463+
464+# Fields that might be necessary for the metadata file
465+METADATA_ARCH_FIELD = 'architecture'
466+METADATA_VERSION_FIELD = 'version'
467+
468+# The allowed partition layouts.
469+DEFINED_PARTITION_LAYOUTS = [
470+ 'bootfs16_rootfs',
471+ 'bootfs_rootfs',
472+ 'reserved_bootfs_rootfs', ]
473
474=== modified file 'linaro_image_tools/hwpack/tests/__init__.py'
475--- linaro_image_tools/hwpack/tests/__init__.py 2012-06-13 14:26:02 +0000
476+++ linaro_image_tools/hwpack/tests/__init__.py 2012-07-19 15:36:20 +0000
477@@ -28,6 +28,7 @@
478 'linaro_image_tools.hwpack.tests.test_builder',
479 'linaro_image_tools.hwpack.tests.test_config',
480 'linaro_image_tools.hwpack.tests.test_hardwarepack',
481+ 'linaro_image_tools.hwpack.tests.test_hwpack_converter',
482 'linaro_image_tools.hwpack.tests.test_packages',
483 'linaro_image_tools.hwpack.tests.test_script',
484 'linaro_image_tools.hwpack.tests.test_tarfile_matchers',
485
486=== added file 'linaro_image_tools/hwpack/tests/test_hwpack_converter.py'
487--- linaro_image_tools/hwpack/tests/test_hwpack_converter.py 1970-01-01 00:00:00 +0000
488+++ linaro_image_tools/hwpack/tests/test_hwpack_converter.py 2012-07-19 15:36:20 +0000
489@@ -0,0 +1,132 @@
490+# Copyright (C) 2010, 2011, 2012 Linaro
491+#
492+# Author: Milo Casagrande <milo.casagrande@linaro.org>
493+#
494+# This file is part of Linaro Image Tools.
495+#
496+# Linaro Image Tools is free software; you can redistribute it and/or
497+# modify it under the terms of the GNU General Public License
498+# as published by the Free Software Foundation; either version 2
499+# of the License, or (at your option) any later version.
500+#
501+# Linaro Image Tools is distributed in the hope that it will be useful,
502+# but WITHOUT ANY WARRANTY; without even the implied warranty of
503+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
504+# GNU General Public License for more details.
505+#
506+# You should have received a copy of the GNU General Public License
507+# along with Linaro Image Tools; if not, write to the Free Software
508+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
509+# USA.
510+
511+import tempfile
512+from linaro_image_tools.testing import TestCaseWithFixtures
513+from linaro_image_tools.tests.fixtures import (
514+ CreateTempDirFixture,
515+ CreateTempFileFixture,
516+ )
517+
518+from linaro_image_tools.hwpack.hwpack_convert import (
519+ HwpackConverter,
520+ HwpackConverterException,
521+ check_and_validate_args,
522+ )
523+
524+
525+class Args():
526+ """Defines the args for the command line options."""
527+ def __init__(self, input_file, output_file=None):
528+ self.CONFIG_FILE = input_file
529+ self.out = output_file
530+
531+
532+class HwpackConverterTests(TestCaseWithFixtures):
533+ """Test class for the hwpack converter."""
534+
535+ def setUp(self):
536+ super(HwpackConverterTests, self).setUp()
537+
538+ def test_wrong_input_file(self):
539+ """Pass a non-existing file."""
540+ input_file = '/tmp/foobaz'
541+ self.assertRaises(
542+ HwpackConverterException, check_and_validate_args,
543+ Args(input_file=input_file))
544+
545+ def test_wrong_input_dir(self):
546+ """Pass a directory instead of file."""
547+ temp_file = tempfile.NamedTemporaryFile()
548+ temp_dir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
549+ self.assertRaises(
550+ HwpackConverterException, check_and_validate_args,
551+ Args(input_file=temp_file.name, output_file=temp_dir))
552+
553+ def test_same_input_output_file(self):
554+ """Pass the same existing file path to the two arguments."""
555+ temp_file = self.useFixture(CreateTempFileFixture()).get_file_name()
556+ self.assertRaises(
557+ HwpackConverterException, check_and_validate_args,
558+ Args(input_file=temp_file, output_file=temp_file))
559+
560+ def test_basic_parse(self):
561+ ini_format = '[hwpack]\nformat=2.0\nsupport=supported'
562+ output_format = "format: '3.0'\nsupport: supported\n"
563+ input_file = self.useFixture(CreateTempFileFixture(ini_format)).\
564+ get_file_name()
565+ output_file = self.useFixture(CreateTempFileFixture()).get_file_name()
566+ converter = HwpackConverter(input_file, output_file)
567+ converter._parse()
568+ self.assertEqual(output_format, str(converter))
569+
570+ def test_architectures_section_creation(self):
571+ """Tests that we create the correct architectures list in the
572+ converted file.
573+ """
574+ ini_format = '[hwpack]\nformat=2.0\narchitectures=armhf armel'
575+ output_format = "format: '3.0'\narchitectures:\n- armhf\n- armel\n"
576+ input_file = self.useFixture(CreateTempFileFixture(ini_format)).\
577+ get_file_name()
578+ output_file = self.useFixture(CreateTempFileFixture()).get_file_name()
579+ converter = HwpackConverter(input_file, output_file)
580+ converter._parse()
581+ self.assertEqual(output_format, str(converter))
582+
583+ def test_bootloaders(self):
584+ """Tests the correct creation of the bootloaders part."""
585+ ini_format = ("[hwpack]\nformat=2.0\nu_boot_package=a_package\n"
586+ "u_boot_file=a_file\nu_boot_in_boot_part=Yes\n"
587+ "u_boot_dd=33")
588+ out_format = ("format: '3.0'\nbootloaders:\n u_boot:\n dd: '33'"
589+ "\n file: a_file\n in_boot_part: true\n"
590+ " package: a_package\n")
591+ input_file = self.useFixture(CreateTempFileFixture(ini_format)).\
592+ get_file_name()
593+ output_file = self.useFixture(CreateTempFileFixture()).get_file_name()
594+ converter = HwpackConverter(input_file, output_file)
595+ converter._parse()
596+ self.assertEqual(out_format, str(converter))
597+
598+ def test_extra_boot_options(self):
599+ """Tests the correct creation of the extra_boot_options part."""
600+ ini_format = ("[hwpack]\nformat=2.0\nu_boot_package=a_package\n"
601+ "extra_boot_options=opt1 opt2")
602+ out_format = ("format: '3.0'\nbootloaders:\n u_boot:\n "
603+ " extra_boot_options:\n - opt1\n "
604+ "- opt2\n package: a_package\n")
605+ input_file = self.useFixture(CreateTempFileFixture(ini_format)).\
606+ get_file_name()
607+ output_file = self.useFixture(CreateTempFileFixture()).get_file_name()
608+ converter = HwpackConverter(input_file, output_file)
609+ converter._parse()
610+ self.assertEqual(out_format, str(converter))
611+
612+ def test_extra_serial_options(self):
613+ """Tests the correct creation of the extra_serial_options part."""
614+ ini_format = ("[hwpack]\nformat=2.0\nextra_serial_options=opt1 opt2")
615+ out_format = ("format: '3.0'\nextra_serial_options:\n- opt1\n- opt2\n")
616+ input_file = self.useFixture(CreateTempFileFixture(ini_format)).\
617+ get_file_name()
618+ output_file = self.useFixture(CreateTempFileFixture()).get_file_name()
619+ converter = HwpackConverter(input_file, output_file)
620+ converter._parse()
621+ self.assertEqual(out_format, str(converter))
622
623=== modified file 'linaro_image_tools/tests/fixtures.py'
624--- linaro_image_tools/tests/fixtures.py 2012-06-13 14:55:34 +0000
625+++ linaro_image_tools/tests/fixtures.py 2012-07-19 15:36:20 +0000
626@@ -41,6 +41,32 @@
627 return self.tempdir
628
629
630+class CreateTempFileFixture(object):
631+ """Class to create a temporary file to be used in a test."""
632+ def __init__(self, string=None):
633+ """Initialize the fixture.
634+
635+ :param string: the string to write in the file.
636+ """
637+ self.temp_file = None
638+ self.string = string
639+
640+ def setUp(self):
641+ self.temp_file = tempfile.NamedTemporaryFile()
642+ if self.string is not None:
643+ self.temp_file.write(self.string)
644+ # Go back to the initial position, we just need to write something
645+ # and be able to read from the beginning of the file.
646+ self.temp_file.seek(0)
647+
648+ def tearDown(self):
649+ # We don't need to do anything, file is automatically deleted.
650+ pass
651+
652+ def get_file_name(self):
653+ return self.temp_file.name
654+
655+
656 class MockSomethingFixture(object):
657 """A fixture which mocks something on the given object.
658

Subscribers

People subscribed via source and target branches