SoapUI API - Setting TestCase property - properties

I'm trying to use SoapUI API in jython (modifying SoapUILibrary for Robot Framework) and somehow i am not able to find any way to set property of a Property TestStep.
Setting project, global and system properties is easy using
SoapUITestCaseRunner.setProjectProperties()
from com.eviware.soapui.tools import (SoapUITestCaseRunner)
from com.eviware.soapui.tools import (SoapUIMockServiceRunner)
from robot.api import logger
class SoapUILibrary2:
""" The main class of the library """
ROBOT_LIBRARY_SCOPE = 'TEST CASE'
ROBOT_LIBRARY_VERSION = '0.2'
def __init__(self):
self.__runner = None
self.__mockrunner = None
self._project_properties = []
def soapui_project(self, prj):
""" Initialize the runner and set the project string """
self.__runner = SoapUITestCaseRunner()
self.__runner.setProjectFile(prj)
def soapui_suite(self, s):
""" Set the suite string """
self.__runner.setTestSuite(s)
def soapui_case(self, c):
""" Set the test case string """
self.__runner.setTestCase(c)
def soapui_set_project_property(self, *properties):
""" Sets project properties for the current test run. (...)
"""
for prop in properties:
if len(prop.split('=')) == 2:
self._project_properties.append(prop)
else:
logger.warn("Skipping property: '%s'. Properties must be specified as: key=value" % prop)
try:
self.__runner.setProjectProperties(self._project_properties)
except AttributeError:
logger.warn('No project set. Cannot set project properties.')
SoapUITestCaseRunner class does not contain any way to access testSteps...
I found some examples how to solve this issue in groovy, however is it possible to set such properties using SoapUI API?
EDIT:
Adding whole code of the library. It's made to be imported in robot framework and used as its keywords.
http://tny.cz/34882261

