Play 2.0 - access running (Fake)Application from scala console - scala

I'm just getting started with the Play Framework 2.0 (using current trunk 2.1-SNAPSHOT, Scala) and I'm finding it very useful to experiment with the Scala API in the play console.
For some things, however, for example stuff that depends on play.libs.WS API, I'm getting the There is no started application error. Fair enough, but I can't figure out how to set up a fake one up to use from the console, or whether this is even possible.
It seems that play.api.test._ isn't even accessible from the console. Any suggestions?
Update: Thanks to #charroch, I needed to run play test:console, so I can now do:
import play.api.test.Helpers.running
import play.api.test.FakeApplication
val res = running(FakeApplication()) {
MyWebservice.someFunction()
}

try test:console to start the console with test api in classpath
You need to have running(FakeApplication) {...} in your test as per:
http://www.playframework.org/documentation/2.0/ScalaTest

Related

A constructor from a node module I'm importing works when using Create React App, but errors in ParcelJS. What is going on?

I'm converting a project that was built using Create React App to use ParcelJS as a bundler instead. Strangely, a dependency that I imported during development (#twilio/voice-sdk) works fine in the CRA version of the application, but I get the following error when I try to invoke the constructor in the Parcel version:
TypeError: (this._options.AudioHelper || audiohelper_1.default) is not a constructor
The package is identical between both (#v2.1.1, the latest). I'm importing using ESM syntax, so:
import { Device } from '#twilio/voice-sdk'
I trying using CommonJS syntax (require) and it still didn't work. I've dug into the compiled code, and that seems to be the issue. I imagine there are a lot of differences, but one that I've noticed is here:
On the left is the code compiled by Create React App, which does seem to be exporting something more substantial than on the left - is the export just an empty object? If so, it's no wonder I'm getting a constructor error.
Unfortunately, no amount of googling and SO sleuthing has clarified what I could do to make ParcelJS transpile this dependency properly, if that's the issue. I've tried to make the babel config for ParcelJS match CRA more closely by adding the following to a babel.config.json
{
"plugins": [
"#babel/plugin-transform-modules-commonjs"
]
}
But no luck. Any ideas from where to go from here, or is it time to switch to Webpack?
It looks like Twilio package has a problem when using Parcel 2: https://github.com/twilio/twilio-voice.js/issues/101

Cucumber Test Runner file-Not executing step definitions

I am building a Restassured API test framework with cucumber.(This is a new adventure for me so apologies if this seems basic)
Below is how I setup my test runner file.
package cucumber.Options;
import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
#RunWith(Cucumber.class)
#CucumberOptions(features="src/test/java/features", glue={"stepDefinitions"},strict=true,stepNotifications = true)
public class TestRunner{
}
I have made sure the glue matches my step def file, ive also tried adding the full path.
However my step definitions no matter what I set as the glue are not being executed.
As soon as I run the TestRunner File as a junit test junit marks the runs as complete.
I set up a simple scenario where I am just printing a test output to console and console never shows the output.
I even tried setting my glue to a filename that doesnt even exist to see if i got an error but i get the same result as above.
And whenever I click one of the the lines in the feature file I get error "Test class not found in selected project"
Error
Has anyone experienced the same behavior with eclipse?

Splitting routes with prefix not working in Play 2.7 (worked in 2.6)

Our project uses multiple routes files.
The conf/routes file contains something like:
/some/stuff
...
-> /api/admin admin.Routes
-> /api/user user.Routes
We then have conf/admin.routes and conf/user.routes files, which contain the prefixed API routes.
I’m trying to upgrade from Play 2.6 (where this setup has worked fine, as well as on earlier versions), to Play 2.7. When compiling I get the error:
[error] /usr/src/backend/conf/admin.routes:401: value concatPrefix is not a member of object play.api.routing.Router
[error] GET /myAdminRoute #com.my.some.controllers.MyControl.list()
[error] /usr/src/backend/conf/user.routes:140: value concatPrefix is not a member of object play.api.routing.Router
[error] GET /myUserRoute #com.my.other.controllers.MyControl.list()
Looking at Play migration for 2.7:
I’m not using StaticRoutesGenerator https://www.playframework.com/documentation/2.7.x/Migration27#StaticRoutesGenerator-removed
Looks suspicious: https://www.playframework.com/documentation/2.7.x/Migration27#StaticRoutesGenerator-removed Router#withPrefix should always add a prefix`. But I’m just using Play conf/routes, so I’m not sure what I should be changing?
I assume the issue is because of that Router withPrefix change, but I’m not sure how to interpret it in terms of what I need to update. Has anyone else had this issue with Play 2.7?
I've just had another play with this, the first time was a few weeks ago - and I'm not getting the same error. I can repro if I start again and forget the SBT unlock; reload; lock cycle, which is probably the mistake I made before. This leaves me with Play 2.6 libraries installed with the Play 2.7 plugin.

ScalaTest and SBT: Reporting progress of test suite?

I am using ScalaTest and have a test suite that contains many tests, and each test can take about a minute to run.
class LargeSuite extends FunSuite {
test("Name of test 1") { ... }
...
test("Name of test n") { ... }
}
As is usual with running ScalaTest tests from the SBT console, nothing is reported to the screen until each test in the FunSuite has been run. The problem is that when n is large and each test is slow to run, you do not know what is happening. (Running top or Windows Task Manager and looking for the CPU usage of Java is not really satisfactory.)
But the real problem is when the build is run by Travis CI: Travis assumes that the build has gone wrong and kills it if 10 minutes pass and nothing is printed to the screen. In my case, Travis is killing my build, even though the tests are still running, and each individual test in a FunSuite does not require 10 minutes (although the entire suite does require more than 10 minutes because of the number of tests).
My first question is therefore this: how can I get ScalaTest to report on progress to the console after each test in FunSuite, in an idiomatic way?
My partial solution is to use the following trait as a mixin, which solves the problem with Travis:
trait ProgressConsolePrinter extends BeforeAndAfterEach with BeforeAndAfterAll {
self: Suite =>
override def beforeAll: Unit = {
Console.print(s"$suiteName running")
Console.flush
}
override def afterEach: Unit = {
Console.print(".")
Console.flush
}
override def afterAll: Unit = {
Console.println
Console.flush
}
}
But I understand that using Console to print to the SBT console is not entirely reliable (Googling this seems to somewhat confirm this from the experiences of others).
Also (i) anything you print from Console does not go via SBT's logger, and is therefore not prefixed with [info], and (ii) when trying the above, the messages printed from Console are jumbled up with other messages from SBT. If I was able to use the proper logger, then neither of these things would happen.
My second question is therefore this: How can I print to an SBT logger from within a test in ScalaTest?
To get ScalaTest to report to the console after each test within SBT, add
logBuffered in Test := false
to your build configuration. (See the SBT docs.)
For general logging purposes within SBT, you can use an instance of sbt.util.Logger obtained from streams.value.log within an SBT task as described here. Wilson's answer below can be used if logging is required from the test code.
(I'm answering my own question two years later, but this is currently the first hit on Google for "ScalaTest sbt progress".)
This may be helpful for your second question.
To log like that you must use scala logging. You must add scala logging as a test dependency, extend some of its logging classes (suggest LazyLogging) and then call logger.info("Your message").

Calling into Play framework app from the Scala console

I have a Play Framework 2.3 app. I can drop into a Scala console with activator console. However, when I try to call into code from my app, specifically some helper function which uses WS, which uses the implicit import play.api.Play.current to retrieve the currently running app, I get the error message java.lang.RuntimeException: There is no started application.
What steps do I have to take to be able to load my app into the current console session?
There is a similar existing question, but the accepted answer appears to be using a mock app from the framework's test helpers. Preferably, I would like to run in the context of my actual app. If I must use a fake app, would it be possible to make it match my development environment (what I get when running activator run) rather than my test environment (what I get when running the unit tests)?
Thanks in advance!
In this specific case you can just create an Application instance and use it instead of the implicit one:
// Tested in 2.3.7
import play.api.{Play, Mode, DefaultApplication}
import java.io.File
import play.api.libs.ws.WS
val application = new DefaultApplication(
new File("."),
Thread.currentThread().getContextClassLoader(),
None,
Mode.Dev
)
import scala.concurrent.ExecutionContext.Implicits.global
WS.client(application).url("http://www.google.com").get().map((x) => println(x.body))
For future readers, for Play framework 2.5.x:
import play.api._
val env = Environment(new java.io.File("."), this.getClass.getClassLoader, Mode.Dev)
val context = ApplicationLoader.createContext(env)
val loader = ApplicationLoader(context)
val app = loader.load(context)
Play.start(app)
Source: https://www.playframework.com/documentation/2.5.x/PlayConsole#Launch-the-interactive-console