Archive

Archive for June, 2015

First script with Velocity (VM)

Velocity is a Java-based template engine. It permits web page designers to reference methods defined in Java code. Basically, you can create files (HTML, XML, etc…) writing scripts and generate them following a template.

 

– Create Maven Project.

– Add dependency in your pom file – Change the version of the lib:

<dependency>

  <groupId>org.apache.velocity</groupId>

  <artifactId>velocity</artifactId>

  <version>1.6.4</version>

</dependency>

 


– Create a Vm template, like this one. Save as .vm (I created outside the package test). So, place your template in Project > src > customer.vm and not with the code which the structure is: Project > src > package.test:

Hello $word! This is your first Velocity script !

 

– Create a Java Class called CreateScript:
import java.io.StringWriter;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;

public class createXml {
   public static void main(String[] args) throws Exception {
   VelocityEngine ve = new VelocityEngine();
   ve.init();

   try {
    Template t = ve.getTemplate("src/helloworld.vm");

    VelocityContext context = new VelocityContext();
    context.put("word", "World");
    StringWriter writer = new StringWriter();
    t.merge(context, writer);
    System.out.println(writer.toString());
    } catch (ResourceNotFoundException rnfe) {
      System.out.println("Couldn't find the template");
    } catch (ParseErrorException pee) {
      System.out.println("syntax error: problem parsing the template");
    } catch (MethodInvocationException mie) {
      System.out.println("something invoked in the template");
      System.out.println("threw an exception");
    } catch (Exception e) {
    }
  }
}

– Vm file is the template, you will create the template and what the variables that will have the value that you want.

– Inside Java Class:

You need initialize the Velocity API – Write the path of the vm template – Initialize the context and write all the variables and the values (name – variable, word – value) – Initialize the Writer which will render the template – Merge the context and the values creating the template – Show the result

– To run the project, first I had to compil with maven test and after this I just choose Run As – Java Application.

So, this is the first script, I will write more about, but between this you can have a look on the links below. See you guys 🙂

 

Sources:

http://velocity.apache.org/engine/devel/developer-guide.html

https://velocity.apache.org/engine/releases/velocity-1.5/webapps.html

http://www.javaranch.com/journal/2004/03/Velocity-AnIntroduction.html

http://www.javaworld.com/article/2075966/core-java/start-up-the-velocity-template-engine.html

Advertisements

Configure Thucydides (Report for JBehave) – BDD

June 17, 2015 6 comments

What is ?

Basically, this report of your scenarios/features:

Screen Shot 2015-06-17 at 12.34.50

 

Project Structure

+ src
   + main
      + java
         + com.mycompany.pages
            - HomePage.java   

   + test
      + java
         + com.mycompany.pages
            + requirements
               - Application.java
            + steps
               - EndUserSteps.java
            - SearchByKeywordStoryTest.java 

      + stories
         + com.wakaleo.webtests.wikipedia
            - SearchingForCats.story

 

Starting

If you have maven installed, go to the terminal or IDE and:

– Create a new project:

mvn archetype:generate -Dfilter=thucydides

– Open your settings.xml and write:

<?xml version="1.0" encoding="UTF-8"?>
<settings>
   <pluginGroups>
       <pluginGroup>net.thucydides.maven.plugins</pluginGroup>
  </pluginGroups>
</settings>

– In the pom.xml file, update the default JUnit dependency to at least 4.11

– Add a dependency to hamcrest-all and thucydides-junit. Thucydides uses SLF4J for its logging, so add an SLF4J implementation (e.g. slf4j-simple) as well.

– If you are not using Maven 3, make sure you configure the Maven compiler plugin to use Java 5.

