How to debug static code block in GEB Page model - spock

I am trying out GEB and wanted to debug the static code block in the examples. I have tried to set breakpoints but i seem unable to inspect the data that is used in the static content block.
class GoogleResultsPage extends Page {
static at = { results }
static content = {
results(wait: true) { $("li.g") }
result { i -> results[i] }
resultLink { i -> result(i).find("a.l")[0] }
firstResultLink { resultLink(0) }
}
}
Any clue on how this normally can be debugged using for example IntelliJ?

Since the content block is using a DSL and undergoes a transformation when compiled I'm thinking it wouldn't be possible to debug without special support from the IDE, however I hope someone can prove me wrong.
The approach I have been using is to define methods for anything beyond the core content. This provides a few benefits, including debugging support, IDE autocompletion when writing tests, and good refactoring support. The drawback of course is slightly more verbose code, although the tradeoff has been worth it for my purposes.
Here's how I might do the GoogleResultsPage:
class GoogleResultsPage extends Page {
static at = { results }
static content = {
results(wait: true) { $("li.g") }
}
Navigator result(int i) { results[i] }
Navigator resultLink(int i) { result(i).find("a.l")[0] }
Navigator firstResultLink { resultLink(0) }
}
Then when writing the test I use a slightly more typed approach:
class MySpec extends GebReportingSpec {
def "google search with keyword should have a first result"() {
given:
GoogleHomePage homePage = to(GoogleHomePage)
when:
homePage.search("keyword")
then:
GoogleResultsPage resultsPage = at(GoogleResultsPage)
resultsPage.result(0).displayed
}
}

Related

How do I add a Global Tag in Axe DevTools (Attest)

I'm using Axe DevTools and I'm trying to figure out how to tag multiple scans with the same build information. Right now I have my tests running like this:
class MyTestCase : XCTestCase {
func myTest() {
Attest.that(view: view)
.isAccessible({ result in })
.andPushResult(withTags: [myBuild])
}
}
How can I add the myBuild tag globally to all tests that I run?
I would build my own class that utilizes the Axe DevTools (Attest) APIs. Then have my test cases interact with my own class instead of interacting with Attest itself!
class AccessibilityTestUtils {
static let buildTag:String = Bundle.main.object(
forInfoDictionaryKey: "CFBundleShortVersionString"
) as! String
init(build: String) {
self.buildTag = build
}
static func runAccessibilityTestOn(aView : View) {
Attest.that(view: aView).isAccessible({ result in })
.andPushResult(withTags: [buildTag])
}
}
Example Usage
class YourTestClass {
func yourTestCase() {
AccessibilityTestUtils.runAccessibilityTestOn(aView)
}
}
Note: This approach also protects you from future changes to the Attest library by making it so that you only have to change one line of code in the event of non backwards compatible changes.

How do functions with multiple parameters of the same name work?

I've been looking through the code for a Flash game (link). However, I'm having trouble understanding how some of these functions work, especially because some of them have function definitions that I would think to fail to get past the compiler.
The following is some code from TodCommon.as that appears to conflict with itself (or at the very least uses bad naming conventions).
private static var gFlashingColor:Color = new Color();
final public static function ClampFloat(ClampInt:Number, ClampInt:Number, ClampInt:Number) : Number
{
if(ClampInt <= ClampInt)
{
return ClampInt;
}
if(ClampInt >= ClampInt)
{
return ClampInt;
}
return ClampInt;
}
final public static function ClampInt(gFlashingColor:int, gFlashingColor:int, gFlashingColor:int) : int
{
if(gFlashingColor <= gFlashingColor)
{
return gFlashingColor;
}
if(gFlashingColor >= gFlashingColor)
{
return gFlashingColor;
}
return gFlashingColor;
}
Also in the code is the weirdest syntax for a for-each loop that I've ever seen (this example also features a package name as a parameter name)
public function CountPlantByType(com.popcap.flash.framework.resources.fonts:int) : int
{
var _loc_3:CPlant = null;
var _loc_2:int = 0;
var _loc_4:int = 0;
var _loc_5:* = this.mPlants;
while(<to complete>)
{
_loc_3 = __nextvalue;
if(_loc_3.mSeedType != com.popcap.flash.framework.resources.fonts)
{
break;
}
_loc_2++;
}
return _loc_2;
}
Those are just a few examples of things that I think look super weird and am having trouble understanding. But these functions all work and are used extensively throughout the code. Can someone explain how the ClampFloat and ClampInt functions work, or why it's legal to use a package name as a parameter? Thanks
Resolved. Turns out the program I used to extract these files from the SWF also corrupted them in the process. Using JPEXS Free Flash Decompiler instead of ActionScriptExtractor fixed the code syntax.

Is this loginRequired(f)() the way to handle login required functions in dart?

