Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
ajbalogh committed Dec 18, 2020
1 parent d359113 commit 78d6572
Show file tree
Hide file tree
Showing 14 changed files with 538 additions and 297 deletions.
2 changes: 2 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[flake8]
ignore = F403, F405, E501, E303, W293, W291, W391
1 change: 1 addition & 0 deletions .github/workflows/generate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ jobs:
python -m pip install --upgrade wheel
python -m pip install --upgrade twine
python -m pip install --upgrade requests
python -m pip install --upgrade flask
- name: Generate python sdist and wheel distributions
run: |
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ dist
.pytest_cache
snappi.egg-info
docs/openapi.yaml
*.yaml
snappi/*
!snappi/snappicommon.py
!snappi/snappigenerator.py
Expand Down
2 changes: 1 addition & 1 deletion docs/GENERATORRULES.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ The generator should do the following:

## ` choice property`
Given a property named choice...
```
```yaml
components:
schemas:
Flow.Header:
Expand Down
2 changes: 0 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,10 @@
import os
from setuptools import setup, find_packages
from snappi.snappigenerator import SnappiGenerator
import pytest

pkg_name = 'snappi'

SnappiGenerator()
pytest.main(['-s', './%s/tests' % pkg_name])

base_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(base_dir, 'README.md')) as fid:
Expand Down
103 changes: 87 additions & 16 deletions snappi/snappicommon.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,33 @@
import importlib
import json
import yaml
import requests
import sys

if sys.version_info[0] == 3:
unicode = str

class SnappiRestTransport(object):
def __init__(self):
self.base_url = 'http://127.0.0.1:80'
self._session = requests.Session()

def send_recv(self, method, relative_url, payload=None):
url = '%s%s' % (self.base_url, relative_url)
data = None
if payload is not None:
data = payload.serialize()
response = self._session.request(method=method,
url=url,
data=data,
verify=False,
allow_redirects=True)
if response.ok is not True:
raise Exception(response.status_code)
elif response.headers['content-type'] == 'application/json':
return yaml.safe_load(response.text)
else:
return None


class SnappiObject(object):
Expand All @@ -11,8 +38,20 @@ class SnappiObject(object):
def __init__(self):
self._properties = {}

def encode(self, encoding=JSON):
"""Helper method for serialization
def serialize(self, encoding=JSON):
"""Serialize the current snappi object according to a specified encoding.
Args
----
- encoding (str[json, yaml, dict]): The object will be recursively
encoded according to the specified encoding.
The supported encodings are json, yaml and python dict.
Returns
-------
- obj(Union[str, dict]): A str or dict object depending on the specified
encoding. The json and yaml encodings will return a str object and
the dict encoding will return a python dict object.
"""
if encoding == SnappiObject.JSON:
return json.dumps(self._encode(), indent=2)
Expand All @@ -34,13 +73,24 @@ def _encode(self):
output[key] = value
return output

def decode(self, obj):
"""Deserialize a json object depth first into the snappi object hierarchy
Returns: obj(snappicommon.SnappiObject)
def deserialize(self, encoded_snappi_object):
"""Deserialize a python object into the current snappi object.
If the input `encoded_snappi_object` does not match the current
snappi object an exception will be raised.
Args
----
- encoded_snappi_object (Union[str, dict]): The object to deserialize.
The supported encodings of obj are json, yaml and python dict.
Returns
-------
- obj(snappicommon.SnappiObject): A snappi object
"""
if isinstance(obj, str):
obj = yaml.safe_load(obj)
self._decode(obj)
if isinstance(encoded_snappi_object, (str, unicode)):
encoded_snappi_object = yaml.safe_load(encoded_snappi_object)
self._decode(encoded_snappi_object)
return self

def _decode(self, obj):
Expand All @@ -50,7 +100,8 @@ def _decode(self, obj):
if isinstance(property_value, dict):
child = self._get_child_class(property_name)
property_value = child[1]()._decode(property_value)
elif isinstance(property_value, list):
elif isinstance(property_value,
list) and property_name in self._TYPES:
child = self._get_child_class(property_name, True)
snappi_list = child[0]()
for item in property_value:
Expand All @@ -76,6 +127,9 @@ def _get_child_class(self, property_name, is_property_list=False):
object_class = getattr(module, child_class_name[0:-4])
return (list_class, object_class)

def __str__(self):
return self.serialize(self.YAML)


class SnappiList(object):
"""Container class for SnappiObject
Expand All @@ -97,23 +151,29 @@ def __init__(self):

def __getattr__(self, name):
if len(self._items) == 0:
raise Exception('no items')
elif hasattr(self._items[0], name):
return getattr(self._items[0], name, None)
raise IndexError('List is empty')
elif hasattr(self._items[self._index], name):
return getattr(self._items[self._index], name, None)
else:
raise AttributeError('%s is not a valid attribute')
raise AttributeError('%s.%s is not a valid attribute' %
(type(self).__name__, name))

def __len__(self):
return len(self._items)

def __getitem__(self, key):
found = None
if isinstance(key, int):
return self._items[key]
found = self._items[key]
elif isinstance(key, str):
for item in self._items:
if item.name == key:
return item
found = item
if found is None:
raise IndexError()
if 'choice' in found._properties:
return found._properties[found._properties['choice']]
return found

def __iter__(self):
self._index = -1
Expand All @@ -129,8 +189,19 @@ def __next__(self):
self._index += 1
return self[self._index]

def keys(self):
def _keys(self):
return [item.name for item in self._items]

def _add(self, item):
self._items.append(item)
self._index = len(self._items) - 1

def clear(self):
self._items.clear()
self._index = -1

def _encode(self):
return [item._encode() for item in self._items]

def __str__(self):
return yaml.safe_dump(self._encode())
Loading

0 comments on commit 78d6572

Please sign in to comment.