Test Failed
Pull Request — master (#23)
by Vinicius
01:55
created

build.setup.SimpleCommand.initialize_options()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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