dynamically put enpoint url through setup scripts - soap

I have two Environment and a lot of test cases, but not all test cases are needed to be run in all environment. Is there a way to run only an specific test cases from a test suite based on the selected Environment. in Setup script .I am using soap ui version 5.4.0 For Example If I select Environment1, it will run the following test cases TC0001 TC0002 If I select Environment2, it will run only the following test cases TC0003 TC0004
Here as I am using "testcases.each" its replacing all endpoint url to one env but i want to exceute based on the testcasename.I am new to the groovy scripting .So can anyone help on this
I am currently using below code but its replacing all endpoint urls in all test cases::
def result = com.eviware.soapui.support.UISupport.prompt("Please select the enviornment", "Environment", ['UAT_API','IT2','UAT1'])
def testcases = testSuite.getTestCaseList()
if(result == 'UAT1'){
testcases.each { testcase ->
def teststeps = testcase.getTestStepList()
teststeps.each { teststep ->
teststep.setPropertyValue('endpoint','')
}
}
}else if(result == 'UAT_API'){
testcases.each { testcase ->
def teststeps = testcase.getTestStepList()
teststeps.each { teststep ->
teststep.setPropertyValue('endpoint','https://a-api.com')
}
}
}else if(result == 'IT2'){
testcases.each { testcase ->
def teststeps = testcase.getTestStepList()
teststeps.each { teststep ->
teststep.setPropertyValue('endpoint','https://it-webservices.com:1')
}
}
}
Can someone give guidance how to proceed from here to?

Related

fixture 'pylon_config_missing_usageplan' not found while running pytest-bdd

#scenario('../features/config.feature', 'Loading a valid config')
def test_config():
pass
#given("I have provided a valid pylon config",target_fixture="pylon_config")
def pylon_config():
input_data = {
}
return input_data
#when("The configuration is loaded")
def excute_pylon_config(pylon_config):
createFilterPattern(pylon_config)
#then("It should be enriched with the expected FilterPatterns")
def no_error_message(pylon_config):
test_data1= {
}
test_data_2 = {
}
result = pylon_config
#scenario('../features/config.feature', 'Missing usagePlan section')
def test_missing_usageplan():
pass
#given("I have provided a pylon config with a missing key",target_fixture="pylon_config_missing_usageplan")
def pylon_config_missing_usageplan():
input_data = {
'metricFilters': {
'defaults': {
'xyz': []
}
}
}
return input_data
#when("The configuration is loaded")
def excute_pylon_config_missing_usageplan(pylon_config_missing_usageplan):
try:
createFilterPattern(pylon_config_missing_usageplan)
except KeyError:
pass
#then("I should receive an exception")
def error_message_pylon_config_missing_usageplan(pylon_config_missing_usageplan):
print(pylon_config_missing_usageplan)
I have written multiple test case with specifying target_fixture in both #given scenario.
While running the test case it's throwing an error with
fixture 'pylon_config_missing_usageplan' not found
available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pylon_config, pytestbdd_given_I have provided a pylon config with a missing key, pytestbdd_given_I have provided a valid pylon config, pytestbdd_given_trace, pytestbdd_then_I should receive an exception, pytestbdd_then_It should be enriched with the expected FilterPatterns, pytestbdd_then_trace, pytestbdd_when_The configuration is loaded, pytestbdd_when_trace, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
use 'pytest --fixtures [testpath]' for help on them.
Can anyone help me over here?
The issue is, that the step When The configuration is loaded has two different implementations in code:
#when("The configuration is loaded")
def excute_pylon_config(pylon_config):
createFilterPattern(pylon_config)
#when("The configuration is loaded")
def excute_pylon_config_missing_usageplan(pylon_config_missing_usageplan):
try:
createFilterPattern(pylon_config_missing_usageplan)
except KeyError:
pass
The function excute_pylon_config_missing_usageplan overrides the step implementation of excute_pylon_config and therefore if you try to load the pylon config in scenario Loading a valid config, pytest-bdd actually tries to execute the function excute_pylon_config_missing_usageplan, which is expecting the fixture pylon_config_missing_usageplan (which is not available in this scenario ...)
Solutions
Have two distinct steps for loading a valid/invalid config, e.g. When The configuration is loaded and When The invalid configuration is loaded (I would recommend this approach, since it is simpler and easier to read than solution 2)
Add a variable to the step for loading the configuration which contains the type of the configuration
Example of variable in configuration loading step:
#when(parsers.parse("The {config_type} configuration is loaded"))
def excute_pylon_config(request, config_type):
if config_type == 'valid':
# Retrieve fixture dynamically by name
pylon_config = request.getfixturevalue('pylon_config')
createFilterPattern(pylon_config)
else:
# Retrieve fixture dynamically by name
pylon_config_missing_usageplan = request.getfixturevalue('pylon_config_missing_usageplan')
try:
createFilterPattern(pylon_config_missing_usageplan)
except KeyError:
pass

integration testing of Jooby application using Spock

I've got pretty simple application that uses Jooby as web framework. Its class responsible for REST looks like this
class Sandbox : Kooby ({
path("/sandbox") {
get {
val environment = require(Config::class).getString("application.env")
"Current environment: $environment"
}
get ("/:name") {
val name = param("name")
"Auto response $name"
}
}
})
I want to write integration test for it. My test looks like this. I use spock and rest-assured. The thing is that I don't have the application running and want to run it using some kind of embedded server or whatever. How to do that?
My simple test looks like this
class SandboxTest extends Specification {
def "check current environment"() {
given:
def request = given()
when:
def response = request.when().get("/sandbox")
then:
response.then().statusCode(200) // for now 404
}
}
You need to look for before/after test (or class) hooks in Spock. In the before hook you start Jooby without blocking the thread:
app.start("server.join=false")
in the after hook:
app.stop();
Never used Spock but here is a small extension method for Spek:
fun SpecBody.jooby(app: Jooby, body: SpecBody.() -> Unit) {
beforeGroup {
app.start("server.join=false")
}
body()
afterGroup {
app.stop()
}
}
Finally from your test:
#RunWith(JUnitPlatform::class)
object AppTest : Spek({
jooby(App()) {
describe("Get with query parameter") {
given("queryParameter name=Kotlin") {
it("should return Hello Kotlin!") {
val name = "Kotlin"
given()
.queryParam("name", name)
.`when`()
.get("/")
.then()
.assertThat()
.statusCode(Status.OK.value())
.extract()
.asString()
.let {
assertEquals(it, "Hello $name!")
}
}
...
...
...
...
Maven Spek example
Gradle Spek example

How to add a plugin to Telegraf?

Hello I would to know if someone have all ready add a plugin to telegraf for Influxdb.
I have my go code which is working. What do I need next and where to put theses files?
I've found that I need to do something like this:
type ReadFile struct {
//buf []byte
//MemoryBytes int64
//PID int
}
func (s *ReadFile) Description() string {
return "This is a test plugin to read data from a file and send them to influxdb" }
func (s *ReadFile) SampleConfig() string {
return "ok = true # indicate if everything is fine"
}
func Gather(acc plugins.Accumulator) error {
readFile(alarmFile)
acc.Add("alarm", result_of_readFile_here, tags)
}
}
func init() {
plugins.Add("readFile", func() plugins.Plugin { &ReadFile{} })
}
But is this my entire Go plugin or another file in Go to add with my Go program?
And where does the file.conf is store?
[tags]
dc = "alarm"
[agent]
interval = "10s"
# OUTPUTS
[outputs]
[outputs.influxdb]
url = "http://127.0.0.1:8086" # required.
database = "summer" # required.
precision = "s"
# PLUGINS
[readFile]
If you have a list of what I need, how to structure it, where I store file or maybe an example could be really helpful.
Thanks!!
-> I receive this, it gave me a better understanding, I think it could be helpful:
https://github.com/influxdata/telegraf/blob/master/CONTRIBUTING.md
"His plugin code looks good to go. He needs to place that file in $GOPATH/src/github.com/influxdata/telegraf/plugin/inputs/testPlugin/testPlugin.go
He should write a test for the plugin and place it at $GOPATH/src/github.com/influxdata/telegraf/plugin/inputs/testPlugin/testPlugin_test.go
After this is complete he needs to register the plugin at $GOPATH/src/github.com/influxdata/telegraf/plugin/inputs/all/all.go
Then he should run make from $GOPATH/src/github.com/influxdata/telegraf. This will place the new telegraf binary in $GOPATH/bin/telegraf.
Run the binary with the following flags to generate the valid configuration:
$GOPATH/bin/telegraf -sample-config -input-filter testPlugin -output-filter influxdb > testPlugin_config.conf
From there you can run the binary with the -test flag by passing it the sample config:
$GOPATH/bin/telegraf -config testPlugin_config.conf -test
This will output the line protocol that is to be inserted into the database."
-> And the testPlugin.go that he talks about:
package testPlugin
import (
"time"
)
type ReadFile struct {
counter int64
}
func (s *TestPlugin) Description() string {
return "This is a test plugin to write data to influxdb with a plugin"
}
func (s *TestPlugin) SampleConfig() string {
return "ok = true # indicate if everything is fine"
}
func Gather(acc telegraf.Accumulator) error {
c := time.Tick(10 * time.Second)
for now := range c {
counter := counter + 1
acc.Add("counter",counter, tags)
}
}
func init() {
inputs.Add("testPlugin", func() telegraf.Input { return &TestPlugin{} })
}
There's an opened issue for external plugin support which might be part of Telegraf 1.4.0. If will probably load external *.so files.
Until then all plugins are supposed to be merged into master repository via PRs. There are already many plugins waiting in review process. This model is obviously not very scalable.

How to mock domain specific closures in Spock

I'd like to test a Grails controller that is sending out emails using the grails Email plugin. I'm at a loss exactly how to mock the sendMail closure in order for interactions to work. Here's my latest version of the test code:
def 'controller should send a multipart email'() {
given: 'a mocked mailService'
controller.mailService = Mock(grails.plugin.mail.MailService)
controller.mailService.sendMail(*_) >> Mock(org.springframework.mail.MailMessage)
when:
controller.sendNow()
then:
1* _.multipart(true)
}
The controller code looks something like what you'd expect, e.g.:
def mailService
def sendNow() {
mailService.sendMail {
multipart true
to 'example#example.org'
from 'me#here.com'
subject 'a subject'
body 'a body'
}
}
If I run this test, I get 0 invocations of my multipart interaction instead of 1. The second line of the given: block seems suspicious to me, but if I try to mock a Closure instead of org.springframework.mail.MailMessage my test crashes. I should also mention that the controller itself works as expected (it couldn't wait for me to figure out the unit tests first).
Edited
Aha, looking at the code with a fresh mind a few hours later, I can see why the above code does not work; in order for me to catch multipart and other DSL calls, I would have to mock the closure itself, not the sendMail method (and I can't do that since the closure is defined inside the controller itself). What I probably can do is check the arguments to the sendMail method to see everything necessary was passed into it.
I was able to achieve this in Spock with the following:
def messageBuilder
def bodyParams
def setup(){
def mockMailService = new MockFor(MailService)
mockMailService.ignore.sendMail{ callable ->
messageBuilder = new MailMessageBuilder(null, new ConfigObject())
messageBuilder.metaClass.body = { Map params ->
bodyParams = params
}
callable.delegate = messageBuilder
callable.resolveStrategy = Closure.DELEGATE_FIRST
callable.call()
}
service.mailService = mockMailService.proxyInstance()
}
And an example test:
def "sendEmailReceipt_passesCorrectParams"(){
when:
def receiptItems = [] << [item: "item1", price: 100]
service.sendEmailReceipt(receiptItems, "some#email.com")
then:
messageBuilder.message.to[0] == "some#email.com"
messageBuilder.message.subject == "My subject"
bodyParams.view == "/mailtemplates/emailReceipt"
bodyParams.model.receiptItems == data
}
You can install the greenMail plugin, and use it in an integration test:
From the greenmail plugin home page:
import com.icegreen.greenmail.util.*
class GreenmailTests extends GroovyTestCase {
def mailService
def greenMail
void testSendMail() {
Map mail = [message:'hello world', from:'from#piragua.com', to:'to#piragua.com', subject:'subject']
mailService.sendMail {
to mail.to
from mail.from
subject mail.subject
body mail.message
}
assertEquals(1, greenMail.getReceivedMessages().length)
def message = greenMail.getReceivedMessages()[0]
assertEquals(mail.message, GreenMailUtil.getBody(message))
assertEquals(mail.from, GreenMailUtil.getAddressList(message.from))
assertEquals(mail.subject, message.subject)
}
void tearDown() {
greenMail.deleteAllMessages()
}
}
I'm not a Spock expert but you should be able to translate this junit test to spock style.
Source: http://grails.org/plugin/greenmail
Udpate, alternative by mocking sendMail
This is an answer to Gregor's update. In my opinion, you would have to mock the sendMail method, and inside this method have an stub that implements the different properties and methods that are used in the closure. Lets call it an evaluator. The you would initialize the closure's delegate to the evaluatro, and execute the closure. The evaluator should have the assertions. You see that I'm using more junit concepts here. I don't know how easily you can translate that into spock concepts. You probably would be able to us the behaviour checking facilities of spock.
class MailVerifier {
void multiPart(boolean v){
//...
}
void to(String address){
//...
}
boolean isVerified() {
//check internal state obtained by the appropriate invocation of the methods
}
}
def sendMail(Closure mailDefintion) {
def evaluator = createMailVerifier()
mailDefinition.delegate = evaluator
mailDefinition()
assert evaluator.verified
}
Take a look at plugin tests here: plugin integration test and here: plugin unit test. In my opinion it would be hard for you to mock all MailService dependencies - factory and builder that builds your mail message. I'd end up with testing only if my controller's sendNow is called.
Edit
I've found this answer. According to it you can try:
def 'controller should send a multipart email'() {
given: 'a mocked mailService'
def mockMailService = new Object()
def mockMessageBuilder = Mock(MessageBuilder)
mockMailService.metaClass.sendMail = { callable ->
callable.delegate = mockMessageBuilder
callable.resolveStrategy = Closure.DELEGATE_FIRST
callable.call()
}
controller.mailService = mockMailService
when:
controller.sendNow()
then:
1* mockMessageBuilder.multipart(true)
}
def mailService = Mock(MailService)
mockMailService.metaClass.sendMail = { ... your logic ... }
controller.mailService = mailService

Eclipse IDE doesnt allow me to give the input while running groovy script

I tried to run the groovy script. But unfortunately the script does not ask me for the input and through null pointer exceptions. Please help me what I need to do for this.
static startShell() {
client = new Client()
// TODO add Windows compatibility check
def historyFile = new File(System.getProperty("user.home"), "kitty.history")
historyFile.createNewFile()
def history = new History(historyFile)
def reader = new ConsoleReader()
reader.setBellEnabled(false)
reader.setUseHistory(true)
reader.setDefaultPrompt(PROMPT)
reader.setHistory(history)
reader.addCompletor(new SimpleCompletor(commands as String[]))
LOOP: while (true) {
def input = reader?.readLine().trim()
if (input.length() == 0)
continue
if (["exit", "quit"].contains(input.tokenize().get(0)))
break LOOP
try {
inputHandler(input)
}
catch (Exception e) {
println e.getMessage()
}
I also tried by replacing the reader? with reader also.
Error:
kitty> Caught: java.lang.NullPointerException: Cannot invoke method trim() on null object
at org.apache.kitty.CmdShell.startShell(CmdShell.groovy:100)
at org.apache.kitty.CmdShell.main(CmdShell.groovy:79)
Please Help
I believe this is related to this question:
java.io.Console support in Eclipse IDE
Essentially, Eclipse does not support Console Reader for running applications - though I'm confused as to how Andrew Eisenberg got a working result in Eclipse if that is the case.
Can you simplify your program into something that I can run? I tried something very simple and I was able to have it run both on the command line and inside Eclipse.
Here's the script I created:
import jline.ConsoleReader
def reader = new ConsoleReader()
LOOP: while (true) {
def input = reader?.readLine().trim()
if (input.length() == 0)
continue
if (["exit", "quit"].contains(input.tokenize().get(0)))
break LOOP
println "You said: " + input
}
Can you try running this and see if this works for you?