get_pr_ut.py 16.3 KB
Newer Older
C
chalsliu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" For the PR that only modified the unit test, get cases in pull request. """

import os
import json
18 19
import re
import sys
20 21
import time
import subprocess
22
import requests
23 24
import urllib.request
import ssl
Y
YUNSHEN XIE 已提交
25
import platform
C
chalsliu 已提交
26 27 28
from github import Github

PADDLE_ROOT = os.getenv('PADDLE_ROOT', '/paddle/')
C
chalsliu 已提交
29 30
PADDLE_ROOT += '/'
PADDLE_ROOT = PADDLE_ROOT.replace('//', '/')
31
ssl._create_default_https_context = ssl._create_unverified_context
C
chalsliu 已提交
32 33 34 35 36 37


class PRChecker(object):
    """ PR Checker. """

    def __init__(self):
38
        self.github = Github(os.getenv('GITHUB_API_TOKEN'), timeout=60)
C
chalsliu 已提交
39
        self.repo = self.github.get_repo('PaddlePaddle/Paddle')
40
        self.py_prog_oneline = re.compile('\d+\|\s*#.*')
C
chalsliu 已提交
41 42
        self.py_prog_multiline_a = re.compile('\d+\|\s*r?""".*?"""', re.DOTALL)
        self.py_prog_multiline_b = re.compile("\d+\|\s*r?'''.*?'''", re.DOTALL)
43 44 45
        self.cc_prog_online = re.compile('\d+\|\s*//.*')
        self.cc_prog_multiline = re.compile('\d+\|\s*/\*.*?\*/', re.DOTALL)
        self.lineno_prog = re.compile('@@ \-\d+,\d+ \+(\d+),(\d+) @@')
C
chalsliu 已提交
46
        self.pr = None
47
        self.suffix = ''
C
chalsliu 已提交
48
        self.full_case = False
C
chalsliu 已提交
49 50 51 52 53

    def init(self):
        """ Get pull request. """
        pr_id = os.getenv('GIT_PR_ID')
        if not pr_id:
54
            print('PREC No PR ID')
C
chalsliu 已提交
55
            exit(0)
56 57 58
        suffix = os.getenv('PREC_SUFFIX')
        if suffix:
            self.suffix = suffix
C
chalsliu 已提交
59
        self.pr = self.repo.get_pull(int(pr_id))
C
chalsliu 已提交
60 61 62 63 64 65 66 67 68
        last_commit = None
        ix = 0
        while True:
            commits = self.pr.get_commits().get_page(ix)
            for c in commits:
                last_commit = c.commit
            else:
                break
            ix = ix + 1
69 70
        if last_commit.message.find('test=allcase') != -1:
            print('PREC test=allcase is set')
C
chalsliu 已提交
71
            self.full_case = True
C
chalsliu 已提交
72

73 74 75 76 77 78 79 80
    #todo: exception
    def __wget_with_retry(self, url):
        ix = 1
        proxy = '--no-proxy'
        while ix < 6:
            if ix // 2 == 0:
                proxy = ''
            else:
81 82 83 84
                if platform.system() == 'Windows':
                    proxy = '-Y off'
                else:
                    proxy = '--no-proxy'
85 86 87 88 89 90
            code = subprocess.call(
                'wget -q {} --no-check-certificate {}'.format(proxy, url),
                shell=True)
            if code == 0:
                return True
            print(
91 92
                'PREC download {} error, retry {} time(s) after {} secs.[proxy_option={}]'
                .format(url, ix, ix * 10, proxy))
93 94 95 96
            time.sleep(ix * 10)
            ix += 1
        return False

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    def __urlretrieve(self, url, filename):
        ix = 1
        with_proxy = urllib.request.getproxies()
        without_proxy = {'http': '', 'http': ''}
        while ix < 6:
            if ix // 2 == 0:
                cur_proxy = urllib.request.ProxyHandler(without_proxy)
            else:
                cur_proxy = urllib.request.ProxyHandler(with_proxy)
            opener = urllib.request.build_opener(cur_proxy,
                                                 urllib.request.HTTPHandler)
            urllib.request.install_opener(opener)
            try:
                urllib.request.urlretrieve(url, filename)
            except Exception as e:
                print(e)
                print(
114 115
                    'PREC download {} error, retry {} time(s) after {} secs.[proxy_option={}]'
                    .format(url, ix, ix * 10, cur_proxy))
116 117 118 119 120 121 122 123
                continue
            else:
                return True
            time.sleep(ix * 10)
            ix += 1

        return False

C
chalsliu 已提交
124 125 126
    def get_pr_files(self):
        """ Get files in pull request. """
        page = 0
Z
zhangchunle 已提交
127
        file_dict = {}
