[ONOS-7039] [ONOS-7044] Fix PEP8 Warnings in TestON
Change-Id: Ied79ff9caff5487a6df50466307f757468d7ca3a
diff --git a/TestON/core/Thread.py b/TestON/core/Thread.py
index 4c040a6..9c655a5 100644
--- a/TestON/core/Thread.py
+++ b/TestON/core/Thread.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
-'''
-Copyright 2015 Open Networking Foundation (ONF)
+"""
+Copyright 2015 Open Networking Foundation ( ONF )
Please refer questions to either the onos test mailing list at <onos-test@onosproject.org>,
the System Testing Plans and Results wiki page at <https://wiki.onosproject.org/x/voMg>,
@@ -10,7 +10,7 @@
TestON is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -19,10 +19,12 @@
You should have received a copy of the GNU General Public License
along with TestON. If not, see <http://www.gnu.org/licenses/>.
-'''
+"""
import threading
+
class Thread( threading.Thread ):
+
def __init__( self, target=None, threadID=None, name="", args=(),
kwargs={} ):
super( Thread, self ).__init__()
diff --git a/TestON/core/ast.py b/TestON/core/ast.py
index fd5dfdb..33464da 100644
--- a/TestON/core/ast.py
+++ b/TestON/core/ast.py
@@ -19,7 +19,7 @@
Additionally various helper functions are provided that make working with
the trees simpler. The main intention of the helper functions and this
module in general is to provide an easy to use interface for libraries
- that work tightly with the python syntax (template engines for example).
+ that work tightly with the python syntax ( template engines for example ).
:copyright: Copyright 2008 by Armin Ronacher.
@@ -29,58 +29,59 @@
from _ast import __version__
-def parse(source, filename='<unknown>', mode='exec'):
+def parse( source, filename='<unknown>', mode='exec' ):
"""
Parse the source into an AST node.
- Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
+ Equivalent to compile( source, filename, mode, PyCF_ONLY_AST ).
"""
- return compile(source, filename, mode, PyCF_ONLY_AST)
+ return compile( source, filename, mode, PyCF_ONLY_AST )
-def literal_eval(node_or_string):
+def literal_eval( node_or_string ):
"""
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.
"""
- _safe_names = {'None': None, 'True': True, 'False': False}
- if isinstance(node_or_string, basestring):
- node_or_string = parse(node_or_string, mode='eval')
- if isinstance(node_or_string, Expression):
+ _safe_names = { 'None': None, 'True': True, 'False': False }
+ if isinstance( node_or_string, basestring ):
+ node_or_string = parse( node_or_string, mode='eval' )
+ if isinstance( node_or_string, Expression ):
node_or_string = node_or_string.body
- def _convert(node):
- if isinstance(node, Str):
+
+ def _convert( node ):
+ if isinstance( node, Str ):
return node.s
- elif isinstance(node, Num):
+ elif isinstance( node, Num ):
return node.n
- elif isinstance(node, Tuple):
- return tuple(map(_convert, node.elts))
- elif isinstance(node, List):
- return list(map(_convert, node.elts))
- elif isinstance(node, Dict):
- return dict((_convert(k), _convert(v)) for k, v
- in zip(node.keys, node.values))
- elif isinstance(node, Name):
+ elif isinstance( node, Tuple ):
+ return tuple( map( _convert, node.elts ) )
+ elif isinstance( node, List ):
+ return list( map( _convert, node.elts ) )
+ elif isinstance( node, Dict ):
+ return dict( ( _convert( k ), _convert( v ) ) for k, v
+ in zip( node.keys, node.values ) )
+ elif isinstance( node, Name ):
if node.id in _safe_names:
- return _safe_names[node.id]
- elif isinstance(node, BinOp) and \
- isinstance(node.op, (Add, Sub)) and \
- isinstance(node.right, Num) and \
- isinstance(node.right.n, complex) and \
- isinstance(node.left, Num) and \
- isinstance(node.left.n, (int, long, float)):
+ return _safe_names[ node.id ]
+ elif isinstance( node, BinOp ) and \
+ isinstance( node.op, ( Add, Sub ) ) and \
+ isinstance( node.right, Num ) and \
+ isinstance( node.right.n, complex ) and \
+ isinstance( node.left, Num ) and \
+ isinstance( node.left.n, ( int, long, float ) ):
left = node.left.n
right = node.right.n
- if isinstance(node.op, Add):
+ if isinstance( node.op, Add ):
return left + right
else:
return left - right
- raise ValueError('malformed string')
- return _convert(node_or_string)
+ raise ValueError( 'malformed string' )
+ return _convert( node_or_string )
-def dump(node, annotate_fields=True, include_attributes=False):
+def dump( node, annotate_fields=True, include_attributes=False ):
"""
Return a formatted dump of the tree in *node*. This is mainly useful for
debugging purposes. The returned string will show the names and the values
@@ -89,40 +90,40 @@
numbers and column offsets are not dumped by default. If this is wanted,
*include_attributes* can be set to True.
"""
- def _format(node):
- if isinstance(node, AST):
- fields = [(a, _format(b)) for a, b in iter_fields(node)]
- rv = '%s(%s' % (node.__class__.__name__, ', '.join(
- ('%s=%s' % field for field in fields)
+ def _format( node ):
+ if isinstance( node, AST ):
+ fields = [ ( a, _format( b ) ) for a, b in iter_fields( node ) ]
+ rv = '%s(%s' % ( node.__class__.__name__, ', '.join(
+ ( '%s=%s' % field for field in fields )
if annotate_fields else
- (b for a, b in fields)
- ))
+ ( b for a, b in fields )
+ ) )
if include_attributes and node._attributes:
rv += fields and ', ' or ' '
- rv += ', '.join('%s=%s' % (a, _format(getattr(node, a)))
- for a in node._attributes)
+ rv += ', '.join( '%s=%s' % ( a, _format( getattr( node, a ) ) )
+ for a in node._attributes )
return rv + ')'
- elif isinstance(node, list):
- return '[%s]' % ', '.join(_format(x) for x in node)
- return repr(node)
- if not isinstance(node, AST):
- raise TypeError('expected AST, got %r' % node.__class__.__name__)
- return _format(node)
+ elif isinstance( node, list ):
+ return '[%s]' % ', '.join( _format( x ) for x in node )
+ return repr( node )
+ if not isinstance( node, AST ):
+ raise TypeError( 'expected AST, got %r' % node.__class__.__name__ )
+ return _format( node )
-def copy_location(new_node, old_node):
+def copy_location( new_node, old_node ):
"""
- Copy source location (`lineno` and `col_offset` attributes) from
+ Copy source location ( `lineno` and `col_offset` attributes ) from
*old_node* to *new_node* if possible, and return *new_node*.
"""
for attr in 'lineno', 'col_offset':
if attr in old_node._attributes and attr in new_node._attributes \
- and hasattr(old_node, attr):
- setattr(new_node, attr, getattr(old_node, attr))
+ and hasattr( old_node, attr ):
+ setattr( new_node, attr, getattr( old_node, attr ) )
return new_node
-def fix_missing_locations(node):
+def fix_missing_locations( node ):
"""
When you compile a node tree with compile(), the compiler expects lineno and
col_offset attributes for every node that supports them. This is rather
@@ -130,91 +131,92 @@
recursively where not already set, by setting them to the values of the
parent node. It works recursively starting at *node*.
"""
- def _fix(node, lineno, col_offset):
+ def _fix( node, lineno, col_offset ):
if 'lineno' in node._attributes:
- if not hasattr(node, 'lineno'):
+ if not hasattr( node, 'lineno' ):
node.lineno = lineno
else:
lineno = node.lineno
if 'col_offset' in node._attributes:
- if not hasattr(node, 'col_offset'):
+ if not hasattr( node, 'col_offset' ):
node.col_offset = col_offset
else:
col_offset = node.col_offset
- for child in iter_child_nodes(node):
- _fix(child, lineno, col_offset)
- _fix(node, 1, 0)
+ for child in iter_child_nodes( node ):
+ _fix( child, lineno, col_offset )
+ _fix( node, 1, 0 )
return node
-def increment_lineno(node, n=1):
+def increment_lineno( node, n=1 ):
"""
Increment the line number of each node in the tree starting at *node* by *n*.
This is useful to "move code" to a different location in a file.
"""
- for child in walk(node):
+ for child in walk( node ):
if 'lineno' in child._attributes:
- child.lineno = getattr(child, 'lineno', 0) + n
+ child.lineno = getattr( child, 'lineno', 0 ) + n
return node
-def iter_fields(node):
+def iter_fields( node ):
"""
- Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
+ Yield a tuple of ``( fieldname, value )`` for each field in ``node._fields``
that is present on *node*.
"""
for field in node._fields:
try:
- yield field, getattr(node, field)
+ yield field, getattr( node, field )
except AttributeError:
pass
-def iter_child_nodes(node):
+def iter_child_nodes( node ):
"""
Yield all direct child nodes of *node*, that is, all fields that are nodes
and all items of fields that are lists of nodes.
"""
- for name, field in iter_fields(node):
- if isinstance(field, AST):
+ for name, field in iter_fields( node ):
+ if isinstance( field, AST ):
yield field
- elif isinstance(field, list):
+ elif isinstance( field, list ):
for item in field:
- if isinstance(item, AST):
+ if isinstance( item, AST ):
yield item
-def get_docstring(node, clean=True):
+def get_docstring( node, clean=True ):
"""
Return the docstring for the given node or None if no docstring can
be found. If the node provided does not have docstrings a TypeError
will be raised.
"""
- if not isinstance(node, (FunctionDef, ClassDef, Module)):
- raise TypeError("%r can't have docstrings" % node.__class__.__name__)
- if node.body and isinstance(node.body[0], Expr) and \
- isinstance(node.body[0].value, Str):
+ if not isinstance( node, ( FunctionDef, ClassDef, Module ) ):
+ raise TypeError( "%r can't have docstrings" % node.__class__.__name__ )
+ if node.body and isinstance( node.body[ 0 ], Expr ) and \
+ isinstance( node.body[ 0 ].value, Str ):
if clean:
import inspect
- return inspect.cleandoc(node.body[0].value.s)
- return node.body[0].value.s
+ return inspect.cleandoc( node.body[ 0 ].value.s )
+ return node.body[ 0 ].value.s
-def walk(node):
+def walk( node ):
"""
Recursively yield all descendant nodes in the tree starting at *node*
- (including *node* itself), in no specified order. This is useful if you
+ ( including *node* itself ), in no specified order. This is useful if you
only want to modify nodes in place and don't care about the context.
"""
from collections import deque
- todo = deque([node])
+ todo = deque( [ node ] )
while todo:
node = todo.popleft()
- todo.extend(iter_child_nodes(node))
+ todo.extend( iter_child_nodes( node ) )
yield node
-class NodeVisitor(object):
+class NodeVisitor( object ):
+
"""
A node visitor base class that walks the abstract syntax tree and calls a
visitor function for every node found. This function may return a value
@@ -227,31 +229,31 @@
class name of the node. So a `TryFinally` node visit function would
be `visit_TryFinally`. This behavior can be changed by overriding
the `visit` method. If no visitor function exists for a node
- (return value `None`) the `generic_visit` visitor is used instead.
+ ( return value `None` ) the `generic_visit` visitor is used instead.
Don't use the `NodeVisitor` if you want to apply changes to nodes during
- traversing. For this a special visitor exists (`NodeTransformer`) that
+ traversing. For this a special visitor exists ( `NodeTransformer` ) that
allows modifications.
"""
-
- def visit(self, node):
- """Visit a node."""
+ def visit( self, node ):
+ "Visit a node."
method = 'visit_' + node.__class__.__name__
- visitor = getattr(self, method, self.generic_visit)
- return visitor(node)
+ visitor = getattr( self, method, self.generic_visit )
+ return visitor( node )
- def generic_visit(self, node):
- """Called if no explicit visitor function exists for a node."""
- for field, value in iter_fields(node):
- if isinstance(value, list):
+ def generic_visit( self, node ):
+ "Called if no explicit visitor function exists for a node."
+ for field, value in iter_fields( node ):
+ if isinstance( value, list ):
for item in value:
- if isinstance(item, AST):
- self.visit(item)
- elif isinstance(value, AST):
- self.visit(value)
+ if isinstance( item, AST ):
+ self.visit( item )
+ elif isinstance( value, AST ):
+ self.visit( value )
-class NodeTransformer(NodeVisitor):
+class NodeTransformer( NodeVisitor ):
+
"""
A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
allows modification of nodes.
@@ -263,49 +265,48 @@
original node in which case no replacement takes place.
Here is an example transformer that rewrites all occurrences of name lookups
- (``foo``) to ``data['foo']``::
+ ( ``foo`` ) to ``data[ 'foo' ]``::
- class RewriteName(NodeTransformer):
+ class RewriteName( NodeTransformer ):
- def visit_Name(self, node):
- return copy_location(Subscript(
- value=Name(id='data', ctx=Load()),
- slice=Index(value=Str(s=node.id)),
+ def visit_Name( self, node ):
+ return copy_location( Subscript(
+ value=Name( id='data', ctx=Load() ),
+ slice=Index( value=Str( s=node.id ) ),
ctx=node.ctx
- ), node)
+ ), node )
Keep in mind that if the node you're operating on has child nodes you must
either transform the child nodes yourself or call the :meth:`generic_visit`
method for the node first.
- For nodes that were part of a collection of statements (that applies to all
- statement nodes), the visitor may also return a list of nodes rather than
+ For nodes that were part of a collection of statements ( that applies to all
+ statement nodes ), the visitor may also return a list of nodes rather than
just a single node.
Usually you use the transformer like this::
- node = YourTransformer().visit(node)
+ node = YourTransformer().visit( node )
"""
-
- def generic_visit(self, node):
- for field, old_value in iter_fields(node):
- old_value = getattr(node, field, None)
- if isinstance(old_value, list):
+ def generic_visit( self, node ):
+ for field, old_value in iter_fields( node ):
+ old_value = getattr( node, field, None )
+ if isinstance( old_value, list ):
new_values = []
for value in old_value:
- if isinstance(value, AST):
- value = self.visit(value)
+ if isinstance( value, AST ):
+ value = self.visit( value )
if value is None:
continue
- elif not isinstance(value, AST):
- new_values.extend(value)
+ elif not isinstance( value, AST ):
+ new_values.extend( value )
continue
- new_values.append(value)
- old_value[:] = new_values
- elif isinstance(old_value, AST):
- new_node = self.visit(old_value)
+ new_values.append( value )
+ old_value[ : ] = new_values
+ elif isinstance( old_value, AST ):
+ new_node = self.visit( old_value )
if new_node is None:
- delattr(node, field)
+ delattr( node, field )
else:
- setattr(node, field, new_node)
+ setattr( node, field, new_node )
return node
diff --git a/TestON/core/graph.py b/TestON/core/graph.py
index b1cbdb2..b5bf9f6 100644
--- a/TestON/core/graph.py
+++ b/TestON/core/graph.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
-'''
-Copyright 2016 Open Networking Foundation (ONF)
+"""
+Copyright 2016 Open Networking Foundation ( ONF )
Please refer questions to either the onos test mailing list at <onos-test@onosproject.org>,
the System Testing Plans and Results wiki page at <https://wiki.onosproject.org/x/voMg>,
@@ -10,7 +10,7 @@
TestON is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -20,29 +20,28 @@
You should have received a copy of the GNU General Public License
along with TestON. If not, see <http://www.gnu.org/licenses/>.
-'''
-
-
+"""
import time
import random
+
class Graph:
+
"""
Graph class provides implementations of graph algorithms.
The functions currently supported include:
- Comparing two graphs with specified attributes for vertices and edges
- - Getting DFI (Depth First Index) and back edges during a DFS
+ - Getting DFI ( Depth First Index ) and back edges during a DFS
- Chain decomposition of a graph
- - Finding (non-)cut-edges and vertices
+ - Finding ( non- )cut-edges and vertices
"""
-
def __init__( self ):
# We use a dictionary to store all information about the graph
self.graphDict = {}
# Depth-first index of each vertex
self.DFI = {}
self.currentDFI = 0
- # Parent vertex (and edge to that vertex) of each vertex in depth-first search tree
+ # Parent vertex ( and edge to that vertex ) of each vertex in depth-first search tree
self.parentVertexInDFS = {}
self.parentEdgeInDFS = {}
# Back edges of the graph generated during DFS
@@ -60,7 +59,7 @@
vertex2: { 'edges': ..., 'name': ..., 'protocol': ... } }
Each vertex should at least have an 'edges' attribute which describes the
adjacency information. The value of 'edges' attribute is also represented by
- a dictionary, which maps each edge (identified by the neighbor vertex) to a
+ a dictionary, which maps each edge ( identified by the neighbor vertex ) to a
list of attributes.
An example of the edges dictionary:
'edges': { vertex2: { 'port': ..., 'type': ... },
@@ -69,7 +68,7 @@
self.graphDict = graphDict
return main.TRUE
- def compareGraphs( self, graphDictA, graphDictB, vertexAttributes=['edges'], edgeAttributes=['port'] ):
+ def compareGraphs( self, graphDictA, graphDictB, vertexAttributes=[ 'edges' ], edgeAttributes=[ 'port' ] ):
"""
Compare two graphs.
By default only the adjacency relationship, i.e. 'port' attribute in
@@ -103,7 +102,7 @@
# Compare two attributes
attributeValueA = graphDictA[ vertex ][ vertexAttribute ]
attributeValueB = graphDictB[ vertex ][ vertexAttribute ]
- # FIXME: the comparison may not work for (sub)attribute values that are of list type
+ # FIXME: the comparison may not work for ( sub )attribute values that are of list type
# For attributes except for 'edges', we just rely on '==' for comparison
if not vertexAttribute == 'edges':
if not attributeValueA == attributeValueB:
@@ -150,8 +149,8 @@
attributeValueA,
attributeValueB ) )
if not result:
- #main.log.debug( "Graph: graphDictA: {}".format( graphDictA ) )
- #main.log.debug( "Graph: graphDictB: {}".format( graphDictB ) )
+ # main.log.debug( "Graph: graphDictA: {}".format( graphDictA ) )
+ # main.log.debug( "Graph: graphDictB: {}".format( graphDictB ) )
pass
return result
except TypeError:
@@ -166,8 +165,8 @@
def getNonCutEdges( self ):
"""
- Get a list of non-cut-edges (non-bridges).
- The definition of a cut-edge (bridge) is: the deletion of a cut-edge will
+ Get a list of non-cut-edges ( non-bridges ).
+ The definition of a cut-edge ( bridge ) is: the deletion of a cut-edge will
increase the number of connected component of a graph.
The function is realized by impelementing Schmidt's algorithm based on
chain decomposition.
@@ -183,7 +182,7 @@
for chain in self.chains:
for edge in chain:
nonCutEdges.append( edge )
- #main.log.debug( 'Non-cut-edges: {}'.format( nonCutEdges ) )
+ # main.log.debug( 'Non-cut-edges: {}'.format( nonCutEdges ) )
return nonCutEdges
except Exception:
main.log.exception( "Graph: Uncaught exception" )
@@ -207,16 +206,16 @@
# chain, the chain is a cycle chain
if chain[ 0 ][ 0 ] == chain[ -1 ][ 1 ]:
cycleChains.append( chain )
- #main.log.debug( 'Cycle chains: {}'.format( cycleChains ) )
+ # main.log.debug( 'Cycle chains: {}'.format( cycleChains ) )
# Get a set of vertices which are the first vertices of a cycle chain (excluding the first
# cycle chain), and these vertices are a subset of all cut-vertices
subsetOfCutVertices = []
if len( cycleChains ) > 1:
for cycleChain in cycleChains[ 1: ]:
subsetOfCutVertices.append( cycleChain[ 0 ][ 0 ] )
- #main.log.debug( 'Subset of cut vertices: {}'.format( subsetOfCutVertices ) )
+ # main.log.debug( 'Subset of cut vertices: {}'.format( subsetOfCutVertices ) )
nonCutVertices = []
- assert nonCutEdges != None
+ assert nonCutEdges is not None
for vertex in self.graphDict.keys():
if vertex in subsetOfCutVertices:
continue
@@ -224,12 +223,12 @@
for neighbor in self.graphDict[ vertex ][ 'edges' ].keys():
edge = [ vertex, neighbor ]
backwardEdge = [ neighbor, vertex ]
- if not edge in nonCutEdges and not backwardEdge in nonCutEdges:
+ if edge not in nonCutEdges and backwardEdge not in nonCutEdges:
vertexIsNonCut = False
break
if vertexIsNonCut:
nonCutVertices.append( vertex )
- #main.log.debug( 'Non-cut-vertices: {}'.format( nonCutVertices ) )
+ # main.log.debug( 'Non-cut-vertices: {}'.format( nonCutVertices ) )
return nonCutVertices
except KeyError:
main.log.exception( "Graph: KeyError exception found" )
@@ -247,7 +246,7 @@
as generates the back edges
"""
try:
- assert self.graphDict != None and len( self.graphDict ) != 0
+ assert self.graphDict is not None and len( self.graphDict ) != 0
for vertex in self.graphDict.keys():
self.DFI[ vertex ] = -1
self.parentVertexInDFS[ vertex ] = ''
@@ -288,14 +287,14 @@
else:
key = self.DFI[ neighbor ]
if key in self.backEdges.keys():
- if not edge in self.backEdges[ key ] and\
- not backwardEdge in self.backEdges[ key ]:
+ if edge not in self.backEdges[ key ] and\
+ backwardEdge not in self.backEdges[ key ]:
self.backEdges[ key ].append( backwardEdge )
else:
tempKey = self.DFI[ vertex ]
if tempKey in self.backEdges.keys():
- if not edge in self.backEdges[ tempKey ] and\
- not backwardEdge in self.backEdges[ tempKey ]:
+ if edge not in self.backEdges[ tempKey ] and\
+ backwardEdge not in self.backEdges[ tempKey ]:
self.backEdges[ key ] = [ backwardEdge ]
else:
self.backEdges[ key ] = [ backwardEdge ]
@@ -311,8 +310,7 @@
"""
This function finds all the chains in chain-decomposition algorithm
"""
- keyList = self.backEdges.keys()
- keyList.sort()
+ keyList = sorted( self.backEdges.keys() )
vertexIsVisited = {}
self.chains = []
for vertex in self.graphDict.keys():
@@ -329,7 +327,7 @@
nextVertex = currentEdge[ 1 ]
vertexIsVisited[ currentVertex ] = True
chain.append( currentEdge )
- if nextVertex == sourceVertex or vertexIsVisited[ nextVertex ] == True:
+ if nextVertex == sourceVertex or vertexIsVisited[ nextVertex ]:
break
currentEdge = self.parentEdgeInDFS[ nextVertex ]
self.chains.append( chain )
diff --git a/TestON/core/logger.py b/TestON/core/logger.py
index ed9b0bd..559f84d 100644
--- a/TestON/core/logger.py
+++ b/TestON/core/logger.py
@@ -1,5 +1,5 @@
-#/usr/bin/env python
-'''
+# /usr/bin/env python
+"""
Created on 07-Jan-2013
Modified 2015 by ON.Lab
@@ -10,7 +10,7 @@
TestON is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -21,105 +21,107 @@
along with TestON. If not, see <http://www.gnu.org/licenses/>.
-'''
-
+"""
import logging
import datetime
import re
import os
+
+
class Logger:
- '''
+
+ """
Add continuous logs and reports of the test.
- @author: Raghav Kashyap(raghavkashyap@paxterrasolutions.com)
- '''
- def _printHeader(self,main) :
- '''
+ author:: Raghav Kashyap( raghavkashyap@paxterrasolutions.com )
+ """
+ def _printHeader( self, main ):
+ """
Log's header will be append to the Log file
- '''
- logmsg = "\n"+" " * 32+"+----------------+\n" +"-" * 30+" { Script And Files } "+"-" * 30+"\n" +" " * 32+"+----------------+\n";
+ """
+ logmsg = "\n" + " " * 32 + "+----------------+\n" + "-" * 30 + " { Script And Files } " + "-" * 30 + "\n" + " " * 32 + "+----------------+\n"
logmsg = logmsg + "\n\tScript Log File : " + main.LogFileName + ""
logmsg = logmsg + "\n\tReport Log File : " + main.ReportFileName + ""
for component in main.componentDictionary.keys():
- logmsg = logmsg + "\n\t"+component+" Session Log : " + main.logdir+"/"+component+".session" + ""
+ logmsg = logmsg + "\n\t" + component + " Session Log : " + main.logdir + "/" + component + ".session" + ""
- logmsg = logmsg + "\n\tTest Script :" + path + "Tests/" + main.TEST + ".py"+ ""
+ logmsg = logmsg + "\n\tTest Script :" + path + "Tests/" + main.TEST + ".py" + ""
logmsg = logmsg + "\n\tTest Params : " + path + "Tests/" + main.TEST + ".params" + ""
- logmsg = logmsg + "\n\tTopology : " + path + "Tests/" +main.TEST + ".topo" + ""
- logmsg = logmsg + "\n"+" " * 30+"+" +"-" * 18+"+" +"\n" +"-" * 27+" { Script Exec Params } "+"-" * 27 +"\n" +" " * 30 +"+"+"-" * 18 +"+\n";
- values = "\n\t" + str(main.params)
- values = re.sub(",", "\n\t", values)
- values = re.sub("{", "\n\t", values)
- values = re.sub("}", "\n\t", values)
+ logmsg = logmsg + "\n\tTopology : " + path + "Tests/" + main.TEST + ".topo" + ""
+ logmsg = logmsg + "\n" + " " * 30 + "+" + "-" * 18 + "+" + "\n" + "-" * 27 + " { Script Exec Params } " + "-" * 27 + "\n" + " " * 30 + "+" + "-" * 18 + "+\n"
+ values = "\n\t" + str( main.params )
+ values = re.sub( ",", "\n\t", values )
+ values = re.sub( "{", "\n\t", values )
+ values = re.sub( "}", "\n\t", values )
logmsg = logmsg + values
- logmsg = logmsg + "\n\n"+" " * 31+"+---------------+\n" +"-" * 29+" { Components Used } " +"-" * 29+"\n"+" " * 31+"+---------------+\n"
+ logmsg = logmsg + "\n\n" + " " * 31 + "+---------------+\n" + "-" * 29 + " { Components Used } " + "-" * 29 + "\n" + " " * 31 + "+---------------+\n"
component_list = []
- component_list.append(None)
+ component_list.append( None )
# Listing the components in the order of test_target component should be first.
- if type(main.componentDictionary) == dict:
+ if isinstance( main.componentDictionary, dict ):
for key in main.componentDictionary.keys():
- if main.test_target == key :
- component_list[0] = key+"-Test Target"
- else :
- component_list.append(key)
+ if main.test_target == key:
+ component_list[ 0 ] = key + "-Test Target"
+ else:
+ component_list.append( key )
- for index in range(len(component_list)) :
- if index==0:
- if component_list[index]:
- logmsg+="\t"+component_list[index]+"\n"
- elif index > 0 :
- logmsg+="\t"+str(component_list[index])+"\n"
+ for index in range( len( component_list ) ):
+ if index == 0:
+ if component_list[ index ]:
+ logmsg += "\t" + component_list[ index ] + "\n"
+ elif index > 0:
+ logmsg += "\t" + str( component_list[ index ] ) + "\n"
- logmsg = logmsg + "\n\n"+" " * 30+"+--------+\n" +"-" * 28+" { Topology } "+"-" * 28 +"\n" +" " * 30+"+--------+\n"
- values = "\n\t" + str(main.topology['COMPONENT'])
- values = re.sub(",", "\n\t", values)
- values = re.sub("{", "\n\t", values)
- values = re.sub("}", "\n\t", values)
+ logmsg = logmsg + "\n\n" + " " * 30 + "+--------+\n" + "-" * 28 + " { Topology } " + "-" * 28 + "\n" + " " * 30 + "+--------+\n"
+ values = "\n\t" + str( main.topology[ 'COMPONENT' ] )
+ values = re.sub( ",", "\n\t", values )
+ values = re.sub( "{", "\n\t", values )
+ values = re.sub( "}", "\n\t", values )
logmsg = logmsg + values
- logmsg = logmsg + "\n"+"-" * 60+"\n"
+ logmsg = logmsg + "\n" + "-" * 60 + "\n"
# enter into log file all headers
- logfile = open(main.LogFileName,"w+")
- logfile.write (logmsg)
+ logfile = open( main.LogFileName, "w+" )
+ logfile.write( logmsg )
print logmsg
main.logHeader = logmsg
logfile.close()
- #enter into report file all headers
- main.reportFile = open(main.ReportFileName,"w+")
- main.reportFile.write(logmsg)
+ # enter into report file all headers
+ main.reportFile = open( main.ReportFileName, "w+" )
+ main.reportFile.write( logmsg )
main.reportFile.close()
- #Sumamry file header
- currentTime = str( main.STARTTIME.strftime("%d %b %Y %H:%M:%S") )
+ # Sumamry file header
+ currentTime = str( main.STARTTIME.strftime( "%d %b %Y %H:%M:%S" ) )
main.summaryFile = open( main.SummaryFileName, "w+" )
main.summaryFile.write( main.TEST + " at " + currentTime + "\n" )
main.summaryFile.close()
- #wiki file header
- currentTime = str( main.STARTTIME.strftime("%d %b %Y %H:%M:%S") )
+ # wiki file header
+ currentTime = str( main.STARTTIME.strftime( "%d %b %Y %H:%M:%S" ) )
main.wikiFile = open( main.WikiFileName, "w+" )
main.wikiFile.write( main.TEST + " at " + currentTime + "<p></p>\n" )
main.wikiFile.close()
- def initlog(self,main):
- '''
+ def initlog( self, main ):
+ """
Initialise all the log handles.
- '''
+ """
main._getTest()
main.STARTTIME = datetime.datetime.now()
- currentTime = re.sub("-|\s|:|\.", "_", str(main.STARTTIME.strftime("%d %b %Y %H:%M:%S")))
+ currentTime = re.sub( "-|\s|:|\.", "_", str( main.STARTTIME.strftime( "%d %b %Y %H:%M:%S" ) ) )
if main.logdir:
- main.logdir = main.logdir+ "/"+main.TEST + "_" + currentTime
+ main.logdir = main.logdir + "/" + main.TEST + "_" + currentTime
else:
main.logdir = main.logs_path + main.TEST + "_" + currentTime
- os.mkdir(main.logdir)
+ os.mkdir( main.logdir )
- main.LogFileName = main.logdir + "/" + main.TEST + "_" +str(currentTime) + ".log"
- main.ReportFileName = main.logdir + "/" + main.TEST + "_" + str(currentTime) + ".rpt"
+ main.LogFileName = main.logdir + "/" + main.TEST + "_" + str( currentTime ) + ".log"
+ main.ReportFileName = main.logdir + "/" + main.TEST + "_" + str( currentTime ) + ".rpt"
main.WikiFileName = main.logdir + "/" + main.TEST + "Wiki.txt"
main.SummaryFileName = main.logdir + "/" + main.TEST + "Summary.txt"
main.JenkinsCSV = main.logdir + "/" + main.TEST + ".csv"
@@ -127,126 +129,128 @@
main.TOTAL_TC_SUCCESS = 0
- #### Add log-level - Report
- logging.addLevelName(9, "REPORT")
- logging.addLevelName(7, "EXACT")
- logging.addLevelName(11, "CASE")
- logging.addLevelName(12, "STEP")
- main.log = logging.getLogger(main.TEST)
- def report(msg):
- '''
+ # Add log-level - Report
+ logging.addLevelName( 9, "REPORT" )
+ logging.addLevelName( 7, "EXACT" )
+ logging.addLevelName( 11, "CASE" )
+ logging.addLevelName( 12, "STEP" )
+ main.log = logging.getLogger( main.TEST )
+
+ def report( msg ):
+ """
Will append the report message to the logs.
- '''
- main.log._log(9,msg,"OpenFlowAutoMattion","OFAutoMation")
+ """
+ main.log._log( 9, msg, "OpenFlowAutoMattion", "OFAutoMation" )
currentTime = datetime.datetime.now()
- currentTime = currentTime.strftime("%d %b %Y %H:%M:%S")
- newmsg = "\n[REPORT] " +"["+ str(currentTime)+"] "+msg
+ currentTime = currentTime.strftime( "%d %b %Y %H:%M:%S" )
+ newmsg = "\n[REPORT] " + "[" + str( currentTime ) + "] " + msg
print newmsg
- main.reportFile = open(main.ReportFileName,"a+")
- main.reportFile.write(newmsg)
+ main.reportFile = open( main.ReportFileName, "a+" )
+ main.reportFile.write( newmsg )
main.reportFile.close()
main.log.report = report
def summary( msg ):
- '''
+ """
Will append the message to the txt file for the summary.
- '''
- main.log._log(6,msg,"OpenFlowAutoMattion","OFAutoMation")
- main.summaryFile = open(main.SummaryFileName,"a+")
- main.summaryFile.write(msg+"\n")
+ """
+ main.log._log( 6, msg, "OpenFlowAutoMattion", "OFAutoMation" )
+ main.summaryFile = open( main.SummaryFileName, "a+" )
+ main.summaryFile.write( msg + "\n" )
main.summaryFile.close()
main.log.summary = summary
def wiki( msg ):
- '''
+ """
Will append the message to the txt file for the wiki.
- '''
- main.log._log(6,msg,"OpenFlowAutoMattion","OFAutoMation")
- main.wikiFile = open(main.WikiFileName,"a+")
- main.wikiFile.write(msg+"\n")
+ """
+ main.log._log( 6, msg, "OpenFlowAutoMattion", "OFAutoMation" )
+ main.wikiFile = open( main.WikiFileName, "a+" )
+ main.wikiFile.write( msg + "\n" )
main.wikiFile.close()
main.log.wiki = wiki
- def exact(exmsg):
- '''
+ def exact( exmsg ):
+ """
Will append the raw formatted message to the logs
- '''
- main.log._log(7,exmsg,"OpenFlowAutoMattion","OFAutoMation")
- main.reportFile = open(main.ReportFileName,"a+")
- main.reportFile.write(exmsg)
+ """
+ main.log._log( 7, exmsg, "OpenFlowAutoMattion", "OFAutoMation" )
+ main.reportFile = open( main.ReportFileName, "a+" )
+ main.reportFile.write( exmsg )
main.reportFile.close()
- logfile = open(main.LogFileName,"a")
- logfile.write("\n"+ str(exmsg) +"\n")
+ logfile = open( main.LogFileName, "a" )
+ logfile.write( "\n" + str( exmsg ) + "\n" )
logfile.close()
print exmsg
main.log.exact = exact
- def case(msg):
- '''
+ def case( msg ):
+ """
Format of the case type log defined here.
- '''
- main.log._log(9,msg,"OpenFlowAutoMattion","OFAutoMation")
+ """
+ main.log._log( 9, msg, "OpenFlowAutoMattion", "OFAutoMation" )
currentTime = datetime.datetime.now()
- newmsg = "["+str(currentTime)+"] " + "["+main.TEST+"] " + "[CASE] " +msg
- logfile = open(main.LogFileName,"a")
- logfile.write("\n"+ str(newmsg) +"\n")
+ newmsg = "[" + str( currentTime ) + "] " + "[" + main.TEST + "] " + "[CASE] " + msg
+ logfile = open( main.LogFileName, "a" )
+ logfile.write( "\n" + str( newmsg ) + "\n" )
logfile.close()
print newmsg
main.log.case = case
- def step(msg):
- '''
+ def step( msg ):
+ """
Format of the step type log defined here.
- '''
- main.log._log(9,msg,"OpenFlowAutoMattion","OFAutoMation")
+ """
+ main.log._log( 9, msg, "OpenFlowAutoMattion", "OFAutoMation" )
currentTime = datetime.datetime.now()
- newmsg = "["+str(currentTime)+"] " + "["+main.TEST+"] " + "[STEP] " +msg
- logfile = open(main.LogFileName,"a")
- logfile.write("\n"+ str(newmsg) +"\n")
+ newmsg = "[" + str( currentTime ) + "] " + "[" + main.TEST + "] " + "[STEP] " + msg
+ logfile = open( main.LogFileName, "a" )
+ logfile.write( "\n" + str( newmsg ) + "\n" )
logfile.close()
print newmsg
main.log.step = step
- main.LogFileHandler = logging.FileHandler(main.LogFileName)
- self._printHeader(main)
+ main.LogFileHandler = logging.FileHandler( main.LogFileName )
+ self._printHeader( main )
- ### initializing logging module and settig log level
- main.log.setLevel(logging.INFO)
- main.log.setLevel(logging.DEBUG) # Temporary
- main.LogFileHandler.setLevel(logging.INFO)
+ # initializing logging module and setting log level
+ main.log.setLevel( logging.INFO )
+ main.log.setLevel( logging.DEBUG ) # Temporary
+ main.LogFileHandler.setLevel( logging.INFO )
# create console handler with a higher log level
main.ConsoleHandler = logging.StreamHandler()
- main.ConsoleHandler.setLevel(logging.INFO)
- main.ConsoleHandler.setLevel(logging.DEBUG) #Temporary
+ main.ConsoleHandler.setLevel( logging.INFO )
+ main.ConsoleHandler.setLevel( logging.DEBUG ) # Temporary
# create formatter and add it to the handlers
- #formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+ # formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' )
+
class MyFormatter( logging.Formatter ):
colors = { 'cyan': '\033[96m', 'purple': '\033[95m',
'blue': '\033[94m', 'green': '\033[92m',
'yellow': '\033[93m', 'red': '\033[91m',
'end': '\033[0m' }
- FORMATS = {'DEFAULT': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'}
+ FORMATS = { 'DEFAULT': '%(asctime)s - %(name)s - %(levelname)s - %(message)s' }
if COLORS: # NOTE:colors will only be loaded if command is run from one line
# IE: './cli.py run testname'
# This is to prevent issues with Jenkins parsing
# TODO: Make colors configurable
- levels = { logging.ERROR : colors['red'] +
- FORMATS['DEFAULT'] +
- colors['end'],
- logging.WARN : colors['yellow'] +
- FORMATS['DEFAULT'] +
- colors['end'],
- logging.DEBUG : colors['purple'] +
- FORMATS['DEFAULT'] +
- colors['end'] }
+ levels = { logging.ERROR: colors[ 'red' ] +
+ FORMATS[ 'DEFAULT' ] +
+ colors[ 'end' ],
+ logging.WARN: colors[ 'yellow' ] +
+ FORMATS[ 'DEFAULT' ] +
+ colors[ 'end' ],
+ logging.DEBUG: colors[ 'purple' ] +
+ FORMATS[ 'DEFAULT' ] +
+ colors[ 'end' ] }
FORMATS.update( levels )
def format( self, record ):
@@ -254,89 +258,87 @@
self.FORMATS[ 'DEFAULT' ] )
return logging.Formatter.format( self, record )
formatter = MyFormatter()
- main.ConsoleHandler.setFormatter(formatter)
- main.LogFileHandler.setFormatter(formatter)
+ main.ConsoleHandler.setFormatter( formatter )
+ main.LogFileHandler.setFormatter( formatter )
# add the handlers to logger
- main.log.addHandler(main.ConsoleHandler)
- main.log.addHandler(main.LogFileHandler)
+ main.log.addHandler( main.ConsoleHandler )
+ main.log.addHandler( main.LogFileHandler )
- def testSummary(self,main):
- '''
+ def testSummary( self, main ):
+ """
testSummary will take care about the Summary of test.
- '''
-
+ """
main.ENDTIME = datetime.datetime.now()
main.EXECTIME = main.ENDTIME - main.STARTTIME
- if (main.TOTAL_TC_PASS == 0):
+ if ( main.TOTAL_TC_PASS == 0 ):
main.TOTAL_TC_SUCCESS = 0
else:
- main.TOTAL_TC_SUCCESS = str((main.TOTAL_TC_PASS*100)/main.TOTAL_TC_RUN)
- if (main.TOTAL_TC_RUN == 0) :
+ main.TOTAL_TC_SUCCESS = str( ( main.TOTAL_TC_PASS * 100 ) / main.TOTAL_TC_RUN )
+ if ( main.TOTAL_TC_RUN == 0 ):
main.TOTAL_TC_EXECPERCENT = 0
- else :
- main.TOTAL_TC_EXECPERCENT = str((main.TOTAL_TC_RUN*100)/main.TOTAL_TC_PLANNED)
- testResult = "\n\n"+"*" * 37+"\n" + "\tTest Execution Summary\n" + "\n"+"*" * 37+" \n"
- testResult = testResult + "\n Test Start : " + str(main.STARTTIME.strftime("%d %b %Y %H:%M:%S"))
- testResult = testResult + "\n Test End : " + str(main.ENDTIME.strftime("%d %b %Y %H:%M:%S"))
- testResult = testResult + "\n Execution Time : " + str(main.EXECTIME)
- testResult = testResult + "\n Total tests planned : " + str(main.TOTAL_TC_PLANNED)
- testResult = testResult + "\n Total tests RUN : " + str(main.TOTAL_TC_RUN)
- testResult = testResult + "\n Total Pass : " + str(main.TOTAL_TC_PASS)
- testResult = testResult + "\n Total Fail : " + str(main.TOTAL_TC_FAIL)
- testResult = testResult + "\n Total No Result : " + str(main.TOTAL_TC_NORESULT)
- testResult = testResult + "\n Success Percentage : " + str(main.TOTAL_TC_SUCCESS) + "%"
- testResult = testResult + "\n Execution Result : " + str(main.TOTAL_TC_EXECPERCENT) + "%\n"
+ else:
+ main.TOTAL_TC_EXECPERCENT = str( ( main.TOTAL_TC_RUN * 100 ) / main.TOTAL_TC_PLANNED )
+ testResult = "\n\n" + "*" * 37 + "\n" + "\tTest Execution Summary\n" + "\n" + "*" * 37 + " \n"
+ testResult = testResult + "\n Test Start : " + str( main.STARTTIME.strftime( "%d %b %Y %H:%M:%S" ) )
+ testResult = testResult + "\n Test End : " + str( main.ENDTIME.strftime( "%d %b %Y %H:%M:%S" ) )
+ testResult = testResult + "\n Execution Time : " + str( main.EXECTIME )
+ testResult = testResult + "\n Total tests planned : " + str( main.TOTAL_TC_PLANNED )
+ testResult = testResult + "\n Total tests RUN : " + str( main.TOTAL_TC_RUN )
+ testResult = testResult + "\n Total Pass : " + str( main.TOTAL_TC_PASS )
+ testResult = testResult + "\n Total Fail : " + str( main.TOTAL_TC_FAIL )
+ testResult = testResult + "\n Total No Result : " + str( main.TOTAL_TC_NORESULT )
+ testResult = testResult + "\n Success Percentage : " + str( main.TOTAL_TC_SUCCESS ) + "%"
+ testResult = testResult + "\n Execution Result : " + str( main.TOTAL_TC_EXECPERCENT ) + "%\n"
if main.failedCase:
- testResult = testResult + "\n Case Failed : " + str( main.failedCase )
+ testResult = testResult + "\n Case Failed : " + str( main.failedCase )
if main.noResultCase:
- testResult = testResult + "\n Case NoResult : " + str( main.noResultCase )
- testResult = testResult + "\n Case Executed : " + str( main.executedCase )
- testResult = testResult + "\n Case Not Executed : " + str( main.leftCase )
- #main.log.report(testResult)
+ testResult = testResult + "\n Case NoResult : " + str( main.noResultCase )
+ testResult = testResult + "\n Case Executed : " + str( main.executedCase )
+ testResult = testResult + "\n Case Not Executed : " + str( main.leftCase )
+ # main.log.report( testResult )
main.testResult = testResult
- main.log.exact(testResult)
+ main.log.exact( testResult )
- ##CSV output needed for Jenkin's plot plugin
- #NOTE: the elements were orded based on the colors assigned to the data
- logfile = open(main.JenkinsCSV ,"w")
- logfile.write(",".join( ['Tests Failed', 'Tests Passed', 'Tests Planned'] ) + "\n")
- logfile.write(",".join( [str(int(main.TOTAL_TC_FAIL)), str(int(main.TOTAL_TC_PASS)), str(int(main.TOTAL_TC_PLANNED))] ) + "\n")
+ # CSV output needed for Jenkins plot plugin
+ # NOTE: the elements were ordered based on the colors assigned to the data
+ logfile = open( main.JenkinsCSV, "w" )
+ logfile.write( ",".join( [ 'Tests Failed', 'Tests Passed', 'Tests Planned' ] ) + "\n" )
+ logfile.write( ",".join( [ str( int( main.TOTAL_TC_FAIL ) ), str( int( main.TOTAL_TC_PASS ) ), str( int( main.TOTAL_TC_PLANNED ) ) ] ) + "\n" )
logfile.close()
- executedStatus = open(main.resultFile, "w")
+ executedStatus = open( main.resultFile, "w" )
if main.TOTAL_TC_FAIL == 0 and main.TOTAL_TC_NORESULT + main.TOTAL_TC_PASS == main.TOTAL_TC_PLANNED:
- executedStatus.write("1\n")
+ executedStatus.write( "1\n" )
else:
- executedStatus.write("0\n")
+ executedStatus.write( "0\n" )
executedStatus.close()
- def updateCaseResults(self,main):
- '''
+ def updateCaseResults( self, main ):
+ """
Update the case result based on the steps execution and asserting each step in the test-case
- '''
- case = str(main.CurrentTestCaseNumber)
- currentResult = main.testCaseResult.get(case, 2)
+ """
+ case = str( main.CurrentTestCaseNumber )
+ currentResult = main.testCaseResult.get( case, 2 )
if currentResult == 2:
- main.TOTAL_TC_RUN = main.TOTAL_TC_RUN + 1
+ main.TOTAL_TC_RUN = main.TOTAL_TC_RUN + 1
main.TOTAL_TC_NORESULT = main.TOTAL_TC_NORESULT + 1
- main.log.exact("\n "+"*" * 29+"\n" + "\n Result: No Assertion Called \n"+"*" * 29+"\n")
- line = "Case "+case+": "+main.CurrentTestCase+" - No Result"
+ main.log.exact( "\n " + "*" * 29 + "\n" + "\n Result: No Assertion Called \n" + "*" * 29 + "\n" )
+ line = "Case " + case + ": " + main.CurrentTestCase + " - No Result"
elif currentResult == 1:
- main.TOTAL_TC_RUN = main.TOTAL_TC_RUN + 1
- main.TOTAL_TC_PASS = main.TOTAL_TC_PASS + 1
- main.log.exact("\n"+"*" * 29+"\n Result: Pass \n"+"*" * 29+"\n")
- line = "Case "+case+": "+main.CurrentTestCase+" - PASS"
+ main.TOTAL_TC_RUN = main.TOTAL_TC_RUN + 1
+ main.TOTAL_TC_PASS = main.TOTAL_TC_PASS + 1
+ main.log.exact( "\n" + "*" * 29 + "\n Result: Pass \n" + "*" * 29 + "\n" )
+ line = "Case " + case + ": " + main.CurrentTestCase + " - PASS"
elif currentResult == 0:
- main.TOTAL_TC_RUN = main.TOTAL_TC_RUN + 1
+ main.TOTAL_TC_RUN = main.TOTAL_TC_RUN + 1
main.TOTAL_TC_FAIL = main.TOTAL_TC_FAIL + 1
- main.log.exact("\n"+"*" * 29+"\n Result: Failed \n"+"*" * 29+"\n")
- line = "Case "+case+": "+main.CurrentTestCase+" - FAIL"
+ main.log.exact( "\n" + "*" * 29 + "\n Result: Failed \n" + "*" * 29 + "\n" )
+ line = "Case " + case + ": " + main.CurrentTestCase + " - FAIL"
else:
main.log.error( " Unknown result of case " + case +
". Result was: " + currentResult )
- line = "Case "+case+": "+main.CurrentTestCase+" - ERROR"
+ line = "Case " + case + ": " + main.CurrentTestCase + " - ERROR"
main.log.wiki( "<h3>" + line + "</h3>" )
main.log.summary( line )
-
diff --git a/TestON/core/openspeak.py b/TestON/core/openspeak.py
index b98c68b..dfcfe42 100644
--- a/TestON/core/openspeak.py
+++ b/TestON/core/openspeak.py
@@ -1,5 +1,5 @@
-#/usr/bin/env python
-'''
+# /usr/bin/env python
+"""
Created on 20-Dec-2012
Modified 2015 by ON.Lab
@@ -10,7 +10,7 @@
TestON is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -21,797 +21,772 @@
along with TestON. If not, see <http://www.gnu.org/licenses/>.
-'''
+"""
import re
import inspect
class OpenSpeak:
- def __init__(self):
+ def __init__( self ):
self.default = ''
self.flag = 0
self.CurrentStep = 0
self.grtrOrLssr = 0
- def compiler(self,**compileParameters):
- '''
+ def compiler( self, **compileParameters ):
+ """
This method will parse the openspeak file and will write to a python module with the equivalent translations.
It can accept OpenSpeak syntax in string or an OpenSpeak file as an input parameter.
Translated form can be written into python module if attribute "WRITETOFILE" is set to 1.
- '''
-
- args = self.parse_args(["OPENSPEAKFILE","TEXT","WRITETOFILE","FILEHANDLE"],**compileParameters)
+ """
+ args = self.parse_args( [ "OPENSPEAKFILE", "TEXT", "WRITETOFILE", "FILEHANDLE" ], **compileParameters )
resultString = ''
Test = "Mininet"
- args["WRITETOFILE"] = args["WRITETOFILE"] if args["WRITETOFILE"] != None else 1
+ args[ "WRITETOFILE" ] = args[ "WRITETOFILE" ] if args[ "WRITETOFILE" ] is not None else 1
self.CurrentStep = 0
self.CurrentCase = ''
- ## here Open Speak file will be parsed by each line and translated.
- if args["OPENSPEAKFILE"] !=None and args["TEXT"] ==None and args["FILEHANDLE"] == None:
- self.openspeakfile = args["OPENSPEAKFILE"]
- openSpeakFile = open(args["OPENSPEAKFILE"],"r").readlines()
+ # here Open Speak file will be parsed by each line and translated.
+ if args[ "OPENSPEAKFILE" ] is not None and args[ "TEXT" ] is None and args[ "FILEHANDLE" ] is None:
+ self.openspeakfile = args[ "OPENSPEAKFILE" ]
+ openSpeakFile = open( args[ "OPENSPEAKFILE" ], "r" ).readlines()
- elif args["OPENSPEAKFILE"] ==None and args["TEXT"] and args["FILEHANDLE"] == None:
- openSpeakFile = args["TEXT"].split("\n")
- elif args["FILEHANDLE"] and args["OPENSPEAKFILE"] ==None and args["TEXT"] ==None:
- openSpeakFile = args["FILEHANDLE"].readlines()
+ elif args[ "OPENSPEAKFILE" ] is None and args[ "TEXT" ] and args[ "FILEHANDLE" ] is None:
+ openSpeakFile = args[ "TEXT" ].split( "\n" )
+ elif args[ "FILEHANDLE" ] and args[ "OPENSPEAKFILE" ] is None and args[ "TEXT" ] is None:
+ openSpeakFile = args[ "FILEHANDLE" ].readlines()
index = 0
outputFile = []
- testName = re.search("\/(.*)\.ospk$",self.openspeakfile,0)
- testName = testName.group(1)
- testName = testName.split("/")
- testName = testName[len(testName)-1]
- outputFile.append("\nclass " + testName + " :" + "\n")
- outputFile.append("\n" + " " * 4 + "def __init__(self) :")
- outputFile.append("\n" + " " * 8 + "self.default = \'\'" + "\n")
+ testName = re.search( "\/(.*)\.ospk$", self.openspeakfile, 0 )
+ testName = testName.group( 1 )
+ testName = testName.split( "/" )
+ testName = testName[ len( testName ) - 1 ]
+ outputFile.append( "\nclass " + testName + " :" + "\n" )
+ outputFile.append( "\n" + " " * 4 + "def __init__(self) :" )
+ outputFile.append( "\n" + " " * 8 + "self.default = \'\'" + "\n" )
- while index < len(openSpeakFile):
- ifelseMatch = re.match("\s+IF|\s+ELSE|\s+ELIF",openSpeakFile[index],flags=0)
- line = openSpeakFile[index]
- repeatMatch = re.match("\s*REPEAT", openSpeakFile[index], flags=0)
- if ifelseMatch :
- result = self.verify_and_translate(line)
- initialSpaces = len(line) -len(line.lstrip())
+ while index < len( openSpeakFile ):
+ ifelseMatch = re.match( "\s+IF|\s+ELSE|\s+ELIF", openSpeakFile[ index ], flags=0 )
+ line = openSpeakFile[ index ]
+ repeatMatch = re.match( "\s*REPEAT", openSpeakFile[ index ], flags=0 )
+ if ifelseMatch:
+ result = self.verify_and_translate( line )
+ initialSpaces = len( line ) - len( line.lstrip() )
self.outLoopSpace = initialSpaces
- nextLine = openSpeakFile[index+1]
- nextinitialSpaces = len(nextLine) -len(nextLine.lstrip())
+ nextLine = openSpeakFile[ index + 1 ]
+ nextinitialSpaces = len( nextLine ) - len( nextLine.lstrip() )
-
- while nextinitialSpaces > initialSpaces :
- try :
- elseMatch = re.match("\s*ELSE|\s*ELIF",nextLine,flags=0)
- if elseMatch :
- self.flag = self.flag -1
- result = result + self.verify_and_translate(nextLine)
- nextLine = openSpeakFile[index + 1]
- nextinitialSpaces = len(nextLine) -len(nextLine.lstrip())
+ while nextinitialSpaces > initialSpaces:
+ try:
+ elseMatch = re.match( "\s*ELSE|\s*ELIF", nextLine, flags=0 )
+ if elseMatch:
+ self.flag = self.flag - 1
+ result = result + self.verify_and_translate( nextLine )
+ nextLine = openSpeakFile[ index + 1 ]
+ nextinitialSpaces = len( nextLine ) - len( nextLine.lstrip() )
except IndexError:
pass
index = index + 1
self.flag = 0
elif repeatMatch:
self.flag = 0
- result = self.verify_and_translate(line)
+ result = self.verify_and_translate( line )
index = index + 1
- endMatch = re.match("\s*END",openSpeakFile[index],flags=0)
- while not endMatch :
- try :
+ endMatch = re.match( "\s*END", openSpeakFile[ index ], flags=0 )
+ while not endMatch:
+ try:
self.flag = self.flag + 1
- result = result + self.verify_and_translate(openSpeakFile[index])
+ result = result + self.verify_and_translate( openSpeakFile[ index ] )
index = index + 1
- except IndexError :
+ except IndexError:
pass
-
- else :
+ else:
self.flag = 0
- result = self.verify_and_translate(line)
+ result = self.verify_and_translate( line )
index = index + 1
- outputFile.append(result)
+ outputFile.append( result )
- if args["WRITETOFILE"] == 1 :
- testscript = re.sub("ospk","py",self.openspeakfile,0)
- testScript = open(testscript,"w")
- for lines in outputFile :
- testScript.write(lines)
+ if args[ "WRITETOFILE" ] == 1:
+ testscript = re.sub( "ospk", "py", self.openspeakfile, 0 )
+ testScript = open( testscript, "w" )
+ for lines in outputFile:
+ testScript.write( lines )
testScript.close()
return resultString
- def verify_and_translate(self,line):
- '''
+ def verify_and_translate( self, line ):
+ """
It will accept the each line and calls the suitable API to conver into pyton equivalent syntax .
It will return the translated python syntax .
- '''
- lineSpace = re.match("^\s+",line,flags=0)
- initialSpaces = len(line) -len(line.lstrip())
- line = re.sub("^\s+","",line) if lineSpace else line
-
+ """
+ lineSpace = re.match( "^\s+", line, flags=0 )
+ initialSpaces = len( line ) - len( line.lstrip() )
+ line = re.sub( "^\s+", "", line ) if lineSpace else line
resultString = None
- resultString = "\n" + " " * 4 if str(inspect.stack()[1][3]) == "compiler" else "\n"
- indent = " " *(4 + 4 * self.flag) if self.flag > 0 else " " * 4
- caseMatch = re.search("^CASE\s+(\d+)",line,flags=0)
- nameMatch = re.match("^NAME\s+\"(.*)\"",line,flags=0)
- commentMatch = re.match("^COMMENT\s+\"(.*)\"",line,flags=0)
- stepMatch = re.match("^STEP\s+\"(.*)\"",line,flags=0)
- connectMatch = re.match("^CONNECT\s+(\w+)\s+USING\s+(.*)",line,flags=0)
- disconnectMatch = re.match("^DISCONNECT\s+(.*)",line,flags=0)
- ondoMatch = re.match("^ON\s+(.*)\s+DO\s+(.*)",line,flags=0)
+ resultString = "\n" + " " * 4 if str( inspect.stack()[ 1 ][ 3 ] ) == "compiler" else "\n"
+ indent = " " * ( 4 + 4 * self.flag ) if self.flag > 0 else " " * 4
+ caseMatch = re.search( "^CASE\s+(\d+)", line, flags=0 )
+ nameMatch = re.match( "^NAME\s+\"( .* )\"", line, flags=0 )
+ commentMatch = re.match( "^COMMENT\s+\"( .* )\"", line, flags=0 )
+ stepMatch = re.match( "^STEP\s+\"( .* )\"", line, flags=0 )
+ connectMatch = re.match( "^CONNECT\s+(\w+)\s+USING\s+(.*)", line, flags=0 )
+ disconnectMatch = re.match( "^DISCONNECT\s+(.*)", line, flags=0 )
+ ondoMatch = re.match( "^ON\s+(.*)\s+DO\s+(.*)", line, flags=0 )
- storeMatch = re.match("^STORE\s+(.*)\s+IN\s+(.*)",line,flags=0)
- variableMatch = re.match("^(.*)\s+=\s+(.*)",line,flags=0)
- assertMatch = re.match("^ASSERT\s+(\w+)\s+(.*)\s+(.*)\s+ONPASS\s+(.*)\s+ONFAIL\s+(.*)",line,flags=0)
- logMatch = re.match("^(ERROR|INFO|DEBUG|CRITICAL|REPORT|EXACT|WARN)\s+(.*)",line,flags=0)
- ifloop = re.match("IF\s+(\w+)\s*(..|\w+)\s*(.*)",line,flags=0)
- elseloopMatch = re.match("ELSE\s*$",line,flags=0)
- elifloop = re.match("ELSE\sIF\s+(\w+)\s*(..|\w+)\s*(.*)",line,flags=0)
- forloopMatch = re.match("\s*REPEAT\s+(/d+)\s+TIMES",line,flags=0)
- experimentalMatch = re.match("EXPERIMENTAL\s+MODE\s+(\w+)",line,flags=0)
- repeatMatch = re.match("\s*REPEAT\s+(\d+)\s+TIMES", line, flags=0)
+ storeMatch = re.match( "^STORE\s+(.*)\s+IN\s+(.*)", line, flags=0 )
+ variableMatch = re.match( "^(.*)\s+=\s+(.*)", line, flags=0 )
+ assertMatch = re.match( "^ASSERT\s+(\w+)\s+(.*)\s+(.*)\s+ONPASS\s+(.*)\s+ONFAIL\s+(.*)", line, flags=0 )
+ logMatch = re.match( "^(ERROR|INFO|DEBUG|CRITICAL|REPORT|EXACT|WARN)\s+(.*)", line, flags=0 )
+ ifloop = re.match( "IF\s+(\w+)\s*(..|\w+)\s*(.*)", line, flags=0 )
+ elseloopMatch = re.match( "ELSE\s*$", line, flags=0 )
+ elifloop = re.match( "ELSE\sIF\s+(\w+)\s*(..|\w+)\s*(.*)", line, flags=0 )
+ forloopMatch = re.match( "\s*REPEAT\s+(/d+)\s+TIMES", line, flags=0 )
+ experimentalMatch = re.match( "EXPERIMENTAL\s+MODE\s+(\w+)", line, flags=0 )
+ repeatMatch = re.match( "\s*REPEAT\s+(\d+)\s+TIMES", line, flags=0 )
- response_pasrse = re.match("\s*PARSE\s+(\w+)\s+AS\s+(\w+)\s+INTO\s+(\w+)", line, flags=0)
+ response_pasrse = re.match( "\s*PARSE\s+(\w+)\s+AS\s+(\w+)\s+INTO\s+(\w+)", line, flags=0 )
- if caseMatch :
+ if caseMatch:
self.CurrentStep = 0
- self.CurrentCase = "CASE" + caseMatch.group(1)
- resultString = resultString + self.translate_case_block(casenumber=caseMatch.group(1))
+ self.CurrentCase = "CASE" + caseMatch.group( 1 )
+ resultString = resultString + self.translate_case_block( casenumber=caseMatch.group( 1 ) )
elif repeatMatch:
- resultString = resultString + indent + self.translate_repeat(repeat=repeatMatch.group(1))
- elif nameMatch :
- resultString = resultString + indent + self.translate_testcase_name(testname=nameMatch.group(1))
- elif commentMatch :
- resultString = resultString + indent + self.translate_comment(comment=commentMatch.group(1))
- elif stepMatch :
+ resultString = resultString + indent + self.translate_repeat( repeat=repeatMatch.group( 1 ) )
+ elif nameMatch:
+ resultString = resultString + indent + self.translate_testcase_name( testname=nameMatch.group( 1 ) )
+ elif commentMatch:
+ resultString = resultString + indent + self.translate_comment( comment=commentMatch.group( 1 ) )
+ elif stepMatch:
self.CurrentStep = self.CurrentStep + 1
- resultString = resultString + indent + self.translate_step(step=stepMatch.group(1))
- elif connectMatch :
- resultString = resultString + indent + self.translate_connect(component=connectMatch.group(1),
- arguments=connectMatch.group(2) )
- elif disconnectMatch :
- resultString = resultString + indent + self.translate_disconnect(component=disconnectMatch.group(1))
- elif ondoMatch :
- resultString = resultString + indent + self.translate_onDOAs(component=ondoMatch.group(1),action=ondoMatch.group(2))
- elif storeMatch :
- resultString = resultString + indent + self.translate_store(variable=storeMatch.group(2),
- value=storeMatch.group(1))
- elif variableMatch :
- resultString = resultString + indent + self.translate_store(variable=variableMatch.group(1),
- value=variableMatch.group(2))
- elif assertMatch :
- resultString = resultString + indent + self.translate_assertion(leftvalue=assertMatch.group(1),
- operator=assertMatch.group(2),
- rightvalue=assertMatch.group(3),
- onpass=assertMatch.group(4),
- onfail=assertMatch.group(5))
- elif logMatch :
- resultString = resultString + indent + self.translate_logs(loglevel=logMatch.group(1),
- message=logMatch.group(2))
- elif ifloop :
+ resultString = resultString + indent + self.translate_step( step=stepMatch.group( 1 ) )
+ elif connectMatch:
+ resultString = resultString + indent + self.translate_connect( component=connectMatch.group( 1 ),
+ arguments=connectMatch.group( 2 ) )
+ elif disconnectMatch:
+ resultString = resultString + indent + self.translate_disconnect( component=disconnectMatch.group( 1 ) )
+ elif ondoMatch:
+ resultString = resultString + indent + self.translate_onDOAs( component=ondoMatch.group( 1 ), action=ondoMatch.group( 2 ) )
+ elif storeMatch:
+ resultString = resultString + indent + self.translate_store( variable=storeMatch.group( 2 ),
+ value=storeMatch.group( 1 ) )
+ elif variableMatch:
+ resultString = resultString + indent + self.translate_store( variable=variableMatch.group( 1 ),
+ value=variableMatch.group( 2 ) )
+ elif assertMatch:
+ resultString = resultString + indent + self.translate_assertion( leftvalue=assertMatch.group( 1 ),
+ operator=assertMatch.group( 2 ),
+ rightvalue=assertMatch.group( 3 ),
+ onpass=assertMatch.group( 4 ),
+ onfail=assertMatch.group( 5 ) )
+ elif logMatch:
+ resultString = resultString + indent + self.translate_logs( loglevel=logMatch.group( 1 ),
+ message=logMatch.group( 2 ) )
+ elif ifloop:
self.initSpace = initialSpaces
- operand = ifloop.group(1)
- operator = ifloop.group(2)
- value = ifloop.group(3)
- resultString = resultString + indent + "if " + operand + self.translate_if_else_operator(conditionoperator=operator) + value + ":"
+ operand = ifloop.group( 1 )
+ operator = ifloop.group( 2 )
+ value = ifloop.group( 3 )
+ resultString = resultString + indent + "if " + operand + self.translate_if_else_operator( conditionoperator=operator ) + value + ":"
self.flag = self.flag + 1
- elif experimentalMatch :
- resultString = resultString + indent + self.translate_experimental_mode(mode=experimentalMatch.group(1))
+ elif experimentalMatch:
+ resultString = resultString + indent + self.translate_experimental_mode( mode=experimentalMatch.group( 1 ) )
- elif elseloopMatch :
+ elif elseloopMatch:
if initialSpaces == self.initSpace or initialSpaces == self.outLoopSpace:
resultString = resultString + indent + "else :"
self.flag = self.flag + 1
- else :
- indent = " " *(4 + 4 * (self.flag-1))
+ else:
+ indent = " " * ( 4 + 4 * ( self.flag - 1 ) )
resultString = resultString + indent + "else :"
self.flag = self.flag + 1
- elif elifloop :
+ elif elifloop:
- operand = elifloop.group(1)
- operator = elifloop.group(2)
- value = elifloop.group(3)
+ operand = elifloop.group( 1 )
+ operator = elifloop.group( 2 )
+ value = elifloop.group( 3 )
if initialSpaces == self.initSpace or initialSpaces == self.outLoopSpace:
- resultString = resultString + indent + "elif " + operand + self.translate_if_else_operator(conditionoperator=operator) + value + ":"
+ resultString = resultString + indent + "elif " + operand + self.translate_if_else_operator( conditionoperator=operator ) + value + ":"
self.flag = self.flag + 1
- else :
- indent = " " *(4 + 4 * (self.flag-1))
- resultString = resultString + indent + "elif " + operand + self.translate_if_else_operator(conditionoperator=operator) + value + ":"
+ else:
+ indent = " " * ( 4 + 4 * ( self.flag - 1 ) )
+ resultString = resultString + indent + "elif " + operand + self.translate_if_else_operator( conditionoperator=operator ) + value + ":"
self.flag = self.flag + 1
- elif response_pasrse :
- output_string = response_pasrse.group(1)
- req_format = response_pasrse.group(2)
- store_in = response_pasrse.group(3)
- resultString = resultString + indent + store_in +'= main.response_parser('+output_string+",\""+req_format+"\")"
+ elif response_pasrse:
+ output_string = response_pasrse.group( 1 )
+ req_format = response_pasrse.group( 2 )
+ store_in = response_pasrse.group( 3 )
+ resultString = resultString + indent + store_in + '= main.response_parser(' + output_string + ",\"" + req_format + "\")"
self.flag = self.flag + 1
return resultString
- def translate_repeat(self,**repeatStatement):
- '''
+ def translate_repeat( self, **repeatStatement ):
+ """
this will transalte the repeat statement into a python equivalen while loop
- '''
-
- args = self.parse_args(["REPEAT"],**repeatStatement)
+ """
+ args = self.parse_args( [ "REPEAT" ], **repeatStatement )
resultString = ''
resultString = "i = 0"
- resultString = resultString + "\n" + " " * 8 +"while i<" + args["REPEAT"] + " :"
+ resultString = resultString + "\n" + " " * 8 + "while i<" + args[ "REPEAT" ] + " :"
return resultString
- def translate_if_else_operator(self,**loopBlock):
- '''
+ def translate_if_else_operator( self, **loopBlock ):
+ """
This method will translate if-else loop block into its equivalent python code.
Whole loop block will be passed into loopBlock List.
It returns the transalted reuslt as a string.
- '''
- args = self.parse_args(["CONDITIONOPERATOR"],**loopBlock)
+ """
+ args = self.parse_args( [ "CONDITIONOPERATOR" ], **loopBlock )
resultString = ''
# process the loopBlock List translate all statements underlying the given loop block
- equalsMatch = re.match("EQUALS$|==\s*$",args["CONDITIONOPERATOR"],flags=0)
- greaterMatch = re.match("GREATER\s+THAN$|>\s*$",args["CONDITIONOPERATOR"],flags=0)
- lesserMatch = re.match("LESSER\s+THAN$|<\s*$",args["CONDITIONOPERATOR"],flags=0)
- greaterEqualMatch = re.match("GREATER\s+THAN\s+OR\s+EQUALS$|>=\s*$",args["CONDITIONOPERATOR"],flags=0)
- lesserEqualMatch = re.match("LESSER\s+THAN\s+OR\s+EQUALS$|<=\s*$",args["CONDITIONOPERATOR"],flags=0)
- if equalsMatch :
+ equalsMatch = re.match( "EQUALS$|==\s*$", args[ "CONDITIONOPERATOR" ], flags=0 )
+ greaterMatch = re.match( "GREATER\s+THAN$|>\s*$", args[ "CONDITIONOPERATOR" ], flags=0 )
+ lesserMatch = re.match( "LESSER\s+THAN$|<\s*$", args[ "CONDITIONOPERATOR" ], flags=0 )
+ greaterEqualMatch = re.match( "GREATER\s+THAN\s+OR\s+EQUALS$|>=\s*$", args[ "CONDITIONOPERATOR" ], flags=0 )
+ lesserEqualMatch = re.match( "LESSER\s+THAN\s+OR\s+EQUALS$|<=\s*$", args[ "CONDITIONOPERATOR" ], flags=0 )
+ if equalsMatch:
resultString = resultString + " == "
- elif greaterMatch :
+ elif greaterMatch:
resultString = resultString + " > "
- elif lesserMatch :
+ elif lesserMatch:
resultString = resultString + " < "
elif greaterEqualMatch:
resultString = resultString + " >= "
- elif lesserEqualMatch :
+ elif lesserEqualMatch:
resultString = resultString + " <= "
- else :
+ else:
print "\n Error: Given Operator is not listed "
return resultString
- def translate_experimental_mode(self,**modeType):
- '''
+ def translate_experimental_mode( self, **modeType ):
+ """
This API will translate statment EXPERIMENTAL MODE ON/OFF into python equivalent.
It will return the transalted value.
- '''
- args = self.parse_args(["MODE"],**modeType)
+ """
+ args = self.parse_args( [ "MODE" ], **modeType )
resultString = ''
- ONmatch = re.match("\s*ON",args["MODE"],flags=0)
- OFFmatch = re.match("\sOFF",args["MODE"],flags=0)
+ ONmatch = re.match( "\s*ON", args[ "MODE" ], flags=0 )
+ OFFmatch = re.match( "\sOFF", args[ "MODE" ], flags=0 )
- if ONmatch :
+ if ONmatch:
resultString = "main.EXPERIMENTAL_MODE = main.TRUE"
- elif OFFmatch :
+ elif OFFmatch:
resultString = "main.EXPERIMENTAL_MODE = main.FALSE"
return resultString
- def interpret(self,**interpetParameters):
- '''
+ def interpret( self, **interpetParameters ):
+ """
This method will accept the OpenSpeak syntax into a string and will return
a python equivalent translations statement
- '''
-
- args = self.parse_args(["TEXT","WRITETOFILE"],**interpetParameters)
+ """
+ args = self.parse_args( [ "TEXT", "WRITETOFILE" ], **interpetParameters )
resultString = ''
- ## here Open Speak syntax will be translated into python equivalent.
- resultString = self.verify_and_translate(args["TEXT"])
- lineSpace = re.match("^\s+",resultString,flags=0)
+ # here Open Speak syntax will be translated into python equivalent.
+ resultString = self.verify_and_translate( args[ "TEXT" ] )
+ lineSpace = re.match( "^\s+", resultString, flags=0 )
- resultString = re.sub("^\s+","",resultString) if lineSpace else resultString
+ resultString = re.sub( "^\s+", "", resultString ) if lineSpace else resultString
return resultString
- def translate_logs(self,**logStatement):
- '''
+ def translate_logs( self, **logStatement ):
+ """
This will translate the OpenSpeak log message statements into python equivalent
to resultString and returns resultString
- '''
- args = self.parse_args(["LOGLEVEL","MESSAGE"],**logStatement)
+ """
+ args = self.parse_args( [ "LOGLEVEL", "MESSAGE" ], **logStatement )
resultString = ''
# convert the statement here
- message = self.translate_log_message(message=args["MESSAGE"])
- if args["LOGLEVEL"] == "INFO" :
+ message = self.translate_log_message( message=args[ "MESSAGE" ] )
+ if args[ "LOGLEVEL" ] == "INFO":
resultString = resultString + "main.log.info(" + message + ")"
- elif args["LOGLEVEL"] == "ERROR" :
- resultString = resultString + "main.log.error(" + message + ")"
- elif args["LOGLEVEL"] == "DEBUG" :
+ elif args[ "LOGLEVEL" ] == "ERROR":
+ resultString = resultString + "main.log.error(" + message + ")"
+ elif args[ "LOGLEVEL" ] == "DEBUG":
resultString = resultString + "main.log.debug(" + message + ")"
- elif args["LOGLEVEL"] == "REPORT" :
+ elif args[ "LOGLEVEL" ] == "REPORT":
resultString = resultString + "main.log.report(" + message + ")"
- elif args["LOGLEVEL"] == "CRITICAL" :
+ elif args[ "LOGLEVEL" ] == "CRITICAL":
resultString = resultString + "main.log.critical(" + message + ")"
- elif args["LOGLEVEL"] == "WARN" :
- resultString = resultString + "main.log.warn(" + args["MESSAGE"] + ")"
- elif args["LOGLEVEL"] == "EXACT" :
- resultString = resultString + "main.log.exact(" + args["MESSAGE"] + ")"
-
+ elif args[ "LOGLEVEL" ] == "WARN":
+ resultString = resultString + "main.log.warn(" + args[ "MESSAGE" ] + ")"
+ elif args[ "LOGLEVEL" ] == "EXACT":
+ resultString = resultString + "main.log.exact(" + args[ "MESSAGE" ] + ")"
return resultString
- def translate_log_message(self,**messageStatement) :
- '''
+ def translate_log_message( self, **messageStatement ):
+ """
This API will translate log messages if it is a string or Variable or combination
of string and variable.
It will return the analysed and translate message.
- '''
- args = self.parse_args(["MESSAGE"],**messageStatement)
+ """
+ args = self.parse_args( [ "MESSAGE" ], **messageStatement )
resultString = ''
- paramsMatch = re.match("PARAMS\[(.*)\]|STEP\[(.*)\]|TOPO\[(.*)\]|CASE\[(.*)\]|LAST_RESULT|LAST_RESPONSE",args["MESSAGE"],flags=0)
- stringMatch = re.match("\s*\"(.*)\"\s*$",args["MESSAGE"],flags=0)
- stringWidVariableMatch = re.match("\"(.*)\"\s+\+\s+(.*)",args["MESSAGE"],flags=0)
- varRefMatch = re.search("\<(\w+)\>",args["MESSAGE"],flags=0)
- if paramsMatch :
- resultString = resultString + self.translate_parameters(parameters=args["MESSAGE"])
- elif stringMatch :
- resultString = resultString + args["MESSAGE"]
+ paramsMatch = re.match( "PARAMS\[(.*)\]|STEP\[(.*)\]|TOPO\[(.*)\]|CASE\[(.*)\]|LAST_RESULT|LAST_RESPONSE", args[ "MESSAGE" ], flags=0 )
+ stringMatch = re.match( "\s*\"( .* )\"\s*$", args[ "MESSAGE" ], flags=0 )
+ stringWidVariableMatch = re.match( "\"( .* )\"\s+\+\s+(.*)", args[ "MESSAGE" ], flags=0 )
+ varRefMatch = re.search( "\<(\w+)\>", args[ "MESSAGE" ], flags=0 )
+ if paramsMatch:
+ resultString = resultString + self.translate_parameters( parameters=args[ "MESSAGE" ] )
+ elif stringMatch:
+ resultString = resultString + args[ "MESSAGE" ]
elif stringWidVariableMatch:
- quoteWord = stringWidVariableMatch.group(1)
- variableRef = stringWidVariableMatch.group(2)
- varMatch = re.search("PARAMS\[(.*)\]|STEP\[(.*)\]|TOPO\[(.*)\]|CASE\[(.*)\]",variableRef,flags=0)
- varRefMatch = re.search("\<(\w+)\>",variableRef,flags=0)
- if varMatch :
- resultString = resultString + "\"" + quoteWord + "\"" + " + " + self.translate_parameters(parameters=variableRef)
- elif varRefMatch :
- resultString = resultString + "\"" + quoteWord + "\"" + " + " + varRefMatch.group(1)
+ quoteWord = stringWidVariableMatch.group( 1 )
+ variableRef = stringWidVariableMatch.group( 2 )
+ varMatch = re.search( "PARAMS\[(.*)\]|STEP\[(.*)\]|TOPO\[(.*)\]|CASE\[(.*)\]", variableRef, flags=0 )
+ varRefMatch = re.search( "\<(\w+)\>", variableRef, flags=0 )
+ if varMatch:
+ resultString = resultString + "\"" + quoteWord + "\"" + " + " + self.translate_parameters( parameters=variableRef )
+ elif varRefMatch:
+ resultString = resultString + "\"" + quoteWord + "\"" + " + " + varRefMatch.group( 1 )
elif varRefMatch:
- resultString = resultString + varRefMatch.group(1)
- else :
- print "\nError : Syntax error , Not defined way to give log message" + args["MESSAGE"]
+ resultString = resultString + varRefMatch.group( 1 )
+ else:
+ print "\nError : Syntax error , Not defined way to give log message" + args[ "MESSAGE" ]
return resultString
- def translate_assertion(self,**assertStatement):
- '''
+ def translate_assertion( self, **assertStatement ):
+ """
This will translate the ASSERT <value1> <COMPARISON OPERATOR> <value2> into python
equivalent to resultString and returns resultString
- '''
- args = self.parse_args(["LEFTVALUE","OPERATOR","RIGHTVALUE","ONPASS","ONFAIL"],**assertStatement)
+ """
+ args = self.parse_args( [ "LEFTVALUE", "OPERATOR", "RIGHTVALUE", "ONPASS", "ONFAIL" ], **assertStatement )
resultString = ''
# convert the statement here
- notOperatorMatch = re.search("NOT\s+(.*)",args["OPERATOR"],flags=0)
- notOperatorSymbMatch = re.search("\!(.*)",args["OPERATOR"],flags=0)
+ notOperatorMatch = re.search( "NOT\s+(.*)", args[ "OPERATOR" ], flags=0 )
+ notOperatorSymbMatch = re.search( "\!(.*)", args[ "OPERATOR" ], flags=0 )
operator = ''
- lastresultMatch = re.match("LAST_RESULT",args["RIGHTVALUE"],flags=0)
- lastresponseMatch = re.match("LAST_RESPONSE",args["RIGHTVALUE"],flags=0)
- if lastresultMatch :
+ lastresultMatch = re.match( "LAST_RESULT", args[ "RIGHTVALUE" ], flags=0 )
+ lastresponseMatch = re.match( "LAST_RESPONSE", args[ "RIGHTVALUE" ], flags=0 )
+ if lastresultMatch:
operator = "main.last_result"
- elif lastresponseMatch :
+ elif lastresponseMatch:
operator = "main.last_response"
- else :
- operator = args["RIGHTVALUE"]
+ else:
+ operator = args[ "RIGHTVALUE" ]
- if args["OPERATOR"] == None or args["OPERATOR"] == "" :
+ if args[ "OPERATOR" ] is None or args[ "OPERATOR" ] == "":
print "\n Error : Operator has not been specified !!!"
elif notOperatorMatch or notOperatorSymbMatch:
- operators = notOperatorMatch.group(1) if notOperatorMatch else notOperatorSymbMatch.group(1)
- operators = self.translate_operator(operator=operators)
- if self.grtrOrLssr == 0 :
+ operators = notOperatorMatch.group( 1 ) if notOperatorMatch else notOperatorSymbMatch.group( 1 )
+ operators = self.translate_operator( operator=operators )
+ if self.grtrOrLssr == 0:
resultString = resultString + "utilities.assert_not_" + operators + "(expect=" +\
- self.translate_response_result(operator=args["RIGHTVALUE"]) + ",actual=" + self.translate_response_result(operator=args["LEFTVALUE"]) +\
- ",onpass=" + self.translate_assertMessage(message=args["ONPASS"]) +\
- ",onfail=" + self.translate_assertMessage(message=args["ONFAIL"]) + ")"
- else :
+ self.translate_response_result( operator=args[ "RIGHTVALUE" ] ) + ",actual=" + self.translate_response_result( operator=args[ "LEFTVALUE" ] ) +\
+ ",onpass=" + self.translate_assertMessage( message=args[ "ONPASS" ] ) +\
+ ",onfail=" + self.translate_assertMessage( message=args[ "ONFAIL" ] ) + ")"
+ else:
resultString = resultString + "utilities.assert_not_" + operators + "(expect=" +\
- self.translate_response_result(operator=args["LEFTVALUE"]) + ",actual=" + self.translate_response_result(operator=args["RIGHTVALUE"]) +\
- ",onpass=" + self.translate_assertMessage(message=args["ONPASS"]) +\
- ",onfail=" + self.translate_assertMessage(message=args["ONFAIL"]) + ")"
+ self.translate_response_result( operator=args[ "LEFTVALUE" ] ) + ",actual=" + self.translate_response_result( operator=args[ "RIGHTVALUE" ] ) +\
+ ",onpass=" + self.translate_assertMessage( message=args[ "ONPASS" ] ) +\
+ ",onfail=" + self.translate_assertMessage( message=args[ "ONFAIL" ] ) + ")"
- else :
- operators = self.translate_operator(operator=args["OPERATOR"])
- if self.grtrOrLssr == 0 :
+ else:
+ operators = self.translate_operator( operator=args[ "OPERATOR" ] )
+ if self.grtrOrLssr == 0:
resultString = resultString + "utilities.assert_" + operators + "(expect=" +\
- self.translate_response_result(operator=args["RIGHTVALUE"]) +\
- ",actual=" + self.translate_response_result(operator=args["LEFTVALUE"]) +\
- ",onpass=" + self.translate_assertMessage(message=args["ONPASS"]) +\
- ",onfail=" + self.translate_assertMessage(message=args["ONFAIL"]) + ")"
- else :
+ self.translate_response_result( operator=args[ "RIGHTVALUE" ] ) +\
+ ",actual=" + self.translate_response_result( operator=args[ "LEFTVALUE" ] ) +\
+ ",onpass=" + self.translate_assertMessage( message=args[ "ONPASS" ] ) +\
+ ",onfail=" + self.translate_assertMessage( message=args[ "ONFAIL" ] ) + ")"
+ else:
resultString = resultString + "utilities.assert_" + operators + "(expect=" +\
- self.translate_response_result(operator=args["LEFTVALUE"]) +\
- ",actual=" + self.translate_response_result(operator=args["RIGHTVALUE"]) +\
- ",onpass=" + self.translate_assertMessage(message=args["ONPASS"]) +\
- ",onfail=" + self.translate_assertMessage(message=args["ONFAIL"]) + ")"
-
+ self.translate_response_result( operator=args[ "LEFTVALUE" ] ) +\
+ ",actual=" + self.translate_response_result( operator=args[ "RIGHTVALUE" ] ) +\
+ ",onpass=" + self.translate_assertMessage( message=args[ "ONPASS" ] ) +\
+ ",onfail=" + self.translate_assertMessage( message=args[ "ONFAIL" ] ) + ")"
return resultString
- def translate_response_result(self,**operatorStatement):
- '''
+ def translate_response_result( self, **operatorStatement ):
+ """
It will translate the LAST_RESPONSE or LAST_RESULT statement into its equivalent.
It returns the translate form in resulString.
- '''
- args = self.parse_args(["OPERATOR"],**operatorStatement)
+ """
+ args = self.parse_args( [ "OPERATOR" ], **operatorStatement )
resultString = ''
- lastResultMatch = re.match("LAST_RESULT",args["OPERATOR"],flags=0)
- lastResponseMatch = re.match("LAST_RESPONSE",args["OPERATOR"],flags=0)
- if lastResultMatch :
+ lastResultMatch = re.match( "LAST_RESULT", args[ "OPERATOR" ], flags=0 )
+ lastResponseMatch = re.match( "LAST_RESPONSE", args[ "OPERATOR" ], flags=0 )
+ if lastResultMatch:
resultString = resultString + "main.last_result"
elif lastResponseMatch:
resultString = resultString + "main.last_response"
- else :
- resultString = resultString + args["OPERATOR"]
+ else:
+ resultString = resultString + args[ "OPERATOR" ]
return resultString
-
- def translate_assertMessage(self,**messageStatement) :
- '''
+ def translate_assertMessage( self, **messageStatement ):
+ """
This API will facilitate the translation of assert ONPASS or ONFAIL messages . The message can be
a string or calling another API in OpenSpeak syntax.
It will return the translated message
- '''
- args = self.parse_args(["MESSAGE"],**messageStatement)
+ """
+ args = self.parse_args( [ "MESSAGE" ], **messageStatement )
- connectMatch = re.search("CONNECT\s+(\w+)\s+USING\s+(.*)",args["MESSAGE"],flags=0)
- disconnectMatch = re.search("DISCONNECT\s+(.*)",args["MESSAGE"],flags=0)
- ondoMatch = re.search("ON\s+(.*)\s+DO\s+(.*)",args["MESSAGE"],flags=0)
- paramsMatch = re.search("PARAMS\[(.*)\]|STEP\[(.*)\]|TOPO\[(.*)\]|CASE\[(.*)\]",args["MESSAGE"],flags=0)
- stringMatch = re.search("\"(.*)\"|\'(.*)\'",args["MESSAGE"],flags=0)
- variableMatch = re.search("\<(.*)\>",args["MESSAGE"],flags=0)
+ connectMatch = re.search( "CONNECT\s+(\w+)\s+USING\s+(.*)", args[ "MESSAGE" ], flags=0 )
+ disconnectMatch = re.search( "DISCONNECT\s+(.*)", args[ "MESSAGE" ], flags=0 )
+ ondoMatch = re.search( "ON\s+(.*)\s+DO\s+(.*)", args[ "MESSAGE" ], flags=0 )
+ paramsMatch = re.search( "PARAMS\[(.*)\]|STEP\[(.*)\]|TOPO\[(.*)\]|CASE\[(.*)\]", args[ "MESSAGE" ], flags=0 )
+ stringMatch = re.search( "\"( .* )\"|\'(.*)\'", args[ "MESSAGE" ], flags=0 )
+ variableMatch = re.search( "\<(.*)\>", args[ "MESSAGE" ], flags=0 )
resultString = ''
- if connectMatch :
- resultString = resultString + self.translate_connect(component=connectMatch.group(1),
- arguments=connectMatch.group(2) )
- elif disconnectMatch :
- resultString = resultString + self.translate_disconnect(component=disconnectMatch.group(1))
- elif ondoMatch :
- resultString = resultString + self.translate_onDOAs(component=ondoMatch.group(1),
- action=ondoMatch.group(2))
- elif paramsMatch :
- resultString = resultString + self.translate_parameters(parameters=args["MESSAGE"])
- elif stringMatch :
+ if connectMatch:
+ resultString = resultString + self.translate_connect( component=connectMatch.group( 1 ),
+ arguments=connectMatch.group( 2 ) )
+ elif disconnectMatch:
+ resultString = resultString + self.translate_disconnect( component=disconnectMatch.group( 1 ) )
+ elif ondoMatch:
+ resultString = resultString + self.translate_onDOAs( component=ondoMatch.group( 1 ),
+ action=ondoMatch.group( 2 ) )
+ elif paramsMatch:
+ resultString = resultString + self.translate_parameters( parameters=args[ "MESSAGE" ] )
+ elif stringMatch:
resultString = resultString + "\"" + stringMatch.group(1) + "\""
- elif variableMatch :
- resultString = resultString + variableMatch.group(1)
- elif args["MESSAGE"] == None :
+ elif variableMatch:
+ resultString = resultString + variableMatch.group( 1 )
+ elif args[ "MESSAGE" ] is None:
print "\n Error : Please pass a message or action for assertion "
return resultString
- def translate_operator(self,**operatorStatement) :
- '''
+ def translate_operator( self, **operatorStatement ):
+ """
It will translate the operator for assertion , by ensuring against given arguments.
It will return the translated assertion operator.
- '''
- args = self.parse_args(["OPERATOR"],**operatorStatement)
+ """
+ args = self.parse_args( [ "OPERATOR" ], **operatorStatement )
resultString = ''
- equalsMatch = re.match("EQUALS$|==$",args["OPERATOR"],flags=0)
- greaterMatch = re.match("GREATER\s+THAN$|>$",args["OPERATOR"],flags=0)
- lesserMatch = re.match("LESSER\s+THAN$|<$",args["OPERATOR"],flags=0)
- stringMatch = re.match("MATCHES|~$",args["OPERATOR"],flags=0)
- greaterEqualMatch = re.match("GREATER\s+THAN\s+OR\s+EQUALS$|>=$",args["OPERATOR"],flags=0)
- lesserEqualMatch = re.match("LESSER\s+THAN\s+OR\s+EQUALS$|<=$",args["OPERATOR"],flags=0)
- if equalsMatch :
+ equalsMatch = re.match( "EQUALS$|==$", args[ "OPERATOR" ], flags=0 )
+ greaterMatch = re.match( "GREATER\s+THAN$|>$", args[ "OPERATOR" ], flags=0 )
+ lesserMatch = re.match( "LESSER\s+THAN$|<$", args[ "OPERATOR" ], flags=0 )
+ stringMatch = re.match( "MATCHES|~$", args[ "OPERATOR" ], flags=0 )
+ greaterEqualMatch = re.match( "GREATER\s+THAN\s+OR\s+EQUALS$|>=$", args[ "OPERATOR" ], flags=0 )
+ lesserEqualMatch = re.match( "LESSER\s+THAN\s+OR\s+EQUALS$|<=$", args[ "OPERATOR" ], flags=0 )
+ if equalsMatch:
resultString = resultString + "equals"
- elif greaterMatch :
+ elif greaterMatch:
self.grtrOrLssr = self.grtrOrLssr + 1
resultString = resultString + "greater"
- elif lesserMatch :
+ elif lesserMatch:
self.grtrOrLssr = self.grtrOrLssr + 1
resultString = resultString + "lesser"
- elif stringMatch :
+ elif stringMatch:
resultString = resultString + "matches"
elif greaterEqualMatch:
resultString = resultString + "greater_equals"
- elif lesserEqualMatch :
+ elif lesserEqualMatch:
resultString = resultString + "lesser_equals"
- else :
+ else:
print "\n Error: Given Operator is not listed for assertion"
return resultString
- def translate_store(self,**storeStatement):
- '''
+ def translate_store( self, **storeStatement ):
+ """
This will translate the STORE <variable> IN <value> or <variable> = <value>
into python equivalent to resultString and returns resultString
- '''
- args = self.parse_args(["VARIABLE","VALUE"],**storeStatement)
+ """
+ args = self.parse_args( [ "VARIABLE", "VALUE" ], **storeStatement )
resultString = ''
# convert the statement here
- ondoMatch = re.match("^\s*ON\s+(.*)\s+DO\s+(.*)",args["VALUE"],flags=0)
- paramsMatch = re.match("^\s*PARAMS\[(.*)\]|STEP\[(.*)\]|TOPO\[(.*)\]|CASE\[(.*)\]|LAST_RESULT|LAST_RESPONSE",args["VALUE"],flags=0)
- if paramsMatch :
- argString = self.translate_parameters(parameters=args["VALUE"])
- resultString = args["VARIABLE"] + " = " + argString
- elif ondoMatch :
- resultString = args["VARIABLE"] + " = " + self.translate_onDOAs(component=ondoMatch.group(1),action=ondoMatch.group(2))
- else :
- resultString = args["VARIABLE"] + " = " + args["VALUE"]
-
+ ondoMatch = re.match( "^\s*ON\s+(.*)\s+DO\s+(.*)", args[ "VALUE" ], flags=0 )
+ paramsMatch = re.match( "^\s*PARAMS\[(.*)\]|STEP\[(.*)\]|TOPO\[(.*)\]|CASE\[(.*)\]|LAST_RESULT|LAST_RESPONSE", args[ "VALUE" ], flags=0 )
+ if paramsMatch:
+ argString = self.translate_parameters( parameters=args[ "VALUE" ] )
+ resultString = args[ "VARIABLE" ] + " = " + argString
+ elif ondoMatch:
+ resultString = args[ "VARIABLE" ] + " = " + self.translate_onDOAs( component=ondoMatch.group( 1 ), action=ondoMatch.group( 2 ) )
+ else:
+ resultString = args[ "VARIABLE" ] + " = " + args[ "VALUE" ]
return resultString
- def translate_disconnect(self,**disconnectStatement):
- '''
+ def translate_disconnect( self, **disconnectStatement ):
+ """
This will translate the DISCONNECT <component_name> into python
equivalent to resultString and returns resultString
- '''
- args = self.parse_args(["COMPONENT"],**disconnectStatement)
+ """
+ args = self.parse_args( [ "COMPONENT" ], **disconnectStatement )
resultString = ''
# convert the statement here
- resultString = "main." + args["COMPONENT"] + ".disconnect()"
+ resultString = "main." + args[ "COMPONENT" ] + ".disconnect()"
return resultString
- def translate_onDOAs(self,**onDoStatement):
- '''
+ def translate_onDOAs( self, **onDoStatement ):
+ """
This will translate the ON <component> DO <action> USING <arg1> AS <value1>,<arg2> AS <value2>
into python equivalent to resultString and returns resultString
- '''
- args = self.parse_args(["COMPONENT","ACTION","ARGUMENTS"],**onDoStatement)
+ """
+ args = self.parse_args( [ "COMPONENT", "ACTION", "ARGUMENTS" ], **onDoStatement )
subString = ''
- usingMatch = re.match("\s*(.*)\s+USING\s+(.*)",args["ACTION"],flags=0)
+ usingMatch = re.match( "\s*(.*)\s+USING\s+(.*)", args[ "ACTION" ], flags=0 )
action = ''
- if usingMatch :
- action = usingMatch.group(1)
- arguments = usingMatch.group(2)
- subString = self.translate_usingas(arguments=arguments)
+ if usingMatch:
+ action = usingMatch.group( 1 )
+ arguments = usingMatch.group( 2 )
+ subString = self.translate_usingas( arguments=arguments )
- else :
- andCheck = re.search ("(.*)\s+AND\s+(.*)",args["ACTION"],flags=0)
+ else:
+ andCheck = re.search( "(.*)\s+AND\s+(.*)", args[ "ACTION" ], flags=0 )
action = action + "()"
if andCheck:
- action = andCheck.group(1) + "()"
- subString = subString + self.handle_conjuction(statement=andCheck.group(2))
- else :
- action = args["ACTION"]
+ action = andCheck.group( 1 ) + "()"
+ subString = subString + self.handle_conjuction( statement=andCheck.group( 2 ) )
+ else:
+ action = args[ "ACTION" ]
action = action + "()"
# convert the statement here
- resultString = "main." + args["COMPONENT"] + "." + action + subString
+ resultString = "main." + args[ "COMPONENT" ] + "." + action + subString
return resultString
-
- def handle_conjuction(self,**conjuctStatement):
- '''
+ def handle_conjuction( self, **conjuctStatement ):
+ """
This will handle the conjuctions
- '''
-
- args = self.parse_args(["STATEMENT"],**conjuctStatement)
+ """
+ args = self.parse_args( [ "STATEMENT" ], **conjuctStatement )
subSentence = ''
- storeMatch = re.match("\s*STORE\s+(.*)\s+IN\s+(.*)",args["STATEMENT"],flags=0)
- assertMatch = re.match("\s*ASSERT\s+(\w+)\s+(.*)\s+(.*)\s+ONPASS\s+(.*)\s+ONFAIL\s+(.*)",args["STATEMENT"],flags=0)
- if storeMatch :
- subSentence = "\n" + " " * 8 + self.translate_store(variable=storeMatch.group(2),
- value=storeMatch.group(1))
- elif assertMatch :
- subSentence = "\n" + " " * 8 + self.translate_assertion(leftvalue=assertMatch.group(1),
- operator=assertMatch.group(2),
- rightvalue=assertMatch.group(3),
- onpass=assertMatch.group(4),
- onfail=assertMatch.group(5))
+ storeMatch = re.match( "\s*STORE\s+(.*)\s+IN\s+(.*)", args[ "STATEMENT" ], flags=0 )
+ assertMatch = re.match( "\s*ASSERT\s+(\w+)\s+(.*)\s+(.*)\s+ONPASS\s+(.*)\s+ONFAIL\s+(.*)", args[ "STATEMENT" ], flags=0 )
+ if storeMatch:
+ subSentence = "\n" + " " * 8 + self.translate_store( variable=storeMatch.group( 2 ),
+ value=storeMatch.group( 1 ) )
+ elif assertMatch:
+ subSentence = "\n" + " " * 8 + self.translate_assertion( leftvalue=assertMatch.group( 1 ),
+ operator=assertMatch.group( 2 ),
+ rightvalue=assertMatch.group( 3 ),
+ onpass=assertMatch.group( 4 ),
+ onfail=assertMatch.group( 5 ) )
return subSentence
- def translate_usingas(self,**argumentAS) :
- '''
+ def translate_usingas( self, **argumentAS ):
+ """
This will tranlate USING argument AS value Statement into equivalent argument passing.
It will return translated form into resultString
- '''
- args = self.parse_args(["ARGUMENTS"],**argumentAS)
+ """
+ args = self.parse_args( [ "ARGUMENTS" ], **argumentAS )
resultString = ''
argsList = []
subString = ''
subSentence = ''
line = ''
- andCheck = re.search ("(.*)\s+AND\s+(.*)",args["ARGUMENTS"],flags=0)
+ andCheck = re.search( "(.*)\s+AND\s+(.*)", args[ "ARGUMENTS" ], flags=0 )
if andCheck:
- line = andCheck.group(1)
- subSentence = self.handle_conjuction(statement=andCheck.group(2))
- else :
- line = args["ARGUMENTS"]
+ line = andCheck.group( 1 )
+ subSentence = self.handle_conjuction( statement=andCheck.group( 2 ) )
+ else:
+ line = args[ "ARGUMENTS" ]
+ argsMatch = re.search( "(.*),(.*)", line, flags=0 )
-
- argsMatch = re.search("(.*),(.*)",line,flags=0)
-
-
- if args["ARGUMENTS"] == None or args["ARGUMENTS"] == '' :
+ if args[ "ARGUMENTS" ] is None or args[ "ARGUMENTS" ] == '':
subString = ''
- elif argsMatch :
+ elif argsMatch:
- argsList = line.split(",")
- for index, arguments in enumerate(argsList):
- argMatch = re.search("(.*)\s+AS\s+(.*)",arguments,flags=0)
+ argsList = line.split( "," )
+ for index, arguments in enumerate( argsList ):
+ argMatch = re.search( "(.*)\s+AS\s+(.*)", arguments, flags=0 )
if argMatch:
- argsKey = argMatch.group(1)
- argsValue = argMatch.group(2)
- paramsMatch = re.search("PARAMS\[(.*)\]|STEP\[(.*)\]|TOPO\[(.*)\]|CASE\[(.*)\]|LAST_RESPONSE|LAST_RESULT",argsValue,flags=0)
- if not paramsMatch :
- if index == len(argsList) - 1 :
- subString = subString + argsKey + "=" + argsValue
- else :
- subString = subString + argsKey + "=" + argsValue + ","
- else :
- argString = self.translate_parameters(parameters=argsValue)
- if index == len(argsList) - 1 :
- subString = subString + argsKey + "=" + argString
- else :
- subString = subString + argsKey + "=" + argString + ","
- else :
- if index == len(argsList) - 1 :
- subString = subString + arguments
- else :
+ argsKey = argMatch.group( 1 )
+ argsValue = argMatch.group( 2 )
+ paramsMatch = re.search( "PARAMS\[(.*)\]|STEP\[(.*)\]|TOPO\[(.*)\]|CASE\[(.*)\]|LAST_RESPONSE|LAST_RESULT", argsValue, flags=0 )
+ if not paramsMatch:
+ if index == len( argsList ) - 1:
+ subString = subString + argsKey + "=" + argsValue
+ else:
+ subString = subString + argsKey + "=" + argsValue + ","
+ else:
+ argString = self.translate_parameters( parameters=argsValue )
+ if index == len( argsList ) - 1:
+ subString = subString + argsKey + "=" + argString
+ else:
+ subString = subString + argsKey + "=" + argString + ","
+ else:
+ if index == len( argsList ) - 1:
+ subString = subString + arguments
+ else:
subString = subString + arguments + ","
- else :
- argMatch = re.search("(.*)\s+AS\s+(.*)",args["ARGUMENTS"],flags=0)
+ else:
+ argMatch = re.search( "(.*)\s+AS\s+(.*)", args[ "ARGUMENTS" ], flags=0 )
if argMatch:
- argsKey = argMatch.group(1)
- argsValue = argMatch.group(2)
- paramsMatch = re.search("PARAMS\[(.*)\]|STEP\[(.*)\]|TOPO\[(.*)\]|CASE\[(.*)\]|LAST_RESPONSE|LAST_RESULT",argsValue,flags=0)
- if not paramsMatch :
- subString = subString + argsKey + "=" + argsValue
- else :
- argString = self.translate_parameters(parameters=argsValue)
- subString = subString + argsKey + "=" + argString
- else :
- paramsMatch = re.match("PARAMS\[(.*)\]|STEP\[(.*)\]|TOPO\[(.*)\]|CASE\[(.*)\]|LAST_RESPONSE|LAST_RESULT",line,flags=0)
- if paramsMatch :
- subString = subString + self.translate_parameters(parameters=line)
- else :
- subString = subString + line
- resultString = "(" + subString + ")"+ subSentence
+ argsKey = argMatch.group( 1 )
+ argsValue = argMatch.group( 2 )
+ paramsMatch = re.search( "PARAMS\[(.*)\]|STEP\[(.*)\]|TOPO\[(.*)\]|CASE\[(.*)\]|LAST_RESPONSE|LAST_RESULT", argsValue, flags=0 )
+ if not paramsMatch:
+ subString = subString + argsKey + "=" + argsValue
+ else:
+ argString = self.translate_parameters( parameters=argsValue )
+ subString = subString + argsKey + "=" + argString
+ else:
+ paramsMatch = re.match( "PARAMS\[(.*)\]|STEP\[(.*)\]|TOPO\[(.*)\]|CASE\[(.*)\]|LAST_RESPONSE|LAST_RESULT", line, flags=0 )
+ if paramsMatch:
+ subString = subString + self.translate_parameters( parameters=line )
+ else:
+ subString = subString + line
+ resultString = "(" + subString + ")" + subSentence
return resultString
-
- def translate_connect(self,**connectStatement):
- '''
+ def translate_connect( self, **connectStatement ):
+ """
This will translate the CONNECT <component_name> USING1 <arg1> AS <value1>, <arg2> AS <value2>
into python equivalent to resultString and returns resultString
- '''
- args = self.parse_args(["COMPONENT","ARGUMENTS"],**connectStatement)
+ """
+ args = self.parse_args( [ "COMPONENT", "ARGUMENTS" ], **connectStatement )
resultString = ''
- subString = self.translate_usingas(arguments=args["ARGUMENTS"])
+ subString = self.translate_usingas( arguments=args[ "ARGUMENTS" ] )
# convert the statement here
- resultString = "main." + args["COMPONENT"] + ".connect(" + subString + ")"
+ resultString = "main." + args[ "COMPONENT" ] + ".connect(" + subString + ")"
return resultString
-
- def translate_parameters(self,**parameterStatement):
- '''
+ def translate_parameters( self, **parameterStatement ):
+ """
This will translate the OpenSpeak Case and Params parameters into python equivalent
to resultString and returns resultString
- '''
- args = self.parse_args(["PARAMETERS"],**parameterStatement)
- argument = args["PARAMETERS"]
+ """
+ args = self.parse_args( [ "PARAMETERS" ], **parameterStatement )
+ argument = args[ "PARAMETERS" ]
resultString = ''
- ### match arguments
- paramsMatch = re.search("PARAMS((\[(.*)\])*)",argument,flags=0)
- stepsMatch = re.search("STEP((\[(.*)\])*)",argument,flags=0)
- casesMatch = re.search("CASE((\[(.*)\])*)",argument,flags=0)
- topoMatch = re.search("TOPO((\[(.*)\])*)",argument,flags=0)
- lastResultMatch = re.match("LAST_RESULT",argument,flags=0)
- lastResponseMatch = re.match("LAST_RESPONSE",argument,flags=0)
+ # match arguments
+ paramsMatch = re.search( "PARAMS((\[(.*)\])*)", argument, flags=0 )
+ stepsMatch = re.search( "STEP((\[(.*)\])*)", argument, flags=0 )
+ casesMatch = re.search( "CASE((\[(.*)\])*)", argument, flags=0 )
+ topoMatch = re.search( "TOPO((\[(.*)\])*)", argument, flags=0 )
+ lastResultMatch = re.match( "LAST_RESULT", argument, flags=0 )
+ lastResponseMatch = re.match( "LAST_RESPONSE", argument, flags=0 )
# convert the statement here
- if paramsMatch :
- params = paramsMatch.group(1)
- resultString = resultString + "main.params" + self._argsCheck(checkvar=params)
- elif stepsMatch :
- resultString = resultString +"main.params[\'" + self.CurrentCase +\
- "\'][\'STEP" + str(self.CurrentStep) + "\']" +\
- self._argsCheck(checkvar=stepsMatch.group(1))
- elif casesMatch :
+ if paramsMatch:
+ params = paramsMatch.group( 1 )
+ resultString = resultString + "main.params" + self._argsCheck( checkvar=params )
+ elif stepsMatch:
+ resultString = resultString + "main.params[\'" + self.CurrentCase +\
+ "\'][\'STEP" + str( self.CurrentStep ) + "\']" +\
+ self._argsCheck( checkvar=stepsMatch.group( 1 ) )
+ elif casesMatch:
resultString = resultString + "main.params[\'" + self.CurrentCase + "\']" +\
- self._argsCheck(checkvar=casesMatch.group(1))
- elif topoMatch :
+ self._argsCheck( checkvar=casesMatch.group( 1 ) )
+ elif topoMatch:
resultString = resultString + "main.componentDictionary" +\
- self._argsCheck(checkvar=topoMatch.group(1))
- elif lastResultMatch :
+ self._argsCheck( checkvar=topoMatch.group( 1 ) )
+ elif lastResultMatch:
resultString = resultString + "main.last_result"
- elif lastResponseMatch :
+ elif lastResponseMatch:
resultString = resultString + "main.last_response"
return resultString
- def _argsCheck(self,**args):
- ''' This API will check if given argument is varibale reference or String and will translate accordingly.
+ def _argsCheck( self, **args ):
+ """ This API will check if given argument is varibale reference or String and will translate accordingly.
It will return the tanslate form in resultString.
- '''
- args = self.parse_args(["CHECKVAR"],**args)
- params = args["CHECKVAR"]
- argsList = params.split("]")
+ """
+ args = self.parse_args( [ "CHECKVAR" ], **args )
+ params = args[ "CHECKVAR" ]
+ argsList = params.split( "]" )
resultString = ''
- del argsList[len(argsList) - 1]
- for index,paramArgs in enumerate(argsList) :
- argsWidVariable = re.search("(\"|\')\s*(\w+)\s*(\'|\")",paramArgs,flags=0)
- if argsWidVariable :
+ del argsList[ len( argsList ) - 1 ]
+ for index, paramArgs in enumerate( argsList ):
+ argsWidVariable = re.search( "(\"|\')\s*(\w+)\s*(\'|\")", paramArgs, flags=0 )
+ if argsWidVariable:
resultString = resultString + "[\'" + argsWidVariable.group(2) + "\']"
- else :
+ else:
resultString = resultString + paramArgs + "]"
return resultString
- def translate_step(self,**stepStatement):
- '''
+ def translate_step( self, **stepStatement ):
+ """
This will translate the STEP "DO SOMETHING HERE" into python equivalent
to resultString and returns resultString
- '''
- args = self.parse_args(["STEP"],**stepStatement)
+ """
+ args = self.parse_args( [ "STEP" ], **stepStatement )
resultString = ''
resultString = "main.step(\"" + args["STEP"] + "\")"
# convert the statement here
return resultString
-
- def translate_comment(self,**commentStatement):
- '''
+ def translate_comment( self, **commentStatement ):
+ """
This will translate the COMMENT "DO SOMETHING HERE" into python equivalent
to resultString and returns resultString
- '''
- args = self.parse_args(["COMMENT"],**commentStatement)
+ """
+ args = self.parse_args( [ "COMMENT" ], **commentStatement )
resultString = ''
- resultString = "#" + args["COMMENT"]
+ resultString = "#" + args[ "COMMENT" ]
# convert the statement here
return resultString
- def translate_testcase_name(self,**nameStatement):
- '''
+ def translate_testcase_name( self, **nameStatement ):
+ """
This method will convert NAME "<Testcase_name>" into python equivalent statement
to resultString and returns resultString
- '''
- args = self.parse_args(["TESTNAME"],**nameStatement)
+ """
+ args = self.parse_args( [ "TESTNAME" ], **nameStatement )
resultString = ''
- resultString = "main.case(\"" + args["TESTNAME"] + "\")"
+ resultString = "main.case(\"" + args["TESTNAME"] + "\")"
# convert the statement here
return resultString
-
- def translate_case_block(self,**caseBlock):
- '''
+ def translate_case_block( self, **caseBlock ):
+ """
This method will translate the case block in test script .
It returns the translated equivalent python code for test script
- '''
- args = self.parse_args(["CASENUMBER"],**caseBlock)
+ """
+ args = self.parse_args( [ "CASENUMBER" ], **caseBlock )
resultString = ""
- resultString = "def CASE" + str(args["CASENUMBER"]) + "(self,main) :\n"
+ resultString = "def CASE" + str( args[ "CASENUMBER" ] ) + "(self,main) :\n"
# process the caseBlock List translate all statements underlying the given case
return resultString
-
-
- def translate_loop_block(self,*loopBlock):
- '''
+ def translate_loop_block( self, *loopBlock ):
+ """
This method will translate for loop block into its equivalent python code.
Whole loop block will be passed into loopBlock List.
It returns the transalted reuslt as a string.
- '''
+ """
resultString = ''
# process the loopBlock List translate all statements underlying the given loop block
return resultString
-
- def translate_conjuction(self,conjuctionStatement):
- '''
+ def translate_conjuction( self, conjuctionStatement ):
+ """
This will translate the AND conjuction statements into python equivalent
to resultString and returns resultString
- '''
+ """
resultString = ''
# convert the statement here
return resultString
-
- def parse_args(self,args, **kwargs):
- '''
- It will accept the (key,value) pair and will return the (key,value) pairs with keys in uppercase.
- '''
+ def parse_args( self, args, **kwargs ):
+ """
+ It will accept the ( key,value ) pair and will return the ( key,value ) pairs with keys in uppercase.
+ """
newArgs = {}
- for key,value in kwargs.iteritems():
- #currentKey = str.upper(key)
- if isinstance(args,list) and str.upper(key) in args:
+ for key, value in kwargs.iteritems():
+ # currentKey = str.upper( key )
+ if isinstance( args, list ) and str.upper( key ) in args:
for each in args:
- if each==str.upper(key):
- newArgs [str(each)] = value
- elif each != str.upper(key) and (newArgs.has_key(str(each)) == False ):
- newArgs[str(each)] = None
-
-
+ if each == str.upper( key ):
+ newArgs[ str( each ) ] = value
+ elif each != str.upper( key ) and not ( ( str( each ) in newArgs ) ):
+ newArgs[ str( each ) ] = None
return newArgs
diff --git a/TestON/core/teston.py b/TestON/core/teston.py
index 89315dc..d6ebc89 100644
--- a/TestON/core/teston.py
+++ b/TestON/core/teston.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
-'''
+"""
Created on 22-Oct-2012
-Copyright 2012 Open Networking Foundation (ONF)
+Copyright 2012 Open Networking Foundation ( ONF )
Please refer questions to either the onos test mailing list at <onos-test@onosproject.org>,
the System Testing Plans and Results wiki page at <https://wiki.onosproject.org/x/voMg>,
@@ -10,7 +10,7 @@
TestON is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -24,8 +24,7 @@
teston is the main module.
-'''
-
+"""
import sys
import getpass
import os
@@ -55,21 +54,24 @@
from core.utilities import Utilities
from core.Thread import Thread
+
class SkipCase( Exception ):
pass
+
class TestON:
- '''
+
+ """
TestON will initiate the specified test.
The main tasks are:
* Initiate the required Component handles for the test.
* Create Log file Handles.
- '''
+ """
def __init__( self, options ):
- '''
+ """
Initialise the component handles specified in the topology file of
the specified test.
- '''
+ """
# Initialization of the variables.
__builtin__.main = self
__builtin__.path = path
@@ -110,19 +112,19 @@
verifyOptions( options )
load_logger()
self.componentDictionary = {}
- self.componentDictionary = self.topology['COMPONENT']
+ self.componentDictionary = self.topology[ 'COMPONENT' ]
self.driversList = []
- if isinstance( self.componentDictionary, str):
+ if isinstance( self.componentDictionary, str ):
self.componentDictionary = dict( self.componentDictionary )
for component in self.componentDictionary:
- self.driversList.append( self.componentDictionary[component]['type'] )
+ self.driversList.append( self.componentDictionary[ component ][ 'type' ] )
self.driversList = list( set( self.driversList ) ) # Removing duplicates.
# Checking the test_target option set for the component or not
if isinstance( self.componentDictionary, dict ):
for component in self.componentDictionary.keys():
- if 'test_target' in self.componentDictionary[component].keys():
+ if 'test_target' in self.componentDictionary[ component ].keys():
self.test_target = component
# Checking for the openspeak file and test script
@@ -136,20 +138,20 @@
components_connect_order = {}
if isinstance( self.componentDictionary, dict ):
for component in self.componentDictionary.keys():
- if 'connect_order' not in self.componentDictionary[component].keys():
- self.componentDictionary[component]['connect_order'] = str( self.get_random() )
- components_connect_order[component] = eval( self.componentDictionary[component]['connect_order'] )
+ if 'connect_order' not in self.componentDictionary[ component ].keys():
+ self.componentDictionary[ component ][ 'connect_order' ] = str( self.get_random() )
+ components_connect_order[ component ] = eval( self.componentDictionary[ component ][ 'connect_order' ] )
# Ordering components based on the connect order.
ordered_component_list = sorted( components_connect_order,
- key=lambda key: components_connect_order[key] )
+ key=lambda key: components_connect_order[ key ] )
print ordered_component_list
for component in ordered_component_list:
self.componentInit( component )
def configparser( self ):
- '''
- It will parse the config file (teston.cfg) and return as dictionary
- '''
+ """
+ It will parse the config file ( teston.cfg ) and return as dictionary
+ """
matchFileName = re.match( r'(.*)\.cfg', self.configFile, re.M | re.I )
if matchFileName:
xml = open( self.configFile ).read()
@@ -162,57 +164,57 @@
print "There is no such file to parse " + self.configFile
def componentInit( self, component ):
- '''
+ """
This method will initialize specified component
- '''
+ """
global driver_options
self.initiated = False
self.log.info( "Creating component Handle: " + component )
driver_options = {}
- if 'COMPONENTS' in self.componentDictionary[component].keys():
- driver_options = dict( self.componentDictionary[component]['COMPONENTS'] )
- driver_options['name'] = component
- driverName = self.componentDictionary[component]['type']
- driver_options['type'] = driverName
+ if 'COMPONENTS' in self.componentDictionary[ component ].keys():
+ driver_options = dict( self.componentDictionary[ component ][ 'COMPONENTS' ] )
+ driver_options[ 'name' ] = component
+ driverName = self.componentDictionary[ component ][ 'type' ]
+ driver_options[ 'type' ] = driverName
classPath = self.getDriverPath( driverName.lower() )
driverModule = importlib.import_module( classPath )
driverClass = getattr( driverModule, driverName )
driverObject = driverClass()
- if "OCN" in self.componentDictionary[component]['host'] and\
+ if "OCN" in self.componentDictionary[ component ][ 'host' ] and\
main.onoscell:
- self.componentDictionary[component]['host'] = main.mnIP
+ self.componentDictionary[ component ][ 'host' ] = main.mnIP
- user_name = self.componentDictionary[component].get( 'user',
- getpass.getuser() )
- ip_address = self.componentDictionary[component].get( 'host',
- 'localhost' )
- pwd = self.componentDictionary[component].get( 'password',
- 'changeme' )
- port = self.componentDictionary[component].get( 'port' )
+ user_name = self.componentDictionary[ component ].get( 'user',
+ getpass.getuser() )
+ ip_address = self.componentDictionary[ component ].get( 'host',
+ 'localhost' )
+ pwd = self.componentDictionary[ component ].get( 'password',
+ 'changeme' )
+ port = self.componentDictionary[ component ].get( 'port' )
connect_result = driverObject.connect( user_name=user_name,
ip_address=ip_address,
pwd=pwd,
port=port,
- options=driver_options)
+ options=driver_options )
if not connect_result:
self.log.error( "Exiting from the test execution because connecting to the " +
component + " component failed." )
self.exit()
- vars( self )[component] = driverObject
+ vars( self )[ component ] = driverObject
self.initiated = True
return driverObject
def run( self ):
- '''
+ """
The Execution of the test script's cases listed in the Test params
file will be done here then update each test case result.
This method will return main.TRUE if it executed all the test cases
successfully, else will retun main.FALSE
- '''
+ """
self.testCaseResult = {}
self.TOTAL_TC = 0
self.TOTAL_TC_RUN = 0
@@ -270,12 +272,12 @@
self.CASERESULT = self.NORESULT
stopped = False
try:
- self.code[self.testCaseNumber]
+ self.code[ self.testCaseNumber ]
except KeyError:
self.log.error( "There is no Test-Case " + self.testCaseNumber )
return self.FALSE
self.stepCount = 0
- while self.stepCount < len( self.code[self.testCaseNumber].keys() ):
+ while self.stepCount < len( self.code[ self.testCaseNumber ].keys() ):
result = self.runStep( self.code, self.testCaseNumber )
if result == self.FALSE:
break
@@ -299,7 +301,7 @@
self.CASERESULT = self.TRUE
else:
self.CASERESULT = self.NORESULT
- self.testCaseResult[str( self.CurrentTestCaseNumber )] = self.CASERESULT
+ self.testCaseResult[ str( self.CurrentTestCaseNumber ) ] = self.CASERESULT
self.organizeResult( self.CurrentTestCaseNumber, self.CASERESULT )
self.logger.updateCaseResults( self )
self.log.wiki( "<p>" + self.caseExplanation + "</p>" )
@@ -350,7 +352,7 @@
# NOTE: This is needed to catch results of main.step()'s
# called inside functions or loops
self.stepResults = ( [], [], [], [] )
- exec code[testCaseNumber][step] in module.__dict__
+ exec code[ testCaseNumber ][ step ] in module.__dict__
self.stepCount = self.stepCount + 1
self.parseStepResults( testCaseNumber )
except SkipCase: # Raised in self.skipCase()
@@ -361,9 +363,9 @@
self.stepCache += "\t\t" + self.onFailMsg + "\n"
self.stepCount = self.stepCount + 1
return self.FALSE
- except StandardError as e:
+ except Exception as e:
try:
- stepNo = self.stepResults[0][ self.stepNumber - 1 ]
+ stepNo = self.stepResults[ 0 ][ self.stepNumber - 1 ]
except IndexError:
stepNo = "<IndexError>"
main.log.warn( "Error trying to get step number. " +
@@ -371,7 +373,7 @@
str( self.stepNumber ) + " and step " +
str( self.stepNumber + 1 ) )
try:
- stepName = self.stepResults[1][ self.stepNumber - 1 ]
+ stepName = self.stepResults[ 1 ][ self.stepNumber - 1 ]
except IndexError:
stepName = "<IndexError>"
self.log.error( "\nException in the following section of" +
@@ -401,7 +403,7 @@
if cli.stop:
cli.stop = False
self.TOTAL_TC_NORESULT = self.TOTAL_TC_NORESULT + 1
- self.testCaseResult[str( self.CurrentTestCaseNumber )] = "Stopped"
+ self.testCaseResult[ str( self.CurrentTestCaseNumber ) ] = "Stopped"
self.logger.updateCaseResults( self )
result = self.cleanup()
return self.FALSE
@@ -412,12 +414,12 @@
"""
try:
# Iterate through each of the steps and print them
- for index in range( len( self.stepResults[0] ) ):
+ for index in range( len( self.stepResults[ 0 ] ) ):
# stepResults = ( stepNo, stepName, stepResult, onFail )
- stepNo = self.stepResults[0][ index ]
- stepName = self.stepResults[1][ index ]
- stepResult = self.stepResults[2][ index ]
- onFail = self.stepResults[3][ index ]
+ stepNo = self.stepResults[ 0 ][ index ]
+ stepName = self.stepResults[ 1 ][ index ]
+ stepResult = self.stepResults[ 2 ][ index ]
+ onFail = self.stepResults[ 3 ][ index ]
self.stepCache += "\t" + str( testCaseNumber ) + "."
self.stepCache += str( stepNo ) + " "
self.stepCache += stepName + " - "
@@ -460,10 +462,10 @@
caseHeader = "\n" + "*" * 40 + "\nStart of Test Case" +\
str( self.CurrentTestCaseNumber ) + " : "
for driver in self.componentDictionary.keys():
- vars( self )[driver + 'log'].info( caseHeader )
+ vars( self )[ driver + 'log' ].info( caseHeader )
def addCaseFooter( self ):
- stepNo = self.stepResults[0][-2]
+ stepNo = self.stepResults[ 0 ][ -2 ]
if stepNo > 0:
previousStep = " " + str( self.CurrentTestCaseNumber ) + "." +\
str( stepNo ) + ": " + str( self.stepName )
@@ -474,10 +476,10 @@
str( self.CurrentTestCaseNumber ) + "\n" + "*" * 40 + "\n"
for driver in self.driversList:
- vars( self )[driver].write( stepHeader + "\n" + caseFooter )
+ vars( self )[ driver ].write( stepHeader + "\n" + caseFooter )
def cleanup( self ):
- '''
+ """
Print a summary of the current test's results then attempt to release
all the component handles and the close opened file handles.
@@ -486,7 +488,7 @@
This will return TRUE if all the component handles and log handles
closed properly, else return FALSE.
- '''
+ """
result = self.TRUE
lock = self.cleanupLock
if lock.acquire( False ):
@@ -497,12 +499,12 @@
self.logger.testSummary( self )
components = self.componentDictionary
for component in sorted( components,
- key=lambda item: components[item]['connect_order'],
+ key=lambda item: components[ item ][ 'connect_order' ],
reverse=True ):
try:
- tempObject = vars( self )[component]
+ tempObject = vars( self )[ component ]
print "Disconnecting from " + str( tempObject.name ) +\
- ": " + str( tempObject.__class__)
+ ": " + str( tempObject.__class__ )
tempObject.disconnect()
except KeyboardInterrupt:
pass
@@ -510,14 +512,14 @@
# Component not created yet
self.log.warn( "Could not find the component " +
str( component ) )
- except StandardError:
+ except Exception:
self.log.exception( "Exception while disconnecting from " +
str( component ) )
result = self.FALSE
# Closing all the driver's session files
for driver in self.componentDictionary.keys():
try:
- vars( self )[driver].close_log_handles()
+ vars( self )[ driver ].close_log_handles()
except KeyboardInterrupt:
pass
except KeyError:
@@ -525,7 +527,7 @@
self.log.warn( "Could not find the component " +
str( driver ) + " while trying to" +
" close log file" )
- except StandardError:
+ except Exception:
self.log.exception( "Exception while closing log files for " +
str( driver ) )
result = self.FALSE
@@ -543,41 +545,41 @@
return result
def pause( self ):
- '''
+ """
This function will pause the test's execution, and will continue after
user provide 'resume' command.
- '''
+ """
__builtin__.testthread.pause()
def onfail( self, *components ):
- '''
+ """
When test step failed, calling all the components onfail.
- '''
+ """
if not components:
try:
for component in self.componentDictionary.keys():
- tempObject = vars( self )[component]
+ tempObject = vars( self )[ component ]
result = tempObject.onfail()
- except StandardError as e:
+ except Exception as e:
print str( e )
result = self.FALSE
else:
try:
for component in components:
- tempObject = vars( self )[component]
+ tempObject = vars( self )[ component ]
result = tempObject.onfail()
- except StandardError as e:
+ except Exception as e:
print str( e )
result = self.FALSE
def getDriverPath( self, driverName ):
- '''
+ """
Based on the component 'type' specified in the params , this method
will find the absolute path, by recursively searching the name of
the component.
NOTE: This function requires the linux 'find' command.
- '''
+ """
import commands
cmd = "find " + drivers_path + " -name " + driverName + ".py"
@@ -602,66 +604,66 @@
return result
def step( self, stepDesc ):
- '''
+ """
The step information of the test-case will append to the logs.
- '''
+ """
previousStep = " " + str( self.CurrentTestCaseNumber ) + "." +\
str( self.stepNumber ) + ": " + str( self.stepName )
self.stepName = stepDesc
self.stepNumber += 1
- self.stepResults[0].append( self.stepNumber )
- self.stepResults[1].append( stepDesc )
- self.stepResults[2].append( self.NORESULT )
- self.stepResults[3].append( "No on fail message given" )
+ self.stepResults[ 0 ].append( self.stepNumber )
+ self.stepResults[ 1 ].append( stepDesc )
+ self.stepResults[ 2 ].append( self.NORESULT )
+ self.stepResults[ 3 ].append( "No on fail message given" )
stepName = " " + str( self.CurrentTestCaseNumber ) + "." +\
str( self.stepNumber ) + ": " + str( stepDesc )
- self.log.step(stepName)
+ self.log.step( stepName )
stepHeader = ""
line = "\n" + "-" * 45 + "\n"
if self.stepNumber > 1:
stepHeader = line + "End of Step " + previousStep + line
stepHeader += line + "Start of Step" + stepName + line
for driver in self.componentDictionary.keys():
- vars( self )[driver + 'log'].info( stepHeader )
+ vars( self )[ driver + 'log' ].info( stepHeader )
def case( self, testCaseName ):
- '''
+ """
Test's each test-case information will append to the logs.
- '''
+ """
self.CurrentTestCase = testCaseName
testCaseName = " " + str( testCaseName )
self.log.case( testCaseName )
caseHeader = testCaseName + "\n" + "*" * 40 + "\n"
for driver in self.componentDictionary.keys():
- vars( self )[driver + 'log'].info( caseHeader )
+ vars( self )[ driver + 'log' ].info( caseHeader )
def testDesc( self, description ):
- '''
+ """
Test description will append to the logs.
- '''
+ """
description = "Test Description : " + str( description )
self.log.info( description )
def _getTest( self ):
- '''
+ """
This method will parse the test script to find required test
information.
- '''
+ """
testFileHandler = open( main.testFile, 'r' )
testFileList = testFileHandler.readlines()
testFileHandler.close()
counter = 0
for index in range( len( testFileList ) ):
lineMatch = re.match( '\s+def CASE(\d+)(.*):',
- testFileList[index],
+ testFileList[ index ],
0 )
if lineMatch:
counter = counter + 1
self.TC_PLANNED = len( self.testcases_list )
def response_parser( self, response, return_format ):
- ''' It will load the default response parser '''
+ " It will load the default response parser "
response_dict = {}
response_dict = self.response_to_dict( response, return_format )
return_format_string = self.dict_to_return_format( response,
@@ -678,14 +680,14 @@
self.log.info( "Response is in 'JSON' format, converting to '" +
return_format + "' format" )
# Formatting the json string
- response = re.sub( r"{\s*'?(\w)", r'{"\1', response )
+ response = re.sub( r"{\s*'?(\w)", r'{ "\1', response )
response = re.sub( r",\s*'?(\w)", r',"\1', response )
response = re.sub( r"(\w)'?\s*:", r'\1":', response )
response = re.sub( r":\s*'(\w)'\s*([,}])", r':"\1"\2', response )
try:
import json
response_dict = json.loads( response )
- except StandardError:
+ except Exception:
self.log.exception( "Json Parser is unable to parse the string" )
return response_dict
elif ini_match:
@@ -704,21 +706,21 @@
response_dict = xmldict.xml_to_dict( "<response> " +
str( response ) +
" </response>" )
- except StandardError:
+ except Exception:
self.log.exception()
return response_dict
def dict_to_return_format( self, response, return_format, response_dict ):
if return_format == 'table':
- ''' Will return in table format'''
+ " Will return in table format"
to_do = "Call the table output formatter"
global response_table
response_table = '\n'
response_table = response_table + '\t'.join( response_dict ) + "\n"
def get_table( value_to_convert ):
- ''' This will parse the dictionary recusrsively and print as
- table format'''
+ """ This will parse the dictionary recusrsively and print as
+ table format"""
table_data = ""
if isinstance( value_to_convert, dict ):
table_data = table_data + '\t'.join( value_to_convert ) +\
@@ -734,7 +736,7 @@
return response_table
elif return_format == 'config':
- ''' Will return in config format'''
+ " Will return in config format"
to_do = 'Call dict to config coverter'
response_string = str( response_dict )
print response_string
@@ -745,12 +747,12 @@
response_config = re.sub( ":", " =", response_config )
return "[response]\n\t " + response_config
elif return_format == 'xml':
- ''' Will return in xml format'''
+ " Will return in xml format"
response_xml = xmldict.dict_to_xml( response_dict )
response_xml = re.sub( ">\s*<", ">\n<", response_xml )
return "\n" + response_xml
elif return_format == 'json':
- ''' Will return in json format'''
+ " Will return in json format"
to_do = 'Call dict to xml coverter'
import json
response_json = json.dumps( response_dict )
@@ -815,10 +817,10 @@
def verifyOptions( options ):
- '''
+ """
This will verify the command line options and set to default values,
if any option not given in command line.
- '''
+ """
verifyTest( options )
verifyExample( options )
verifyTestScript( options )
@@ -828,6 +830,7 @@
verifyTestCases( options )
verifyOnosCell( options )
+
def verifyTest( options ):
try:
if options.testname:
@@ -842,12 +845,14 @@
print "Test or Example not specified please specify the --test <test name > or --example <example name>"
main.exit()
+
def verifyExample( options ):
if options.example:
main.testDir = path + '/examples/'
main.tests_path = path + "/examples/"
main.classPath = "examples." + main.TEST + "." + main.TEST
+
def verifyLogdir( options ):
# Verifying Log directory option
if options.logdir:
@@ -855,20 +860,22 @@
else:
main.logdir = main.FALSE
+
def verifyMail( options ):
# Mail-To: field
if options.mail: # Test run specific
main.mail = options.mail
- elif main.params.get('mail'): # Test suite specific
+ elif main.params.get( 'mail' ): # Test suite specific
main.mail = main.params.get( 'mail' )
else: # TestON specific
- main.mail = main.config['config'].get( 'mail_to' )
+ main.mail = main.config[ 'config' ].get( 'mail_to' )
# Mail-From: field
- main.sender = main.config['config'].get( 'mail_from' )
+ main.sender = main.config[ 'config' ].get( 'mail_from' )
# Mail smtp server
- main.smtp = main.config['config'].get( 'mail_server' )
+ main.smtp = main.config[ 'config' ].get( 'mail_server' )
# Mail-From account password
- main.senderPwd = main.config['config'].get( 'mail_pass' )
+ main.senderPwd = main.config[ 'config' ].get( 'mail_pass' )
+
def evalTestCase( tempList ):
tList = []
@@ -876,9 +883,10 @@
if isinstance( tcase, list ):
tList.extend( evalTestCase( tcase ) )
else:
- tList.extend( [tcase] )
+ tList.extend( [ tcase ] )
return tList
+
def verifyTestCases( options ):
# Getting Test cases list
if options.testcases:
@@ -888,13 +896,14 @@
main.testcases_list = eval( testcases_list + "," )
else:
if 'testcases' in main.params.keys():
- temp = eval( main.params['testcases'] + "," )
+ temp = eval( main.params[ 'testcases' ] + "," )
main.testcases_list = evalTestCase( list( temp ) )
else:
print "Testcases not specifed in params, please provide in " +\
"params file or 'testcases' commandline argument"
sys.exit()
+
def verifyOnosCell( options ):
# Verifying onoscell option
if options.onoscell:
@@ -902,40 +911,41 @@
main.ONOSip = []
main.mnIP = ""
cellCMD = ". ~/onos/tools/dev/bash_profile; cell " + main.onoscell
- output = subprocess.check_output( ["bash", '-c', cellCMD] )
+ output = subprocess.check_output( [ "bash", '-c', cellCMD ] )
splitOutput = output.splitlines()
main.apps = ""
for i in range( len( splitOutput ) ):
- if re.match( "OCN", splitOutput[i] ):
- mnNode = splitOutput[i].split( "=" )
- main.mnIP = mnNode[1]
+ if re.match( "OCN", splitOutput[ i ] ):
+ mnNode = splitOutput[ i ].split( "=" )
+ main.mnIP = mnNode[ 1 ]
# cell already sorts OC variables in bash, so no need to
# sort in TestON
- elif re.match( "OC[1-9]", splitOutput[i] ):
- onosNodes = splitOutput[i].split( "=" )
- main.ONOSip.append( onosNodes[1] )
- elif re.match( "ONOS_APPS", splitOutput[i] ):
- main.apps = ( splitOutput[i].split( "=" ) )[1]
+ elif re.match( "OC[1-9]", splitOutput[ i ] ):
+ onosNodes = splitOutput[ i ].split( "=" )
+ main.ONOSip.append( onosNodes[ 1 ] )
+ elif re.match( "ONOS_APPS", splitOutput[ i ] ):
+ main.apps = ( splitOutput[ i ].split( "=" ) )[ 1 ]
else:
main.onoscell = main.FALSE
+
def verifyTestScript( options ):
- '''
+ """
Verifyies test script.
- '''
+ """
main.openspeak = openspeak.OpenSpeak()
directory = main.testDir + "/" + main.TEST
if os.path.exists( directory ):
pass
else:
directory = ""
- for root, dirs, files in os.walk( main.testDir, topdown=True):
+ for root, dirs, files in os.walk( main.testDir, topdown=True ):
if not directory:
for name in dirs:
if name == main.TEST:
directory = ( os.path.join( root, name ) )
index = directory.find( "/tests/" ) + 1
- main.classPath = directory[index:].replace( '/', '.' ) + "." + main.TEST
+ main.classPath = directory[ index: ].replace( '/', '.' ) + "." + main.TEST
break
openspeakfile = directory + "/" + main.TEST + ".ospk"
main.testFile = directory + "/" + main.TEST + ".py"
@@ -955,7 +965,7 @@
testModule = __import__( main.classPath,
globals(),
locals(),
- [main.TEST],
+ [ main.TEST ],
-1 )
except ImportError:
print "There was an import error, it might mean that there is " +\
@@ -968,21 +978,22 @@
main.params = main.parser.parseParams( main.classPath )
main.topology = main.parser.parseTopology( main.classPath )
+
def verifyParams( options ):
try:
- main.params = main.params['PARAMS']
+ main.params = main.params[ 'PARAMS' ]
except KeyError:
print "Error with the params file: Either the file not specified " +\
"or the format is not correct"
main.exit()
try:
- main.topology = main.topology['TOPOLOGY']
+ main.topology = main.topology[ 'TOPOLOGY' ]
except KeyError:
print "Error with the Topology file: Either the file not specified " +\
"or the format is not correct"
main.exit()
# Overwrite existing params variables if they are specified from command line
- if len(options.params) > 0:
+ if len( options.params ) > 0:
# Some params variables are specified from command line
for param in options.params:
if not re.search( ".=.", param ):
@@ -997,7 +1008,7 @@
# Get the innermost dictionary
try:
while len( keyList ) > 1:
- key = keyList.pop(0)
+ key = keyList.pop( 0 )
assert isinstance( paramDict[ key ], dict )
paramDict = paramDict[ key ]
except KeyError:
@@ -1007,38 +1018,39 @@
print( "Error when parsing params: \"" + key + "\" is already the innermost level in main.params" )
main.exit()
# Change the value
- if not paramDict.has_key( keyList[0] ):
+ if keyList[ 0 ] not in paramDict:
print( "Error when parsing params: key \"" + keyList[0] + "\" not found in main.params" )
main.exit()
- elif isinstance( paramDict[ keyList[0] ], dict ):
+ elif isinstance( paramDict[ keyList[ 0 ] ], dict ):
print( "Error when parsing params: more levels under key \"" + keyList[0] + "\" in main.params" )
main.exit()
else:
- paramDict[ keyList[0] ] = value
+ paramDict[ keyList[ 0 ] ] = value
+
def load_parser():
- '''
+ """
It facilitates the loading customised parser for topology and params file.
It loads parser mentioned in tab named parser of teston.cfg file.
It also loads default xmlparser if no parser have specified in teston.cfg
file.
- '''
+ """
confighash = main.configDict
- if 'file' in confighash['config']['parser'] and\
- 'class' in confighash['config']['parser']:
- path = confighash['config']['parser']['file']
+ if 'file' in confighash[ 'config' ][ 'parser' ] and\
+ 'class' in confighash[ 'config' ][ 'parser' ]:
+ path = confighash[ 'config' ][ 'parser' ][ 'file' ]
if path is not None or\
- confighash['config']['parser']['class'] is not None:
+ confighash[ 'config' ][ 'parser' ][ 'class' ] is not None:
try:
module = re.sub( r".py\s*$", "", path )
- moduleList = module.split("/")
- newModule = ".".join( moduleList[-2:] )
- parsingClass = confighash['config']['parser']['class']
+ moduleList = module.split( "/" )
+ newModule = ".".join( moduleList[ -2: ] )
+ parsingClass = confighash[ 'config' ][ 'parser' ][ 'class' ]
parsingModule = __import__( newModule,
globals(),
locals(),
- [parsingClass],
+ [ parsingClass ],
-1 )
parsingClass = getattr( parsingModule, parsingClass )
main.parser = parsingClass()
@@ -1053,25 +1065,26 @@
print "Could not find the file " + path +\
" using default parser."
load_defaultParser()
- elif confighash['config']['parser']['file'] is None or\
- confighash['config']['parser']['class'] is None:
+ elif confighash[ 'config' ][ 'parser' ][ 'file' ] is None or\
+ confighash[ 'config' ][ 'parser' ][ 'class' ] is None:
load_defaultParser()
else:
load_defaultParser()
+
def load_defaultParser():
- '''
+ """
It will load the default parser which is xml parser to parse the params and
topology file.
- '''
- moduleList = main.parserPath.split("/")
- newModule = ".".join( moduleList[-2:] )
+ """
+ moduleList = main.parserPath.split( "/" )
+ newModule = ".".join( moduleList[ -2: ] )
try:
parsingClass = main.parsingClass
parsingModule = __import__( newModule,
globals(),
locals(),
- [parsingClass],
+ [ parsingClass ],
-1 )
parsingClass = getattr( parsingModule, parsingClass )
main.parser = parsingClass()
@@ -1082,30 +1095,31 @@
else:
main.exit()
except ImportError:
- print sys.exc_info()[1]
+ print sys.exc_info()[ 1 ]
+
def load_logger():
- '''
+ """
It facilitates the loading customised parser for topology and params file.
It loads parser mentioned in tab named parser of teston.cfg file.
It also loads default xmlparser if no parser have specified in teston.cfg
file.
- '''
+ """
confighash = main.configDict
- if 'file' in confighash['config']['logger'] and\
- 'class' in confighash['config']['logger']:
- path = confighash['config']['logger']['file']
+ if 'file' in confighash[ 'config' ][ 'logger' ] and\
+ 'class' in confighash[ 'config' ][ 'logger' ]:
+ path = confighash[ 'config' ][ 'logger' ][ 'file' ]
if path is not None or\
- confighash['config']['logger']['class'] is not None:
+ confighash[ 'config' ][ 'logger' ][ 'class' ] is not None:
try:
module = re.sub( r".py\s*$", "", path )
moduleList = module.split( "/" )
- newModule = ".".join( moduleList[-2:] )
- loggerClass = confighash['config']['logger']['class']
+ newModule = ".".join( moduleList[ -2: ] )
+ loggerClass = confighash[ 'config' ][ 'logger' ][ 'class' ]
loggerModule = __import__( newModule,
globals(),
locals(),
- [loggerClass],
+ [ loggerClass ],
-1 )
loggerClass = getattr( loggerModule, loggerClass )
main.logger = loggerClass()
@@ -1113,32 +1127,34 @@
print "Could not find the file " + path +\
" using default logger."
load_defaultlogger()
- elif confighash['config']['parser']['file'] is None or\
- confighash['config']['parser']['class'] is None:
+ elif confighash[ 'config' ][ 'parser' ][ 'file' ] is None or\
+ confighash[ 'config' ][ 'parser' ][ 'class' ] is None:
load_defaultlogger()
else:
load_defaultlogger()
+
def load_defaultlogger():
- '''
+ """
It will load the default parser which is xml parser to parse the params and
topology file.
- '''
- moduleList = main.loggerPath.split("/")
- newModule = ".".join( moduleList[-2:] )
+ """
+ moduleList = main.loggerPath.split( "/" )
+ newModule = ".".join( moduleList[ -2: ] )
try:
loggerClass = main.loggerClass
loggerModule = __import__( newModule,
globals(),
locals(),
- [loggerClass],
+ [ loggerClass ],
-1 )
loggerClass = getattr( loggerModule, loggerClass )
main.logger = loggerClass()
except ImportError:
- print sys.exc_info()[1]
+ print sys.exc_info()[ 1 ]
main.exit()
+
def _echo( self ):
print "THIS IS ECHO"
diff --git a/TestON/core/testparser.py b/TestON/core/testparser.py
index 904ebc0..08e4198 100644
--- a/TestON/core/testparser.py
+++ b/TestON/core/testparser.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python
-'''
+"""
Created on 26-Dec-2012
Modified 2015 by ON.Lab
@@ -10,7 +10,7 @@
TestON is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -21,16 +21,19 @@
along with TestON. If not, see <http://www.gnu.org/licenses/>.
-'''
+"""
import re
import sys
+
+
class TestParser:
- def __init__(self,testFile):
- try :
- testFileHandler = open(testFile, 'r')
+
+ def __init__( self, testFile ):
+ try:
+ testFileHandler = open( testFile, 'r' )
except IOError:
- print "No such file "+testFile
- sys.exit(0)
+ print "No such file " + testFile
+ sys.exit( 0 )
testFileList = testFileHandler.readlines()
self.testscript = testFileList
@@ -39,89 +42,89 @@
self.statementsList = []
index = 0
self.statementsList = []
- #initialSpaces = len(line) -len(line.lstrip())
- while index < len(testFileList):
- testFileList[index] = re.sub("^\s{8}|^\s{4}", "", testFileList[index])
+ # initialSpaces = len( line ) -len( line.lstrip() )
+ while index < len( testFileList ):
+ testFileList[ index ] = re.sub( "^\s{8}|^\s{4}", "", testFileList[ index ] )
# Skip multiline comments
- if re.match('^(\'\'\')|^(\"\"\")',testFileList[index],0) :
+ if re.match( '^(\'\'\' )|^( \"\"\" )', testFileList[ index ], 0 ):
index = index + 1
- try :
- while not re.match('^\s*(\'\'\')|^\s*(\"\"\")',testFileList[index],0) :
+ try:
+ while not re.match( '^\s*(\'\'\' )|^\s*( \"\"\" )', testFileList[ index ], 0 ):
index = index + 1
except IndexError:
print ''
# skip empty lines and single line comments
- elif not re.match('#|^\s*$',testFileList[index],0):
- self.statementsList.append(testFileList[index])
+ elif not re.match( '#|^\s*$', testFileList[ index ], 0 ):
+ self.statementsList.append( testFileList[ index ] )
index = index + 1
- def case_code(self):
+ def case_code( self ):
index = 0
statementsList = self.statementsList
- while index < len(statementsList):
- m= re.match('def\s+CASE(\d+)',statementsList[index],0)
+ while index < len( statementsList ):
+ m = re.match( 'def\s+CASE(\d+)', statementsList[ index ], 0 )
self.caseBlock = []
if m:
index = index + 1
- try :
- while not re.match('\s*def\s+CASE(\d+)',statementsList[index],0) :
- self.caseBlock.append(statementsList[index])
- if index < len(statementsList)-1:
+ try:
+ while not re.match( '\s*def\s+CASE(\d+)', statementsList[ index ], 0 ):
+ self.caseBlock.append( statementsList[ index ] )
+ if index < len( statementsList ) - 1:
index = index + 1
- else :
+ else:
break
index = index - 1
except IndexError:
print ''
- self.caseCode [str(m.group(1))] = self.caseBlock
+ self.caseCode[ str( m.group( 1 ) ) ] = self.caseBlock
index = index + 1
return self.caseCode
- def step_code(self,caseStatements):
+ def step_code( self, caseStatements ):
index = 0
step = 0
stepCode = {}
step_flag = False
- while index < len(caseStatements):
- m= re.match('main\.step',caseStatements[index],0)
+ while index < len( caseStatements ):
+ m = re.match( 'main\.step', caseStatements[ index ], 0 )
stepBlock = ''
if m:
step_flag = True
- if step == 0 :
+ if step == 0:
i = 0
block = ''
- while i < index :
- block += caseStatements[i]
+ while i < index:
+ block += caseStatements[ i ]
i = i + 1
- stepCode[step] = block
+ stepCode[ step ] = block
step = step + 1
- stepBlock = stepBlock + caseStatements[index]
+ stepBlock = stepBlock + caseStatements[ index ]
index = index + 1
- try :
- while not re.match('main\.step',caseStatements[index],0) :
- stepBlock = stepBlock + caseStatements[index]
- if index < len(caseStatements)-1:
+ try:
+ while not re.match( 'main\.step', caseStatements[ index ], 0 ):
+ stepBlock = stepBlock + caseStatements[ index ]
+ if index < len( caseStatements ) - 1:
index = index + 1
- else :
+ else:
break
index = index - 1
except IndexError:
print ''
- stepCode[step] = stepBlock
+ stepCode[ step ] = stepBlock
step = step + 1
index = index + 1
# If there is no step defined !!
- if not step_flag :
- stepCode[step] = "".join(caseStatements)
+ if not step_flag:
+ stepCode[ step ] = "".join( caseStatements )
return stepCode
- def getStepCode(self):
+ def getStepCode( self ):
case_step_code = {}
case_block = self.case_code()
- for case in case_block :
- case_step_code[case] = {}
- step_block = self.step_code(case_block[case])
- for step in step_block :
- case_step_code[case][step] = step_block[step]
+ for case in case_block:
+ case_step_code[ case ] = {}
+ step_block = self.step_code( case_block[ case ] )
+ for step in step_block:
+ case_step_code[ case ][ step ] = step_block[ step ]
return case_step_code
diff --git a/TestON/core/utilities.py b/TestON/core/utilities.py
index 2f7e5bb..fee2899 100644
--- a/TestON/core/utilities.py
+++ b/TestON/core/utilities.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
-'''
+"""
Created on 23-Oct-2012
-Copyright 2012 Open Networking Foundation (ONF)
+Copyright 2012 Open Networking Foundation ( ONF )
Please refer questions to either the onos test mailing list at <onos-test@onosproject.org>,
the System Testing Plans and Results wiki page at <https://wiki.onosproject.org/x/voMg>,
@@ -10,7 +10,7 @@
TestON is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -26,7 +26,7 @@
* parse_args for key-value pair handling
* Parsing the params or topology file.
-'''
+"""
import re
from configobj import ConfigObj
from core import ast as ast
@@ -38,56 +38,57 @@
import time
import random
+
class Utilities:
- '''
+
+ """
Utilities will take care about the basic functions like :
* Extended assertion,
* parse_args for key-value pair handling
* Parsing the params or topology file.
- '''
+ """
+ def __init__( self ):
+ self.wrapped = sys.modules[ __name__ ]
- def __init__(self):
- self.wrapped = sys.modules[__name__]
-
- def __getattr__(self, name):
- '''
+ def __getattr__( self, name ):
+ """
This will invoke, if the attribute wasn't found the usual ways.
Here it will look for assert_attribute and will execute when AttributeError occurs.
It will return the result of the assert_attribute.
- '''
+ """
try:
- return getattr(self.wrapped, name)
+ return getattr( self.wrapped, name )
except AttributeError:
- def assertHandling(**kwargs):
- nameVar = re.match("^assert",name,flags=0)
- matchVar = re.match("assert(_not_|_)(equals|matches|greater|lesser)",name,flags=0)
+ def assertHandling( **kwargs ):
+ nameVar = re.match( "^assert", name, flags=0 )
+ matchVar = re.match( "assert(_not_|_)(equals|matches|greater|lesser)", name, flags=0 )
notVar = 0
operators = ""
- try :
- if matchVar.group(1) == "_not_" and matchVar.group(2) :
+ try:
+ if matchVar.group( 1 ) == "_not_" and matchVar.group( 2 ):
notVar = 1
- operators = matchVar.group(2)
- elif matchVar.group(1) == "_" and matchVar.group(2):
- operators = matchVar.group(2)
+ operators = matchVar.group( 2 )
+ elif matchVar.group( 1 ) == "_" and matchVar.group( 2 ):
+ operators = matchVar.group( 2 )
except AttributeError:
- if matchVar==None and nameVar:
- operators ='equals'
- result = self._assert(NOT=notVar,operator=operators,**kwargs)
+ if matchVar is None and nameVar:
+ operators = 'equals'
+ result = self._assert( NOT=notVar, operator=operators, **kwargs )
if result == main.TRUE:
- main.log.info("Assertion Passed")
+ main.log.info( "Assertion Passed" )
main.STEPRESULT = main.TRUE
elif result == main.FALSE:
- main.log.warn("Assertion Failed")
+ main.log.warn( "Assertion Failed" )
main.STEPRESULT = main.FALSE
else:
- main.log.error("There is an Error in Assertion")
+ main.log.error( "There is an Error in Assertion" )
main.STEPRESULT = main.ERROR
return result
return assertHandling
- def _assert (self,**assertParam):
- '''
+ def _assert( self, **assertParam ):
+ """
It will take the arguments :
expect:'Expected output'
actual:'Actual output'
@@ -98,30 +99,29 @@
It will return the assertion result.
- '''
-
- arguments = self.parse_args(["EXPECT","ACTUAL","ONPASS","ONFAIL","NOT","OPERATOR"],**assertParam)
+ """
+ arguments = self.parse_args( [ "EXPECT", "ACTUAL", "ONPASS", "ONFAIL", "NOT", "OPERATOR" ], **assertParam )
result = 0
valuetype = ''
- operation = "not "+ str(arguments["OPERATOR"]) if arguments['NOT'] and arguments['NOT'] == 1 else arguments["OPERATOR"]
- operators = {'equals':{'STR':'==','NUM':'=='}, 'matches' : '=~', 'greater':'>' ,'lesser':'<'}
+ operation = "not " + str( arguments[ "OPERATOR" ] ) if arguments[ 'NOT' ] and arguments[ 'NOT' ] == 1 else arguments[ "OPERATOR" ]
+ operators = { 'equals': { 'STR': '==', 'NUM': '==' }, 'matches': '=~', 'greater': '>', 'lesser': '<' }
- expectMatch = re.match('^\s*[+-]?0(e0)?\s*$', str(arguments["EXPECT"]), re.I+re.M)
- if not ((not expectMatch) and (arguments["EXPECT"]==0)):
+ expectMatch = re.match( '^\s*[+-]?0(e0)?\s*$', str( arguments[ "EXPECT" ] ), re.I + re.M )
+ if not ( ( not expectMatch ) and ( arguments[ "EXPECT" ] == 0 ) ):
valuetype = 'NUM'
- else :
- if arguments["OPERATOR"] == 'greater' or arguments["OPERATOR"] == 'lesser':
- main.log.error("Numeric comparison on strings is not possibele")
+ else:
+ if arguments[ "OPERATOR" ] == 'greater' or arguments[ "OPERATOR" ] == 'lesser':
+ main.log.error( "Numeric comparison on strings is not possibele" )
return main.ERROR
valuetype = 'STR'
- arguments["ACTUAL"] = str(arguments["ACTUAL"])
- if arguments["OPERATOR"] != 'matches':
- arguments["EXPECT"] = str(arguments["EXPECT"])
+ arguments[ "ACTUAL" ] = str( arguments[ "ACTUAL" ] )
+ if arguments[ "OPERATOR" ] != 'matches':
+ arguments[ "EXPECT" ] = str( arguments[ "EXPECT" ] )
- try :
- opcode = operators[str(arguments["OPERATOR"])][valuetype] if arguments["OPERATOR"] == 'equals' else operators[str(arguments["OPERATOR"])]
+ try:
+ opcode = operators[ str( arguments[ "OPERATOR" ] ) ][ valuetype ] if arguments[ "OPERATOR" ] == 'equals' else operators[ str( arguments[ "OPERATOR" ] ) ]
except KeyError as e:
print "Key Error in assertion"
@@ -130,111 +130,111 @@
if opcode == '=~':
try:
- assert re.search(str(arguments["EXPECT"]),str(arguments["ACTUAL"]))
+ assert re.search( str( arguments[ "EXPECT" ] ), str( arguments[ "ACTUAL" ] ) )
result = main.TRUE
except AssertionError:
- try :
- assert re.match(str(arguments["EXPECT"]),str(arguments["ACTUAL"]))
+ try:
+ assert re.match( str( arguments[ "EXPECT" ] ), str( arguments[ "ACTUAL" ] ) )
result = main.TRUE
except AssertionError:
- main.log.error("Assertion Failed")
+ main.log.error( "Assertion Failed" )
result = main.FALSE
- else :
+ else:
try:
- if str(opcode)=="==":
- main.log.info("Verifying the Expected is equal to the actual or not using assert_equal")
- if (arguments["EXPECT"] == arguments["ACTUAL"]):
+ if str( opcode ) == "==":
+ main.log.info( "Verifying the Expected is equal to the actual or not using assert_equal" )
+ if ( arguments[ "EXPECT" ] == arguments[ "ACTUAL" ] ):
result = main.TRUE
- else :
+ else:
result = main.FALSE
- elif str(opcode) == ">":
- main.log.info("Verifying the Expected is Greater than the actual or not using assert_greater")
- if (ast.literal_eval(arguments["EXPECT"]) > ast.literal_eval(arguments["ACTUAL"])) :
+ elif str( opcode ) == ">":
+ main.log.info( "Verifying the Expected is Greater than the actual or not using assert_greater" )
+ if ( ast.literal_eval( arguments[ "EXPECT" ] ) > ast.literal_eval( arguments[ "ACTUAL" ] ) ):
result = main.TRUE
- else :
+ else:
result = main.FALSE
- elif str(opcode) == "<":
- main.log.info("Verifying the Expected is Lesser than the actual or not using assert_lesser")
- if (ast.literal_eval(arguments["EXPECT"]) < ast.literal_eval(arguments["ACTUAL"])):
+ elif str( opcode ) == "<":
+ main.log.info( "Verifying the Expected is Lesser than the actual or not using assert_lesser" )
+ if ( ast.literal_eval( arguments[ "EXPECT" ] ) < ast.literal_eval( arguments[ "ACTUAL" ] ) ):
result = main.TRUE
- else :
+ else:
result = main.FALSE
except AssertionError:
- main.log.error("Assertion Failed")
+ main.log.error( "Assertion Failed" )
result = main.FALSE
result = result if result else 0
- result = not result if arguments["NOT"] and arguments["NOT"] == 1 else result
+ result = not result if arguments[ "NOT" ] and arguments[ "NOT" ] == 1 else result
resultString = ""
- if result :
- resultString = str(resultString) + "PASS"
- main.log.info(arguments["ONPASS"])
- else :
- resultString = str(resultString) + "FAIL"
- if not isinstance(arguments["ONFAIL"],str):
- eval(str(arguments["ONFAIL"]))
- else :
- main.log.error(arguments["ONFAIL"])
- main.log.report(arguments["ONFAIL"])
+ if result:
+ resultString = str( resultString ) + "PASS"
+ main.log.info( arguments[ "ONPASS" ] )
+ else:
+ resultString = str( resultString ) + "FAIL"
+ if not isinstance( arguments[ "ONFAIL" ], str ):
+ eval( str( arguments[ "ONFAIL" ] ) )
+ else:
+ main.log.error( arguments[ "ONFAIL" ] )
+ main.log.report( arguments[ "ONFAIL" ] )
main.onFailMsg = arguments[ 'ONFAIL' ]
- msg = arguments["ON" + str(resultString)]
+ msg = arguments[ "ON" + str( resultString ) ]
- if not isinstance(msg,str):
+ if not isinstance( msg, str ):
try:
- eval(str(msg))
+ eval( str( msg ) )
except SyntaxError as e:
print "function definition is not right"
print e
main.last_result = result
- if main.stepResults[2]:
- main.stepResults[2][-1] = result
+ if main.stepResults[ 2 ]:
+ main.stepResults[ 2 ][ -1 ] = result
try:
- main.stepResults[3][-1] = arguments[ 'ONFAIL' ]
+ main.stepResults[ 3 ][ -1 ] = arguments[ 'ONFAIL' ]
except AttributeError:
pass
else:
main.log.warn( "Assertion called before a test step" )
return result
- def parse_args(self,args, **kwargs):
- '''
- It will accept the (key,value) pair and will return the (key,value) pairs with keys in uppercase.
- '''
+ def parse_args( self, args, **kwargs ):
+ """
+ It will accept the ( key,value ) pair and will return the ( key,value ) pairs with keys in uppercase.
+ """
newArgs = {}
- for key,value in kwargs.iteritems():
- if isinstance(args,list) and str.upper(key) in args:
+ for key, value in kwargs.iteritems():
+ if isinstance( args, list ) and str.upper( key ) in args:
for each in args:
- if each==str.upper(key):
- newArgs [str(each)] = value
- elif each != str.upper(key) and (newArgs.has_key(str(each)) == False ):
- newArgs[str(each)] = None
+ if each == str.upper( key ):
+ newArgs[ str( each ) ] = value
+ elif each != str.upper( key ) and not ( ( str( each ) in newArgs ) ):
+ newArgs[ str( each ) ] = None
return newArgs
- def send_mail(self):
+ def send_mail( self ):
# Create a text/plain message
msg = email.mime.Multipart.MIMEMultipart()
- try :
+ try:
if main.test_target:
sub = "Result summary of \"" + main.TEST + "\" run on component \"" +\
main.test_target + "\" Version \"" +\
- vars( main )[main.test_target].get_version() + "\": " +\
+ vars( main )[ main.test_target ].get_version() + "\": " +\
str( main.TOTAL_TC_SUCCESS ) + "% Passed"
- else :
+ else:
sub = "Result summary of \"" + main.TEST + "\": " +\
str( main.TOTAL_TC_SUCCESS ) + "% Passed"
except ( KeyError, AttributeError ):
sub = "Result summary of \"" + main.TEST + "\": " +\
str( main.TOTAL_TC_SUCCESS ) + "% Passed"
- msg['Subject'] = sub
- msg['From'] = main.sender
- msg['To'] = main.mail
+ msg[ 'Subject' ] = sub
+ msg[ 'From' ] = main.sender
+ msg[ 'To' ] = main.mail
# The main body is just another attachment
body = email.mime.Text.MIMEText( main.logHeader + "\n" +
- main.testResult)
+ main.testResult )
msg.attach( body )
# Attachments
@@ -252,7 +252,7 @@
smtp = smtplib.SMTP( main.smtp )
smtp.starttls()
smtp.login( main.sender, main.senderPwd )
- smtp.sendmail( msg['From'], [msg['To']], msg.as_string() )
+ smtp.sendmail( msg[ 'From' ], [ msg[ 'To' ] ], msg.as_string() )
smtp.quit()
except Exception:
main.log.exception( "Error sending email" )
@@ -265,32 +265,32 @@
# Create a text/plain message
msg = email.mime.Multipart.MIMEMultipart()
- msg['Subject'] = subject
- msg['From'] = main.sender
- msg['To'] = main.mail
+ msg[ 'Subject' ] = subject
+ msg[ 'From' ] = main.sender
+ msg[ 'To' ] = main.mail
smtp = smtplib.SMTP( main.smtp )
smtp.starttls()
smtp.login( main.sender, main.senderPwd )
- smtp.sendmail( msg['From'], [msg['To']], msg.as_string() )
+ smtp.sendmail( msg[ 'From' ], [ msg[ 'To' ] ], msg.as_string() )
smtp.quit()
except Exception:
main.log.exception( "" )
return main.FALSE
return main.TRUE
- def parse(self,fileName):
- '''
+ def parse( self, fileName ):
+ """
This will parse the params or topo or cfg file and return content in the file as Dictionary
- '''
+ """
self.fileName = fileName
- matchFileName = re.match(r'(.*)\.(cfg|params|topo)',self.fileName,re.M|re.I)
+ matchFileName = re.match( r'(.*)\.(cfg|params|topo)', self.fileName, re.M | re.I )
if matchFileName:
- try :
- parsedInfo = ConfigObj(self.fileName)
+ try:
+ parsedInfo = ConfigObj( self.fileName )
return parsedInfo
- except StandardError:
- print "There is no such file to parse "+fileName
+ except Exception:
+ print "There is no such file to parse " + fileName
else:
return 0
@@ -303,7 +303,7 @@
Arguments:
f - a callable object
- retValue - Return value(s) of f to retry on. This can be a list or an
+ retValue - Return value( s ) of f to retry on. This can be a list or an
object.
args - A tuple containing the arguments of f.
kwargs - A dictionary containing the keyword arguments of f.
@@ -314,7 +314,7 @@
random - Boolean indicating if the wait time is random between 0
and sleep or exactly sleep seconds. Defaults to False.
"""
- # TODO: be able to pass in a conditional statement(s). For example:
+ # TODO: be able to pass in a conditional statement( s ). For example:
# retCondition = "< 7"
# Then we do something like 'if eval( "ret " + retCondition ):break'
try:
@@ -327,7 +327,7 @@
for i in range( 0, attempts ):
ret = f( *args, **kwargs )
if ret not in retValue:
- # NOTE that False in [ 0 ] == True
+ # NOTE that False in [ 0 ] == True
break
if randomTime:
sleeptime = random.randint( 0, sleep )
@@ -350,4 +350,4 @@
if __name__ != "__main__":
import sys
- sys.modules[__name__] = Utilities()
+ sys.modules[ __name__ ] = Utilities()
diff --git a/TestON/core/xmldict.py b/TestON/core/xmldict.py
index 808b365..a85c9ad 100644
--- a/TestON/core/xmldict.py
+++ b/TestON/core/xmldict.py
@@ -1,17 +1,17 @@
-'''
+"""
Created on 03-Dec-2012
-Copyright 2012 Open Networking Foundation (ONF)
+Copyright 2012 Open Networking Foundation ( ONF )
Please refer questions to either the onos test mailing list at <onos-test@onosproject.org>,
the System Testing Plans and Results wiki page at <https://wiki.onosproject.org/x/voMg>,
or the System Testing Guide page at <https://wiki.onosproject.org/x/WYQg>
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
+author:: Anil Kumar ( anilkumar.s@paxterrasolutions.com )
TestON is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -21,8 +21,7 @@
You should have received a copy of the GNU General Public License
along with TestON. If not, see <http://www.gnu.org/licenses/>.
-'''
-
+"""
"""
xmldict
~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -31,141 +30,153 @@
"""
import datetime
-def xml_to_dict(root_or_str, strict=True):
+
+def xml_to_dict( root_or_str, strict=True ):
"""
Converts `root_or_str` which can be parsed xml or a xml string to dict.
"""
root = root_or_str
- if isinstance(root, str):
+ if isinstance( root, str ):
import xml.etree.cElementTree as ElementTree
- root = ElementTree.XML(root_or_str)
- try :
- return {root.tag: _from_xml(root, strict)}
- except StandardError:
+ root = ElementTree.XML( root_or_str )
+ try:
+ return { root.tag: _from_xml( root, strict ) }
+ except Exception:
return None
-def dict_to_xml(dict_xml):
+
+def dict_to_xml( dict_xml ):
"""
Converts `dict_xml` which is a python dict to corresponding xml.
"""
- return _to_xml(dict_xml)
+ return _to_xml( dict_xml )
-def _to_xml(el):
+
+def _to_xml( el ):
"""
Converts `el` to its xml representation.
"""
val = None
- if isinstance(el, dict):
- val = _dict_to_xml(el)
- elif isinstance(el, bool):
- val = str(el).lower()
+ if isinstance( el, dict ):
+ val = _dict_to_xml( el )
+ elif isinstance( el, bool ):
+ val = str( el ).lower()
else:
val = el
- if val is None: val = 'null'
+ if val is None:
+ val = 'null'
return val
-def _extract_attrs(els):
+
+def _extract_attrs( els ):
"""
Extracts attributes from dictionary `els`. Attributes are keys which start
with '@'
"""
- if not isinstance(els, dict):
+ if not isinstance( els, dict ):
return ''
- return ''.join(' %s="%s"' % (key[1:], value) for key, value in els.iteritems()
- if key.startswith('@'))
+ return ''.join( ' %s="%s"' % ( key[ 1: ], value ) for key, value in els.iteritems()
+ if key.startswith( '@' ) )
-def _dict_to_xml(els):
+
+def _dict_to_xml( els ):
"""
Converts `els` which is a python dict to corresponding xml.
"""
- def process_content(tag, content):
- attrs = _extract_attrs(content)
- text = isinstance(content, dict) and content.get('#text', '') or ''
- return '<%s%s>%s%s</%s>' % (tag, attrs, _to_xml(content), text, tag)
+ def process_content( tag, content ):
+ attrs = _extract_attrs( content )
+ text = isinstance( content, dict ) and content.get( '#text', '' ) or ''
+ return '<%s%s>%s%s</%s>' % ( tag, attrs, _to_xml( content ), text, tag )
tags = []
for tag, content in els.iteritems():
# Text and attributes
- if tag.startswith('@') or tag == '#text':
+ if tag.startswith( '@' ) or tag == '#text':
continue
- elif isinstance(content, list):
+ elif isinstance( content, list ):
for el in content:
- tags.append(process_content(tag, el))
- elif isinstance(content, dict):
- tags.append(process_content(tag, content))
+ tags.append( process_content( tag, el ) )
+ elif isinstance( content, dict ):
+ tags.append( process_content( tag, content ) )
else:
- tags.append('<%s>%s</%s>' % (tag, _to_xml(content), tag))
- return ''.join(tags)
+ tags.append( '<%s>%s</%s>' % ( tag, _to_xml( content ), tag ) )
+ return ''.join( tags )
-def _is_xml_el_dict(el):
+
+def _is_xml_el_dict( el ):
"""
Returns true if `el` is supposed to be a dict.
This function makes sense only in the context of making dicts out of xml.
"""
- if len(el) == 1 or el[0].tag != el[1].tag:
+ if len( el ) == 1 or el[ 0 ].tag != el[ 1 ].tag:
return True
return False
-def _is_xml_el_list(el):
+
+def _is_xml_el_list( el ):
"""
Returns true if `el` is supposed to be a list.
This function makes sense only in the context of making lists out of xml.
"""
- if len(el) > 1 and el[0].tag == el[1].tag:
+ if len( el ) > 1 and el[ 0 ].tag == el[ 1 ].tag:
return True
return False
-def _str_to_datetime(date_str):
+
+def _str_to_datetime( date_str ):
try:
- val = datetime.datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%SZ")
+ val = datetime.datetime.strptime( date_str, "%Y-%m-%dT%H:%M:%SZ" )
except ValueError:
val = date_str
return val
-def _str_to_boolean(bool_str):
- if bool_str.lower() != 'false' and bool(bool_str):
+
+def _str_to_boolean( bool_str ):
+ if bool_str.lower() != 'false' and bool( bool_str ):
return True
return False
-def _from_xml(el, strict):
+
+def _from_xml( el, strict ):
"""
Extracts value of xml element element `el`.
"""
val = None
# Parent node.
if el:
- if _is_xml_el_dict(el):
- val = _dict_from_xml(el, strict)
- elif _is_xml_el_list(el):
- val = _list_from_xml(el, strict)
+ if _is_xml_el_dict( el ):
+ val = _dict_from_xml( el, strict )
+ elif _is_xml_el_list( el ):
+ val = _list_from_xml( el, strict )
# Simple node.
else:
attribs = el.items()
# An element with attributes.
if attribs and strict:
- val = dict(('@%s' % k, v) for k, v in dict(attribs).iteritems())
+ val = dict( ( '@%s' % k, v ) for k, v in dict( attribs ).iteritems() )
if el.text:
- converted = _val_and_maybe_convert(el)
- val['#text'] = el.text
+ converted = _val_and_maybe_convert( el )
+ val[ '#text' ] = el.text
if converted != el.text:
- val['#value'] = converted
+ val[ '#value' ] = converted
elif el.text:
# An element with no subelements but text.
- val = _val_and_maybe_convert(el)
+ val = _val_and_maybe_convert( el )
elif attribs:
- val = dict(attribs)
+ val = dict( attribs )
return val
-def _val_and_maybe_convert(el):
+
+def _val_and_maybe_convert( el ):
"""
Converts `el.text` if `el` has attribute `type` with valid value.
"""
text = el.text.strip()
- data_type = el.get('type')
- convertor = _val_and_maybe_convert.convertors.get(data_type)
+ data_type = el.get( 'type' )
+ convertor = _val_and_maybe_convert.convertors.get( data_type )
if convertor:
- return convertor(text)
+ return convertor( text )
else:
return text
_val_and_maybe_convert.convertors = {
@@ -174,23 +185,24 @@
'integer': int
}
-def _list_from_xml(els, strict):
+
+def _list_from_xml( els, strict ):
"""
Converts xml elements list `el_list` to a python list.
"""
-
temp = {}
for el in els:
- tag = el.attrib["name"]
- temp[tag] = (_from_xml(el, strict))
+ tag = el.attrib[ "name" ]
+ temp[ tag ] = ( _from_xml( el, strict ) )
return temp
-def _dict_from_xml(els, strict):
+
+def _dict_from_xml( els, strict ):
"""
Converts xml doc with root `root` to a python dict.
"""
# An element with subelements.
res = {}
for el in els:
- res[el.tag] = _from_xml(el, strict)
+ res[ el.tag ] = _from_xml( el, strict )
return res
diff --git a/TestON/core/xmlparser.py b/TestON/core/xmlparser.py
index a41ed92..181f646 100644
--- a/TestON/core/xmlparser.py
+++ b/TestON/core/xmlparser.py
@@ -1,18 +1,18 @@
-#/usr/bin/env python
-'''
+# /usr/bin/env python
+"""
Created on 07-Jan-2013
-Copyright 2013 Open Networking Foundation (ONF)
+Copyright 2013 Open Networking Foundation ( ONF )
Please refer questions to either the onos test mailing list at <onos-test@onosproject.org>,
the System Testing Plans and Results wiki page at <https://wiki.onosproject.org/x/voMg>,
or the System Testing Guide page at <https://wiki.onosproject.org/x/WYQg>
-@author: Raghav Kashyap(raghavkashyap@paxterrasolutions.com)
+author:: Raghav Kashyap( raghavkashyap@paxterrasolutions.com )
TestON is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -23,50 +23,49 @@
along with TestON. If not, see <http://www.gnu.org/licenses/>.
-'''
-
+"""
import xmldict
import re
-class xmlparser :
- def __init__(self) :
+class xmlparser:
+
+ def __init__( self ):
self.default = ''
- def parse(self,fileName) :
- '''
+ def parse( self, fileName ):
+ """
This will parse the params or topo or cfg file and return content in the file as Dictionary
- '''
+ """
self.fileName = fileName
- matchFileName = re.match(r'(.*)\.(params|topo|cfg)', self.fileName, re.M | re.I)
+ matchFileName = re.match( r'(.*)\.(params|topo|cfg)', self.fileName, re.M | re.I )
if matchFileName:
- xml = open(fileName).read()
- try :
- parsedInfo = xmldict.xml_to_dict(xml)
+ xml = open( fileName ).read()
+ try:
+ parsedInfo = xmldict.xml_to_dict( xml )
return parsedInfo
- except StandardError as e:
+ except Exception as e:
print "Error parsing file " + fileName + ": " + e.message
- else :
+ else:
print "File name is not correct"
- def parseParams(self,paramsPath):
- '''
+ def parseParams( self, paramsPath ):
+ """
It will take the params file path and will return the params dictionary
- '''
- paramsPath = re.sub("\.","/",paramsPath)
- paramsPath = re.sub("tests|examples","",paramsPath)
- params = self.parse(main.tests_path+paramsPath+".params")
- paramsAsString = str(params)
- return eval(paramsAsString)
+ """
+ paramsPath = re.sub( "\.", "/", paramsPath )
+ paramsPath = re.sub( "tests|examples", "", paramsPath )
+ params = self.parse( main.tests_path + paramsPath + ".params" )
+ paramsAsString = str( params )
+ return eval( paramsAsString )
- def parseTopology(self,topologyPath):
- '''
+ def parseTopology( self, topologyPath ):
+ """
It will take topology file path and will return topology dictionary
- '''
- topologyPath = re.sub("\.","/",topologyPath)
- topologyPath = re.sub("tests|examples","",topologyPath)
- #topology = self.parse(main.tests_path+"/"+topologyPath+".topo")
- topology = self.parse(main.tests_path+topologyPath+".topo")
- topoAsString = str(topology)
- return eval(topoAsString)
-
+ """
+ topologyPath = re.sub( "\.", "/", topologyPath )
+ topologyPath = re.sub( "tests|examples", "", topologyPath )
+ # topology = self.parse( main.tests_path+"/"+topologyPath+".topo" )
+ topology = self.parse( main.tests_path + topologyPath + ".topo" )
+ topoAsString = str( topology )
+ return eval( topoAsString )