Planeta PT.JUG

O Planeta PT.JUG é um agregador de blogs de membros do PT.JUG. Se queres que o teu blog esteja presente neste agregador então basta fazeres um post para a lista do PT.JUG a indicar isso mesmo.

 Subscrever Feed

Writing a BDD DSL in Scala

One of my favourite BDD frameworks is easyb. I really like the dsl for user stories. In a previous post called Easy Requirements by Example I discussed how easy and clear this dsl can be.

For Scala I would also like to have a dsl just like the one of easyb. Writing a dsl in Scala is real easy, not as easy as in Groovy, but easy enough. So I decided to see how fast I could write a story dsl in Scala.

So, I need to be able to write things like the following

given ("a blogger with a blog") {
val blogger = new Blogger("Mr Blog", "mrblog@blogger.com", "passwd")
val blog = new Blog("blogTitle", blogger)

when("mr blog writes a new post") {
blog addPost ("post Title", "post Text");
}
and
when("mr blog publishes its post") {
blog publishPost
}
then("the post should be publised for reading") {
blog.published shouldHave "post Title"
}
}

The words given, when, then, and, shouldHave are part of the dsl.
The story dsl words are defined by a curried function. They have a explaining piece of text as the first argument and a code block as the second argument.

See below the definition of given

def given(text: String)( codeBlock: => Unit ) = {
codeBlock;
}

Because given is a curried function you can pass in the arguments one at a time. And when you pass in one argument you can choose to use curly braces instead of parentheses. As you can see in the above example, the given function has the rest of the story as the second argument within curly braces. So, the when, then, and form the codeBlock argument.

Here is the definition of the other methods

def then(text: String)( codeBlock: => Unit ) = {
codeBlock;
}

def when(text: String)( codeBlock: => Unit ) = {
codeBlock;
}

def and(text: String)() = {
}

… Yep this is really simple!

Because the codeBlock parameters are so-called “By-name-parameters” the codeBlocks of the functions are only evaluated when the given method evaluates it’s codeBlock! Also because closures in Scala see changes made to the free variables outside of the closure itself, you get the sequential execution ordering of the story.

The only thing that is left is the shouldHave word. As you might have guessed this is just a simple implicit conversion. To have free integration with IDE’s and other tools I choose to use JUnit as the underlying framework. So all the dsl vertification words are mapped to JUnit asserts as you can see below.

implicit def shouldHave(l: List[Any]) = {
ShouldHave(l)
}

case class ShouldHave(i: List[Any]) {
def shouldHave(j: Any) = {
assertEquals(j, i.find( _ == j))
}
}

You can use the dsl in your JUnit test like this

[/sourcecode]
@Test
def bloggerSpecification() = {

given ("a blogger with a blog") {
.....
}
}
[sourcecode]

You can imagine that you would like to execute a story multiple times with different argument values. Lets say that you would like to execute the story with multiple post titles. A little extension of the dsl made that possible. I introduced the words testcases, addCase and execute_testcases_with_specification.
See below an example