In SOAPUI you can define properties for project, testCase and testSuite, it's also possible to generate a special type of testStep (Properties TestStep) but you can't define properties on a specific testStep (i.e on SOAP TestStep). You can see more info about here
However you can use a properties from project, testCase or testSuite in your testSteps so i.e you can define a property in a project level and then use it in your testStep. I can't give more specific info because I don't know exactly what you're trying to achieve.
EDIT:
I don't know the specific jython syntax but If you have the project file (as I see in your sample) you can access a specific testStep through com.eviware.soapui.impl.wsdl.WsdlProject, I give you a groovy script as example:
import com.eviware.soapui.impl.wsdl.WsdlProject;
import com.eviware.soapui.impl.wsdl.WsdlTestSuite;
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase;
import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep
def prj = new WsdlProject(path_prj_file,null);
def tsuite = prj.getTestSuiteByName("TestSuiteName");
def tcase = tsuite.getTestCaseByName("TestCaseName");
def tstep = tcase.getTestStepByName("TestStep");
EDIT 2:
I download jython standalone version 2.5.3 and use soapui 5.0.0 and works for me:
hw.py
from com.eviware.soapui.tools import (SoapUITestCaseRunner)
from com.eviware.soapui.tools import (SoapUILoadTestRunner)
from com.eviware.soapui.tools import (SoapUIMockServiceRunner)
from com.eviware.soapui.impl.wsdl import (WsdlProject)
from com.eviware.soapui.impl.wsdl import (WsdlTestSuite)
from com.eviware.soapui.impl.wsdl.testcase import (WsdlTestCase)
from com.eviware.soapui.impl.wsdl.teststeps import (WsdlTestRequestStep)
import thread
class SoapUI2:
""" The main class of the library """
ROBOT_LIBRARY_SCOPE = 'TEST CASE'
ROBOT_LIBRARY_VERSION = '0.2'
def __init__(self):
self.__runner = None
self.__mockrunner = None
self._project_properties = []
self.__prj = WsdlProject('C:\soapui_project.xml', None)
self.__tsuite = self.__prj.getTestSuiteByName("myTestSuite")
self.__tcase = self.__tsuite.getTestCaseByName("myTestCase")
self.__tstep = self.__tcase.getTestStepByName("myTestStep")
t = self.__tstep.getPropertyValue("Value")
print "Works ok"
def soapui_project(self, prj):
""" Initialize the runner and set the project string """
self.__runner = SoapUITestCaseRunner()
self.__runner.setProjectFile(prj)
def soapui_multiproject(self, prj):
""" Initialize the runner and set the project string """
self.__runner = SoapUILoadTestRunner()
self.__runner.setProjectFile(prj)
def soapui_suite(self, s):
""" Set the suite string """
self.__runner.setTestSuite(s)
def soapui_case(self, c):
""" Set the test case string """
self.__runner.setTestCase(c)
def soapui_set_project_property(self, *properties):
""" Sets project properties for the current test run.
This assumes that you have already initialized the project via
the `SoapUI Project` keyword.
`properies` may contain multiple statements, and each must be specified as: key=value.
This is useful to data drive your existing SoapUI tests via property expansion.
For more information see: http://www.soapui.org/Scripting-Properties/property-expansion.html
Example:
| SoapUI Project | My Project |
| SoapUI Set Project Property | ServiceEndpoint=https://staging.company.com | # set a single property |
| SoapUI Set Project Property | CustomProperty=foo | AnotherProperty=bar | # or set multiple properties |
"""
for prop in properties:
if len(prop.split('=')) == 2:
self._project_properties.append(prop)
else:
logger.warn("Skipping property: '%s'. Properties must be specified as: key=value" % prop)
try:
self.__runner.setProjectProperties(self._project_properties)
except AttributeError:
logger.warn('No project set. Cannot set project properties.')
def soapui_set_multiproject_threads(self, t):
""" Sets number of threads to run in load test """
self.__runner.setThreadCount(long(t))
logger.info("Running with %s threads at once." % t)
def soapui_run(self):
""" Run the runner and report to Robot """
logger.info("Running with the following project properties set: %s" % self._project_properties)
if not self.__runner.run():
raise AssertionError('FAIL: failed to run')
if self.__runner == SoapUITestCaseRunner():
n = self.__runner.getFailedTests().size()
if n != 0:
raise AssertionError('FAIL: ' + str(n) + ' tests failed')
def soapui_start_mock_service(self, p, m):
""" Runs a mock service """
try:
self.__mockrunner = SoapUIMockServiceRunner()
self.__mockrunner.setProjectFile(p)
self.__mockrunner.setMockService(m)
self.__mockrunner.setBlock(False)
self.__mockrunner.run()
except Exception, e:
raise AssertionError('FAIL: Error running the mock service ' + m + '. Reason: ' + str(e))
def soapui_stop_mock_service(self):
""" Stops the mock service """
self.__mockrunner.stopAll()
def soapui_set_step_property(self, s, p,v):
testStep = self.__runner.testCase.getTestStepByName(s)
testStep.setPropertyValue(p,v)
if __name__ == "__main__":
SoapUI2().__init__()
cmd line execution:
java -classpath "jython-standalone-2.5.3.jar;C:\Programari\SoapUI-5.0.0\lib\*;C:\Programari\SoapUI-5.0.0\bin\*" org.python.util.jython hw.py
execution result:
2014-05-27 12:43:09,058 [main] WARN com.eviware.soapui.SoapUI - Could not find jfxrt.jar. Internal browser will be disabled.
12:43:09,589 WARN [SoapUI] Missing folder [C:\temp\ext] for external libraries
12:43:09,964 INFO [DefaultSoapUICore] initialized soapui-settings from [C:\Documents and Settings\aciffone\soapui-settings.xml]
12:43:09,995 INFO [HttpClientSupport$Helper] Initializing KeyStore
12:43:11,682 INFO [WsdlProject] Loaded project from [file:/C:/soapui_project.xml]
Works ok
Hope this helps,

Related

pytest-factoryboy register factory with custom name - error fixture not found

