groovy.lang.MissingMethodException: No signature of method: httpRequest() is applicable for argument types: (java.util.LinkedHashMap) - groovy

I have the following piece of code that used to work great in a pipeline. I have to move it into a shared library in Jenkins, so created a class for it and made the necessary adjustments.
def toJson (input) {
return groovy.json.JsonOutput.toJson(input)
}
def void callAPI (args) {
def apiRequestBody = [
"prop1": args.param1,
"prop2": args.param2
]
// Build the request - notice that authentication should happen seamlessly by using Jenkins Credentials
response = httpRequest (authentication: "${CREDENTIALS_STORED_IN_JENKINS}",
consoleLogResponseBody: true,
httpMode: 'POST',
requestBody: toJson(apiRequestBody),
url: "${API_URL}",
customHeaders: [
[
name: 'Content-Type',
value: 'application/json; charset=utf-8'
],
[
name: 'Accept-Charset',
value: 'utf-8'
]
]
)
When I call the callAPI (args) method, I get the following error:
Exception groovy.lang.MissingMethodException: No signature of method: MY_PACKAGE_PATH.MY_CLASS.httpRequest() is applicable for argument types: (java.util.LinkedHashMap) values: [[authentication:MYAPI_UID_PW, consoleLogResponseBody:true, ...]]
What am I missing?
Thanks

httpRequest is a DSL command that's not directly available within the context of a class, much like ou can't use sh, bat, or node.
See https://www.jenkins.io/doc/book/pipeline/shared-libraries/#accessing-steps for more info about this.
You can lift code from within a Jenkinsfile and place it in a "var" (or Global Variable) instead, though.
If you insist on placing the code in a shared library class, refer to the link above, which would transform your code into (notice the "script" parameter and the script.httpRequest syntax):
def void callAPI (script, args) {
def apiRequestBody = [
"prop1": args.param1,
"prop2": args.param2
]
// Build the request
response = script.httpRequest (authentication: "${CREDENTIALS_STORED_IN_JENKINS}",
// ...
}

Related

Why is #pytest.fixture passed as an argument to tests but not used

Below is a test file for the Streamlink library. I was reading the test files to understand how testing is done and found a confusing set up for the tests. The test set up a series of #pytest.fixtures to help with testing. The assert_live fixture below is defined and passed into some tests, but never called at all. I dont think this is a mistake because a similar pattern is found throughout the file. I read the docs for fixtures but couldn't find anything that mentions this functionality. I got excited when they talked about using yeild inside a fixture but that turned not to touch on the subject either. Google was even less helpful. I am at a loss, but I am very interested in contributing to this library and need to understand how it works and how they test. Test is at the bottom of the code below. Thank you in advance!
# Other fixtures for context/continuity
#pytest.fixture
def mocker(self):
# The built-in requests_mock fixture is bad when trying to reference the following constants or classes
with requests_mock.Mocker() as mocker:
mocker.register_uri(requests_mock.ANY, requests_mock.ANY, exc=requests_mock.exceptions.InvalidRequest)
yield mocker
#pytest.fixture
def mock(self, request, mocker: requests_mock.Mocker):
mock = mocker.post("https://gql.twitch.tv/gql", **getattr(request, "param", {"json": {}}))
yield mock
assert mock.called_once
payload = mock.last_request.json() # type: ignore[union-attr]
assert tuple(sorted(payload.keys())) == ("extensions", "operationName", "variables")
assert payload.get("operationName") == "PlaybackAccessToken"
assert payload.get("extensions") == {
"persistedQuery": {
"sha256Hash": "0828119ded1c13477966434e15800ff57ddacf13ba1911c129dc2200705b0712",
"version": 1,
},
}
# The confusing fixture
#pytest.fixture
def assert_live(self, mock):
yield
assert mock.last_request.json().get("variables") == { # type: ignore[union-attr]
"isLive": True,
"isVod": False,
"login": "channelname",
"vodID": "",
"playerType": "embed",
}
# The confusing test
# note that assert_live is passed as an arg but is not actually used.
#pytest.mark.parametrize("plugin,mock", [
(
[("api-header", [("Authorization", "OAuth invalid-token")])],
{
"status_code": 401,
"json": {"error": "Unauthorized", "status": 401, "message": "The \"Authorization\" token is invalid."},
},
),
], indirect=True)
def test_auth_failure(self, caplog: pytest.LogCaptureFixture, plugin: Twitch, mock: requests_mock.Mocker, assert_live):
with pytest.raises(NoStreamsError) as cm:
plugin._access_token(True, "channelname")
assert str(cm.value) == "No streams found on this URL: https://twitch.tv/channelname"
assert mock.last_request._request.headers["Authorization"] == "OAuth invalid-token" # type: ignore[union-attr]
assert [(record.levelname, record.module, record.message) for record in caplog.records] == [
("error", "twitch", "Unauthorized: The \"Authorization\" token is invalid."),
]

Trying to fetch spot price using uniswap SDK but transaction is throwing error LOK?