testcases {
var postTitle: String = null;

addCase { postTitle = "title 1" }
addCase { postTitle = "title 2" }

execute_testcases_with_specification {
given ("a blogger with a blog") {
val blogger = new Blogger("Mr Blog", "mrblog@blogger.com", "passwd")
val blog = new Blog("blogTitle", blogger)

when ("mr blog writes a new post") {
blog addPost (postTitle, "post Text");
}
and
when ("mr blog publishes its post") {
blog publishPost
}
then ("the post should be publised fo reading") {
blog.published exists(_.title == postTitle) shouldBe true
}
}
}

What you see is that there are two test cases, each specifying a different value for the postTitle. The story is executed for each test case where the free variables are changed according to the test case at hand.

In order to make this work I stored all the test cases in a list. Then for each test case I first evaluate the test case. This sets the free variables of the story closure. Next I evaluate the story itself.

Again the code is really simple as you can see below.

object TestCase {

var codeBlocks = List[() => Unit]()
var scenario: Any = 0;

def addCase( codeBlock: => Unit) = {
codeBlocks = codeBlock _ :: codeBlocks
}

def execute_testcases_with_specification( scenario: => Unit) = {
codeBlocks.foreach( codeBlock => {
codeBlock();
scenario;
})
}

def testcases( codeBlock: => Unit) = {
codeBlock
}
}

If you made it this far in the post… what do you think of this approach?

W3C Widgets Compatibility Matrix for Packaging and Configuration

Daniel Silva, Marcos Caceres and myself have completed Phase 1 of Widgets 1.0: Packaging and Configuration compatibility testing. We have also detailed the results as part of the conformance matrix.
We would like to publish the results as a working group note. Phase 2 will begin in about 3 weeks, in which we are hoping to start working with vendors to improve overall conformance.

We need help with Phase 2: if you know a team contact for any of the targeted products that are claiming conformance to W3C Widgets, then would appreciate your help in making them aware of the results of the testing - Widgets 1.0: Compatibility Matrix for Packaging and Configuration.

Popular Posts

Hiatus…

Para os que, por alguma razão, mantêm um registo dos meus projectos, serve este texto para dar ideia do que tenho andado a fazer, talvez sirva mais para me tentar convencer que, afinal, até tenho feito qualquer coisa com o tempo livre Smiling

Lista de projectos pendentes/em trabalho:

ContraptionsForge - Criação de ...

Uma gota a mais num copo já cheio.

Sempre me considerei uma pessoa ponderada, às vezes demasiado complacente é verdade, mas sempre achei que não há motivo algum para perdermos as estribeiras ou para nos deixarmos afectar com o que os outros fazem, dizem ou pela opinião que têm de nós. Mas recentemente, com ou sem razão, perdi ...

A infâmia de ser Português

Esta é uma sensação que tem vindo a crescer cada vez mais, será que os programadores portugueses têm algum orgulho em serem portugueses? Em falarem e defenderem a língua portuguesa? Ou a maioria de nós esconde-se no facto de que é mais simples utilizar os termos, supostamente técnicos, em inglês?

Recentemente ...

Login automático em ssh com o Putty

Não há razão para se estar sempre a escrever usernames e passwords quando se liga a servidores remotos via ssh com o PuTTY.

Eis aqui como fazer:

  1. Ter o PuTTY
  2. Ter o PuTTYgen
  3. Ter o PAgent

Todos estes programas estão acessíveis em: http://www.chiark.greenend.org.uk/~sgtatham/putty

Antes de mais é necessário gerar uma chave pública e uma chave privada:

  1. Lançar o PuTTYgen
  2. Carregar em Generate
  3. Mover o rato na zona cinzenta para introduzir algum ruído para facilitar a aleatoriedade da chave.
  4. Depois de gerada a chave, escrever um comentário que irá identificar a mesma
  5. Introduzir a Palavra-Chave e a respectiva confirmação. É esta chave que permite abrir a chave privada gerada
  6. Guardar as chaves pública e privada no disco

O conteúdo da chave pública deverá ser copiada para cada um dos servidores remotos aos quais pretendemos ligar. A localização no servidor remoto onde colocar a chave pública é em /home//.ssh/authorized_keys2. No caso do utilizador root, colocar em /root/.ssh/authorized_keys2.

Editar o ficheiro authorized_keys2, e adicionar no fim, numa nova linha, o seguinte:
ssh-rsa
O poderá ser o mesmo que o colocado no ponto 4. Auxilia visualmente a identificar a chave. Salvar o ficheiro.

A directoria .ssh deverá apenas ter permissões para o próprio utilizador (rwx).

Para ligar automaticamente via ssh, é necessário colocar o programa PAgent a correr e adicionar a chave privada. Depois disto o programa pede a Palavra-Chave da chave privada. Introduzir a Palavra-Chave indicada no ponto 5. A partir deste momento é só abrir uma nova consola PuTTY, iniciar uma ligação com um servidor remoto que tenha a chave pública criada, e temos o login automático. Sem mais configurações é ainda necessário introduzir o username, mas a password é automaticamente colocada pelo PuTTY.

Tomar em atenção que o PAgent tem de estar a correr para se usufruir desta funcionalidade.

Para completar o automatismo:

  1. Nas ligações do PuTTY, na parte do Host Name, introduzir: @IP, para o processo ser completamente automático
  2. Para carregar automaticamente as chaves no PAgent, passar na linha de comandos o caminho completo para o ficheiro da chave privada (ex: c:\pchave.ppk)

A Palavra-Chave indicada no ponto 5 tem de ser sempre colocada quando o PAgent corre pela primeira vez numa sessão Windows.

Por ser um mecanismo automático tomar em extrema atenção e não deixar o computador sem vigilância (isto é, bloquear a sessão sempre).

Bom dia Sr. Engenheiro!

Aqui vai um texto que devia ter sido apresentado há dois meses atrás, afinal, é desde essa altura que sou oficialmente Licenciado do curso de Engenharia Informática pela Escola Superior e Tecnologia e Gestão do Instituto Politécnico de Leiria! Grande título Laughing out loud

E o que é que mudou?! Hum... além de ...

Mudar de Alojamento…

Hoje procedi à tarefa de mudar de alojamento.

Todos os sistemas pessoais passaram para o meu servidor, que tenho alugado desde Março, mais coisa menos coisa, e que ia pagando em paralelo com a conta de alojamento na Trignosfera.

Não tenho queixas da Trignosfera, pelo menos nada de especial, ou nada que ...

Scrum Master in the Critical path of the sprint

More then a year ago myself and Eelco Gravendeel wrote the top 9 challenges of adopting Scrum . But those where just the top 9. Some did not make it to the top 9. This post publishes one that did not make it but I think is quite good. here it goes….

 

 

 

“If everything seems under control,
you’re just not going fast enough.”
Mario Andretti

… or the project for that matter. The point is that the Scrum Master or any other leading figure should be more concerned with organizing the team than by “pulling” work towards themselves or otherwise they might be afraid it doesn’t get done in time!

The situation
You’ve got it all setup: a multidisciplinary team, a Product Owner and a dedicated Scrum Master. Deadlines are tight but seem to be do-able, scope appears to be negotiable, and the rest of the organization is well informed and prepared about what is happening. We’re good to go!
However; during the project deadlines are not met, quality doesn’t appear to be as good as expected and overall commitment of team members is not what you would like to see. And although the Scrum Master is pitching in and doing valuable project tasks to help out, things just don’t seem to improve very much per sprint passed.

The problem
The catch here is that the Scrum master is doing “valuable” project tasks. He or she is trying to do work which other team members might depend on to do their tasks. It can even go so far that the Scrum Master gets the feeling that they can’t get the Sprint done without him/her pitching in and picking up those all important / difficult tasks.
What happens next can be a combination of problems, some of these mentioned below:

 Team will not self-organize to meet deadlines
 Team does not feel committed to quality
 Scrum Master does not have (take) enough time to resolve impediments
 Scrum Master does not have (take) enough time to coach Team Members
 Scrum Master does not have (take) enough time to coach Product Owner
 Scrum Master pulls all responsibility towards him-/herself

As a result of such problems the Scrum Master then often feels the Team is letting him/her down and falls into a command & control style of managing (not leading!) the team. That way you miss out on much of the benefits self-organizing teams in general and Scrum specifically can provide.

How to fix this
It is a bit too simplistic to say the Scrum Master can never pick up any development or testing tasks. As always it depends. Here’s what worked for us:

When the project consists of one Team, one Product Owner and One Scrum Master you are best of if the Scrum Master doesn’t do any development, testing or analysis at all. Almost all time will have to be spent facilitating the team by removing impediments, coaching, etc. Some time will have to be spent on reporting about the project to management or other stakeholders. The rest of the time will go into helping out the Product Owner in managing the Product Backlog, managing Stakeholders, etc. Any time spent on doing “in Sprint” work such as development will not be spent on tasks such as mentioned above.

When the project consists of multiple teams or just has a Project Manager assigned to it, all becomes a bit different. The Scrum Master is of course still very much responsible for facilitating the team and removing impediments, but can leave the more “team outward facing” things to the Project Manager. Tasks such as Stakeholder Management, Risk Management, Product Owner coaching or removing impediments on an organizational level can be left to the Project Manager. So, if the Scrum Master has any time left he might be able to help out the team with some development tasks, or testing or whatever. But: The Scrum Master tasks always come first! The team should prevent the Scrum Master from picking up any tasks which might be in the critical path of the sprint, you never know whether some pressing impediment comes along and will require the Scrum Masters full attention!

Procurar Representação Unicode

O site seguinte fornece a tradução (para vários formatos e encodings) de caracteres.

http://www.fileformat.info/info/unicode/char/search.htm

Exemplo para o ç:

UTF-8 (binary) 11000011:10100111

© 2008 - PT.JUG - Todos os direitos reservados
seara