Merge "[ONOS-7125] add/fix the SCPFintent related sanity check"
diff --git a/TestON/JenkinsFile/FUNCJenkinsFile b/TestON/JenkinsFile/FUNCJenkinsFile
index de05cee..3555299 100644
--- a/TestON/JenkinsFile/FUNCJenkinsFile
+++ b/TestON/JenkinsFile/FUNCJenkinsFile
@@ -40,15 +40,18 @@
for ( test in tests.keySet() ){
tests[test].call()
}
-if( prop["manualRun"] == "false" ){
- def end = new Date()
- TimeDuration duration = TimeCategory.minus( end, now )
- slackSend( color:"#5816EE", message: "FUNC tests ended at: " + end.toString() + "\nTime took : " + duration )
+try{
+ if( prop["manualRun"] == "false" ){
+ def end = new Date()
+ TimeDuration duration = TimeCategory.minus( end, now )
+ slackSend( color:"#5816EE", message: "FUNC tests ended at: " + end.toString() + "\nTime took : " + duration )
+ }
}
+catch(all){}
// The testName should be the key from the FUNC
def FUNCTest( testName, toBeRun, prop ) {
return {
- try{
+ catchError{
stage(testName) {
if ( toBeRun ){
workSpace = "/var/jenkins/workspace/"+testName
@@ -168,25 +171,21 @@
]
}
node("TestStation-VMs"){
- sh '''#!/bin/bash
-
- if [ -e ''' + workSpace + "/" + testName + "Result.txt ] && grep -q \"1\" " + workSpace + "/" + testName + "Result.txt" + '''
- then
- echo ''' + testName + " : All passed." + '''
- else
- echo ''' + testName + " : not all passed." + '''
- DoingThisToSetTheResultFalse
- fi'''
+ resultContents = readFile workSpace + "/" + testName + "Result.txt"
+ resultContents = resultContents.split("\n")
+ if( resultContents[ 0 ] == "1" ){
+ print "All passed"
+ }else{
+ print "Failed"
+ if( prop["manualRun"] == "false" )
+ slackSend(color:"FF0000", message: "[" + prop["ONOSBranch"] + "]" + testName + " : Failed!\n"
+ + resultContents[ 1 ] + "\n"
+ + "https://onos-jenkins.onlab.us/blue/organizations/jenkins/${env.JOB_NAME}/detail/${env.JOB_NAME}/${env.BUILD_NUMBER}/pipeline" )
+ Failed
+ }
}
}
}
- }catch (all) {
- catchError{
- if( prop["manualRun"] == "false" )
- slackSend(color:"FF0000", message: "[" + prop["ONOSBranch"] + "]" + testName + " : Failed!\n"
- + "https://onos-jenkins.onlab.us/blue/organizations/jenkins/${env.JOB_NAME}/detail/${env.JOB_NAME}/${env.BUILD_NUMBER}/pipeline" )
- Failed
- }
}
}
}
\ No newline at end of file
diff --git a/TestON/JenkinsFile/HAJenkinsFile b/TestON/JenkinsFile/HAJenkinsFile
index 685ffd6..8493f3c 100644
--- a/TestON/JenkinsFile/HAJenkinsFile
+++ b/TestON/JenkinsFile/HAJenkinsFile
@@ -41,15 +41,19 @@
for ( test in tests.keySet() ){
tests[test].call()
}
-if( prop["manualRun"] == "false" ){
- def end = new Date()
- TimeDuration duration = TimeCategory.minus( end, now )
- slackSend( color:"#5816EE", message: "HA tests ended at: " + end.toString() + "\nTime took : " + duration )
+try{
+ if( prop["manualRun"] == "false" ){
+ def end = new Date()
+ TimeDuration duration = TimeCategory.minus( end, now )
+ slackSend( color:"#5816EE", message: "HA tests ended at: " + end.toString() + "\nTime took : " + duration )
+ }
}
+catch(all){}
+
// The testName should be the key from the FUNC
def HATest( testName, toBeRun, prop ) {
return {
- try{
+ catchError{
stage(testName) {
if ( toBeRun ){
workSpace = "/var/jenkins/workspace/"+testName
@@ -169,25 +173,21 @@
]
}
node("TestStation-VMs"){
- sh '''#!/bin/bash
-
- if [ -e ''' + workSpace + "/" + testName + "Result.txt ] && grep -q \"1\" " + workSpace + "/" + testName + "Result.txt" + '''
- then
- echo ''' + testName + " : All passed." + '''
- else
- echo ''' + testName + " : not all passed." + '''
- DoingThisToSetTheResultFalse
- fi'''
+ resultContents = readFile workSpace + "/" + testName + "Result.txt"
+ resultContents = resultContents.split("\n")
+ if( resultContents[ 0 ] == "1" ){
+ print "All passed"
+ }else{
+ print "Failed"
+ if( prop["manualRun"] == "false" )
+ slackSend(color:"FF0000", message: "[" + prop["ONOSBranch"] + "]" + testName + " : Failed!\n"
+ + resultContents[ 1 ] + "\n"
+ + "https://onos-jenkins.onlab.us/blue/organizations/jenkins/${env.JOB_NAME}/detail/${env.JOB_NAME}/${env.BUILD_NUMBER}/pipeline" )
+ Failed
+ }
}
}
}
- }catch (all) {
- catchError{
- if( prop["manualRun"] == "false" )
- slackSend(color:"FF0000", message: "[" + prop["ONOSBranch"] + "]" + testName + " : Failed!\n"
- + "https://onos-jenkins.onlab.us/blue/organizations/jenkins/${env.JOB_NAME}/detail/${env.JOB_NAME}/${env.BUILD_NUMBER}/pipeline" )
- Failed
- }
}
}
}
\ No newline at end of file
diff --git a/TestON/JenkinsFile/SCPFJenkinsFile b/TestON/JenkinsFile/SCPFJenkinsFile
index d9593c4..fa75de2 100644
--- a/TestON/JenkinsFile/SCPFJenkinsFile
+++ b/TestON/JenkinsFile/SCPFJenkinsFile
@@ -13,7 +13,7 @@
SCPFcbench: [ test:'SCPFcbench', table:'cbench_bm_tests', results:'cbench_bm_results', file:'CbenchDB', rFile:'SCPFcbench.R', extra:none, finalResult:1, graphTitle:['Cbench Test'], dbCols:'avg', dbWhere:'', y_axis:'Throughput (Responses/sec)'],
SCPFhostLat: [ test:'SCPFhostLat', table:'host_latency_tests', results:'host_latency_results', file:'HostAddLatency', rFile:'SCPFhostLat.R', extra:none,finalResult:1, graphTitle:['Host Latency Test'], dbCols:'avg', dbWhere:'AND scale=5', y_axis:'Latency (ms)'],
SCPFportLat: [ test:'SCPFportLat', table:'port_latency_details', results:'port_latency_results', file:'/tmp/portEventResultDb', rFile:'SCPFportLat.R', extra:none, finalResult:1, graphTitle:['Port Latency Test - Port Up','Port Latency Test - Port Down'], dbCols:[ 'up_ofp_to_dev_avg,up_dev_to_link_avg,up_link_to_graph_avg', 'down_ofp_to_dev_avg,down_dev_to_link_avg,down_link_to_graph_avg' ], dbWhere:'AND scale=5', y_axis:'Latency (ms)' ],
- SCPFflowTp1g: [ test:'SCPFflowTp1g --params TEST/flows=12250', table:'flow_tp_tests', results:'flow_tp_results', file:'flowTP1gDB', rFile:'SCPFflowTp1g.R n', extra:neighbors,finalResult:1, graphTitle:['Flow Throughput Test - neighbors=0','Flow Throughput Test - neighbors=4'], dbCols:'avg', dbWhere:[ 'AND scale=5 AND neighbors=0 ','AND scale=5 AND NOT neighbors=0' ], y_axis:'Throughput (,000 Flows/sec)' ],
+ SCPFflowTp1g: [ test:'SCPFflowTp1g', table:'flow_tp_tests', results:'flow_tp_results', file:'flowTP1gDB', rFile:'SCPFflowTp1g.R n', extra:neighbors,finalResult:1, graphTitle:['Flow Throughput Test - neighbors=0','Flow Throughput Test - neighbors=4'], dbCols:'avg', dbWhere:[ 'AND scale=5 AND neighbors=0 ','AND scale=5 AND NOT neighbors=0' ], y_axis:'Throughput (,000 Flows/sec)' ],
SCPFflowTp1gWithFlowObj: [ test:'SCPFflowTp1g --params TEST/flowObj=True', table:'flow_tp_fobj_tests', results:'flow_tp_fobj_results', file:'flowTP1gDBFlowObj', rFile:'SCPFflowTp1g.R y', extra:neighbors, finalResult:0],
SCPFscaleTopo: [ test:'SCPFscaleTopo', table:'scale_topo_latency_details', results:'scale_topo_latency_results', file:'/tmp/scaleTopoResultDb', rFile:'SCPFscaleTopo.R', extra:none, finalResult:1, graphTitle:['Scale Topology Test'], dbCols:[ 'first_connection_to_last_connection, last_connection_to_last_role_request, last_role_request_to_last_topology' ], dbWhere:'AND scale=20' , y_axis:'Latency (s)'],
SCPFswitchLat: [ test:'SCPFswitchLat', table:'switch_latency_details', results:'switch_latency_results', file:'/tmp/switchEventResultDb', rFile:'SCPFswitchLat.R', extra:none, finalResult:1, graphTitle:['Switch Latency Test - Switch Up','Switch Latency Test - Switch Down'], dbCols:[ 'tcp_to_feature_reply_avg,feature_reply_to_role_request_avg,role_request_to_role_reply_avg,role_reply_to_device_avg,up_device_to_graph_avg', 'fin_ack_to_ack_avg,ack_to_device_avg,down_device_to_graph_avg' ], dbWhere:'AND scale=5', y_axis:'Latency (ms)' ],
@@ -54,15 +54,19 @@
for ( test in tests.keySet() ){
tests[test].call()
}
-if( prop["manualRun"] == "false" ){
- def end = new Date()
- TimeDuration duration = TimeCategory.minus( end, now )
- slackSend( color:"#5816EE", message: "SCPF tests ended at: " + end.toString() + "\nTime took : " + duration )
+try{
+ if( prop["manualRun"] == "false" ){
+ def end = new Date()
+ TimeDuration duration = TimeCategory.minus( end, now )
+ slackSend( color:"#5816EE", message: "SCPF tests ended at: " + end.toString() + "\nTime took : " + duration )
+ }
}
+catch(all){}
+
// The testName should be the key from the SCPF map
def SCPFTest( testName, toBeRun, prop ) {
return {
- try{
+ catchError{
stage(testName) {
if ( toBeRun ){
workSpace = "/var/jenkins/workspace/"+testName
@@ -161,25 +165,21 @@
def post = build job: "Pipeline_postjob_BM", propagate: false
}
node("TestStation-BMs"){
- sh '''#!/bin/bash
-
- if [ -e ''' + workSpace + "/*Result.txt ] && grep -q \"1\" " + workSpace + "/*Result.txt" + '''
- then
- echo ''' + testName + " : All passed." + '''
- else
- echo ''' + testName + " : not all passed." + '''
- DoingThisToSetTheResultFalse
- fi'''
+ resultContents = readFile workSpace + "/" + testName + "Result.txt"
+ resultContents = resultContents.split("\n")
+ if( resultContents[ 0 ] == "1" ){
+ print "All passed"
+ }else{
+ print "Failed"
+ if( prop["manualRun"] == "false" )
+ slackSend(color:"FF0000", message: "[" + prop["ONOSBranch"] + "]" + testName + " : Failed!\n"
+ + resultContents[ 1 ] + "\n"
+ + "https://onos-jenkins.onlab.us/blue/organizations/jenkins/${env.JOB_NAME}/detail/${env.JOB_NAME}/${env.BUILD_NUMBER}/pipeline" )
+ Failed
+ }
}
}
}
- }catch (all) {
- catchError{
- if( prop["manualRun"] == "false" )
- slackSend(color:"FF0000", message: "[" + prop["ONOSBranch"] + "]" + testName + " : Failed!\n"
- + "https://onos-jenkins.onlab.us/blue/organizations/jenkins/${env.JOB_NAME}/detail/${env.JOB_NAME}/${env.BUILD_NUMBER}/pipeline" )
- Failed
- }
}
}
}
@@ -196,9 +196,9 @@
def generateCombinedResultGraph( host, port, user, pass, testName, branchName ){
result = ""
for ( int i=0; i< SCPF[testName]['graphTitle'].size(); i++){
- result += "Rscript " + graph_generator_directory + "SCPFLineGraph.R " + host + " " + port + " " + user + " " + pass + " \"" + SCPF[testName]['graphTitle'][i] + "\" " + branchName + " " + 100 + " \"SELECT " +
+ result += "Rscript " + graph_generator_directory + "SCPFLineGraph.R " + host + " " + port + " " + user + " " + pass + " \"" + SCPF[testName]['graphTitle'][i] + "\" " + branchName + " " + 50 + " \"SELECT " +
checkIfList( testName, 'dbCols', i ) + " FROM " + SCPF[testName]['table'] + " WHERE branch=\'" + branchName + "\' " + checkIfList( testName, 'dbWhere', i ) +
- " ORDER BY date DESC LIMIT 100\" \"" + SCPF[testName]['y_axis'] + "\" " + graph_saved_directory + ";"
+ " ORDER BY date DESC LIMIT 50\" \"" + SCPF[testName]['y_axis'] + "\" " + graph_saved_directory + ";"
}
return result
}
diff --git a/TestON/JenkinsFile/USECASEJenkinsFile b/TestON/JenkinsFile/USECASEJenkinsFile
index 63551b9..bfae6c1 100644
--- a/TestON/JenkinsFile/USECASEJenkinsFile
+++ b/TestON/JenkinsFile/USECASEJenkinsFile
@@ -48,15 +48,19 @@
for ( test in tests.keySet() ){
tests[test].call()
}
-if( prop["manualRun"] == "false" ){
- def end = new Date()
- TimeDuration duration = TimeCategory.minus( end, now )
- slackSend( color:"#5816EE", message: "USECASE tests ended at: " + end.toString() + "\nTime took : " + duration )
+try{
+ if( prop["manualRun"] == "false" ){
+ def end = new Date()
+ TimeDuration duration = TimeCategory.minus( end, now )
+ slackSend( color:"#5816EE", message: "USECASE tests ended at: " + end.toString() + "\nTime took : " + duration )
+ }
}
+catch(all){}
+
// The testName should be the key from the FUNC
def USECASETest( testName, toBeRun, prop ) {
return {
- try{
+ catchError{
stage(testName) {
if ( toBeRun ){
workSpace = "/var/jenkins/workspace/"+testName
@@ -178,25 +182,21 @@
]
}
node("TestStation-BMs"){
- sh '''#!/bin/bash
-
- if [ -e ''' + workSpace + "/" + testName + "Result.txt ] && grep -q \"1\" " + workSpace + "/" + testName + "Result.txt" + '''
- then
- echo ''' + testName + " : All passed." + '''
- else
- echo ''' + testName + " : not all passed." + '''
- DoingThisToSetTheResultFalse
- fi'''
+ resultContents = readFile workSpace + "/" + testName + "Result.txt"
+ resultContents = resultContents.split("\n")
+ if( resultContents[ 0 ] == "1" ){
+ print "All passed"
+ }else{
+ print "Failed"
+ if( prop["manualRun"] == "false" )
+ slackSend(color:"FF0000", message: "[" + prop["ONOSBranch"] + "]" + testName + " : Failed!\n"
+ + resultContents[ 1 ] + "\n"
+ + "https://onos-jenkins.onlab.us/blue/organizations/jenkins/${env.JOB_NAME}/detail/${env.JOB_NAME}/${env.BUILD_NUMBER}/pipeline" )
+ Failed
+ }
}
}
}
- }catch (all) {
- catchError{
- if( prop["manualRun"] == "false" )
- slackSend(color:"FF0000", message: "[" + prop["ONOSBranch"] + "]" + testName + " : Failed!\n"
- + "https://onos-jenkins.onlab.us/blue/organizations/jenkins/${env.JOB_NAME}/detail/${env.JOB_NAME}/${env.BUILD_NUMBER}/pipeline" )
- Failed
- }
}
}
}
\ No newline at end of file
diff --git a/TestON/JenkinsFile/scripts/SCPFIntentInstallWithdrawRerouteLat.R b/TestON/JenkinsFile/scripts/SCPFIntentInstallWithdrawRerouteLat.R
index 98447ca..76352e8 100644
--- a/TestON/JenkinsFile/scripts/SCPFIntentInstallWithdrawRerouteLat.R
+++ b/TestON/JenkinsFile/scripts/SCPFIntentInstallWithdrawRerouteLat.R
@@ -149,9 +149,9 @@
print( "Generating fundamental graph data." )
-theme_set( theme_grey( base_size = 20 ) ) # set the default text size of the graph.
+theme_set( theme_grey( base_size = 22 ) ) # set the default text size of the graph.
-mainPlot <- ggplot( data = dataFrame, aes( x = scale, y = ms, ymin = ms - stds, ymax = ms + stds,fill = type ) )
+mainPlot <- ggplot( data = dataFrame, aes( x = scale, y = ms, ymin = ms, ymax = ms + stds, fill = type ) )
# Formatting the plot
width <- 1.3 # Width of the bars.
@@ -166,9 +166,7 @@
chartTitle <- paste( chartTitle, "\nBatch Size =" )
chartTitle <- paste( chartTitle, fileData1[ 1,'batch_size' ] )
-theme <- theme( plot.title=element_text( hjust = 0.5, size = 22, face='bold' ) )
-
-
+theme <- theme( plot.title=element_text( hjust = 0.5, size = 32, face='bold' ), legend.position="bottom", legend.text=element_text( size=22 ), legend.title = element_blank(), legend.key.size = unit( 1.5, 'lines' ) )
# Store plot configurations as 1 variable
fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme
@@ -179,14 +177,16 @@
# - width: the width of the bar types (declared above)
# geom_errorbar contains similar arguments as geom_bar.
print( "Generating bar graph with error bars." )
+colors <- scale_fill_manual( values=c( "#F77670", "#619DFA", "#18BA48" ) )
barGraphFormat <- geom_bar( stat = "identity", width = width, position = "dodge" )
-errorBarFormat <- geom_errorbar( width = width, position = "dodge", color=rgb( 140, 140, 140, maxColorValue=255 ) )
-title <- ggtitle( chartTitle )
-values <- geom_text( aes( x=dataFrame$scale, y=dataFrame$ms + 0.035 * max( dataFrame$ms ), label = format( dataFrame$ms, digits=3, big.mark = ",", scientific = FALSE ) ), position=position_dodge( width=1.3 ), size = 3.2, fontface = "bold" )
+errorBarFormat <- geom_errorbar( width = width, position = position_dodge( width ), color=rgb( 140, 140, 140, maxColorValue=255 ) )
-result <- fundamentalGraphData + barGraphFormat + errorBarFormat + title + values
+title <- ggtitle( chartTitle )
+values <- geom_text( aes( x=dataFrame$scale, y=dataFrame$ms + 0.035 * max( dataFrame$ms ), label = format( dataFrame$ms, digits=3, big.mark = ",", scientific = FALSE ) ), position=position_dodge( width=width ), size = 5.5, fontface = "bold" )
+wrapLegend <- guides( fill=guide_legend( nrow=1, byrow=TRUE ) )
+result <- fundamentalGraphData + barGraphFormat + colors + errorBarFormat + title + values + wrapLegend
# Save graph to file
print( paste( "Saving bar chart with error bars to", errBarOutputFile ) )
-ggsave( errBarOutputFile, width = 10, height = 6, dpi = 200 )
+ggsave( errBarOutputFile, width = 15, height = 10, dpi = 200 )
print( paste( "Successfully wrote bar chart with error bars out to", errBarOutputFile ) )
diff --git a/TestON/JenkinsFile/scripts/SCPFLineGraph.R b/TestON/JenkinsFile/scripts/SCPFLineGraph.R
index 376014d..15451a4 100644
--- a/TestON/JenkinsFile/scripts/SCPFLineGraph.R
+++ b/TestON/JenkinsFile/scripts/SCPFLineGraph.R
@@ -115,7 +115,7 @@
# - x: x-axis values (usually iterative, but it will become date # later)
# - y: y-axis values (usually tests)
# - color: the category of the colored lines (usually legend of test)
-theme_set( theme_grey( base_size = 20 ) ) # set the default text size of the graph.
+theme_set( theme_grey( base_size = 22 ) ) # set the default text size of the graph.
mainPlot <- ggplot( data = dataFrame, aes( x = iterative, y = Values, color = Legend ) )
print( "Formatting main plot." )
@@ -125,23 +125,25 @@
yScaleConfig <- scale_y_continuous( breaks = seq( 0, max( dataFrame$Values ) * 1.05, by = ceiling( max( dataFrame$Values ) / 10 ) ) )
-xLabel <- xlab( "Date" )
+xLabel <- xlab( "Time" )
yLabel <- ylab( args[ 9 ] )
fillLabel <- labs( fill="Type" )
legendLabels <- scale_colour_discrete( labels = names( fileData ) )
centerTitle <- theme( plot.title=element_text( hjust = 0.5 ) ) # To center the title text
-theme <- theme( axis.text.x = element_blank(), axis.ticks.x = element_blank(), plot.title = element_text( size = 28, face='bold' ) )
+theme <- theme( axis.text.x = element_blank(), axis.ticks.x = element_blank(), plot.title = element_text( size = 32, face='bold' ), legend.position="bottom", legend.text=element_text( size=22 ), legend.title = element_blank(), legend.key.size = unit( 1.5, 'lines' ), legend.direction = 'horizontal' )
+colors <- scale_color_manual( values=c( "#111111", "#008CFF", "#FF3700", "#00E043", "#EEB600", "#E500FF") )
+wrapLegend <- guides( color=guide_legend( nrow=2, byrow=TRUE ) )
-fundamentalGraphData <- fundamentalGraphData + yScaleConfig + xLabel + yLabel + fillLabel + legendLabels + centerTitle + theme
+fundamentalGraphData <- fundamentalGraphData + yScaleConfig + xLabel + yLabel + fillLabel + legendLabels + centerTitle + theme + colors
print( "Generating line graph." )
-lineGraphFormat <- geom_line()
-pointFormat <- geom_point( size = 0.2 )
+lineGraphFormat <- geom_line( size = 0.75 )
+pointFormat <- geom_point( size = 1.75 )
title <- ggtitle( title )
-result <- fundamentalGraphData + lineGraphFormat + pointFormat + title
+result <- fundamentalGraphData + lineGraphFormat + pointFormat + title + wrapLegend
# Save graph to file
print( paste( "Saving result graph to", outputFile ) )
-ggsave( outputFile, width = 10, height = 6, dpi = 200 )
-print( paste( "Successfully wrote result graph out to", outputFile ) )
\ No newline at end of file
+ggsave( outputFile, width = 15, height = 10, dpi = 200 )
+print( paste( "Successfully wrote result graph out to", outputFile ) )
diff --git a/TestON/JenkinsFile/scripts/SCPFbatchFlowResp.R b/TestON/JenkinsFile/scripts/SCPFbatchFlowResp.R
index 72f66c7..8d0b6b4 100644
--- a/TestON/JenkinsFile/scripts/SCPFbatchFlowResp.R
+++ b/TestON/JenkinsFile/scripts/SCPFbatchFlowResp.R
@@ -93,15 +93,16 @@
print( "Generating fundamental graph data." )
-theme_set( theme_grey( base_size = 20 ) ) # set the default text size of the graph.
+theme_set( theme_grey( base_size = 22 ) ) # set the default text size of the graph.
mainPlot <- ggplot( data = dataFrame, aes( x = iterative, y = ms, fill = type ) )
xScaleConfig <- scale_x_continuous( breaks = dataFrame$iterative, label = dataFrame$date )
xLabel <- xlab( "Build Date" )
yLabel <- ylab( "Latency (ms)" )
fillLabel <- labs( fill="Type" )
-theme <- theme( plot.title=element_text( hjust = 0.5, size = 28, face='bold' ) )
-
+theme <- theme( plot.title=element_text( hjust = 0.5, size = 32, face='bold' ), legend.position="bottom", legend.text=element_text( size=22 ), legend.title = element_blank(), legend.key.size = unit( 1.5, 'lines' ) )
+colors <- scale_fill_manual( values=c( "#F77670", "#619DFA" ) )
+wrapLegend <- guides( fill=guide_legend( nrow=1, byrow=TRUE ) )
fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme
@@ -109,13 +110,13 @@
width <- 0.3
barGraphFormat <- geom_bar( stat="identity", width = width )
sum <- fileData[ 'posttoconfrm' ] + fileData[ 'elapsepost' ]
-values <- geom_text( aes( x=dataFrame$iterative, y=sum + 0.04 * max( sum ), label = format( sum, digits=3, big.mark = ",", scientific = FALSE ) ), size = 5, fontface = "bold" )
+values <- geom_text( aes( x=dataFrame$iterative, y=sum + 0.03 * max( sum ), label = format( sum, digits=3, big.mark = ",", scientific = FALSE ) ), size = 7.0, fontface = "bold" )
title <- ggtitle( chartTitle )
-result <- fundamentalGraphData + barGraphFormat + title + values
+result <- fundamentalGraphData + barGraphFormat + colors + title + values
print( paste( "Saving bar chart to", errBarOutputFile ) )
-ggsave( errBarOutputFile, width = 10, height = 6, dpi = 200 )
+ggsave( errBarOutputFile, width = 15, height = 10, dpi = 200 )
print( paste( "Successfully wrote stacked bar chart out to", errBarOutputFile ) )
@@ -151,32 +152,33 @@
print( "Generating fundamental graph data." )
-theme_set( theme_grey( base_size = 20 ) ) # set the default text size of the graph.
+theme_set( theme_grey( base_size = 22 ) ) # set the default text size of the graph.
mainPlot <- ggplot( data = dataFrame, aes( x = iterative, y = ms, fill = type ) )
xScaleConfig <- scale_x_continuous( breaks = dataFrame$iterative, label = dataFrame$date )
xLabel <- xlab( "Build Date" )
yLabel <- ylab( "Latency (ms)" )
fillLabel <- labs( fill="Type" )
-theme <- theme( plot.title=element_text( hjust = 0.5, size = 28, face='bold' ) )
-
-fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme
+theme <- theme( plot.title=element_text( hjust = 0.5, size = 32, face='bold' ), legend.position="bottom", legend.text=element_text( size=22 ), legend.title = element_blank(), legend.key.size = unit( 1.5, 'lines' ) )
+colors <- scale_fill_manual( values=c( "#F77670", "#619DFA" ) )
+wrapLegend <- guides( fill=guide_legend( nrow=1, byrow=TRUE ) )
+fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme + wrapLegend
print( "Generating bar graph." )
width <- 0.3
barGraphFormat <- geom_bar( stat="identity", width = width )
sum <- fileData[ 'deltoconfrm' ] + fileData[ 'elapsedel' ]
-values <- geom_text( aes( x=dataFrame$iterative, y=sum + 0.04 * max( sum ), label = format( sum, digits=3, big.mark = ",", scientific = FALSE ) ), size = 5, fontface = "bold" )
+values <- geom_text( aes( x=dataFrame$iterative, y=sum + 0.03 * max( sum ), label = format( sum, digits=3, big.mark = ",", scientific = FALSE ) ), size = 7.0, fontface = "bold" )
chartTitle <- paste( "Single Bench Flow Latency - Del", "Last 3 Builds", sep = "\n" )
title <- ggtitle( chartTitle )
-result <- fundamentalGraphData + barGraphFormat + title + values
+result <- fundamentalGraphData + barGraphFormat + colors + title + values
errBarOutputFile <- paste( args[ 7 ], args[ 5 ], sep="" )
errBarOutputFile <- paste( errBarOutputFile, args[ 6 ], sep="_" )
errBarOutputFile <- paste( errBarOutputFile, "_DelGraph.jpg", sep="" )
print( paste( "Saving bar chart to", errBarOutputFile ) )
-ggsave( errBarOutputFile, width = 10, height = 6, dpi = 200 )
+ggsave( errBarOutputFile, width = 15, height = 10, dpi = 200 )
print( paste( "Successfully wrote stacked bar chart out to", errBarOutputFile ) )
\ No newline at end of file
diff --git a/TestON/JenkinsFile/scripts/SCPFcbench.R b/TestON/JenkinsFile/scripts/SCPFcbench.R
index c9a6c37..55e3978 100644
--- a/TestON/JenkinsFile/scripts/SCPFcbench.R
+++ b/TestON/JenkinsFile/scripts/SCPFcbench.R
@@ -93,14 +93,14 @@
print( "Generating fundamental graph data." )
-theme_set( theme_grey( base_size = 20 ) ) # set the default text size of the graph.
+theme_set( theme_grey( base_size = 22 ) ) # set the default text size of the graph.
-mainPlot <- ggplot( data = dataFrame, aes( x = iterative, y = ms, ymin = ms - std, ymax = ms + std ) )
-xScaleConfig <- scale_x_continuous( breaks = dataFrame$iterative, label = dataFrame$date )
+mainPlot <- ggplot( data = dataFrame, aes( x = iterative, y = ms, ymin = ms, ymax = ms + std ) )
+xScaleConfig <- scale_x_continuous( breaks = dataFrame$iterative, label = dataFrame$date )
xLabel <- xlab( "Build Date" )
yLabel <- ylab( "Responses / sec" )
fillLabel <- labs( fill="Type" )
-theme <- theme( plot.title=element_text( hjust = 0.5, size = 28, face='bold' ) )
+theme <- theme( plot.title=element_text( hjust = 0.5, size = 32, face='bold' ), legend.position="bottom", legend.text=element_text( size=18, face="bold" ), legend.title = element_blank() )
fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme
@@ -108,12 +108,12 @@
print( "Generating bar graph with error bars." )
width <- 0.3
barGraphFormat <- geom_bar( stat="identity", position = position_dodge(), width = width, fill="#00AA13" )
-errorBarFormat <- geom_errorbar( width = width, color=rgb( 140, 140,140, maxColorValue=255 ) )
-values <- geom_text( aes( x=dataFrame$iterative, y=fileData[ 'avg' ] + 0.025 * max( fileData[ 'avg' ] ), label = format( fileData[ 'avg' ], digits=3, big.mark = ",", scientific = FALSE ) ), size = 4.5, fontface = "bold" )
+errorBarFormat <- geom_errorbar( width = width, color=rgb( 140,140,140, maxColorValue=255 ) )
+values <- geom_text( aes( x=dataFrame$iterative, y=fileData[ 'avg' ] + 0.025 * max( fileData[ 'avg' ] ), label = format( fileData[ 'avg' ], digits=3, big.mark = ",", scientific = FALSE ) ), size = 7.0, fontface = "bold" )
title <- ggtitle( chartTitle )
result <- fundamentalGraphData + barGraphFormat + errorBarFormat + title + values
print( paste( "Saving bar chart with error bars to", errBarOutputFile ) )
-ggsave( errBarOutputFile, width = 10, height = 6, dpi = 200 )
+ggsave( errBarOutputFile, width = 15, height = 10, dpi = 200 )
print( paste( "Successfully wrote bar chart with error bars out to", errBarOutputFile ) )
diff --git a/TestON/JenkinsFile/scripts/SCPFflowTp1g.R b/TestON/JenkinsFile/scripts/SCPFflowTp1g.R
index 8ec053e..26584ad 100644
--- a/TestON/JenkinsFile/scripts/SCPFflowTp1g.R
+++ b/TestON/JenkinsFile/scripts/SCPFflowTp1g.R
@@ -135,9 +135,9 @@
# - y: y-axis values (usually time in milliseconds)
# - fill: the category of the colored side-by-side bars (usually type)
-theme_set( theme_grey( base_size = 20 ) ) # set the default text size of the graph.
+theme_set( theme_grey( base_size = 22 ) ) # set the default text size of the graph.
-mainPlot <- ggplot( data = dataFrame, aes( x = scale, y = throughput, ymin = throughput - std, ymax = throughput + std, fill = type ) )
+mainPlot <- ggplot( data = dataFrame, aes( x = scale, y = throughput, ymin = throughput, ymax = throughput + std, fill = type ) )
# Formatting the plot
width <- 0.7 # Width of the bars.
@@ -156,7 +156,7 @@
chartTitle <- paste( chartTitle, "0" )
}
-theme <- theme( plot.title=element_text( hjust = 0.5, size = 28, face='bold' ) )
+theme <- theme( plot.title=element_text( hjust = 0.5, size = 32, face='bold' ) )
# Store plot configurations as 1 variable
@@ -169,13 +169,13 @@
# - width: the width of the bar types (declared above)
# geom_errorbar contains similar arguments as geom_bar.
print( "Generating bar graph with error bars." )
-barGraphFormat <- geom_bar( stat = "identity", width = width, fill="#FFA94F" )
+barGraphFormat <- geom_bar( stat = "identity", width = width, fill="#FFAA3C" )
errorBarFormat <- geom_errorbar( width = width, position=position_dodge(), color=rgb( 140,140,140, maxColorValue=255 ) )
-values <- geom_text( aes( x=dataFrame$scale, y=dataFrame$throughput + 0.04 * max( dataFrame$throughput ), label = format( dataFrame$throughput, digits=3, big.mark = ",", scientific = FALSE ) ), size = 5, fontface = "bold" )
+values <- geom_text( aes( x=dataFrame$scale, y=dataFrame$throughput + 0.03 * max( dataFrame$throughput ), label = format( dataFrame$throughput, digits=3, big.mark = ",", scientific = FALSE ) ), size = 7.0, fontface = "bold" )
title <- ggtitle( paste( chartTitle, "" ) )
result <- fundamentalGraphData + barGraphFormat + errorBarFormat + title + values
# Save graph to file
print( paste( "Saving bar chart with error bars to", errBarOutputFile ) )
-ggsave( errBarOutputFile, width = 10, height = 6, dpi = 200 )
+ggsave( errBarOutputFile, width = 15, height = 10, dpi = 200 )
print( paste( "Successfully wrote bar chart with error bars out to", errBarOutputFile ) )
diff --git a/TestON/JenkinsFile/scripts/SCPFhostLat.R b/TestON/JenkinsFile/scripts/SCPFhostLat.R
index 738765a..f60fc59 100644
--- a/TestON/JenkinsFile/scripts/SCPFhostLat.R
+++ b/TestON/JenkinsFile/scripts/SCPFhostLat.R
@@ -94,27 +94,27 @@
print( "Generating fundamental graph data." )
-theme_set( theme_grey( base_size = 20 ) ) # set the default text size of the graph.
-mainPlot <- ggplot( data = dataFrame, aes( x = scale, y = ms, ymin = ms - std, ymax = ms + std ) )
+theme_set( theme_grey( base_size = 22 ) ) # set the default text size of the graph.
+mainPlot <- ggplot( data = dataFrame, aes( x = scale, y = ms, ymin = ms, ymax = ms + std ) )
xScaleConfig <- scale_x_continuous( breaks=c( 1, 3, 5, 7, 9) )
xLabel <- xlab( "Scale" )
yLabel <- ylab( "Latency (ms)" )
fillLabel <- labs( fill="Type" )
-theme <- theme( plot.title=element_text( hjust = 0.5, size = 28, face='bold' ) )
+theme <- theme( plot.title=element_text( hjust = 0.5, size = 32, face='bold' ) )
fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme
print( "Generating bar graph with error bars." )
width <- 0.9
-barGraphFormat <- geom_bar( stat="identity", position=position_dodge( ), width = width, fill="#E8BD00" )
+barGraphFormat <- geom_bar( stat="identity", position=position_dodge( ), width = width, fill="#A700EF" )
errorBarFormat <- geom_errorbar( position=position_dodge(), width = width, color=rgb( 140, 140, 140, maxColorValue=255 ) )
-values <- geom_text( aes( x=dataFrame$scale, y=dataFrame$ms + 0.08 * max( dataFrame$ms ), label = format( dataFrame$ms, digits=3, big.mark = ",", scientific = FALSE ) ), size = 5, fontface = "bold" )
-title <- ggtitle( paste( chartTitle, "with Standard Error Bars" ) )
+values <- geom_text( aes( x=dataFrame$scale, y=dataFrame$ms + 0.06 * max( dataFrame$ms ), label = format( dataFrame$ms, digits=3, big.mark = ",", scientific = FALSE ) ), size = 7.0, fontface = "bold" )
+title <- ggtitle( paste( chartTitle, "" ) )
result <- fundamentalGraphData + barGraphFormat + errorBarFormat + title + values
print( paste( "Saving bar chart with error bars to", errBarOutputFile ) )
-ggsave( errBarOutputFile, width = 10, height = 6, dpi = 200 )
+ggsave( errBarOutputFile, width = 15, height = 10, dpi = 200 )
print( paste( "Successfully wrote bar chart out to", errBarOutputFile ) )
\ No newline at end of file
diff --git a/TestON/JenkinsFile/scripts/SCPFintentEventTp.R b/TestON/JenkinsFile/scripts/SCPFintentEventTp.R
index 420b444..471fc7a 100644
--- a/TestON/JenkinsFile/scripts/SCPFintentEventTp.R
+++ b/TestON/JenkinsFile/scripts/SCPFintentEventTp.R
@@ -133,7 +133,7 @@
# - x: x-axis values (usually node scaling)
# - y: y-axis values (usually time in milliseconds)
# - fill: the category of the colored side-by-side bars (usually type)
-theme_set( theme_grey( base_size = 20 ) ) # set the default text size of the graph.
+theme_set( theme_grey( base_size = 22 ) ) # set the default text size of the graph.
mainPlot <- ggplot( data = dataFrame, aes( x = scale, y = throughput, fill = type ) )
@@ -154,8 +154,8 @@
chartTitle <- paste( chartTitle, "0" )
}
-theme <- theme( plot.title=element_text( hjust = 0.5, size = 28, face='bold' ) )
-values <- geom_text( aes( x=dataFrame$scale, y=dataFrame$throughput + 0.04 * max( dataFrame$throughput ), label = format( dataFrame$throughput, digits=3, big.mark = ",", scientific = FALSE ) ), size = 5, fontface = "bold" )
+theme <- theme( plot.title=element_text( hjust = 0.5, size = 32, face='bold' ), legend.position="bottom", legend.text=element_text( size=18, face="bold" ), legend.title = element_blank() )
+values <- geom_text( aes( x=dataFrame$scale, y=dataFrame$throughput + 0.03 * max( dataFrame$throughput ), label = format( dataFrame$throughput, digits=3, big.mark = ",", scientific = FALSE ) ), size = 7, fontface = "bold" )
# Store plot configurations as 1 variable
fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme + values
@@ -168,6 +168,6 @@
# Save graph to file
print( paste( "Saving bar chart to", errBarOutputFile ) )
-ggsave( errBarOutputFile, width = 10, height = 6, dpi = 200 )
+ggsave( errBarOutputFile, width = 15, height = 10, dpi = 200 )
print( paste( "Successfully wrote bar chart out to", errBarOutputFile ) )
diff --git a/TestON/JenkinsFile/scripts/SCPFmastershipFailoverLat.R b/TestON/JenkinsFile/scripts/SCPFmastershipFailoverLat.R
index 9eea330..90bcb8d 100644
--- a/TestON/JenkinsFile/scripts/SCPFmastershipFailoverLat.R
+++ b/TestON/JenkinsFile/scripts/SCPFmastershipFailoverLat.R
@@ -111,29 +111,31 @@
print( "Generating fundamental graph data." )
-theme_set( theme_grey( base_size = 20 ) ) # set the default text size of the graph.
+theme_set( theme_grey( base_size = 22 ) ) # set the default text size of the graph.
-mainPlot <- ggplot( data = avgData, aes( x = scale, y = ms, ymin = ms - stdData$ms, ymax = ms + stdData$ms,fill = type ) )
+mainPlot <- ggplot( data = avgData, aes( x = scale, y = ms, ymin = ms, ymax = ms + stdData$ms,fill = type ) )
xScaleConfig <- scale_x_continuous( breaks=c( 1, 3, 5, 7, 9) )
xLabel <- xlab( "Scale" )
yLabel <- ylab( "Latency (ms)" )
fillLabel <- labs( fill="Type" )
-theme <- theme( plot.title=element_text( hjust = 0.5, size = 28, face='bold' ) )
+theme <- theme( plot.title=element_text( hjust = 0.5, size = 32, face='bold' ), legend.position="bottom", legend.text=element_text( size=22 ), legend.title = element_blank(), legend.key.size = unit( 1.5, 'lines' ) )
+wrapLegend <- guides( fill=guide_legend( nrow=1, byrow=TRUE ) )
-fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme
+fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme + wrapLegend
print( "Generating bar graph with error bars." )
width <- 0.9
barGraphFormat <- geom_bar( stat="identity", position=position_dodge(), width = width )
+colors <- scale_fill_manual( values=c( "#F77670", "#619DFA" ) )
errorBarFormat <- geom_errorbar( width = width, position=position_dodge(), color=rgb( 140, 140, 140, maxColorValue=255 ) )
-values <- geom_text( aes( x=avgData$scale, y=avgData$ms + 0.04 * max( avgData$ms ), label = format( avgData$ms, digits=3, big.mark = ",", scientific = FALSE ) ), size = 5, fontface = "bold", position=position_dodge( 0.9 ) )
+values <- geom_text( aes( x=avgData$scale, y=avgData$ms + 0.02 * max( avgData$ms ), label = format( avgData$ms, digits=3, big.mark = ",", scientific = FALSE ) ), size = 7.0, fontface = "bold", position=position_dodge( 0.9 ) )
title <- ggtitle( paste( chartTitle, "" ) )
-result <- fundamentalGraphData + barGraphFormat + errorBarFormat + title + values
+result <- fundamentalGraphData + barGraphFormat + colors + errorBarFormat + title + values
print( paste( "Saving bar chart with error bars to", errBarOutputFile ) )
-ggsave( errBarOutputFile, width = 10, height = 6, dpi = 200 )
+ggsave( errBarOutputFile, width = 15, height = 10, dpi = 200 )
print( paste( "Successfully wrote bar chart with error bars out to", errBarOutputFile ) )
@@ -143,12 +145,12 @@
stackedBarFormat <- geom_bar( stat="identity", width=width )
title <- ggtitle( paste( chartTitle, "" ) )
sum <- fileData[ 'deact_role_avg' ] + fileData[ 'kill_deact_avg' ]
-values <- geom_text( aes( x=avgData$scale, y=sum + 0.04 * max( sum ), label = format( sum, digits=3, big.mark = ",", scientific = FALSE ) ), size = 5, fontface = "bold" )
-result <- fundamentalGraphData + stackedBarFormat + title + values
+values <- geom_text( aes( x=avgData$scale, y=sum + 0.02 * max( sum ), label = format( sum, digits=3, big.mark = ",", scientific = FALSE ) ), size = 7.0, fontface = "bold" )
+result <- fundamentalGraphData + stackedBarFormat + colors + title + values
print( paste( "Saving stacked bar chart to", stackedBarOutputFile ) )
-ggsave( stackedBarOutputFile, width = 10, height = 6, dpi = 200 )
+ggsave( stackedBarOutputFile, width = 15, height = 10, dpi = 200 )
print( paste( "Successfully wrote stacked bar chart out to", stackedBarOutputFile ) )
\ No newline at end of file
diff --git a/TestON/JenkinsFile/scripts/SCPFportLat.R b/TestON/JenkinsFile/scripts/SCPFportLat.R
index fd24c8d..0f9176a 100644
--- a/TestON/JenkinsFile/scripts/SCPFportLat.R
+++ b/TestON/JenkinsFile/scripts/SCPFportLat.R
@@ -111,28 +111,30 @@
print( "Generating fundamental graph data (Port Up Latency)." )
width <- 1
-theme_set( theme_grey( base_size = 20 ) ) # set the default text size of the graph.
+theme_set( theme_grey( base_size = 22 ) ) # set the default text size of the graph.
-mainPlot <- ggplot( data = upAvgsData, aes( x = scale, y = ms, fill = type, ymin = fileData[ 'up_end_to_end_avg' ] - stds, ymax = fileData[ 'up_end_to_end_avg' ] + stds ) )
+mainPlot <- ggplot( data = upAvgsData, aes( x = scale, y = ms, fill = type, ymin = fileData[ 'up_end_to_end_avg' ], ymax = fileData[ 'up_end_to_end_avg' ] + stds ) )
xScaleConfig <- scale_x_continuous( breaks=c( 1, 3, 5, 7, 9) )
xLabel <- xlab( "Scale" )
yLabel <- ylab( "Latency (ms)" )
fillLabel <- labs( fill="Type" )
-theme <- theme( plot.title=element_text( hjust = 0.5, size = 28, face='bold' ) )
+theme <- theme( plot.title=element_text( hjust = 0.5, size = 32, face='bold' ), legend.position="bottom", legend.text=element_text( size=22 ), legend.title = element_blank(), legend.key.size = unit( 1.5, 'lines' ) )
+colors <- scale_fill_manual( values=c( "#F77670", "#619DFA", "#18BA48" ) )
+wrapLegend <- guides( fill=guide_legend( nrow=1, byrow=TRUE ) )
-fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme
+fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme + wrapLegend
print( "Generating bar graph with error bars (Port Up Latency)." )
barGraphFormat <- geom_bar( stat="identity", width = width )
errorBarFormat <- geom_errorbar( width = width, color=rgb( 140, 140, 140, maxColorValue=255 ) )
sum <- fileData[ 'up_ofp_to_dev_avg' ] + fileData[ 'up_dev_to_link_avg' ] + fileData[ 'up_link_to_graph_avg' ]
-values <- geom_text( aes( x=upAvgsData$scale, y=sum + 0.04 * max( sum ), label = format( sum, digits=3, big.mark = ",", scientific = FALSE ) ), size = 5, fontface = "bold" )
+values <- geom_text( aes( x=upAvgsData$scale, y=sum + 0.03 * max( sum ), label = format( sum, digits=3, big.mark = ",", scientific = FALSE ) ), size = 7.0, fontface = "bold" )
title <- ggtitle( "Port Up Latency" )
-result <- fundamentalGraphData + barGraphFormat + errorBarFormat + title + values
+result <- fundamentalGraphData + barGraphFormat + colors + errorBarFormat + title + values
print( paste( "Saving bar chart with error bars (Port Up Latency) to", errBarOutputFileUp ) )
-ggsave( errBarOutputFileUp, width = 10, height = 6, dpi = 200 )
+ggsave( errBarOutputFileUp, width = 15, height = 10, dpi = 200 )
print( paste( "Successfully wrote bar chart with error bars (Port Up Latency) out to", errBarOutputFileUp ) )
@@ -140,23 +142,23 @@
print( "Generating fundamental graph data (Port Down Latency)." )
-mainPlot <- ggplot( data = downAvgsData, aes( x = scale, y = ms, fill = type, ymin = fileData[ 'down_end_to_end_avg' ] - stds, ymax = fileData[ 'down_end_to_end_avg' ] + stds ) )
-theme <- theme( plot.title=element_text( hjust = 0.5, size = 28, face='bold' ) )
+mainPlot <- ggplot( data = downAvgsData, aes( x = scale, y = ms, fill = type, ymin = fileData[ 'down_end_to_end_avg' ], ymax = fileData[ 'down_end_to_end_avg' ] + stds ) )
+wrapLegend <- guides( fill=guide_legend( nrow=1, byrow=TRUE ) )
-fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme
+fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme + wrapLegend
print( "Generating bar graph with error bars (Port Down Latency)." )
barGraphFormat <- geom_bar( stat="identity", width = width )
errorBarFormat <- geom_errorbar( width = width, color=rgb( 140, 140, 140, maxColorValue=255 ) )
sum <- fileData[ 'down_ofp_to_dev_avg' ] + fileData[ 'down_dev_to_link_avg' ] + fileData[ 'down_link_to_graph_avg' ]
-values <- geom_text( aes( x=downAvgsData$scale, y=sum + 0.04 * max( sum ), label = format( sum, digits=3, big.mark = ",", scientific = FALSE ) ), size = 5, fontface = "bold" )
+values <- geom_text( aes( x=downAvgsData$scale, y=sum + 0.03 * max( sum ), label = format( sum, digits=3, big.mark = ",", scientific = FALSE ) ), size = 7.0, fontface = "bold" )
title <- ggtitle( "Port Down Latency" )
-result <- fundamentalGraphData + barGraphFormat + errorBarFormat + title + values
+result <- fundamentalGraphData + barGraphFormat + colors + errorBarFormat + title + values
print( paste( "Saving bar chart with error bars (Port Down Latency) to", errBarOutputFileDown ) )
-ggsave( errBarOutputFileDown, width = 10, height = 6, dpi = 200 )
+ggsave( errBarOutputFileDown, width = 15, height = 10, dpi = 200 )
print( paste( "Successfully wrote bar chart with error bars (Port Down Latency) out to", errBarOutputFileDown ) )
diff --git a/TestON/JenkinsFile/scripts/SCPFscaleTopo.R b/TestON/JenkinsFile/scripts/SCPFscaleTopo.R
index 195019d..6be3533 100644
--- a/TestON/JenkinsFile/scripts/SCPFscaleTopo.R
+++ b/TestON/JenkinsFile/scripts/SCPFscaleTopo.R
@@ -77,7 +77,7 @@
# Parse lists into data frames.
dataFrame <- melt( avgs ) # This is where reshape2 comes in. Avgs list is converted to data frame
dataFrame$scale <- fileData$scale # Add node scaling to the data frame.
-colnames( dataFrame ) <- c( "ms", "type", "scale")
+colnames( dataFrame ) <- c( "s", "type", "scale")
# Format data frame so that the data is in the same order as it appeared in the file.
@@ -117,20 +117,20 @@
# - x: x-axis values (usually node scaling)
# - y: y-axis values (usually time in milliseconds)
# - fill: the category of the colored side-by-side bars (usually type)
-mainPlot <- ggplot( data = dataFrame, aes( x = iterative, y = ms, fill = type ) )
+mainPlot <- ggplot( data = dataFrame, aes( x = iterative, y = s, fill = type ) )
# Formatting the plot
width <- 0.6 # Width of the bars.
xScaleConfig <- scale_x_continuous( breaks = dataFrame$iterative, label = dataFrame$scale )
xLabel <- xlab( "Scale" )
-yLabel <- ylab( "Latency (ms)" )
+yLabel <- ylab( "Latency (s)" )
fillLabel <- labs( fill="Type" )
chartTitle <- paste( "Scale Topology Latency Test" )
-theme <- theme( plot.title=element_text( hjust = 0.5, size = 28, face='bold' ) )
-values <- geom_text( aes( x=dataFrame$iterative, y=sum + 0.02 * max( sum ), label = format( sum, big.mark = ",", scientific = FALSE ), fontface = "bold" ) )
-
+theme <- theme( plot.title=element_text( hjust = 0.5, size = 32, face='bold' ), legend.position="bottom", legend.text=element_text( size=22 ), legend.title = element_blank(), legend.key.size = unit( 1.5, 'lines' ) )
+values <- geom_text( aes( x=dataFrame$iterative, y=sum + 0.02 * max( sum ), label = format( sum, big.mark = ",", scientific = FALSE ), fontface = "bold" ), size = 7.0 )
+wrapLegend <- guides( fill=guide_legend( nrow=2, byrow=TRUE ) )
# Store plot configurations as 1 variable
-fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme + values
+fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme + values + wrapLegend
print( "Generating bar graph." )
barGraphFormat <- geom_bar( stat = "identity", width = width )
@@ -139,5 +139,5 @@
# Save graph to file
print( paste( "Saving bar chart to", outputFile ) )
-ggsave( outputFile, width = 10, height = 6, dpi = 200 )
+ggsave( outputFile, width = 15, height = 10, dpi = 200 )
print( paste( "Successfully wrote bar chart out to", outputFile ) )
diff --git a/TestON/JenkinsFile/scripts/SCPFscalingMaxIntents.R b/TestON/JenkinsFile/scripts/SCPFscalingMaxIntents.R
index 02f4f28..0f09023 100644
--- a/TestON/JenkinsFile/scripts/SCPFscalingMaxIntents.R
+++ b/TestON/JenkinsFile/scripts/SCPFscalingMaxIntents.R
@@ -110,27 +110,28 @@
print( "Generating fundamental graph data." )
-theme_set( theme_grey( base_size = 20 ) ) # set the default text size of the graph.
+theme_set( theme_grey( base_size = 22 ) ) # set the default text size of the graph.
mainPlot <- ggplot( data = dataFrame, aes( x = scale, y = ms, fill = type ) )
xScaleConfig <- scale_x_continuous( breaks=c( 1, 3, 5, 7, 9) )
xLabel <- xlab( "Scale" )
yLabel <- ylab( "Max Number of Intents/Flow Rules" )
fillLabel <- labs( fill="Type" )
-theme <- theme( plot.title=element_text( hjust = 0.5, size = 28, face='bold' ) )
-
-fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme
+theme <- theme( plot.title=element_text( hjust = 0.5, size = 32, face='bold' ), legend.position="bottom", legend.text=element_text( size=22 ), legend.title = element_blank(), legend.key.size = unit( 1.5, 'lines' ) )
+colors <- scale_fill_manual( values=c( "#F77670", "#619DFA" ) )
+wrapLegend <- guides( fill=guide_legend( nrow=1, byrow=TRUE ) )
+fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme + wrapLegend
print( "Generating bar graph bars." )
width <- 1.3
barGraphFormat <- geom_bar( stat="identity", position=position_dodge( ), width = width )
-values <- geom_text( aes( x=dataFrame$scale, y=dataFrame$ms + 0.02 * max( dataFrame$ms ), label = format( dataFrame$ms, digits=3, big.mark = ",", scientific = FALSE ) ), size = 3.2, fontface = "bold", position=position_dodge( width=1.25 ) )
+values <- geom_text( aes( x=dataFrame$scale, y=dataFrame$ms + 0.015 * max( dataFrame$ms ), label = format( dataFrame$ms, digits=3, big.mark = ",", scientific = FALSE ) ), size = 5.2, fontface = "bold", position=position_dodge( width=1.25 ) )
title <- ggtitle( chartTitle )
-result <- fundamentalGraphData + barGraphFormat + title + values
+result <- fundamentalGraphData + barGraphFormat + colors + title + values
print( paste( "Saving bar chart to", outputFile ) )
-ggsave( outputFile, width = 10, height = 6, dpi = 200 )
+ggsave( outputFile, width = 15, height = 10, dpi = 200 )
print( paste( "Successfully wrote bar chart out to", outputFile ) )
diff --git a/TestON/JenkinsFile/scripts/SCPFswitchLat.R b/TestON/JenkinsFile/scripts/SCPFswitchLat.R
index 8a03863..7bf0a44 100644
--- a/TestON/JenkinsFile/scripts/SCPFswitchLat.R
+++ b/TestON/JenkinsFile/scripts/SCPFswitchLat.R
@@ -107,14 +107,14 @@
print( "Generating fundamental graph data (Switch Up Latency)." )
width <- 1
-theme_set( theme_grey( base_size = 20 ) ) # set the default text size of the graph.
+theme_set( theme_grey( base_size = 22 ) ) # set the default text size of the graph.
-mainPlot <- ggplot( data = upAvgsData, aes( x = scale, y = ms, fill = type, ymin = fileData[ 'up_end_to_end_avg' ] - stds, ymax = fileData[ 'up_end_to_end_avg' ] + stds ) )
+mainPlot <- ggplot( data = upAvgsData, aes( x = scale, y = ms, fill = type, ymin = fileData[ 'up_end_to_end_avg' ], ymax = fileData[ 'up_end_to_end_avg' ] + stds ) )
xScaleConfig <- scale_x_continuous( breaks=c( 1, 3, 5, 7, 9) )
xLabel <- xlab( "Scale" )
yLabel <- ylab( "Latency (ms)" )
fillLabel <- labs( fill="Type" )
-theme <- theme( plot.title=element_text( hjust = 0.5, size = 28, face='bold' ) )
+theme <- theme( plot.title=element_text( hjust = 0.5, size = 32, face='bold' ), legend.position="bottom", legend.text=element_text( size=22 ), legend.title = element_blank(), legend.key.size = unit( 1.5, 'lines' ) )
fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme
@@ -122,13 +122,14 @@
barGraphFormat <- geom_bar( stat="identity", width = width )
errorBarFormat <- geom_errorbar( width = width, color=rgb( 140, 140, 140, maxColorValue=255 ) )
sum <- fileData[ 'up_device_to_graph_avg' ] + fileData[ 'role_reply_to_device_avg' ] + fileData[ 'role_request_to_role_reply_avg' ] + fileData[ 'feature_reply_to_role_request_avg' ] + fileData[ 'tcp_to_feature_reply_avg' ]
-values <- geom_text( aes( x=upAvgsData$scale, y=sum + 0.04 * max( sum ), label = format( sum, digits=3, big.mark = ",", scientific = FALSE ) ), size = 5, fontface = "bold" )
+values <- geom_text( aes( x=upAvgsData$scale, y=sum + 0.04 * max( sum ), label = format( sum, digits=3, big.mark = ",", scientific = FALSE ) ), size = 7.0, fontface = "bold" )
title <- ggtitle( "Switch Up Latency" )
-result <- fundamentalGraphData + barGraphFormat + errorBarFormat + title + values
+wrapLegend <- guides( fill=guide_legend( nrow=2, byrow=TRUE ) )
+result <- fundamentalGraphData + barGraphFormat + errorBarFormat + title + values + wrapLegend
print( paste( "Saving bar chart with error bars (Switch Up Latency) to", errBarOutputFileUp ) )
-ggsave( errBarOutputFileUp, width = 10, height = 6, dpi = 200 )
+ggsave( errBarOutputFileUp, width = 15, height = 10, dpi = 200 )
print( paste( "Successfully wrote bar chart with error bars (Switch Up Latency) out to", errBarOutputFileUp ) )
@@ -136,9 +137,9 @@
print( "Generating fundamental graph data (Switch Down Latency)." )
-mainPlot <- ggplot( data = downAvgsData, aes( x = scale, y = ms, fill = type, ymin = fileData[ 'down_end_to_end_avg' ] - stds, ymax = fileData[ 'down_end_to_end_avg' ] + stds ) )
-theme <- theme( plot.title=element_text( hjust = 0.5, size = 28, face='bold' ) )
-
+mainPlot <- ggplot( data = downAvgsData, aes( x = scale, y = ms, fill = type, ymin = fileData[ 'down_end_to_end_avg' ], ymax = fileData[ 'down_end_to_end_avg' ] + stds ) )
+theme <- theme( plot.title=element_text( hjust = 0.5, size = 32, face='bold' ), legend.position="bottom", legend.text=element_text( size=22 ), legend.title = element_blank(), legend.key.size = unit( 1.5, 'lines' ) )
+colors <- scale_fill_manual( values=c( "#F77670", "#619DFA", "#18BA48" ) )
fundamentalGraphData <- mainPlot + xScaleConfig + xLabel + yLabel + fillLabel + theme
@@ -148,12 +149,12 @@
title <- ggtitle( "Switch Down Latency" )
sum <- fileData[ 'down_device_to_graph_avg' ] + fileData[ 'ack_to_device_avg' ] + fileData[ 'fin_ack_to_ack_avg' ]
-values <- geom_text( aes( x=downAvgsData$scale, y=sum + 0.04 * max( sum ), label = format( sum, digits=3, big.mark = ",", scientific = FALSE ) ), size = 5, fontface = "bold" )
-result <- fundamentalGraphData + barGraphFormat + errorBarFormat + title + values
-
+values <- geom_text( aes( x=downAvgsData$scale, y=sum + 0.04 * max( sum ), label = format( sum, digits=3, big.mark = ",", scientific = FALSE ) ), size = 7.0, fontface = "bold" )
+wrapLegend <- guides( fill=guide_legend( nrow=1, byrow=TRUE ) )
+result <- fundamentalGraphData + barGraphFormat + colors + errorBarFormat + title + values + wrapLegend
print( paste( "Saving bar chart with error bars (Switch Down Latency) to", errBarOutputFileDown ) )
-ggsave( errBarOutputFileDown, width = 10, height = 6, dpi = 200 )
+ggsave( errBarOutputFileDown, width = 15, height = 10, dpi = 200 )
print( paste( "Successfully wrote bar chart with error bars (Switch Down Latency) out to", errBarOutputFileDown ) )
diff --git a/TestON/JenkinsFile/scripts/testCaseGraphGenerator.R b/TestON/JenkinsFile/scripts/testCaseGraphGenerator.R
index 395823d..2973755 100644
--- a/TestON/JenkinsFile/scripts/testCaseGraphGenerator.R
+++ b/TestON/JenkinsFile/scripts/testCaseGraphGenerator.R
@@ -120,7 +120,7 @@
# - x: x-axis values (usually iterative, but it will become build # later)
# - y: y-axis values (usually tests)
# - color: the category of the colored lines (usually status of test)
-theme_set( theme_grey( base_size = 20 ) ) # set the default text size of the graph.
+theme_set( theme_grey( base_size = 26 ) ) # set the default text size of the graph.
mainPlot <- ggplot( data = dataFrame, aes( x = iterative, y = Tests, color = Status ) )
print( "Formatting main plot." )
@@ -129,18 +129,21 @@
passedColor <- geom_ribbon( aes( ymin = 0, ymax = dataFrame$num_passed ), fill = "green", linetype = 0, alpha = 0.05 )
plannedColor <- geom_ribbon( aes( ymin = 0, ymax = dataFrame$num_planned ), fill = "blue", linetype = 0, alpha = 0.01 )
+colors <- scale_color_manual( values=c( "#E80000", "#00B208", "#00A5FF") )
+
xScaleConfig <- scale_x_continuous( breaks = dataFrame$iterative, label = dataFrame$Build )
yScaleConfig <- scale_y_continuous( breaks = seq( 0, max( dataFrame$Tests ), by = ceiling( max( dataFrame$Tests ) / 10 ) ) )
xLabel <- xlab( "Build Number" )
yLabel <- ylab( "Test Cases" )
fillLabel <- labs( fill="Type" )
-legendLabels <- scale_colour_discrete( labels = c( "Failed", "Passed", "Planned" ) )
+legendLabels <- scale_colour_discrete( labels = c( "Failed Cases", "Passed Cases", "Planned Cases" ) )
centerTitle <- theme( plot.title=element_text( hjust = 0.5 ) ) # To center the title text
-theme <- theme( plot.title = element_text( size = 28, face='bold' ), axis.text.x = element_text( angle = 45, size = 10 ) )
+theme <- theme( plot.title = element_text( size = 32, face='bold' ), axis.text.x = element_text( angle = 0, size = 14 ), legend.position="bottom", legend.text=element_text( size=22 ), legend.title = element_blank(), legend.key.size = unit( 1.5, 'lines' ) )
+
# Store plot configurations as 1 variable
-fundamentalGraphData <- mainPlot + plannedColor + passedColor + failedColor + xScaleConfig + yScaleConfig + xLabel + yLabel + fillLabel + legendLabels + centerTitle + theme
+fundamentalGraphData <- mainPlot + plannedColor + passedColor + failedColor + xScaleConfig + yScaleConfig + xLabel + yLabel + fillLabel + colors + legendLabels + centerTitle + theme
print( "Generating line graph." )
@@ -152,5 +155,5 @@
# Save graph to file
print( paste( "Saving result graph to", outputFile ) )
-ggsave( outputFile, width = 10, height = 6, dpi = 200 )
+ggsave( outputFile, width = 15, height = 10, dpi = 200 )
print( paste( "Successfully wrote result graph out to", outputFile ) )
diff --git a/TestON/bin/cli.py b/TestON/bin/cli.py
index a7e1297..8e48311 100755
--- a/TestON/bin/cli.py
+++ b/TestON/bin/cli.py
@@ -46,16 +46,16 @@
import threading
import __builtin__
import pprint
-dump = pprint.PrettyPrinter(indent=4)
+dump = pprint.PrettyPrinter( indent=4 )
__builtin__.testthread = False
introduction = "TestON is the testing framework \nDeveloped by Paxterra Solutions (www.paxterrasolutions.com)"
__builtin__.COLORS = False
-path = re.sub( "/bin$", "", sys.path[0] )
+path = re.sub( "/bin$", "", sys.path[ 0 ] )
sys.path.insert( 1, path )
from core.teston import *
-class CLI( threading.Thread,Cmd,object ):
+class CLI( threading.Thread, Cmd, object ):
"command-line interface to execute the test."
prompt = 'teston> '
@@ -64,7 +64,7 @@
self.teston = teston
self._mainevent = threading.Event()
- threading.Thread.__init__(self)
+ threading.Thread.__init__( self )
self.main_stop = False
self.locals = { 'test': teston }
self.stdin = stdin
@@ -86,7 +86,8 @@
Cmd.do_help( self, line )
if line is '':
output( self.helpStr )
- def do_run(self,args):
+
+ def do_run( self, args ):
'''
run command will execute the test with following optional command line arguments
logdir <directory to store logs in>
@@ -97,22 +98,22 @@
try:
args = args.split()
options = {}
- options = self.parseArgs(args,options)
- options = dictToObj(options)
+ options = self.parseArgs( args, options )
+ options = dictToObj( options )
if not testthread:
- test = TestThread(options)
+ test = TestThread( options )
test.start()
while test.isAlive():
- test.join(1)
+ test.join( 1 )
else:
- print main.TEST+ " test execution paused, please resume that before executing to another test"
+ print main.TEST + " test execution paused, please resume that before executing to another test"
except KeyboardInterrupt, SystemExit:
print "Interrupt called, Exiting."
test._Thread__stop()
main.cleanup()
main.exit()
- def do_resume(self, line):
+ def do_resume( self, line ):
'''
resume command will continue the execution of paused test.
teston>resume
@@ -122,10 +123,10 @@
'''
if testthread:
testthread.play()
- else :
+ else:
print "There is no test to resume"
- def do_nextstep(self,line):
+ def do_nextstep( self, line ):
'''
nextstep will execute the next-step of the paused test and
it will pause the test after finishing of step.
@@ -140,14 +141,14 @@
'''
if testthread:
- main.log.info("Executing the nextstep, Will pause test execution, after completion of the step")
+ main.log.info( "Executing the nextstep, Will pause test execution, after completion of the step" )
testthread.play()
- time.sleep(.1)
+ time.sleep( .1 )
testthread.pause()
else:
print "There is no paused test "
- def do_dumpvar(self,line):
+ def do_dumpvar( self, line ):
'''
dumpvar will print all the test data in raw format.
usgae :
@@ -162,16 +163,16 @@
'''
if testthread:
if line == "main":
- dump.pprint(vars(main))
- else :
- try :
- dump.pprint(vars(main)[line])
+ dump.pprint( vars( main ) )
+ else:
+ try:
+ dump.pprint( vars( main )[ line ] )
except KeyError as e:
print e
- else :
+ else:
print "There is no paused test "
- def do_currentcase(self,line):
+ def do_currentcase( self, line ):
'''
currentcase will return the current case in the test execution.
@@ -180,12 +181,11 @@
'''
if testthread:
- print "Currently executing test case is: "+str(main.CurrentTestCaseNumber)
- else :
+ print "Currently executing test case is: " + str( main.CurrentTestCaseNumber )
+ else:
print "There is no paused test "
-
- def do_currentstep(self,line):
+ def do_currentstep( self, line ):
'''
currentstep will return the current step in the test execution.
@@ -193,12 +193,11 @@
Currently executing test step is: 2.3
'''
if testthread:
- print "Currently executing test step is: "+str(main.CurrentTestCaseNumber)+'.'+str(main.stepCount)
- else :
+ print "Currently executing test step is: " + str( main.CurrentTestCaseNumber ) + '.' + str( main.stepCount )
+ else:
print "There is no paused test "
-
- def do_stop(self,line):
+ def do_stop( self, line ):
'''
Will stop the paused test, if any !
'''
@@ -207,7 +206,7 @@
return 'exited by user command'
- def do_gettest(self,line):
+ def do_gettest( self, line ):
'''
gettest will return the test name which is under execution or recently executed.
@@ -218,16 +217,16 @@
Test recently executed:
Recently executed test is: MininetTest
'''
- try :
- if testthread :
- print "Currently executing Test is: "+main.TEST
- else :
- print "Recently executed test is: "+main.TEST
+ try:
+ if testthread:
+ print "Currently executing Test is: " + main.TEST
+ else:
+ print "Recently executed test is: " + main.TEST
except NameError:
print "There is no previously executed Test"
- def do_showlog(self,line):
+ def do_showlog( self, line ):
'''
showlog will show the test's Log
teston>showlog
@@ -237,16 +236,16 @@
Currently executing Test's log is: /home/openflow/TestON/logs/PoxTest_07_Jan_2013_21_46_58/PoxTest_07_Jan_2013_21_46_58.log
.....
'''
- try :
- if testthread :
- print "Currently executing Test's log is: "+main.LogFileName
+ try:
+ if testthread:
+ print "Currently executing Test's log is: " + main.LogFileName
- else :
- print "Last executed test's log is : "+main.LogFileName
+ else:
+ print "Last executed test's log is : " + main.LogFileName
logFile = main.LogFileName
- logFileHandler = open(logFile, 'r')
- for msg in logFileHandler.readlines() :
+ logFileHandler = open( logFile, 'r' )
+ for msg in logFileHandler.readlines():
print msg,
logFileHandler.close()
@@ -254,79 +253,77 @@
except NameError:
print "There is no previously executed Test"
-
-
- def parseArgs(self,args,options):
+ def parseArgs( self, args, options ):
'''
This will parse the command line arguments.
'''
- options = self.initOptions(options)
- try :
+ options = self.initOptions( options )
+ try:
index = 0
while index < len( args ):
- option = args[index]
- if index > 0 :
- if re.match("--params", option, flags=0):
+ option = args[ index ]
+ if index > 0:
+ if re.match( "--params", option, flags=0 ):
# check if there is a params
- options['params'].append(args[index+1])
- elif re.match("logdir|mail|example|testdir|testcases|onoscell", option, flags = 0):
- options[option] = args[index+1]
- options = self.testcasesInRange(index+1,option,args,options)
+ options[ 'params' ].append( args[ index + 1 ] )
+ elif re.match( "logdir|mail|example|testdir|testcases|onoscell", option, flags = 0 ):
+ options[ option ] = args[ index + 1 ]
+ options = self.testcasesInRange( index + 1, option, args, options )
index += 2
- else :
- options['testname'] = option
+ else:
+ options[ 'testname' ] = option
index += 1
except IndexError as e:
- print (e)
+ print ( e )
main.cleanup()
main.exit()
return options
- def initOptions(self,options):
+ def initOptions( self, options ):
'''
This will initialize the commandline options.
'''
- options['logdir'] = None
- options['mail'] = None
- options['example'] = None
- options['testdir'] = None
- options['testcases'] = None
- options['onoscell'] = None
+ options[ 'logdir' ] = None
+ options[ 'mail' ] = None
+ options[ 'example' ] = None
+ options[ 'testdir' ] = None
+ options[ 'testcases' ] = None
+ options[ 'onoscell' ] = None
# init params as a empty list
- options['params'] = []
+ options[ 'params' ] = []
return options
- def testcasesInRange(self,index,option,args,options):
+ def testcasesInRange( self, index, option, args, options ):
'''
This method will handle testcases list,specified in range [1-10].
'''
- if re.match("testcases",option,1):
+ if re.match( "testcases", option, 1 ):
testcases = []
- args[index] = re.sub("\[|\]","",args[index],0)
- m = re.match("(\d+)\-(\d+)",args[index],flags=0)
+ args[ index ] = re.sub( "\[|\]", "", args[ index ], 0 )
+ m = re.match( "(\d+)\-(\d+)", args[ index ], flags=0 )
if m:
- start_case = eval(m.group(1))
- end_case = eval(m.group(2))
- if (start_case <= end_case):
+ start_case = eval( m.group( 1 ) )
+ end_case = eval( m.group( 2 ) )
+ if ( start_case <= end_case ):
i = start_case
while i <= end_case:
- testcases.append(i)
- i= i+1
- else :
+ testcases.append( i )
+ i = i + 1
+ else:
print "Please specify testcases properly like 1-5"
- else :
- options[option] = args[index]
+ else:
+ options[ option ] = args[ index ]
return options
- options[option] = str(testcases)
+ options[ option ] = str( testcases )
return options
- def cmdloop(self, intro=introduction):
+ def cmdloop( self, intro=introduction ):
print introduction
while True:
try:
- super(CLI, self).cmdloop(intro="")
+ super( CLI, self ).cmdloop( intro="" )
self.postloop()
except KeyboardInterrupt:
if testthread:
@@ -339,7 +336,7 @@
'''
Echoing of given input.
'''
- output(line)
+ output( line )
def do_sh( self, line ):
'''
@@ -349,7 +346,6 @@
'''
call( line, shell=True )
-
def do_py( self, line ):
'''
Evaluate a Python expression.
@@ -363,7 +359,7 @@
except Exception as e:
output( str( e ) + '\n' )
- def do_interpret(self,line):
+ def do_interpret( self, line ):
'''
interpret will translate the single line openspeak statement to equivalent python script.
@@ -373,13 +369,13 @@
'''
from core import openspeak
ospk = openspeak.OpenSpeak()
- try :
- translated_code = ospk.interpret(text=line)
+ try:
+ translated_code = ospk.interpret( text=line )
print translated_code
except AttributeError as e:
print 'Dynamic params are not allowed in single statement translations'
- def do_do (self,line):
+ def do_do( self, line ):
'''
Do will translate and execute the openspeak statement for the paused test.
do <OpenSpeak statement>
@@ -387,16 +383,16 @@
if testthread:
from core import openspeak
ospk = openspeak.OpenSpeak()
- try :
- translated_code = ospk.interpret(text=line)
- eval(translated_code)
+ try:
+ translated_code = ospk.interpret( text=line )
+ eval( translated_code )
except ( AttributeError, SyntaxError ) as e:
print 'Dynamic params are not allowed in single statement translations:'
print e
- else :
+ else:
print "Do will translate and execute the openspeak statement for the paused test.\nPlease use interpret to translate the OpenSpeak statement."
- def do_compile(self,line):
+ def do_compile( self, line ):
'''
compile will translate the openspeak (.ospk) file into TestON test script (python).
It will receive the openspeak file path as input and will generate
@@ -411,11 +407,11 @@
from core import openspeak
openspeak = openspeak.OpenSpeak()
openspeakfile = line
- if os.path.exists(openspeakfile) :
- openspeak.compiler(openspeakfile=openspeakfile,writetofile=1)
- print "Auto-generated test-script file is "+ re.sub("ospk","py",openspeakfile,0)
+ if os.path.exists( openspeakfile ):
+ openspeak.compiler( openspeakfile=openspeakfile, writetofile=1 )
+ print "Auto-generated test-script file is " + re.sub( "ospk", "py", openspeakfile, 0 )
else:
- print 'There is no such file : '+line
+ print 'There is no such file : ' + line
def do_exit( self, _line ):
"Exit"
@@ -454,7 +450,7 @@
'''
args = line.split()
- if len(args) != 1:
+ if len( args ) != 1:
error( 'usage: source <file>\n' )
return
try:
@@ -471,43 +467,43 @@
def do_time( self, line ):
"Measure time taken for any command in TestON."
start = time.time()
- self.onecmd(line)
+ self.onecmd( line )
elapsed = time.time() - start
- self.stdout.write("*** Elapsed time: %0.6f secs\n" % elapsed)
+ self.stdout.write( "*** Elapsed time: %0.6f secs\n" % elapsed )
def default( self, line ):
"""Called on an input line when the command prefix is not recognized."""
first, args, line = self.parseline( line )
if not args:
return
- if args and len(args) > 0 and args[ -1 ] == '\n':
- args = args[ :-1 ]
+ if args and len( args ) > 0 and args[ -1 ] == '\n':
+ args = args[:-1 ]
rest = args.split( ' ' )
error( '*** Unknown command: %s\n' % first )
-class TestThread(threading.Thread):
+class TestThread( threading.Thread ):
'''
TestThread class will handle the test execution and will communicate with the thread in the do_run.
'''
- def __init__(self,options):
+ def __init__( self, options ):
self._stopevent = threading.Event()
- threading.Thread.__init__(self)
+ threading.Thread.__init__( self )
self.is_stop = False
self.options = options
__builtin__.testthread = self
- def run(self):
+ def run( self ):
'''
Will execute the test.
'''
- while not self.is_stop :
+ while not self.is_stop:
if not self._stopevent.isSet():
- self.test_on = TestON(self.options)
- try :
+ self.test_on = TestON( self.options )
+ try:
if self.test_on.init_result:
result = self.test_on.run()
- if not self.is_stop :
+ if not self.is_stop:
result = self.test_on.cleanup()
self.is_stop = True
except KeyboardInterrupt:
@@ -517,7 +513,7 @@
__builtin__.testthread = False
- def pause(self):
+ def pause( self ):
'''
Will pause the test.
'''
@@ -533,14 +529,14 @@
result = self.test_on.cleanup()
self.is_stop = True
- def play(self):
+ def play( self ):
'''
Will resume the paused test.
'''
self._stopevent.clear()
cli.pause = False
- def stop(self):
+ def stop( self ):
'''
Will stop the test execution.
'''
@@ -550,39 +546,40 @@
cli.stop = True
__builtin__.testthread = False
-def output(msg):
+def output( msg ):
'''
Simply, print the message in console
'''
print msg
-def error(msg):
+def error( msg ):
'''
print the error message.
'''
print msg
-def dictToObj(dictionary):
+def dictToObj( dictionary ):
'''
This will facilitates the converting of the dictionary to the object.
This method will help to send options as object format to the test.
'''
- if isinstance(dictionary, list):
- dictionary = [dictToObj(x) for x in dictionary]
- if not isinstance(dictionary, dict):
+ if isinstance( dictionary, list ):
+ dictionary = [ dictToObj( x ) for x in dictionary ]
+ if not isinstance( dictionary, dict ):
return dictionary
- class Convert(object):
+
+ class Convert( object ):
pass
obj = Convert()
for k in dictionary:
- obj.__dict__[k] = dictToObj(dictionary[k])
+ obj.__dict__[ k ] = dictToObj( dictionary[ k ] )
return obj
if __name__ == '__main__':
- if len(sys.argv) > 1:
+ if len( sys.argv ) > 1:
__builtin__.COLORS = True
- CLI("test").onecmd(' '.join(sys.argv[1:]))
+ CLI( "test" ).onecmd( ' '.join( sys.argv[ 1: ] ) )
else:
__builtin__.COLORS = False
- CLI("test").cmdloop()
+ CLI( "test" ).cmdloop()
diff --git a/TestON/core/Thread.py b/TestON/core/Thread.py
index 4c040a6..0907dd8 100644
--- a/TestON/core/Thread.py
+++ b/TestON/core/Thread.py
@@ -38,8 +38,8 @@
if self.target is not None:
self.result = self.target( *self.args, **self.kwargs )
except Exception as e:
- print "ThreadID:" + str( self.threadID ) + ", Name:" +\
- self.name + "- something went wrong with " +\
- str( self.target.im_class ) + "." +\
+ print "ThreadID:" + str( self.threadID ) + ", Name:" + \
+ self.name + "- something went wrong with " + \
+ str( self.target.im_class ) + "." + \
str( self.target.im_func ) + " method: "
print e
diff --git a/TestON/core/ast.py b/TestON/core/ast.py
index fd5dfdb..c876b45 100644
--- a/TestON/core/ast.py
+++ b/TestON/core/ast.py
@@ -29,58 +29,58 @@
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).
"""
- 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 +89,39 @@
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
*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 +129,91 @@
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``
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
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
@@ -234,24 +233,24 @@
allows modifications.
"""
- def visit(self, 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):
+ 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 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.
@@ -287,25 +286,25 @@
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..7c2988e 100644
--- a/TestON/core/graph.py
+++ b/TestON/core/graph.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+# !/usr/bin/env python
'''
Copyright 2016 Open Networking Foundation (ONF)
@@ -69,7 +69,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
@@ -150,8 +150,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:
@@ -183,7 +183,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 +207,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 +224,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 +247,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 +288,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 ]
@@ -329,7 +329,7 @@
nextVertex = currentEdge[ 1 ]
vertexIsVisited[ currentVertex ] = True
chain.append( currentEdge )
- if nextVertex == sourceVertex or vertexIsVisited[ nextVertex ] == True:
+ if nextVertex == sourceVertex or vertexIsVisited[ nextVertex ] is True:
break
currentEdge = self.parentEdgeInDFS[ nextVertex ]
self.chains.append( chain )
diff --git a/TestON/core/logger.py b/TestON/core/logger.py
index ed9b0bd..dc2b2b2 100644
--- a/TestON/core/logger.py
+++ b/TestON/core/logger.py
@@ -1,7 +1,7 @@
-#/usr/bin/env python
+# /usr/bin/env python
'''
Created on 07-Jan-2013
-Modified 2015 by ON.Lab
+Modified 2015 by Open Networking Foundation
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>,
@@ -33,93 +33,93 @@
@author: Raghav Kashyap(raghavkashyap@paxterrasolutions.com)
'''
- def _printHeader(self,main) :
+ 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 type( 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,23 +127,24 @@
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
@@ -152,9 +153,9 @@
'''
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
@@ -163,90 +164,91 @@
'''
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 settig 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 +256,89 @@
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 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" )
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.write( "[Total]:" + str( main.TOTAL_TC_PLANNED ) + " [Executed]:" + str( main.TOTAL_TC_RUN ) + " [Failed]:" + str( main.TOTAL_TC_FAIL ) + "\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..1b351f9 100644
--- a/TestON/core/openspeak.py
+++ b/TestON/core/openspeak.py
@@ -1,4 +1,4 @@
-#/usr/bin/env python
+# /usr/bin/env python
'''
Created on 20-Dec-2012
Modified 2015 by ON.Lab
@@ -20,764 +20,745 @@
You should have received a copy of the GNU General Public License
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" :
- resultString = resultString + "main.log.info(" + message + ")"
- elif args["LOGLEVEL"] == "ERROR" :
- resultString = resultString + "main.log.error(" + message + ")"
- elif args["LOGLEVEL"] == "DEBUG" :
- resultString = resultString + "main.log.debug(" + message + ")"
- elif args["LOGLEVEL"] == "REPORT" :
- resultString = resultString + "main.log.report(" + message + ")"
- 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"] + ")"
-
+ 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":
+ resultString = resultString + "main.log.debug( " + message + " )"
+ elif args[ "LOGLEVEL" ] == "REPORT":
+ resultString = resultString + "main.log.report( " + message + " )"
+ 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" ] + ")"
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 :
- 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 :
- 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"]) + ")"
+ 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:
+ 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" ] ) + ")"
- 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 :
- 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"]) + ")"
-
+ 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:
+ 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" ] ) + ")"
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 :
- resultString = resultString + "\"" + stringMatch.group(1) + "\""
- elif variableMatch :
- resultString = resultString + variableMatch.group(1)
- elif args["MESSAGE"] == None :
+ 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" ] 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 :
- subString = subString + arguments + ","
- else :
- argMatch = re.search("(.*)\s+AS\s+(.*)",args["ARGUMENTS"],flags=0)
+ 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 )
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 :
- resultString = resultString + "main.params[\'" + self.CurrentCase + "\']" +\
- self._argsCheck(checkvar=casesMatch.group(1))
- elif topoMatch :
- resultString = resultString + "main.componentDictionary" +\
- self._argsCheck(checkvar=topoMatch.group(1))
- elif lastResultMatch :
+ 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:
+ resultString = resultString + "main.componentDictionary" + \
+ 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):
+ 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 :
- resultString = resultString + "[\'" + argsWidVariable.group(2) + "\']"
- else :
+ 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:
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"] + "\")"
+ 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.
@@ -787,8 +768,7 @@
# 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
@@ -797,21 +777,16 @@
# convert the statement here
return resultString
-
- def parse_args(self,args, **kwargs):
+ 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():
+ 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 str( each ) not in newArgs:
+ newArgs[ str( each ) ] = None
return newArgs
diff --git a/TestON/core/teston.py b/TestON/core/teston.py
index 89315dc..6794564 100644
--- a/TestON/core/teston.py
+++ b/TestON/core/teston.py
@@ -110,19 +110,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,12 +136,12 @@
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 )
@@ -169,40 +169,37 @@
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
@@ -270,12 +267,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 +296,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 +347,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()
@@ -363,7 +360,7 @@
return self.FALSE
except StandardError 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 +368,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 +398,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 +409,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 + " - "
@@ -454,27 +451,27 @@
raise SkipCase
def addCaseHeader( self ):
- caseHeader = "\n" + "*" * 30 + "\n Result summary for Testcase" +\
+ caseHeader = "\n" + "*" * 30 + "\n Result summary for Testcase" + \
str( self.CurrentTestCaseNumber ) + "\n" + "*" * 30 + "\n"
self.log.exact( caseHeader )
- caseHeader = "\n" + "*" * 40 + "\nStart of Test Case" +\
+ 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 ) + "." +\
+ previousStep = " " + str( self.CurrentTestCaseNumber ) + "." + \
str( stepNo ) + ": " + str( self.stepName )
- stepHeader = "\n" + "*" * 40 + "\nEnd of Step " + previousStep +\
+ stepHeader = "\n" + "*" * 40 + "\nEnd of Step " + previousStep + \
"\n" + "*" * 40 + "\n"
- caseFooter = "\n" + "*" * 40 + "\nEnd of Test case " +\
+ caseFooter = "\n" + "*" * 40 + "\nEnd of Test case " + \
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 ):
'''
@@ -497,12 +494,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]
- print "Disconnecting from " + str( tempObject.name ) +\
- ": " + str( tempObject.__class__)
+ tempObject = vars( self )[ component ]
+ print "Disconnecting from " + str( tempObject.name ) + \
+ ": " + str( tempObject.__class__ )
tempObject.disconnect()
except KeyboardInterrupt:
pass
@@ -517,7 +514,7 @@
# 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:
@@ -556,7 +553,7 @@
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:
print str( e )
@@ -564,7 +561,7 @@
else:
try:
for component in components:
- tempObject = vars( self )[component]
+ tempObject = vars( self )[ component ]
result = tempObject.onfail()
except StandardError as e:
print str( e )
@@ -605,25 +602,25 @@
'''
The step information of the test-case will append to the logs.
'''
- previousStep = " " + str( self.CurrentTestCaseNumber ) + "." +\
+ 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 ) + "." +\
+ 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 ):
'''
@@ -634,7 +631,7 @@
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 ):
'''
@@ -654,7 +651,7 @@
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
@@ -721,7 +718,7 @@
table format'''
table_data = ""
if isinstance( value_to_convert, dict ):
- table_data = table_data + '\t'.join( value_to_convert ) +\
+ table_data = table_data + '\t'.join( value_to_convert ) + \
"\n"
for temp_val in value_to_convert.values():
table_data = table_data + get_table( temp_val )
@@ -770,7 +767,7 @@
# NOTE: We should catch any exceptions while trying to
# close the thread so that we can try to close the other
# threads as well
- print str( thread.getName() ) +\
+ print str( thread.getName() ) + \
' could not be terminated'
os.system( "stty sane" ) # fix format if necessary
sys.exit()
@@ -859,16 +856,16 @@
# 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,7 +873,7 @@
if isinstance( tcase, list ):
tList.extend( evalTestCase( tcase ) )
else:
- tList.extend( [tcase] )
+ tList.extend( [ tcase ] )
return tList
def verifyTestCases( options ):
@@ -888,10 +885,10 @@
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 " +\
+ print "Testcases not specifed in params, please provide in " + \
"params file or 'testcases' commandline argument"
sys.exit()
@@ -902,20 +899,20 @@
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
@@ -929,13 +926,13 @@
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"
@@ -946,8 +943,8 @@
# No openspeak found, using python file instead
pass
else:
- print "\nThere is no \"" + main.TEST + "\" test script.\nPlease provide a " +\
- "Python or OpenSpeak test script in the tests folder: " +\
+ print "\nThere is no \"" + main.TEST + "\" test script.\nPlease provide a " + \
+ "Python or OpenSpeak test script in the tests folder: " + \
main.testDir + "/" + main.TEST + "/"
__builtin__.testthread = None
main.exit()
@@ -955,10 +952,10 @@
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 " +\
+ print "There was an import error, it might mean that there is " + \
"no test named " + main.TEST
main.exit()
@@ -970,19 +967,19 @@
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 " +\
+ 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 " +\
+ 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 +994,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,14 +1004,14 @@
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] ):
- print( "Error when parsing params: key \"" + keyList[0] + "\" not found in main.params" )
+ 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 ):
- print( "Error when parsing params: more levels under key \"" + keyList[0] + "\" in main.params" )
+ 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():
'''
@@ -1025,20 +1022,20 @@
'''
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()
@@ -1050,11 +1047,11 @@
print "Invalid parser format"
main.exit()
except ImportError:
- print "Could not find the file " + path +\
+ 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()
@@ -1064,14 +1061,14 @@
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,7 +1079,7 @@
else:
main.exit()
except ImportError:
- print sys.exc_info()[1]
+ print sys.exc_info()[ 1 ]
def load_logger():
'''
@@ -1092,29 +1089,29 @@
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()
except ImportError:
- print "Could not find the file " + path +\
+ 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()
@@ -1124,20 +1121,20 @@
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 ):
diff --git a/TestON/core/testparser.py b/TestON/core/testparser.py
index 904ebc0..1dea300 100644
--- a/TestON/core/testparser.py
+++ b/TestON/core/testparser.py
@@ -25,12 +25,12 @@
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 +39,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..91fc105 100644
--- a/TestON/core/utilities.py
+++ b/TestON/core/utilities.py
@@ -46,47 +46,47 @@
* 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'
@@ -100,28 +100,28 @@
'''
- 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):
+ 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 str( each ) not 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() + "\": " +\
+ sub = "Result summary of \"" + main.TEST + "\" run on component \"" + \
+ main.test_target + "\" Version \"" + \
+ vars( main )[ main.test_target ].get_version() + "\": " + \
str( main.TOTAL_TC_SUCCESS ) + "% Passed"
- else :
- sub = "Result summary of \"" + main.TEST + "\": " +\
+ else:
+ sub = "Result summary of \"" + main.TEST + "\": " + \
str( main.TOTAL_TC_SUCCESS ) + "% Passed"
- except ( KeyError, AttributeError ):
- sub = "Result summary of \"" + main.TEST + "\": " +\
+ 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
+ print "There is no such file to parse " + fileName
else:
return 0
@@ -326,8 +326,7 @@
startTime = time.time()
for i in range( 0, attempts ):
ret = f( *args, **kwargs )
- if ret not in retValue:
- # NOTE that False in [ 0 ] == True
+ if ret not in retValue: # NOTE that False in [ 0 ] == True
break
if randomTime:
sleeptime = random.randint( 0, sleep )
@@ -350,4 +349,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..41bb670 100644
--- a/TestON/core/xmldict.py
+++ b/TestON/core/xmldict.py
@@ -31,141 +31,141 @@
"""
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)}
+ root = ElementTree.XML( root_or_str )
+ try:
+ return { root.tag: _from_xml( root, strict ) }
except StandardError:
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 +174,23 @@
'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..12a3f61 100644
--- a/TestON/core/xmlparser.py
+++ b/TestON/core/xmlparser.py
@@ -1,4 +1,4 @@
-#/usr/bin/env python
+# /usr/bin/env python
'''
Created on 07-Jan-2013
Copyright 2013 Open Networking Foundation (ONF)
@@ -28,45 +28,44 @@
import xmldict
import re
-class xmlparser :
+class xmlparser:
- def __init__(self) :
+ 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:
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" )
+ topoAsString = str( topology )
+ return eval( topoAsString )
diff --git a/TestON/tests/SCPF/SCPFscaleTopo/dependencies/scaleTopoFunction.py b/TestON/tests/SCPF/SCPFscaleTopo/dependencies/scaleTopoFunction.py
index a48ddf7..b59a833 100644
--- a/TestON/tests/SCPF/SCPFscaleTopo/dependencies/scaleTopoFunction.py
+++ b/TestON/tests/SCPF/SCPFscaleTopo/dependencies/scaleTopoFunction.py
@@ -446,7 +446,7 @@
while compareRetry < 3 and main.postResult:
for controller in main.Cluster.active():
if controller.CLI.summary() is None:
- main.info.error( "Something happened to ONOS. Skip the rest of the steps" )
+ main.log.error( "Something happened to ONOS. Skip the rest of the steps" )
main.postResult = False
break
time.sleep( 5 )