using pytest-factoryboy in my conftest.py
import pytest
from pytest_factoryboy import register
from rest_framework.test import APIClient
from apps.api.factories import leadfactory, userfactory
#pytest.fixture
def client():
return APIClient()
#pytest.fixture
def staff(db):
return userfactory.StaffFactory()
register(leadfactory.OpenLeadFactory, "lead1")
pytest_lead.py
def test_leads_get(self, client, staff, lead1):
client.login(username=staff.username, password="staff")
url = reverse("lead_list")
response = client.get(url)
assert response.status_code == 200
after runnig pytest i'm getting error
________________________________________________ ERROR at setup of TestLeads.test_leads_get ________________________________________________
file C:\Users\suraj\Desktop\ShwetaSoftwares\Working\git\udimagic_project\apps\api\pytest\pytest_leads.py, line 38
def test_leads_get(self, client, staff, lead1):
file C:\Users\suraj\AppData\Local\Programs\Python\Python39\lib\site-packages\pytest_factoryboy\fixture.py, line 350
def model_fixture(request: SubRequest, factory_name: str) -> Any:
file C:\Users\suraj\AppData\Local\Programs\Python\Python39\lib\site-packages\pytest_factoryboy\fixture.py, line 503
def subfactory_fixture(request: SubRequest, factory_class: FactoryType) -> Any:
E fixture 'custom_user__first_name' not found
> available fixtures: _dj_autoclear_mailbox, _django_clear_site_cache, _django_db_helper, _django_db_marker, _django_set_urlconf, _django_setup_unittest, _fail_for_invalid_template_variable, _live_server_helper, _session_faker, _template_string_if_invalid_marker, admin_client, admin_user, affiliate, async_client, async_rf, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, client, db, django_assert_max_num_queries, django_assert_num_queries, django_capture_on_commit_callbacks, django_db_blocker, django_db_createdb, django_db_keepdb, django_db_modify_db_settings, django_db_modify_db_settings_parallel_suffix, django_db_modify_db_settings_tox_suffix, django_db_modify_db_settings_xdist_suffix, django_db_reset_sequences, django_db_serialized_rollback, django_db_setup, django_db_use_migrations, django_mail_dnsname, django_mail_patch_dns, django_test_environment, django_user_model, django_username_field, doctest_namespace, factoryboy_request, faker, lead1, lead1__addresscountry, lead1__addressstate, lead1__billing_name, lead1__created_at, lead1__created_by, lead1__description, lead1__email, lead1__first_name, lead1__lead_status, lead1__mobile, lead1__owner, lead_data, live_server, mailoutbox, monkeypatch, normal, open_lead_factory, partner1, partner2, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, rf, settings, staff, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory, transactional_db
> use 'pytest --fixtures [testpath]' for help on them.
when i'm using it without custom name its working -
register(leadfactory.OpenLeadFactory)
help me, after using custom name where i'm making mistake

How to extract the [Documentation] text from Robot framework test case

