Passed
Pull Request — master (#69)
by Gleyberson
02:05
created

build.setup.TestCommand.get_args()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nop 1
1
"""Setup script.
2
3
Run "python3 setup.py --help-commands" to list all available commands and their
4
descriptions.
5
"""
6
import json
7
import os
8
import shutil
9
import sys
10
from abc import abstractmethod
11
from pathlib import Path
12
from subprocess import CalledProcessError, call, check_call
13
14
from setuptools import Command, setup
15
from setuptools.command.develop import develop
16
# from setuptools.command.egg_info import egg_info
17
from setuptools.command.install import install
18
19
if 'bdist_wheel' in sys.argv:
20
    raise RuntimeError("This setup.py does not support wheels")
21
22
# Paths setup with virtualenv detection
23
BASE_ENV = Path(os.environ.get('VIRTUAL_ENV', '/'))
24
# Kytos var folder
25
VAR_PATH = BASE_ENV / 'var' / 'lib' / 'kytos'
26
# Path for enabled NApps
27
ENABLED_PATH = VAR_PATH / 'napps'
28
# Path to install NApps
29
INSTALLED_PATH = VAR_PATH / 'napps' / '.installed'
30
CURRENT_DIR = Path('.').resolve()
31
32
# NApps enabled by default
33
# CORE_NAPPS = ['of_core']
34
35
36
class SimpleCommand(Command):
37
    """Make Command implementation simpler."""
38
39
    user_options = []
40
41
    @abstractmethod
42
    def run(self):
43
        """Run when command is invoked.
44
45
        Use *call* instead of *check_call* to ignore failures.
46
        """
47
    def initialize_options(self):
48
        """Set default values for options."""
49
50
    def finalize_options(self):
51
        """Post-process options."""
52
53
54
# pylint: disable=attribute-defined-outside-init, abstract-method
55
class TestCommand(Command):
56
    """Test tags decorators."""
57
58
    user_options = [
59
        ('size=', None, 'Specify the size of tests to be executed.'),
60
        ('type=', None, 'Specify the type of tests to be executed.'),
61
    ]
62
63
    sizes = ('small', 'medium', 'large', 'all')
64
    types = ('unit', 'integration', 'e2e')
65
66
    def get_args(self):
67
        """Return args to be used in test command."""
68
        return '--size %s --type %s' % (self.size, self.type)
69
70
    def initialize_options(self):
71
        """Set default size and type args."""
72
        self.size = 'all'
73
        self.type = 'unit'
74
75
    def finalize_options(self):
76
        """Post-process."""
77
        try:
78
            assert self.size in self.sizes, ('ERROR: Invalid size:'
79
                                             f':{self.size}')
80
            assert self.type in self.types, ('ERROR: Invalid type:'
81
                                             f':{self.type}')
82
        except AssertionError as exc:
83
            print(exc)
84
            sys.exit(-1)
85
86
87
class Cleaner(SimpleCommand):
88
    """Custom clean command to tidy up the project root."""
89
90
    description = 'clean build, dist, pyc and egg from package and docs'
91
92
    def run(self):
93
        """Clean build, dist, pyc and egg from package and docs."""
94
        call('rm -vrf ./build ./dist ./*.egg-info', shell=True)
95
        call('find . -name __pycache__ -type d | xargs rm -rf', shell=True)
96
        call('make -C docs/ clean', shell=True)
97
98
99
class Test(TestCommand):
100
    """Run all tests."""
101
102
    description = 'run tests and display results'
103
104
    def get_args(self):
105
        """Return args to be used in test command."""
106
        markers = self.size
107
        if markers == "small":
108
            sizes = ['medium', 'large']
109
            markers = "".join(['not %s and ' % size for size in sizes])[:-5]
110
        size_args = "" if self.size == "all" else "-m '%s'" % markers
111
        return '--addopts="tests/%s %s"' % (self.type, size_args)
112
113
    def run(self):
114
        """Run tests."""
115
        cmd = 'python setup.py test_fw %s' % self.get_args()
116
        try:
117
            check_call(cmd, shell=True)
118
        except CalledProcessError as exc:
119
            print(exc)
120
121
122
class TestCoverage(Test):
123
    """Display test coverage."""
124
125
    description = 'run tests and display code coverage'
126
127
    def run(self):
128
        """Run tests quietly and display coverage report."""
129
        cmd = 'coverage3 run setup.py test_fw %s' % self.get_args()
130
        cmd += '&& coverage3 report'
131
        try:
132
            check_call(cmd, shell=True)
133
        except CalledProcessError as exc:
134
            print(exc)
135
136
137
class Linter(SimpleCommand):
138
    """Code linters."""
139
140
    description = 'lint Python source code'
141
142
    def run(self):
143
        """Run yala."""
144
        print('Yala is running. It may take several seconds...')
145
        check_call('yala *.py v0x?? tests', shell=True)
146
147
148
class CITest(TestCommand):
149
    """Run all CI tests."""
150
151
    description = 'run all CI tests: unit and doc tests, linter'
152
153
    def run(self):
154
        """Run unit tests with coverage, doc tests and linter."""
155
        coverage_cmd = 'python3.6 setup.py coverage %s' % self.get_args()
156
        lint_cmd = 'python3.6 setup.py lint'
157
        cmd = '%s && %s' % (coverage_cmd, lint_cmd)
158
        check_call(cmd, shell=True)
159
160
161
# class KytosInstall:
162
#     """Common code for all install types."""
163
#
164
#     @staticmethod
165
#     def enable_core_napps():
166
#         """Enable a NAPP by creating a symlink."""
167
#         (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
168
#         for napp in CORE_NAPPS:
169
#             napp_path = Path('kytos', napp)
170
#             src = ENABLED_PATH / napp_path
171
#             dst = INSTALLED_PATH / napp_path
172
#             src.symlink_to(dst)
173
174
175
class InstallMode(install):
176
    """Create files in var/lib/kytos."""
177
178
    description = 'To install NApps, use kytos-utils. Devs, see "develop".'
179
180
    def run(self):
181
        """Create of_core as default napps enabled."""
182
        print(self.description)
183
184
185
# class EggInfo(egg_info):
186
#     """Prepare files to be packed."""
187
#
188
#     def run(self):
189
#         """Build css."""
190
#         self._install_deps_wheels()
191
#         super().run()
192
#
193
#     @staticmethod
194
#     def _install_deps_wheels():
195
#         """Python wheels are much faster (no compiling)."""
196
#         print('Installing dependencies...')
197
#         check_call([sys.executable, '-m', 'pip', 'install', '-r',
198
#                     'requirements/run.in'])
199
200
201
class DevelopMode(develop):
202
    """Recommended setup for kytos-napps developers.
203
204
    Instead of copying the files to the expected directories, a symlink is
205
    created on the system aiming the current source code.
206
    """
207
208
    description = 'install NApps in development mode'
209
210
    def run(self):
211
        """Install the package in a developer mode."""
212
        super().run()
213
        if self.uninstall:
214
            shutil.rmtree(str(ENABLED_PATH), ignore_errors=True)
215
        else:
216
            self._create_folder_symlinks()
217
            # self._create_file_symlinks()
218
            # KytosInstall.enable_core_napps()
219
220
    @staticmethod
221
    def _create_folder_symlinks():
222
        """Symlink to all Kytos NApps folders.
223
224
        ./napps/kytos/napp_name will generate a link in
225
        var/lib/kytos/napps/.installed/kytos/napp_name.
226
        """
227
        links = INSTALLED_PATH / 'kytos'
228
        links.mkdir(parents=True, exist_ok=True)
229
        code = CURRENT_DIR
230
        src = links / 'of_core'
231
        symlink_if_different(src, code)
232
233
        (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
234
        dst = ENABLED_PATH / Path('kytos', 'of_core')
235
        symlink_if_different(dst, src)
236
237
    # @staticmethod
238
    # def _create_file_symlinks():
239
    #     """Symlink to required files."""
240
    #     src = ENABLED_PATH / '__init__.py'
241
    #     dst = CURRENT_DIR / 'napps' / '__init__.py'
242
    #     symlink_if_different(src, dst)
243
244
245
def symlink_if_different(path, target):
246
    """Force symlink creation if it points anywhere else."""
247
    # print(f"symlinking {path} to target: {target}...", end=" ")
248
    if not path.exists():
249
        # print(f"path doesn't exist. linking...")
250
        path.symlink_to(target)
251
    elif not path.samefile(target):
252
        # print(f"path exists, but is different. removing and linking...")
253
        # Exists but points to a different file, so let's replace it
254
        path.unlink()
255
        path.symlink_to(target)
256
257
258
def read_version_from_json():
259
    """Read the NApp version from NApp kytos.json file."""
260
    file = Path('kytos.json')
261
    metadata = json.loads(file.read_text())
262
    return metadata['version']
263
264
265
setup(name='kytos_of_core',
266
      version=read_version_from_json(),
267
      description='Core NApps developed by Kytos Team',
268
      url='http://github.com/kytos/of_core',
269
      author='Kytos Team',
270
      author_email='[email protected]',
271
      license='MIT',
272
      setup_requires=['pytest-runner'],
273
      tests_require=['pytest'],
274
      extras_require={
275
          'dev': [
276
              'coverage',
277
              'pip-tools',
278
              'yala',
279
              'tox',
280
          ],
281
      },
282
      cmdclass={
283
          'clean': Cleaner,
284
          'ci': CITest,
285
          'coverage': TestCoverage,
286
          'develop': DevelopMode,
287
          'install': InstallMode,
288
          'lint': Linter,
289
          'test': Test,
290
          # 'egg_info': EggInfo,
291
      },
292
      zip_safe=False,
293
      classifiers=[
294
          'License :: OSI Approved :: MIT License',
295
          'Operating System :: POSIX :: Linux',
296
          'Programming Language :: Python :: 3.6',
297
          'Topic :: System :: Networking',
298
      ])
299