C
chalsliu 已提交
128 129 130 131 132
        while True:
            files = self.pr.get_files().get_page(page)
            if not files:
                break
            for f in files:
Z
zhangchunle 已提交
133
                file_dict[PADDLE_ROOT + f.filename] = f.status
C
chalsliu 已提交
134
            page += 1
Z
zhangchunle 已提交
135 136 137 138 139 140
        print("pr modify files: %s" % file_dict)
        return file_dict

    def get_is_white_file(self, filename):
        """ judge is white file in pr's files. """
        isWhiteFile = False
141 142 143 144
        not_white_files = (PADDLE_ROOT + 'cmake/', PADDLE_ROOT + 'patches/',
                           PADDLE_ROOT + 'tools/dockerfile/',
                           PADDLE_ROOT + 'tools/windows/',
                           PADDLE_ROOT + 'tools/test_runner.py',
Z
zhangchunle 已提交
145
                           PADDLE_ROOT + 'tools/parallel_UT_rule.py')
Z
zhangchunle 已提交
146 147
        if 'cmakelist' in filename.lower():
            isWhiteFile = False
148
        elif filename.startswith((not_white_files)):
Z
zhangchunle 已提交
149 150 151 152
            isWhiteFile = False
        else:
            isWhiteFile = True
        return isWhiteFile
C
chalsliu 已提交
153

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    def __get_comment_by_filetype(self, content, filetype):
        result = []
        if filetype == 'py':
            result = self.__get_comment_by_prog(content, self.py_prog_oneline)
            result.extend(
                self.__get_comment_by_prog(content, self.py_prog_multiline_a))
            result.extend(
                self.__get_comment_by_prog(content, self.py_prog_multiline_b))
        if filetype == 'cc':
            result = self.__get_comment_by_prog(content, self.cc_prog_oneline)
            result.extend(
                self.__get_comment_by_prog(content, self.cc_prog_multiline))
        return result

    def __get_comment_by_prog(self, content, prog):
        result_list = prog.findall(content)
        if not result_list:
C
chalsliu 已提交
171 172
            return []
        result = []
173 174 175 176 177 178
        for u in result_list:
            result.extend(u.split('\n'))
        return result

    def get_comment_of_file(self, f):
        #content = self.repo.get_contents(f.replace(PADDLE_ROOT, ''), 'pull/').decoded_content
179
        #todo: get file from github
180
        with open(f, encoding="utf-8") as fd:
181 182 183 184 185 186 187 188 189 190 191 192 193 194
            lines = fd.readlines()
        lineno = 1
        inputs = ''
        for line in lines:
            #for line in content.split('\n'):
            #input += str(lineno) + '|' + line + '\n'
            inputs += str(lineno) + '|' + line
            lineno += 1
        fietype = ''
        if f.endswith('.h') or f.endswith('.cc') or f.endswith('.cu'):
            filetype = 'cc'
        if f.endswith('.py'):
            filetype = 'py'
        else:
C
chalsliu 已提交
195
            return []
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
        return self.__get_comment_by_filetype(inputs, filetype)

    def get_pr_diff_lines(self):
        file_to_diff_lines = {}
        r = requests.get(self.pr.diff_url)
        data = r.text
        data = data.split('\n')
        ix = 0
        while ix < len(data):
            if data[ix].startswith('+++'):
                if data[ix].rstrip('\r\n') == '+++ /dev/null':
                    ix += 1
                    continue
                filename = data[ix][6:]
                ix += 1
                while ix < len(data):
                    result = self.lineno_prog.match(data[ix])
                    if not result:
                        break
                    lineno = int(result.group(1))
                    length = int(result.group(2))
                    ix += 1
                    end = ix + length
                    while ix < end:
                        if data[ix][0] == '-':
                            end += 1
                        if data[ix][0] == '+':
                            line_list = file_to_diff_lines.get(filename)
C
chalsliu 已提交
224 225
                            line = '{}{}'.format(lineno,
                                                 data[ix].replace('+', '|', 1))
226 227 228
                            if line_list:
                                line_list.append(line)
                            else:
229 230 231
                                file_to_diff_lines[filename] = [
                                    line,
                                ]
232 233 234 235 236 237 238 239 240
                        if data[ix][0] != '-':
                            lineno += 1
                        ix += 1
            ix += 1
        return file_to_diff_lines

    def is_only_comment(self, f):
        file_to_diff_lines = self.get_pr_diff_lines()
        comment_lines = self.get_comment_of_file(f)
C
chalsliu 已提交
241 242 243
        diff_lines = file_to_diff_lines.get(f.replace(PADDLE_ROOT, '', 1))
        if not diff_lines:
            return False
244 245 246
        for l in diff_lines:
            if l not in comment_lines:
                return False
