Archive for the 'scala' Category
Selenium2 from Scalatest
Scalatest offers some very elegant ways to layout your tests. After using Selenium2 at work I started thinking how I could leverage the BDD-like goodness in combination with Selenium2. The combination proves to be very useful.
Some basics
Selenium2 offers a couple of drivers which allow your code to spawn webbrowsers (or a virtual browser) and control and monitor them.
In Scala starting a Firefox instace and opening a url would look like:
-
val driver = new FirefoxDriver
-
driver.get("http://log4p.com/")
After opening the page you can use the driver to browse the actual Dom of the response. Methods for this include stuff like findElementsByTagName, ClassName, Id and XPath. It even allows you to make a PNG image of the page.
Bind pages to classes
Next to the above methods the driver can 'bind' values in the page to bean properties. I discovered that Selenium has no problems with populating annotated Scala classes:
-
class BlogPage {
-
@FindBy(how = How.ID, using = "cat")
-
var categorySelect: WebElement = null
-
-
@FindBy(how = How.ID, using = "content")
-
var content: WebElement = null
-
-
....
-
}
The FindBy annotations can also be configure to use classes, XPaths, partial url texts etc. Populating instances can be done via the driver (after having it request a url):
-
driver.get("http://log4p.com/")
-
val indexPage = PageFactory.initElements(driver, classOf[BlogPage])
combined with FeatureSpec
FeatureSpecs allow you to describe scenarios of features, and has options to create 'pending' tests; very useful for test driven development. If we combine Selenium with this type of test we get something like this:
-
class Log4pSpec extends FeatureSpec with GivenWhenThen with ShouldMatchers {
-
lazy val driver = new FirefoxDriver
-
-
feature("A weblog should have a archive based on post categories") {
-
info("As a visitor")
-
info("I want to be able to select a category")
-
-
scenario("we select the 'scala' category to see posts about Scala") {
-
given("we open the frontpage page")
-
-
driver.get("http://log4p.com/")
-
val indexPage = PageFactory.initElements(driver, classOf[BlogPage])
-
-
then("we should see a widget containing categories")
-
indexPage.categorySelect.isEnabled should equal(true)
-
-
given("we select 'scala' using the select widget")
-
indexPage.selectCategoryName("scala")
-
-
then("the url for that category should be openend")
-
driver.getCurrentUrl should endWith("/category/scala/")
-
-
then("all posts should have the selected category in their metadata")
-
val categoryPage = PageFactory.initElements(driver, classOf[BlogPage])
-
categoryPage.verifyPostCategories("scala") should equal(true)
-
}
-
-
}
-
}
This test will:
- Start Firefox
- Open the frontpage of this blog
- Select 'scala' in the category box in the menu on the right
- Verify the opened url
- Verify that all posts in the category page have the selected category in their metadata
If you run the test, scalatest will create some very nice output:
-
Feature: A weblog should have a archive based on post categories
-
As a visitor
-
I want to be able to select a category
-
Scenario: we select the 'scala' category to see posts about Scala
-
Given we open the frontpage page
-
Then we should see a widget containing categories
-
Given we select 'scala' using the select widget
-
Then the url for that category should be openend
-
Then all posts should have the selected category in their metadata
Keen observers might have noticed some helper methods on the BlogPage class, like 'selectCategoryName' and 'verifyPostCategories'. Using the collection conversions from Scala 2.8 we don't even have to wrap the Selenium API to make them look nice:
-
class BlogPage {
-
@FindBy(how = How.ID, using = "cat")
-
var categorySelect: WebElement = null
-
-
@FindBy(how = How.ID, using = "content")
-
var content: WebElement = null
-
-
-
def selectCategoryName(categoryName: String) = {
-
val options = categorySelect.findElements(By.tagName("option"))
-
val option: Option[WebElement] = options.find(_.getText.equals(categoryName))
-
if (option.isDefined)
-
option.get.setSelected
-
}
-
-
def verifyPostCategories(categoryName: String): Boolean = {
-
val entries = content.findElements(By.className("entry"))
-
entries.forall {
-
entry =>
-
val entryMetaData = entry.findElement(By.className("entrymeta"))
-
entryMetaData.getText.split("Category:").last.split(",").map(_.trim).contains(categoryName)
-
}
-
}
-
}
As you can see translating stories into real integration tests is quite simple; and it should be possible to run the tests in different browsers (Chrome, IE) as well. And since you won't be writing production code it could be a very nice way to give scala into your project!
No commentsPresentation: DSLs in Scala
At DuSe III I gave a presentation on writing Domain Specific Languages using Scala based on the work I did for my blogposts on internal and external with Scala.
After the SQL example I also showed some of the work I did on a custom templating language I wrote as a experiment for Ebay/Markplaats for which I wrote the parser and interpreter in Scala. Maybe I can give some more details on that in the future.
No commentsIntroduction to Scala
Last Tuesday I gave a 'introduction to Scala' presentation during the monthly 'Tech Tuesday' at Ebay/Marktplaats. After going through the slides I did some live test driven development. I think I managed to get some more people interested!
ScotchBuilder with Scala 2.8
While writing my internal SQL DSL example I stumbled upon this blogpost about a Type-safe Builder Pattern in Scala a couple of times. One of the issues I have with that code is the unnecessary use of mutable state in the example. Which are probably there to demonstrate the validation of the result at the end of the article.
The blogpost concludes with some complex implicit solution to have the builder only create valid configurations, but (IMHO) fails to address the fact that it is still possible to create OrderOfScotch variants which are invalid through its' constructor.
With Scala 2.8 it is possible to vastly simplify the example by using the the copy method on the case classes and default arguments:
-
sealed abstract class Preparation
-
case object Neat extends Preparation
-
case object OnTheRocks extends Preparation
-
case object WithExtraWater extends Preparation
-
-
sealed abstract class Glass
-
case object Short extends Glass
-
case object Tall extends Glass
-
case object Tulip extends Glass
-
-
case class OrderOfScotch(val brand:String , val mode:Preparation = Neat, val double:Boolean = false, val glass:Option[Glass] = None) {
-
val invalid: Boolean = double && glass.isDefined && glass.get == Short
-
if(invalid) {
-
throw new IllegalStateException("Illegal combination")
-
}
-
-
def prepare(p:Preparation) = copy(mode = p)
-
def isDouble(d:Boolean) = copy(double = d)
-
def inGlass(g:Glass) = copy(glass = Option(g))
-
}
-
-
object OrderBuilder {
-
def scotch(brand:String) = OrderOfScotch(brand)
-
}
Using the above you can write something like:
-
val scotchOrder1 = scotch("Glenfoobar") prepare WithExtraWater inGlass Tulip
-
val scotchOrder2 = scotch("Talisker") inGlass Tall prepare Neat
When using an incorrect configuration (in the example implementation a double scotch, in a short glass) creating the Order throws an exception. And since we in effect only use the constructor to create the Order this works in any case.
Consider the following tests:
-
class ScotchBuilderSpec extends Spec with ShouldMatchers {
-
import OrderBuilder._
-
describe("given two scotches with the same configuration") {
-
val constructorResult = OrderOfScotch("Glenfoobar", WithExtraWater, false, Option(Tulip))
-
val builderResult = scotch("Glenfoobar") prepare WithExtraWater inGlass Tulip
-
-
describe("when created by constructor and by the builder") {
-
it("they should return identical results") {
-
constructorResult should be (builderResult)
-
println("success!")
-
}
-
}
-
}
-
-
describe("trying to create an illegal order") {
-
describe("like combining a double portion with a short glass") {
-
it("should throw an exception, for now") {
-
evaluating { OrderOfScotch("Glenfoobar", Neat, true, Option(Short)) } should produce[Throwable]
-
evaluating { scotch("Glenfoobar") isDouble(true) inGlass Short } should produce[Throwable]
-
}
-
}
-
}
-
}
As you can see the amount of boilerplate code was reduced dramatically, we've got rid of all mutable state and moved validation of the Order to a (IMHO) better location!
One 'drawback' of my solution is of course that it only works on runtime; whereas the solution presented in the catches incorrect configurations created by the builder at compiletime... which was the entire point of that blogpost. I'll try and see if I can factor that into a more compact form as well lator on!
2 commentsexternal DSLs with scala
Following up on my previous post on writing an internal SQL-like DSL for Scala I decided to bite the bullet and implement a 'real' parser for a subset of the SQL language to create the object tree from a SQL-like string. Since I didn't have any experience in Parser/Combinators this proved to be quite an interesting exercise.
At this point the specs for the following queries succeed and produce valid results when I render SQL from the object graph:
-
select name from users order by name asc
-
select name from users where name = "peter"
-
select age from users where age = 30
-
select name from users where name = "peter" and age = 30
-
select name from users where age = 20 or age = 30
-
select name from users where name = "peter" and age = 20 or age = 30
-
select name,age from users where name = "peter" and (active = true or age = 30)
The entire parser is just under 54 lines of code!
As you can see in the source code the Parser is basically a collection of small parsers which are combined into a parser for the entire language. Let's have a look at the more basic ones:
The order clause
The order clause is probably the easiest part of the query. The production for the parser looks like this:
-
def order:Parser[Direction] = {
-
"order" ~> "by" ~> ident ~ ("asc" | "desc") ^^ {
-
case f ~ "asc" => Asc(f)
-
case f ~ "desc" => Desc(f)
-
}
-
}
It matches a string which starts with order by, then an identifier and ends with asc or desc. The tilde (~) depicts a separater, and the greater then (>) after the tilde is used to drop the fields on the left side of the operator; just to have less repetition in the match algorithm to bind the value into objects which will form the AST.
Quite straightforward and easy to read.
Typed predicates
I had some more troubles implementing the typed predicates and still feel this could be written a bit more concise:
-
def predicate = (
-
ident ~ "=" ~ boolean ^^ { case f ~ "=" ~ b => BooleanEquals(f,b)}
-
| ident ~ "=" ~ stringLiteral ^^ { case f ~ "=" ~ v => StringEquals(f,stripQuotes(v))}
-
| ident ~ "=" ~ wholeNumber ^^ { case f ~ "=" ~ i => NumberEquals(f,i.toInt)}
-
)
And/Or en parentheses
Implementing and/or in the where clause proved to be more difficult then I expected; mainly due to the precedence rules when using parentheses. I asked around on stackoverflow and read how this is done in this great article by Jim McBeath.
This resulted in the following solution:
-
def where:Parser[Where] = "where" ~> rep(clause) ^^ (Where(_:_*))
-
-
def clause:Parser[Clause] = (predicate|parens) * (
-
"and" ^^^ { (a:Clause, b:Clause) => And(a,b) } |
-
"or" ^^^ { (a:Clause, b:Clause) => Or(a,b) }
-
)
-
-
def parens:Parser[Clause] = "(" ~> clause <~ ")"
Which effectively is a way of repeating predicates or clauses within parentheses interleaved with and/or. The parens production is just pre- and postfixing the clause with parens.
Optional parts
The select and order clause are optional, this is specified using the opt method:
-
def query:Parser[Query] = operation ~ from ~ opt(where) ~ opt(order) ^^ {
-
case operation ~ from ~ where ~ order => Query(operation, from, where, order)
-
}
Since the Query object already accepts optional objects as where and order clause binding is straightforward.
Conclusion
Being fairly new to this game I had some trouble finding out how I was supposed to approach some of the problems I faced; but managed to overcome them quickly. There is a lot of documentation on various blogs and books. Writing a parser in Java, Groovy or Ruby would probably have taken me more time and would probably have resulted in far more code.
Now, off to look for some nails to test my new hammer on!
Full sources can be found in the Scala-SQL-DSL github repository.
3 commentsInternal DSLs with Scala
I've been playing around with Scala again lately. Writing a (internal) DSL or a fluent api was still on todo-list.
Instead of writing some arbitrary language for a made-up domain I decided to pick a language and a domain I know: SQL. Or, a rather small subset.
The first step was creating a model of the language (no, I didn't start with this diagram):
As you can see a query object consists of:
- Operation (i.e. select, update, delete)
- From
- Where, containing various predicates and ways to combine predicates
- Optional ordering
In Scala my implementation of the model looks like this:
-
case class Query(val operation:Operation, val from: From, val where: Where, val order: Option[Direction] = None) {
-
def order(dir: Direction) = this.copy(order = Option(dir))
-
}
-
-
abstract class Operation {
-
def from(table: String) = From(this, table)
-
}
-
case class Select(val fields:String*) extends Operation
-
-
case class From(val operation:Operation, val table: String) {
-
def where(clauses: Clause*): Query = Query(operation, this, Where(clauses:_*))
-
}
-
-
case class Where(val clauses: Clause*)
-
-
abstract class Clause {
-
def and(otherField: Clause): Clause = And(this, otherField)
-
def or(otherField: Clause): Clause = Or(this, otherField)
-
}
-
-
case class StringEquals(val f: String, val value: String) extends Clause
-
case class NumberEquals(val f: String, val value: Number) extends Clause
-
case class BooleanEquals(val f: String, val value: Boolean) extends Clause
-
case class In(val field: String, val values: String*) extends Clause
-
case class And(val clauses: Clause*) extends Clause
-
case class Or(val clauses: Clause*) extends Clause
-
-
abstract class Direction
-
case class Asc(field: String) extends Direction
-
case class Desc(field: String) extends Direction
As you can see the code is a straightforward implementation of the model, only using immutable values. I added some utility methods which will be used to 'chain' objects:
- Query#order - Clones the query object and overrides the order with the specified order
- Operation#from - creates a from clause from the operation object
- Clause#and / Clause#or - combines two clauses
Next to the model I created a QueryBuilder object which contains some implicit conversions and utility methods:
-
object QueryBuilder {
-
implicit def tuple2field(t: (String, String)): StringEquals = StringEquals(t._1, t._2)
-
implicit def tuple2field(t: (String, Int)): NumberEquals = NumberEquals(t._1, t._2)
-
implicit def tuple2field(t: (String, Boolean)): BooleanEquals = BooleanEquals(t._1, t._2)
-
-
/** entrypoint for starting a select query */
-
def select(fields:String*) = Select(fields:_*)
-
def in(field: String, values: String*) = In(field, values: _*)
-
}
The implicit conversions allow tuples to be converted to typed case classes. With the above we can write Scala code which resembles SQL. I Wrote some tests (using ScalaTest) which demonstrate how it works. Example inputs for my tests include:
-
val q = select ("*") from ("user") where (("name","peter") and (("active", true) or ("role", "admin")))
-
val q = select ("*") from ("user") where (("name","p'eter"))
-
val q = select ("*") from ("user") where (("id", 100))
-
val q = select ("*") from ("user") where (in("name","pe'ter","petrus"))
-
val q = select ("*") from ("user") where (("name","peter")) order Desc("name")
To generate a SQL String from a Query object I wrote a fairly basic generator and an implicit conversion to convert queries to SQL:
-
case class SQL(val sql:String)
-
-
object AnsiSqlRenderer {
-
implicit def query2sql(q:Query):SQL = SQL(sql(q))
-
-
def sql(q: Query): String = {
-
List(
-
expandOperation(q),
-
expandFrom(q),
-
expandWhere(q),
-
expandOrder(q)
-
).mkString(" ").trim
-
}
-
-
def expandOperation(q:Query):String = q.operation match {
-
case Select(fields) => "select %s".format(fields.mkString(","))
-
case _ => throw new IllegalArgumentException("Operation %s not implemented".format(q.operation))
-
}
-
-
def expandFrom(q: Query) = "from %s".format(q.from.table)
-
def expandWhere(q: Query) = "where %s".format(q.where.clauses.map(expandClause(_)).mkString(" "))
-
-
def expandClause(clause: Clause): String = clause match {
-
case StringEquals(field, value) => "%s = %s".format(field, quote(value))
-
case BooleanEquals(field, value) => "%s = %s".format(field, value)
-
case NumberEquals(field, value) => "%s = %s".format(field, value)
-
case in:In => "%s in (%s)".format(in.field, in.values.map(quote(_)).mkString(","))
-
case and:And => and.clauses.map(expandClause(_)).mkString("(", " and ", ")")
-
case or:Or => or.clauses.map(expandClause(_)).mkString("(", " or ", ")")
-
case _ => throw new IllegalArgumentException("Clause %s not implemented".format(clause))
-
}
-
-
def expandOrder(q: Query) = q.order match {
-
case Some(direction) => direction match {
-
case Asc(field) => "order by %s asc".format(field)
-
case Desc(field) => "order by %s desc".format(field)
-
}
-
case None => ""
-
}
-
-
def quote(value: String) = "'%s'".format(escape(value))
-
def escape(value: String) = value.replaceAll("'", "''")
-
}
Most of the beef is in (recursively) expanding the where clause into a String. When using the implicit conversion you can now do the following:
-
scala> val q = select ("*") from ("user") where (("name","peter") and (("active", true) or ("role", "admin")))
-
scala> q.sql
-
res0: java.lang.String = select * from user where (name = 'peter' and (active = true or role = 'admin'))
Apart from the parentheses (probably I'll figure out how to get rid of some more of them one day) the two look very similar. But the first one creates a typesafe object graph which can be rendered/validated/manipulated in various ways!
The example could be extended to allow 'greater/smaller then' clauses (using operator overloading?) or joins in the from clause; feel free to clone my repository and do so!
Full sources can be found in the Scala-SQL-DSL github repository.
6 comments3v12 api from Scala
I rewrote the code in my previous post in Scala, with a minor difference.. I'm not using an RSS api here.. Scala has native XML support... which makes writing basic RSS a breeze:
-
package v12_rss
-
-
import java.net.{URLConnection, URL}
-
import scala.xml._
-
-
// define some case classes as a simple model for the rss feed we're going to build
-
case class Channel(title:String, link:String, description:String, items:List[Item]) {
-
def toXML = <channel>
-
<title>{title}</title>
-
<link>{link}</link>
-
<description>{description}</description>
-
{items.map{_.toXML}}
-
</channel>
-
}
-
case class Item(title:String, link:String, description:String, enclosure:Enclosure) {
-
def toXML = <item>
-
<title>{title}</title>
-
<link>{link}</link>
-
<description>{}</description>
-
{enclosure.toXML}
-
</item>
-
}
-
case class Enclosure(url:String) {
-
def toXML = <enclosure url={url} type="image/jpeg"/>
-
}
-
-
// Helper for working with URN values from the API
-
case class Urn(urn:String) {
-
def comps = urn.split(":").slice(1, 4).toArray // remove the first value ('urn') not interesting
-
-
def src = comps.apply(0)
-
def mediaType = comps.apply(1)
-
def number = comps.apply(2)
-
}
-
-
object Main {
-
-
def main(args: Array[String]) = {
-
val groupElem = retrieveGroup(41129661)
-
println(<rss version="2.0">
-
{new Channel(title(groupElem), "http://3voor12.vpro.nl/tv/", shortTitle(groupElem), itemize(groupElem)).toXML}
-
</rss>)
-
}
-
-
def retrieveGroup(num:Int):Elem = {
-
XML.load("http://3voor12.vpro.nl/api/media/1/rest/group/"+ num + ".xml")
-
}
-
-
// short for getting an attribute as string
-
def attr(node:Node, name:String) = node.attribute(name).get.text
-
-
// retrieve the first title field from the given XML
-
def title(elem:Elem):String = (elem \\ "title").first.text
-
-
// retrieve the first shortTitle field from the given XML
-
def shortTitle(elem:Elem):String = (elem \\ "shortTitle").first.text
-
-
// determine the image url for the given media xml
-
def imageUrl(elem:Elem):String = "http://images.vpro.nl/images/" + new Urn(attr((elem \\ "image").first, "urn")).number
-
-
def itemize(group:Elem):List[Item] = {
-
val items = (group \\ "media") slice(0, 15) map{ m =>
-
val urn = new Urn(attr(m, "urn"))
-
println ("http://3voor12.vpro.nl/api/media/1/rest/"+ urn.mediaType +"/"+ urn.number + ".xml")
-
val media = XML.load("http://3voor12.vpro.nl/api/media/1/rest/"+ urn.mediaType +"/"+ urn.number + ".xml")
-
-
new Item(title(media), "http://3voor12.vpro.nl/tv/#/41129661/" + urn.number , shortTitle(media), new Enclosure(imageUrl(media)))
-
}
-
-
items.toList
-
}
-
}
