Merge ~jslarraz/review-tools:rework-extract-file into review-tools:master

Proposed by Jorge Sancho Larraz
Status: Merged
Merged at revision: 50e283a3278d17ba6d0be701a209ac8df0ef2de9
Proposed branch: ~jslarraz/review-tools:rework-extract-file
Merge into: review-tools:master
Diff against target: 125 lines (+40/-17)
3 files modified
reviewtools/containers/base_container.py (+20/-9)
reviewtools/sr_lint.py (+3/-4)
reviewtools/tests/containers/test_base_container.py (+17/-4)
Reviewer Review Type Date Requested Status
Alex Murray Approve
Review via email: mp+466381@code.launchpad.net

Commit message

rework BaseContainer:_extract_file and add relevant tests

To post a comment you must log in.
Revision history for this message
Alex Murray (alexmurray) wrote :

LGTM - nice use of type hints too!

review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1diff --git a/reviewtools/containers/base_container.py b/reviewtools/containers/base_container.py
2index 173036a..3cd069f 100644
3--- a/reviewtools/containers/base_container.py
4+++ b/reviewtools/containers/base_container.py
5@@ -1,6 +1,7 @@
6 import os
7 import shutil
8 import magic
9+from typing import Union
10 from tempfile import mkdtemp
11
12 from reviewtools.common import (
13@@ -9,7 +10,6 @@ from reviewtools.common import (
14 debug,
15 unpack_pkg,
16 recursive_rm,
17- open_file_read,
18 )
19
20
21@@ -104,15 +104,26 @@ class BaseContainer:
22 if os.path.exists(self.tmp_dir):
23 recursive_rm(self.tmp_dir)
24
25- def _extract_file(self, fn):
26- """Extract file"""
27- if not fn.startswith("/"):
28- raise ContainerException("_extract_file() expects absolute path")
29- rel = os.path.relpath(fn, self.unpack_dir)
30+ def get_file(self, fn: str) -> Union[str, None]:
31+ """
32+ Reads and return the raw content of the specified file.
33+
34+ Args:
35+ fn (str): file path relative to the container root (i.e. unpack_dir)
36+
37+ Returns:
38+ str: raw content of the specified file. The output will need to be
39+ decoded() to use it as a string
40+
41+ Raises:
42+ ContainerException: Calling this method will raise an exception if
43+ the requested file is not found.
44+ """
45+ if not os.path.exists(os.path.join(self.unpack_dir, fn)):
46+ raise ContainerException("Could not find '%s'" % fn)
47
48- if not os.path.isfile(fn):
49- raise ContainerException("Could not find '%s'" % rel)
50- return open_file_read(fn)
51+ with open(os.path.join(self.unpack_dir, fn), "rb") as fd:
52+ return fd.read()
53
54 def get_files_list(self):
55 """List all files included in this package."""
56diff --git a/reviewtools/sr_lint.py b/reviewtools/sr_lint.py
57index 518e9a2..aeea216 100644
58--- a/reviewtools/sr_lint.py
59+++ b/reviewtools/sr_lint.py
60@@ -1982,11 +1982,10 @@ class SnapReviewLint(SnapReview):
61 appnames.append("%s.%s" % (self.snap_yaml["name"], app))
62
63 try:
64- fh = self.snap._extract_file(fn)
65+ file = self.snap.get_file(fn)
66 except ContainerException as e:
67 error(str(e))
68- lines = fh.readlines()
69- fh.close()
70+ lines = file.decode().split("\n")
71
72 # For now, just check Exec=, Icon= and bools since:
73 # - snapd strips out anything it doesn't understand
74@@ -2130,7 +2129,7 @@ class SnapReviewLint(SnapReview):
75 for f in self.pkg_files:
76 fn = os.path.relpath(f, self._get_unpack_dir())
77 if fn.startswith("meta/gui/") and fn.endswith(".desktop"):
78- self._verify_desktop_file(f)
79+ self._verify_desktop_file(fn)
80 has_desktop_files = True
81 break
82
83diff --git a/reviewtools/tests/containers/test_base_container.py b/reviewtools/tests/containers/test_base_container.py
84index 4d0563f..976c74a 100644
85--- a/reviewtools/tests/containers/test_base_container.py
86+++ b/reviewtools/tests/containers/test_base_container.py
87@@ -12,9 +12,7 @@ class TestBaseContainer(unittest.TestCase):
88 @classmethod
89 def setUpClass(cls):
90 cls.tmp_dir = mkdtemp()
91- cls.fn = make_snap2(
92- output_dir=cls.tmp_dir,
93- )
94+ cls.fn = make_snap2(output_dir=cls.tmp_dir, yaml="Test")
95
96 @classmethod
97 def tearDownClass(cls):
98@@ -25,7 +23,7 @@ class TestBaseContainer(unittest.TestCase):
99 def test_initialization_container__happy(self):
100 try:
101 BaseContainer(self.fn)
102- except Exception:
103+ except ContainerException:
104 self.fail(
105 "An unexpected error occurred during BaseContainer initialization with container file"
106 )
107@@ -37,3 +35,18 @@ class TestBaseContainer(unittest.TestCase):
108 "does not exists or has incorrect permissions"
109 in context.exception.value
110 )
111+
112+ # Test get file
113+ def test_get_file__happy(self):
114+ try:
115+ container = BaseContainer(self.fn)
116+ snap_yaml = container.get_file("meta/snap.yaml")
117+ self.assertEqual(snap_yaml.decode(), "Test")
118+ except ContainerException:
119+ self.fail("An unexpected error occurred while getting meta/snap.yaml")
120+
121+ def test_get_file__missing_file(self):
122+ with self.assertRaises(ContainerException) as context:
123+ container = BaseContainer(self.fn)
124+ container.get_file("non/existent/file")
125+ self.assertTrue("Could not find" in context.exception.value)

Subscribers

People subscribed via source and target branches