Using SLIM to write Fitnesse tests using Python - python

I downloaded and ran the fitnesse-standalone to test how does the SLIM protocol work.
Below is the directory structure
/Users
|
-redmont
|
-fitnesse-standalone.jar
|
-Calc.py
|
-FitNesseRoot/
FitNesse Wiki
!contents -R2 -g -p -f -h
!This is a test page
!define TEST_SYSTEM {slim}
!define SLIM_VERSION {0.1}
!path /Users/redmont/Calc.py
!path /Users/redmont/fitnesse-standalone.jar
!define COMMAND_PATTERN {python -m waferslim.server --syspath 8080}
|import|
|waferslim.examples.decision_table|
|Calc.MyCalc|
|my calc|
|A |B |multiply? |
|1 |2 |2 |
|1 |0 |0 |
|3 |5 |15 |
Calc.py
from waferslim.converters import convert_arg, convert_result, YesNoConverter
class MyCalc(object):
"""
Base test class
"""
def __init__(self):
"""
Initialise instance variables a and b to multiply
"""
self._A = 0
self._B = 0
self._multiply = 0
#convert_arg(to_type=int)
def setA(self, A):
"""
Decorated method to the variable 'a' as an int.
The decorator uses the implicitly registered int converter to
translate from a standard slim string value to an int.
"""
self._A = A
#convert_arg(to_type=int)
def setB(self, B):
self._B = B
#convert_result(to_type=str)
def multiply(self):
return self._A * self._B
I start the fitnesse-standalone using
java -jar fitnesse-standalone.jar -p 8080 -v
The logs in the terminal are
Socket class: class java.net.Socket
Remote address = /0:0:0:0:0:0:0:1:57853
Local socket address = /0:0:0:0:0:0:0:1:8080
Closed = false
Connected = true
Bound = true
isInputShutdown = false
isOutputShutdown = false
Creating plain socket on port: 0
Trying to connect to host: localhost on port: 57859 SSL=false timeout setting: 10
Creating plain client: localhost:57859
Socket class: class java.net.Socket
Connected to host: localhost on port: 57859 SSL=false timeout setting: 10
Remote address = /127.0.0.1:57860
Local socket address = /127.0.0.1:57859
Closed = false
Connected = true
Bound = true
isInputShutdown = false
isOutputShutdown = false
Read Slim Header: >Slim -- V0.4<
Got Slim Header: Slim -- V0.4, and Version 0.4
When I run this fixture in FitNesse with debug, I get the following error:
Could not invoke constructor for MyCalc[0]
1 The instance decisionTable_1.setA. does not exist
2 The instance decisionTable_1.setB. does not exist
2 The instance decisionTable_1.multiply. does not exist
I am unable to understand why isn't FitNesse able to find my fixture code?
Is it because of some permission?
I have also installed waferslim using its egg from cheese shop.

Reinstalling waferslim somehow solved my problem.

Related

Output format of subprocess python

I'm trying to keep the format generated by a command to see all wordpress plugin list.
my script is :
import subprocess
r = open("/tmp/resultplugin", "w")
f = open("path/to/my/list", "r")
for x in f:
x = x.rstrip()
bashCommand = "wp plugin list --allow-root"
process = subprocess.Popen(bashCommand, cwd=x, shell=True, stdout=r)
output, error = process.communicate()
The output of the command when launched directly on the bash shell :
| name | status | update | version |
+---------------------------------+----------+-----------+------------+
| plugin name | inactive | none | 5.2.2 |
| plugin name | active | none | 10.4.0 |
| plugin name | inactive | none | 5.65 |
| plugin | inactive | none | 9.4.8 |
The output when i redirect the output in a file :
name status update version
plugin name inactive none 5.2.2
plugin name active none 10.4.0
plugin name inactive none 5.65
plugin name inactive none 9.4.8
I have hard time to find how to keep the same format, or at least have a little bit more visibility as it's very hard to read in the file
Can someone explain me how i can format the output to the file correctly ?
Thank you

pywinauto - Getting property text