247
        print('PREC {} is only comment'.format(f))
248 249
        return True

Z
zhangchunle 已提交
250
    def get_all_count(self):
251 252 253
        p = subprocess.Popen("cd {}build && ctest -N".format(PADDLE_ROOT),
                             shell=True,
                             stdout=subprocess.PIPE)
Y
YUNSHEN XIE 已提交
254 255 256 257 258
        out, err = p.communicate()
        for line in out.splitlines():
            if 'Total Tests:' in str(line):
                all_counts = line.split()[-1]
        return int(all_counts)
Z
zhangchunle 已提交
259

C
chalsliu 已提交
260 261
    def get_pr_ut(self):
        """ Get unit tests in pull request. """
C
chalsliu 已提交
262 263
        if self.full_case:
            return ''
C
chalsliu 已提交
264
        check_added_ut = False
C
chalsliu 已提交
265 266
        ut_list = []
        file_ut_map = None
Z
zhangchunle 已提交
267

268
        ret = self.__urlretrieve(
Z
zhangchunle 已提交
269 270
            'https://paddle-docker-tar.bj.bcebos.com/pre_test/ut_file_map.json',
            'ut_file_map.json')
271 272 273
        if not ret:
            print('PREC download file_ut.json failed')
            exit(1)
Z
zhangchunle 已提交
274

Z
zhangchunle 已提交
275
        with open('ut_file_map.json') as jsonfile:
C
chalsliu 已提交
276
            file_ut_map = json.load(jsonfile)
Z
zhangchunle 已提交
277 278 279

        current_system = platform.system()
        notHitMapFiles = []
Z
zhangchunle 已提交
280
        hitMapFiles = {}
Z
zhangchunle 已提交
281
        onlyCommentsFilesOrXpu = []
Z
zhangchunle 已提交
282 283 284 285
        filterFiles = []
        file_list = []
        file_dict = self.get_pr_files()
        for filename in file_dict:
Z
zhangchunle 已提交
286
            if filename.startswith(PADDLE_ROOT + 'python/'):
Z
zhangchunle 已提交
287
                file_list.append(filename)
Z
zhangchunle 已提交
288 289 290 291 292 293 294 295 296 297 298 299 300
            elif filename.startswith(PADDLE_ROOT + 'paddle/'):
                if filename.startswith((PADDLE_ROOT + 'paddle/infrt',
                                        PADDLE_ROOT + 'paddle/utils')):
                    filterFiles.append(filename)
                elif filename.startswith(PADDLE_ROOT + 'paddle/scripts'):
                    if filename.startswith(
                        (PADDLE_ROOT + 'paddle/scripts/paddle_build.sh',
                         PADDLE_ROOT + 'paddle/scripts/paddle_build.bat')):
                        file_list.append(filename)
                    else:
                        filterFiles.append(filename)
                else:
                    file_list.append(filename)
Z
zhangchunle 已提交
301
            else:
302
                if file_dict[filename] == 'added':
Z
zhangchunle 已提交
303 304
                    file_list.append(filename)
                else:
305 306 307 308 309
                    isWhiteFile = self.get_is_white_file(filename)
                    if isWhiteFile == False:
                        file_list.append(filename)
                    else:
                        filterFiles.append(filename)
Z
zhangchunle 已提交
310 311
        if len(file_list) == 0:
            ut_list.append('filterfiles_placeholder')
Z
zhangchunle 已提交
312 313 314 315 316 317 318 319 320 321 322 323
            ret = self.__urlretrieve(
                'https://paddle-docker-tar.bj.bcebos.com/pre_test/prec_delta',
                'prec_delta')
            if ret:
                with open('prec_delta') as delta:
                    for ut in delta:
                        ut_list.append(ut.rstrip('\r\n'))
            else:
                print('PREC download prec_delta failed')
                exit(1)
            PRECISION_TEST_Cases_ratio = format(
                float(len(ut_list)) / float(self.get_all_count()), '.2f')
Z
zhangchunle 已提交
324 325
            print("filterFiles: %s" % filterFiles)
            print("ipipe_log_param_PRECISION_TEST: true")
Z
zhangchunle 已提交
326 327 328 329
            print("ipipe_log_param_PRECISION_TEST_Cases_count: %s" %
                  len(ut_list))
            print("ipipe_log_param_PRECISION_TEST_Cases_ratio: %s" %
                  PRECISION_TEST_Cases_ratio)
Z
zhangchunle 已提交
330
            return '\n'.join(ut_list)
