text:
package com.twilio.thinq;

public class TwilioWrapperLibraryBuilder {
    private String twilio_account_sid;
    private String twilio_account_token;
    private String thinQ_id;
    private String thinQ_token;

    public TwilioWrapperLibraryBuilder() { }

    /**
     * Wrap the library and return the library object.
     * @return
     */

    public TwilioWrapperLibrary buildLibrary()
    {
        return new TwilioWrapperLibrary( this.twilio_account_sid, this.twilio_account_token, this.thinQ_id, this.thinQ_token);
    }

    /**
     * Set customer phone number
     * @param _id   thinQid received when signed up at thinQ website
     * @param _token   thinQtoken received when signed up at thinQ website
     * @return
     */

    public TwilioWrapperLibraryBuilder thinQ(String _id, String _token)
    {
        this.thinQ_id = _id;
        this.thinQ_token = _token;
        return this;
    }

    /**
     * Set twilio acount details
     * @param _sid  twilio account sid
     * @param _token    twilio account token
     * @return
     */

    public TwilioWrapperLibraryBuilder twilio(String _sid, String _token)
    {
        this.twilio_account_sid = _sid;
        this.twilio_account_token = _token;
        return this;
    }
}


text:
<template name="exception">

An error has occured. Please try again later.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Praesentium, recusandae. Impedit aliquam perferendis sed velit quia, ea laborum porro ratione accusamus consequuntur, doloribus neque debitis. Obcaecati magnam architecto, omnis harum.

</template>

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2016, EMC, Inc.

'use strict';

var di = require('di');

module.exports = racadmToolJobFactory;
di.annotate(racadmToolJobFactory, new di.Provide('Job.Dell.RacadmTool'));
di.annotate(racadmToolJobFactory, new di.Inject(
    'Job.Base',
    'JobUtils.RacadmTool',
    'Logger',
    'Util',
    'Assert',
    'Promise',
    '_',
    'Services.Encryption',
    'Services.Lookup',
    'Constants',
    'Services.Waterline'
));

function racadmToolJobFactory(
    BaseJob,
    racadmTool,
    Logger,
    util,
    assert,
    Promise,
    _,
    encryption,
    lookup,
    Constants,
    waterline
) {
    var logger = Logger.initialize(racadmToolJobFactory);
    /**
     *
     * @param {Object} options
     * @param {Object} context
     * @param {String} taskId
     * @constructor
     */
    function RacadmToolJob(options, context, taskId) {
        RacadmToolJob.super_.call(this, logger, options, context, taskId);

        this.nodeId = this.context.target;
        this.action = options.action;
        this.userConfig = {user: options.serverUsername, password: options.serverPassword,
            filePath: options.serverFilePath};
        if (typeof options.forceReboot !== "undefined") {
            this.userConfig.forceReboot = options.forceReboot;
        }
        if (typeof options.components !== "undefined") {
            this.userConfig = options.components;
        }
    }
    util.inherits(RacadmToolJob, BaseJob);

    /**
     * @memberOf RacadmToolJob
     */
    RacadmToolJob.prototype._run = function() {
        var self = this;
            return waterline.obms.findByNode(self.nodeId, 'ipmi-obm-service', true)
            .then(function (obm) {
                if (!obm) {
                   return waterline.obms.findByNode(self.nodeId, 'dell-wsman-obm-service', true);
                }
                return obm;
            })
            .then(function (obmSettings) {
                return obmSettings.config;
            })
            .then(self.lookupHost)
            .then(function(obmSetting) {
                assert.func(racadmTool[self.action]);
                return racadmTool[self.action](obmSetting.host, obmSetting.user,
                    obmSetting.password,
                    self.userConfig);
            })
            .then(function(results){
                if (results.status){
                    logger.debug(results.status);
                }else{
                logger.debug(results);
                }
                self._done();
            })
            .catch(function(err) {
                self._done(err);
            });

    };

    RacadmToolJob.prototype.lookupHost = function lookupHost (options) {
        if (options.host && Constants.Regex.MacAddress.test(options.host)) {
            return lookup.macAddressToIp(options.host).then(function (ipAddress) {
                options.host = ipAddress;
                return options;
            });
        }

        return options;
    };
    return RacadmToolJob;
}


text:
title: Documentation
layout: page
group: navigation
---
{% include JB/setup %}