I'm using pywinauto and I want to select text from one of the properties. However, I can't figure out how to access it.
import pywinauto
pwa_app = pywinauto.application.Application()
path = r'C:\Users\me\Cisco\Cisco AnyConnect Secure Mobility Client\vpnui.exe'
pwa_app.start(path)
w_handle = pywinauto.findwindows.find_windows(title=u'Cisco AnyConnect Secure Mobility Client', class_name='#32770')[0]
window = pwa_app.window_(handle=w_handle)
window.SetFocus()
window.print_control_identifiers(2)
Control Identifiers:
Dialog - 'Cisco AnyConnect Secure Mobility Client' (L1421, T493, R1854, B690)
['Cisco AnyConnect Secure Mobility Client', 'Cisco AnyConnect Secure Mobility ClientDialog', 'Dialog']
child_window(title="Cisco AnyConnect Secure Mobility Client", class_name="#32770")
|
| #32770 - '' (L1441, T535, R1834, B647)
| ['#32770', 'VPN:#32770']
| child_window(class_name="#32770")
|
| Static - 'VPN:' (L1527, T548, R1551, B561)
| ['Static', 'VPN:Static', 'VPN:', 'Static0', 'Static1']
| child_window(title="VPN:", class_name="Static")
|
| ComboBox - 'Brock AppDMZ VPN' (L1527, T594, R1719, B615)
| ['ComboBox', 'Connected to Brock AppDMZ VPN.ComboBox', 'VPN:ComboBox', 'ComboBox0', 'ComboBox1', 'Connected to Brock AppDMZ VPN.ComboBox0', 'Connected to Brock AppDMZ VPN.ComboBox1']
| child_window(title="Brock AppDMZ VPN", class_name="ComboBox")
|
| Edit - 'Brock AppDMZ VPN' (L1530, T597, R1699, B612)
| ['Connected to Brock AppDMZ VPN.Edit', 'Edit']
| child_window(title="Brock AppDMZ VPN", class_name="Edit")
|
| ComboBox - '' (L1527, T594, R1719, B615)
| ['ComboBox2', 'Connected to Brock AppDMZ VPN.ComboBox2']
| child_window(class_name="ComboBox")
I want to access the value "Connected to Brock AppDMZ VPN" in order to determine whether I'm connected to my VPN but the documentation on this library isn't super clear about how to do this.
The output of print_control_identifiers() is incomplete (the target text label is not listed here, there are 3 static texts on the window), but fortunately I have the same Cisco VPN client on my PC. The problem is that this "static" text is dynamic. :) There are 2 ways how to handle this situation.
1) Just create a window specification and check if this window exists:
connected_label = window.child_window(title="Connected to Brock AppDMZ VPN.", class_name="Static")
# default timeout is pywinauto.timings.Timings.window_find_timeout (5 sec.)
if connected_label.exists(timeout=10):
pass # do whatever you want
2) Rely on the number of this static text and check its text every time you need the status of connection:
label = window.child_window(class_name="Static", found_index=1).wait('exists')
if label.window_text() == "Connected to Brock AppDMZ VPN.":
pass # do whatever you want
label = window.child_window(class_name="Static", found_index=1).wait('exists')
print label.get_value()
Try this, <element>.get_value() hope this will get you the text required.

python boto - how to create health check for route 53