I am new to Dart programming. I am trying to figure out what is the proper way (what everyone will do) to handle/guard those functions which are login required. The following is my first trial:
$ vim login_sample.dart:
var isLoggedIn;
class LoginRequiredException implements Exception {
String cause;
LoginRequiredException(this.cause);
}
Function loginRequired(Function f) {
if (!isLoggedIn) {
throw new LoginRequiredException("Login is reuiqred.");
}
return f;
}
void secretPrint() {
print("This is a secret");
}
void main(List<String> args) {
if (args.length != 1) return null;
isLoggedIn = (args[0] == '1') ? true : false;
try {
loginRequired(secretPrint)();
} on LoginRequiredException {
print("Login is required!");
}
}
then, run it with $ dart login_sample.dart 1 and $ dart login_sample.dart 2.
I am wondering if this is the recommended way to guard login required functions or not.
Thank you very much for your help.
Edited:
My question is more about general programming skills in Dart than how to use a plugin. In python, I just need to add #login_required decorator in the front of the function to protect it. I am wondering if this decorator function way is recommended in dart or not.
PS: All firebase/google/twitter/facebook etc... are blocked in my country.
I like the functional approach. I'd only avoid using globals, you can wrap it in a Context so you can mock then for tests and use Futures as Monads: https://dartpad.dartlang.org/ac24a5659b893e8614f3c29a8006a6cc
Passing the function is not buying much value. In a typical larger Dart project using a framework there will be some way to guard at a higher level than a function - such as an entire page or component/widget.
If you do want to guard at a per-function level you first need to decide with it should be the function or the call site that decides what needs to be guarded. In your example it is the call site making the decision. After that decision you can implement a throwIfNotAuthenticated and add a call at either the definition or call site.
void throwIfNotAuthenticated() {
if (!userIsAuthenticated) {
throw new LoginRequiredException();
}
}
// Function decides authentication is required:
void secretPrint() {
throwIfNotAuthenticated();
print('This is a secret');
}
// Call site decides authentication is required:
void main() {
// do stuff...
throwIfNotAuthenticated();
anotherSecreteMethod();
}

What are the alternatives to overriding asType() when writing conversion code?

It appears the convention for converting objects in Groovy is to use the as operator and override asType(). For example:
class Id {
def value
#Override
public Object asType(Class type) {
if (type == FormattedId) {
return new FormattedId(value: value.toUpperCase())
}
}
}
def formattedId = new Id(value: "test") as FormattedId
However, Grails over-writes the implementation of asType() for all objects at runtime so that it can support idioms like render as JSON.
An alternative is to re-write the asType() in the Grails Bootstrap class as follows:
def init = { servletContext ->
Id.metaClass.asType = { Class type ->
if (type == FormattedId) {
return new FormattedId(value: value.toUpperCase())
}
}
}
However, this leads to code duplication (DRY) as you now need to repeat the above in both the Bootstrap and the Id class otherwise the as FormattedId will not work outside the Grails container.
What alternatives exist to writing conversion code in Groovy/Grails that do not break good code/OO design principals like the Single Responsibility Principal or DRY? Are Mixins are good use here?
You can use the Grails support for Codecs to automatically add encodeAs* functions to your Grails archetypes:
class FormattedIdCodec {
static encode = { target ->
new FormattedId((target as String).toUpperCase()
}
}
Then you can use the following in your code:
def formattedId = new Id(value: "test").encodeAsFormattedId
My un-elegant solution is to rename the original asType(), and make a new asType() that calls it, and to also make your BootStrap overwrite astType with a call to that method:
so, your class:
class Id {
def value
#Override
public Object asType(Class type) {
return oldAsType(type);
}
public Object oldAsType(Class type) {
if (type == FormattedId) {
return new FormattedId(value: value.toUpperCase())
}
}
}
In my app, I had asType defined in a number of classes, so I ended up using a common closure in BootStrap.groovy:
def useOldAsType = {Class clazz ->
delegate.oldAsType(clazz)
}
Id.metaClass.asType = useOldAsType;
Value.metaClass.asType = useOldAsType;
OtherClass.metaClass.asType = useOldAsType;
SubclassOfValue.metaClass.asType = useOldAsType;
Note that if you have a subclass that does not override asType, but you want it to use the superclass's, you must also set it in BootStrap.

Groovy Meta Programming

I want to override a method definition in Grails. I am trying to use Groovy metaprogramming as the class which I want to override belongs to a framework.
Below is the original class.
class SpringSocialSimpleSignInAdapter implements SignInAdapter {
private RequestCache requestCache
SpringSocialSimpleSignInAdapter(RequestCache requestCache) {
this.requestCache = requestCache;
}
String signIn(String localUserId, Connection<?> connection, NativeWebRequest request) {
SignInUtils.signin localUserId
extractOriginalUrl request
}
}
I am trying to override like below
SpringSocialSimpleSignInAdapter.metaClass.signIn = {java.lang.String str, org.springframework.social.connect.Connection conn, org.springframework.web.context.request.NativeWebRequest webreq ->
println 'coming here....' // my implementation here
return 'something'
}
But for some reason overriding is not hapening. I am not able to figure it out. Any help would be greatly appretiated.
Thanks
Yeah, seems like that bug. I don't know your whole scenario, but anyway, here's a small workaround i made:
In your class definition, you don't implement the interface
You create your object and do your metamagic
Use groovy coercion to make it act as the interface and then you can pass it around
Here is a small script i made using JIRA bug to prove it:
interface I {
def doIt()
}
class T /*implements I*/ {
def doIt() { true }
}
def t = new T()
assert t.doIt()
t.metaClass.doIt = { -> false }
// here the coercion happens and the assertion works fine
def i = t as I
assert !i.doIt()
assert !t.doIt()
// here the polymorphism happens fine
def iOnlyAcceptInterface(I i) { assert !i.doIt() }
iOnlyAcceptInterface(i)

Resources