Imported library 'owaspapi' contains no keywords. (if it's installed using pip) - python-2.7

I have made a library for Robot Framework (myapi.py). If I place it in the same directory with my robot test I can import the library like this:
Library myapi.py
It works just fine.
However, I made the library pip installable so that others may take it into use in other projects easily. The library installs just fine with pip. I also changed the robot test to import the library like this:
Library myapi
When I run the robot test I get warning:
[ WARN ] Imported library 'myapi' contains no keywords.
Here's the (pip installable) library file structure:
setup.py
myapi
\__init__.py
\myapi.py
\version.py
The setup.py content is:
from setuptools import setup, find_packages
exec(open('myapi/version.py').read())
setup(
name='myapi',
version=__version__,
packages=['myapi'],
install_requires=['requests']
)
The init.py content is:
from .version import __version__
The version.py content is:
__version__ = '1.1.0'
The myapi.py content is (included only the first function I have):
import requests
import time
from time import strftime
import urllib2
__all__ = ['create_new_MY_session']
def create_new_MY_session():
session_name = strftime('my_session_%S_%H_%M_%d_%m_%Y')
r = requests.get("http://localhost:8080/JSON/core/action/newSession/?zapapiformat=JSON&name=" + session_name + "/'")
print ("Creating new session: " + session_name + ". Status code...")
print (r.status_code)
assert (r.status_code) == 200
And finally the beginning of the robot test (login.robot):
*** Settings ***
Suite Setup Open Firefox With Proxy
Suite Teardown Close Browser
Library mypapi
Library OperatingSystem
Library Selenium2Library
Resource ws_keywords/product/webui.robot
*** Test Cases ***
MY Start New MY Session
Create New MY Session
I wonder if the library works just fine when located right next to the robot test, what am I missing if I make it pip installable...? Why does it complain that there are no keywords?

In your myapi.py file you missing the class reference. When the file is placed inside your Robot Framework project this wasn't an issue, but when creating a pip installable module, this is required. A basic Python Library code example is this:
myapi.py
class myapi(object):
ROBOT_LIBRARY_VERSION = 1.0
def __init__(self):
pass
def keyword(self):
pass

Related

Issue with import module in python framework when working with Appium integrated with toolium

I have created an automation framework using toolium with Appium which works for both IOS and Android. Toolium is a python wrapper that I've used to facilitate page object modelling. Basically the UI is separated from the test case so that the same test case can be used across android as well as IOS.
I now need to get the framework working with IOS 10 (With XCUI test framework). So I have changed the elements for IOS so as to support XCUI (Places were XPATH is used and there is no other means of element identification). There is no change in the folder structure/execution mechanism whatsoever. But with the new framework I get an import error from toolium.
Code from tooling mobile page objects.py looks something like this.
# -*- coding: utf-8 -*-
import importlib
from toolium.driver_wrapper import DriverWrappersPool
from toolium.pageobjects.page_object import PageObject
class MobilePageObject(PageObject):
def __new__(cls, driver_wrapper=None):
"""Instantiate android or ios page object from base page object depending on driver configuration
Base, Android and iOS page objects must be defined with following structure:
FOLDER/base/MODULE_NAME.py
class BasePAGE_OBJECT_NAME(MobilePageObject)
FOLDER/android/MODULE_NAME.py
class AndroidPAGE_OBJECT_NAME(BasePAGE_OBJECT_NAME)
FOLDER/ios/MODULE_NAME.py
class IosPAGE_OBJECT_NAME(BasePAGE_OBJECT_NAME)
:param driver_wrapper: driver wrapper instance
:returns: android or ios page object instance
"""
if cls.__name__.startswith('Base'):
__driver_wrapper = driver_wrapper if driver_wrapper else DriverWrappersPool.get_default_wrapper()
__os_name = 'ios' if __driver_wrapper.is_ios_test() else 'android'
__class_name = cls.__name__.replace('Base', __os_name.capitalize())
try:
return getattr(importlib.import_module(cls.__module__), __class_name)(__driver_wrapper)
except AttributeError:
__module_name = cls.__module__.replace('.base.', '.{}.'.format(__os_name))
print __module_name
print __class_name
print __driver_wrapper
return getattr(importlib.import_module(__module_name), __class_name)(__driver_wrapper)
else:
return super(MobilePageObject, cls).__new__(cls)
I follow the folder structure as mentioned in toolium. Basically I have,
pageobjects folder under which I have base folder, ios folder and android folder. All my methods are in the base class. The elements are picked up either from the iOS folder or android folder at run time based on the driver type.
Below is the error from the import module
name = 'pageobjects.ios.intro', package = None
def import_module(name, package=None):
"""Import a module.
The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import.
"""
if name.startswith('.'):
if not package:
raise TypeError("relative imports require the 'package' argument")
level = 0
for character in name:
if character != '.':
break
level += 1
name = _resolve_name(name[level:], package, level)
__import__(name)
E ImportError: No module named ios.intro
When I print the module name and class name this is what I get.
module name = pageobjects.ios.intro
class name = IosIntroduction
intro is one of the modules basically. I access it something like this
from pageobjects.base.intro import BaseIntroduction
On the same machine I have the old framework working without any problem. I have checked environment variables/permissions etc. But I can't seem to figure out as to why the import is failing.
PS: I am running this on MACOSX and also use virtualenvironment for python

ImportError with nltk_train

I am trying to get my ways around with nltk-trainer (https://github.com/japerk/nltk-trainer). I managed to train Dutch taggers and chunkers with the commands (directly in Anaconda console):
python train_tagger.py conll2002 --fileids ned.train --classifier IIS --filename ~/nltk_data/taggers/conll2002_ned_IIS.pickle
python train_chunker.py conll2002 --fileids ned.train --classifier NaiveBayes --filename ~/nltk_data/chunkers/conll2002_ned_NaiveBayes.pickle
Then I run a little script to test the tagger and the chunker:
import nltk
from nltk.corpus import conll2002
# Loading training pickles
tokenizer = nltk.data.load('tokenizers/punkt/dutch.pickle')
tagger = nltk.data.load('taggers/conll2002_ned_IIS.pickle')
chunker = nltk.data.load('chunkers/conll2002_ned_NaiveBayes.pickle')
# Testing
test_sents = conll2002.tagged_sents(fileids="ned.testb")[0:1000]
print "tagger accuracy on test-set: " + str(tagger.evaluate(test_sents))
test_sents = conll2002.chunked_sents(fileids="ned.testb")[0:1000]
print "tagger accuracy on test-set: " + str(chunker.evaluate(test_sents))
This works fine from the nltk-trainer-master folder, but when I move the script elsewhere, I get an import error:
ImportError: No module named nltk_trainer.chunking.chunkers
How can I make this work outside the nltk-trainer-master folder, without copying the nltk_trainer folder?
(Python 2.7, nltk 3.2.1)

Selenium Python Configure Jenkins to run build. My build fails

I am trying to configure Jenkins to build my Selenium Webdriver Python code.
When i click Build Now it fails
The Console output shows the following:
Building in workspace C:\Program Files\Jenkins\workspace\ClearCore
[ClearCore] $ cmd /c call C:\Windows\TEMP\hudson6133135491793466847.bat
C:\Program Files\Jenkins\workspace\ClearCore>copy E:\RL Fusion\projects\Jenkins sample\ClearCore501\TestCases\*.py
The system cannot find the file specified.
C:\Program Files\Jenkins\workspace\ClearCore>python smoketests.py
python: can't open file 'smoketests.py': [Errno 2] No such file or directory
C:\Program Files\Jenkins\workspace\ClearCore>exit 2
Build step 'Execute Windows batch command' marked build as failure
Recording test results
ERROR: Publisher 'Publish JUnit test result report' failed: No test report files were found. Configuration error?
Finished: FAILURE
In PyCharm i have a smoketests.py file as follows:
import unittest
from xmlrunner import xmlrunner
from TestCases.LoginPage_TestCase import LoginPage_TestCase
from TestCases.AdministrationPage_TestCase import AdministrationPage_TestCase
from TestCases.DataConfigurationPage_TestCase import DataConfigurationPage_TestCase
login_tests = unittest.TestLoader().loadTestsFromTestCase(LoginPage_TestCase)
admin_tests = unittest.TestLoader().loadTestsFromTestCase(AdministrationPage_TestCase)
dataconf_tests = unittest.TestLoader().loadTestsFromTestCase(DataConfigurationPage_TestCase)
smoke_tests = unittest.TestSuite([login_tests, admin_tests, dataconf_tests])
xmlrunner.XMLTestRunner(verbosity=2, output='test-reports').run(smoke_tests)
I have a test_HTMLRunner.py as follows:
import unittest
import HTMLTestRunner
import os
from TestCases.LoginPage_TestCase import LoginPage_TestCase
from TestCases.AdministrationPage_TestCase import AdministrationPage_TestCase
from TestCases.DataConfigurationPage_TestCase import DataConfigurationPage_TestCase
# get the directory path to output report file
result_dir = os.getcwd()
login_tests = unittest.TestLoader().loadTestsFromTestCase(LoginPage_TestCase)
admin_tests = unittest.TestLoader().loadTestsFromTestCase(AdministrationPage_TestCase)
dataconf_tests = unittest.TestLoader().loadTestsFromTestCase(DataConfigurationPage_TestCase)
smoke_tests = unittest.TestSuite([login_tests, admin_tests, dataconf_tests])
# open the report file
outfile = open(result_dir + "\TestReport.html", "w")
# configure HTMLTestRunner options
runner = HTMLTestRunner.HTMLTestRunner(stream=outfile,
title='Test Report',
description='LADEMO create a basic project test')
# run the suite using HTMLTestRunner
runner.run(smoke_tests)
I have a suite.py as follows:
import sys
import unittest
import HTMLTestRunner
import os
import unittest
import AdministrationPage_TestCase
import LoginPage_TestCase
import DataConfigurationPage_TestCase
class Test_Suite(unittest.TestCase):
def test_main(self):
# suite of TestCases
self.suite = unittest.TestSuite()
self.suite.addTests([
unittest.defaultTestLoader.loadTestsFromTestCase(LoginPage_TestCase.LoginPage_TestCase),
unittest.defaultTestLoader.loadTestsFromTestCase(AdministrationPage_TestCase.AdministrationPage_TestCase),
unittest.defaultTestLoader.loadTestsFromTestCase(DataConfigurationPage_TestCase.DataConfigurationPage_TestCase),
])
runner = unittest.TextTestRunner()
runner.run (self.suite)
import unittest
if __name__ == "__main__":
unittest.main()
In Jenkins I have configured the following:
From the section Build, Execute Windows Batch Command
copy E:\RL Fusion\projects\Jenkins sample\ClearCore501\TestCases\*.py
python smoketests.py
From the section Post-Build Actions, Publish JUnit test result report
test_reports/*..xml
Below test_reports/*..xml it shows:
‘test_reports/*..xml’ doesn’t match anything: even ‘test_reports’ doesn’t exist
How do i get this to work please? What am i doing wrong?
Is there any sample demo I could follow and then I can get my setup to work?
Thanks,
Riaz
The problem looks to be in the copy step of you batch file. Notice how it says it cant find the file. Surround the source and destination paths with double quotes so that windows knows your path has spaces in it.
It also appears the copy operation doesn't have a destination specified. You should may want to specify that too. Although apparently that isn't a requirement, as I just found out :).
Once the copy operation succeeds, check the workspace directory to see if the file(s) you expect are present.
Alternatively, you can tell the Jenkins job to use a custom workspace, the directory where your tests live. With this configuration you don't even have to worry about copying files.
Here's how:
In the job config in Jenkins, open the Advanced Project Options and select use custom workspace and set the directory to E:\RL Fusion\projects\Jenkins sample\ClearCore501\TestCases\.
Then the build command can just be python smoketests.py.

pywin32 and pyttsx error, trouble combining the two

i have pywin32 in my site packages and my pyttsx is in a separate folder. Is this the reason why i am getting the following error?
import win32api, sys, os
ImportError: DLL load failed: The specified module could not be found
The code is as follows,
import pyttsx
def onStart(name):
print 'starting', name
def onWord(name, location, length):
print 'word', name, location, length
def onEnd(name, completed):
print 'finishing', name, completed
engine = pyttsx.init()
engine.connect('started-utterance', onStart)
engine.connect('started-word', onWord)
engine.connect('finished-utterance', onEnd)
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()
from here, http://pyttsx.readthedocs.org/en/latest/engine.html#examples
My pywin32 is from here,
http://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/
for Py 2.7
The problem was that the file
pywintypes27.dll
was not in the right directory. It had to be in
'C:\Windows\System32'
#CristiFati
Use the pyttsx3 module instead . It supports both python3 and python2.
To install:
pip install pyttsx3.
It automatically installs those win32 and other dependencies.

Add method imports to shell_plus

In shell_plus, is there a way to automatically import selected helper methods, like the models are?
I often open the shell to type:
proj = Project.objects.get(project_id="asdf")
I want to replace that with:
proj = getproj("asdf")
Found it in the docs. Quoted from there:
Additional Imports
In addition to importing the models you can specify other items to
import by default. These are specified in SHELL_PLUS_PRE_IMPORTS and
SHELL_PLUS_POST_IMPORTS. The former is imported before any other
imports (such as the default models import) and the latter is imported
after any other imports. Both have similar syntax. So in your
settings.py file:
SHELL_PLUS_PRE_IMPORTS = (
('module.submodule1', ('class1', 'function2')),
('module.submodule2', 'function3'),
('module.submodule3', '*'),
'module.submodule4'
)
The above example would directly translate to the following python
code which would be executed before the automatic imports:
from module.submodule1 import class1, function2
from module.submodule2 import function3
from module.submodule3 import *
import module.submodule4
These symbols will be available as soon as the shell starts.
ok, two ways:
1) using PYTHONSTARTUP variable (see this Docs)
#in some file. (here, I'll call it "~/path/to/foo.py"
def getproj(p_od):
#I'm importing here because this script run in any python shell session
from some_app.models import Project
return Project.objects.get(project_id="asdf")
#in your .bashrc
export PYTHONSTARTUP="~/path/to/foo.py"
2) using ipython startup (my favourite) (See this Docs,this issue and this Docs ):
$ pip install ipython
$ ipython profile create
# put the foo.py script in your profile_default/startup directory.
# django run ipython if it's installed.
$ django-admin.py shell_plus