test_sampcd_processor.py 18.2 KB
Newer Older
1 2 3
#! python

# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
4
#
5 6 7
# 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
8
#
9
#     http://www.apache.org/licenses/LICENSE-2.0
10
#
11 12 13 14 15 16 17
# 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.

import os
18
import re
19 20 21
import shutil
import unittest

22
import sampcd_processor
23 24 25 26 27 28 29 30 31 32
from sampcd_processor import (
    execute_samplecode,
    extract_code_blocks_from_docstr,
    find_all,
    find_last_future_line_end,
    get_test_capacity,
    insert_codes_into_codeblock,
    is_required_match,
    sampcd_extract_to_file,
)
33
from sampcd_processor_utils import get_api_md5, get_incrementapi
34 35 36 37 38 39 40 41 42 43


class Test_find_all(unittest.TestCase):
    def test_find_none(self):
        self.assertEqual(0, len(find_all('hello', 'world')))

    def test_find_one(self):
        self.assertListEqual([0], find_all('hello', 'hello'))

    def test_find_two(self):
44 45 46
        self.assertListEqual(
            [1, 15], find_all(' hello, world; hello paddle!', 'hello')
        )
47 48


49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
class Test_find_last_future_line_end(unittest.TestCase):
    def test_no_instant(self):
        samplecodes = """
                print(10//3)
        """
        self.assertIsNone(find_last_future_line_end(samplecodes))

    def test_1_instant(self):
        samplecodes = """
                from __future__ import print_function

                print(10//3)
        """
        mo = re.search("print_function\n", samplecodes)
        self.assertIsNotNone(mo)
64 65 66
        self.assertGreaterEqual(
            find_last_future_line_end(samplecodes), mo.end()
        )
67 68 69 70 71 72 73 74 75 76

    def test_2_instant(self):
        samplecodes = """
                from __future__ import print_function
                from __future__ import division

                print(10//3)
        """
        mo = re.search("division\n", samplecodes)
        self.assertIsNotNone(mo)
77 78 79
        self.assertGreaterEqual(
            find_last_future_line_end(samplecodes), mo.end()
        )
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107


class Test_extract_code_blocks_from_docstr(unittest.TestCase):
    def test_no_samplecode(self):
        docstr = """
        placeholder
        """
        codeblocks = extract_code_blocks_from_docstr(docstr)
        self.assertListEqual([], codeblocks)

    def test_codeblock_before_examples_is_ignored(self):
        docstr = """
            .. code-block:: python

                print(1+1)
        Examples:
        """
        codeblocks = extract_code_blocks_from_docstr(docstr)
        self.assertListEqual(codeblocks, [])

    def test_1_samplecode(self):
        docstr = """
        Examples:
            .. code-block:: python

                print(1+1)
        """
        codeblocks = extract_code_blocks_from_docstr(docstr)
108 109 110 111 112 113 114 115
        self.assertListEqual(
            codeblocks,
            [
                {
                    'codes': """print(1+1)""",
                    'name': None,
                    'id': 1,
                    'required': None,
116
                    'in_examples': True,
117 118 119
                }
            ],
        )
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

    def test_2_samplecodes(self):
        docstr = """
        placeholder
        Examples:
            .. code-block:: python

                print(1/0)

            .. code-block:: python
               :name: one_plus_one
               :linenos:

                # required: gpu
                print(1+1)
        """
        codeblocks = extract_code_blocks_from_docstr(docstr)
137 138 139 140 141 142 143 144
        self.assertListEqual(
            codeblocks,
            [
                {
                    'codes': """print(1/0)""",
                    'name': None,
                    'id': 1,
                    'required': None,
145
                    'in_examples': True,
146 147 148
                },
                {
                    'codes': """# required: gpu
149
print(1+1)""",
150 151 152
                    'name': 'one_plus_one',
                    'id': 2,
                    'required': 'gpu',
153
                    'in_examples': True,
154 155 156
                },
            ],
        )
157 158 159 160 161 162 163 164 165 166


