Test Failed
Pull Request — master (#74)
by
unknown
02:02
created

build.setup.CITest.run()   A

Complexity

Conditions 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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