I want to override the ScalaTest trait BeforeAndAfterEach to have that stuff implemented once for all my tests. Finally I got it to compile, but I don't understand why.
trait MySetup extends BeforeAndAfterEach {
this : org.scalatest.BeforeAndAfterEach with org.scalatest.Suite =>
var service: String = _
abstract override def beforeEach(): Unit = {
service = "apa"
super.beforeEach()
}
abstract override def afterEach(): Unit = {
service = ""
}
}
The thing that got it working was the line:
this : org.scalatest.BeforeAndAfterEach with org.scalatest.Suite =>
I found it in the beginning of the BeforeAndAfterEach implementation and copied it.
What does it do, and why do I need it?
Update:
This is a simpler version.
trait MySetup extends FlatSpec with BeforeAndAfterEach {
var service: String = _
override def beforeEach {
service = "apa"
super.beforeEach
}
override def afterEach {
service = ""
super.afterEach
}
}
BeforeAndAfterEach has a self-type of Suite, meaning that BeforeAndAfterEach can only be mixed in to a type that extends Suite. ScalaTest wants to you pick a primary suite type first and then mix-in behavior afterwards.
The self-type declaration is not inherited in sub-traits so you have to redeclare the self-type.
The following question has some tradeoffs between self-types and sub-traits: What is the difference between self-types and trait subclasses?
For some background on ScalaTest design, see: http://www.artima.com/scalazine/articles/selfless_trait_pattern.html
The way I'd probably write MySetup is this:
import org.scalatest.Suite
import org.scalatest.BeforeAndAfterEach
trait MySetup extends BeforeAndAfterEach { this: Suite =>
var service: String = _
abstract override def beforeEach(): Unit = {
service = "apa"
super.beforeEach()
}
abstract override def afterEach(): Unit = {
try {
super.afterEach() // To be stackable, must call super.afterEach
}
finally {
service = ""
}
}
}
That way the self type is less intrusive. Mike's answer is correct. The idea is to allow traits to stack, so you can mix in multiple traits like this, in different orders if you want. Another relevant article is "The Stackable Trait Pattern":
http://www.artima.com/scalazine/articles/stackable_trait_pattern.html
You may also find the examples in the relevant Scaladoc section helpful:
http://www.scalatest.org/scaladoc-1.6.1/org/scalatest/FlatSpec.html#composingFixtures
Note I call super.afterEach too. To be stackable, you need to call super on both beforeEach and afterEach. I do it in a try so that if the super.afterEach blows up with an exception, you still get the after behavior of this trait. (Though likely your Suite will abort anyway at that point, so in this case it probably doesn't matter. But in general it's a good idea.)
This is Scalas syntax for dependency injection.
this: <dependency> =>
It means literally this trait depends upon <dependency> trait. Read this article for more.
Related
I am trying to override a method of trait in my case class which want to display all the members of case class. I am using it for debugging purpose.
trait A{
def myMethod(employee:Emp):Unit
}
case class Emp(id:String,name:String) extends A {
override def myMethod(employee: Emp): Unit =
emp.productIterator.toList.foreach(println)
}
other possible way to do this is
emp.productIterator.toList.mkString("\n")
to declare Emp("10","abc"). I am new to Scala, not sure how to call the override method of trait.
I am not sure if any other generic way to achieve this functionality
to get string form of case class members.
Efficient way to use trait and case class to achieve this
functionality.I want to understand how apply method and companion
objects can be implemented .
I want to implement logging instead of using println. Can anyone
suggest a tutorial for it?
Previous answer was because i didn't understood your question right. This should answer your question:
If you want this only for debugging purposes you can use it like that:
trait A{
def myMethod(employee:Emp):Unit
}
case class Emp(id:String,name:String) extends A {
override def myMethod(employee: Emp): Unit =
this.productIterator.toList.foreach(println)
}
Emp("1", "2").myMethod(None.orNull)
But more logical would be to use object with this nonGeneric method:
case class Emp(id:String,name:String)
object A{
def myMethod(employee: Emp):Unit = {
employee.productIterator.toList.foreach(println)
}
}
A.myMethod(Emp("1", "2"))
For logging purposes you can use just apache log4j
We've got several types of resources and we wanted to make a method to check if a resource is healthy or not. Given that the type of resources are very heterogeneous we didn't want to use standard subclassing and we decided to use a typeclass:
trait CanHealthCheck[T] {
def isHealthy(t: T): Boolean
}
We also have a utility method to be able to check if a given resource is alive/healthy or not
object LivenessChecker {
def isAlive[T](t: T)(implicit canHealthCheck: CanHealthCheck[T]): Boolean = {
canHealthCheck.isHealthy(t)
}
}
We've got a repository layer to access to the data. We would like to express the idea that a given abstract repository must be "health checkable" but to leave the implementation details to the subclasses implementing the trait:
trait UserRepository {
def findSomeUser(): User = ???
implicit def isHealthCheckable: CanHealthCheck[UserRepository]
}
The problem arises when we want to subclass UserRepository with a particular implementation, given that CanHealthCheck is not covariant on the type T.
class DbUserRepository extends UserRepository {
def ping: Boolean = ???
override implicit val isHealthCheckable: CanHealthCheck[UserRepository] =
new CanHealthCheck[DbUserRepository] {
def isHealthy(db: DbUserRepository) = db.ping
}
}
And this is an example of some dummy function that acts on the abstract repository while trying to check if the repository is alive:
def someDummyFunction(userRepository: UserRepository) = {
if(LivenessChecker.isAlive(userRepository)) // This won't compile
userRepository.findSomeUser()
}
The idea is that our application uses the UserRepository trait and not the implementation, and thus we cannot check whether the repository is alive or not. How can we continue using the repository abstraction layer and be able to check if a given (abstract) repository is alive? Is the typeclass pattern the correct pattern to use here?
There is something a bit fishy with isHealthCheckable inside UserRespository. The isHealthy method, when called, would have two instances of UserRepository available: of course, the one passed as the t argument, but also, the UserRepository.this of the enclosing instance.
This is a sign of something wrong. Either the method should be written somewhere else, so that it does not get enclosing this, or it should not get the argument
That second option is consistent with using UserRepository the object-oriented, subtyping way. Also, it is consistent with your idea that every UserRepository must be heath-checkable. Just do
trait UserRepository {
...
def isHealty: Boolean
}
It is fine to call that directly, userDirectory.isHealthy. But you can then also easily implement the type class:
object UserRepository {
implicit val canHealthCheck = new CanHealthCheck[UserRepository] {
def isHealthy(repository: UserRepository) = repository.IsHealthy
}
}
also note that it was not clear at all how the implicit instance method would have come into the implicit scope. With the companion object, it works fine.
Use "type bounds".
I couldn't test this, but to get the code to compile, you could do something like:
class DbUserRepository[U <: UserRepository] extends UserRepository {
def ping: Boolean = ???
implicit val isHealthCheckable: CanHealthCheck[U] =
new CanHealthCheck[U] {
def isHealthy(db: U) = db.ping
}
}
I'm trying to design a small module system for my application such that I can do this:
new MyApplication extends Module1 with Module2 ... with ModuleN
In order to let my modules register themselves with the application, I also have:
trait ModuleRegistry {
def register(start: () => Unit) = // Stores start functions in a list
}
trait Module {
self: ModuleRegistry =>
self.register(start)
def start(): Unit
}
class Application extends ModuleRegistry {
}
trait Module1 extends Module {
...
}
The idea is that modules can register a function with the registry to be called when the application starts up. Unfortunately, the Scala compiler forces me to do this:
trait Module1 extends Module {
self: ModuleRegistry =>
}
meaning that all implementations of a module have to explicitly self-type themselves with the registry, when ideally they'd have no knowledge of it.
So my questions are:
Why does the compiler force me to re-specify this self-type on an extending trait? Ideally I don't even want the extending trait to 'see' this type, as it should be handled by the base Module trait. The 'concrete' module is meant to be implemented by 3rd parties, so exposing the registry to them seems kinda ugly.
Is there a better way to do what I'm trying to achieve in Scala so that modules can be freely mixed in?
This isn't a good use of the cake pattern, as you want all the modules to retain their own functionality (presumably), not mix and overwrite each other when mixed in. If you want the latter, you shouldn't: only with very careful design can this give predictable and sane results, and if third parties are supposed to provide the modules it's pretty much guaranteed that the design will not be that careful.
Instead, you should adhere to the "favor composition over inheritance" advice.
trait Module {
def start: Unit
}
trait Modular {
protected def moduleList: Seq[Module]
protected def register() = moduleList.map(m => m.start _)
}
class Application(modules: Module*) extends Modular {
protected def moduleList: Seq[Module] = modules // Fix varargs type
protected val registered = register()
}
object Module1 extends Module {
def start = println("One")
}
object Module2 extends Module {
def start = println("Two")
}
val app = new Application(Module1, Module2) {
registered.foreach(_())
}
// Prints "One", then "Two"
This is assuming a singleton is okay for a module. If you need a specific instance, you can either override apply (syntax is then Module1()) in the companion object, or add a builder trait that Module1 extends (e.g. trait ModuleBuilder { def module: Module }).
I am using Specs2 with play 2.2.1 built with Scala 2.10.2 (running Java 1.7.0_51). I have been reading about how to do setup/teardown with Specs2. I have seen examples using the "After" trait as follows:
class Specs2Play extends org.specs2.mutable.Specification {
"this is the first example" in new SetupAndTeardownPasswordAccount {
println("testing")
}
}
trait SetupAndTeardownPasswordAccount extends org.specs2.mutable.After {
println("setup")
def after = println("teardown ")
}
This works fine, except that all of my tests are using "in new WithApplication". It seems what I need is to have an object which is both a "WithApplication" and an "After". Below does not compile, but is essentially what I want:
trait SetupAndTeardownPasswordAccount extends org.specs2.mutable.After with WithApplication
So, my question is, how do I add setup/teardown to my tests which are already using "in WithApplication"? My primary concern is that all of our tests make use of fake routing like this (so they need the With Application).
val aFakeRequest = FakeRequest(method, url).withHeaders(headers).withBody(jsonBody)
val Some(result) = play.api.test.Helpers.route(aFakeRequest)
result
This is the code for WithApplication:
abstract class WithApplication(val app: FakeApplication = FakeApplication()) extends Around with Scope {
implicit def implicitApp = app
override def around[T: AsResult](t: => T): Result = {
Helpers.running(app)(AsResult.effectively(t))
}
}
It's actually quite easy to modify this to suit your needs without creating a bunch of other traits. The missing piece here is the anonymous function t, which you provide the implementation for in your tests (using WithApplication). It would be nice to make WithApplication a little more robust to be able to execute arbitrary blocks of code before and after the tests, if necessary.
One approach could be to create a similar class to WithApplication that accepts two anonymous functions setup and teardown that both return Unit. All I really need to do is modify what's happening inside AsResult.effectively(t). To keep this simple, I'm going to remove the app parameter from the parameter list, and use FakeApplication always. You don't seem to be providing a different configuration, and it can always be added back.
abstract class WithEnv(setup: => Unit, teardown: => Unit) extends Around with Scope {
implicit def implicitApp = app
override def around[T: AsResult](t: => T): Result = {
Helpers.running(app)(AsResult.effectively{
setup
try {
t
} finally {
teardown
}
})
}
}
Instead of simply calling the anonymous function t, I first call setup, then t, then teardown. The try/finally block is important because failed tests in specs2 throw exceptions, and we want to be sure that teardown will be executed no matter what the outcome.
Now you can easily setup test environments using functions.
import java.nio.files.{Files, Paths}
def createFolder: Unit = Files.createDirectories(Paths.get("temp/test"))
def deleteFolder: Unit = Files.delete("temp/test")
"check if a file exists" in new WithEnv(createFolder, deleteFolder) {
Files.exists(Paths.get("temp/test")) must beTrue
}
(This might not compile, but you get the idea.)
If your after method doesn't need anything from the WithApplication trait you can mix in your specification the AfterExample trait and define the after behaviour for the whole spec:
import org.specs2.specification._
class Specs2Play extends org.specs2.mutable.Specification with AfterExample {
"this is the first example" in new SetupAndTeardownPasswordAccount {
pending("testing")
}
trait SetupAndTeardownPasswordAccount extends WithApplication
def after = println("cleanup")
}
In Scala, is there there anything wrong with using the below method of dependency injection.
// Define an interface
trait FileStorage {
def readFile(filename:String):OutputStream
}
// And an implementation
class S3FileStorage extends FileStorage {
def readFile(filename:String):OutputStream = ???
}
// Define our service as a trait with abstract fields that need to be
// injected in order to construct. All implementation details go here.
trait FileHTTPServer {
val fileStorage:FileStorage
def fetchFile( session:Session, filename:String ) = ???
}
Now we wire things up
// Wire up a concrete file service that we actually use in code
// No implementation details should go here, we're simply wiring up a FileHttpServerl
// An entire project could be wired up this way in a central location if desired.
object S3FileHttpServer extends FileHTTPServer {
val fileStorage = new S3FileStorage
}
// We could also do this anonymously
val myHttpServer = new FileHttpServer {
val fileStorage = new S3FileStorage
}
// Or create a mocked version for testing
val mockedHttpServer = new FileHttpServer {
val fileStorage = mock[FileStorage]
}
Obviously the Cake pattern provides more flexibility (particularly around self-types), however for simpler use cases this has much less boilerplate, while still providing compile time checking and a clean unambiguous interface.
Yes, this is absolutely fine approach. And yes, sometimes you can use constructor injection, nothing wrong with that too. But with constructor injection you have to propagate your dependencies manually, while with cake pattern your dependencies are propagated automatically via self-type annotations. So for big projects constructor injection actually lead to more boilerplate than cake pattern, especially at the construction site (where you create all your objects and set up dependencies between them).
However, what you have presented is not full-fledged cake pattern. In real cake pattern there is an additional layer around business logic classes, so-called components, and you do not wire up logic classes directly but components instead.
trait FileStorageComponent {
def fileStorage: FileStorage
trait FileStorage {
def readFile(filename: String): OutputStream
}
}
trait S3FileStorageComponent extends FileStorageComponent {
val fileStorage = new S3FileStorage
class S3FileStorage extends FileStorage {
def readFile(filename: String): OutputStream = ???
}
}
trait FileHttpServerComponent {
self: FileStorageComponent =>
val fileHttpServer = new FileHttpServer
class FileHttpServer {
def fetchFile(session: Session, filename: String) = ???
}
}
// Wiring
object S3FileHttpServer extends FileHttpServerComponent with S3FileStorageComponent
// Anonymous
val server = new FileHttpServerComponent with S3FileStorageComponent
// Mocking
object TestFileHttpServer extends FileHttpServerComponent with FileStorageComponent {
val fileStorage = mock[FileStorage]
}
In this approach there are more boilerplate in traits definitions, but in return you have greater flexibility and very clear dependency management on the use place. For example, here is how program entry point in one of my projects looks like:
object Main
extends MainUI
with DefaultActorsManagerComponent
with DefaultPreferencesAccessComponent
with DefaultModelComponent
with DefaultMainWindowViewComponent
with DefaultMainWindowControllerComponent
with MainWindowReporterComponent
with DefaultClientActorComponent
with DefaultResponseParserActorComponent
with DefaultArchiverActorComponent
with DefaultMainWindowAccessActorComponent
with DefaultUrlParserComponent
with DefaultListenerActorComponent
with DefaultXmlPrettifierComponent
All main program components are in one place. Pretty neat IMO.