class Test_insert_codes_into_codeblock(unittest.TestCase):
    def test_required_None(self):
        codeblock = {
            'codes': """print(1/0)""",
            'name': None,
            'id': 1,
            'required': None,
        }
167 168
        self.assertEqual(
            """
169 170 171 172
import os
os.environ["CUDA_VISIBLE_DEVICES"] = ""
print(1/0)
print("not-specified's sample code (name:None, id:1) is executed successfully!")""",
173 174
            insert_codes_into_codeblock(codeblock),
        )
175 176 177 178 179 180 181 182 183

    def test_required_gpu(self):
        codeblock = {
            'codes': """# required: gpu
print(1+1)""",
            'name': None,
            'id': 1,
            'required': 'gpu',
        }
184 185
        self.assertEqual(
            """
186 187 188 189 190
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
# required: gpu
print(1+1)
print("not-specified's sample code (name:None, id:1) is executed successfully!")""",
191 192
            insert_codes_into_codeblock(codeblock),
        )
193 194 195 196 197 198 199 200 201 202 203

    def test_from_future(self):
        codeblock = {
            'codes': """
from __future__ import print_function
from __future__ import division
print(10//3)""",
            'name': 'future',
            'id': 1,
            'required': None,
        }
204 205
        self.assertEqual(
            """
206 207 208 209 210 211 212
from __future__ import print_function
from __future__ import division

import os
os.environ["CUDA_VISIBLE_DEVICES"] = ""
print(10//3)
print("not-specified's sample code (name:future, id:1) is executed successfully!")""",
213 214
            insert_codes_into_codeblock(codeblock),
        )
215 216 217 218 219 220 221


def clear_capacity():
    sampcd_processor.SAMPLE_CODE_TEST_CAPACITY = set()
    sampcd_processor.RUN_ON_DEVICE = 'cpu'
    if sampcd_processor.ENV_KEY_TEST_CAPACITY in os.environ:
        del os.environ[sampcd_processor.ENV_KEY_TEST_CAPACITY]
222 223


224 225 226 227 228 229 230 231 232 233 234 235
class Test_get_test_capacity(unittest.TestCase):
    def setUp(self):
        clear_capacity()
        get_test_capacity()

    def tearDown(self):
        clear_capacity()
        get_test_capacity()

    def test_NoEnvVar(self):
        clear_capacity()
        get_test_capacity()
236 237 238 239 240 241
        self.assertCountEqual(
            [
                'cpu',
            ],
            sampcd_processor.SAMPLE_CODE_TEST_CAPACITY,
        )
242 243 244 245 246

    def test_NoEnvVar_RUN_ON_DEVICE_gpu(self):
        clear_capacity()
        sampcd_processor.RUN_ON_DEVICE = 'gpu'
        get_test_capacity()
247 248 249
        self.assertCountEqual(
            ['cpu', 'gpu'], sampcd_processor.SAMPLE_CODE_TEST_CAPACITY
        )
250 251 252 253 254

    def test_EnvVar_gpu(self):
        clear_capacity()
        os.environ[sampcd_processor.ENV_KEY_TEST_CAPACITY] = 'gpu'
        get_test_capacity()
255 256 257
        self.assertCountEqual(
            ['cpu', 'gpu'], sampcd_processor.SAMPLE_CODE_TEST_CAPACITY
        )
258 259 260 261 262

    def test_EnvVar_gpu_and_distributed(self):
        clear_capacity()
        os.environ[sampcd_processor.ENV_KEY_TEST_CAPACITY] = 'gpu,distributed'
        get_test_capacity()
263 264 265 266
        self.assertCountEqual(
            ['cpu', 'gpu', 'distributed'],
            sampcd_processor.SAMPLE_CODE_TEST_CAPACITY,
        )
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306