How do I create a health check for route53 using python boto? There are no examples and documentation is very lacking http://boto.readthedocs.org/en/latest/ref/route53.html
So.if given ip address, port, and path.....then what?
Even though boto documentation is lacking, you can understand it by the code and AWS API.
Take a look at boto.route53.healthcheck.HealthCheck and implement as
route = boto.connect_route53()
hc = boto.route53.healthcheck.HealthCheck(...)
route = create_health_check(hc)
... will be filled out by the help page of HealthCheck:
Help on HealthCheck in module boto.route53.healthcheck object:
class HealthCheck(__builtin__.object)
| An individual health check
|
| Methods defined here:
|
| __init__(self, ip_addr, port, hc_type, resource_path, fqdn=None, string_match=None, request_interval=30, failure_threshold=3)
| HealthCheck object
|
| :type ip_addr: str
| :param ip_addr: IP Address
|
| :type port: int
| :param port: Port to check
|
| :type hc_type: str
| :param ip_addr: One of HTTP | HTTPS | HTTP_STR_MATCH | HTTPS_STR_MATCH | TCP
|
| :type resource_path: str
| :param resource_path: Path to check
|
| :type fqdn: str
| :param fqdn: domain name of the endpoint to check
|
| :type string_match: str
| :param string_match: if hc_type is HTTP_STR_MATCH or HTTPS_STR_MATCH, the string to search for in the response body from the specified resource
|
| :type request_interval: int
| :param request_interval: The number of seconds between the time that Amazon Route 53 gets a response from your endpoint and the time that it sends the next health-check request.
|
| :type failure_threshold: int
| :param failure_threshold: The number of consecutive health checks that an endpoint must pass or fail for Amazon Route 53 to change the current status of the endpoint from unhealthy to healthy or vice versa.
|
| to_xml(self)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| POSTXMLBody = '\n <HealthCheckConfig>\n <IPAddr...il...
|
| XMLFQDNPart = '<FullyQualifiedDomainName>%(fqdn)s</FullyQualifiedDomai...
|
| XMLRequestIntervalPart = '<RequestInterval>%(request_interval)d</Reque...
|
| XMLStringMatchPart = '<SearchString>%(string_match)s</SearchString>'
|
| valid_request_intervals = (10, 30)

How can I create a relay server using tulip/asyncio in Python?