I am trying to extract the content of the [Documentation] section as a string for comparision with other part in a Python script.
I was told to use Robot framework API https://robot-framework.readthedocs.io/en/stable/
to extract but I have no idea how.
However, I am required to work with version 3.1.2
Example:
*** Test Cases ***
ATC Verify that Sensor Battery can enable and disable manufacturing mode
[Documentation] E1: This is the description of the test 1
... E2: This is the description of the test 2
[Tags] E1 TRACE{Trace_of_E1}
... E2 TRACE{Trace_of_E2}
Extract the string as
E1: This is the description of the test 1
E2: This is the description of the test 2
Have a look at these examples. I did something similar to generate testplans descritio. I tried to adapt my code to your requirements and this could maybe work for you.
import os
import re
from robot.api.parsing import (
get_model, get_tokens, Documentation, EmptyLine, KeywordCall,
ModelVisitor, Token
)
class RobotParser(ModelVisitor):
def __init__(self):
# Create object with remarkup_text to store formated documentation
self.text = ''
def get_text(self):
return self.text
def visit_TestCase(self, node):
# The matched `TestCase` node is a block with `header` and
# `body` attributes. `header` is a statement with familiar
# `get_token` and `get_value` methods for getting certain
# tokens or their value.
for keyword in node.body:
# skip empty lines
if keyword.get_value(Token.DOCUMENTATION) == None:
continue
self.text += keyword.get_value(Token.ARGUMENT)
def visit_Documentation(self,node):
# The matched "Documentation" node with value
self.remarkup_text += node.value + self.new_line
def visit_File(self, node):
# Call `generic_visit` to visit also child nodes.
return self.generic_visit(node)
if __name__ == "__main__":
path = "../tests"
for filename in os.listdir(path):
if re.match(".*\.robot", filename):
model = get_model(os.path.join(path, filename))
robot_parser = RobotParser()
robot_parser.visit(model)
text=robot_parser._text()
The code marked as best answer didn't quite work for me and has a lot of redundancy but it inspired me enough to get into the parsing and write it in a much readable and efficient way that actually works as is. You just have to have your own way of generating & iterating through filesystem where you call the get_robot_metadata(filepath) function.
from robot.api.parsing import (get_model, ModelVisitor, Token)
class RobotParser(ModelVisitor):
def __init__(self):
self.testcases = {}
def visit_TestCase(self, node):
testcasename = (node.header.name)
self.testcases[testcasename] = {}
for section in node.body:
if section.get_value(Token.DOCUMENTATION) != None:
documentation = section.value
self.testcases[testcasename]['Documentation'] = documentation
elif section.get_value(Token.TAGS) != None:
tags = section.values
self.testcases[testcasename]['Tags'] = tags
def get_testcases(self):
return self.testcases
def get_robot_metadata(filepath):
if filepath.endswith('.robot'):
robot_parser = RobotParser()
model = get_model(filepath)
robot_parser.visit(model)
metadata = robot_parser.get_testcases()
return metadata
This function will be able to extract the [Documentation] section from the testcase:
def documentation_extractor(testcase):
documentation = []
for setting in testcase.settings:
if len(setting) > 2 and setting[1].lower() == "[documentation]":
for doc in setting[2:]:
if doc.startswith("#"):
# the start of a comment, so skip rest of the line
break
documentation.append(doc)
break
return "\n".join(documentation)

How to set developer Mode as default in ODOO

i use a lot developer Mode in odoo so i always have to go to config and set dev mode every time i need it
is there any way to make this developper mode as default
thank you so much
you can enable odoo dev mode very easy !
You can use a chrome extension called Odoo Debug:
Odoo Debug
Or a Firefox extension called Odoo Easy Debug:
Odoo Easy Debug
Regards,
You don't need a chrome or firefox extension to activate and set the debug mode by default in Odoo. You can do something like the following code withing the Odoo framework. This is taken from this Odoo module and works at least in Odoo v8
Create a class with the settings values
class DevelopmentToolsConfigSettings(models.TransientModel):
_name = 'development_tools.config.settings'
development_mode = fields.Boolean(
string='Development mode as default',
required=False,
readonly=False,
index=False,
default=True,
help='Set development mode by default'
)
#api.model
def get_default_values(self, values):
return dict(
development_mode=self.get_debug_mode(),
)
def get_debug_mode(self):
param = self._get_parameter('development_mode')
if param:
value = self._safe_eval(param.value, bool)
else:
value = self._defaults['development_mode']
return value
def _set_debug_mode(self):
param = self._get_parameter('development_mode', force=True)
param.value = unicode(self.development_mode)
Override web.Home controller and add auto-debug mode behavior:
from openerp.http import route, request, Controller, redirect_with_hash
import openerp.addons.web.controllers.main as webmain
from openerp.tools.translate import _
from logging import getLogger
import werkzeug
_logger = getLogger(__name__)
class Home(webmain.Home):
#route()
def web_client(self, s_action=None, **kw):
result = None
if not request.debug and request.db and self._get_debug_mode():
_logger.info(self._debug_message)
result = self._build_debug_response()
return result or super(Home, self).web_client(s_action, **kw)
def _get_debug_mode(self):
config = request.env['development_tools.config.settings']
debug = config.get_debug_mode()
return debug == True
def _build_debug_response(self):
result = None
try:
query = request.params
query.update({'debug': u''})
url = '/web?' + werkzeug.url_encode(query)
result = redirect_with_hash(url)
except Exception as ex:
_logger.error(self._error_response.format(ex))
return result
_debug_message = _(u'Auto-redirect to enter in debug mode')
_error_response = _(
u'The debug response could not be built.\n'
u'System has said: {}'
)