class Test_is_required_match(unittest.TestCase):
    def setUp(self):
        clear_capacity()

    def tearDown(self):
        clear_capacity()
        get_test_capacity()

    def test_alldefault(self):
        clear_capacity()
        get_test_capacity()
        self.assertTrue(is_required_match(''))
        self.assertTrue(is_required_match(None))
        self.assertTrue(is_required_match('cpu'))
        self.assertFalse(is_required_match('gpu'))
        self.assertIsNone(is_required_match('skiptest'))
        self.assertIsNone(is_required_match('skip'))
        self.assertIsNone(is_required_match('cpu,skiptest'))

    def test_gpu_equipped(self):
        clear_capacity()
        os.environ[sampcd_processor.ENV_KEY_TEST_CAPACITY] = 'gpu'
        get_test_capacity()
        self.assertTrue(is_required_match('cpu'))
        self.assertTrue(is_required_match('gpu'))
        self.assertTrue(is_required_match('gpu,cpu'))
        self.assertIsNone(is_required_match('skiptest'))
        self.assertFalse(is_required_match('distributed'))

    def test_gpu_distributed_equipped(self):
        clear_capacity()
        os.environ[sampcd_processor.ENV_KEY_TEST_CAPACITY] = 'gpu,distributed'
        get_test_capacity()
        self.assertTrue(is_required_match('cpu'))
        self.assertTrue(is_required_match('gpu'))
        self.assertTrue(is_required_match('distributed'))
        self.assertFalse(is_required_match('xpu'))
        self.assertIsNone(is_required_match('skiptest'))
307 308


309 310
class Test_execute_samplecode(unittest.TestCase):
    def setUp(self):
311 312 313
        if not os.path.exists(sampcd_processor.SAMPLECODE_TEMPDIR):
            os.mkdir(sampcd_processor.SAMPLECODE_TEMPDIR)
        self.successSampleCodeFile = os.path.join(
314 315
            sampcd_processor.SAMPLECODE_TEMPDIR, 'samplecode_success.py'
        )
316 317
        with open(self.successSampleCodeFile, 'w') as f:
            f.write('print(1+1)')
318
        self.failedSampleCodeFile = os.path.join(
319 320
            sampcd_processor.SAMPLECODE_TEMPDIR, 'samplecode_failed.py'
        )
321 322 323 324 325 326 327 328
        with open(self.failedSampleCodeFile, 'w') as f:
            f.write('print(1/0)')

    def tearDown(self):
        os.remove(self.successSampleCodeFile)
        os.remove(self.failedSampleCodeFile)

    def test_run_success(self):
329
        result, tfname, msg, exec_time = execute_samplecode(
330 331
            self.successSampleCodeFile
        )
332 333 334 335
        self.assertTrue(result)
        self.assertEqual(self.successSampleCodeFile, tfname)
        self.assertIsNotNone(msg)
        self.assertLess(msg.find('skipped'), 0)
336
        self.assertLess(exec_time, 10)
337 338

    def test_run_failed(self):
339
        result, tfname, msg, exec_time = execute_samplecode(
340 341
            self.failedSampleCodeFile
        )
342 343 344 345
        self.assertFalse(result)
        self.assertEqual(self.failedSampleCodeFile, tfname)
        self.assertIsNotNone(msg)
        self.assertLess(msg.find('skipped'), 0)
346
        self.assertLess(exec_time, 10)
347

348 349 350 351

def clear_summary_info():
    for k in sampcd_processor.SUMMARY_INFO.keys():
        sampcd_processor.SUMMARY_INFO[k].clear()
352 353 354


class Test_sampcd_extract_to_file(unittest.TestCase):
355
    def setUp(self):
356 357 358 359 360
        if not os.path.exists(sampcd_processor.SAMPLECODE_TEMPDIR):
            os.mkdir(sampcd_processor.SAMPLECODE_TEMPDIR)
        clear_capacity()
        os.environ[sampcd_processor.ENV_KEY_TEST_CAPACITY] = 'gpu,distributed'
        get_test_capacity()
361

362
    def tearDown(self):
363 364 365
        shutil.rmtree(sampcd_processor.SAMPLECODE_TEMPDIR)
        clear_capacity()
        get_test_capacity()
366 367

    def test_1_samplecode(self):
368 369 370
        comments = """
        Examples:
            .. code-block:: python
371

372 373 374
                print(1+1)
        """
        funcname = 'one_plus_one'