I have the example echo server
import asyncio
class EchoServer(asyncio.Protocol):
def connection_made(self, transport):
peername = transport.get_extra_info('peername')
print('connection from {}'.format(peername))
self.transport = transport
def data_received(self, data):
self.transport.write(data)
# Client piece goes here
loop = asyncio.get_event_loop()
coro = loop.create_server(EchoServer, '127.0.0.1', 8888)
server = loop.run_until_complete(coro)
print('serving on {}'.format(server.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
print("exit")
finally:
server.close()
loop.close()
What I'm trying to do is add a client piece where I've commented that will connect to a new server and send the data off that-a-way. There's the echo client, but I need a process that looks like this:
+-----------+ +-----------+ +--------------+
| My Server | | My Client | | Other Server |
+-----------+ +-----------+ +--------------+
| | |
===>Get some data | |
| | |
Send data ---------->| |
| | |
| Send data ----------->|
| | |
| | Do Stuff
| | |
| | <-----------Send Data
| | |
| <--------- Send data |
| | |
<=== Send data | |
| | |
| | |
| | |
| | |
Obviously I can do this synchronously, but I'm trying to make the client -> other server bit async, and I'm not really figuring out how to use the asyncio methods to communicate between my server piece and a client piece.
What do I need to do here?
Here is a simple proxy which allow you to wget 127.0.0.1:8888 and get a html response from google:
import asyncio
class Client(asyncio.Protocol):
def connection_made(self, transport):
self.connected = True
# save the transport
self.transport = transport
def data_received(self, data):
# forward data to the server
self.server_transport.write(data)
def connection_lost(self, *args):
self.connected = False
class Server(asyncio.Protocol):
clients = {}
def connection_made(self, transport):
# save the transport
self.transport = transport
#asyncio.coroutine
def send_data(self, data):
# get a client by its peername
peername = self.transport.get_extra_info('peername')
client = self.clients.get(peername)
# create a client if peername is not known or the client disconnect
if client is None or not client.connected:
protocol, client = yield from loop.create_connection(
Client, 'google.com', 80)
client.server_transport = self.transport
self.clients[peername] = client
# forward data to the client
client.transport.write(data)
def data_received(self, data):
# use a task so this is executed async
asyncio.Task(self.send_data(data))
#asyncio.coroutine
def initialize(loop):
# use a coroutine to use yield from and get the async result of
# create_server
server = yield from loop.create_server(Server, '127.0.0.1', 8888)
loop = asyncio.get_event_loop()
# main task to initialize everything
asyncio.Task(initialize(loop))
# run
loop.run_forever()

Can't seem to get pexpect to print data from command

I'm steadily working on how to ssh and parse data on a device by running a command. I have had a few questions along the way of this endeavor and much help with the questions I have asked. I'm now working with pexpect and I'm not seeing much in documentation with what I am doing. Basically I need to ssh in, as I said, and then run a command that will print out data, then get that data to print to my console.
Here is my code:
import pexpect
import pxssh
import getpass
child = pexpect.spawn('ssh www.example.com')
password = getpass.getpass('password: ')
child.sendline ('foo bar')
data = (child.read_nonblocking(size=1000, timeout=100))
print data
OUTPUT:
password:
foo bar
In the foo bar command the first line of the print out is foo bar so I am wondering if this is trying to print this data but only printing the first line. I add the read_nonblocking(size=1000, timeout=100) trying to set the size to be greater and a timeout to let the data print.
UPDATE with PXSSH
I have also tried to use the pxssh samples to do this and get only the list of commands that foo can run. I need to get the print out of foo bar which is the list of configs. My guess is that you can't have commands with spaces? Here is the code I have tried:
import pxssh
import getpass
try:
s = pxssh.pxssh()
s.force_password = True
hostname = raw_input('hostname: ')
username = raw_input('username: ')
password = getpass.getpass('password: ')
s.login (hostname, username, password)
s.sendline ('foo bar') # run a command
s.prompt() # match the prompt
print s.before # print everything before the prompt.
s.logout()
except pxssh.ExceptionPxssh, e:
print "pxssh failed on login."
print str(e)
Which gives me this back in console:
pxssh failed on login.
could not set shell prompt
:
Session idle time out is disabled
SSH> unset PROMPT_COMMAND
Error - Command [unset PROMPT_COMMAND] not found.
foo [ bar | bart | ran | up
| cmd | bee | hvac | monkey
| selective | list | help ]
check[v,nv,beep] [ list | help ]
delete [ all | bee | neewb | stuff
| up | cmd | fooconfig | root
| app | list | hvac | monkey
| selective | <filename> | confirmed | list | help ]
exit [ help ]
get [ vcf | nvcf | snmpcf | help ] [<filename>]
verbose [ help ]
help [ <command> | help ]
up arrow - brings up old command lines
down arrow - brings up newer command lines
right arrow - moves cursor to the right
left arrow - moves cursor to the left
insert - inserts a space at the cursor
delete - deletes character at the cursor
SSH> PS1='[PEXPECT]\$ '
Error - Command [PS1='[PEXPECT]\$ '] not found.
foo [ bar | bart | ran | up
| cmd | bee | hvac | monkey
| selective | list | help ]
check[v,nv,beep] [ list | help ]
delete [ all | bee | neewb | stuff
| up | cmd | fooconfig | root
| app | list | hvac | monkey
| selective | <filename> | confirmed | list | help ]
exit [ help ]
get [ vcf | nvcf | snmpcf | help ] [<filename>]
verbose [ help ]
help [ <command> | help ]
up arrow - brings up old command lines
down arrow - brings up newer command lines
right arrow - moves cursor to the right
left arrow - moves cursor to the left
insert - inserts a space at the cursor
delete - deletes character at the cursor
And as I mentioned I'm just trying to get the console to print out the foo bar command configs. This is the code I had working with python-exscript before finding out I needed to work in older Python 2.4.
CODE THAT I HAD WORKING IN EXSCRIPT THAT I NEED PEXPECT TO DO
account = read_login()
conn = SSH2()
conn.connect('example.com')
conn.login(account)
conn.execute('foo bar')
data = conn.response
conn.send('exit\r')
conn.close()
print data
Any help on how to get this code to work is greatly appreciated! Thanks!
Figured out the issue. I was missing a s.prompt()
try:
s = pxssh.pxssh(timeout=60, maxread=2000000)
s.force_password = True
hostname = raw_imput('hostname: ')
username = raw_input('password: ')
password = getpass.getpass('password: ')
s.PROMPT= 'SSH> '
s.login (hostname, username, password, auto_prompt_reset=False)
s.prompt()
s.sendline('foo bar')
s.prompt()
data = s.before
print data
s.logout()
except pxssh.ExceptionPxssh, e:
print "pxssh failed on login."
print str(e)

Categories