tkinter variable for drop down selection empty

I tried to program an app in tkinter that would load random lines from a file you select from a pull down menu and display the selected line in a text window.
It seems like the variable "var" in insert_text does not return the selected "option" but rather an "empty" string resulting in a the following error:
"File not found error" (FileNotFoundError: [Errno2] No such file or
directory: '').
Please help!
#!/usr/bin/env python
# Python 3
import tkinter
from tkinter import ttk
import random
class Application:
def __init__(self, root):
self.root = root
self.root.title('Random Stuff')
ttk.Frame(self.root, width=450, height=185).pack()
self.init_widgets()
var = tkinter.StringVar(root)
script = var.get()
choices = ['option1', 'option2', 'option3']
option = tkinter.OptionMenu(root, var, *choices)
option.pack(side='right', padx=10, pady=10)
def init_widgets(self):
ttk.Button(self.root, command=self.insert_txt, text='Button', width='10').place(x=10, y=10)
self.txt = tkinter.Text(self.root, width='45', height='5')
self.txt.place(x=10, y=50)
def insert_txt(self):
var = tkinter.StringVar(root)
name = var.get()
line = random.choice(open(str(name)).readlines())
self.txt.insert(tkinter.INSERT, line)
if __name__ == '__main__':
root = tkinter.Tk()
Application(root)
root.mainloop()
That's because you're just creating an empty StringVar that isn't modified later, thus returning an empty string.
The OptionMenu takes the command parameter that calls the specified method every time another option is selected. Now, you can call a method like this, replacing you insert_txt:
def __init__(self):
# ...
self.var = tkinter.StringVar()
self.options = tkinter.OptionMenu(root, var, *choices, command=self.option_selected)
# ...
def option_selected(self, event):
name = self.var.get()
# The stuff you already had
Additionally, you have to empty the Text widget, otherwise the previous text would stay. I think the Entry widget is better for that, too.

Test fails in tests.py but succeeds in python shell

I'm a newbee to python and django and I can't figure out what I'm doing wrong here.
I have a Site object:
class Site (models.Model):
domain = models.CharField(max_length=30)
support_status = models.CharField(max_length=20, choices= SITE_SUPPORTED_STATUS, blank=False)
requests = models.IntegerField()
objects = SiteManager()
def __unicode__(self):
return u'%s %s' % (self.domain, self.support_status)
And a SiteManager object
class SiteManager(models.Manager):
def supported_site_counts(self):
i = self.filter(support_status__iexact="SUPPORTED").count()
return i
From the console, the method "supported_site_counts()" works just fine
>>(InteractiveConsole)
>>> from bookmark.models import Site, SiteManager
>>> Site.objects.supported_site_counts()
>>>>2012-05-18 18:09:20,027 DEBUG (0.001) SELECT COUNT(*) FROM "bookmark_site" WHERE
>>>>"bookmark_site"."support_status" LIKE SUPPORTED ESCAPE '\' ; args=(u'SUPPORTED',)
>>>>2012-05-18 18:09:20,028 DEBUG Got 1 supported site
>>>>1
But when it's called from a testcase, the count returns as 0
class SiteManagerTest(unittest.TestCase):
def test_supported_site_counts(self):
self.x = False
self.count = Site.objects.supported_site_counts()
logging.debug(self.count)
This is probably because the tests will set up a database separate from your development database to run the tests in. You will need to put testing data in to the testing database, either programmatically or using fixtures.