Z
zhangchunle 已提交
331 332 333 334 335 336 337 338 339 340
        else:
            for f in file_list:
                if current_system == "Darwin" or current_system == "Windows" or self.suffix == ".py3":
                    f_judge = f.replace(PADDLE_ROOT, '/paddle/', 1)
                    f_judge = f_judge.replace('//', '/')
                else:
                    f_judge = f
                if f_judge not in file_ut_map:
                    if f_judge.endswith('.md'):
                        ut_list.append('md_placeholder')
Z
zhangchunle 已提交
341
                        onlyCommentsFilesOrXpu.append(f_judge)
342
                    elif 'tests/unittests/xpu' in f_judge or 'tests/unittests/npu' in f_judge or 'op_npu.cc' in f_judge:
Z
zhangchunle 已提交
343 344 345 346 347 348
                        ut_list.append('xpu_npu_placeholder')
                        onlyCommentsFilesOrXpu.append(f_judge)
                    elif f_judge.endswith(('.h', '.cu', '.cc', 'py')):
                        if f_judge.find('test_') != -1 or f_judge.find(
                                '_test') != -1:
                            check_added_ut = True
Z
zhangchunle 已提交
349 350 351 352 353 354 355 356 357
                        if file_dict[f] not in ['removed']:
                            if self.is_only_comment(f):
                                ut_list.append('comment_placeholder')
                                onlyCommentsFilesOrXpu.append(f_judge)
                            else:
                                notHitMapFiles.append(f_judge)
                        else:
                            print("remove file not hit mapFiles: %s" % f_judge)
                    else:
358 359
                        notHitMapFiles.append(
                            f_judge) if file_dict[f] != 'removed' else print(
Z
zhangchunle 已提交
360 361 362
                                "remove file not hit mapFiles: %s" % f_judge)
                else:
                    if file_dict[f] not in ['removed']:
Z
zhangchunle 已提交
363 364 365 366
                        if self.is_only_comment(f):
                            ut_list.append('comment_placeholder')
                            onlyCommentsFilesOrXpu.append(f_judge)
                        else:
Z
zhangchunle 已提交
367 368
                            hitMapFiles[f_judge] = len(file_ut_map[f_judge])
                            ut_list.extend(file_ut_map.get(f_judge))
369
                    else:
Z
zhangchunle 已提交
370
                        hitMapFiles[f_judge] = len(file_ut_map[f_judge])
Z
zhangchunle 已提交
371
                        ut_list.extend(file_ut_map.get(f_judge))
Z
zhangchunle 已提交
372

Z
zhangchunle 已提交
373 374 375 376
            ut_list = list(set(ut_list))
            if len(notHitMapFiles) != 0:
                print("ipipe_log_param_PRECISION_TEST: false")
                print("notHitMapFiles: %s" % notHitMapFiles)
Z
zhangchunle 已提交
377 378
                if len(filterFiles) != 0:
                    print("filterFiles: %s" % filterFiles)
Z
zhangchunle 已提交
379
                return ''
C
chalsliu 已提交
380
            else:
Z
zhangchunle 已提交
381 382 383
                if check_added_ut:
                    with open('{}/added_ut'.format(PADDLE_ROOT)) as utfile:
                        for ut in utfile:
Z
zhangchunle 已提交
384
                            ut_list.append(ut.rstrip('\r\n'))
Z
zhangchunle 已提交
385 386 387 388 389 390 391 392 393 394 395
                if ut_list:
                    ret = self.__urlretrieve(
                        'https://paddle-docker-tar.bj.bcebos.com/pre_test/prec_delta',
                        'prec_delta')
                    if ret:
                        with open('prec_delta') as delta:
                            for ut in delta:
                                ut_list.append(ut.rstrip('\r\n'))
                    else:
                        print('PREC download prec_delta failed')
                        exit(1)
Z
zhangchunle 已提交
396
                    print("hitMapFiles: %s" % hitMapFiles)
Z
zhangchunle 已提交
397 398 399 400 401 402 403 404
                    print("ipipe_log_param_PRECISION_TEST: true")
                    print("ipipe_log_param_PRECISION_TEST_Cases_count: %s" %
                          len(ut_list))
                    PRECISION_TEST_Cases_ratio = format(
                        float(len(ut_list)) / float(self.get_all_count()),
                        '.2f')
                    print("ipipe_log_param_PRECISION_TEST_Cases_ratio: %s" %
                          PRECISION_TEST_Cases_ratio)
Z
zhangchunle 已提交
405 406
                    if len(filterFiles) != 0:
                        print("filterFiles: %s" % filterFiles)
Z
zhangchunle 已提交
407
                return '\n'.join(ut_list)
C
chalsliu 已提交
408 409 410 411 412


if __name__ == '__main__':
    pr_checker = PRChecker()
    pr_checker.init()
413 414
    with open('ut_list', 'w') as f:
        f.write(pr_checker.get_pr_ut())