summaryrefslogtreecommitdiffstats
path: root/meta/lib/patchtest/tests
diff options
context:
space:
mode:
authorTrevor Gamblin <tgamblin@baylibre.com>2023-09-13 13:00:46 -0400
committerRichard Purdie <richard.purdie@linuxfoundation.org>2023-09-14 15:20:08 +0100
commit4a6f38c5327b40a45c340af49fee9a0d5cc890bd (patch)
tree669ae555ecc031990579baa207d40f38ab7e1335 /meta/lib/patchtest/tests
parente12e6d94ecbea6e0dafc080f2f196e12228730eb (diff)
downloadpoky-4a6f38c5327b40a45c340af49fee9a0d5cc890bd.tar.gz
patchtest: Add tests from patchtest oe repo
Copy the core components of the patchtest-oe repo into meta/lib/patchtest in oe-core. (From OE-Core rev: 257f64f4e4414b78981104aec132b067beb5a92a) Signed-off-by: Trevor Gamblin <tgamblin@baylibre.com> Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
Diffstat (limited to 'meta/lib/patchtest/tests')
-rw-r--r--meta/lib/patchtest/tests/__init__.py0
-rw-r--r--meta/lib/patchtest/tests/base.py239
-rw-r--r--meta/lib/patchtest/tests/pyparsing/common.py26
-rw-r--r--meta/lib/patchtest/tests/pyparsing/parse_cve_tags.py18
-rw-r--r--meta/lib/patchtest/tests/pyparsing/parse_shortlog.py14
-rw-r--r--meta/lib/patchtest/tests/pyparsing/parse_signed_off_by.py22
-rw-r--r--meta/lib/patchtest/tests/pyparsing/parse_upstream_status.py24
-rw-r--r--meta/lib/patchtest/tests/test_mbox_author.py29
-rw-r--r--meta/lib/patchtest/tests/test_mbox_bugzilla.py22
-rw-r--r--meta/lib/patchtest/tests/test_mbox_cve.py49
-rw-r--r--meta/lib/patchtest/tests/test_mbox_description.py17
-rw-r--r--meta/lib/patchtest/tests/test_mbox_format.py16
-rw-r--r--meta/lib/patchtest/tests/test_mbox_mailinglist.py64
-rw-r--r--meta/lib/patchtest/tests/test_mbox_merge.py25
-rw-r--r--meta/lib/patchtest/tests/test_mbox_shortlog.py41
-rw-r--r--meta/lib/patchtest/tests/test_mbox_signed_off_by.py28
-rw-r--r--meta/lib/patchtest/tests/test_metadata_lic_files_chksum.py82
-rw-r--r--meta/lib/patchtest/tests/test_metadata_license.py55
-rw-r--r--meta/lib/patchtest/tests/test_metadata_max_length.py26
-rw-r--r--meta/lib/patchtest/tests/test_metadata_src_uri.py75
-rw-r--r--meta/lib/patchtest/tests/test_metadata_summary.py32
-rw-r--r--meta/lib/patchtest/tests/test_patch_cve.py51
-rw-r--r--meta/lib/patchtest/tests/test_patch_signed_off_by.py43
-rw-r--r--meta/lib/patchtest/tests/test_patch_upstream_status.py64
-rw-r--r--meta/lib/patchtest/tests/test_python_pylint.py61
25 files changed, 1123 insertions, 0 deletions
diff --git a/meta/lib/patchtest/tests/__init__.py b/meta/lib/patchtest/tests/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/meta/lib/patchtest/tests/__init__.py
diff --git a/meta/lib/patchtest/tests/base.py b/meta/lib/patchtest/tests/base.py
new file mode 100644
index 0000000000..27db380353
--- /dev/null
+++ b/meta/lib/patchtest/tests/base.py
@@ -0,0 +1,239 @@
1# Base class to be used by all test cases defined in the suite
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import unittest
8import logging
9import json
10import unidiff
11from data import PatchTestInput
12import mailbox
13import collections
14import sys
15import os
16import re
17
18sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'pyparsing'))
19
20logger = logging.getLogger('patchtest')
21debug=logger.debug
22info=logger.info
23warn=logger.warn
24error=logger.error
25
26Commit = collections.namedtuple('Commit', ['author', 'subject', 'commit_message', 'shortlog', 'payload'])
27
28class PatchtestOEError(Exception):
29 """Exception for handling patchtest-oe errors"""
30 def __init__(self, message, exitcode=1):
31 super().__init__(message)
32 self.exitcode = exitcode
33
34class Base(unittest.TestCase):
35 # if unit test fails, fail message will throw at least the following JSON: {"id": <testid>}
36
37 endcommit_messages_regex = re.compile('\(From \w+-\w+ rev:|(?<!\S)Signed-off-by|(?<!\S)---\n')
38 patchmetadata_regex = re.compile('-{3} \S+|\+{3} \S+|@{2} -\d+,\d+ \+\d+,\d+ @{2} \S+')
39
40
41 @staticmethod
42 def msg_to_commit(msg):
43 payload = msg.get_payload()
44 return Commit(subject=msg['subject'].replace('\n', ' ').replace(' ', ' '),
45 author=msg.get('From'),
46 shortlog=Base.shortlog(msg['subject']),
47 commit_message=Base.commit_message(payload),
48 payload=payload)
49
50 @staticmethod
51 def commit_message(payload):
52 commit_message = payload.__str__()
53 match = Base.endcommit_messages_regex.search(payload)
54 if match:
55 commit_message = payload[:match.start()]
56 return commit_message
57
58 @staticmethod
59 def shortlog(shlog):
60 # remove possible prefix (between brackets) before colon
61 start = shlog.find(']', 0, shlog.find(':'))
62 # remove also newlines and spaces at both sides
63 return shlog[start + 1:].replace('\n', '').strip()
64
65 @classmethod
66 def setUpClass(cls):
67
68 # General objects: mailbox.mbox and patchset
69 cls.mbox = mailbox.mbox(PatchTestInput.repo.patch)
70
71 # Patch may be malformed, so try parsing it
72 cls.unidiff_parse_error = ''
73 cls.patchset = None
74 try:
75 cls.patchset = unidiff.PatchSet.from_filename(PatchTestInput.repo.patch, encoding=u'UTF-8')
76 except unidiff.UnidiffParseError as upe:
77 cls.patchset = []
78 cls.unidiff_parse_error = str(upe)
79
80 # Easy to iterate list of commits
81 cls.commits = []
82 for msg in cls.mbox:
83 if msg['subject'] and msg.get_payload():
84 cls.commits.append(Base.msg_to_commit(msg))
85
86 cls.setUpClassLocal()
87
88 @classmethod
89 def tearDownClass(cls):
90 cls.tearDownClassLocal()
91
92 @classmethod
93 def setUpClassLocal(cls):
94 pass
95
96 @classmethod
97 def tearDownClassLocal(cls):
98 pass
99
100 def fail(self, issue, fix=None, commit=None, data=None):
101 """ Convert to a JSON string failure data"""
102 value = {'id': self.id(),
103 'issue': issue}
104
105 if fix:
106 value['fix'] = fix
107 if commit:
108 value['commit'] = {'subject': commit.subject,
109 'shortlog': commit.shortlog}
110
111 # extend return value with other useful info
112 if data:
113 value['data'] = data
114
115 return super(Base, self).fail(json.dumps(value))
116
117 def skip(self, issue, data=None):
118 """ Convert the skip string to JSON"""
119 value = {'id': self.id(),
120 'issue': issue}
121
122 # extend return value with other useful info
123 if data:
124 value['data'] = data
125
126 return super(Base, self).skipTest(json.dumps(value))
127
128 def shortid(self):
129 return self.id().split('.')[-1]
130
131 def __str__(self):
132 return json.dumps({'id': self.id()})
133
134class Metadata(Base):
135 @classmethod
136 def setUpClassLocal(cls):
137 cls.tinfoil = cls.setup_tinfoil()
138
139 # get info about added/modified/remove recipes
140 cls.added, cls.modified, cls.removed = cls.get_metadata_stats(cls.patchset)
141
142 @classmethod
143 def tearDownClassLocal(cls):
144 cls.tinfoil.shutdown()
145
146 @classmethod
147 def setup_tinfoil(cls, config_only=False):
148 """Initialize tinfoil api from bitbake"""
149
150 # import relevant libraries
151 try:
152 scripts_path = os.path.join(PatchTestInput.repodir, 'scripts', 'lib')
153 if scripts_path not in sys.path:
154 sys.path.insert(0, scripts_path)
155 import scriptpath
156 scriptpath.add_bitbake_lib_path()
157 import bb.tinfoil
158 except ImportError:
159 raise PatchtestOEError('Could not import tinfoil module')
160
161 orig_cwd = os.path.abspath(os.curdir)
162
163 # Load tinfoil
164 tinfoil = None
165 try:
166 builddir = os.environ.get('BUILDDIR')
167 if not builddir:
168 logger.warn('Bitbake environment not loaded?')
169 return tinfoil
170 os.chdir(builddir)
171 tinfoil = bb.tinfoil.Tinfoil()
172 tinfoil.prepare(config_only=config_only)
173 except bb.tinfoil.TinfoilUIException as te:
174 if tinfoil:
175 tinfoil.shutdown()
176 raise PatchtestOEError('Could not prepare properly tinfoil (TinfoilUIException)')
177 except Exception as e:
178 if tinfoil:
179 tinfoil.shutdown()
180 raise e
181 finally:
182 os.chdir(orig_cwd)
183
184 return tinfoil
185
186 @classmethod
187 def get_metadata_stats(cls, patchset):
188 """Get lists of added, modified and removed metadata files"""
189
190 def find_pn(data, path):
191 """Find the PN from data"""
192 pn = None
193 pn_native = None
194 for _path, _pn in data:
195 if path in _path:
196 if 'native' in _pn:
197 # store the native PN but look for the non-native one first
198 pn_native = _pn
199 else:
200 pn = _pn
201 break
202 else:
203 # sent the native PN if found previously
204 if pn_native:
205 return pn_native
206
207 # on renames (usually upgrades), we need to check (FILE) base names
208 # because the unidiff library does not provided the new filename, just the modified one
209 # and tinfoil datastore, once the patch is merged, will contain the new filename
210 path_basename = path.split('_')[0]
211 for _path, _pn in data:
212 _path_basename = _path.split('_')[0]
213 if path_basename == _path_basename:
214 pn = _pn
215 return pn
216
217 if not cls.tinfoil:
218 cls.tinfoil = cls.setup_tinfoil()
219
220 added_paths, modified_paths, removed_paths = [], [], []
221 added, modified, removed = [], [], []
222
223 # get metadata filename additions, modification and removals
224 for patch in patchset:
225 if patch.path.endswith('.bb') or patch.path.endswith('.bbappend') or patch.path.endswith('.inc'):
226 if patch.is_added_file:
227 added_paths.append(os.path.join(os.path.abspath(PatchTestInput.repodir), patch.path))
228 elif patch.is_modified_file:
229 modified_paths.append(os.path.join(os.path.abspath(PatchTestInput.repodir), patch.path))
230 elif patch.is_removed_file:
231 removed_paths.append(os.path.join(os.path.abspath(PatchTestInput.repodir), patch.path))
232
233 data = cls.tinfoil.cooker.recipecaches[''].pkg_fn.items()
234
235 added = [find_pn(data,path) for path in added_paths]
236 modified = [find_pn(data,path) for path in modified_paths]
237 removed = [find_pn(data,path) for path in removed_paths]
238
239 return [a for a in added if a], [m for m in modified if m], [r for r in removed if r]
diff --git a/meta/lib/patchtest/tests/pyparsing/common.py b/meta/lib/patchtest/tests/pyparsing/common.py
new file mode 100644
index 0000000000..9d37b0403d
--- /dev/null
+++ b/meta/lib/patchtest/tests/pyparsing/common.py
@@ -0,0 +1,26 @@
1# common pyparsing variables
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import pyparsing
8
9# general
10colon = pyparsing.Literal(":")
11start = pyparsing.LineStart()
12end = pyparsing.LineEnd()
13at = pyparsing.Literal("@")
14lessthan = pyparsing.Literal("<")
15greaterthan = pyparsing.Literal(">")
16opensquare = pyparsing.Literal("[")
17closesquare = pyparsing.Literal("]")
18inappropriate = pyparsing.CaselessLiteral("Inappropriate")
19submitted = pyparsing.CaselessLiteral("Submitted")
20
21# word related
22nestexpr = pyparsing.nestedExpr(opener='[', closer=']')
23inappropriateinfo = pyparsing.Literal("Inappropriate") + nestexpr
24submittedinfo = pyparsing.Literal("Submitted") + nestexpr
25word = pyparsing.Word(pyparsing.alphas)
26worddot = pyparsing.Word(pyparsing.alphas+".")
diff --git a/meta/lib/patchtest/tests/pyparsing/parse_cve_tags.py b/meta/lib/patchtest/tests/pyparsing/parse_cve_tags.py
new file mode 100644
index 0000000000..dd7131a650
--- /dev/null
+++ b/meta/lib/patchtest/tests/pyparsing/parse_cve_tags.py
@@ -0,0 +1,18 @@
1# signed-off-by pyparsing definition
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7
8import pyparsing
9import common
10
11name = pyparsing.Regex('\S+.*(?= <)')
12username = pyparsing.OneOrMore(common.worddot)
13domain = pyparsing.OneOrMore(common.worddot)
14cve = pyparsing.Regex('CVE\-\d{4}\-\d+')
15cve_mark = pyparsing.Literal("CVE:")
16
17cve_tag = pyparsing.AtLineStart(cve_mark + cve)
18patch_cve_tag = pyparsing.AtLineStart("+" + cve_mark + cve)
diff --git a/meta/lib/patchtest/tests/pyparsing/parse_shortlog.py b/meta/lib/patchtest/tests/pyparsing/parse_shortlog.py
new file mode 100644
index 0000000000..26e9612c4a
--- /dev/null
+++ b/meta/lib/patchtest/tests/pyparsing/parse_shortlog.py
@@ -0,0 +1,14 @@
1# subject pyparsing definition
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7# NOTE:This is an oversimplified syntax of the mbox's summary
8
9import pyparsing
10import common
11
12target = pyparsing.OneOrMore(pyparsing.Word(pyparsing.printables.replace(':','')))
13summary = pyparsing.OneOrMore(pyparsing.Word(pyparsing.printables))
14shortlog = common.start + target + common.colon + summary + common.end
diff --git a/meta/lib/patchtest/tests/pyparsing/parse_signed_off_by.py b/meta/lib/patchtest/tests/pyparsing/parse_signed_off_by.py
new file mode 100644
index 0000000000..c8a4351551
--- /dev/null
+++ b/meta/lib/patchtest/tests/pyparsing/parse_signed_off_by.py
@@ -0,0 +1,22 @@
1# signed-off-by pyparsing definition
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7
8import pyparsing
9import common
10
11name = pyparsing.Regex('\S+.*(?= <)')
12username = pyparsing.OneOrMore(common.worddot)
13domain = pyparsing.OneOrMore(common.worddot)
14
15# taken from https://pyparsing-public.wikispaces.com/Helpful+Expressions
16email = pyparsing.Regex(r"(?P<user>[A-Za-z0-9._%+-]+)@(?P<hostname>[A-Za-z0-9.-]+)\.(?P<domain>[A-Za-z]{2,})")
17
18email_enclosed = common.lessthan + email + common.greaterthan
19
20signed_off_by_mark = pyparsing.Literal("Signed-off-by:")
21signed_off_by = pyparsing.AtLineStart(signed_off_by_mark + name + email_enclosed)
22patch_signed_off_by = pyparsing.AtLineStart("+" + signed_off_by_mark + name + email_enclosed)
diff --git a/meta/lib/patchtest/tests/pyparsing/parse_upstream_status.py b/meta/lib/patchtest/tests/pyparsing/parse_upstream_status.py
new file mode 100644
index 0000000000..511b36d033
--- /dev/null
+++ b/meta/lib/patchtest/tests/pyparsing/parse_upstream_status.py
@@ -0,0 +1,24 @@
1# upstream-status pyparsing definition
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7
8import common
9import pyparsing
10
11upstream_status_literal_valid_status = ["Pending", "Accepted", "Backport", "Denied", "Inappropriate", "Submitted"]
12upstream_status_nonliteral_valid_status = ["Pending", "Accepted", "Backport", "Denied", "Inappropriate [reason]", "Submitted [where]"]
13
14upstream_status_valid_status = pyparsing.Or(
15 [pyparsing.Literal(status) for status in upstream_status_literal_valid_status]
16)
17
18upstream_status_mark = pyparsing.Literal("Upstream-Status")
19inappropriate_status_mark = common.inappropriate
20submitted_status_mark = common.submitted
21
22upstream_status = common.start + upstream_status_mark + common.colon + upstream_status_valid_status
23upstream_status_inappropriate_info = common.start + upstream_status_mark + common.colon + common.inappropriateinfo
24upstream_status_submitted_info = common.start + upstream_status_mark + common.colon + common.submittedinfo
diff --git a/meta/lib/patchtest/tests/test_mbox_author.py b/meta/lib/patchtest/tests/test_mbox_author.py
new file mode 100644
index 0000000000..6c79f164d4
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_mbox_author.py
@@ -0,0 +1,29 @@
1# Checks related to the patch's author
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import base
8import re
9
10class Author(base.Base):
11
12 auh_email = '<auh@auh.yoctoproject.org>'
13
14 invalids = [re.compile("^Upgrade Helper.+"),
15 re.compile(re.escape(auh_email)),
16 re.compile("uh@not\.set"),
17 re.compile("\S+@example\.com")]
18
19
20 def test_author_valid(self):
21 for commit in self.commits:
22 for invalid in self.invalids:
23 if invalid.search(commit.author):
24 self.fail('Invalid author %s' % commit.author, 'Resend the series with a valid patch\'s author', commit)
25
26 def test_non_auh_upgrade(self):
27 for commit in self.commits:
28 if self.auh_email in commit.payload:
29 self.fail('Invalid author %s in commit message' % self.auh_email, 'Resend the series with a valid patch\'s author', commit)
diff --git a/meta/lib/patchtest/tests/test_mbox_bugzilla.py b/meta/lib/patchtest/tests/test_mbox_bugzilla.py
new file mode 100644
index 0000000000..e8de48bb8d
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_mbox_bugzilla.py
@@ -0,0 +1,22 @@
1# Checks related to the patch's bugzilla tag
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import re
8import base
9
10class Bugzilla(base.Base):
11 rexp_detect = re.compile("\[\s?YOCTO.*\]", re.IGNORECASE)
12 rexp_validation = re.compile("\[(\s?YOCTO\s?#\s?(\d+)\s?,?)+\]", re.IGNORECASE)
13
14 def test_bugzilla_entry_format(self):
15 for commit in Bugzilla.commits:
16 for line in commit.commit_message.splitlines():
17 if self.rexp_detect.match(line):
18 if not self.rexp_validation.match(line):
19 self.fail('Yocto Project bugzilla tag is not correctly formatted',
20 'Specify bugzilla ID in commit description with format: "[YOCTO #<bugzilla ID>]"',
21 commit)
22
diff --git a/meta/lib/patchtest/tests/test_mbox_cve.py b/meta/lib/patchtest/tests/test_mbox_cve.py
new file mode 100644
index 0000000000..f99194c094
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_mbox_cve.py
@@ -0,0 +1,49 @@
1# Checks related to the patch's CVE lines
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License version 2 as
7# published by the Free Software Foundation.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License along
15# with this program; if not, write to the Free Software Foundation, Inc.,
16# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
18# SPDX-License-Identifier: GPL-2.0-or-later
19
20import base
21import os
22import parse_cve_tags
23import re
24
25class CVE(base.Base):
26
27 revert_shortlog_regex = re.compile('Revert\s+".*"')
28 prog = parse_cve_tags.cve_tag
29
30 def setUp(self):
31 if self.unidiff_parse_error:
32 self.skip('Parse error %s' % self.unidiff_parse_error)
33
34 # we are just interested in series that introduce CVE patches, thus discard other
35 # possibilities: modification to current CVEs, patch directly introduced into the
36 # recipe, upgrades already including the CVE, etc.
37 new_cves = [p for p in self.patchset if p.path.endswith('.patch') and p.is_added_file]
38 if not new_cves:
39 self.skip('No new CVE patches introduced')
40
41 def test_cve_presence_in_commit_message(self):
42 for commit in CVE.commits:
43 # skip those patches that revert older commits, these do not required the tag presence
44 if self.revert_shortlog_regex.match(commit.shortlog):
45 continue
46 if not self.prog.search_string(commit.payload):
47 self.fail('Missing or incorrectly formatted CVE tag in mbox',
48 'Correct or include the CVE tag in the mbox with format: "CVE: CVE-YYYY-XXXX"',
49 commit)
diff --git a/meta/lib/patchtest/tests/test_mbox_description.py b/meta/lib/patchtest/tests/test_mbox_description.py
new file mode 100644
index 0000000000..7addc6b5f7
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_mbox_description.py
@@ -0,0 +1,17 @@
1# Checks related to the patch's commit_message
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import base
8
9class CommitMessage(base.Base):
10
11 def test_commit_message_presence(self):
12 for commit in CommitMessage.commits:
13 if not commit.commit_message.strip():
14 self.fail('Patch is missing a descriptive commit message',
15 'Please include a commit message on your patch explaining the change (most importantly why the change is being made)',
16 commit)
17
diff --git a/meta/lib/patchtest/tests/test_mbox_format.py b/meta/lib/patchtest/tests/test_mbox_format.py
new file mode 100644
index 0000000000..85c452ca0d
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_mbox_format.py
@@ -0,0 +1,16 @@
1# Checks correct parsing of mboxes
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import base
8import re
9
10class MboxFormat(base.Base):
11
12 def test_mbox_format(self):
13 if self.unidiff_parse_error:
14 self.fail('Series cannot be parsed correctly due to malformed diff lines',
15 'Create the series again using git-format-patch and ensure it can be applied using git am',
16 data=[('Diff line', re.sub('^.+:\s(?<!$)','',self.unidiff_parse_error))])
diff --git a/meta/lib/patchtest/tests/test_mbox_mailinglist.py b/meta/lib/patchtest/tests/test_mbox_mailinglist.py
new file mode 100644
index 0000000000..de38e205b1
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_mbox_mailinglist.py
@@ -0,0 +1,64 @@
1# Check if the series was intended for other project (not OE-Core)
2#
3# Copyright (C) 2017 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import subprocess
8import collections
9import base
10import re
11from data import PatchTestInput
12
13class MailingList(base.Base):
14
15 # base paths of main yocto project sub-projects
16 paths = {
17 'oe-core': ['meta-selftest', 'meta-skeleton', 'meta', 'scripts'],
18 'bitbake': ['bitbake'],
19 'documentation': ['documentation'],
20 'poky': ['meta-poky','meta-yocto-bsp'],
21 'oe': ['meta-gpe', 'meta-gnome', 'meta-efl', 'meta-networking', 'meta-multimedia','meta-initramfs', 'meta-ruby', 'contrib', 'meta-xfce', 'meta-filesystems', 'meta-perl', 'meta-webserver', 'meta-systemd', 'meta-oe', 'meta-python']
22 }
23
24 # scripts folder is a mix of oe-core and poky, most is oe-core code except:
25 poky_scripts = ['scripts/yocto-bsp', 'scripts/yocto-kernel', 'scripts/yocto-layer', 'scripts/lib/bsp']
26
27 Project = collections.namedtuple('Project', ['name', 'listemail', 'gitrepo', 'paths'])
28
29 bitbake = Project(name='Bitbake', listemail='bitbake-devel@lists.openembedded.org', gitrepo='http://git.openembedded.org/bitbake/', paths=paths['bitbake'])
30 doc = Project(name='Documentantion', listemail='yocto@yoctoproject.org', gitrepo='http://git.yoctoproject.org/cgit/cgit.cgi/yocto-docs/', paths=paths['documentation'])
31 poky = Project(name='Poky', listemail='poky@yoctoproject.org', gitrepo='http://git.yoctoproject.org/cgit/cgit.cgi/poky/', paths=paths['poky'])
32 oe = Project(name='oe', listemail='openembedded-devel@lists.openembedded.org', gitrepo='http://git.openembedded.org/meta-openembedded/', paths=paths['oe'])
33
34
35 def test_target_mailing_list(self):
36 """In case of merge failure, check for other targeted projects"""
37 if PatchTestInput.repo.ismerged:
38 self.skip('Series merged, no reason to check other mailing lists')
39
40 # a meta project may be indicted in the message subject, if this is the case, just fail
41 # TODO: there may be other project with no-meta prefix, we also need to detect these
42 project_regex = re.compile("\[(?P<project>meta-.+)\]")
43 for commit in MailingList.commits:
44 match = project_regex.match(commit.subject)
45 if match:
46 self.fail('Series sent to the wrong mailing list',
47 'Check the project\'s README (%s) and send the patch to the indicated list' % match.group('project'),
48 commit)
49
50 for patch in self.patchset:
51 folders = patch.path.split('/')
52 base_path = folders[0]
53 for project in [self.bitbake, self.doc, self.oe, self.poky]:
54 if base_path in project.paths:
55 self.fail('Series sent to the wrong mailing list or some patches from the series correspond to different mailing lists', 'Send the series again to the correct mailing list (ML)',
56 data=[('Suggested ML', '%s [%s]' % (project.listemail, project.gitrepo)),
57 ('Patch\'s path:', patch.path)])
58
59 # check for poky's scripts code
60 if base_path.startswith('scripts'):
61 for poky_file in self.poky_scripts:
62 if patch.path.startswith(poky_file):
63 self.fail('Series sent to the wrong mailing list or some patches from the series correspond to different mailing lists', 'Send the series again to the correct mailing list (ML)',
64 data=[('Suggested ML', '%s [%s]' % (self.poky.listemail, self.poky.gitrepo)),('Patch\'s path:', patch.path)])
diff --git a/meta/lib/patchtest/tests/test_mbox_merge.py b/meta/lib/patchtest/tests/test_mbox_merge.py
new file mode 100644
index 0000000000..c8b6718d15
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_mbox_merge.py
@@ -0,0 +1,25 @@
1# Check if mbox was merged by patchtest
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import subprocess
8import base
9from data import PatchTestInput
10
11def headlog():
12 output = subprocess.check_output(
13 "cd %s; git log --pretty='%%h#%%aN#%%cD:#%%s' -1" % PatchTestInput.repodir,
14 universal_newlines=True,
15 shell=True
16 )
17 return output.split('#')
18
19class Merge(base.Base):
20 def test_series_merge_on_head(self):
21 if not PatchTestInput.repo.ismerged:
22 commithash, author, date, shortlog = headlog()
23 self.fail('Series does not apply on top of target branch',
24 'Rebase your series on top of targeted branch',
25 data=[('Targeted branch', '%s (currently at %s)' % (PatchTestInput.repo.branch, commithash))])
diff --git a/meta/lib/patchtest/tests/test_mbox_shortlog.py b/meta/lib/patchtest/tests/test_mbox_shortlog.py
new file mode 100644
index 0000000000..b6c2a209ff
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_mbox_shortlog.py
@@ -0,0 +1,41 @@
1# Checks related to the patch's summary
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import base
8import parse_shortlog
9import pyparsing
10
11maxlength = 90
12
13class Shortlog(base.Base):
14
15 def test_shortlog_format(self):
16 for commit in Shortlog.commits:
17 shortlog = commit.shortlog
18 if not shortlog.strip():
19 self.skip('Empty shortlog, no reason to execute shortlog format test')
20 else:
21 # no reason to re-check on revert shortlogs
22 if shortlog.startswith('Revert "'):
23 continue
24 try:
25 parse_shortlog.shortlog.parseString(shortlog)
26 except pyparsing.ParseException as pe:
27 self.fail('Shortlog does not follow expected format',
28 'Commit shortlog (first line of commit message) should follow the format "<target>: <summary>"',
29 commit)
30
31 def test_shortlog_length(self):
32 for commit in Shortlog.commits:
33 # no reason to re-check on revert shortlogs
34 shortlog = commit.shortlog
35 if shortlog.startswith('Revert "'):
36 continue
37 l = len(shortlog)
38 if l > maxlength:
39 self.fail('Commit shortlog is too long',
40 'Edit shortlog so that it is %d characters or less (currently %d characters)' % (maxlength, l),
41 commit)
diff --git a/meta/lib/patchtest/tests/test_mbox_signed_off_by.py b/meta/lib/patchtest/tests/test_mbox_signed_off_by.py
new file mode 100644
index 0000000000..6458951f1c
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_mbox_signed_off_by.py
@@ -0,0 +1,28 @@
1# Checks related to the patch's signed-off-by lines
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import base
8import parse_signed_off_by
9import re
10
11class SignedOffBy(base.Base):
12
13 revert_shortlog_regex = re.compile('Revert\s+".*"')
14
15 @classmethod
16 def setUpClassLocal(cls):
17 # match self.mark with no '+' preceding it
18 cls.prog = parse_signed_off_by.signed_off_by
19
20 def test_signed_off_by_presence(self):
21 for commit in SignedOffBy.commits:
22 # skip those patches that revert older commits, these do not required the tag presence
23 if self.revert_shortlog_regex.match(commit.shortlog):
24 continue
25 if not SignedOffBy.prog.search_string(commit.payload):
26 self.fail('Patch is missing Signed-off-by',
27 'Sign off the patch (either manually or with "git commit --amend -s")',
28 commit)
diff --git a/meta/lib/patchtest/tests/test_metadata_lic_files_chksum.py b/meta/lib/patchtest/tests/test_metadata_lic_files_chksum.py
new file mode 100644
index 0000000000..e9a5b6bb4e
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_metadata_lic_files_chksum.py
@@ -0,0 +1,82 @@
1# Checks related to the patch's LIC_FILES_CHKSUM metadata variable
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import base
8import re
9from data import PatchTestInput, PatchTestDataStore
10
11class LicFilesChkSum(base.Metadata):
12 metadata = 'LIC_FILES_CHKSUM'
13 license = 'LICENSE'
14 closed = 'CLOSED'
15 lictag = 'License-Update'
16 lictag_re = re.compile("^%s:" % lictag, re.MULTILINE)
17
18 def setUp(self):
19 # these tests just make sense on patches that can be merged
20 if not PatchTestInput.repo.canbemerged:
21 self.skip('Patch cannot be merged')
22
23 def test_lic_files_chksum_presence(self):
24 if not self.added:
25 self.skip('No added recipes, skipping test')
26
27 for pn in self.added:
28 rd = self.tinfoil.parse_recipe(pn)
29 pathname = rd.getVar('FILE')
30 # we are not interested in images
31 if '/images/' in pathname:
32 continue
33 lic_files_chksum = rd.getVar(self.metadata)
34 if rd.getVar(self.license) == self.closed:
35 continue
36 if not lic_files_chksum:
37 self.fail('%s is missing in newly added recipe' % self.metadata,
38 'Specify the variable %s in %s' % (self.metadata, pn))
39
40 def pretest_lic_files_chksum_modified_not_mentioned(self):
41 if not self.modified:
42 self.skip('No modified recipes, skipping pretest')
43 # get the proper metadata values
44 for pn in self.modified:
45 rd = self.tinfoil.parse_recipe(pn)
46 pathname = rd.getVar('FILE')
47 # we are not interested in images
48 if '/images/' in pathname:
49 continue
50 PatchTestDataStore['%s-%s-%s' % (self.shortid(),self.metadata,pn)] = rd.getVar(self.metadata)
51
52 def test_lic_files_chksum_modified_not_mentioned(self):
53 if not self.modified:
54 self.skip('No modified recipes, skipping test')
55
56 # get the proper metadata values
57 for pn in self.modified:
58 rd = self.tinfoil.parse_recipe(pn)
59 pathname = rd.getVar('FILE')
60 # we are not interested in images
61 if '/images/' in pathname:
62 continue
63 PatchTestDataStore['%s-%s-%s' % (self.shortid(),self.metadata,pn)] = rd.getVar(self.metadata)
64 # compare if there were changes between pre-merge and merge
65 for pn in self.modified:
66 pretest = PatchTestDataStore['pre%s-%s-%s' % (self.shortid(),self.metadata, pn)]
67 test = PatchTestDataStore['%s-%s-%s' % (self.shortid(),self.metadata, pn)]
68
69 # TODO: this is workaround to avoid false-positives when pretest metadata is empty (not reason found yet)
70 # For more info, check bug 12284
71 if not pretest:
72 return
73
74 if pretest != test:
75 # if any patch on the series contain reference on the metadata, fail
76 for commit in self.commits:
77 if self.lictag_re.search(commit.commit_message):
78 break
79 else:
80 self.fail('LIC_FILES_CHKSUM changed on target %s but there is no "%s" tag in commit message' % (pn, self.lictag),
81 'Include "%s: <description>" into the commit message with a brief description' % self.lictag,
82 data=[('Current checksum', pretest), ('New checksum', test)])
diff --git a/meta/lib/patchtest/tests/test_metadata_license.py b/meta/lib/patchtest/tests/test_metadata_license.py
new file mode 100644
index 0000000000..16604dbfb1
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_metadata_license.py
@@ -0,0 +1,55 @@
1# Checks related to the patch's LIC_FILES_CHKSUM metadata variable
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import base
8import os
9from data import PatchTestInput
10
11class License(base.Metadata):
12 metadata = 'LICENSE'
13 invalid_license = 'PATCHTESTINVALID'
14
15 def setUp(self):
16 # these tests just make sense on patches that can be merged
17 if not PatchTestInput.repo.canbemerged:
18 self.skip('Patch cannot be merged')
19
20 def test_license_presence(self):
21 if not self.added:
22 self.skip('No added recipes, skipping test')
23
24 # TODO: this is a workaround so we can parse the recipe not
25 # containing the LICENSE var: add some default license instead
26 # of INVALID into auto.conf, then remove this line at the end
27 auto_conf = os.path.join(os.environ.get('BUILDDIR'), 'conf', 'auto.conf')
28 open_flag = 'w'
29 if os.path.exists(auto_conf):
30 open_flag = 'a'
31 with open(auto_conf, open_flag) as fd:
32 for pn in self.added:
33 fd.write('LICENSE ??= "%s"\n' % self.invalid_license)
34
35 no_license = False
36 for pn in self.added:
37 rd = self.tinfoil.parse_recipe(pn)
38 license = rd.getVar(self.metadata)
39 if license == self.invalid_license:
40 no_license = True
41 break
42
43 # remove auto.conf line or the file itself
44 if open_flag == 'w':
45 os.remove(auto_conf)
46 else:
47 fd = open(auto_conf, 'r')
48 lines = fd.readlines()
49 fd.close()
50 with open(auto_conf, 'w') as fd:
51 fd.write(''.join(lines[:-1]))
52
53 if no_license:
54 self.fail('Recipe does not have the LICENSE field set', 'Include a LICENSE into the new recipe')
55
diff --git a/meta/lib/patchtest/tests/test_metadata_max_length.py b/meta/lib/patchtest/tests/test_metadata_max_length.py
new file mode 100644
index 0000000000..04a5e23469
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_metadata_max_length.py
@@ -0,0 +1,26 @@
1# Checks related to patch line lengths
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import base
8import re
9
10class MaxLength(base.Base):
11 add_mark = re.compile('\+ ')
12 max_length = 200
13
14 def test_max_line_length(self):
15 for patch in self.patchset:
16 # for the moment, we are just interested in metadata
17 if patch.path.endswith('.patch'):
18 continue
19 payload = str(patch)
20 for line in payload.splitlines():
21 if self.add_mark.match(line):
22 current_line_length = len(line[1:])
23 if current_line_length > self.max_length:
24 self.fail('Patch line too long (current length %s)' % current_line_length,
25 'Shorten the corresponding patch line (max length supported %s)' % self.max_length,
26 data=[('Patch', patch.path), ('Line', '%s ...' % line[0:80])])
diff --git a/meta/lib/patchtest/tests/test_metadata_src_uri.py b/meta/lib/patchtest/tests/test_metadata_src_uri.py
new file mode 100644
index 0000000000..718229d7ad
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_metadata_src_uri.py
@@ -0,0 +1,75 @@
1# Checks related to the patch's SRC_URI metadata variable
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import subprocess
8import base
9import re
10import os
11from data import PatchTestInput, PatchTestDataStore
12
13class SrcUri(base.Metadata):
14
15 metadata = 'SRC_URI'
16 md5sum = 'md5sum'
17 sha256sum = 'sha256sum'
18 git_regex = re.compile('^git\:\/\/.*')
19
20 def setUp(self):
21 # these tests just make sense on patches that can be merged
22 if not PatchTestInput.repo.canbemerged:
23 self.skip('Patch cannot be merged')
24
25 def pretest_src_uri_left_files(self):
26 if not self.modified:
27 self.skip('No modified recipes, skipping pretest')
28
29 # get the proper metadata values
30 for pn in self.modified:
31 # we are not interested in images
32 if 'core-image' in pn:
33 continue
34 rd = self.tinfoil.parse_recipe(pn)
35 PatchTestDataStore['%s-%s-%s' % (self.shortid(), self.metadata, pn)] = rd.getVar(self.metadata)
36
37 def test_src_uri_left_files(self):
38 if not self.modified:
39 self.skip('No modified recipes, skipping pretest')
40
41 # get the proper metadata values
42 for pn in self.modified:
43 # we are not interested in images
44 if 'core-image' in pn:
45 continue
46 rd = self.tinfoil.parse_recipe(pn)
47 PatchTestDataStore['%s-%s-%s' % (self.shortid(), self.metadata, pn)] = rd.getVar(self.metadata)
48
49 for pn in self.modified:
50 pretest_src_uri = PatchTestDataStore['pre%s-%s-%s' % (self.shortid(), self.metadata, pn)].split()
51 test_src_uri = PatchTestDataStore['%s-%s-%s' % (self.shortid(), self.metadata, pn)].split()
52
53 pretest_files = set([os.path.basename(patch) for patch in pretest_src_uri if patch.startswith('file://')])
54 test_files = set([os.path.basename(patch) for patch in test_src_uri if patch.startswith('file://')])
55
56 # check if files were removed
57 if len(test_files) < len(pretest_files):
58
59 # get removals from patchset
60 filesremoved_from_patchset = set()
61 for patch in self.patchset:
62 if patch.is_removed_file:
63 filesremoved_from_patchset.add(os.path.basename(patch.path))
64
65 # get the deleted files from the SRC_URI
66 filesremoved_from_usr_uri = pretest_files - test_files
67
68 # finally, get those patches removed at SRC_URI and not removed from the patchset
69 # TODO: we are not taking into account renames, so test may raise false positives
70 not_removed = filesremoved_from_usr_uri - filesremoved_from_patchset
71 if not_removed:
72 self.fail('Patches not removed from tree',
73 'Amend the patch containing the software patch file removal',
74 data=[('Patch', f) for f in not_removed])
75
diff --git a/meta/lib/patchtest/tests/test_metadata_summary.py b/meta/lib/patchtest/tests/test_metadata_summary.py
new file mode 100644
index 0000000000..931b26768e
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_metadata_summary.py
@@ -0,0 +1,32 @@
1# Checks related to the patch's summary metadata variable
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import base
8from data import PatchTestInput
9
10class Summary(base.Metadata):
11 metadata = 'SUMMARY'
12
13 def setUp(self):
14 # these tests just make sense on patches that can be merged
15 if not PatchTestInput.repo.canbemerged:
16 self.skip('Patch cannot be merged')
17
18 def test_summary_presence(self):
19 if not self.added:
20 self.skip('No added recipes, skipping test')
21
22 for pn in self.added:
23 # we are not interested in images
24 if 'core-image' in pn:
25 continue
26 rd = self.tinfoil.parse_recipe(pn)
27 summary = rd.getVar(self.metadata)
28
29 # "${PN} version ${PN}-${PR}" is the default, so fail if default
30 if summary.startswith('%s version' % pn):
31 self.fail('%s is missing in newly added recipe' % self.metadata,
32 'Specify the variable %s in %s' % (self.metadata, pn))
diff --git a/meta/lib/patchtest/tests/test_patch_cve.py b/meta/lib/patchtest/tests/test_patch_cve.py
new file mode 100644
index 0000000000..46ed9ef791
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_patch_cve.py
@@ -0,0 +1,51 @@
1# Checks related to the patch's CVE lines
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License version 2 as
7# published by the Free Software Foundation.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License along
15# with this program; if not, write to the Free Software Foundation, Inc.,
16# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
18# SPDX-License-Identifier: GPL-2.0-or-later
19
20import base
21import os
22import re
23
24class CVE(base.Base):
25
26 re_cve_pattern = re.compile("CVE\-\d{4}\-\d+", re.IGNORECASE)
27 re_cve_payload_tag = re.compile("\+CVE:(\s+CVE\-\d{4}\-\d+)+")
28
29 def setUp(self):
30 if self.unidiff_parse_error:
31 self.skip('Parse error %s' % self.unidiff_parse_error)
32
33 # we are just interested in series that introduce CVE patches, thus discard other
34 # possibilities: modification to current CVEs, patch directly introduced into the
35 # recipe, upgrades already including the CVE, etc.
36 new_cves = [p for p in self.patchset if p.path.endswith('.patch') and p.is_added_file]
37 if not new_cves:
38 self.skip('No new CVE patches introduced')
39
40 def test_cve_tag_format(self):
41 for commit in CVE.commits:
42 if self.re_cve_pattern.search(commit.shortlog) or self.re_cve_pattern.search(commit.commit_message):
43 tag_found = False
44 for line in commit.payload.splitlines():
45 if self.re_cve_payload_tag.match(line):
46 tag_found = True
47 break
48 if not tag_found:
49 self.fail('Missing or incorrectly formatted CVE tag in included patch file',
50 'Correct or include the CVE tag on cve patch with format: "CVE: CVE-YYYY-XXXX"',
51 commit)
diff --git a/meta/lib/patchtest/tests/test_patch_signed_off_by.py b/meta/lib/patchtest/tests/test_patch_signed_off_by.py
new file mode 100644
index 0000000000..4855d6daf7
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_patch_signed_off_by.py
@@ -0,0 +1,43 @@
1# Checks related to the patch's signed-off-by lines
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import base
8import parse_signed_off_by
9import re
10
11class PatchSignedOffBy(base.Base):
12
13 @classmethod
14 def setUpClassLocal(cls):
15 cls.newpatches = []
16 # get just those relevant patches: new software patches
17 for patch in cls.patchset:
18 if patch.path.endswith('.patch') and patch.is_added_file:
19 cls.newpatches.append(patch)
20
21 cls.mark = str(parse_signed_off_by.signed_off_by_mark).strip('"')
22
23 # match PatchSignedOffBy.mark with '+' preceding it
24 cls.prog = parse_signed_off_by.patch_signed_off_by
25
26 def setUp(self):
27 if self.unidiff_parse_error:
28 self.skip('Parse error %s' % self.unidiff_parse_error)
29
30 def test_signed_off_by_presence(self):
31 if not PatchSignedOffBy.newpatches:
32 self.skip("There are no new software patches, no reason to test %s presence" % PatchSignedOffBy.mark)
33
34 for newpatch in PatchSignedOffBy.newpatches:
35 payload = newpatch.__str__()
36 for line in payload.splitlines():
37 if self.patchmetadata_regex.match(line):
38 continue
39 if PatchSignedOffBy.prog.search_string(payload):
40 break
41 else:
42 self.fail('A patch file has been added, but does not have a Signed-off-by tag',
43 'Sign off the added patch file (%s)' % newpatch.path)
diff --git a/meta/lib/patchtest/tests/test_patch_upstream_status.py b/meta/lib/patchtest/tests/test_patch_upstream_status.py
new file mode 100644
index 0000000000..eda5353c66
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_patch_upstream_status.py
@@ -0,0 +1,64 @@
1# Checks related to the patch's upstream-status lines
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import base
8import parse_upstream_status
9import pyparsing
10import os
11
12class PatchUpstreamStatus(base.Base):
13
14 upstream_status_regex = pyparsing.AtLineStart("+" + "Upstream-Status")
15
16 @classmethod
17 def setUpClassLocal(cls):
18 cls.newpatches = []
19 # get just those relevant patches: new software patches
20 for patch in cls.patchset:
21 if patch.path.endswith('.patch') and patch.is_added_file:
22 cls.newpatches.append(patch)
23
24 def setUp(self):
25 if self.unidiff_parse_error:
26 self.skip('Python-unidiff parse error')
27 self.valid_status = ', '.join(parse_upstream_status.upstream_status_nonliteral_valid_status)
28 self.standard_format = 'Upstream-Status: <Valid status>'
29
30 def test_upstream_status_presence_format(self):
31 if not PatchUpstreamStatus.newpatches:
32 self.skip("There are no new software patches, no reason to test Upstream-Status presence/format")
33
34 for newpatch in PatchUpstreamStatus.newpatches:
35 payload = newpatch.__str__()
36 if not self.upstream_status_regex.search_string(payload):
37 self.fail('Added patch file is missing Upstream-Status in the header',
38 'Add Upstream-Status: <Valid status> to the header of %s' % newpatch.path,
39 data=[('Standard format', self.standard_format), ('Valid status', self.valid_status)])
40 for line in payload.splitlines():
41 if self.patchmetadata_regex.match(line):
42 continue
43 if self.upstream_status_regex.search_string(line):
44 if parse_upstream_status.inappropriate_status_mark.searchString(line):
45 try:
46 parse_upstream_status.upstream_status_inappropriate_info.parseString(line.lstrip('+'))
47 except pyparsing.ParseException as pe:
48 self.fail('Upstream-Status is Inappropriate, but no reason was provided',
49 'Include a brief reason why %s is inappropriate' % os.path.basename(newpatch.path),
50 data=[('Current', pe.pstr), ('Standard format', 'Upstream-Status: Inappropriate [reason]')])
51 elif parse_upstream_status.submitted_status_mark.searchString(line):
52 try:
53 parse_upstream_status.upstream_status_submitted_info.parseString(line.lstrip('+'))
54 except pyparsing.ParseException as pe:
55 self.fail('Upstream-Status is Submitted, but it is not mentioned where',
56 'Include where %s was submitted' % os.path.basename(newpatch.path),
57 data=[('Current', pe.pstr), ('Standard format', 'Upstream-Status: Submitted [where]')])
58 else:
59 try:
60 parse_upstream_status.upstream_status.parseString(line.lstrip('+'))
61 except pyparsing.ParseException as pe:
62 self.fail('Upstream-Status is in incorrect format',
63 'Fix Upstream-Status format in %s' % os.path.basename(newpatch.path),
64 data=[('Current', pe.pstr), ('Standard format', self.standard_format), ('Valid status', self.valid_status)])
diff --git a/meta/lib/patchtest/tests/test_python_pylint.py b/meta/lib/patchtest/tests/test_python_pylint.py
new file mode 100644
index 0000000000..ea8efb7c2a
--- /dev/null
+++ b/meta/lib/patchtest/tests/test_python_pylint.py
@@ -0,0 +1,61 @@
1# Checks related to the python code done with pylint
2#
3# Copyright (C) 2016 Intel Corporation
4#
5# SPDX-License-Identifier: GPL-2.0
6
7import base
8from data import PatchTestInput
9import pylint.epylint as lint
10
11class PyLint(base.Base):
12 pythonpatches = []
13 pylint_pretest = {}
14 pylint_test = {}
15 pylint_options = " -E --disable='E0611, E1101, F0401, E0602' --msg-template='L:{line} F:{module} I:{msg}'"
16
17 @classmethod
18 def setUpClassLocal(cls):
19 # get just those patches touching python files
20 cls.pythonpatches = []
21 for patch in cls.patchset:
22 if patch.path.endswith('.py'):
23 if not patch.is_removed_file:
24 cls.pythonpatches.append(patch)
25
26 def setUp(self):
27 if self.unidiff_parse_error:
28 self.skip('Python-unidiff parse error')
29 if not PatchTestInput.repo.canbemerged:
30 self.skip('Patch cannot be merged, no reason to execute the test method')
31 if not PyLint.pythonpatches:
32 self.skip('No python related patches, skipping test')
33
34 def pretest_pylint(self):
35 for pythonpatch in self.pythonpatches:
36 if pythonpatch.is_modified_file:
37 (pylint_stdout, pylint_stderr) = lint.py_run(command_options = pythonpatch.path + self.pylint_options, return_std=True)
38 for line in pylint_stdout.readlines():
39 if not '*' in line:
40 if line.strip():
41 self.pylint_pretest[line.strip().split(' ',1)[0]] = line.strip().split(' ',1)[1]
42
43 def test_pylint(self):
44 for pythonpatch in self.pythonpatches:
45 # a condition checking whether a file is renamed or not
46 # unidiff doesn't support this yet
47 if pythonpatch.target_file is not pythonpatch.path:
48 path = pythonpatch.target_file[2:]
49 else:
50 path = pythonpatch.path
51 (pylint_stdout, pylint_stderr) = lint.py_run(command_options = path + self.pylint_options, return_std=True)
52 for line in pylint_stdout.readlines():
53 if not '*' in line:
54 if line.strip():
55 self.pylint_test[line.strip().split(' ',1)[0]] = line.strip().split(' ',1)[1]
56
57 for issue in self.pylint_test:
58 if self.pylint_test[issue] not in self.pylint_pretest.values():
59 self.fail('Errors in your Python code were encountered',
60 'Correct the lines introduced by your patch',
61 data=[('Output', 'Please, fix the listed issues:'), ('', issue + ' ' + self.pylint_test[issue])])