– Finally, add the thucydides-maven-plugin, which provides the Thucydides reporting services. The resulting pom.xml file should look something like this:


  <groupId>com.wakaleo.webtests.wikipedia</groupId>
  <artifactId>wikipediawebtests</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>wikipediawebtests</name>
  <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <thucydides.version>0.9.228</thucydides.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>net.thucydides</groupId>
            <artifactId>thucydides-junit</artifactId>
            <version>${thucydides.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.1</version>
            <type>pom</type>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>net.thucydides.maven.plugins</groupId>
                <artifactId>maven-thucydides-plugin</artifactId>
                <version>${thucydides.version}</version>
            </plugin>
        </plugins>
    </build>
</project>                      

 

– Run this command to be sure that everything it is running correctly: mvn package

– Create a new class contains the list of “features” that make up the application, and stories related to each feature. These stories are not the tests themselves – rather they are used to model the application requirements.

– Writing your first test:

public class Application {
	    @Feature
	    public class Search {
	        public class SearchByKeyword {}
	        public class SearchByAnimalRelatedKeyword {}
	        public class SearchByFoodRelatedKeyword {}
	        public class SearchByMultipleKeywords {}
	        public class SearchForQuote{}
	    }

	    @Feature
	    public class Backend {
	        public class ProcessSales {}
	        public class ProcessSubscriptions {}
	    }

	    @Feature
	    public class Contribute {
	        public class AddNewArticle {}
	        public class EditExistingArticle {}
	    }
	}

 

– Create a new test class in a package of your choice calledSearchByKeywordStoryTest.java

@Story(SearchBySingleKeyword.class)
@RunWith(ThucydidesRunner.class)
public class SearchByKeywordStoryTest {

    @Managed(uniqueSession = true)
    public WebDriver webdriver;

    @ManagedPages(defaultUrl = "http://www.wikipedia.com")
    public Pages pages;

    @Steps
    public EndUserSteps endUser;

    @Test
    public void should_display_article_about_cats() {
        endUser.is_on_the_wikipedia_home_page();
        endUser.searches_by_keyword("cats");
        endUser.should_see_article_with_title("Cat - Wikipedia, the free
 encyclopedia");

 

PS: @Managed and  @ManagedPages are required to take care of our page objects.

 

– Create a step library called EndUserSteps:

public class EndUserSteps extends ScenarioSteps {

    public EndUserSteps(Pages pages) {
	super(pages);
    }

    @Step
    public void searches_by_keyword(String keyword) {
        enters(keyword);
        performs_search();
    }

    @Step
    public void enters(String keyword) {
    }

    @Step
    public void performs_search() {
    }

    @Step
    public void should_see_article_with_title(String title) {
    }

    @Step
    public void is_on_the_wikipedia_home_page() {
    }
}

 

– You will need create your own classes inside of each Step.

– Run the command to generate your report: mvn verify thucydides:aggregate

– Your report will be in target/thucydides directory, open the home.html

 

If you want to see a complete model, go to this link.

If you want to learn more about maven commands, go to this link.

If you want to see the post of John Smart with his complete example, go to this link.

 

Thank you guys  🙂

 

Sources:

https://github.com/thucydides-webtests/thucydides/wiki/Getting-Started

https://weblogs.java.net/blog/johnsmart/archive/2011/10/31/getting-started-thucydides-%E2%80%93-using-thucydides-maven-archetypes

http://stackoverflow.com/questions/23297718/thucydides-install-from-scratch-archetype-all-tests-are-skipped

http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html

https://github.com/thucydides-webtests/thucydides-demos

Functional Programming

What is functional programming?  Everything is a mathematical function. Functional programming languages can have objects, but generally those objects are immutable — either arguments or return values to functions. There are no for/next loops, as those imply state changes. Instead, that type of looping is performed with recursion and by passing functions as arguments.

Functional programming requires that functions are first-class, which means that they are treated like any other values and can be passed as arguments to other functions or be returned as a result of a function. Being first-class also means that it is possible to define and manipulate functions from within other functions. Special attention needs to be given to functions that reference local variables from their scope. If such a function escapes their block after being returned from it, the local variables must be retained in memory, as they might be needed later when the function is called.

The following table shows which languages support functional programming (by supporting first-class functions) and for which the functional style is the dominant one.

Language Closures Functional
C No No
Pascal No No
C++ Yes No
Java Yes No
Modula-3 Yes No
Python Yes No
Ruby Yes No
Javascript Yes Yes
Ocaml Yes Yes
Erlang Yes Yes
Haskell Yes Yes

Benefits

Functional programming is known to provide better support for structured programming than imperative programming. It is easy, for instance, to abstract out a recurring piece of code by creating a higher-order function, which will make the resulting code more declarative and comprehensible.

Functional programs are often shorter and easier to understand than their imperative counterparts. Since various studies have shown that the average programmer’s productivity in terms of lines of code is more or less the same for any programming language, this translates also to higher productivity.

Look the difference:

Class using C and object-oriented:

public static class SumOfSquaresHelper
{
   public static int Square(int i)
   {
      return i * i;
   }

   public static int SumOfSquares(int n)
   {
      int sum = 0;
      for (int i = 1; i <= n; i++)
      {
         sum += Square(i);
      }
      return sum;
   }
}

Does the same thing using Functional programming:

let square x = x * x
let sumOfSquares n = [1..n] |> List.map square |> List.sum

Object-oriented x Functional languages

When you anticipate a different kind of software evolution:

  • Object-oriented languages are good when you have a fixed set of operations on things, and as your code evolves, you primarily add new things. This can be accomplished by adding new classes which implement existing methods, and the existing classes are left alone.
  • Functional languages are good when you have a fixed set of things, and as your code evolves, you primarily add new operations on existing things. This can be accomplished by adding new functions which compute with existing data types, and the existing functions are left alone.

When evolution goes the wrong way, you have problems:

  • Adding a new operation to an object-oriented program may require editing many class definitions to add a new method.
  • Adding a new kind of thing to a functional program may require editing many function definitions to add a new case.

I have been reading about what is functional programming on the last weeks (Just because I was curious) and I found a lot of articles, but I summarized here a little piece of each place which helped me to better understand what really is.

If you are interested about functional programming you can click on this link. I found it very interesting and easy to understand.

 See you next week !

Sourcehttp://www.javacodegeeks.com/2014/03/functional-programming-with-java-8-lambda-expressions-monads.html

http://www.functionaljava.org/

https://pragprog.com/magazines/2013-01/functional-programming-basics

http://programmers.stackexchange.com/questions/117276/example-of-where-functional-programming-is-superior-to-imperative-or-object-orie

http://c2.com/cgi/wiki?FunctionalProgramming

http://stackoverflow.com/questions/2078978/functional-programming-vs-object-oriented-programming

http://www.infoworld.com/article/2615766/application-development/functional-programming–a-step-backward.html?page=2

http://fsharpforfunandprofit.com/why-use-fsharp/

http://www.tryfsharp.org/Learn

%d bloggers like this: