HowTo mock PackedAvroSource in scadling JobTest - unit-testing

I'm trying to mock PackedAvroSource, no luck.
Here is an exception:
unable to resolve argument selector: [{1}:'bytes'], with incoming: [{1}:0]
it happens when I try to access 'byte field in map taken from avro. Map func whic converts bytes expects to get field named 'bytes
Here is a test code snippet
test("My test"){
JobTest(classOf[PackedAvroSourceJob].getName)
.arg("input", "input")
.arg("output", "output")
.source(PackedAvroSource[ByteBuffer]("input"), createInput)
.sink(PackedAvroSource[ByteBuffer]("output")) { buffer: mutable.Buffer[(Byte)] =>
println("hERE!!!")
}
.run
}
What is the right way to pass schema 'bytes to that PackedAvroSource?

In your Job, when reading PackedAvroSource, use Fields.FIRST for the ByteBuffer field. This will work for both the job and the test.

Related

You called the function 'Value Selector' with these arguments

I am in the process of implementing a LoanBroker with Mulesoft but have an error message when sending a request. I get the following error message back from Postman and Mulesoft Anypoint Studio:
ERROR 2021-06-27 15:20:51,133 [[MuleRuntime].uber.04: [loanbroker].LoanBrokerFlow_Gr7.CPU_LITE #254be3ee] [processor: LoanBrokerFlow_Gr7/processors/0; event: 7e49f560-d74a-11eb-b598-b66921dc5aa5] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler:
********************************************************************************
Message: "You called the function 'Value Selector' with these arguments:
1: Binary ("" as Binary {base: "64"})
2: Name ("amount")
But it expects one of these combinations:
(Array, Name)
(Array, String)
(Date, Name)
(DateTime, Name)
(LocalDateTime, Name)
(LocalTime, Name)
(Object, Name)
(Object, String)
(Period, Name)
(Time, Name)
1| payload.amount
^^^^^^^^^^^^^^
Trace:
at main (line: 1, column: 1)" evaluating expression: "payload.amount".
Element : LoanBrokerFlow_Gr7/processors/0 # loanbroker:bi_gruppe7.xml:34 (Copy_of_setAmount)
Element DSL : <set-variable value="#[payload.amount]" doc:name="Copy_of_setAmount" doc:id="cbcca557-1a69-4cf2-80b1-64333175589d" variableName="amount"></set-variable>
Error type : MULE:EXPRESSION
FlowStack : at LoanBrokerFlow_Gr7(LoanBrokerFlow_Gr7/processors/0 # loanbroker:bi_gruppe7.xml:34 (Copy_of_setAmount))
(set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************
Can anyone help me?
Thanks
This generally happens when one tries to access inner value of a payload like json but incoming payload is NOT actually a json type.
One could check the payload mediaType and then try to access the amount in order to avoid Value Selector exception.
%dw 2.0
output application/java
---
if( !isEmpty(payload) and payload.^mediaType contains "json" )
payload.amount
else
read(payload, "application/json").amount //best effort
Would recommend creating a separate dataweave file like dwl/set-amount.dwl and referencing it.
You are probably sending some body in the HTTP request from Postman but Mule doesn't know how to read it. Maybe you did not the Content-Type header in the request to let DataWeave know it is a JSON (application/json) or XML (application/XML).
Ensure you are sending the right content type.
I ran into the same situation. I know exactly the base64 is a json. So, I tried to set the MIME Type by
<set-payload value="#[payload]" doc:name="Set Payload" mimeType="application/json"/>
It works for me.

Store Data from Postman request in variables to use in tests

Im currently trying to get used to POSTMAN and i was wondering if there is a way to store variables from my request JSON Body via Pre Request in some environment variable so ican resuse it in the tests for response value cheks
This is how my json File might look like
{
"text" : "myText",
"attachments": {
"text": "myText2",
"anotherText" : "myText3"
}
So i want to get all Values, store them in a variable before sending my request, and then test if they match the expected value in my response
(example: myText2 gets mapped to green, myText3 gets mapped to red and so on)
That would make it possible to write one test for several request
Thanks a lot!
You can write the following in your script:
let body = JSON.parse(pm.request.body);
_.forEach(body, (value, key) => pm.environment.set(key, JSON.stringify(value)));
This will set each key and it's associated value as an environment variables.
Note you'll need to JSON.parse the value in the test script before using it for testing.
For eg in your test script you'll need to do something like this:
let attachments = JSON.parse(pm.environment.get('attachments'));
pm.test('All attachments are of correct value', function () {
// ...write your test here using the `attachments` variable
});

Is there any option to use something similar to mockito argument captor?

we are using gopkg.in/mgo.v2/bson to talk with mongo, and its API populates passed structures instead returning results, for example:
func (p *Pipe) One(result interface{}) error {...
Problems occurs when I want to mock / test code which is using that. I want to both mock this execution and somehow get pupulated value in 'result'.
Currently test has:
query.EXPECT().One(gomock.Any())
So as you can see I dont get any value, I just configure gomock to check that when I run my method then query.One has to be called.
I cannot pass structure like
mystruct := MyStruct{}
query.EXPECT().One(&mystruct)
because mystruct in test code and in real code is different and verifing mock will fail (references are different). Im looking for something similar to mockito's argument captor:
https://static.javadoc.io/org.mockito/mockito-core/2.6.9/org/mockito/ArgumentCaptor.html
This can be achieved via Do.
Copy & Paste of Github example from poy.
var capturedArgs []int
someMock.
EXPECT().
SomeMethod(gomock.Any()).
Do(func(arg int){
capturedArgs = append(capturedArgs, arg)
})
Ref: https://github.com/golang/mock/pull/149
This project can help you: https://github.com/bouk/monkey.
You can replace a function and use a bool variable to check the use.
called := false
monkey.Patch(package.One, func(result interface{}) error {
if result == expected {
called := true
return nil
}
return errors.new("not expected")
})
Dont't forget to restore your original function.
defer monkey.Unpatch(package.One)

call_user_func() expects parameter 1 to be a valid callback - Laravel unit testing

I am testing an API that returns a JOSN object, while running the following:
public function testBasicExample()
{
$response = $this->call('GET', 'sites/1/webmaster/totalstats?since=2014-01-01&until=2014-12-30');
}
getting error:
There was 1 error:
1) ExampleTest::testBasicExample ErrorException: call_user_func()
expects parameter 1 to be a valid callback, no array or string given
/var/www/html/laravel/app/facade/Webmaster.php:527
/var/www/html/laravel/app/helpers/WebmasterHelper.php:100
/var/www/html/laravel/app/controllers/WebmasterController.php:129
/var/www/html/laravel/app/routes.php:73
/var/www/html/laravel/vendor/laravel/framework/src/Illuminate/Routing/Route.php:109
/var/www/html/laravel/vendor/laravel/framework/src/Illuminate/Routing/Router.php:1033
/var/www/html/laravel/vendor/laravel/framework/src/Illuminate/Routing/Router.php:1001
/var/www/html/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:775
/var/www/html/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:745
/var/www/html/laravel/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/Client.php:81
/var/www/html/laravel/vendor/symfony/browser-kit/Symfony/Component/BrowserKit/Client.php:327
/var/www/html/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Testing/ApplicationTrait.php:51
/var/www/html/laravel/app/tests/ExampleTest.php:16
FAILURES! Tests: 1, Assertions: 0, Errors: 1.
I just started laravel a few days ago so I might do some very basic mistakes. Please help. Thanks
Assuming that you're trying to send a GET request at that endpoint, you're using the wrong method.
Try this:
public function testBasicExample()
{
$response = $this->get('/sites/1/webmaster/totalstats?since=2014-01-01&until=2014-12-30');
}
Then you'll probably want to make use of one of Laravel's built-in JSON-testing methods: https://laravel.com/docs/5.6/http-tests#testing-json-apis
you might want to do this way
$response = $this->call('GET', 'sites/1/webmaster/totalstats', [
'since' => '2014-01-01',
'until' => '2014-12-30'
]);
input parameters will place as the 3rd parameters, you might give it a try.

Scala Play2 Error on Web Service call

I'm getting an error on compile with the following code.
I'm trying to call a Web Service.
def authenticate(username: String, password: String): String = {
val request: Future[Response] =
WS.url(XXConstants.URL_GetTicket)
.withTimeout(5000)
.post( Map("username" -> Seq(username), "password" -> Seq(password) ) )
request map { response =>
Ok(response.xml.text)
} recover {
case t: TimeoutException =>
RequestTimeout(t.getMessage)
case e =>
ServiceUnavailable(e.getMessage)
}
}
I'm seeing the following compiler error:
type mismatch; found : scala.concurrent.Future[play.api.mvc.SimpleResult[String]] required: String
The value being returned from your authenticate function is val request = ... which is of type Future[Response] but the function expects a String which as the compiler says is a type mismatch error. Changing the return type of the function to Future[Response] or converting request to a String before returning it should fix it.
Like say Brian, you're currently returning a Future[String], when you method said that you want to return a String.
The request return a Future because it's an asynchronous call.
So, you have two alternatives:
Change your method definition to return a Future[String], and manage this future in another method (with .map())
Force the request to get this result immediately, in a synchronous way. It's not a very good deal, but sometimes it's the simplest solution.
import scala.concurrent.Await
import scala.concurrent.duration.Duration
val response: String = Await.result(req, Duration.Inf)