const quotedAmountOut = await quoterContract.callStatic.quoteExactInputSingle(
immutables.token0,
immutables.token1,
immutables.fee,
amountIn,
0
)
I created two erc20 dummy tokens and created a pool for them using uniswapV3Factory createPool() method and obtained the pool address. But when I wanted to fetch the spot price for the tokens i have used using the above script it is throwing following Error:
Error: call revert exception; VM Exception while processing transaction: reverted with reason string "LOK" [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method="quoteExactInputSingle(address,address,uint24,uint256,uint160)", data="0x08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000034c4f4b0000000000000000000000000000000000000000000000000000000000", errorArgs=["LOK"], errorName="Error", errorSignature="Error(string)", reason="LOK", code=CALL_EXCEPTION, version=abi/5.7.0)
at Logger.makeError (/Users/apple/Desktop/solidity/deploy/node_modules/#ethersproject/contracts/lib/index.js:20:58)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
reason: 'LOK',
code: 'CALL_EXCEPTION',
method: 'quoteExactInputSingle(address,address,uint24,uint256,uint160)',
data: '0x08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000034c4f4b0000000000000000000000000000000000000000000000000000000000',
errorArgs: [ 'LOK' ],
errorName: 'Error',
errorSignature: 'Error(string)',
address: '0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6',
args: [
'<Token-1-Address>',
'<Token-2-Address>',
500,
BigNumber { _hex: '0x0de0b6b3a7640000', _isBigNumber: true },
0
],
transaction: {
data: '0xf7729d4300000000000000000000000008a2e53a8ddd2dd1d895c18928fc63778d97a55a0000000000000000000000006d7a02e23505a74143199abb5fb07e6ea20c6d6300000000000000000000000000000000000000000000000000000000000001f40000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000000000000000000000',
to: '0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6'
}
}
i found the issue here is your token address you provided, like token0 is WETH9 you must provide the exactly WETH9 token address, you can find it on etherscan.io

Trouble generating an Intent with delegateDirective from a TouchEvent handler (Alexa)

I need to confirm deleting a task from a button event. For this reason, I want Alexa to ask for confirmation, and therefore I need to generate a DeleteTaskIntent from my code.
I have tried this:
return handlerInput.responseBuilder.addDelegateDirective({
name: 'DeleteTaskIntent',
confirmationStatus: 'NONE',
slots: {
idTask:{
name: 'idTask',
value: idTask,
confirmationStatus: 'NONE'
}
}
}).getResponse();
In my TouchEventHandler, but after checking the request in the requestEnvelope, I see this:
request: {
type: 'System.ExceptionEncountered',
requestId: 'amzn1.echo-api.request.9c2cf5f4-2f2c-419c-898c-05bd5f096810',
timestamp: '2022-02-23T11:30:08Z',
locale: 'es-ES',
error: {
type: 'INVALID_RESPONSE',
message: 'Directive "Dialog.Delegate" cannot be used in response to an event'
},
cause: {
requestId: 'amzn1.echo-api.request.0494d80d-c6ac-41d6-b3a2-dffd97f427b5'
}
}
And the error
{
"name": "AskSdk.GenericRequestDispatcher Error"
}
also appears, which suggests that no handler can handle this case.
Any idea about what I'm doing wrong when trying to generate the Intent?

Moodle Web Service responses with invalid_parameter_exception

I created moodle and mariadb containers with Docker.
Moodle: 3.11.4
Mariadb: 10.3
I am trying following webservice to execute:
client:
wwwroot: 'http://localhost:8012',
service: 'moodle_mobile_app',
token: '8faf4879d2c654f11e404095032ae382',
strictSSL: true
call:
curl "http://localhost:8012/webservice/rest/server.php?wstoken=8faf4879d2c654f11e404095032ae382&moodlewsrestformat=json&wsfunction=core_user_get_users_by_field&moodlewsrestformat=json&id=2"
but getting follwing error:
{"exception":"invalid_parameter_exception","errorcode":"invalidparameter",
"message":"Invalid parameter value detected (Missing required key in single structure:field)",
"debuginfo":"Missing required key in single structure: field"
}
I tried it same with moodle client for node
... client.call({ wsfunction: "core_user_get_users_by_field", method: "POST", args: { id: 2 } })...
but also receiving same error.
I checked API documentation and id is valid parameter for this
webservice.
Can you please help?
Issue is resolved
client.call({
method: "POST",
wsfunction: "core_user_get_users_by_field",
args: {
field: "id",
values: ["2"]
}
}).then(function(info) {
var str = JSON.stringify(info, null, 4);
console.log(str);
});

Failing scripts in groovy using Grab

The following groovy scripts fail using command line
#Grab("org.apache.poi:poi:3.9")
println "test"
Error:
unexpected token: println # line 2, column 1.
println "test"
^
1 error
Removing the Grab, it works!
Anything I missed?
$>groovy -v
Groovy Version: 2.1.7 JVM: 1.7.0_25 Vendor: Oracle Corporation OS: Linux
Annotations can only be applied to certain targets. See SO: Why can't I do a method call after a #Grab declaration in a Groovy script?
#Grab("org.apache.poi:poi:3.9")
dummy = null
println "test"
Alternatively you can use grab as a method call:
import static groovy.grape.Grape.grab
grab(group: "org.apache.poi", module: "poi", version: "3.9")
println "test"
For more information refer to Groovy Language Documentation > Dependency management with Grape.
File 'Grabber.groovy'
package org.taste
import groovy.grape.Grape
//List<List[]> artifacts => [[<group>,<module>,<version>,[<Maven-URL>]],..]
static def grab (List<List[]> artifacts) {
ClassLoader classLoader = new groovy.lang.GroovyClassLoader()
def eal = Grape.getEnableAutoDownload()
artifacts.each { artifact -> {
Map param = [
classLoader: classLoader,
group : artifact.get(0),
module : artifact.get(1),
version : artifact.get(2),
classifier : (artifact.size() < 4) ? null : artifact.get(3)
]
println param
Grape.grab(param)
}
}
Grape.setEnableAutoDownload(eal)
}
Usage :
package org.taste
import org.taste.Grabber
Grabber.grab([
[ "org.codehaus.groovy.modules.http-builder", "http-builder", '0.7.1'],
[ "org.postgresql", "postgresql", '42.3.1', null ],
[ "com.oracle.database.jdbc", "ojdbc8", '12.2.0.1', null]
])

Resources