- [Getting Started](#getting-started)
- [Core Features](#core-features)
    - [Naming Tests](#naming-tests)
    - [Assertions](#assertions)
    - [Isolated Execution Model](#isolated-execution-model)
    - [Non-Isolated Execution Model](#non-isolated-execution-model)
    - ["Before" and "After" Blocks](#before-and-after-blocks)
- [Indirect Features](#indirect-features)
    - [Parameterized Tests](#parameterized-tests)
    - [Executing Tests Only in Some Environments](#executing-tests-only-in-some-environments)
    - ["Pending Until Fixed"](#pending-until-fixed)

Getting Started
-----------

### 1. Dependencies

Add to your project a dependency to Specsy's programming language specific API. Choose one or more of the following:

<dependency>
    <groupId>org.specsy</groupId>
    <artifactId>specsy-scala_2.11</artifactId>
    <version>2.3.3</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.specsy</groupId>
    <artifactId>specsy-groovy</artifactId>
    <version>2.3.3</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.specsy</groupId>
    <artifactId>specsy-java</artifactId>
    <version>2.3.3</version>
    <scope>test</scope>
</dependency>

If you are running tests with the [Jumi test runner](http://jumi.fi/), then nothing more is needed.

If you are running tests with the [JUnit 5 test runner](http://junit.org/junit5/), then you will also need to add the following dependency:

<dependency>
    <groupId>org.specsy</groupId>
    <artifactId>specsy-junit</artifactId>
    <version>2.3.3</version>
    <scope>test</scope>
</dependency>

### 2. Syntax

Create a test class by extending Specsy's programming language specific base class:

import org.specsy.scala.ScalaSpecsy

class HelloWorldSpec extends ScalaSpecsy {

  // top-level spec; add your test code here and/or the child specs

  "name of the spec" >> {
    // first child spec
  }

  "name of the spec" >> {
    // second child spec

    "name of the spec" >> {
      // a nested child spec
    }
  }
}

import org.specsy.groovy.GroovySpecsy

class HelloWorldSpec extends GroovySpecsy {
    @Override
    void run() {

        // top-level spec; add your test code here and/or the child specs

        spec "name of the spec", {
            // first child spec
        }

        spec "name of the spec", {
            // second child spec

            spec "name of the spec", {
                // a nested child spec
            }
        }
    }
}

import org.specsy.java.JavaSpecsy;

public class HelloWorldSpec extends JavaSpecsy {
    @Override
    public void run() throws Throwable {

        // top-level spec; add your test code here and/or the child specs

        spec("name of the spec", () -> {
            // first child spec
        });

        spec("name of the spec", () -> {
            // second child spec

            spec("name of the spec", () -> {
                // a nested child spec
            });
        });
    }
}

P.S. It's easy to add support for more JVM-based languages (create just one [facade class](https://github.com/luontola/specsy/blob/master/specsy-groovy/src/main/java/org/specsy/groovy) and [syntax example](https://github.com/luontola/specsy/tree/master/specsy-groovy/src/test/java/org/specsy/groovy)), so create a [feature or pull request](https://github.com/luontola/specsy/issues) if you would like your favorite language supported.

### 3. Mental Model

You can add test code to any of the blocks between curly braces - semantically there is no difference between the top-level spec and all the nested child specs. There can be as many or few nested specs as you wish (including zero). A child spec will see the side-effects of its parent specs, but it cannot see any side-effects from its sibling specs (see [Isolated Execution Model](#isolated-execution-model)). Test runners may run each leaf child spec in its own thread.

Read the rest of this documentation to learn Specsy's features.

Core Features
-------------

### Naming Tests

It is recommended to name the tests using full sentences which describe features. [FibonacciSpec] is an example of how to use descriptive [specification-style test names](http://blog.orfjackal.net/2010/02/three-styles-of-naming-tests.html):

class FibonacciSpec extends ScalaSpecsy {
  val sequenceLength = 10
  val fib = new Fibonacci().sequence(sequenceLength)
  assertThat(fib.length, is(sequenceLength))

  "The first two Fibonacci numbers are 0 and 1" >> {
    assertThat(fib(0), is(0))
    assertThat(fib(1), is(1))
  }
  "Each remaining number is the sum of the previous two" >> {
    for (i <- 2 until fib.length) {
      assertThat(fib(i), is(fib(i - 1) + fib(i - 2)))
    }
  }
}

class FibonacciSpec extends GroovySpecsy {
    @Override
    void run() {
        int sequenceLength = 10
        int[] fib = new Fibonacci().sequence(sequenceLength)
        assertThat(fib.length, is(sequenceLength))

        spec "The first two Fibonacci numbers are 0 and 1", {
            assertThat(fib[0], is(0))
            assertThat(fib[1], is(1))
        }

        spec "Each remaining number is the sum of the previous two", {
            for (int i = 2; i < fib.length; i++) {
                assertThat(fib[i], is(fib[i - 1] + fib[i - 2]))
            }
        }
    }
}

public class FibonacciSpec extends JavaSpecsy {
    @Override
    public void run() {
        int sequenceLength = 10;
        int[] fib = new Fibonacci().sequence(sequenceLength);
        assertThat(fib.length, is(sequenceLength));

        spec("The first two Fibonacci numbers are 0 and 1", () -> {
            assertThat(fib[0], is(0));
            assertThat(fib[1], is(1));
        });

        spec("Each remaining number is the sum of the previous two", () -> {
            for (int i = 2; i < fib.length; i++) {
                assertThat(fib[i], is(fib[i - 1] + fib[i - 2]));
            }
        });
    }
}

You can take advantage of the ability to nest tests when writing the test names, for example as in [StackSpec].

### Assertions

Specsy does not have its own assertion syntax, because you can easily use any assertion libraries.

To use the assertions from [JUnit 4](http://www.junit.org/), add the following import to your test file:

import org.junit.Assert._

import static org.junit.Assert.*

import static org.junit.Assert.*;

To use the assertions from [Hamcrest](http://code.google.com/p/hamcrest/), add the following imports to your test file:

import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers._

import static org.hamcrest.MatcherAssert.assertThat
import static org.hamcrest.Matchers.*

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

To use the assertions from [specs](http://code.google.com/p/specs/), mix in one of the traits mentioned in [specs' matchers guide](http://code.google.com/p/specs/wiki/MatchersGuide#Use_specs_matchers_alone). For example:

class SomeSpec extends ScalaSpecsy with SpecsMatchers {
}

To use the assertions from [specs2](http://etorreborre.github.com/specs2/), mix in one of the exception throwing traits mentioned in [specs2's mathers guide](http://etorreborre.github.com/specs2/guide/org.specs2.guide.Matchers.html#Outside+specs2).

To use the assertions from [ScalaTest](http://www.scalatest.org/), mix in the [org.scalatest.matchers.ShouldMatchers](http://doc.scalatest.org/1.8/index.html#org.scalatest.matchers.ShouldMatchers) trait or one of the other matcher traits:

class SomeSpec extends ScalaSpecsy with ShouldMatchers {
}

Any other assertion libraries are also okay. All that is needed is that they throw an exception when the assertion fails. Refer to the documentation of other testing frameworks for instructions on how to use their assertions in another framework.

### Isolated Execution Model

[StackSpec] illustrates the isolated execution model. As you notice, the stack is a mutable data structure and it is being modified in nearly every child spec. But each child spec can trust that it sees only the modifications made in its parent specs, so there are no weird order-dependent test failures - everything just works as expected. It's kind of like *lexical scoping* applied to side-effects. Specsy accomplishes this by creating multiple fresh instances of the test class and selectively executing the nested specs.

class StackSpec extends ScalaSpecsy {
  val stack = new scala.collection.mutable.Stack[String]

  "An empty stack" >> {

    "is empty" >> {
      assertTrue(stack.isEmpty)
    }
    "After a push, the stack is no longer empty" >> {
      stack.push("a push")
      assertFalse(stack.isEmpty)
    }
  }

  "When objects have been pushed onto a stack" >> {
    stack.push("pushed first")
    stack.push("pushed last")

    "the object pushed last is popped first" >> {
      val poppedFirst = stack.pop()
      assertThat(poppedFirst, is("pushed last"))
    }
    "the object pushed first is popped last" >> {
      stack.pop()
      val poppedLast = stack.pop()
      assertThat(poppedLast, is("pushed first"))
    }
    "After popping all objects, the stack is empty" >> {
      stack.pop()
      stack.pop()
      assertTrue(stack.isEmpty)
    }
  }
}

class StackSpec extends GroovySpecsy {
    def stack = new ArrayDeque<String>()

    @Override
    void run() {

        spec "An empty stack", {

            spec "is empty", {
                assertTrue(stack.isEmpty())
            }
            spec "After a push, the stack is no longer empty", {
                stack.push("a push")
                assertFalse(stack.isEmpty())
            }
        }

        spec "When objects have been pushed onto a stack", {
            stack.push("pushed first")
            stack.push("pushed last")

            spec "the object pushed last is popped first", {
                String poppedFirst = stack.pop()
                assertThat(poppedFirst, is("pushed last"))
            }
            spec "the object pushed first is popped last", {
                stack.pop()
                String poppedLast = stack.pop()
                assertThat(poppedLast, is("pushed first"))
            }
            spec "After popping all objects, the stack is empty", {
                stack.pop()
                stack.pop()
                assertTrue(stack.isEmpty())
            }
        }
    }
}

public class StackSpec extends JavaSpecsy {
    private Deque<String> stack = new ArrayDeque<>();

    @Override
    public void run() {

        spec("An empty stack", () -> {

            spec("is empty", () -> {
                assertTrue(stack.isEmpty());
            });
            spec("After a push, the stack is no longer empty", () -> {
                stack.push("a push");
                assertFalse(stack.isEmpty());
            });
        });

        spec("When objects have been pushed onto a stack", () -> {
            stack.push("pushed first");
            stack.push("pushed last");

            spec("the object pushed last is popped first", () -> {
                String poppedFirst = stack.pop();
                assertThat(poppedFirst, is("pushed last"));
            });
            spec("the object pushed first is popped last", () -> {
                stack.pop();
                String poppedLast = stack.pop();
                assertThat(poppedLast, is("pushed first"));
            });
            spec("After popping all objects, the stack is empty", () -> {
                stack.pop();
                stack.pop();
                assertTrue(stack.isEmpty());
            });
        });
    }
}

A rule of thumb is that out of all sibling specs (i.e. child specs with the same parent) always *exactly one sibling spec is executed during a test run*, and each test run has its own instance of the test class. So when the closure of a spec is executed and Specsy encounters a child spec declaration, it will selectively execute one of its child specs (right where it is declared) and skip the others. Then a fresh instance of the test class is created and a different code path is executed, until all child specs have been executed.

### Non-Isolated Execution Model

In some cases it may be desirable to avoid the isolation of side-effects; perhaps it would make the tests harder to organize (e.g. writing tests for a multi-step process) or it would affect performance too much (e.g. side-effect free [parameterized tests](#parameterized-tests)). For those situations you may call `shareSideEffects()` which will cause all child specs of the current spec to see each other's side-effects. [ShareSideEffectsExampleSpec] illustrates this:

class ShareSideEffectsExampleSpec extends ScalaSpecsy {
  var counter = 0

  // Without the call to `shareSideEffects()` the value of `counter` would be `1`
  // in the asserts of each of the following child specs.
  shareSideEffects()
  "One" >> {
    counter += 1
    assertThat(counter, is(1))
  }
  "Two" >> {
    counter += 1
    assertThat(counter, is(2))
  }
  "Three" >> {
    counter += 1
    assertThat(counter, is(3))
  }
}

class ShareSideEffectsExampleSpec extends GroovySpecsy {
    def counter = 0

    @Override
    void run() {

        // Without the call to `shareSideEffects()` the value of `counter` would be `1`
        // in the asserts of each of the following child specs.
        shareSideEffects()
        spec "One", {
            counter += 1
            assertThat(counter, is(1))
        }
        spec "Two", {
            counter += 1
            assertThat(counter, is(2))
        }
        spec "Three", {
            counter += 1
            assertThat(counter, is(3))
        }
    }
}

public class ShareSideEffectsExampleSpec extends JavaSpecsy {
    private int counter = 0;

    @Override
    public void run() {

        // Without the call to `shareSideEffects()` the value of `counter` would be `1`
        // in the asserts of each of the following child specs.
        shareSideEffects();
        spec("One", () -> {
            counter += 1;
            assertThat(counter, is(1));
        });
        spec("Two", () -> {
            counter += 1;
            assertThat(counter, is(2));
        });
        spec("Three", () -> {
            counter += 1;
            assertThat(counter, is(3));
        });
    }
}

Note that the effects of `shareSideEffects()` (pun intended) are restricted inside the subtree of the current spec, after the call to `shareSideEffects()`. The subtree can start from the root spec (if `shareSideEffects()` is called at the top level before all nested specs), or it can start from *any* nested spec. So you can mix the isolated and non-isolated modes inside one test class, so that only one subtree of specs is affected by it (or any number of subtrees, for that matter).

[See here](https://github.com/luontola/dimdwarf/blob/e0f109dcd2d81f35b411fd1a2ad75be7ef60ae75/dimdwarf-core/src/test/scala/net/orfjackal/dimdwarf/domain/SimpleTimestampSpec.scala#L64) for a real-life example of using `shareSideEffects()` as a performance optimization for parameterized tests. Actually this is the first use case which drove me to finally implement `shareSideEffects()` (and it took [just one hour to implement](https://github.com/luontola/specsy/commit/c31f8508969098b05f7bedac0a9fe9a1b6fe833a)). Before that I had used Specsy for 9 months without any need for it, even though it had been in my plans already since much earlier in [GoSpec](https://github.com/luontola/gospec). So it should very rarely, if ever, be necessary to use the non-isolated execution model.

### "Before" and "After" Blocks

In Specsy, every parent spec acts similar to the "before" blocks in other testing frameworks. And as for "after" blocks, Specsy has a construct called *defer blocks* (inspired by [Go's defer statement](http://golang.org/doc/effective_go.html#defer)). Each spec can declare as many or few defer blocks as it wishes, and they will be executed in LIFO order when the spec exits.

[DeferBlocksExampleSpec] shows how the defer blocks can be used:

class DeferBlocksExampleSpec extends ScalaSpecsy {
  val dir = Paths.get("temp-directory-" + UUID.randomUUID())
  Files.createDirectory(dir)
  defer {
    Files.delete(dir)
  }

  val file1 = dir.resolve("file 1.txt")
  Files.createFile(file1)
  defer {
    Files.delete(file1)
  }

  "..." >> {
    // do something with the files
  }

  "..." >> {
    // child specs can also use defer blocks
    val file2 = dir.resolve("file 2.txt")
    Files.createFile(file2)
    defer {
      Files.delete(file2)
    }

    // 'file2' will be deleted when this child spec exits
  }

  // will delete first 'file1' and second 'dir'
  // (or if creating 'file1' failed, then will delete only 'dir')
}

class DeferBlocksExampleSpec extends GroovySpecsy {
    @Override
    void run() {
        Path dir = Paths.get("temp-directory-" + UUID.randomUUID())
        Files.createDirectory(dir)
        defer {
            Files.delete(dir)
        }

        Path file1 = dir.resolve("file 1.txt")
        Files.createFile(file1)
        defer {
            Files.delete(file1)
        }

        spec "...", {
            // do something with the files
        }

        spec "...", {
            // child specs can also use defer blocks
            Path file2 = dir.resolve("file 2.txt")
            Files.createFile(file2)
            defer {
                Files.delete(file2)
            }

            // 'file2' will be deleted when this child spec exits
        }
        // will delete first 'file1' and second 'dir'
        // (or if creating 'file1' failed, then will delete only 'dir')
    }
}

public class DeferBlocksExampleSpec extends JavaSpecsy {
    @Override
    public void run() throws IOException {
        Path dir = Paths.get("temp-directory-" + UUID.randomUUID());
        Files.createDirectory(dir);
        defer(() -> {
            Files.delete(dir);
        });

        Path file1 = dir.resolve("file 1.txt");
        Files.createFile(file1);
        defer(() -> {
            Files.delete(file1);
        });

        spec("...", () -> {
            // do something with the files
        });

        spec("...", () -> {
            // child specs can also use defer blocks
            Path file2 = dir.resolve("file 2.txt");
            Files.createFile(file2);
            defer(() -> {
                Files.delete(file2);
            });

            // 'file2' will be deleted when this child spec exits
        });
        // will delete first 'file1' and second 'dir'
        // (or if creating 'file1' failed, then will delete only 'dir')
    }
}

The code duplication in the above spec could be removed by extracting a method out of it, although it requires knowledge of Scala's more advanced features. [DeferBlocksExample2Spec] does the same thing as above, but with less code:

class DeferBlocksExample2Spec extends ScalaSpecsy {
  val dir = createWithCleanup(Paths.get("temp-directory-" + UUID.randomUUID()), Files.createDirectory(_))
  val file1 = createWithCleanup(dir.resolve("file 1.txt"), Files.createFile(_))

  "..." >> {
  }

  "..." >> {
    val file2 = createWithCleanup(dir.resolve("file 2.txt"), Files.createFile(_))
  }

  def createWithCleanup(path: Path, create: Path => Any): Path = {
    println("Creating " + path)
    create(path)
    defer {
      println("Deleting " + path)
      Files.delete(path)
    }
    path
  }
}

class DeferBlocksExample2Spec extends GroovySpecsy {
    @Override
    void run() {
        Path dir = createWithCleanup(Paths.get("temp-directory-" + UUID.randomUUID()), Files.&createDirectory)
        Path file1 = createWithCleanup(dir.resolve("file 1.txt"), Files.&createFile)

        spec "...", {
        }

        spec "...", {
            Path file2 = createWithCleanup(dir.resolve("file 2.txt"), Files.&createFile)
        }
    }

    private Path createWithCleanup(Path path, Closure create) {
        println "Creating $path"
        create(path)
        defer {
            println "Deleting $path"
            Files.delete(path)
        }
        return path
    }
}

public class DeferBlocksExample2Spec extends JavaSpecsy {
    @Override
    public void run() throws IOException {
        Path dir = createWithCleanup(Paths.get("temp-directory-" + UUID.randomUUID()), Files::createDirectory);
        Path file1 = createWithCleanup(dir.resolve("file 1.txt"), Files::createFile);

        spec("...", () -> {
        });

        spec("...", () -> {
            Path file2 = createWithCleanup(dir.resolve("file 2.txt"), Files::createFile);
        });
    }

    private Path createWithCleanup(Path path, FileCreator creator) throws IOException {
        System.out.println("Creating " + path);
        creator.create(path);
        defer(() -> {
            System.out.println("Deleting " + path);
            Files.delete(path);
        });
        return path;
    }

    private interface FileCreator {
        void create(Path path) throws IOException;
    }
}

Indirect Features
-----------------

### Parameterized Tests

Because Specsy's spec declarations are implemented as method calls which take a closure as a parameter, it's simple to use the framework for parameterized tests. [ParameterizedExampleSpec] shows how to do it:

class ParameterizedExampleSpec extends ScalaSpecsy {
  val parameters = List(
    (0, 0),
    (1, 1),
    (2, 4),
    (3, 9),
    (4, 16),
    (5, 25),
    (6, 36),
    (7, 49),
    (8, 64),
    (9, 81))

  for ((n, expectedSquare) <- parameters) {
    s"Square of $n is $expectedSquare" >> {
      assertThat(n * n, is(expectedSquare))
    }
  }
}

public class ParameterizedExampleSpec extends GroovySpecsy {
    @Override
    public void run() {
        def parameters = [
                [0, 0],
                [1, 1],
                [2, 4],
                [3, 9],
                [4, 16],
                [5, 25],
                [6, 36],
                [7, 49],
                [8, 64],
                [9, 81]
        ]
        parameters.each { n, expectedSquare ->
            spec "Square of $n is $expectedSquare", {
                assertThat(n * n, is(expectedSquare))
            }
        }
    }
}

public class ParameterizedExampleSpec extends JavaSpecsy {
    @Override
    public void run() {
        int[][] parameters = new int[][]{
                {0, 0},
                {1, 1},
                {2, 4},
                {3, 9},
                {4, 16},
                {5, 25},
                {6, 36},
                {7, 49},
                {8, 64},
                {9, 81}
        };
        for (int[] pair : parameters) {
            int n = pair[0];
            int expectedSquare = pair[1];

            spec("Square of " + n + " is " + expectedSquare, () -> {
                assertThat(n * n, is(expectedSquare));
            });
        }
    }
}

Note that the code which declares the specs must be deterministic. Otherwise the test isolation mechanism may not run all specs exactly once. Also here it might be desirable to use `shareSideEffects()` as a performance optimization (see [Non-Isolated Execution Model](#non-isolated-execution-model)), assuming that the generated specs do not have side-effects.

### Executing Tests Only in Some Environments

Since in Specsy every spec is a closure, it is very easy to customize how individual specs are run. For example, let's say that some of the tests require Java 8 to be able to run. You can write a helper method such as the `worksOnlyOnJava8` in [EnvironmentFilterExampleSpec], as shown below, and mark/surround the closures of affected specs with it.

class EnvironmentFilterExampleSpec extends ScalaSpecsy {

  "This test is run every time" >> {
    // Test code...
  }

  "This test is run only under Java 8 and greater" >> worksOnlyOnJava8 {
    // Test code... For example something which uses the new Date and Time API (JSR-310)
    // which was added in Java 8
  }

  // This can also be used at the top level, if many/all tests work only on Java 8.
  // Just surround all tests and variable/field declarations into a closure.
  worksOnlyOnJava8 {

    "This requires Java 8" >> {
      // Test code...
    }
    "This also requires Java 8" >> {
      // Test code...
    }
  }

  private def worksOnlyOnJava8(closure: => Unit) {
    if (isJava8) {
      closure
    }
  }

  private def isJava8: Boolean = {
    try {
      Class.forName("java.time.LocalDate")
      true
    } catch {
      case e: ClassNotFoundException => false
    }
  }
}

class EnvironmentFilterExampleSpec extends GroovySpecsy {
    @Override
    void run() {
        spec "This test is run every time", {
            // Test code...
        }

        spec "This test is run only under Java 8 and greater", {
            worksOnlyOnJava8 {
                // Test code... For example something which uses the new Date and Time API (JSR-310)
                // which was added in Java 8
            }
        }

        // This can also be used at the top level, if many/all tests work only on Java 8.
        // Just surround all tests and variable/field declarations into a closure.
        worksOnlyOnJava8 {

            spec "This requires Java 8", {
                // Test code...
            }
            spec "This also requires Java 8", {
                // Test code...
            }
        }
    }

    private static void worksOnlyOnJava8(Closure closure) {
        if (isJava8()) {
            closure.run()
        }
    }

    private static boolean isJava8() {
        try {
            Class.forName("java.time.LocalDate")
            return true
        } catch (ClassNotFoundException e) {
            return false
        }
    }
}

public class EnvironmentFilterExampleSpec extends JavaSpecsy {
    @Override
    public void run() throws Throwable {
        spec("This test is run every time", () -> {
            // Test code...
        });

        spec("This test is run only under Java 8 and greater", () -> worksOnlyOnJava8(() -> {
            // Test code... For example something which uses the new Date and Time API (JSR-310)
            // which was added in Java 8
        }));

        // This can also be used at the top level, if many/all tests work only on Java 8.
        // Just surround all tests and variable/field declarations into a closure.
        worksOnlyOnJava8(() -> {

            spec("This requires Java 8", () -> {
                // Test code...
            });
            spec("This also requires Java 8", () -> {
                // Test code...
            });
        });
    }

    private static void worksOnlyOnJava8(Closure closure) throws Throwable {
        if (isJava8()) {
            closure.run();
        }
    }

    private static boolean isJava8() {
        try {
            Class.forName("java.time.LocalDate");
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }
}

### "Pending Until Fixed"

A common situation in Acceptance Test Driven Development (ATDD) is that you have an acceptance test which is not yet passing, until you implement the feature specified by that acceptance test, but that might take a long time. In that situation it can be useful to make the test so that if the test throws an exception, then you don't fail it but consider it to be pending, but if the test does *not* throw an exception and the feature is complete, then you fail it so that you would remember to remove the pending-until-fixed tag.

Specsy does not (yet) have a concept of "pending", but you can achieve almost the same thing by making the test pass and by having the `pendingUntilFixed` method in a helper class which all tests use, so that it's easy to seach for all its usages to find out which tests are pending. [PendingUntilFixedExampleSpec] illustrates this:

class PendingUntilFixedExampleSpec extends ScalaSpecsy {

  "An acceptance test for an already implemented feature" >> {
    // Test code...
  }

  "An acceptance test whose feature has not yet been implemented" >> AcceptanceTestHelpers.pendingUntilFixed {
    // Test code which is still failing...
    assert(false, "this feature is not implemented")
  }
}

object AcceptanceTestHelpers {

  // When this method is in a helper class, it's easy to find all pending tests
  // by searching for all usages of this method with your IDE.
  def pendingUntilFixed(closure: => Unit) {
    try {
      closure
    } catch {
      case e: Throwable =>
        System.err.println("This test is pending until fixed:")
        e.printStackTrace()
        return // test is pending
    }
    throw new AssertionError("This test would now pass. Remove the 'pendingUntilFixed' tag.")
  }
}

import static com.example.AcceptanceTestHelpers.pendingUntilFixed

class PendingUntilFixedExampleSpec extends GroovySpecsy {
    @Override
    void run() {
        spec "An acceptance test for an already implemented feature", {
            // Test code...
        }

        spec "An acceptance test whose feature has not yet been implemented", {
            pendingUntilFixed {
                // Test code which is still failing...
                throw new AssertionError("this feature is not implemented")
            }
        }
    }
}

class AcceptanceTestHelpers {

    // When this method is in a helper class, it's easy to find all pending tests
    // by searching for all usages of this method with your IDE.
    public static void pendingUntilFixed(Closure closure) {
        try {
            closure.run()
        } catch (Throwable t) {
            System.err.println("This test is pending until fixed:")
            t.printStackTrace()
            return // test is pending
        }
        throw new AssertionError("This test would now pass. Remove the 'pendingUntilFixed' tag.")
    }
}

import static com.example.AcceptanceTestHelpers.pendingUntilFixed;

public class PendingUntilFixedExampleSpec extends JavaSpecsy {
    @Override
    public void run() {
        spec("An acceptance test for an already implemented feature", () -> {
            // Test code...
        });

        spec("An acceptance test whose feature has not yet been implemented", () -> pendingUntilFixed(() -> {
            // Test code which is still failing...
            throw new AssertionError("this feature is not implemented");
        }));
    }
}

class AcceptanceTestHelpers {

    // When this method is in a helper class, it's easy to find all pending tests
    // by searching for all usages of this method with your IDE.
    public static void pendingUntilFixed(Closure closure) {
        try {
            closure.run();
        } catch (Throwable t) {
            System.err.println("This test is pending until fixed:");
            t.printStackTrace();
            return; // test is pending
        }
        throw new AssertionError("This test would now pass. Remove the 'pendingUntilFixed' tag.");
    }
}

[FibonacciSpec]:                https://github.com/luontola/specsy/blob/master/specsy-examples/src/test/scala/org/specsy/examples/scala/FibonacciSpec.scala
[StackSpec]:                    https://github.com/luontola/specsy/blob/master/specsy-examples/src/test/scala/org/specsy/examples/scala/StackSpec.scala
[ShareSideEffectsExampleSpec]:  https://github.com/luontola/specsy/blob/master/specsy-examples/src/test/scala/org/specsy/examples/scala/ShareSideEffectsExampleSpec.scala
[DeferBlocksExampleSpec]:       https://github.com/luontola/specsy/blob/master/specsy-examples/src/test/scala/org/specsy/examples/scala/DeferBlocksExampleSpec.scala
[DeferBlocksExample2Spec]:      https://github.com/luontola/specsy/blob/master/specsy-examples/src/test/scala/org/specsy/examples/scala/DeferBlocksExample2Spec.scala
[ParameterizedExampleSpec]:     https://github.com/luontola/specsy/blob/master/specsy-examples/src/test/scala/org/specsy/examples/scala/ParameterizedExampleSpec.scala
[EnvironmentFilterExampleSpec]: https://github.com/luontola/specsy/blob/master/specsy-examples/src/test/scala/org/specsy/examples/scala/EnvironmentFilterExampleSpec.scala
[PendingUntilFixedExampleSpec]: https://github.com/luontola/specsy/blob/master/specsy-examples/src/test/scala/org/specsy/examples/scala/PendingUntilFixedExampleSpec.scala


text:
{% extends "non_sheet_page_small_logo.html" %}

{% block title %}
    {{ user.username }}'s Dashboard: Dirigible
{% endblock %}

{% block head %}
    {{ block.super }}
    <link rel="stylesheet" href="/static/dirigible/styles/user_page.css" type="text/css" media="screen" charset="utf-8" />
{% endblock %}

{% block content %}

Sheets

                Create new sheet...

                {% if sheets %}

                        {% for s in sheets %}

{{s.name}}

                        {% endfor %}

                {% else %}

You have no sheets. Create one to get started!

                {% endif %}

Account details

                Change password...
                <form id="id_change_password_form" method="POST">
                    {% csrf_token %}
                    Current Password: <input id="id_change_password_current_password" name="id_change_password_current_password" type="password">

                    New Password: <input id="id_change_password_new_password" name="id_change_password_new_password" type="password">

                    Confirm Password: <input id="id_change_password_new_password_again" name="id_change_password_new_password_again" type="password">

                        <input type="submit" class="blue_button" id="id_change_password_ok_button" type="button" value="OK">
                        <input id="id_change_password_cancel_button" class="blue_button" type="button" value="Cancel">

                </form>

Example sheets

            Here are some example spreadsheets you can copy into your account to
            get you started.

{% endblock %}


text:
using System;
using System.ComponentModel;
using TryCSharp.Common;

namespace TryCSharp.Samples.Basic
{
    /// <summary>
    ///     手動でイベントを制御する方法に関してのサンプルです。(EventHandlerList)
    /// </summary>
    [Sample]
    public class EventSettingSamples02 : IExecutable
    {
        public void Execute()
        {
            var obj = new Sample();

            EventHandler handler = (s, e) => { Output.WriteLine("event raised."); };

            obj.TestEvent += handler;
            obj.FireEvents();
            obj.TestEvent -= handler;
            obj.FireEvents();
        }

        private class Sample
        {
            private readonly object _eventTarget = new object();

            public Sample()
            {
                Events = new EventHandlerList();
            }

            public EventHandlerList Events { get; }

            public event EventHandler TestEvent
            {
                add
                {
                    Output.WriteLine("add handler.");
                    Events.AddHandler(_eventTarget, value);
                }
                remove
                {
                    Output.WriteLine("remove handler.");
                    Events.RemoveHandler(_eventTarget, value);
                }
            }

            public void FireEvents()
            {
                var handler = Events[_eventTarget] as EventHandler;
                handler?.Invoke(this, EventArgs.Empty);
            }
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>encodings.idna — ArcherBashPYDocs 1.0.0. documentation</title>

  <link href='https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic|Roboto+Slab:400,700|Inconsolata:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />

    <link rel="top" title="ArcherBashPYDocs 1.0.0. documentation" href="../../index.html"/>
        <link rel="up" title="encodings" href="../encodings.html"/>

           ArcherBashPYDocs

  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

        ArcherBashPYDocs

Docs »

Module code »

encodings »

encodings.idna

Source code for encodings.idna

# This module implements the RFCs 3490 (IDNA) and 3491 (Nameprep)

import stringprep, re, codecs
from unicodedata import ucd_3_2_0 as unicodedata

# IDNA section 3.1
dots = re.compile("[\u002E\u3002\uFF0E\uFF61]")

# IDNA section 5
ace_prefix = b"xn--"
sace_prefix = "xn--"

# This assumes query strings, so AllowUnassigned is true

[docs]def nameprep(label):
    # Map
    newlabel = []
    for c in label:
        if stringprep.in_table_b1(c):
            # Map to nothing
            continue
        newlabel.append(stringprep.map_table_b2(c))
    label = "".join(newlabel)

    # Normalize
    label = unicodedata.normalize("NFKC", label)

    # Prohibit
    for c in label:
        if stringprep.in_table_c12(c) or \
           stringprep.in_table_c22(c) or \
           stringprep.in_table_c3(c) or \
           stringprep.in_table_c4(c) or \
           stringprep.in_table_c5(c) or \
           stringprep.in_table_c6(c) or \
           stringprep.in_table_c7(c) or \
           stringprep.in_table_c8(c) or \
           stringprep.in_table_c9(c):
            raise UnicodeError("Invalid character %r" % c)

    # Check bidi
    RandAL = [stringprep.in_table_d1(x) for x in label]
    for c in RandAL:
        if c:
            # There is a RandAL char in the string. Must perform further
            # tests:
            # 1) The characters in section 5.8 MUST be prohibited.
            # This is table C.8, which was already checked
            # 2) If a string contains any RandALCat character, the string
            # MUST NOT contain any LCat character.
            if any(stringprep.in_table_d2(x) for x in label):
                raise UnicodeError("Violation of BIDI requirement 2")

            # 3) If a string contains any RandALCat character, a
            # RandALCat character MUST be the first character of the
            # string, and a RandALCat character MUST be the last
            # character of the string.
            if not RandAL[0] or not RandAL[-1]:
                raise UnicodeError("Violation of BIDI requirement 3")

    return label

[docs]def ToASCII(label):
    try:
        # Step 1: try ASCII
        label = label.encode("ascii")
    except UnicodeError:
        pass
    else:
        # Skip to step 3: UseSTD3ASCIIRules is false, so
        # Skip to step 8.
        if 0 < len(label) < 64:
            return label
        raise UnicodeError("label empty or too long")

    # Step 2: nameprep
    label = nameprep(label)

    # Step 3: UseSTD3ASCIIRules is false
    # Step 4: try ASCII
    try:
        label = label.encode("ascii")
    except UnicodeError:
        pass
    else:
        # Skip to step 8.
        if 0 < len(label) < 64:
            return label
        raise UnicodeError("label empty or too long")

    # Step 5: Check ACE prefix
    if label.startswith(sace_prefix):
        raise UnicodeError("Label starts with ACE prefix")

    # Step 6: Encode with PUNYCODE
    label = label.encode("punycode")

    # Step 7: Prepend ACE prefix
    label = ace_prefix + label

    # Step 8: Check size
    if 0 < len(label) < 64:
        return label
    raise UnicodeError("label empty or too long")

[docs]def ToUnicode(label):
    # Step 1: Check for ASCII
    if isinstance(label, bytes):
        pure_ascii = True
    else:
        try:
            label = label.encode("ascii")
            pure_ascii = True
        except UnicodeError:
            pure_ascii = False
    if not pure_ascii:
        # Step 2: Perform nameprep
        label = nameprep(label)
        # It doesn't say this, but apparently, it should be ASCII now
        try:
            label = label.encode("ascii")
        except UnicodeError:
            raise UnicodeError("Invalid character in IDN label")
    # Step 3: Check for ACE prefix
    if not label.startswith(ace_prefix):
        return str(label, "ascii")

    # Step 4: Remove ACE prefix
    label1 = label[len(ace_prefix):]

    # Step 5: Decode using PUNYCODE
    result = label1.decode("punycode")

    # Step 6: Apply ToASCII
    label2 = ToASCII(result)

    # Step 7: Compare the result of step 6 with the one of step 3
    # label2 will already be in lower case.
    if str(label, "ascii").lower() != str(label2, "ascii"):
        raise UnicodeError("IDNA does not round-trip", label, label2)

    # Step 8: return the result of step 5
    return result

### Codec APIs

[docs]class Codec(codecs.Codec):

[docs]    def encode(self, input, errors='strict'):

        if errors != 'strict':
            # IDNA is quite clear that implementations must be strict
            raise UnicodeError("unsupported error handling "+errors)

        if not input:
            return b'', 0

        try:
            result = input.encode('ascii')
        except UnicodeEncodeError:
            pass
        else:
            # ASCII name: fast path
            labels = result.split(b'.')
            for label in labels[:-1]:
                if not (0 < len(label) < 64):
                    raise UnicodeError("label empty or too long")
            if len(labels[-1]) >= 64:
                raise UnicodeError("label too long")
            return result, len(input)

        result = bytearray()
        labels = dots.split(input)
        if labels and not labels[-1]:
            trailing_dot = b'.'
            del labels[-1]
        else:
            trailing_dot = b''
        for label in labels:
            if result:
                # Join with U+002E
                result.extend(b'.')
            result.extend(ToASCII(label))
        return bytes(result+trailing_dot), len(input)

[docs]    def decode(self, input, errors='strict'):

        if errors != 'strict':
            raise UnicodeError("Unsupported error handling "+errors)

        if not input:
            return "", 0

        # IDNA allows decoding to operate on Unicode strings, too.
        if not isinstance(input, bytes):
            # XXX obviously wrong, see #3232
            input = bytes(input)

        if ace_prefix not in input:
            # Fast path
            try:
                return input.decode('ascii'), len(input)
            except UnicodeDecodeError:
                pass

        labels = input.split(b".")

        if labels and len(labels[-1]) == 0:
            trailing_dot = '.'
            del labels[-1]
        else:
            trailing_dot = ''

        result = []
        for label in labels:
            result.append(ToUnicode(label))

        return ".".join(result)+trailing_dot, len(input)

[docs]class IncrementalEncoder(codecs.BufferedIncrementalEncoder):
    def _buffer_encode(self, input, errors, final):
        if errors != 'strict':
            # IDNA is quite clear that implementations must be strict
            raise UnicodeError("unsupported error handling "+errors)

        if not input:
            return (b'', 0)

        labels = dots.split(input)
        trailing_dot = b''
        if labels:
            if not labels[-1]:
                trailing_dot = b'.'
                del labels[-1]
            elif not final:
                # Keep potentially unfinished label until the next call
                del labels[-1]
                if labels:
                    trailing_dot = b'.'

        result = bytearray()
        size = 0
        for label in labels:
            if size:
                # Join with U+002E
                result.extend(b'.')
                size += 1
            result.extend(ToASCII(label))
            size += len(label)

        result += trailing_dot
        size += len(trailing_dot)
        return (bytes(result), size)

[docs]class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
    def _buffer_decode(self, input, errors, final):
        if errors != 'strict':
            raise UnicodeError("Unsupported error handling "+errors)

        if not input:
            return ("", 0)

        # IDNA allows decoding to operate on Unicode strings, too.
        if isinstance(input, str):
            labels = dots.split(input)
        else:
            # Must be ASCII string
            input = str(input, "ascii")
            labels = input.split(".")

        trailing_dot = ''
        if labels:
            if not labels[-1]:
                trailing_dot = '.'
                del labels[-1]
            elif not final:
                # Keep potentially unfinished label until the next call
                del labels[-1]
                if labels:
                    trailing_dot = '.'

        result = []
        size = 0
        for label in labels:
            result.append(ToUnicode(label))
            if size:
                size += 1
            size += len(label)

        result = ".".join(result) + trailing_dot
        size += len(trailing_dot)
        return (result, size)

[docs]class StreamWriter(Codec,codecs.StreamWriter):
    pass

[docs]class StreamReader(Codec,codecs.StreamReader):
    pass

### encodings module API

[docs]def getregentry():
    return codecs.CodecInfo(
        name='idna',
        encode=Codec().encode,
        decode=Codec().decode,
        incrementalencoder=IncrementalEncoder,
        incrementaldecoder=IncrementalDecoder,
        streamwriter=StreamWriter,
        streamreader=StreamReader,
    )

        © Copyright 2015, Weldon Henson.

  Built with Sphinx using a theme provided by Read the Docs.


text:
using NUnit.Framework;
using Rhino.Mocks;
using StructureMap.Interceptors;

namespace StructureMap.Testing.Graph.Interceptors
{
    [TestFixture]
    public class CompoundInterceptorTester
    {
        #region Setup/Teardown

        [SetUp]
        public void SetUp()
        {
        }

        #endregion

        [Test]
        public void CallAllTheInterceptors()
        {
            var mocks = new MockRepository();
            var interceptor1 = mocks.StrictMock<InstanceInterceptor>();
            var interceptor2 = mocks.StrictMock<InstanceInterceptor>();
            var interceptor3 = mocks.StrictMock<InstanceInterceptor>();
            var interceptor4 = mocks.StrictMock<InstanceInterceptor>();

            Expect.Call(interceptor1.Process("0", null)).Return("1");
            Expect.Call(interceptor2.Process("1", null)).Return("2");
            Expect.Call(interceptor3.Process("2", null)).Return("3");
            Expect.Call(interceptor4.Process("3", null)).Return("4");

            mocks.ReplayAll();
            var compoundInterceptor = new CompoundInterceptor(new[]
            {
                interceptor1,
                interceptor2,
                interceptor3,
                interceptor4
            });

            Assert.AreEqual("4", compoundInterceptor.Process("0", null));
            mocks.VerifyAll();
        }
    }
}


text:
using Linux.MVC.Learn.Model.Blog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Linux.MVC.Learn.DDL.ViewModel
{
    public class BlogTagViewModel
    {
        public BlogTagViewModel(BlogTag tag,int count)
        {
            Slug = tag.Slug;
            Name = tag.Tag;
        }
        public BlogTagViewModel(string name, string slug, int count)
        {
            this.Name = name;
            this.PostCount = count;
            this.Slug = slug;
        }

        public BlogTagViewModel()
        {
            // TODO: Complete member initialization
        }

        public string Slug { get; set; }

        public string Name { get; set; }

        public int PostCount { get; set; }
    }
}