Unable to get IntelliJ's (Velocity) Code Template to work correctly with conditional variable assignment - scala

I am attempting to improve a Scala Companion Object plus Case Class code generating template in IntelliJ 2021.3 (Build #IU-213.5744.223, built on November 27, 2021).
I would like to allow the user to be able to leave some of the input parameters unspecified (empty) and then have the template generate sane defaults. This is because the generated code can then be refactored by the client to something more pertinent later.
My question is this: Is there another way to approach achieving my goal than the way I show below using the Velocity #macro (which I got from here, and then doesn't appear to work anyway)?
With the current approach using the #marco, when I invoke it...
With:
NAME = "Longitude"
PROPERTY_1_VARIABLE = "value"
PROPERTY_1_TYPE - "Double"
The Scala code target:
final case class Longitude(value: Double)
With:
NAME = "Longitude"
PROPERTY_1_VARIABLE = ""
PROPERTY_1_TYPE - ""
The Scala code target using defaults for 2 and 3:
final case class Longitude(property1: Property1Type)
And here's my attempt to make it work with the IntelliJ (Velocity) Code Template:
#macro(condOp $check, $default)
#if ($check == "")
$default
#else
$check
#end
#end
#set (${PROPERTY_1_VARIABLE} = "#condOp(${PROPERTY_1_VARIABLE}, 'property1')")
#set (${PROPERTY_1_TYPE} = "#condOp(${PROPERTY_1_TYPE}, 'Property1Type')")
#if ((${PACKAGE_NAME} && ${PACKAGE_NAME} != ""))package ${PACKAGE_NAME} #end
final case class ${NAME} (${PROPERTY_1_VARIABLE}: ${PROPERTY_1_TYPE})
First, the IntelliJ popup box for entering the parameters correctly shows "Name:". And then incorrectly shows "default:" and "check". I have submitted a ticket with Jetbrains for this IntelliJ issue. Please vote for it, if you get a chance so it increases in priority.
And then when the macro finishes executing (I provide the Name of "LongLat", but leave the default and check parameters empty), I don't understand why I get the following gibberish.
package org.public_domain
${PROPERTY_1_TYPE})
Any guidance on fixing my current Velocity Code Template script or suggest another way to effectively approach solving the problem would be deeply appreciated.

Related

Example third person controler in Unity / StringToHash

I am trying to learn game development through different ways and sources and recently I have created a project in unity with example ThirdPersonController.
While looking through the code I came across one thing which I am finding difficult to wrap my mind around. It is "StringToHash". What is the purpose of this? Here is an example of variable with specified values set:
private void AssignAnimationIDs()
{
_animIDSpeed = Animator.StringToHash("Speed");
_animIDGrounded = Animator.StringToHash("Grounded");
_animIDJump = Animator.StringToHash("Jump");
_animIDFreeFall = Animator.StringToHash("FreeFall");
_animIDMotionSpeed = Animator.StringToHash("MotionSpeed");
}
and here is an example when this is used when being called:
if (_hasAnimator)
{
_animator.SetFloat(_animIDSpeed, _animationBlend);
_animator.SetFloat(_animIDMotionSpeed, inputMagnitude);
}
Welcome to Stack overflow.
Similar question already has been asked HERE . Unity Docs .
In your code below you changing values (parameters) of your animator. To find which values it should change it must compare the name of the value you gave in .SetFloat to the ones it has (in "parameters" section on "animator" tab).
You could do
.SetFloat("speed", _animationBlend);
But to get that milliseconds of time advantage (optimization) your "speed" is converted to integers first (like in your code above) and then you use it.

Stop huge error output from testing-library