375
        sample_code_filenames = sampcd_extract_to_file(comments, funcname)
376 377 378 379 380 381 382 383 384
        self.assertCountEqual(
            [
                os.path.join(
                    sampcd_processor.SAMPLECODE_TEMPDIR,
                    funcname + '_example.py',
                )
            ],
            sample_code_filenames,
        )
385

386
    def test_no_samplecode(self):
387 388 389 390
        comments = """
        placeholder
        """
        funcname = 'one_plus_one'
391 392
        sample_code_filenames = sampcd_extract_to_file(comments, funcname)
        self.assertCountEqual([], sample_code_filenames)
393

394
    def test_2_samplecodes(self):
395 396 397 398 399
        comments = """
        placeholder
        Examples:
            .. code-block:: python

400
                print(1/0)
401

402
            .. code-block:: python
403

404 405 406 407
                print(1+1)
        """
        funcname = 'one_plus_one'
        sample_code_filenames = sampcd_extract_to_file(comments, funcname)
408 409 410 411 412 413 414 415 416 417 418 419 420
        self.assertCountEqual(
            [
                os.path.join(
                    sampcd_processor.SAMPLECODE_TEMPDIR,
                    funcname + '_example_1.py',
                ),
                os.path.join(
                    sampcd_processor.SAMPLECODE_TEMPDIR,
                    funcname + '_example_2.py',
                ),
            ],
            sample_code_filenames,
        )
421

422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
    def test_2_samplecodes_has_skipped(self):
        comments = """
        placeholder
        Examples:
            .. code-block:: python

                # required: skiptest
                print(1/0)

            .. code-block:: python

                print(1+1)

            .. code-block:: python

                # required: gpu
                print(1//1)

            .. code-block:: python

                # required: xpu
                print(1//1)

            .. code-block:: python

                # required: distributed
                print(1//1)

            .. code-block:: python

                # required: gpu
                print(1//1)
        """
        funcname = 'one_plus_one'
        clear_summary_info()
        clear_capacity()
        get_test_capacity()

        sample_code_filenames = sampcd_extract_to_file(comments, funcname)
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
        self.assertCountEqual(
            [
                os.path.join(
                    sampcd_processor.SAMPLECODE_TEMPDIR,
                    funcname + '_example_2.py',
                )
            ],
            sample_code_filenames,
        )
        self.assertCountEqual(
            sampcd_processor.SUMMARY_INFO['skiptest'], [funcname + '-1']
        )
        self.assertCountEqual(
            sampcd_processor.SUMMARY_INFO['gpu'],
            [funcname + '-3', funcname + '-6'],
        )
        self.assertCountEqual(
            sampcd_processor.SUMMARY_INFO['xpu'], [funcname + '-4']
        )
        self.assertCountEqual(
            sampcd_processor.SUMMARY_INFO['distributed'], [funcname + '-5']
        )
483

484 485 486 487 488 489 490 491 492 493 494 495 496 497
    def test_skip_ps_wrapped_code(self):
        comments = """
        placeholder
        Examples:
            .. code-block:: python

                >>> print(1 + 1)
                2

        """
        funcname = 'one_plus_one'
        sample_code_filenames = sampcd_extract_to_file(comments, funcname)
        self.assertCountEqual([], sample_code_filenames)

498 499 500 501

class Test_get_api_md5(unittest.TestCase):
    def setUp(self):
        self.api_pr_spec_filename = os.path.abspath(
502 503
            os.path.join(os.getcwd(), "..", 'paddle/fluid/API_PR.spec')
        )
504
        with open(self.api_pr_spec_filename, 'w') as f:
505 506 507 508 509 510 511 512 513 514 515
            f.write(
                "\n".join(
                    [
                        """paddle.one_plus_one (ArgSpec(args=[], varargs=None, keywords=None, defaults=(,)), ('document', 'ff0f188c95030158cc6398d2a6c55one'))""",
                        """paddle.two_plus_two (ArgSpec(args=[], varargs=None, keywords=None, defaults=(,)), ('document', 'ff0f188c95030158cc6398d2a6c55two'))""",
                        """paddle.three_plus_three (ArgSpec(args=[], varargs=None, keywords=None, defaults=(,)), ('document', 'ff0f188c95030158cc6398d2a6cthree'))""",
                        """paddle.four_plus_four (paddle.four_plus_four, ('document', 'ff0f188c95030158cc6398d2a6c5four'))""",
                        """paddle.five_plus_five (ArgSpec(), ('document', 'ff0f188c95030158cc6398d2a6c5five'))""",
                    ]
                )
            )
516 517 518 519 520 521

    def tearDown(self):
        os.remove(self.api_pr_spec_filename)

    def test_get_api_md5(self):
        res = get_api_md5('paddle/fluid/API_PR.spec')
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
        self.assertEqual(
            "ff0f188c95030158cc6398d2a6c55one", res['paddle.one_plus_one']
        )
        self.assertEqual(
            "ff0f188c95030158cc6398d2a6c55two", res['paddle.two_plus_two']
        )
        self.assertEqual(
            "ff0f188c95030158cc6398d2a6cthree", res['paddle.three_plus_three']
        )
        self.assertEqual(
            "ff0f188c95030158cc6398d2a6c5four", res['paddle.four_plus_four']
        )
        self.assertEqual(
            "ff0f188c95030158cc6398d2a6c5five", res['paddle.five_plus_five']
        )
537 538 539 540 541


class Test_get_incrementapi(unittest.TestCase):
    def setUp(self):
        self.api_pr_spec_filename = os.path.abspath(
542 543
            os.path.join(os.getcwd(), "..", 'paddle/fluid/API_PR.spec')
        )
544
        with open(self.api_pr_spec_filename, 'w') as f:
545 546 547 548 549 550 551 552 553 554
            f.write(
                "\n".join(
                    [
                        """paddle.one_plus_one (ArgSpec(args=[], varargs=None, keywords=None, defaults=(,)), ('document', 'ff0f188c95030158cc6398d2a6c55one'))""",
                        """paddle.two_plus_two (ArgSpec(args=[], varargs=None, keywords=None, defaults=(,)), ('document', 'ff0f188c95030158cc6398d2a6c55two'))""",
                        """paddle.three_plus_three (ArgSpec(args=[], varargs=None, keywords=None, defaults=(,)), ('document', 'ff0f188c95030158cc6398d2a6cthree'))""",
                        """paddle.four_plus_four (paddle.four_plus_four, ('document', 'ff0f188c95030158cc6398d2a6c5four'))""",
                    ]
                )
            )
555
        self.api_dev_spec_filename = os.path.abspath(
556 557
            os.path.join(os.getcwd(), "..", 'paddle/fluid/API_DEV.spec')
        )
558
        with open(self.api_dev_spec_filename, 'w') as f:
559 560 561 562 563 564 565
            f.write(
                "\n".join(
                    [
                        """paddle.one_plus_one (ArgSpec(args=[], varargs=None, keywords=None, defaults=(,)), ('document', 'ff0f188c95030158cc6398d2a6c55one'))""",
                    ]
                )
            )
566
        self.api_diff_spec_filename = os.path.abspath(
567 568
            os.path.join(os.getcwd(), "dev_pr_diff_api.spec")
        )
569 570 571 572 573 574 575 576 577 578

    def tearDown(self):
        os.remove(self.api_pr_spec_filename)
        os.remove(self.api_dev_spec_filename)
        os.remove(self.api_diff_spec_filename)

    def test_it(self):
        get_incrementapi()
        with open(self.api_diff_spec_filename, 'r') as f:
            lines = f.readlines()
579 580 581 582 583 584 585 586
            self.assertCountEqual(
                [
                    "paddle.two_plus_two\n",
                    "paddle.three_plus_three\n",
                    "paddle.four_plus_four\n",
                ],
                lines,
            )
587 588 589 590 591 592 593


# https://github.com/PaddlePaddle/Paddle/blob/develop/python/paddle/fluid/layers/ops.py
# why? unabled to use the ast module. emmmmm

if __name__ == '__main__':
    unittest.main()