I love testing-library, have used it a lot in a React project, and I'm trying to use it in an Angular project now - but I've always struggled with the enormous error output, including the HTML text of the render. Not only is this not usually helpful (I couldn't find an element, here's the HTML where it isn't); but it gets truncated, often before the interesting line if you're running in debug mode.
I simply added it as a library alongside the standard Angular Karma+Jasmine setup.
I'm sure you could say the components I'm testing are too large if the HTML output causes my console window to spool for ages, but I have a lot of integration tests in Protractor, and they are SO SLOW :(.
I would say the best solution would be to use the configure method and pass a custom function for getElementError which does what you want.
You can read about configuration here: https://testing-library.com/docs/dom-testing-library/api-configuration
An example of this might look like:
configure({
getElementError: (message: string, container) => {
const error = new Error(message);
error.name = 'TestingLibraryElementError';
error.stack = null;
return error;
},
});
You can then put this in any single test file or use Jest's setupFiles or setupFilesAfterEnv config options to have it run globally.
I am assuming you running jest with rtl in your project.
I personally wouldn't turn it off as it's there to help us, but everyone has a way so if you have your reasons, then fair enough.
1. If you want to disable errors for a specific test, you can mock the console.error.
it('disable error example', () => {
const errorObject = console.error; //store the state of the object
console.error = jest.fn(); // mock the object
// code
//assertion (expect)
console.error = errorObject; // assign it back so you can use it in the next test
});
2. If you want to silence it for all the test, you could use the jest --silent CLI option. Check the docs
The above might even disable the DOM printing that is done by rtl, I am not sure as I haven't tried this, but if you look at the docs I linked, it says
"Prevent tests from printing messages through the console."
Now you almost certainly have everything disabled except the DOM recommendations if the above doesn't work. On that case you might look into react-testing-library's source code and find out what is used for those print statements. Is it a console.log? is it a console.warn? When you got that, just mock it out like option 1 above.
UPDATE
After some digging, I found out that all testing-library DOM printing is built on prettyDOM();
While prettyDOM() can't be disabled you can limit the number of lines to 0, and that would just give you the error message and three dots ... below the message.
Here is an example printout, I messed around with:
TestingLibraryElementError: Unable to find an element with the text: Hello ther. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
...
All you need to do is to pass in an environment variable before executing your test suite, so for example with an npm script it would look like:
DEBUG_PRINT_LIMIT=0 npm run test
Here is the doc
UPDATE 2:
As per the OP's FR on github this can also be achieved without injecting in a global variable to limit the PrettyDOM line output (in case if it's used elsewhere). The getElementError config option need to be changed:
dom-testing-library/src/config.js
// called when getBy* queries fail. (message, container) => Error
getElementError(message, container) {
const error = new Error(
[message, prettyDOM(container)].filter(Boolean).join('\n\n'),
)
error.name = 'TestingLibraryElementError'
return error
},
The callstack can also be removed
You can change how the message is built by setting the DOM testing library message building function with config. In my Angular project I added this to test.js:
configure({
getElementError: (message: string, container) => {
const error = new Error(message);
error.name = 'TestingLibraryElementError';
error.stack = null;
return error;
},
});
This was answered here: https://github.com/testing-library/dom-testing-library/issues/773 by https://github.com/wyze.

Unable to select an option from a drop down in Katalon studio

I am new to Katalon Studio and I am facing an issue regarding selection of the drop down.
Please find below the details:
This is the HTML :
I have tried using selectByIndex with the object xpath as:
//div[#class='paCriteriaContainer']//select[#class = 'pa-criteria-select a-select initialized']
It does not select any option and fails with an error stating "Unable to select option by index '2' of object"
Note:
I tried clicking on the input and then selecting the option, but that doesn't seem to work either.
Selecting by label and value don't work either
Please help me here.
Thank you
Try to capture an object and then use following methods :
WebUI.click(findTestObject(Your captured object))
WebUI.selectOptionByValue(findTestObject(Your captured object), 'TEST (2020)', false)
Did you done as I've described and it does not work ?
I tried clicking on the input and then selecting the option, but that doesn't seem to work either.
Are you sure you are clicking the right element in this case?
Try the following instead: create programmatically the element and select by value (note, value isn't the text contained, it is the value html attribute):
TestObject to = new TestObject().addProperty("xpath", ConditionType.EQUALS, "//div[#class='paCriteriaContainer']//select[#class = 'pa-criteria-select a-select initialized']")
WebUI.selectOptionByValue(to, '40696', false)
You have some options to do that, I reggardly suggest you that use always the xpath to reach all the elements that you want to use. The reasson is because the object reports usually fail and, in my opinion, this way is so much more complicated.
But obviously, the xpath will change if the web do, so take care with it.
The imports you need:
import static org.junit.Assert.*
import org.openqa.selenium.By
import org.openqa.selenium.Keys
import com.kms.katalon.core.webui.driver.DriverFactory as DriverFactory
def driver = DriverFactory.getWebDriver()
//If you want to click your input would be:
WebUI.click(WebUI.convertWebElementToTestObject(driver.findElement(By.xpath("(//input[#id='a-select-paCricteriaId_6908'])"))))
//**you just can click on "TestObject" type, and findElement returns "Element" type**
And if you want to select the option you need to know the whole path (I cannot get it with the given information).
An important tip for testing the xpath is to use this function in console mode (F12):
function getElementByXpath(path) {
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
//And this code in the same console to test your xpath:
getElementByXpath("YOURTESTXPATH")
Furthermore, there are other ways to reach the same objetive with xpath, for example:
import com.kms.katalon.core.testobject.TestObject as TestObject
...
TestObject tobj = new TestObject('myTestObject')
String expr = '/some/valid/xpath/expression'
tobj.addProperty('xpath', ConditionType.EQUALS, expr)
WebUI.click(tobj)
You have a lot of information if you google "how to get elements by xpath katalon".
Here you can get official information about it:
https://docs.katalon.com/katalon-studio/tutorials/detect_elements_xpath.html#what-is-xpath
Test in the browser console
$x('//*[contains(#class, "pa-criteria-select a-select initialized")]')
if more than one result appear then you can access it like this
$x('(//*[contains(#class, "pa-criteria-select a-select initialized")])[1]')
then you can also access their children
$x('(//*[contains(#class, "pa-criteria-select a-select initialized")])[1]/option')
Use WebUI.selectOptionByIndex keyword but the object should point to the select tag instead of the div.
Update the object element and your code should work

Debugging test cases when they are combination of Robot framework and python selenium

Currently I'm using Eclipse with Nokia/Red plugin which allows me to write robot framework test suites. Support is Python 3.6 and Selenium for it.
My project is called "Automation" and Test suites are in .robot files.
Test suites have test cases which are called "Keywords".
Test Cases
Create New Vehicle
Create new vehicle with next ${registrationno} and ${description}
Navigate to data section
Those "Keywords" are imported from python library and look like:
#keyword("Create new vehicle with next ${registrationno} and ${description}")
def create_new_vehicle_Simple(self,registrationno, description):
headerPage = HeaderPage(TestCaseKeywords.driver)
sideBarPage = headerPage.selectDaten()
basicVehicleCreation = sideBarPage.createNewVehicle()
basicVehicleCreation.setKennzeichen(registrationno)
basicVehicleCreation.setBeschreibung(description)
TestCaseKeywords.carnumber = basicVehicleCreation.save()
The problem is that when I run test cases, in log I only get result of this whole python function, pass or failed. I can't see at which step it failed- is it at first or second step of this function.
Is there any plugin or other solution for this case to be able to see which exact python function pass or fail? (of course, workaround is to use in TC for every function a keyword but that is not what I prefer)
If you need to "step into" a python defined keyword you need to use python debugger together with RED.
This can be done with any python debugger,if you like to have everything in one application, PyDev can be used with RED.
Follow below help document, if you will face any problems leave a comment here.
RED Debug with PyDev
If you are wanting to know which statement in the python-based keyword failed, you simply need to have it throw an appropriate error. Robot won't do this for you, however. From a reporting standpoint, a python based keyword is a black box. You will have to explicitly add logging messages, and return useful errors.
For example, the call to sideBarPage.createNewVehicle() should throw an exception such as "unable to create new vehicle". Likewise, the call to basicVehicleCreation.setKennzeichen(registrationno) should raise an error like "failed to register the vehicle".
If you don't have control over those methods, you can do the error handling from within your keyword:
#keyword("Create new vehicle with next ${registrationno} and ${description}")
def create_new_vehicle_Simple(self,registrationno, description):
headerPage = HeaderPage(TestCaseKeywords.driver)
sideBarPage = headerPage.selectDaten()
try:
basicVehicleCreation = sideBarPage.createNewVehicle()
except:
raise Exception("unable to create new vehicle")
try:
basicVehicleCreation.setKennzeichen(registrationno)
except:
raise exception("unable to register new vehicle")
...

Why sbt.Extracted remove the previously defined TaskKey while append method?

There is a suitable method in the sbt.Exctracted to add the TaskKey to the current state. Assume I have inState: State:
val key1 = TaskKey[String]("key1")
Project.extract(inState).append(Seq(key1 := "key1 value"), inState)
I have faced with the strange behavior when I do it twice. I got the exception in the following example:
val key1 = TaskKey[String]("key1")
val key2 = TaskKey[String]("key2")
val st1: State = Project.extract(inState).append(Seq(key1 := "key1 value"), inState)
val st2: State = Project.extract(st1).append(Seq(key2 := "key2 value"), st1)
Project.extract(st2).runTask(key1, st2)
leads to:
java.lang.RuntimeException: */*:key1 is undefined.
The question is - why does it work like this? Is it possible to add several TaskKeys while executing the particular task by several calls to sbt.Extracted.append?
The example sbt project is sbt.Extracted append-example, to reproduce the issue just run sbt fooCmd
Josh Suereth posted the answer to sbt-dev mail list. Quote:
The append function is pretty dirty/low-level. This is probably a bug in its implementation (or the lack of documentation), but it blows away any other appended setting when used.
What you want to do, (I think) is append into the current "Session" so things will stick around and the user can remove what you've done via "sesison clear" command.
Additonally, the settings you're passing are in "raw" or "fully qualified" form. If you'd for the setting you write to work exactly the same as it would from a build.sbt file, you need to transform it first, so the Scopes match the current project, etc.
We provide a utility in sbt-server that makes it a bit easier to append settings into the current session:
https://github.com/sbt/sbt-remote-control/blob/master/server/src/main/scala/sbt/server/SettingUtil.scala#L11-L29
I have tested the proposed solution and that works like a charm.