code
stringlengths 5
1M
| repo_name
stringlengths 5
109
| path
stringlengths 6
208
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1M
|
---|---|---|---|---|---|
// - Project: scalajs-angulate (https://github.com/jokade/scalajs-angulate)
// Description:
//
// Distributed under the MIT License (see included file LICENSE)
package biz.enef.angulate.impl
import acyclic.file
import scala.reflect.macros.blackbox
protected [angulate] class ServiceMacros(val c: blackbox.Context) extends MacroBase {
import c.universe._
// print generated code to console during compilation
private lazy val logCode = c.settings.exists( _ == "biz.enef.angulate.ServiceMacros.debug" )
def serviceOf[T: c.WeakTypeTag] = {
val serviceType = weakTypeOf[T]
val name = serviceType.toString.split('.').last
createService(serviceType, q"${name.head.toLower+name.tail}")
}
def serviceOfWithName[T: c.WeakTypeTag](name: c.Tree) = {
val serviceType = weakTypeOf[T]
createService(serviceType, q"${name}")
}
private def createService(ct: c.Type, name: c.Tree) = {
val module = Select(c.prefix.tree, TermName("self"))
val constr = ct.members.filter( _.isConstructor ).map( _.asMethod ).head
val (params,args) = makeArgsList(constr)
val deps = getDINames(constr)
// AngularJS service construction array
val carray =
q"""js.Array[Any](..$deps, ((..$params) =>
new $ct(..$args)):js.Function)
"""
val tree = q"""{import scala.scalajs.js
import js.Dynamic.{global,literal}
$module.self.factory($name,$carray)
}"""
if (logCode) printCode(tree, "\\nserviceOf macro:")
tree
}
}
|
CapeSepias/scalajs-angulate
|
src/main/scala/biz/enef/angulate/impl/ServiceMacros.scala
|
Scala
|
mit
| 1,539 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.samza.container
import org.apache.samza.metrics.ReadableMetricsRegistry
import org.apache.samza.metrics.MetricsRegistryMap
import org.apache.samza.metrics.MetricsHelper
import org.apache.samza.system.SystemStreamPartition
class TaskInstanceMetrics(
val source: String = "unknown",
val registry: ReadableMetricsRegistry = new MetricsRegistryMap,
val prefix: String = "") extends MetricsHelper {
val commits = newCounter("commit-calls")
val windows = newCounter("window-calls")
val processes = newCounter("process-calls")
val messagesActuallyProcessed = newCounter("messages-actually-processed")
val sends = newCounter("send-calls")
val flushes = newCounter("flush-calls")
val pendingMessages = newGauge("pending-messages", 0)
val messagesInFlight = newGauge("messages-in-flight", 0)
val asyncCallbackCompleted = newCounter("async-callback-complete-calls");
def addOffsetGauge(systemStreamPartition: SystemStreamPartition, getValue: () => String) {
newGauge("%s-%s-%d-offset" format (systemStreamPartition.getSystem, systemStreamPartition.getStream, systemStreamPartition.getPartition.getPartitionId), getValue)
}
override def getPrefix: String = prefix
}
|
lhaiesp/samza
|
samza-core/src/main/scala/org/apache/samza/container/TaskInstanceMetrics.scala
|
Scala
|
apache-2.0
| 2,021 |
package com.freshsoft.matterbridge.client.ninegag
import akka.actor.{ActorRef, ActorSystem, Props}
import akka.testkit.TestKit
import model.MatterBridgeEntities.NineGagGifResult
import org.scalatest._
/**
* The nine gag receiver test
*/
class NineGagReceiverTest
extends TestKit(ActorSystem("testSystem"))
with WordSpecLike
with Matchers
with BeforeAndAfter {
val expectedMessage = NineGagGifResult("Sample", "Some String", "Test")
val nineGagReceiver: ActorRef =
system.actorOf(Props(classOf[NineGagIntegration.NineGagGifReceiver]))
before {}
"The nine gag receiver actor" should {
"not send a message back" in {
nineGagReceiver ! expectedMessage
expectNoMsg()
}
"store a gif" in {
nineGagReceiver ! expectedMessage
expectNoMsg()
}
}
}
|
Freshwood/matterbridge
|
src/test/scala/com/freshsoft/matterbridge/client/ninegag/NineGagReceiverTest.scala
|
Scala
|
mit
| 816 |
package controllers.stack
import controllers.BaseAuthConfig
import com.github.tototoshi.play2.auth.AuthElement
import jp.t2v.lab.play2.stackc.{RequestAttributeKey, RequestWithAttributes, StackableController}
import play.api.mvc.{Controller, Result}
import play.twirl.api.Html
import views.html
import scala.concurrent.Future
trait Pjax extends StackableController with AuthElement {
self: Controller with BaseAuthConfig =>
type Template = String => Html => Html
case object TemplateKey extends RequestAttributeKey[Template]
abstract override def proceed[A](req: RequestWithAttributes[A])(f: RequestWithAttributes[A] => Future[Result]): Future[Result] = {
super.proceed(req) { req =>
val template: Template = if (req.headers.keys("X-Pjax")) html.pjaxTemplate.apply else fullTemplate(loggedIn(req))
f(req.set(TemplateKey, template))
}
}
implicit def template(implicit req: RequestWithAttributes[_]): Template = req.get(TemplateKey).get
protected val fullTemplate: User => Template
}
|
tototoshi/play2-auth
|
sample/app/controllers/stack/Pjax.scala
|
Scala
|
apache-2.0
| 1,026 |
package pricemap
import Types.{latitude, longitude}
case class BoundingBox(minLat: latitude,
maxLat: latitude,
minLon: longitude,
maxLon: longitude)
case class BooliParameters(callerId: String,
privateKey: String,
uri: String,
maxPages: Int)
object Booli {
}
|
lastsys/pricemap
|
client/src/main/scala/pricemap/Booli.scala
|
Scala
|
bsd-3-clause
| 414 |
import scala.tools.partest._
import java.io.{Console => _, _}
object Test extends DirectTest {
override def extraSettings: String = "-usejavacp -Xprint:patmat -Xprint-pos -d " + testOutput.path
override def code =
"""
|object Case3 {
| def unapply(z: Any): Option[Int] = Some(-1)
|
| "" match {
| case Case3(nr) => ()
| }
|}
|object Case4 {
| def unapplySeq(z: Any): Option[List[Int]] = None
|
| "" match {
| case Case4(nr) => ()
| }
|}
|object Case5 {
| def unapply(z: Any): Boolean = true
|
| "" match {
| case Case4() => ()
| }
|}
|
|""".stripMargin.trim
override def show(): Unit = {
// Now: [84][84]Case3.unapply([84]x1);
// Was: [84][84]Case3.unapply([64]x1);
Console.withErr(System.out) {
compile()
}
}
}
|
yusuke2255/dotty
|
tests/pending/run/t6288.scala
|
Scala
|
bsd-3-clause
| 906 |
/*
,i::,
:;;;;;;;
;:,,::;.
1ft1;::;1tL
t1;::;1,
:;::; _____ __ ___ __
fCLff ;:: tfLLC / ___/ / |/ /____ _ _____ / /_
CLft11 :,, i1tffLi \\__ \\ ____ / /|_/ // __ `// ___// __ \\
1t1i .;; .1tf ___/ //___// / / // /_/ // /__ / / / /
CLt1i :,: .1tfL. /____/ /_/ /_/ \\__,_/ \\___//_/ /_/
Lft1,:;: , 1tfL:
;it1i ,,,:::;;;::1tti s_mach.concurrent
.t1i .,::;;; ;1tt Copyright (c) 2017 S-Mach, Inc.
Lft11ii;::;ii1tfL: Author: [email protected]
.L1 1tt1ttt,,Li
...1LLLL...
*/
package s_mach.concurrent
/* WARNING: Generated code. To modify see s_mach.concurrent.codegen.TupleAsyncTaskRunnerTestCodeGen */
import scala.util.{Random, Success, Failure}
import org.scalatest.{FlatSpec, Matchers}
import s_mach.concurrent.TestBuilder._
import util._
class Tuple16AsyncTaskRunnerTest extends FlatSpec with Matchers with ConcurrentTestCommon {
"Tuple16AsyncTaskRunner-t0" must "wait on all Futures to complete concurrently" in {
val results =
test repeat TEST_COUNT run {
implicit val ctc = mkConcurrentTestContext()
import ctc._
sched.addEvent("start")
val items = IndexedSeq.fill(16)(Random.nextInt)
val fa = success(items(0))
val fb = success(items(1))
val fc = success(items(2))
val fd = success(items(3))
val fe = success(items(4))
val ff = success(items(5))
val fg = success(items(6))
val fh = success(items(7))
val fi = success(items(8))
val fj = success(items(9))
val fk = success(items(10))
val fl = success(items(11))
val fm = success(items(12))
val fn = success(items(13))
val fo = success(items(14))
val fp = success(items(15))
val result = async.par.run(fa,fb,fc,fd,fe,ff,fg,fh,fi,fj,fk,fl,fm,fn,fo,fp)
waitForActiveExecutionCount(0)
sched.addEvent("end")
result.awaitTry should be(Success((items(0),items(1),items(2),items(3),items(4),items(5),items(6),items(7),items(8),items(9),items(10),items(11),items(12),items(13),items(14),items(15))))
isConcurrentSchedule(Vector(items(0),items(1),items(2),items(3),items(4),items(5),items(6),items(7),items(8),items(9),items(10),items(11),items(12),items(13),items(14),items(15)), sched)
}
val concurrentPercent = results.count(_ == true) / results.size.toDouble
concurrentPercent should be >= MIN_CONCURRENCY_PERCENT
}
"TupleAsyncTaskRunner-t1" must "complete immediately after any Future fails" in {
test repeat TEST_COUNT run {
implicit val ctc = mkConcurrentTestContext()
import ctc._
sched.addEvent("start")
val endLatch = Latch()
val fb = fail(2)
// Note1: without hooking the end latch here there would be a race condition here between success 1,3,4,5,6
// and end. The latch is used to create a serialization schedule that can be reliably tested
// Note2: Due to this design, a bug in merge that does not complete immediately on failure will cause a
// deadlock here instead of a failing test
val fa = endLatch happensBefore success(1)
val fc = endLatch happensBefore success(3)
val fd = endLatch happensBefore success(4)
val fe = endLatch happensBefore success(5)
val ff = endLatch happensBefore success(6)
val fg = endLatch happensBefore success(7)
val fh = endLatch happensBefore success(8)
val fi = endLatch happensBefore success(9)
val fj = endLatch happensBefore success(10)
val fk = endLatch happensBefore success(11)
val fl = endLatch happensBefore success(12)
val fm = endLatch happensBefore success(13)
val fn = endLatch happensBefore success(14)
val fo = endLatch happensBefore success(15)
val fp = endLatch happensBefore success(16)
val result = async.par.run(fa,fb,fc,fd,fe,ff,fg,fh,fi,fj,fk,fl,fm,fn,fo,fp)
waitForActiveExecutionCount(0)
sched.addEvent("end")
endLatch.set()
waitForActiveExecutionCount(0)
result.awaitTry shouldBe a [Failure[_]]
result.awaitTry.failed.get shouldBe a [AsyncParThrowable]
sched.happensBefore("start","fail-2") should equal(true)
sched.happensBefore("fail-2","end") should equal(true)
(1 to 16).filter(_ != 2).foreach { i =>
sched.happensBefore("end", s"success-$i") should equal(true)
}
}
}
"TupleAsyncTaskRunner-t2" must "throw AsyncParThrowable which can wait for all failures" in {
test repeat TEST_COUNT run {
implicit val ctc = mkConcurrentTestContext()
import ctc._
val failures = Random.shuffle(Seq(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16)).take(2)
def call(i: Int) = if(failures.contains(i)) {
fail(i)
} else {
success(i)
}
val result = async.par.run(call(1),call(2),call(3),call(4),call(5),call(6),call(7),call(8),call(9),call(10),call(11),call(12),call(13),call(14),call(15),call(16))
waitForActiveExecutionCount(0)
val thrown = result.failed.await.asInstanceOf[AsyncParThrowable]
// Even though there are two worker threads, it technically is a race condition to see which failure happens
// first. This actually happens in about 1/1000 runs where it appears worker one while processing fail-1 stalls
// and worker 2 is able to complete success-2, success-3 and fail-4 before fail-1 finishes
thrown.firstFailure.toString.startsWith("java.lang.RuntimeException: fail-") should equal(true)
thrown.allFailure.await.map(_.toString) should contain theSameElementsAs(
failures.map(failIdx => new RuntimeException(s"fail-$failIdx").toString)
)
}
}
}
|
S-Mach/s_mach.concurrent
|
src/test/scala/s_mach/concurrent/Tuple16AsyncTaskRunnerTest.scala
|
Scala
|
mit
| 5,947 |
package service
import util.Directory._
import util.ControlUtil._
import SystemSettingsService._
trait SystemSettingsService {
def saveSystemSettings(settings: SystemSettings): Unit = {
defining(new java.util.Properties()){ props =>
settings.baseUrl.foreach(props.setProperty(BaseURL, _))
props.setProperty(AllowAccountRegistration, settings.allowAccountRegistration.toString)
props.setProperty(Gravatar, settings.gravatar.toString)
props.setProperty(Notification, settings.notification.toString)
if(settings.notification) {
settings.smtp.foreach { smtp =>
props.setProperty(SmtpHost, smtp.host)
smtp.port.foreach(x => props.setProperty(SmtpPort, x.toString))
smtp.user.foreach(props.setProperty(SmtpUser, _))
smtp.password.foreach(props.setProperty(SmtpPassword, _))
smtp.ssl.foreach(x => props.setProperty(SmtpSsl, x.toString))
smtp.fromAddress.foreach(props.setProperty(SmtpFromAddress, _))
smtp.fromName.foreach(props.setProperty(SmtpFromName, _))
}
}
props.setProperty(LdapAuthentication, settings.ldapAuthentication.toString)
if(settings.ldapAuthentication){
settings.ldap.map { ldap =>
props.setProperty(LdapHost, ldap.host)
ldap.port.foreach(x => props.setProperty(LdapPort, x.toString))
ldap.bindDN.foreach(x => props.setProperty(LdapBindDN, x))
ldap.bindPassword.foreach(x => props.setProperty(LdapBindPassword, x))
props.setProperty(LdapBaseDN, ldap.baseDN)
props.setProperty(LdapUserNameAttribute, ldap.userNameAttribute)
ldap.fullNameAttribute.foreach(x => props.setProperty(LdapFullNameAttribute, x))
props.setProperty(LdapMailAddressAttribute, ldap.mailAttribute)
ldap.tls.foreach(x => props.setProperty(LdapTls, x.toString))
ldap.keystore.foreach(x => props.setProperty(LdapKeystore, x))
}
}
props.store(new java.io.FileOutputStream(GitBucketConf), null)
}
}
def loadSystemSettings(): SystemSettings = {
defining(new java.util.Properties()){ props =>
if(GitBucketConf.exists){
props.load(new java.io.FileInputStream(GitBucketConf))
}
SystemSettings(
getOptionValue(props, BaseURL, None),
getValue(props, AllowAccountRegistration, false),
getValue(props, Gravatar, true),
getValue(props, Notification, false),
if(getValue(props, Notification, false)){
Some(Smtp(
getValue(props, SmtpHost, ""),
getOptionValue(props, SmtpPort, Some(DefaultSmtpPort)),
getOptionValue(props, SmtpUser, None),
getOptionValue(props, SmtpPassword, None),
getOptionValue[Boolean](props, SmtpSsl, None),
getOptionValue(props, SmtpFromAddress, None),
getOptionValue(props, SmtpFromName, None)))
} else {
None
},
getValue(props, LdapAuthentication, false),
if(getValue(props, LdapAuthentication, false)){
Some(Ldap(
getValue(props, LdapHost, ""),
getOptionValue(props, LdapPort, Some(DefaultLdapPort)),
getOptionValue(props, LdapBindDN, None),
getOptionValue(props, LdapBindPassword, None),
getValue(props, LdapBaseDN, ""),
getValue(props, LdapUserNameAttribute, ""),
getOptionValue(props, LdapFullNameAttribute, None),
getValue(props, LdapMailAddressAttribute, ""),
getOptionValue[Boolean](props, LdapTls, None),
getOptionValue(props, LdapKeystore, None)))
} else {
None
}
)
}
}
}
object SystemSettingsService {
import scala.reflect.ClassTag
case class SystemSettings(
baseUrl: Option[String],
allowAccountRegistration: Boolean,
gravatar: Boolean,
notification: Boolean,
smtp: Option[Smtp],
ldapAuthentication: Boolean,
ldap: Option[Ldap])
case class Ldap(
host: String,
port: Option[Int],
bindDN: Option[String],
bindPassword: Option[String],
baseDN: String,
userNameAttribute: String,
fullNameAttribute: Option[String],
mailAttribute: String,
tls: Option[Boolean],
keystore: Option[String])
case class Smtp(
host: String,
port: Option[Int],
user: Option[String],
password: Option[String],
ssl: Option[Boolean],
fromAddress: Option[String],
fromName: Option[String])
val DefaultSmtpPort = 25
val DefaultLdapPort = 389
private val BaseURL = "base_url"
private val AllowAccountRegistration = "allow_account_registration"
private val Gravatar = "gravatar"
private val Notification = "notification"
private val SmtpHost = "smtp.host"
private val SmtpPort = "smtp.port"
private val SmtpUser = "smtp.user"
private val SmtpPassword = "smtp.password"
private val SmtpSsl = "smtp.ssl"
private val SmtpFromAddress = "smtp.from_address"
private val SmtpFromName = "smtp.from_name"
private val LdapAuthentication = "ldap_authentication"
private val LdapHost = "ldap.host"
private val LdapPort = "ldap.port"
private val LdapBindDN = "ldap.bindDN"
private val LdapBindPassword = "ldap.bind_password"
private val LdapBaseDN = "ldap.baseDN"
private val LdapUserNameAttribute = "ldap.username_attribute"
private val LdapFullNameAttribute = "ldap.fullname_attribute"
private val LdapMailAddressAttribute = "ldap.mail_attribute"
private val LdapTls = "ldap.tls"
private val LdapKeystore = "ldap.keystore"
private def getValue[A: ClassTag](props: java.util.Properties, key: String, default: A): A =
defining(props.getProperty(key)){ value =>
if(value == null || value.isEmpty) default
else convertType(value).asInstanceOf[A]
}
private def getOptionValue[A: ClassTag](props: java.util.Properties, key: String, default: Option[A]): Option[A] =
defining(props.getProperty(key)){ value =>
if(value == null || value.isEmpty) default
else Some(convertType(value)).asInstanceOf[Option[A]]
}
private def convertType[A: ClassTag](value: String) =
defining(implicitly[ClassTag[A]].runtimeClass){ c =>
if(c == classOf[Boolean]) value.toBoolean
else if(c == classOf[Int]) value.toInt
else value
}
}
|
odz/gitbucket
|
src/main/scala/service/SystemSettingsService.scala
|
Scala
|
apache-2.0
| 6,516 |
package com.bot4s.telegram.api
import com.bot4s.telegram.models.ResponseParameters
/**
* Telegram API errors, e.g. when `response.ok` is false.
* Does not wrap exceptions related to de/serialization, network errors...
*/
case class TelegramApiException(
message: String,
errorCode: Int,
cause: Option[Throwable] = None,
parameters: Option[ResponseParameters] = None
) extends RuntimeException(message, cause.orNull)
|
mukel/telegrambot4s
|
core/src/com/bot4s/telegram/api/TelegramApiException.scala
|
Scala
|
apache-2.0
| 429 |
package co.ledger.wallet.web.ripple.core.device
import java.io.ByteArrayOutputStream
/**
*
* LedgerTransportHelper
* Default (Template) Project
*
* Created by Pierre Pollastri on 27/05/2016.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
object LedgerTransportHelper {
private val TAG_APDU = 0x05
def wrapCommandAPDU(channel: Int, command: Array[Byte], packetSize: Int): Array[Byte] = {
val output = new ByteArrayOutputStream()
if (packetSize < 3) {
throw new Exception("Can't handle Ledger framing with less than 3 bytes for the report")
}
var sequenceIdx = 0
var offset = 0
output.write(channel >> 8)
output.write(channel)
output.write(TAG_APDU)
output.write(sequenceIdx >> 8)
output.write(sequenceIdx)
sequenceIdx += 1
output.write(command.length >> 8)
output.write(command.length)
var blockSize = (if (command.length > packetSize - 7) packetSize - 7 else command.length)
output.write(command, offset, blockSize)
offset += blockSize
while (offset != command.length) {
output.write(channel >> 8)
output.write(channel)
output.write(TAG_APDU)
output.write(sequenceIdx >> 8)
output.write(sequenceIdx)
sequenceIdx += 1
blockSize = (if (command.length - offset > packetSize - 5) packetSize - 5 else command.length - offset)
output.write(command, offset, blockSize)
offset += blockSize
}
if ((output.size % packetSize) != 0) {
val padding = Array.ofDim[Byte](packetSize - (output.size % packetSize))
output.write(padding, 0, padding.length)
}
output.toByteArray()
}
def unwrapResponseAPDU(channel: Int, data: Array[Byte], packetSize: Int): Array[Byte] = {
val response = new ByteArrayOutputStream()
var offset = 0
var responseLength: Int = 0
var sequenceIdx = 0
if ((data == null) || (data.length < 7 + 5)) {
return null
}
if (data(offset) != (channel >> 8)) {
throw new Exception("Invalid channel")
}
offset += 1
if (data(offset) != (channel & 0xff)) {
throw new Exception("Invalid channel")
}
offset += 1
if (data(offset) != TAG_APDU) {
throw new Exception("Invalid tag")
}
offset += 1
if (data(offset) != 0x00) {
throw new Exception("Invalid sequence")
}
offset += 1
if (data(offset) != 0x00) {
throw new Exception("Invalid sequence")
}
offset += 1
responseLength = (data(offset) & 0xff) << 8
offset += 1
responseLength |= (data(offset) & 0xff)
offset += 1
if (data.length < 7 + responseLength) {
return null
}
var blockSize = if (responseLength > packetSize - 7) packetSize - 7 else responseLength
response.write(data, offset, blockSize)
offset += blockSize
while (response.size != responseLength) {
sequenceIdx += 1
if (offset == data.length) {
return null
}
if (data(offset) != (channel >> 8)) {
throw new Exception("Invalid channel")
}
offset += 1
if (data(offset) != (channel & 0xff)) {
throw new Exception("Invalid channel")
}
offset += 1
if (data(offset) != TAG_APDU) {
throw new Exception("Invalid tag")
}
offset += 1
if (data(offset) != (sequenceIdx >> 8)) {
throw new Exception("Invalid sequence")
}
offset += 1
if (data(offset) != (sequenceIdx & 0xff)) {
throw new Exception("Invalid sequence")
}
offset += 1
blockSize = if (responseLength - response.size > packetSize - 5) packetSize - 5 else responseLength - response.size
if (blockSize > data.length - offset) {
return null
}
response.write(data, offset, blockSize)
offset += blockSize
}
response.toByteArray
}
}
|
LedgerHQ/ledger-wallet-ripple
|
src/main/scala/co/ledger/wallet/web/ripple/core/device/LedgerTransportHelper.scala
|
Scala
|
mit
| 4,944 |
package scavlink.link.nav
import akka.actor.Props
import akka.actor.Status.Failure
import scavlink.link.Vehicle
import scavlink.link.mission._
import scavlink.link.nav.NavTellAPI._
import scavlink.link.operation._
import scavlink.link.telemetry.Telemetry
import scavlink.message.Mode
import scavlink.message.common.MissionStart
import scavlink.message.enums.MavCmd
import scavlink.state._
case class RunMission(mission: Mission, course: MissionCourse) extends NavOp {
val actorType = classOf[RunMissionActor]
}
case class RunMissionResult(vehicle: Vehicle, op: RunMission, last: MissionCourse) extends OpResult
case class RunMissionFailed(vehicle: Vehicle, op: RunMission, last: MissionCourse,
error: CourseError.Value, message: String) extends OpException
case class RunMissionStatus(vehicle: Vehicle, op: RunMission, last: MissionCourse, isNewWaypoint: Boolean) extends OpProgress {
val percent = 0
override def toString = {
val cmds = op.mission.map { c => MavCmd(c.command) }
s"RunMissionStatus(vehicle=${ vehicle.id } commands=$cmds last=$last isNewWaypoint=$isNewWaypoint)"
}
}
object RunMissionActor {
def props(vehicle: Vehicle) = Props(classOf[RunMissionActor], vehicle)
}
/**
* Executes a mission and tracks its progress.
* @author Nick Rossi
*/
class RunMissionActor(vehicle: Vehicle) extends VehicleOpActor[RunMission](vehicle) {
private case class MissionData(course: MissionCourse, receivedSystemState: Boolean) extends OpData
private case object WriteMission extends OpState
private case object StartMission extends OpState
private case object AbortMission extends OpState
when(Idle) {
case Event(op: RunMission, Uninitialized) =>
start(op, sender())
vehicle.missionCache ! SetMission(op.mission)
goto(WriteMission) using MissionData(op.course, false)
}
when(WriteMission) {
case Event(SetMissionResult(`vehicle`, _, mission), _) =>
vehicle.holdConversation(Conversation(ConversationStep(MissionStart())))
goto(StartMission)
case Event(Failure(SetMissionFailed(`vehicle`, _, result)), MissionData(course, _)) =>
stop using Finish(RunMissionFailed(vehicle, op, course, CourseError.SetupFailed,
s"SetMission failed with result $result"))
}
when(StartMission) {
case Event(_: ConversationSucceeded, MissionData(course, _)) =>
link.events.subscribe(self, Telemetry.subscribeTo(vehicle.id, course.states + classOf[SystemState]))
goto(Active)
case Event(Failure(f: ConversationFailed), MissionData(course, _)) =>
stop using Finish(RunMissionFailed(vehicle, op, course, CourseError.SetupFailed,
s"SetMode to Auto failed on ${f.request} with ${f.reply}"))
}
onTransition {
case StartMission -> Active =>
nextStateData match {
case MissionData(course, _) => origin ! RunMissionStatus(vehicle, op, course, true)
case _ => //
}
}
when(Active, stateTimeout = operationSettings.telemetryTimeout) {
case Event(Telemetry(_, state, _), MissionData(course, receivedSystemState)) =>
state match {
// only check if this is not the first SystemState, since it could have been sent before the mode change
case s: SystemState if receivedSystemState && s.specificMode != Mode.Auto(vehicleType) =>
stop using Finish(RunMissionResult(vehicle, op, course.completed))
case s =>
val newCourse = course.update(s)
val newReceived = receivedSystemState || state.isInstanceOf[SystemState]
if (newCourse eq course) {
if (receivedSystemState == newReceived) {
stay()
} else {
stay using MissionData(course, newReceived)
}
} else {
if (newCourse.current != course.current) {
origin ! RunMissionStatus(vehicle, op, newCourse, newCourse.waypoint != course.waypoint)
}
newCourse match {
case nc if nc.isComplete =>
stop using Finish(RunMissionResult(vehicle, op, nc))
case nc if nc.status == CourseStatus.Error =>
goto(AbortMission) using Finish(RunMissionFailed(vehicle, op, nc, CourseError.OffCourse,
"Vehicle is off course"))
case nc =>
stay using MissionData(nc, newReceived)
}
}
}
case Event(StateTimeout, MissionData(course, _)) =>
stop using Finish(RunMissionFailed(vehicle, op, course, CourseError.TelemetryTimeout,
s"Telemetry not received in ${ context.receiveTimeout }"))
}
onTransition {
case _ -> AbortMission =>
link.events.unsubscribe(self)
vehicle.setMode(Mode.Loiter)
}
when(AbortMission) {
case Event(_: ConversationSucceeded, finish: Finish) =>
stop using finish
case Event(Failure(r: ConversationFailed), finish: Finish) =>
val error = s"Failed to set Loiter mode: ${ r.reply }"
val newFinish = finish match {
case Finish(fin: RunMissionResult) => RunMissionFailed(vehicle, fin.op, fin.last, CourseError.TeardownFailed, error)
case Finish(fin: RunMissionFailed) => fin.copy(message = fin.message + " | " + error)
}
stop using Finish(newFinish)
}
/**
* If actor is stopping unexpectedly and we were in the middle of a course,
* set the vehicle to Loiter mode.
*/
override def unexpectedStop(state: OpState, data: OpData): Unit = state match {
case Active => vehicle.setMode(Mode.Loiter)
case _ => //
}
}
|
nickolasrossi/scavlink
|
src/main/scala/scavlink/link/nav/RunMission.scala
|
Scala
|
mit
| 5,581 |
package scala.tools.tastytest
import scala.collection.immutable.ArraySeq
import scala.util.{Try, Success, Properties}
import javax.tools.ToolProvider
object Javac extends Script.Command {
def javac(out: String, sources: String*): Try[Boolean] = {
val javaCompiler = ToolProvider.getSystemJavaCompiler
val javaCP = Properties.propOrEmpty("java.class.path")
def compile(args: String*) =
Try(javaCompiler.run(null, null, null, args:_*) == 0)
if (sources.isEmpty) {
Success(true)
}
else {
val classpath = Seq(out, javaCP).filter(!_.isEmpty).mkString(Files.classpathSep)
val settings = Array(
"-d", out,
"-classpath", classpath,
) ++ sources
compile(ArraySeq.unsafeWrapArray(settings):_*)
}
}
val commandName: String = "javac"
val describe: String = s"$commandName <out: Directory> <src: File>"
def process(args: String*): Int = {
if (args.length != 2) {
println(red(s"please provide two arguments in sub-command: $describe"))
return 1
}
val Seq(out, src) = args: @unchecked
val success = javac(out, src).get
if (success) 0 else 1
}
}
|
scala/scala
|
src/tastytest/scala/tools/tastytest/Javac.scala
|
Scala
|
apache-2.0
| 1,164 |
package mesosphere.marathon
package util
import mesosphere.AkkaUnitTest
import scala.concurrent.Future
import scala.concurrent.duration._
class TimeoutTest extends AkkaUnitTest {
"Timeout" when {
"async" should {
"complete" in {
Timeout(1.second)(Future.successful(1)).futureValue should equal(1)
}
"fail if the method fails" in {
val failure = Timeout(1.second)(Future.failed(new IllegalArgumentException())).failed.futureValue
failure shouldBe a[IllegalArgumentException]
}
"fail with a timeout exception if the method took too long" in {
val failure = Timeout(1.milli)(Future(Thread.sleep(1000))).failed.futureValue
failure shouldBe a[TimeoutException]
}
}
"blocking" should {
"complete" in {
Timeout.blocking(1.second)(1).futureValue should equal(1)
}
"fail if the method fails" in {
val failure = Timeout.blocking(1.second)(throw new IllegalArgumentException).failed.futureValue
failure shouldBe a[IllegalArgumentException]
}
"fail with a timeout if the method took too long" in {
val failure = Timeout.blocking(1.milli)(Thread.sleep(1000)).failed.futureValue
failure shouldBe a[TimeoutException]
}
}
}
}
|
gsantovena/marathon
|
src/test/scala/mesosphere/marathon/util/TimeoutTest.scala
|
Scala
|
apache-2.0
| 1,285 |
/*
* sbt-haxe
* Copyright 2014 深圳岂凡网络有限公司 (Shenzhen QiFun Network Corp., LTD)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.microbuilder.sbtHaxe
import HaxeConfigurations._
import HaxeKeys._
import sbt.Keys._
import sbt._
/**
* A Plugin used to compile Haxe sources to Flash swf file.
*/
object HaxeFlashPlugin extends AutoPlugin {
override final def requires = BaseHaxePlugin
override final lazy val projectSettings: Seq[Setting[_]] = {
super.projectSettings ++
sbt.addArtifact(artifact in packageBin in HaxeFlash, packageBin in HaxeFlash) ++
inConfig(Flash)(SbtHaxe.baseHaxeSettings) ++
inConfig(TestFlash)(SbtHaxe.baseHaxeSettings) ++
inConfig(HaxeFlash)(SbtHaxe.baseHaxeSettings) ++
inConfig(HaxeFlash)(SbtHaxe.extendSettings) ++
inConfig(TestHaxeFlash)(SbtHaxe.baseHaxeSettings) ++
inConfig(TestHaxeFlash)(SbtHaxe.extendTestSettings) ++
SbtHaxe.injectSettings(HaxeFlash, Flash) ++
SbtHaxe.injectSettings(TestHaxeFlash, TestFlash) ++
(for {
injectConfiguration <- Seq(Flash, TestFlash)
setting <- Seq(
haxePlatformName in injectConfiguration := "swf",
target in haxe in injectConfiguration := {
if ((isLibrary in injectConfiguration).value) {
(sourceManaged in injectConfiguration).value / raw"""${name.value}.swc"""
} else {
(sourceManaged in injectConfiguration).value / raw"""${name.value}.swf"""
}
},
haxeOutputPath in injectConfiguration := Some((target in haxe in injectConfiguration).value)
)
} yield setting) ++
Seq(
haxeXmls in Compile ++= (haxeXml in Flash).value,
haxeXmls in Test ++= (haxeXml in TestFlash).value,
doxRegex in Compile := SbtHaxe.buildDoxRegex((sourceDirectories in HaxeFlash).value),
doxRegex in Test := SbtHaxe.buildDoxRegex((sourceDirectories in TestHaxeFlash).value),
ivyConfigurations += Haxe,
ivyConfigurations += TestHaxe,
ivyConfigurations += HaxeFlash,
ivyConfigurations += TestHaxeFlash)
}
}
|
ThoughtWorksInc/sbt-haxe
|
src/main/scala/com/thoughtworks/microbuilder/sbtHaxe/HaxeFlashPlugin.scala
|
Scala
|
apache-2.0
| 2,680 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openwhisk.common.tracing
import java.util.concurrent.TimeUnit
import brave.Tracing
import brave.opentracing.BraveTracer
import brave.sampler.Sampler
import com.github.benmanes.caffeine.cache.{Caffeine, Ticker}
import io.opentracing.propagation.{Format, TextMapExtractAdapter, TextMapInjectAdapter}
import io.opentracing.util.GlobalTracer
import io.opentracing.{Span, SpanContext, Tracer}
import pureconfig._
import pureconfig.generic.auto._
import org.apache.openwhisk.common.{LogMarkerToken, TransactionId}
import org.apache.openwhisk.core.ConfigKeys
import zipkin2.reporter.okhttp3.OkHttpSender
import zipkin2.reporter.{AsyncReporter, Sender}
import scala.collection.JavaConverters._
import scala.collection.mutable
import scala.concurrent.duration.Duration
/**
* OpenTracing based implementation for tracing
*/
class OpenTracer(val tracer: Tracer, tracingConfig: TracingConfig, ticker: Ticker = SystemTicker) extends WhiskTracer {
val spanMap = configureCache[String, List[Span]]()
val contextMap = configureCache[String, SpanContext]()
/**
* Start a Trace for given service.
*
* @param transactionId transactionId to which this Trace belongs.
* @return TracedRequest which provides details about current service being traced.
*/
override def startSpan(logMarker: LogMarkerToken, transactionId: TransactionId): Unit = {
//initialize list for this transactionId
val spanList = spanMap.getOrElse(transactionId.meta.id, Nil)
val spanBuilder = tracer
.buildSpan(logMarker.action)
.withTag("transactionId", transactionId.meta.id)
val active = spanList match {
case Nil =>
//Check if any active context then resume from that else create a fresh span
contextMap
.get(transactionId.meta.id)
.map(spanBuilder.asChildOf)
.getOrElse(spanBuilder.ignoreActiveSpan())
.startActive(true)
.span()
case head :: _ =>
//Create a child span of current head
spanBuilder.asChildOf(head).startActive(true).span()
}
//add active span to list
spanMap.put(transactionId.meta.id, active :: spanList)
}
/**
* Finish a Trace associated with given transactionId.
*
* @param transactionId
*/
override def finishSpan(transactionId: TransactionId): Unit = {
clear(transactionId, withErrorMessage = None)
}
/**
* Register error
*
* @param transactionId
*/
override def error(transactionId: TransactionId, message: => String): Unit = {
clear(transactionId, withErrorMessage = Some(message))
}
/**
* Get the current TraceContext which can be used for downstream services
*
* @param transactionId
* @return
*/
override def getTraceContext(transactionId: TransactionId): Option[Map[String, String]] = {
spanMap
.get(transactionId.meta.id)
.flatMap(_.headOption)
.map { span =>
val map = mutable.Map.empty[String, String]
tracer.inject(span.context(), Format.Builtin.TEXT_MAP, new TextMapInjectAdapter(map.asJava))
map.toMap
}
}
/**
* Get the current TraceContext which can be used for downstream services
*
* @param transactionId
* @return
*/
override def setTraceContext(transactionId: TransactionId, context: Option[Map[String, String]]) = {
context.foreach { scalaMap =>
val ctx: SpanContext = tracer.extract(Format.Builtin.TEXT_MAP, new TextMapExtractAdapter(scalaMap.asJava))
contextMap.put(transactionId.meta.id, ctx)
}
}
private def clear(transactionId: TransactionId, withErrorMessage: Option[String]): Unit = {
spanMap.get(transactionId.meta.id).foreach {
case head :: Nil =>
withErrorMessage.foreach(setErrorTags(head, _))
head.finish()
spanMap.remove(transactionId.meta.id)
contextMap.remove(transactionId.meta.id)
case head :: tail =>
withErrorMessage.foreach(setErrorTags(head, _))
head.finish()
spanMap.put(transactionId.meta.id, tail)
case Nil =>
}
}
private def setErrorTags(span: Span, message: => String): Unit = {
span.setTag("error", true)
span.setTag("message", message)
}
private def configureCache[T, R](): collection.concurrent.Map[T, R] =
Caffeine
.newBuilder()
.ticker(ticker)
.expireAfterAccess(tracingConfig.cacheExpiry.toSeconds, TimeUnit.SECONDS)
.build()
.asMap()
.asScala
.asInstanceOf[collection.concurrent.Map[T, R]]
}
trait WhiskTracer {
def startSpan(logMarker: LogMarkerToken, transactionId: TransactionId): Unit = {}
def finishSpan(transactionId: TransactionId): Unit = {}
def error(transactionId: TransactionId, message: => String): Unit = {}
def getTraceContext(transactionId: TransactionId): Option[Map[String, String]] = None
def setTraceContext(transactionId: TransactionId, context: Option[Map[String, String]]): Unit = {}
}
object WhiskTracerProvider {
val tracingConfig = loadConfigOrThrow[TracingConfig](ConfigKeys.tracing)
val tracer: WhiskTracer = createTracer(tracingConfig)
private def createTracer(tracingConfig: TracingConfig): WhiskTracer = {
tracingConfig.zipkin match {
case Some(zipkinConfig) => {
if (!GlobalTracer.isRegistered) {
val sender: Sender = OkHttpSender.create(zipkinConfig.generateUrl)
val spanReporter = AsyncReporter.create(sender)
val braveTracing = Tracing
.newBuilder()
.localServiceName(tracingConfig.component)
.spanReporter(spanReporter)
.sampler(Sampler.create(zipkinConfig.sampleRate.toFloat))
.build()
//register with OpenTracing
GlobalTracer.register(BraveTracer.create(braveTracing))
sys.addShutdownHook({ spanReporter.close() })
}
}
case None =>
}
if (GlobalTracer.isRegistered)
new OpenTracer(GlobalTracer.get(), tracingConfig)
else
NoopTracer
}
}
private object NoopTracer extends WhiskTracer
case class TracingConfig(component: String, cacheExpiry: Duration, zipkin: Option[ZipkinConfig] = None)
case class ZipkinConfig(url: String, sampleRate: String) {
def generateUrl = s"$url/api/v2/spans"
}
object SystemTicker extends Ticker {
override def read() = {
System.nanoTime()
}
}
|
jasonpet/openwhisk
|
common/scala/src/main/scala/org/apache/openwhisk/common/tracing/OpenTracingProvider.scala
|
Scala
|
apache-2.0
| 7,151 |
package suiryc.scala.javafx.util
import javafx.{util => jfxu}
object Callback {
import scala.language.implicitConversions
implicit def fn1ToCallback[P, R](fn: P => R): jfxu.Callback[P, R] = {
new jfxu.Callback[P, R] {
override def call(p: P): R =
fn(p)
}
}
}
|
swhgoon/suiryc-scala
|
javafx/src/main/scala/suiryc/scala/javafx/util/Callback.scala
|
Scala
|
gpl-3.0
| 292 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.catalyst
import java.math.BigInteger
import java.sql.{Date, Timestamp}
import org.apache.spark.SparkFunSuite
import org.apache.spark.sql.types._
case class PrimitiveData(
intField: Int,
longField: Long,
doubleField: Double,
floatField: Float,
shortField: Short,
byteField: Byte,
booleanField: Boolean)
case class NullableData(
intField: java.lang.Integer,
longField: java.lang.Long,
doubleField: java.lang.Double,
floatField: java.lang.Float,
shortField: java.lang.Short,
byteField: java.lang.Byte,
booleanField: java.lang.Boolean,
stringField: String,
decimalField: java.math.BigDecimal,
dateField: Date,
timestampField: Timestamp,
binaryField: Array[Byte])
case class OptionalData(
intField: Option[Int],
longField: Option[Long],
doubleField: Option[Double],
floatField: Option[Float],
shortField: Option[Short],
byteField: Option[Byte],
booleanField: Option[Boolean],
structField: Option[PrimitiveData])
case class ComplexData(
arrayField: Seq[Int],
arrayField1: Array[Int],
arrayField2: List[Int],
arrayFieldContainsNull: Seq[java.lang.Integer],
mapField: Map[Int, Long],
mapFieldValueContainsNull: Map[Int, java.lang.Long],
structField: PrimitiveData,
nestedArrayField: Array[Array[Int]])
case class GenericData[A](
genericField: A)
case class MultipleConstructorsData(a: Int, b: String, c: Double) {
def this(b: String, a: Int) = this(a, b, c = 1.0)
}
class ScalaReflectionSuite extends SparkFunSuite {
import org.apache.spark.sql.catalyst.ScalaReflection._
test("primitive data") {
val schema = schemaFor[PrimitiveData]
assert(schema === Schema(
StructType(Seq(
StructField("intField", IntegerType, nullable = false),
StructField("longField", LongType, nullable = false),
StructField("doubleField", DoubleType, nullable = false),
StructField("floatField", FloatType, nullable = false),
StructField("shortField", ShortType, nullable = false),
StructField("byteField", ByteType, nullable = false),
StructField("booleanField", BooleanType, nullable = false))),
nullable = true))
}
test("nullable data") {
val schema = schemaFor[NullableData]
assert(schema === Schema(
StructType(Seq(
StructField("intField", IntegerType, nullable = true),
StructField("longField", LongType, nullable = true),
StructField("doubleField", DoubleType, nullable = true),
StructField("floatField", FloatType, nullable = true),
StructField("shortField", ShortType, nullable = true),
StructField("byteField", ByteType, nullable = true),
StructField("booleanField", BooleanType, nullable = true),
StructField("stringField", StringType, nullable = true),
StructField("decimalField", DecimalType.SYSTEM_DEFAULT, nullable = true),
StructField("dateField", DateType, nullable = true),
StructField("timestampField", TimestampType, nullable = true),
StructField("binaryField", BinaryType, nullable = true))),
nullable = true))
}
test("optional data") {
val schema = schemaFor[OptionalData]
assert(schema === Schema(
StructType(Seq(
StructField("intField", IntegerType, nullable = true),
StructField("longField", LongType, nullable = true),
StructField("doubleField", DoubleType, nullable = true),
StructField("floatField", FloatType, nullable = true),
StructField("shortField", ShortType, nullable = true),
StructField("byteField", ByteType, nullable = true),
StructField("booleanField", BooleanType, nullable = true),
StructField("structField", schemaFor[PrimitiveData].dataType, nullable = true))),
nullable = true))
}
test("complex data") {
val schema = schemaFor[ComplexData]
assert(schema === Schema(
StructType(Seq(
StructField(
"arrayField",
ArrayType(IntegerType, containsNull = false),
nullable = true),
StructField(
"arrayField1",
ArrayType(IntegerType, containsNull = false),
nullable = true),
StructField(
"arrayField2",
ArrayType(IntegerType, containsNull = false),
nullable = true),
StructField(
"arrayFieldContainsNull",
ArrayType(IntegerType, containsNull = true),
nullable = true),
StructField(
"mapField",
MapType(IntegerType, LongType, valueContainsNull = false),
nullable = true),
StructField(
"mapFieldValueContainsNull",
MapType(IntegerType, LongType, valueContainsNull = true),
nullable = true),
StructField(
"structField",
StructType(Seq(
StructField("intField", IntegerType, nullable = false),
StructField("longField", LongType, nullable = false),
StructField("doubleField", DoubleType, nullable = false),
StructField("floatField", FloatType, nullable = false),
StructField("shortField", ShortType, nullable = false),
StructField("byteField", ByteType, nullable = false),
StructField("booleanField", BooleanType, nullable = false))),
nullable = true),
StructField(
"nestedArrayField",
ArrayType(ArrayType(IntegerType, containsNull = false), containsNull = true)))),
nullable = true))
}
test("generic data") {
val schema = schemaFor[GenericData[Int]]
assert(schema === Schema(
StructType(Seq(
StructField("genericField", IntegerType, nullable = false))),
nullable = true))
}
test("tuple data") {
val schema = schemaFor[(Int, String)]
assert(schema === Schema(
StructType(Seq(
StructField("_1", IntegerType, nullable = false),
StructField("_2", StringType, nullable = true))),
nullable = true))
}
test("get data type of a value") {
// BooleanType
assert(BooleanType === typeOfObject(true))
assert(BooleanType === typeOfObject(false))
// BinaryType
assert(BinaryType === typeOfObject("string".getBytes))
// StringType
assert(StringType === typeOfObject("string"))
// ByteType
assert(ByteType === typeOfObject(127.toByte))
// ShortType
assert(ShortType === typeOfObject(32767.toShort))
// IntegerType
assert(IntegerType === typeOfObject(2147483647))
// LongType
assert(LongType === typeOfObject(9223372036854775807L))
// FloatType
assert(FloatType === typeOfObject(3.4028235E38.toFloat))
// DoubleType
assert(DoubleType === typeOfObject(1.7976931348623157E308))
// DecimalType
assert(DecimalType.SYSTEM_DEFAULT ===
typeOfObject(new java.math.BigDecimal("1.7976931348623157E318")))
// DateType
assert(DateType === typeOfObject(Date.valueOf("2014-07-25")))
// TimestampType
assert(TimestampType === typeOfObject(Timestamp.valueOf("2014-07-25 10:26:00")))
// NullType
assert(NullType === typeOfObject(null))
def typeOfObject1: PartialFunction[Any, DataType] = typeOfObject orElse {
case value: java.math.BigInteger => DecimalType.SYSTEM_DEFAULT
case value: java.math.BigDecimal => DecimalType.SYSTEM_DEFAULT
case _ => StringType
}
assert(DecimalType.SYSTEM_DEFAULT === typeOfObject1(
new BigInteger("92233720368547758070")))
assert(DecimalType.SYSTEM_DEFAULT === typeOfObject1(
new java.math.BigDecimal("1.7976931348623157E318")))
assert(StringType === typeOfObject1(BigInt("92233720368547758070")))
def typeOfObject2: PartialFunction[Any, DataType] = typeOfObject orElse {
case value: java.math.BigInteger => DecimalType.SYSTEM_DEFAULT
}
intercept[MatchError](typeOfObject2(BigInt("92233720368547758070")))
def typeOfObject3: PartialFunction[Any, DataType] = typeOfObject orElse {
case c: Seq[_] => ArrayType(typeOfObject3(c.head))
}
assert(ArrayType(IntegerType) === typeOfObject3(Seq(1, 2, 3)))
assert(ArrayType(ArrayType(IntegerType)) === typeOfObject3(Seq(Seq(1, 2, 3))))
}
test("convert PrimitiveData to catalyst") {
val data = PrimitiveData(1, 1, 1, 1, 1, 1, true)
val convertedData = InternalRow(1, 1.toLong, 1.toDouble, 1.toFloat, 1.toShort, 1.toByte, true)
val dataType = schemaFor[PrimitiveData].dataType
assert(CatalystTypeConverters.createToCatalystConverter(dataType)(data) === convertedData)
}
test("convert Option[Product] to catalyst") {
val primitiveData = PrimitiveData(1, 1, 1, 1, 1, 1, true)
val data = OptionalData(Some(2), Some(2), Some(2), Some(2), Some(2), Some(2), Some(true),
Some(primitiveData))
val dataType = schemaFor[OptionalData].dataType
val convertedData = InternalRow(2, 2.toLong, 2.toDouble, 2.toFloat, 2.toShort, 2.toByte, true,
InternalRow(1, 1, 1, 1, 1, 1, true))
assert(CatalystTypeConverters.createToCatalystConverter(dataType)(data) === convertedData)
}
test("infer schema from case class with multiple constructors") {
val dataType = schemaFor[MultipleConstructorsData].dataType
dataType match {
case s: StructType =>
// Schema should have order: a: Int, b: String, c: Double
assert(s.fieldNames === Seq("a", "b", "c"))
assert(s.fields.map(_.dataType) === Seq(IntegerType, StringType, DoubleType))
}
}
}
|
ArvinDevel/onlineAggregationOnSparkV2
|
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/ScalaReflectionSuite.scala
|
Scala
|
apache-2.0
| 10,326 |
package com.asto.dop.api.processor
import java.net.URL
import java.text.SimpleDateFormat
import java.util.Date
import com.asto.dop.api.{APIModel, Startup}
import com.asto.dop.core.CoreModel
import com.asto.dop.core.helper.KafkaHelper
import com.ecfront.common.Resp
import com.typesafe.scalalogging.slf4j.LazyLogging
import io.vertx.core.{AsyncResult, Future, Handler}
object MessageProcessor extends LazyLogging {
private var kafkaHelper: KafkaHelper[String, String] = _
private val df = new SimpleDateFormat("yyyyMMddHHmmss")
def process(apiMessage: APIModel, callback: => Resp[String] => Unit): Unit = {
basePackageMessage(apiMessage, {
msgResult =>
if (msgResult) {
val msgStr:String=msgResult.body
kafkaHelper.send(msgStr, {
kafkaResult =>
callback(kafkaResult)
})
} else {
callback(msgResult)
}
})
}
def init(): Unit = {
val topic = Startup.config.getJsonObject("producer").getString("topic")
val metadataBrokerList = Startup.config.getJsonObject("producer").getString("metadata.broker.list")
Startup.vertx.executeBlocking(new Handler[Future[Void]] {
override def handle(event: Future[Void]): Unit = {
kafkaHelper = KafkaHelper[String,String](topic,metadataBrokerList).init()
event.complete()
}
}, new Handler[AsyncResult[Void]] {
override def handle(event: AsyncResult[Void]): Unit = {
}
})
}
private def basePackageMessage(apiMessage: APIModel, callback: => Resp[CoreModel] => Unit): Unit = {
val url = if (apiMessage.url != null && apiMessage.url.trim.nonEmpty) {
apiMessage.url.trim
} else {
callback(Resp.badRequest("缺少参数:【url】"))
return
}
val msg_type = if (apiMessage.msg_type != null && apiMessage.msg_type.trim.nonEmpty) {
apiMessage.msg_type.trim
} else {
callback(Resp.badRequest("缺少参数:【msg_type】"))
return
}
val urlObj = new URL(url)
val path = urlObj.getPath
val query = urlObj.getQuery
val occur_time = if (apiMessage.occur_time != null && apiMessage.occur_time.trim.nonEmpty) {
apiMessage.occur_time.trim
} else {
df.format(new Date)
}
val referer = if (apiMessage.referer != null && apiMessage.referer.trim.nonEmpty) {
apiMessage.referer.trim
} else {
""
}
val user_id = if (apiMessage.user_id != null && apiMessage.user_id.trim.nonEmpty) {
apiMessage.user_id.trim
} else {
""
}
val user_ip = if (apiMessage.user_ip != null && apiMessage.user_ip.trim.nonEmpty) {
apiMessage.user_ip.trim
} else {
""
}
val cookie_id = if (apiMessage.cookie_id != null && apiMessage.cookie_id.trim.nonEmpty) {
apiMessage.cookie_id.trim
} else {
""
}
val cookies = if (apiMessage.cookies != null && apiMessage.cookies.trim.nonEmpty) {
apiMessage.cookies.trim
} else {
""
}
val message = CoreModel(occur_time, url, referer, path, query, user_id, user_ip, cookie_id, cookies, msg_type)
callback(Resp.success(message))
}
}
|
zj-lingxin/dop
|
source/api/src/main/scala/com/asto/dop/api/processor/MessageProcessor.scala
|
Scala
|
mit
| 3,161 |
package com.softwaremill.streams
import akka.actor.ActorSystem
import akka.stream.stage.{GraphStageLogic, GraphStage}
import akka.stream._
import akka.stream.scaladsl._
import akka.stream.scaladsl.GraphDSL.Implicits._
import scala.concurrent.Await
import scala.concurrent.duration._
import scalaz.\\/-
import scalaz.concurrent.Task
import scalaz.stream.{wye, async, Process}
import com.softwaremill.streams.util.Timed._
trait ParallelProcessing {
def run(in: List[Int]): List[Int]
}
object AkkaStreamsParallelProcessing extends ParallelProcessing {
override def run(in: List[Int]) = {
val out = Sink.fold[List[Int], Int](Nil) { case (l, e) => l.+:(e)}
val g = GraphDSL.create(out) { implicit builder => sink =>
val start = Source(in)
val split = builder.add(new SplitStage[Int](el => if (el % 2 == 0) Left(el) else Right(el)))
val merge = builder.add(Merge[Int](2))
val f = Flow[Int].map { el => Thread.sleep(1000L); el * 2 }.addAttributes(Attributes.asyncBoundary)
start ~> split.in
split.out0 ~> f ~> merge
split.out1 ~> f ~> merge
merge ~> sink
ClosedShape
}
implicit val system = ActorSystem()
implicit val mat = ActorMaterializer()
try Await.result(RunnableGraph.fromGraph(g).run(), 1.hour).reverse finally system.terminate()
}
}
class SplitStage[T](splitFn: T => Either[T, T]) extends GraphStage[FanOutShape2[T, T, T]] {
val in = Inlet[T]("SplitStage.in")
val out0 = Outlet[T]("SplitStage.out0")
val out1 = Outlet[T]("SplitStage.out1")
override def shape = new FanOutShape2[T, T, T](in, out0, out1)
override def createLogic(inheritedAttributes: Attributes) = new GraphStageLogic(shape) {
setHandler(in, ignoreTerminateInput)
setHandler(out0, eagerTerminateOutput)
setHandler(out1, eagerTerminateOutput)
def doRead(): Unit = {
read(in)(
el => splitFn(el).fold(doEmit(out0, _), doEmit(out1, _)),
() => completeStage()
)
}
def doEmit(out: Outlet[T], el: T): Unit = emit(out, el, doRead _)
override def preStart() = doRead()
}
}
object ScalazStreamsParallelProcessing extends ParallelProcessing {
def run(in: List[Int]): List[Int] = {
val start = Process(in: _*)
val queueLimit = 1
val left = async.boundedQueue[Int](queueLimit)
val right = async.boundedQueue[Int](queueLimit)
val enqueue: Process[Task, Unit] = start.zip(left.enqueue.zip(right.enqueue))
.map { case (el, (lEnqueue, rEnqueue)) =>
if (el % 2 == 0) lEnqueue(el) else rEnqueue(el)
}.eval.onComplete(Process.eval_(left.close) ++ Process.eval_(right.close))
val processElement = (el: Int) => Task { Thread.sleep(1000L); el * 2 }
val lDequeue = left.dequeue.evalMap(processElement)
val rDequeue = right.dequeue.evalMap(processElement)
val dequeue = lDequeue merge rDequeue
enqueue
.wye(dequeue)(wye.either)
.collect { case \\/-(el) => el }
.runLog.run.toList
}
}
object ParallelProcessingRunner extends App {
val impls = List(
("scalaz", ScalazStreamsParallelProcessing),
("akka", AkkaStreamsParallelProcessing)
)
for ((name, impl) <- impls) {
val (r, time) = timed { impl.run(List(1, 2, 3, 4, 5)) }
println(f"$name%-10s $r%-35s ${time/1000.0d}%4.2fs")
}
}
|
softwaremill/streams-tests
|
src/main/scala/com/softwaremill/streams/ParallelProcessing.scala
|
Scala
|
apache-2.0
| 3,343 |
/*
* Copyright (C) Lightbend Inc. <https://www.lightbend.com>
*/
package docs.scaladsl.mb
import com.lightbend.lagom.scaladsl.api.ServiceCall
import com.lightbend.lagom.scaladsl.persistence.EventStreamElement
import com.lightbend.lagom.scaladsl.persistence.PersistentEntityRegistry
import com.lightbend.lagom.scaladsl.api.broker.Topic
import com.lightbend.lagom.scaladsl.broker.TopicProducer
/**
* Implementation of the HelloService.
*/
class HelloServiceImpl(persistentEntityRegistry: PersistentEntityRegistry) extends HelloService {
override def hello(id: String) = ServiceCall { _ =>
// Look up the Hello entity for the given ID.
val ref = persistentEntityRegistry.refFor[HelloEntity](id)
// Ask the entity the Hello command.
ref.ask(Hello(id, None))
}
override def useGreeting(id: String) = ServiceCall { request =>
// Look up the Hello entity for the given ID.
val ref = persistentEntityRegistry.refFor[HelloEntity](id)
// Tell the entity to use the greeting message specified.
ref.ask(UseGreetingMessage(request.message))
}
//#implement-topic
override def greetingsTopic(): Topic[GreetingMessage] =
TopicProducer.singleStreamWithOffset { fromOffset =>
persistentEntityRegistry
.eventStream(HelloEventTag.INSTANCE, fromOffset)
.map(ev => (convertEvent(ev), ev.offset))
}
private def convertEvent(helloEvent: EventStreamElement[HelloEvent]): GreetingMessage = {
helloEvent.event match {
case GreetingMessageChanged(msg) => GreetingMessage(msg)
}
}
//#implement-topic
}
|
lagom/lagom
|
docs/manual/scala/guide/broker/code/docs/scaladsl/mb/HelloServiceImpl.scala
|
Scala
|
apache-2.0
| 1,579 |
package edu.ucsc.dbtune.cli
import scala.actors.Actor
import scala.actors.Actor._
import java.lang.Integer
import java.sql.SQLException
import java.util.HashSet
import java.util.Iterator
import java.util.Set
import edu.ucsc.dbtune.DatabaseSystem
import edu.ucsc.dbtune.metadata.Index
import edu.ucsc.dbtune.util.Environment
import edu.ucsc.dbtune.util.Environment._
import edu.ucsc.dbtune.viz.VisualizationFactory._
import edu.ucsc.dbtune.workload.SQLStatement
import edu.ucsc.dbtune.workload.Workload
/**
* The CLI interface to WFIT. Registers WFIT advisor to the given stream.
*
* @param db
* the database on which WFIT will be executed
* @param wl
* workload that WFIT will be listening to
* @param initialSet
* an (optional) initial candidate set
* @author Ivo Jimenez
*/
class WFIT(
db: Database,
wl: WorkloadStream,
initialSet: Set[Index] = new HashSet[Index],
isPaused: Boolean = true,
stateCnt: Integer = getInstance.getMaxNumStates,
idxCnt: Integer = getInstance.getMaxNumIndexes,
histSize: Integer = getInstance.getIndexStatisticsWindow,
partitionIters: Integer = getInstance.getNumPartitionIterations)
extends edu.ucsc.dbtune.advisor.wfit.WFIT(
db.DBMS, wl.workloadReader.getWorkload, initialSet, isPaused, stateCnt,
idxCnt, histSize, partitionIters)
{
val workload = wl
val visualizer = newVisualizer(this)
def this(db: Database, workload: WorkloadStream, isPaused: Boolean) = {
this(db, workload, new HashSet[Index], isPaused,
getInstance.getMaxNumStates)
this.getRecommendationStatistics.setAlgorithmName("WFIT")
}
def this(db: Database, workload: WorkloadStream) = {
this(db, workload, new HashSet[Index], true, getInstance.getMaxNumStates)
this.getRecommendationStatistics.setAlgorithmName("WFIT")
}
def this(db: Database, workload: WorkloadStream, initialSet: Set[Index]) = {
this(db, workload, initialSet, true, getInstance.getMaxNumStates)
this.getRecommendationStatistics.setAlgorithmName("WFIT")
}
def this(db: Database, workload: WorkloadStream, stateCnt: Integer) = {
this(db, workload, new HashSet[Index], true, stateCnt)
this.getRecommendationStatistics.setAlgorithmName("WFIT" + stateCnt)
}
def this(db: Database, workload: WorkloadStream, name: String) = {
this(db, workload)
this.getRecommendationStatistics.setAlgorithmName(name)
}
override def voteUp(id: Integer) = { super.voteUp(id) }
override def voteDown(id: Integer) = { super.voteDown(id) }
}
object WFIT {
def show(wfit: WFIT) = {
wfit.visualizer.showit
}
}
|
dbgroup-at-ucsc/dbtune
|
extensions/cli/src/edu/ucsc/dbtune/cli/WFIT.scala
|
Scala
|
bsd-3-clause
| 2,619 |
package com.taig.tmpltr.engine.html.property
import com.taig.tmpltr.Property
trait link
{
class rel( rel: String ) extends Property( rel )
object rel
{
object alternate extends rel( "alternate" )
object archives extends rel( "archives" )
object author extends rel( "author" )
object bookmark extends rel( "bookmark" )
object external extends rel( "external" )
object first extends rel( "first" )
object help extends rel( "help" )
object icon extends rel( "icon" )
object last extends rel( "last" )
object license extends rel( "license" )
object next extends rel( "next" )
object no_follow extends rel( "nofollow" )
object no_referrer extends rel( "noreferrer" )
object pingback extends rel( "pingback" )
object prefetch extends rel( "prefetch" )
object previous extends rel( "prev" )
object search extends rel( "search" )
object sidebar extends rel( "sidebar" )
object stylesheet extends rel( "stylesheet" )
object tag extends rel( "tag" )
object up extends rel( "up" )
}
}
|
Taig/Play-Tmpltr
|
app/com/taig/tmpltr/engine/html/property/link.scala
|
Scala
|
mit
| 1,022 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ml.dmlc.mxnet
import ml.dmlc.mxnet.Base._
import ml.dmlc.mxnet.DType.DType
import ml.dmlc.mxnet.io.{MXDataPack, MXDataIter}
import org.slf4j.LoggerFactory
import scala.collection.immutable.ListMap
import scala.collection.mutable.ListBuffer
/**
* IO iterators for loading training & validation data
*/
object IO {
type IterCreateFunc = (Map[String, String]) => DataIter
type PackCreateFunc = (Map[String, String]) => DataPack
private val logger = LoggerFactory.getLogger(classOf[DataIter])
private val iterCreateFuncs: Map[String, IterCreateFunc] = initIOModule()
def MNISTIter: IterCreateFunc = iterCreateFuncs("MNISTIter")
def ImageRecordIter: IterCreateFunc = iterCreateFuncs("ImageRecordIter")
def CSVIter: IterCreateFunc = iterCreateFuncs("CSVIter")
def MNISTPack: PackCreateFunc = createMXDataPack("MNISTIter")
def ImageRecodePack: PackCreateFunc = createMXDataPack("ImageRecordIter")
def CSVPack: PackCreateFunc = createMXDataPack("CSVIter")
/**
* create iterator via iterName and params
* @param iterName name of iterator; "MNISTIter" or "ImageRecordIter"
* @param params parameters for create iterator
* @return created data iterator
*/
def createIterator(iterName: String, params: Map[String, String]): DataIter = {
iterCreateFuncs(iterName)(params)
}
/**
* create dataPack for iterator via itername and params
* @param iterName name of iterator: "MNISTIter" or "ImageRecordIter"
* @param params parameters for create iterator
* @return created dataPack
*/
def createMXDataPack(iterName: String)(params: Map[String, String]): DataPack = {
new MXDataPack(iterName, params)
}
/**
* initialize all IO creator Functions
* @return Map from name to iter creator function
*/
private def initIOModule(): Map[String, IterCreateFunc] = {
val IterCreators = new ListBuffer[DataIterCreator]
checkCall(_LIB.mxListDataIters(IterCreators))
IterCreators.map(makeIOIterator).toMap
}
private def makeIOIterator(handle: DataIterCreator): (String, IterCreateFunc) = {
val name = new RefString
val desc = new RefString
val argNames = new ListBuffer[String]
val argTypes = new ListBuffer[String]
val argDescs = new ListBuffer[String]
checkCall(_LIB.mxDataIterGetIterInfo(handle, name, desc, argNames, argTypes, argDescs))
val paramStr = Base.ctypes2docstring(argNames, argTypes, argDescs)
val docStr = s"${name.value}\\n${desc.value}\\n\\n$paramStr\\n"
logger.debug(docStr)
(name.value, creator(handle))
}
/**
* DataIter creator
* @param handle native memory ptr for the iterator
* @param params parameter passed to the iterator
* @return created DataIter
*/
private def creator(handle: DataIterCreator)(
params: Map[String, String]): DataIter = {
val out = new DataIterHandleRef
val keys = params.keys.toArray
val vals = params.values.toArray
checkCall(_LIB.mxDataIterCreateIter(handle, keys, vals, out))
val dataName = params.getOrElse("data_name", "data")
val labelName = params.getOrElse("label_name", "label")
new MXDataIter(out.value, dataName, labelName)
}
// Convert data into canonical form.
private[mxnet] def initData(data: IndexedSeq[NDArray],
allowEmpty: Boolean,
defaultName: String): IndexedSeq[(String, NDArray)] = {
require(data != null)
require(data != IndexedSeq.empty || allowEmpty)
if (data == IndexedSeq.empty) {
IndexedSeq()
} else if (data.length == 1) {
IndexedSeq((defaultName, data(0)))
} else {
data.zipWithIndex.map(item => {
(defaultName + "_" + item._2, item._1)
}).toIndexedSeq
}
}
}
/**
* class batch of data
*/
class DataBatch(val data: IndexedSeq[NDArray],
val label: IndexedSeq[NDArray],
val index: IndexedSeq[Long],
val pad: Int,
// the key for the bucket that should be used for this batch,
// for bucketing io only
val bucketKey: AnyRef = null,
// use ListMap to indicate the order of data/label loading
// (must match the order of input data/label)
private val providedData: ListMap[String, Shape] = null,
private val providedLabel: ListMap[String, Shape] = null) {
/**
* Dispose its data and labels
* The object shall never be used after it is disposed.
*/
def dispose(): Unit = {
if (data != null) {
data.foreach(arr => if (arr != null) arr.dispose())
}
if (label != null) {
label.foreach(arr => if (arr != null) arr.dispose())
}
}
// The name and shape of data
def provideData: ListMap[String, Shape] = providedData
// The name and shape of label
def provideLabel: ListMap[String, Shape] = providedLabel
}
/**
* DataIter object in mxnet.
*/
abstract class DataIter extends Iterator[DataBatch] {
/**
* reset the iterator
*/
def reset(): Unit
def batchSize: Int
/**
* get next data batch from iterator
* @return
*/
@throws(classOf[NoSuchElementException])
def next(): DataBatch = {
new DataBatch(getData(), getLabel(), getIndex(), getPad())
}
/**
* get data of current batch
* @return the data of current batch
*/
def getData(): IndexedSeq[NDArray]
/**
* Get label of current batch
* @return the label of current batch
*/
def getLabel(): IndexedSeq[NDArray]
/**
* Get the number of padding examples
* in current batch
* @return number of padding examples in current batch
*/
def getPad(): Int
/**
* Get the index of current batch
* @return the index of current batch
*/
def getIndex(): IndexedSeq[Long]
// The name and shape of data provided by this iterator
def provideData: ListMap[String, Shape]
// The name and shape of label provided by this iterator
def provideLabel: ListMap[String, Shape]
// For bucketing io only
// The bucket key for the default symbol.
def defaultBucketKey: AnyRef = null
}
/**
* pack of DataIter, use as Iterable class
*/
abstract class DataPack() extends Iterable[DataBatch] {
/**
* get data iterator
* @return DataIter
*/
def iterator: DataIter
}
// Named data desc description contains name, shape, type and other extended attributes.
case class DataDesc(name: String, shape: Shape,
dtype: DType = Base.MX_REAL_TYPE, layout: String = "NCHW") {
require(shape.length == layout.length, ("number of dimensions in shape :%d with" +
" shape: %s should match the length of the layout: %d with layout: %s").
format(shape.length, shape.toString, layout.length, layout))
override def toString(): String = {
s"DataDesc[$name,$shape,$dtype,$layout]"
}
}
object DataDesc {
/**
* Get the dimension that corresponds to the batch size.
* @param layout layout string. For example, "NCHW".
* @return An axis indicating the batch_size dimension. When data-parallelism is used,
* the data will be automatically split and concatenate along the batch_size dimension.
* Axis can be -1, which means the whole array will be copied
* for each data-parallelism device.
*/
def getBatchAxis(layout: Option[String]): Int = {
layout.map(_.indexOf('N')).getOrElse(0)
}
implicit def ListMap2Descs(shapes: ListMap[String, Shape]): IndexedSeq[DataDesc] = {
shapes.map { case (k, s) => new DataDesc(k, s) }.toIndexedSeq
}
}
|
jiajiechen/mxnet
|
scala-package/core/src/main/scala/ml/dmlc/mxnet/IO.scala
|
Scala
|
apache-2.0
| 8,340 |
package gh2011.models
import net.liftweb.json.JsonAST.JValue
case class SimplifiedActor(url: String, avatar_url: String)
object SimplifiedActor
{
def apply(json: JValue): Option[SimplifiedActor] =
{
val n2s = gh3.node2String(json)(_)
val n2l = gh3.node2Long(json)(_)
val url = n2s("url")
val avatar_url = n2s("avatar_url")
val params = Seq(url, avatar_url)
if(params.forall(_.isDefined))
Some(SimplifiedActor(url.get, avatar_url.get))
else None
}
}
|
mgoeminne/github_etl
|
src/main/scala/gh2011/models/SimplifiedActor.scala
|
Scala
|
mit
| 514 |
package com.godatadriven.twitter_classifier
import java.util.concurrent.{TimeUnit, TimeoutException}
import com.google.gson.Gson
import org.apache.spark.streaming.twitter.TwitterUtils
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.{Accumulator, SparkConf}
import org.neo4j.driver.internal.value.{ListValue, StringValue}
import org.neo4j.driver.v1.{GraphDatabase, Session, Value}
import twitter4j.Status
import scala.collection.JavaConversions._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
case class StoreToNeo4j(checkpointDirectory: String) {
val languages = Array[String]("en", "en-gb", "nl")
val insertStatement =
"""WITH {mentions} as mentions
|MERGE (u:User {username: {username}})
|CREATE (t:Tweet {text: {text}, language: {language}})
|CREATE (u)-[:TWEETS]->(t)
|foreach(name in mentions | MERGE (m:User {username: name}) CREATE (t)-[:MENTIONS]->(m))
""".stripMargin
private var gson = new Gson()
def run(): Unit = {
val streamingContext = StreamingContext.getOrCreate(checkpointDirectory, createStreamingContext)
streamingContext.start()
streamingContext.awaitTermination()
}
private def createStreamingContext(): StreamingContext = {
val sparkConfig = new SparkConf().setAppName("Spark Twitter Example")
sparkConfig.set("spark.streaming.backpressure.enabled", "true")
val streamingContext = new StreamingContext(sparkConfig, Seconds(1))
val failedMessages: Accumulator[Int] = streamingContext.sparkContext.accumulator(0, "failedMessages")
val successMessages: Accumulator[Int] = streamingContext.sparkContext.accumulator(0, "successMessages")
val allTweets = TwitterUtils.createStream(streamingContext, None)
allTweets.foreachRDD { rdd =>
rdd.foreachPartition { partition =>
val driver = GraphDatabase.driver("bolt://localhost")
val session = driver.session()
partition.foreach { record =>
try {
Await.ready(Future {
processRecord(session, record)
}, Duration.apply(100, TimeUnit.MILLISECONDS))
successMessages.add(1)
} catch {
case e: TimeoutException => failedMessages.add(1)
}
}
session.close()
driver.close()
}
}
streamingContext
}
def processRecord(session: Session, record: Status): Unit = {
if (shouldProcessRecord(record)) {
val user = record.getUser
val userName = new StringValue(user.getScreenName)
val text = new StringValue(record.getText)
val mentionNames: Array[Value] = record.getUserMentionEntities.map { x => new StringValue(x.getScreenName) }
val mentions = new ListValue(mentionNames: _*)
val tweet = scala.collection.mutable.Map[String, Value](
"username" -> userName,
"mentions" -> mentions,
"text" -> text,
"source" -> new StringValue(record.getSource),
"language" -> new StringValue(record.getUser.getLang.toLowerCase))
session.run(insertStatement, tweet)
}
}
def shouldProcessRecord(record: Status): Boolean = {
val language: String = record.getUser.getLang.toLowerCase
// !record.isRetweet && languages.contains(language)
true
}
}
|
rweverwijk/twitter-to-neo4j
|
src/main/scala/com/godatadriven/twitter_classifier/StoreToNeo4j.scala
|
Scala
|
apache-2.0
| 3,381 |
/*******************************************************************************
* Copyright (c) 2019. Carl Minden
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package com.anathema_roguelike
package main.ui.uielements.interactiveuielements.menus
import com.anathema_roguelike.main.Game
import com.anathema_roguelike.main.display.Color
import com.anathema_roguelike.main.display.Display.DisplayLayer
import com.anathema_roguelike.main.ui.uielements.interactiveuielements.{InteractiveUIElement, MouseCallback}
import com.anathema_roguelike.main.utilities.Utils
import com.anathema_roguelike.main.utilities.position.Point
abstract class AbstractMenuItem[T](menu: AbstractMenu[_], item: T, position: Point, background: Float)
extends InteractiveUIElement[T](position, Utils.getName(item).length, 1, background) {
def onSelect(menuItem: AbstractMenuItem[T]): Unit
private var focused = false
def getText: String = Utils.getName(item)
def select(): Unit = {
onSelect(this)
}
def focus(): Unit = {
focused = true
}
def unfocus(): Unit = {
focused = false
}
def getItem: T = item
def getMenu: AbstractMenu[_] = menu
override def registerMouseCallbacks(): Unit = {
val callback = new MouseCallback() {
override def onMouseover(): Unit = {
menu.setFocused(AbstractMenuItem.this)
}
override def onClick(): Unit = {
menu.setFocused(AbstractMenuItem.this)
select()
}
}
(0 until getWidth).foreach(i => {
Game.getInstance.getInput.registerMouseCallback(callback, Point(getX + i, getY))
})
}
override def processKeyEvent(key: Char, alt: Boolean, ctrl: Boolean, shift: Boolean): Unit = {
// TODO Auto-generated method stub
}
override def processScrollEvent(amount: Int) = false
override def renderContent(): Unit = {
val colors = if (focused) {
(Color.BLACK, Color.WHITE)
} else {
(Color.WHITE, Color.BLACK)
}
renderString(DisplayLayer.UI_FOREGROUND, DisplayLayer.UI_BACKGROUND, 0, 0, getText, colors._1, colors._2)
}
}
|
carlminden/anathema-roguelike
|
src/com/anathema_roguelike/main/ui/uielements/interactiveuielements/menus/AbstractMenuItem.scala
|
Scala
|
gpl-3.0
| 2,759 |
/**
* This software is licensed under the GNU Affero General Public License, quoted below.
*
* This file is a part of PowerAPI.
*
* Copyright (C) 2011-2014 Inria, University of Lille 1.
*
* PowerAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* PowerAPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with PowerAPI.
* If not, please consult http://www.gnu.org/licenses/agpl-3.0.html.
*/
package org.powerapi.core
import com.typesafe.config.Config
import java.io.{IOException, File}
import org.apache.logging.log4j.LogManager
import org.powerapi.core.FileHelper.using
import org.powerapi.core.target.{Application, Process, Target}
import scala.collection.JavaConversions._
import scala.sys.process._
/**
* This is not a monitoring target. It's an internal wrapper for the Thread IDentifier.
*
* @param tid: thread identifier
*
* @author <a href="mailto:[email protected]">Maxime Colmant</a>
*/
case class Thread(tid: Int)
/**
* Wrapper class for the time spent by the cpu in each frequency (if dvfs enabled).
*
* @author <a href="mailto:[email protected]">Aurélien Bourdon</a
* @author <a href="mailto:[email protected]">Maxime Colmant</a>
*/
case class TimeInStates(times: Map[Long, Long]) {
def -(that: TimeInStates) =
TimeInStates((for ((frequency, time) <- times) yield (frequency, time - that.times.getOrElse(frequency, 0: Long))).toMap)
}
/**
* Wrapper class for the global cpu times. It includes the global time and the time consumed by the CPU.
*
* @author <a href="mailto:[email protected]">Maxime Colmant</a>
*/
case class GlobalCpuTime(globalTime: Long, activeTime: Long)
/**
* Base trait use for implementing os specific methods.
*
* @author <a href="mailto:[email protected]">Maxime Colmant</a>
*/
trait OSHelper {
/**
* Get the list of frequencies available on the CPU.
*/
def getCPUFrequencies: Set[Long]
/**
* Get the list of processes behind an Application.
*
* @param application: targeted application.
*/
def getProcesses(application: Application): Set[Process]
/**
* Get the list of thread behind a Process.
*
* @param process: targeted process.
*/
def getThreads(process: Process): Set[Thread]
/**
* Get the process execution time on the cpu.
*
* @param process: targeted process
*/
def getProcessCpuTime(process: Process): Option[Long]
/**
* Get the global execution time for the cpu.
*/
def getGlobalCpuTime: GlobalCpuTime
/**
* Get how many time CPU spent under each frequency.
*/
def getTimeInStates: TimeInStates
/**
* Get the target cpu time.
*/
def getTargetCpuTime(target: Target): Option[Long] = {
target match {
case process: Process => getProcessCpuTime(process)
case application: Application => Some(
getProcesses(application).foldLeft(0: Long) {
(acc, process: Process) => {
getProcessCpuTime(process) match {
case Some(value) => acc + value
case _ => acc
}
}
}
)
case _ => None
}
}
}
/**
* Linux special helper.
π
* @author <a href="mailto:[email protected]">Maxime Colmant</a>
*/
class LinuxHelper extends OSHelper with Configuration {
private val log = LogManager.getLogger
private val PSFormat = """^\\s*(\\d+)\\s*""".r
private val GlobalStatFormat = """cpu\\s+([\\d\\s]+)""".r
private val TimeInStateFormat = """(\\d+)\\s+(\\d+)""".r
/**
* This file allows to get all the cpu frequencies with the help of procfs and cpufreq_utils.
*/
lazy val frequenciesPath = load { _.getString("powerapi.procfs.frequencies-path") } match {
case ConfigValue(path) if path.contains("%?core") => path
case _ => "/sys/devices/system/cpu/cpu%?core/cpufreq/scaling_available_frequencies"
}
/**
* This file allows to get all threads associated to one PID with the help of the procfs.
*/
lazy val taskPath = load { _.getString("powerapi.procfs.process-task-path") } match {
case ConfigValue(path) if path.contains("%?pid") => path
case _ => "/proc/%?pid/task"
}
/**
* Global stat file, giving global information of the system itself.
* Typically presents under /proc/stat.
*/
lazy val globalStatPath = load { _.getString("powerapi.procfs.global-path") } match {
case ConfigValue(path) => path
case _ => "/proc/stat"
}
/**
* Process stat file, giving information about the process itself.
* Typically presents under /proc/[pid]/stat.
*/
lazy val processStatPath = load { _.getString("powerapi.procfs.process-path") } match {
case ConfigValue(path) if path.contains("%?pid") => path
case _ => "/proc/%?pid/stat"
}
/**
* Time in state file, giving information about how many time CPU spent under each frequency.
*/
lazy val timeInStatePath = load { _.getString("powerapi.sysfs.timeinstates-path") } match {
case ConfigValue(path) => path
case _ => "/sys/devices/system/cpu/cpu%?index/cpufreq/stats/time_in_state"
}
/**
* CPU's topology.
*/
lazy val topology: Map[Int, Set[Int]] = load { conf =>
(for (item: Config <- conf.getConfigList("powerapi.cpu.topology"))
yield (item.getInt("core"), item.getDoubleList("indexes").map(_.toInt).toSet)).toMap
} match {
case ConfigValue(values) => values
case _ => Map()
}
def getCPUFrequencies: Set[Long] = {
(for(index <- topology.values.flatten) yield {
try {
using(frequenciesPath.replace("%?core", s"$index"))(source => {
log.debug("using {} as a frequencies path", frequenciesPath)
source.getLines.toIndexedSeq(0).split("\\\\s").map(_.toLong).toSet
})
}
catch {
case ioe: IOException => log.warn("i/o exception: {}", ioe.getMessage); Set[Long]()
}
}).flatten.toSet
}
def getProcesses(application: Application): Set[Process] = {
Seq("ps", "-C", application.name, "-o", "pid", "--no-headers").lineStream_!.map {
case PSFormat(pid) => Process(pid.toInt)
}.toSet
}
def getThreads(process: Process): Set[Thread] = {
val pidDirectory = new File(taskPath.replace("%?pid", s"${process.pid}"))
if (pidDirectory.exists && pidDirectory.isDirectory) {
/**
* The pid is removed because it corresponds to the main thread.
*/
pidDirectory.listFiles.filter(dir => dir.isDirectory && dir.getName != s"${process.pid}").map(dir => Thread(dir.getName.toInt)).toSet
}
else Set[Thread]()
}
def getProcessCpuTime(process: Process): Option[Long] = {
try {
using(processStatPath.replace("%?pid", s"${process.pid}"))(source => {
log.debug("using {} as a procfs process stat path", processStatPath)
val statLine = source.getLines.toIndexedSeq(0).split("\\\\s")
// User time + System time
Some(statLine(13).toLong + statLine(14).toLong)
})
}
catch {
case ioe: IOException => log.warn("i/o exception: {}", ioe.getMessage); None
}
}
def getGlobalCpuTime: GlobalCpuTime = {
try {
using(globalStatPath)(source => {
log.debug("using {} as a procfs global stat path", globalStatPath)
val cpuTimes = source.getLines.toIndexedSeq(0) match {
/**
* Exclude all guest columns, they are already added in utime column.
*
* @see http://lxr.free-electrons.com/source/kernel/sched/cputime.c#L165
*/
case GlobalStatFormat(times) => {
val globalTime = times.split("\\\\s").slice(0, 8).foldLeft(0: Long) {
(acc, x) => acc + x.toLong
}
val activeTime = globalTime - times.split("\\\\s")(3).toLong
GlobalCpuTime(globalTime, activeTime)
}
case _ => log.warn("unable to parse line from {}", globalStatPath); GlobalCpuTime(0, 0)
}
cpuTimes
})
}
catch {
case ioe: IOException => log.warn("i/o exception: {}", ioe.getMessage); GlobalCpuTime(0, 0)
}
}
def getTimeInStates: TimeInStates = {
val result = collection.mutable.HashMap[Long, Long]()
for(core <- topology.keys) {
try {
using(timeInStatePath.replace("%?index", s"$core"))(source => {
log.debug("using {} as a sysfs timeinstates path", timeInStatePath)
for(line <- source.getLines) {
line match {
case TimeInStateFormat(freq, t) => result += (freq.toLong -> (t.toLong + result.getOrElse(freq.toLong, 0l)))
case _ => log.warn("unable to parse line {} from file {}", line, timeInStatePath)
}
}
})
}
catch {
case ioe: IOException => log.warn("i/o exception: {}", ioe.getMessage);
}
}
TimeInStates(result.toMap[Long, Long])
}
}
|
rouvoy/powerapi
|
powerapi-core/src/main/scala/org/powerapi/core/OSHelper.scala
|
Scala
|
agpl-3.0
| 9,300 |
package notebook.front.third.bokeh
import io.continuum.bokeh.{Renderer, Plot}
/**
* Created by gerrit on 15.11.14.
*/
object PlotOps {
implicit class PlotOps(val plot: Plot) {
def +=(renderer: Renderer): Plot = {
plot.renderers := renderer :: plot.renderers.value
plot
}
def ++=(renderers: List[Renderer]): Plot = {
plot.renderers := renderers ++ plot.renderers.value
plot
}
}
}
|
vitan/spark-notebook
|
modules/common/src/main/scala/notebook/front/third/bokeh/PlotOps.scala
|
Scala
|
apache-2.0
| 430 |
package fr.inria.spirals.sigma.ttc14.fixml
import fr.unice.i3s.sigma.m2t.M2T
import fr.inria.spirals.sigma.ttc14.fixml.objlang.support.ObjLang
import fr.inria.spirals.sigma.ttc14.fixml.objlang.support.ObjLang._objlang._
class ObjLang2CPPClassHeader extends BaseObjLang2Class with ObjLang2CPP with ObjLang2CPPHeader {
override def header = {
super.header
source.fields map (_.type_) collect {
case x: Class => x
} map (_.cppHeaderFile) foreach { hdr ⇒
!s"#include ${hdr.quoted}"
}
!endl
}
override def genFields = {
!"public:" indent {
super.genFields
}
}
override def genField(c: Field) =
!s"${type2Code(c)} ${c.name};"
override def genConstructors = {
!"public:" indent {
super.genConstructors
}
}
override def genConstructor(c: Constructor) = {
val args = c.parameters map param2Code mkString (", ")
!s"${source.name}($args);"
!endl
}
}
|
fikovnik/ttc14-fixml-sigma
|
ttc14-fixml-extension-1/src/fr/inria/spirals/sigma/ttc14/fixml/ObjLang2CPPClassHeader.scala
|
Scala
|
epl-1.0
| 945 |
/*
* Copyright 2013 Georgia Tech Applied Research Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.gatech.gtri.typesafeconfigextensions.forwebapps
import org.specs2.mutable._
import edu.gatech.gtri.typesafeconfigextensions.forscala._
import edu.gatech.gtri.typesafeconfigextensions.factory.ConfigFactory.noBindings
import edu.gatech.gtri.typesafeconfigextensions.factory.PathSpecifications
class ServletContextDirectoryConfigSourceSpec extends Specification {
"ServletContextDirectoryConfigSource" >> {
"byKey" >> {
val source = new ServletContextDirectoryConfigSource(PathSpecifications.byKey("some.key"))
"toString" ! ( source.toString shouldEqual
"ConfigSource { servlet context relative to directory by key: some.key }" )
"with nothing bound" ! ( source.load(noBindings) shouldEqual Nil.toConfig )
}
}
}
|
gtri/typesafeconfig-extensions
|
for-webapps/src/test/scala/edu/gatech/gtri/typesafeconfigextensions/forwebapps/ServletContextDirectoryConfigSourceSpec.scala
|
Scala
|
apache-2.0
| 1,392 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.planner.plan.batch.sql
import org.apache.flink.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.descriptors.{FileSystem, OldCsv, Schema}
import org.apache.flink.table.planner.expressions.utils.Func0
import org.apache.flink.table.planner.utils.TableTestBase
import org.junit.{Before, Test}
class TableScanTest extends TableTestBase {
private val util = batchTestUtil()
@Before
def before(): Unit = {
util.tableEnv.registerFunction("my_udf", Func0)
util.addTable(
s"""
|create table computed_column_t(
| a int,
| b varchar,
| c as a + 1,
| d as to_timestamp(b),
| e as my_udf(a)
|) with (
| 'connector' = 'values',
| 'bounded' = 'true'
|)
""".stripMargin)
util.addTable(
s"""
|create table c_watermark_t(
| a int,
| b varchar,
| c as a + 1,
| d as to_timestamp(b),
| e as my_udf(a),
| WATERMARK FOR d AS d - INTERVAL '0.001' SECOND
|) with (
| 'connector' = 'values',
| 'bounded' = 'true'
|)
""".stripMargin)
}
@Test
def testLegacyTableSourceScan(): Unit = {
util.addTableSource[(Int, Long, String)]("MyTable", 'a, 'b, 'c)
util.verifyPlan("SELECT * FROM MyTable")
}
@Test
def testDDLTableScan(): Unit = {
util.addTable(
"""
|CREATE TABLE src (
| ts TIMESTAMP(3),
| a INT,
| b DOUBLE,
| WATERMARK FOR ts AS ts - INTERVAL '0.001' SECOND
|) WITH (
| 'connector' = 'values',
| 'bounded' = 'true'
|)
""".stripMargin)
util.verifyPlan("SELECT * FROM src WHERE a > 1")
}
@Test
def testScanOnUnboundedSource(): Unit = {
util.addTable(
"""
|CREATE TABLE src (
| ts TIMESTAMP(3),
| a INT,
| b DOUBLE,
| WATERMARK FOR ts AS ts - INTERVAL '0.001' SECOND
|) WITH (
| 'connector' = 'values',
| 'bounded' = 'false'
|)
""".stripMargin)
thrown.expect(classOf[ValidationException])
thrown.expectMessage("Cannot query on an unbounded source in batch mode, " +
"but 'default_catalog.default_database.src' is unbounded")
util.verifyPlan("SELECT * FROM src WHERE a > 1")
}
@Test
def testScanOnChangelogSource(): Unit = {
util.addTable(
"""
|CREATE TABLE src (
| ts TIMESTAMP(3),
| a INT,
| b DOUBLE
|) WITH (
| 'connector' = 'values',
| 'bounded' = 'true',
| 'changelog-mode' = 'I,UA,UB'
|)
""".stripMargin)
thrown.expect(classOf[UnsupportedOperationException])
thrown.expectMessage(
"Currently, batch mode only supports INSERT only source, " +
"but 'default_catalog.default_database.src' source produces not INSERT only messages")
util.verifyPlan("SELECT * FROM src WHERE a > 1")
}
@Test
def testDDLWithComputedColumn(): Unit = {
util.verifyPlan("SELECT * FROM computed_column_t")
}
@Test
def testDDLWithWatermarkComputedColumn(): Unit = {
util.verifyPlan("SELECT * FROM c_watermark_t")
}
@Test
def testTableApiScanWithComputedColumn(): Unit = {
util.verifyPlan(util.tableEnv.from("computed_column_t"))
}
@Test
def testTableApiScanWithWatermark(): Unit = {
util.verifyPlan(util.tableEnv.from("c_watermark_t"))
}
@Test
def testTableApiScanWithDDL(): Unit = {
util.addTable(
s"""
|create table t1(
| a int,
| b varchar
|) with (
| 'connector' = 'values',
| 'bounded' = 'true'
|)
""".stripMargin)
util.verifyPlan(util.tableEnv.from("t1"))
}
@Test
def testTableApiScanWithTemporaryTable(): Unit = {
util.tableEnv.connect(new FileSystem().path(tempFolder.newFile.getPath))
.withFormat(new OldCsv())
.withSchema(new Schema().field("word", DataTypes.STRING()))
.createTemporaryTable("t1")
util.verifyPlan(util.tableEnv.from("t1"))
}
}
|
tzulitai/flink
|
flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/planner/plan/batch/sql/TableScanTest.scala
|
Scala
|
apache-2.0
| 4,972 |
object Build extends android.AutoBuild
|
aafa/realm-sbt-plugin
|
src/sbt-test/sbt-realm-test/realm/project/Build.scala
|
Scala
|
mit
| 39 |
package org.xmly.thrall.rec.service
import org.springframework.stereotype.Component
import org.xmly.thrall.rec.protocol.RecRequest
import org.apache.spark.mllib.recommendation.MatrixFactorizationModel
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
@Component
class ScoreService {
val conf = new SparkConf().setAppName("ScorePredictor").setMaster("local[2]")
val sc = new SparkContext(conf)
val model = MatrixFactorizationModel.load(sc, "./score.model")
def estimateScore(req: RecRequest): Long = {
if (model != null) model.predict(req.uid, req.qid).toLong else -1L
}
}
|
gexiao01/thrall
|
thrall-rec/src/main/scala/org/xmly/thrall/rec/service/ScoreService.scala
|
Scala
|
apache-2.0
| 625 |
/*
* Copyright (c) 2014-2019 Israel Herraiz <[email protected]>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// --------------------
// Code for example 3.6
// --------------------
package chap03
object Ex06 {
def init[A](l: List[A]): List[A] = {
@annotation.tailrec
def loop(m: List[A], n: List[A]): List[A] = {
m match {
case Nil => n
case h :: Nil => n
case h :: t => loop(t, n :+ h)
}
}
loop(l, Nil)
}
}
|
iht/fpinscala
|
src/main/scala/chap03/ex06.scala
|
Scala
|
mit
| 1,512 |
package dsmoq.controllers
import scala.util.Failure
import scala.util.Success
import scala.util.Try
import org.scalatra.ActionResult
import org.scalatra.BadRequest
import org.scalatra.Forbidden
import org.scalatra.InternalServerError
import org.scalatra.NotFound
import org.scalatra.Ok
import org.slf4j.MarkerFactory
import com.typesafe.scalalogging.LazyLogging
import dsmoq.exceptions.AccessDeniedException
import dsmoq.exceptions.BadRequestException
import dsmoq.exceptions.InputCheckException
import dsmoq.exceptions.InputValidationException
import dsmoq.exceptions.NotAuthorizedException
import dsmoq.exceptions.NotFoundException
/**
* 入力検査異常を表す型
*
* @param key 入力検査異常が発生したキー
* @param value 入力検査異常の詳細メッセージ
*/
case class CheckError(key: String, value: String)
/**
* 処理結果のAjax表現を表す型
*
* @param A 処理結果の型
* @param status 処理結果のステータスメッセージ
* @param data 処理結果
*/
case class AjaxResponse[A](status: String, data: A = {})
/**
* 処理結果のAjax表現を表す型のコンパリオンオブジェクト
*/
object AjaxResponse extends LazyLogging {
/**
* ログマーカー
*/
val LOG_MARKER = MarkerFactory.getMarker("AJAX_RESPONSE_LOG")
/**
* 処理結果をActionResultに変換します。
*
* @param result 処理結果
* @return 処理結果のActionResult表現
*/
def toActionResult(result: Try[_]): ActionResult = {
result match {
case Success(()) => Ok(AjaxResponse("OK"))
case Success(x) => Ok(AjaxResponse("OK", x))
case Failure(e) => {
logger.info(LOG_MARKER, e.getMessage)
ResponseUtil.toActionResult(e)
}
}
}
}
/**
* レスポンス型変換ユーティリティ
*/
object ResponseUtil extends LazyLogging {
/**
* ログマーカー
*/
val LOG_MARKER = MarkerFactory.getMarker("RESPONSE_UTIL_LOG")
/**
* 処理結果をActionResultに変換します。
*
* @param result 処理結果
* @return 処理結果のActionResult表現
*/
def toActionResult(result: Try[_]): ActionResult = {
result match {
case Success(x) => Ok(x)
case Failure(e) => {
logger.info(LOG_MARKER, e.getMessage)
toActionResult(e)
}
}
}
/**
* 処理結果の例外をActionResultに変換します。
*
* @param e 処理結果の例外
* @return 例外のActionResult表現
*/
def toActionResult(e: Throwable): ActionResult = {
e match {
case e: NotAuthorizedException => Forbidden(AjaxResponse("Unauthorized", e.getMessage)) // 403
case e: AccessDeniedException => Forbidden(AjaxResponse("AccessDenied", e.getMessage)) // 403
case e: NotFoundException => NotFound(AjaxResponse("NotFound")) // 404
case e: InputCheckException => {
if (e.isUrlParam) {
NotFound(AjaxResponse("Illegal Argument", CheckError(e.target, e.message))) // 404
} else {
BadRequest(AjaxResponse("Illegal Argument", CheckError(e.target, e.message))) // 400
}
}
case e: InputValidationException => BadRequest(AjaxResponse("BadRequest", e.getErrorMessage())) // 400
case e: BadRequestException => BadRequest(AjaxResponse("BadRequest", e.getMessage)) // 400
case e => {
logger.error(LOG_MARKER, e.getMessage, e)
InternalServerError(AjaxResponse("NG")) // 500
}
}
}
/**
* レスポンスヘッダのContent-Dispositionに設定する文字列を返す。
*
* @param fileName ファイル名
* @return Content-Dispositionに設定する文字列
*/
def generateContentDispositionValue(fileName: String): String = {
"attachment; filename*=UTF-8''" + java.net.URLEncoder.encode(fileName.split(Array[Char]('\\', '/')).last, "UTF-8")
}
}
|
nkawa/dsmoq
|
server/apiServer/src/main/scala/dsmoq/controllers/ResponseUtil.scala
|
Scala
|
apache-2.0
| 3,873 |
/*
* Copyright 2009 Ilja Booij
*
* This file is part of GarminTrainer.
*
* GarminTrainer is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GarminTrainer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GarminTrainer. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.iljabooij.garmintrainer.parser.digester
import nl.iljabooij.garmintrainer.model.DateTime
import nl.iljabooij.garmintrainer.model.Length
import nl.iljabooij.garmintrainer.model.MeasuredTrackPoint
/**
* An Implementation of {@link MeasuredTrackPoint} that uses a {@link TrackPointType}
* object to get it's values.
* @author ilja
*
*/
class DigesterMeasuredTrackPoint(delegate: TrackPointType)
extends MeasuredTrackPoint with NotNull {
override def heartRate = delegate.heartRate
override def altitude = delegate.altitude
override def distance = delegate.distance
override def time = delegate.time
override def latitude = delegate.latitude
override def longitude = delegate.longitude
}
|
chmandrade/garmintrainer
|
src/main/scala/nl/iljabooij/garmintrainer/parser/digester/DigesterMeasuredTrackPoint.scala
|
Scala
|
gpl-3.0
| 1,457 |
object Test extends App {
def nested: Unit = {
sealed trait Foo
object Foo {
trait Bar extends Foo
trait Baz extends Foo
}
val subs = Macros.knownDirectSubclasses[Foo]
assert(subs.toSet == Set("Bar", "Baz"))
}
nested
}
|
scala/scala
|
test/files/run/t7046-2/Test_2.scala
|
Scala
|
apache-2.0
| 259 |
package com.typesafe.slick.testkit.tests
import org.junit.Assert._
import com.typesafe.slick.testkit.util.{TestkitTest, TestDB}
class ExecutorTest(val tdb: TestDB) extends TestkitTest {
import tdb.profile.simple._
def test {
object T extends Table[Int]("t") {
def a = column[Int]("a")
def * = a
}
T.ddl.create
T.insertAll(2, 3, 1, 5, 4)
val q = T.sortBy(_.a).map(_.a)
val r1 = q.list
val r1t: List[Int] = r1
assertEquals(List(1, 2, 3, 4, 5), r1t)
val r2 = q.run
val r2t: Seq[Int] = r2
assertEquals(List(1, 2, 3, 4, 5), r2t)
val r3 = q.length.run
val r3t: Int = r3
assertEquals(5, r3t)
}
}
|
boldradius/slick
|
slick-testkit/src/main/scala/com/typesafe/slick/testkit/tests/ExecutorTest.scala
|
Scala
|
bsd-2-clause
| 672 |
/***
* Copyright 2014 Rackspace US, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rackspace.com.papi.components.checker.wadl
import com.rackspace.com.papi.components.checker.{LogAssertions, TestConfig}
import org.apache.logging.log4j.Level
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import scala.xml._
@RunWith(classOf[JUnitRunner])
class WADLCheckerSpec extends BaseCheckerSpec with LogAssertions {
//
// Register some common prefixes, you'll need the for XPath
// assertions.
//
register ("xsd", "http://www.w3.org/2001/XMLSchema")
register ("wadl","http://wadl.dev.java.net/2009/02")
register ("xsl","http://www.w3.org/1999/XSL/Transform")
register ("chk","http://www.rackspace.com/repose/wadl/checker")
register ("tst","http://www.rackspace.com/repose/wadl/checker/step/test")
feature ("The WADLCheckerBuilder can correctly transforma a WADL into checker format") {
info ("As a developer")
info ("I want to be able to transform a WADL which references multiple XSDs into a ")
info ("a description of a machine that can validate the API in checker format")
info ("so that an API validator can process the checker format to validate the API")
scenario("The WADL does not contain any resources") {
Given("a WADL with no resources")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource/>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
Then("The checker should contain a single start node")
assert (checker, "count(//chk:step[@type='START']) = 1")
And("The only steps accessible from start should be the fail states")
val path = allStepsFromStart(checker)
assert (path, "count(//chk:step) = 3")
assert (path, "/chk:checker/chk:step[@type='START']")
assert (path, "/chk:checker/chk:step[@type='METHOD_FAIL']")
assert (path, "/chk:checker/chk:step[@type='URL_FAIL']")
And("There should exist a direct path from start to each failed state")
assert (checker, Start, URLFail)
assert (checker, Start, MethodFail)
}
scenario("The WADL contains an explicit root element, with no methods on the root") {
Given("a WADL with an explicit root element, no methods on root")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="/">
<resource path="element">
<method name="GET">
<response status="200"/>
</method>
</resource>
</resource>
</resources>
</application>
val checker = builder.build (inWADL, stdConfig)
Then("The checker should contain an URL node only for the element")
assert (checker, "count(/chk:checker/chk:step[@type='URL']) = 1")
And ("The checker should contain a single GET method")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
And ("The checker should NOT contian URL steps with a match == '/'")
assert (checker, "count(/chk:checker/chk:step[@type='URL' and @match='/']) = 0")
And ("The URL path should simply be from Start to the element")
assert (checker, Start, URL("element"), Method("GET"))
And ("The Start state and each URL state should contain a path to MethodFail and URLFail")
assert (checker, Start, URLFail)
assert (checker, Start, MethodFail)
assert (checker, URL("element"), URLFail)
assert (checker, URL("element"), MethodFail)
}
scenario("The WADL contains an explicit root element, with methods on the root") {
Given("a WADL with an explicit root element, methods on root")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="/">
<method name="GET">
<response status="200"/>
</method>
<resource path="element">
<method name="GET">
<response status="200"/>
</method>
</resource>
</resource>
</resources>
</application>
val checker = builder.build (inWADL, stdConfig)
Then("The checker should contain an URL node only for the element")
assert (checker, "count(/chk:checker/chk:step[@type='URL']) = 1")
And ("The checker should contain two GET methods")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 2")
And ("The checker should NOT contian URL steps with a match == '/'")
assert (checker, "count(/chk:checker/chk:step[@type='URL' and @match='/']) = 0")
And ("The URL path should exist from Start to the element")
assert (checker, Start, URL("element"), Method("GET"))
And ("The URL path should exist from START directly to GET method")
assert (checker, Start, Method("GET"))
And ("The Start state and each URL state should contain a path to MethodFail and URLFail")
assert (checker, Start, URLFail)
assert (checker, Start, MethodFail)
assert (checker, URL("element"), URLFail)
assert (checker, URL("element"), MethodFail)
}
scenario("The WADL contains a / path deeper in the URI structure") {
Given("a WADL that contains a / path deefer in the URI structure")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="/">
<method name="GET">
<response status="200"/>
</method>
<resource path="element">
<resource path="/">
<method name="GET">
<response status="200"/>
</method>
</resource>
</resource>
</resource>
</resources>
</application>
val checker = builder.build (inWADL, stdConfig)
Then("The checker should contain an URL node only for the element")
assert (checker, "count(/chk:checker/chk:step[@type='URL']) = 1")
And ("The checker should contain two GET methods")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 2")
And ("The checker should NOT contian URL steps with a match == '/'")
assert (checker, "count(/chk:checker/chk:step[@type='URL' and @match='/']) = 0")
And ("The URL path should exist from Start to the element")
assert (checker, Start, URL("element"), Method("GET"))
And ("The URL path should exist from START directly to GET method")
assert (checker, Start, Method("GET"))
And ("The Start state and each URL state should contain a path to MethodFail and URLFail")
assert (checker, Start, URLFail)
assert (checker, Start, MethodFail)
assert (checker, URL("element"), URLFail)
assert (checker, URL("element"), MethodFail)
}
scenario("The WADL contains a / path deeper in the URI structure (with sub elements)") {
Given("a WADL that contains a / path deeper in the URI structure")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="/">
<method name="GET">
<response status="200"/>
</method>
<resource path="element">
<resource path="/">
<method name="GET">
<response status="200"/>
</method>
<resource path="element2">
<method name="POST">
<response status="200"/>
</method>
</resource>
</resource>
</resource>
</resource>
</resources>
</application>
val checker = builder.build (inWADL, stdConfig)
Then("The checker should contain an URL node and element2")
assert (checker, "count(/chk:checker/chk:step[@type='URL']) = 2")
And ("The checker should contain two GET methods")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 2")
And ("The checker should contain a POST methods")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 1")
And ("The checker should NOT contian URL steps with a match == '/'")
assert (checker, "count(/chk:checker/chk:step[@type='URL' and @match='/']) = 0")
And ("The URL path should exist from Start to the element")
assert (checker, Start, URL("element"), Method("GET"))
And ("The URL path should exist from Start to the element2")
assert (checker, Start, URL("element"), URL("element2"), Method("POST"))
And ("The URL path should exist from START directly to GET method")
assert (checker, Start, Method("GET"))
And ("The Start state and each URL state should contain a path to MethodFail and URLFail")
assert (checker, Start, URLFail)
assert (checker, Start, MethodFail)
assert (checker, URL("element"), URLFail)
assert (checker, URL("element"), MethodFail)
assert (checker, URL("element2"), URLFail)
assert (checker, URL("element2"), MethodFail)
}
scenario("The WADL contains a / path deeper in the URI structure (with sub elements one of which is a fixed template param)") {
Given("a WADL that contains a / path deeper in the URI structure")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="/">
<method name="GET">
<response status="200"/>
</method>
<resource path="{elm}">
<param name="elm" style="template" type="xsd:string" fixed="element"/>
<resource path="/">
<method name="GET">
<response status="200"/>
</method>
<resource path="element2">
<method name="POST">
<response status="200"/>
</method>
</resource>
</resource>
</resource>
</resource>
</resources>
</application>
val checker = builder.build (inWADL, stdConfig)
Then("The checker should contain an URL node and element2")
assert (checker, "count(/chk:checker/chk:step[@type='URL']) = 2")
And ("The checker should contain two GET methods")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 2")
And ("The checker should contain a POST methods")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 1")
And ("The checker should NOT contian URL steps with a match == '/'")
assert (checker, "count(/chk:checker/chk:step[@type='URL' and @match='/']) = 0")
And ("The URL path should exist from Start to the element")
assert (checker, Start, URL("element"), Method("GET"))
And ("The URL path should exist from Start to the element2")
assert (checker, Start, URL("element"), URL("element2"), Method("POST"))
And ("The URL path should exist from START directly to GET method")
assert (checker, Start, Method("GET"))
And ("The Start state and each URL state should contain a path to MethodFail and URLFail")
assert (checker, Start, URLFail)
assert (checker, Start, MethodFail)
assert (checker, URL("element"), URLFail)
assert (checker, URL("element"), MethodFail)
assert (checker, URL("element2"), URLFail)
assert (checker, URL("element2"), MethodFail)
}
scenario("The WADL contains a / path deeper in the URI structure (with sub elements and multiple nested '/')") {
Given("a WADL that contains a / path deeper in the URI structure")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="/">
<method name="GET">
<response status="200"/>
</method>
<resource path="element">
<resource path="/">
<resource path="/">
<method name="GET">
<response status="200"/>
</method>
<resource path="element2">
<method name="POST">
<response status="200"/>
</method>
</resource>
</resource>
</resource>
</resource>
</resource>
</resources>
</application>
val checker = builder.build (inWADL, stdConfig)
Then("The checker should contain an URL node and element2")
assert (checker, "count(/chk:checker/chk:step[@type='URL']) = 2")
And ("The checker should contain two GET methods")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 2")
And ("The checker should contain a POST methods")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 1")
And ("The checker should NOT contian URL steps with a match == '/'")
assert (checker, "count(/chk:checker/chk:step[@type='URL' and @match='/']) = 0")
And ("The URL path should exist from Start to the element")
assert (checker, Start, URL("element"), Method("GET"))
And ("The URL path should exist from Start to the element2")
assert (checker, Start, URL("element"), URL("element2"), Method("POST"))
And ("The URL path should exist from START directly to GET method")
assert (checker, Start, Method("GET"))
And ("The Start state and each URL state should contain a path to MethodFail and URLFail")
assert (checker, Start, URLFail)
assert (checker, Start, MethodFail)
assert (checker, URL("element"), URLFail)
assert (checker, URL("element"), MethodFail)
assert (checker, URL("element2"), URLFail)
assert (checker, URL("element2"), MethodFail)
}
//
// The following scenarios test a single resource located at
// /path/to/my/resource with a GET, DELETE, and POST method. They are
// equivalent but they are written in slightly different WADL
// form the assertions below must apply to all of them.
// Only application/xml is allowed in the POST operation
//
//
def singlePathAssertions (checker : NodeSeq) : Unit = {
Then("The checker should contain an URL node for each path step")
assert (checker, "count(/chk:checker/chk:step[@type='URL']) = 4")
And ("The checker should contain a GET, DELETE, and POST method")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='GET']")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='DELETE']")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='POST']")
And ("The path from the start should contain all URL nodes in order")
And ("it should end in the GET and a DELETE method node")
assert (checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("GET"))
assert (checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("DELETE"))
assert (checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("POST"), ReqType("(application/xml)(;.*)?"))
And ("The Start state and each URL state should contain a path to MethodFail and URLFail")
assert (checker, Start, URLFail)
assert (checker, Start, MethodFail)
assert (checker, URL("path"), URLFail)
assert (checker, URL("path"), MethodFail)
assert (checker, URL("to"), URLFail)
assert (checker, URL("to"), MethodFail)
assert (checker, URL("my"), URLFail)
assert (checker, URL("my"), MethodFail)
assert (checker, URL("resource"), URLFail)
assert (checker, URL("resource"), MethodFail)
And ("The POST method should contain an ReqTypeFail")
assert (checker, Method("POST"), ReqTypeFail)
}
scenario("The WADL contains a single multi-path resource") {
Given("a WADL that contains a single multi-path resource with a GET, DELETE, and POST method")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource">
<method name="GET">
<response status="200 203"/>
</method>
<method name="DELETE">
<response status="200"/>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
<response status="200"/>
</method>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
singlePathAssertions(checker)
}
scenario("The WADL contains a single multi-path resource ending in /") {
Given("a WADL that contains a single multi-path resource with a GET, DELETE, and POST method and ending in /")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource/">
<method name="GET">
<response status="200 203"/>
</method>
<method name="DELETE">
<response status="200"/>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
<response status="200"/>
</method>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
singlePathAssertions(checker)
}
scenario("The WADL contains a single multi-path resource in tree form") {
Given("a WADL that contains a single multi-path resource in tree form with a GET, DELETE, and POST method")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path">
<resource path="to">
<resource path="my">
<resource path="resource">
<method name="GET">
<response status="200 203"/>
</method>
<method name="DELETE">
<response status="200"/>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
<response status="200"/>
</method>
</resource>
</resource>
</resource>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
singlePathAssertions(checker)
}
scenario("The WADL contains a single multi-path resource in mixed form") {
Given("a WADL that contains a single multi-path resource in mixed form with a GET, DELETE, and POST method")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my">
<resource path="resource">
<method name="GET">
<response status="200 203"/>
</method>
<method name="DELETE">
<response status="200"/>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
<response status="200"/>
</method>
</resource>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
singlePathAssertions(checker)
}
scenario("The WADL contains a single multi-path resource with a method referece") {
Given("a WADL that contains a single multi-path resource with a method reference")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource">
<method href="#getMethod" />
<method name="DELETE">
<response status="200"/>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
<response status="200"/>
</method>
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
singlePathAssertions(checker)
}
scenario("The WADL contains a single multi-path resource with a resource type") {
Given("a WADL that contains a single multi-path resource with a resource type")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource" type="#test"/>
</resources>
<resource_type id="test">
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
<method name="DELETE">
<response status="200"/>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
<response status="200"/>
</method>
</resource_type>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
singlePathAssertions(checker)
}
scenario("The WADL contains a single multi-path resource with a resource type with method references") {
Given("a WADL that contains a single multi-path resource with a resource type with method references")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource" type="#test"/>
</resources>
<resource_type id="test">
<method href="#getMethod" />
<method name="DELETE">
<response status="200"/>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
<response status="200"/>
</method>
</resource_type>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
singlePathAssertions(checker)
}
//
// The following scenarios test two resources located at
// /path/to/my/resource with a GET and a DELETE method and
// /path/to/my/other_resource with a GET and POST method. They
// are equivalent but they are written in slightly different WADL
// form. The assertions below must apply to all of them.
//
def multiplePathAssertions (checker : NodeSeq) : Unit = {
Then("The checker should contain an URL node for each path step")
assert (checker, "count(/chk:checker/chk:step[@type='URL']) = 5")
And ("The checker should contain a GET, POST, and DELETE method")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='GET']")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='DELETE']")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='POST']")
And ("The path from the start should contain all URL nodes in order")
And ("it should end in the right method")
assert (checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("GET"))
assert (checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("DELETE"))
assert (checker, Start, URL("path"), URL("to"), URL("my"), URL("other_resource"), Method("GET"))
assert (checker, Start, URL("path"), URL("to"), URL("my"), URL("other_resource"), Method("POST"))
And ("The Start state and each URL state should contain a path to MethodFail and URLFail")
assert (checker, Start, URLFail)
assert (checker, Start, MethodFail)
assert (checker, URL("path"), URLFail)
assert (checker, URL("path"), MethodFail)
assert (checker, URL("to"), URLFail)
assert (checker, URL("to"), MethodFail)
assert (checker, URL("my"), URLFail)
assert (checker, URL("my"), MethodFail)
assert (checker, URL("resource"), URLFail)
assert (checker, URL("resource"), MethodFail)
assert (checker, URL("other_resource"), URLFail)
assert (checker, URL("other_resource"), MethodFail)
}
scenario("The WADL contains multiple, related paths") {
Given ("a WADL with multiple related paths")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource">
<method name="GET">
<response status="200 203"/>
</method>
<method name="DELETE">
<response status="200"/>
</method>
</resource>
<resource path="path/to/my/other_resource">
<method name="GET">
<response status="200 203"/>
</method>
<method name="POST">
<response status="200"/>
</method>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
multiplePathAssertions(checker)
}
scenario("The WADL in tree format contains multiple, related paths") {
Given ("a WADL in tree format with multiple related paths")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path">
<resource path="to">
<resource path="my">
<resource path="resource">
<method name="GET">
<response status="200 203"/>
</method>
<method name="DELETE">
<response status="200"/>
</method>
</resource>
<resource path="other_resource">
<method name="GET">
<response status="200 203"/>
</method>
<method name="POST">
<response status="200"/>
</method>
</resource>
</resource>
</resource>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
multiplePathAssertions(checker)
}
scenario("The WADL in mix format contains multiple, related paths") {
Given ("a WADL in mix format with multiple related paths")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my">
<resource path="resource">
<method name="GET">
<response status="200 203"/>
</method>
<method name="DELETE">
<response status="200"/>
</method>
</resource>
<resource path="other_resource">
<method name="GET">
<response status="200 203"/>
</method>
<method name="POST">
<response status="200"/>
</method>
</resource>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
multiplePathAssertions(checker)
}
//
// The following scenarios test two resources located at
// /path/to/my/resource with a GET and a DELETE method and
// /path/to/my/other_resource with a GET and POST method. They
// are equivalent but they are written in slightly different WADL
// form. The assertions below must apply to all of them.
//
def multipleUnrelatedPathAssertions (checker : NodeSeq) : Unit = {
Then("The checker should contain an URL node for each path step")
assert (checker, "count(/chk:checker/chk:step[@type='URL']) = 8")
And ("The checker should contain a GET, POST, and DELETE method")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='GET']")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='DELETE']")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='POST']")
And ("The path from the start should contain all URL nodes in order")
And ("it should end in the right method")
assert (checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("GET"))
assert (checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("DELETE"))
assert (checker, Start, URL("this"), URL("is"), URL("my"), URL("other_resource"), Method("GET"))
assert (checker, Start, URL("this"), URL("is"), URL("my"), URL("other_resource"), Method("POST"))
And ("The Start state and each URL state should contain a path to MethodFail and URLFail")
assert (checker, Start, URLFail)
assert (checker, Start, MethodFail)
assert (checker, URL("this"), URLFail)
assert (checker, URL("this"), MethodFail)
assert (checker, URL("is"), URLFail)
assert (checker, URL("is"), MethodFail)
assert (checker, URL("path"), URLFail)
assert (checker, URL("path"), MethodFail)
assert (checker, URL("to"), URLFail)
assert (checker, URL("to"), MethodFail)
assert (checker, URL("my"), URLFail)
assert (checker, URL("my"), MethodFail)
assert (checker, URL("resource"), URLFail)
assert (checker, URL("resource"), MethodFail)
assert (checker, URL("other_resource"), URLFail)
assert (checker, URL("other_resource"), MethodFail)
}
scenario("The WADL contains multiple, unrelated paths") {
Given ("a WADL with multiple unrelated paths")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource">
<method name="GET">
<response status="200 203"/>
</method>
<method name="DELETE">
<response status="200"/>
</method>
</resource>
<resource path="this/is/my/other_resource">
<method name="GET">
<response status="200 203"/>
</method>
<method name="POST">
<response status="200"/>
</method>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
multipleUnrelatedPathAssertions(checker)
}
scenario("The WADL in tree format contains multiple, unrelated paths") {
Given ("a WADL in tree format with multiple unrelated paths")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path">
<resource path="to">
<resource path="my">
<resource path="resource">
<method name="GET">
<response status="200 203"/>
</method>
<method name="DELETE">
<response status="200"/>
</method>
</resource>
</resource>
</resource>
</resource>
<resource path="this">
<resource path="is">
<resource path="my">
<resource path="other_resource">
<method name="GET">
<response status="200 203"/>
</method>
<method name="POST">
<response status="200"/>
</method>
</resource>
</resource>
</resource>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
multipleUnrelatedPathAssertions(checker)
}
scenario("The WADL in mix format contains multiple, unrelated paths") {
Given ("a WADL in mix format with multiple unrelated paths")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my">
<resource path="resource">
<method name="GET">
<response status="200 203"/>
</method>
<method name="DELETE">
<response status="200"/>
</method>
</resource>
</resource>
<resource path="this/is/my">
<resource path="other_resource">
<method name="GET">
<response status="200 203"/>
</method>
<method name="POST">
<response status="200"/>
</method>
</resource>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
multipleUnrelatedPathAssertions(checker)
}
scenario("The WADL contains method ids") {
Given ("a WADL with method IDs")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource">
<method id="getResource" name="GET">
<response status="200 203"/>
</method>
<method id="deleteResource" name="DELETE">
<response status="200"/>
</method>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
Then("The method nodes should contain a resource label with the id")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD']) = 2")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='GET' and @label='getResource']")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='DELETE' and @label='deleteResource']")
}
scenario("The WADL contains method ids specifed in docs") {
Given ("a WADL with method IDs")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource">
<method id="getResource" name="GET">
<doc title="Get My Resource"/>
<response status="200 203"/>
</method>
<method id="deleteResource" name="DELETE">
<response status="200"/>
</method>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
Then("The method nodes should contain a resource label with the id")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD']) = 2")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='GET' and @label='Get My Resource']")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='DELETE' and @label='deleteResource']")
}
scenario("The WADL contains method ids specifed in docs (multiple docs)") {
Given ("a WADL with method IDs")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource">
<method id="getResource" name="GET">
<doc title="Get My Resource"/>
<doc title="Alt get my resource"/>
<response status="200 203"/>
</method>
<method id="deleteResource" name="DELETE">
<response status="200"/>
</method>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
Then("The method nodes should contain a resource label with the id")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD']) = 2")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='GET' and @label='Get My Resource']")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='DELETE' and @label='deleteResource']")
}
scenario("The WADL contains an initial invisible node") {
Given ("a WADL with an initial invisble node")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource rax:invisible="true" path="path">
<method name="GET">
<response status="200 203"/>
</method>
<resource path="to">
<resource path="my">
<resource path="resource">
<method name="GET">
<response status="200 203"/>
</method>
<method name="DELETE">
<response status="200"/>
</method>
</resource>
</resource>
</resource>
</resource>
</resources>
</application>
When ("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
Then("All paths should be available as defined in the WADL...")
assert (checker, Start, URL("path"), Method("GET"))
assert (checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("GET"))
assert (checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("DELETE"))
And("Paths should also be accessible directly from start")
assert (checker, Start, Method("GET"))
assert (checker, Start, URL("to"), URL("my"), URL("resource"), Method("GET"))
assert (checker, Start, URL("to"), URL("my"), URL("resource"), Method("DELETE"))
}
//
// The following scenarios test a string template parameter at the
// of a resource path (/path/to/my/resource/{id}. They are
// equivalent but they are written in slightly different WADL
// form the assertions below must apply to all of them.
//
def stringTemplateAtEndAssertions (checker : NodeSeq) : Unit = {
Then("The checker should contain an URL node for each path step")
assert (checker, "count(/chk:checker/chk:step[@type='URL']) = 5")
And ("The checker should contain a GET method")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='GET']")
And ("The path from the start should contain all URL nodes including a .*")
And ("it should end in the GET method node")
assert (checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), URL("(?s).*"), Method("GET"))
And ("The Start state and each URL state should contain a path to MethodFail and URLFail")
assert (checker, Start, URLFail)
assert (checker, Start, MethodFail)
assert (checker, URL("path"), URLFail)
assert (checker, URL("path"), MethodFail)
assert (checker, URL("to"), URLFail)
assert (checker, URL("to"), MethodFail)
assert (checker, URL("my"), URLFail)
assert (checker, URL("my"), MethodFail)
assert (checker, URL("resource"), MethodFail)
assert (checker, URL("(?s).*"), URLFail)
assert (checker, URL("(?s).*"), MethodFail)
And ("the URL('resource') will not have an URL fail because all URLs are accepted")
val stepsFromResource = allStepsFromStep (checker, URL("resource"), 2)
assert (stepsFromResource, "not(//chk:step[@type='URL_FAIL'])")
}
scenario("The WADL contains a template parameter of type string at the end of a path") {
Given("a WADL with a single template string at the end of the path")
val inWADL=
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource/{id}">
<param name="id" style="template" type="xsd:string"/>
<method href="#getMethod" />
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When ("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
stringTemplateAtEndAssertions(checker)
}
scenario("The WADL in tree format contains a template parameter of type string at the end of a path") {
Given("a WADL in tree format with a single template string at the end of the path")
val inWADL=
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path">
<resource path="to">
<resource path="my">
<resource path="resource">
<resource path="{id}">
<param name="id" style="template" type="xsd:string"/>
<method href="#getMethod" />
</resource>
</resource>
</resource>
</resource>
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When ("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
stringTemplateAtEndAssertions(checker)
}
scenario("The WADL in mix format contains a template parameter of type string at the end of a path") {
Given("a WADL in mix format with a single template string at the end of the path")
val inWADL=
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my">
<resource path="resource">
<resource path="{id}">
<param name="id" style="template" type="xsd:string"/>
<method href="#getMethod" />
</resource>
</resource>
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When ("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
stringTemplateAtEndAssertions(checker)
}
scenario("The WADL contains a template parameter of type string at the end of a path, the prefix used is not xsd, but the qname is valid") {
Given("a WADL with a single template string at the end of the path, the prefix used is not xsd, but the qname is valid")
val inWADL=
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:x="http://www.w3.org/2001/XMLSchema">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource/{id}">
<param name="id" style="template" type="x:string"/>
<method href="#getMethod" />
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When ("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
stringTemplateAtEndAssertions(checker)
}
scenario("Error Condition: The WADL contains a template parameter of type string, but the param element has a name mismatch") {
Given("a WADL with a template parameter, with a mismatch in the param name")
val inWADL=
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource/{id}">
<param name="other" style="template" type="xsd:string"/>
<method href="#getMethod" />
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When ("the wadl is translated")
Then ("A WADLException should be thrown")
intercept[WADLException] {
val checker = builder.build (inWADL, stdConfig)
}
}
scenario("Error Condition: The WADL contains a template parameter of type string, but is missing a param element") {
Given("a WADL with a template parameter but no param element")
val inWADL=
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource/{id}">
<method href="#getMethod" />
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When ("the wadl is translated")
Then ("A WADLException should be thrown")
intercept[WADLException] {
val checker = builder.build (inWADL, stdConfig)
}
}
scenario("Error Condition: The WADL contains a template parameter of type string, but the param element has a type mismatch") {
Given("a WADL with a template parameter, with a mismatch in the param type")
val inWADL=
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource/{id}">
<param name="id" style="header" rax:anyMatch="true" type="xsd:string" repeating="true"/>
<method href="#getMethod" />
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When ("the wadl is translated")
Then ("A WADLException should be thrown")
intercept[WADLException] {
val checker = builder.build (inWADL, stdConfig)
}
}
scenario("Error Condition: The WADL contains a template parameter of a type with a bad qname") {
Given("a WADL with a template parameter of a type with a bad qname")
val inWADL=
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource/{id}">
<param name="id" style="template" type="xsd:string"/>
<method href="#getMethod" />
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When ("the wadl is translated")
Then ("A WADLException should be thrown")
intercept[WADLException] {
val checker = builder.build (inWADL, stdConfig)
}
}
//
// The following scenarios test a string template parameter in the
// middle of the resource path (/path/to/my/{id}/resource. They are
// equivalent but they are written in slightly different WADL
// form the assertions below must apply to all of them.
//
def stringTemplateInMiddleAssertions (checker : NodeSeq) : Unit = {
Then("The checker should contain an URL node for each path step")
assert (checker, "count(/chk:checker/chk:step[@type='URL']) = 5")
And ("The checker should contain a GET method")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='GET']")
And ("The path from the start should contain all URL nodes including a .*")
And ("it should end in the GET method node")
assert (checker, Start, URL("path"), URL("to"), URL("my"), URL("(?s).*"), URL("resource"), Method("GET"))
And ("The Start state and each URL state should contain a path to MethodFail and URLFail")
assert (checker, Start, URLFail)
assert (checker, Start, MethodFail)
assert (checker, URL("path"), URLFail)
assert (checker, URL("path"), MethodFail)
assert (checker, URL("to"), URLFail)
assert (checker, URL("to"), MethodFail)
assert (checker, URL("my"), MethodFail)
assert (checker, URL("resource"), MethodFail)
assert (checker, URL("resource"), URLFail)
assert (checker, URL("(?s).*"), URLFail)
assert (checker, URL("(?s).*"), MethodFail)
And ("the URL('my') will not have an URL fail because all URLs are accepted")
val stepsFromResource = allStepsFromStep (checker, URL("my"), 2)
assert (stepsFromResource, "not(//chk:step[@type='URL_FAIL'])")
}
scenario("The WADL contains a template parameter of type string in the middle of the path") {
Given("a WADL with a single template string in the middle of the path")
val inWADL=
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/{id}/resource">
<param name="id" style="template" type="xsd:string"/>
<method href="#getMethod" />
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When ("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
stringTemplateInMiddleAssertions(checker)
}
scenario("The WADL in tree format contains a template parameter of type string in the middle of the path") {
Given("a WADL in tree format with a single template string in the middle of the path")
val inWADL=
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path">
<resource path="to">
<resource path="my">
<resource path="{id}">
<param name="id" style="template" type="xsd:string"/>
<resource path="resource">
<method href="#getMethod" />
</resource>
</resource>
</resource>
</resource>
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When ("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
stringTemplateInMiddleAssertions(checker)
}
scenario("The WADL in mix format contains a template parameter of type string in the middle of the path") {
Given("a WADL in mix format with a single template string in the middle of the path")
val inWADL=
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my">
<resource path="{id}">
<param name="id" style="template" type="xsd:string"/>
<resource path="resource">
<method href="#getMethod" />
</resource>
</resource>
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When ("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
stringTemplateInMiddleAssertions(checker)
}
//
// The following scenarios test a custom type template parameter at the
// of a resource path (/path/to/my/resource/{yn}. They are
// equivalent but they are written in slightly different WADL
// form the assertions below must apply to all of them.
//
def customTemplateAtEndAssertions (checker : NodeSeq) : Unit = {
Then("The checker should contain an URL node for each path step")
assert (checker, "count(/chk:checker/chk:step[@type='URL']) = 4")
And("A single URLXSD node")
assert (checker, "count(/chk:checker/chk:step[@type='URLXSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='URLXSD' and @label='yn']) = 1")
And ("The checker should contain a GET method")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='GET']")
And ("The path from the start should contain all URL and URLXSD nodes")
And ("it should end in the GET method node")
assert (checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Label("yn"), Method("GET"))
And ("The URLXSD should match a valid QName")
assert (checker, "namespace-uri-from-QName(resolve-QName(//chk:step[@label='yn'][1]/@match, //chk:step[@label='yn'][1])) "+
"= 'test://schema/a'")
assert (checker, "local-name-from-QName(resolve-QName(//chk:step[@label='yn'][1]/@match, //chk:step[@label='yn'][1])) "+
"= 'yesno'")
And ("The Start state and each URL state should contain a path to MethodFail and URLFail")
assert (checker, Start, URLFail)
assert (checker, Start, MethodFail)
assert (checker, URL("path"), URLFail)
assert (checker, URL("path"), MethodFail)
assert (checker, URL("to"), URLFail)
assert (checker, URL("to"), MethodFail)
assert (checker, URL("my"), URLFail)
assert (checker, URL("my"), MethodFail)
assert (checker, URL("resource"), URLFail)
assert (checker, URL("resource"), MethodFail)
assert (checker, Label("yn"), URLFail)
assert (checker, Label("yn"), MethodFail)
And("The grammar nodes are added to the checker")
assert (checker, "/chk:checker/chk:grammar[@ns='test://schema/a' and @type='W3C_XML']")
assert (checker, "if (/chk:checker/chk:grammar/@href) then not(/chk:checker/chk:grammar/xsd:schema) else /chk:checker/chk:grammar/xsd:schema")
assert (checker, "if (/chk:checker/chk:grammar/@href) then /chk:checker/chk:grammar/@href='test://app/xsd/simple.xsd' else true()")
}
scenario("The WADL contains a template parameter of a custom type at the end of the path") {
Given("A WADL with a template parameter of a custom type at the end of the path")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="test://schema/a">
<grammars>
<include href="test://app/xsd/simple.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource id="yn" path="path/to/my/resource/{yn}">
<param name="yn" style="template" type="tst:yesno"/>
<method href="#getMethod" />
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
register("test://app/xsd/simple.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/a">
<simpleType name="yesno">
<restriction base="xsd:string">
<enumeration value="yes"/>
<enumeration value="no"/>
</restriction>
</simpleType>
</schema>)
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
customTemplateAtEndAssertions(checker)
}
scenario("The WADL contains a template parameter of a custom type at the end of the path, the XSD is embedded") {
Given("A WADL with a template parameter of a custom type at the end of the path, the XSD is embedded")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="test://schema/a">
<grammars>
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/a">
<simpleType name="yesno">
<restriction base="xsd:string">
<enumeration value="yes"/>
<enumeration value="no"/>
</restriction>
</simpleType>
</schema>
</grammars>
<resources base="https://test.api.openstack.com">
<resource id="yn" path="path/to/my/resource/{yn}">
<param name="yn" style="template" type="tst:yesno"/>
<method href="#getMethod" />
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
customTemplateAtEndAssertions(checker)
}
scenario("The WADL contains a template parameter of a custom type at the end of the path, the schema is in a relative path") {
Given("A WADL with a template parameter of a custom type at the end of the path, the schema is in a relative path")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="test://schema/a">
<grammars>
<include href="xsd/simple.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource id="yn" path="path/to/my/resource/{yn}">
<param name="yn" style="template" type="tst:yesno"/>
<method href="#getMethod" />
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
register("test://app/xsd/simple.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/a">
<simpleType name="yesno">
<restriction base="xsd:string">
<enumeration value="yes"/>
<enumeration value="no"/>
</restriction>
</simpleType>
</schema>)
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
customTemplateAtEndAssertions(checker)
}
scenario("The WADL in tree format contains a template parameter of a custom type at the end of the path") {
Given("A WADL in tree format with a template parameter of a custom type at the end of the path")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="test://schema/a">
<grammars>
<include href="test://app/xsd/simple.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="path">
<resource path="to">
<resource path="my">
<resource path="resource">
<resource path="{yn}">
<param name="yn" style="template" type="tst:yesno"/>
<method href="#getMethod" />
</resource>
</resource>
</resource>
</resource>
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
register("test://app/xsd/simple.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/a">
<simpleType name="yesno">
<restriction base="xsd:string">
<enumeration value="yes"/>
<enumeration value="no"/>
</restriction>
</simpleType>
</schema>)
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
customTemplateAtEndAssertions(checker)
}
scenario("The WADL in mix format contains a template parameter of a custom type at the end of the path") {
Given("A WADL in mix format with a template parameter of a custom type at the end of the path")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="test://schema/a">
<grammars>
<include href="test://app/xsd/simple.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my">
<resource path="resource">
<resource id="yn" path="{yn}">
<param name="yn" style="template" type="tst:yesno"/>
<method href="#getMethod" />
</resource>
</resource>
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
register("test://app/xsd/simple.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/a">
<simpleType name="yesno">
<restriction base="xsd:string">
<enumeration value="yes"/>
<enumeration value="no"/>
</restriction>
</simpleType>
</schema>)
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
customTemplateAtEndAssertions(checker)
}
scenario("The WADL contains a template parameter of a custom type at the end of the path, the type is in the default namespace") {
Given("A WADL with a template parameter of a custom type at the end of the path, with the type in a default namespace")
val inWADL =
<wadl:application xmlns:wadl="http://wadl.dev.java.net/2009/02"
xmlns="test://schema/a">
<wadl:grammars>
<wadl:include href="test://app/xsd/simple.xsd"/>
</wadl:grammars>
<wadl:resources base="https://test.api.openstack.com">
<wadl:resource id="yn" path="path/to/my/resource/{yn}">
<wadl:param name="yn" style="template" type="yesno"/>
<wadl:method href="#getMethod" />
</wadl:resource>
</wadl:resources>
<wadl:method id="getMethod" name="GET">
<wadl:response status="200 203"/>
</wadl:method>
</wadl:application>
register("test://app/xsd/simple.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/a">
<simpleType name="yesno">
<restriction base="xsd:string">
<enumeration value="yes"/>
<enumeration value="no"/>
</restriction>
</simpleType>
</schema>)
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
customTemplateAtEndAssertions(checker)
}
scenario("The WADL in tree format contains a template parameter of a custom type at the end of the path, the type is in the default namespace") {
Given("A WADL in tree format with a template parameter of a custom type at the end of the path, the type is in the default namespace")
val inWADL =
<wadl:application xmlns:wadl="http://wadl.dev.java.net/2009/02"
xmlns="test://schema/a">
<wadl:grammars>
<wadl:include href="test://app/xsd/simple.xsd"/>
</wadl:grammars>
<wadl:resources base="https://test.api.openstack.com">
<wadl:resource path="path">
<wadl:resource path="to">
<wadl:resource path="my">
<wadl:resource path="resource">
<wadl:resource path="{yn}">
<wadl:param name="yn" style="template" type="yesno"/>
<wadl:method href="#getMethod" />
</wadl:resource>
</wadl:resource>
</wadl:resource>
</wadl:resource>
</wadl:resource>
</wadl:resources>
<wadl:method id="getMethod" name="GET">
<wadl:response status="200 203"/>
</wadl:method>
</wadl:application>
register("test://app/xsd/simple.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/a">
<simpleType name="yesno">
<restriction base="xsd:string">
<enumeration value="yes"/>
<enumeration value="no"/>
</restriction>
</simpleType>
</schema>)
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
customTemplateAtEndAssertions(checker)
}
scenario("The WADL in mix format contains a template parameter of a custom type at the end of the path, the type is in the default namespace") {
Given("A WADL in mix format with a template parameter of a custom type at the end of the path, the type is in the default namespace")
val inWADL =
<wadl:application xmlns:wadl="http://wadl.dev.java.net/2009/02"
xmlns="test://schema/a">
<wadl:grammars>
<wadl:include href="test://app/xsd/simple.xsd"/>
</wadl:grammars>
<wadl:resources base="https://test.api.openstack.com">
<wadl:resource path="path/to/my">
<wadl:resource path="resource">
<wadl:resource id="yn" path="{yn}">
<wadl:param name="yn" style="template" type="yesno"/>
<wadl:method href="#getMethod" />
</wadl:resource>
</wadl:resource>
</wadl:resource>
</wadl:resources>
<wadl:method id="getMethod" name="GET">
<wadl:response status="200 203"/>
</wadl:method>
</wadl:application>
register("test://app/xsd/simple.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/a">
<simpleType name="yesno">
<restriction base="xsd:string">
<enumeration value="yes"/>
<enumeration value="no"/>
</restriction>
</simpleType>
</schema>)
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
customTemplateAtEndAssertions(checker)
}
scenario("The WADL contains a template parameter of a custom type at the end of the path, with remove dup on") {
Given("A WADL with a template parameter of a custom type at the end of the path")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="test://schema/a">
<grammars>
<include href="test://app/xsd/simple.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource id="yn" path="path/to/my/resource/{yn}">
<param name="yn" style="template" type="tst:yesno"/>
<method href="#getMethod" />
</resource>
<resource path="1/dup">
<method href="#getMethod" />
</resource>
<resource path="2/dup">
<method href="#getMethod" />
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
register("test://app/xsd/simple.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/a">
<simpleType name="yesno">
<restriction base="xsd:string">
<enumeration value="yes"/>
<enumeration value="no"/>
</restriction>
</simpleType>
</schema>)
When("the wadl is translated")
val checker = builder.build (inWADL, dupConfig)
Then("The checker should contain an URL node for each path step")
assert (checker, "count(/chk:checker/chk:step[@type='URL']) = 7")
And("A single URLXSD node")
assert (checker, "count(/chk:checker/chk:step[@type='URLXSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='URLXSD' and @label='yn']) = 1")
And ("The checker should contain a GET method")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='GET']")
And ("The path from the start should contain all URL and URLXSD nodes")
And ("it should end in the GET method node")
assert (checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Label("yn"), Method("GET"))
And ("The URLXSD should match a valid QName")
assert (checker, "namespace-uri-from-QName(resolve-QName(//chk:step[@label='yn'][1]/@match, //chk:step[@label='yn'][1])) "+
"= 'test://schema/a'")
assert (checker, "local-name-from-QName(resolve-QName(//chk:step[@label='yn'][1]/@match, //chk:step[@label='yn'][1])) "+
"= 'yesno'")
And ("There should not be a duplicate dup node")
assert (checker, "count(//chk:step[@type='URL' and @match='dup']) = 1")
And ("The dup paths should be valid")
assert (checker, Start, URL("1"), URL("dup"), Method("GET"))
assert (checker, Start, URL("2"), URL("dup"), Method("GET"))
And ("The Start state and each URL state should contain a path to MethodFail and URLFail")
assert (checker, Start, URLFail)
assert (checker, Start, MethodFail)
assert (checker, URL("1"), URLFail)
assert (checker, URL("1"), MethodFail)
assert (checker, URL("2"), URLFail)
assert (checker, URL("2"), MethodFail)
assert (checker, URL("dup"), URLFail)
assert (checker, URL("dup"), MethodFail)
assert (checker, URL("path"), URLFail)
assert (checker, URL("path"), MethodFail)
assert (checker, URL("to"), URLFail)
assert (checker, URL("to"), MethodFail)
assert (checker, URL("my"), URLFail)
assert (checker, URL("my"), MethodFail)
assert (checker, URL("resource"), URLFail)
assert (checker, URL("resource"), MethodFail)
assert (checker, Label("yn"), URLFail)
assert (checker, Label("yn"), MethodFail)
And("The grammar nodes are added to the checker")
assert (checker, "/chk:checker/chk:grammar[@ns='test://schema/a' and @href='test://app/xsd/simple.xsd' and @type='W3C_XML']")
}
scenario("The WADL contains a template parameter of a custom type, but the grammar is missing") {
Given("A WADL with a template parameter of a custom type, but the grammar is missing")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="test://schema/a">
<grammars>
<include href="test://app/xsd/simple.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource id="yn" path="path/to/my/resource/{yn}">
<param name="yn" style="template" type="tst:yesno"/>
<method href="#getMethod" />
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When("the wadl is translated")
Then ("A WADLException should be thrown")
intercept[WADLException] {
val checker = builder.build (inWADL, dupConfig)
}
}
scenario("The WADL contains a template parameter of a custom type, but the grammar is not XSD") {
Given("A WADL with a template parameter of a custom type, but the grammar is not XSD")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="test://schema/a">
<grammars>
<include href="test://app/xsd/simple.rng"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource id="int" path="path/to/my/resource/{int}">
<param name="int" style="template" type="tst:int"/>
<method href="#getMethod" />
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When("the wadl is translated")
register("test://app/xsd/simple.rng",
<grammar datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes"
xmlns="http://relaxng.org/ns/structure/1.0" >
<define name="int">
<data type="integer"/>
</define>
</grammar>
)
Then ("The grammar should be ignored")
val checker = builder.build (inWADL, dupConfig)
assert (checker, "not(/chk:checker/chk:grammar)")
}
//
// We ignore until we handle adding an unparsed text reslover for
// testing.
//
ignore("The WADL contains a template parameter of a custom type, but the grammar is not XML") {
Given("A WADL with a template parameter of a custom type, but the grammar is not XML")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="test://schema/a">
<grammars>
<include href="test://app/xsd/simple.json"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource id="int" path="path/to/my/resource/{int}">
<param name="int" style="template" type="tst:int"/>
<method href="#getMethod" />
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
When("the wadl is translated")
// register_unparsed("test://app/xsd/simple.json",
// """
// {
// "type" : "int"
// }
// """
// )
Then ("The grammar should be ignored")
val checker = builder.build (inWADL, stdConfig)
assert (checker, "not(/chk:checker/chk:grammar)")
}
//
// The following scenarios test a custom template parameter in the
// middle of the resource path (/path/to/my/{yn}/resource. They are
// equivalent but they are written in slightly different WADL
// form the assertions below must apply to all of them.
//
def customTemplateInMiddleAssertions (checker : NodeSeq) : Unit = {
Then("The checker should contain an URL node for each path step")
assert (checker, "count(/chk:checker/chk:step[@type='URL']) = 4")
And("A single URLXSD node")
assert (checker, "count(/chk:checker/chk:step[@type='URLXSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='URLXSD' and @label='yn']) = 1")
And ("The checker should contain a GET method")
assert (checker, "/chk:checker/chk:step[@type='METHOD' and @match='GET']")
And ("The path from the start should contain all URL and URLXSD nodes")
And ("it should end in the GET method node")
assert (checker, Start, URL("path"), URL("to"), URL("my"), Label("yn"), URL("resource"), Method("GET"))
And ("The URLXSD should match a valid QName")
assert (checker, "namespace-uri-from-QName(resolve-QName(//chk:step[@label='yn'][1]/@match, //chk:step[@label='yn'][1])) "+
"= 'test://schema/a'")
assert (checker, "local-name-from-QName(resolve-QName(//chk:step[@label='yn'][1]/@match, //chk:step[@label='yn'][1])) "+
"= 'yesno'")
And ("The Start state and each URL state should contain a path to MethodFail and URLFail")
assert (checker, Start, URLFail)
assert (checker, Start, MethodFail)
assert (checker, URL("path"), URLFail)
assert (checker, URL("path"), MethodFail)
assert (checker, URL("to"), URLFail)
assert (checker, URL("to"), MethodFail)
assert (checker, URL("my"), MethodFail)
assert (checker, URL("my"), URLFail)
assert (checker, URL("resource"), MethodFail)
assert (checker, URL("resource"), URLFail)
assert (checker, Label("yn"), URLFail)
assert (checker, Label("yn"), MethodFail)
And("The grammar nodes are added to the checker")
assert (checker, "/chk:checker/chk:grammar[@ns='test://schema/a' and @href='test://simple.xsd' and @type='W3C_XML']")
}
scenario("The WADL contains a template parameter of a custom type in the middle of the path") {
Given("A WADL with a template parameter of a custom type in the middle of the path")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="test://schema/a">
<grammars>
<include href="test://simple.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource id="yn" path="path/to/my/{yn}/resource">
<param name="yn" style="template" type="tst:yesno"/>
<method href="#getMethod" />
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
register("test://simple.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/a">
<simpleType name="yesno">
<restriction base="xsd:string">
<enumeration value="yes"/>
<enumeration value="no"/>
</restriction>
</simpleType>
</schema>)
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
customTemplateInMiddleAssertions(checker)
}
scenario("The WADL in tree format contains a template parameter of a custom type in the middle of the path") {
Given("A WADL in tree format with a template parameter of a custom type in the middle of the path")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="test://schema/a">
<grammars>
<include href="test://simple.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="path">
<resource path="to">
<resource path="my">
<resource id="yn" path="{yn}">
<param name="yn" style="template" type="tst:yesno"/>
<resource path="resource">
<method href="#getMethod" />
</resource>
</resource>
</resource>
</resource>
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
register("test://simple.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/a">
<simpleType name="yesno">
<restriction base="xsd:string">
<enumeration value="yes"/>
<enumeration value="no"/>
</restriction>
</simpleType>
</schema>)
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
customTemplateInMiddleAssertions(checker)
}
scenario("The WADL in mix format contains a template parameter of a custom type in the middle of the path") {
Given("A WADL in mix format with a template parameter of a custom type in the middle of the path")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="test://schema/a">
<grammars>
<include href="test://simple.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my">
<resource id="yn" path="{yn}">
<param name="yn" style="template" type="tst:yesno"/>
<resource path="resource">
<method href="#getMethod" />
</resource>
</resource>
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
</application>
register("test://simple.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/a">
<simpleType name="yesno">
<restriction base="xsd:string">
<enumeration value="yes"/>
<enumeration value="no"/>
</restriction>
</simpleType>
</schema>)
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
customTemplateInMiddleAssertions(checker)
}
//
// The following scenarios test multiple template parameters in
// the middle of the resource path (/path/to/my/{yn}/resource,
// /path/to/my/{tf}/resource. They are equivalent but they are
// written in slightly different WADL form the assertions below
// must apply to all of them.
//
def customTemplatesInMiddleAssertions (checker : NodeSeq) : Unit = {
Then("The checker should contain an URL node for each path step")
assert (checker, "count(/chk:checker/chk:step[@type='URL']) = 5")
And("A single URLXSD node")
assert (checker, "count(/chk:checker/chk:step[@type='URLXSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='URLXSD' and @label='yn']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='URLXSD' and @label='tf']) = 1")
And ("The checker should contain two GET methods")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 2")
And ("The path from the start should contain all URL and URLXSD nodes")
And ("it should end in the GET method node")
assert (checker, Start, URL("path"), URL("to"), URL("my"), Label("yn"), URL("resource"), Method("GET"))
assert (checker, Start, URL("path"), URL("to"), URL("my"), Label("tf"), URL("resource"), Method("GET"))
And ("The URLXSD should match a valid QName")
assert (checker, "namespace-uri-from-QName(resolve-QName(//chk:step[@label='yn'][1]/@match, //chk:step[@label='yn'][1])) "+
"= 'test://schema/a'")
assert (checker, "local-name-from-QName(resolve-QName(//chk:step[@label='yn'][1]/@match, //chk:step[@label='yn'][1])) "+
"= 'yesno'")
assert (checker, "namespace-uri-from-QName(resolve-QName(//chk:step[@label='tf'][1]/@match, //chk:step[@label='tf'][1])) "+
"= 'test://schema/b'")
assert (checker, "local-name-from-QName(resolve-QName(//chk:step[@label='tf'][1]/@match, //chk:step[@label='tf'][1])) "+
"= 'truefalse'")
And ("The Start state and each URL state should contain a path to MethodFail and URLFail")
assert (checker, Start, URLFail)
assert (checker, Start, MethodFail)
assert (checker, URL("path"), URLFail)
assert (checker, URL("path"), MethodFail)
assert (checker, URL("to"), URLFail)
assert (checker, URL("to"), MethodFail)
assert (checker, URL("my"), MethodFail)
assert (checker, URL("my"), URLFail)
assert (checker, URL("resource"), MethodFail)
assert (checker, URL("resource"), URLFail)
assert (checker, Label("yn"), URLFail)
assert (checker, Label("yn"), MethodFail)
assert (checker, Label("tf"), URLFail)
assert (checker, Label("tf"), MethodFail)
And("The grammar nodes are added to the checker")
assert (checker, "/chk:checker/chk:grammar[@ns='test://schema/a' and @href='test://simple.xsd' and @type='W3C_XML']")
assert (checker, "/chk:checker/chk:grammar[@ns='test://schema/b' and @href='test://simple-too.xsd' and @type='W3C_XML']")
}
scenario("The WADL contains multiple template parameters of a custom type in the middle of the path") {
Given("A WADL with multiple template parameters of a custom type in the middle of the path")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="test://schema/a"
xmlns:tst2="test://schema/b"
>
<grammars>
<include href="test://simple.xsd"/>
<include href="test://simple-too.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource id="yn" path="path/to/my/{yn}/resource">
<param name="yn" style="template" type="tst:yesno"/>
<method href="#getMethod" />
</resource>
<resource id="tf" path="path/to/my/{tf}/resource">
<param name="tf" style="template" type="tst2:truefalse"/>
<method href="#otherGetMethod" />
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
<method id="otherGetMethod" name="GET">
<response status="200 203"/>
</method>
</application>
register("test://simple.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/a">
<simpleType name="yesno">
<restriction base="xsd:string">
<enumeration value="yes"/>
<enumeration value="no"/>
</restriction>
</simpleType>
</schema>)
register("test://simple-too.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/b">
<simpleType name="truefalse">
<restriction base="xsd:string">
<enumeration value="true"/>
<enumeration value="false"/>
</restriction>
</simpleType>
</schema>)
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
customTemplatesInMiddleAssertions(checker)
}
scenario("The WADL in tree format contains multiple template parameter of a custom type in the middle of the path") {
Given("A WADL in tree format with multiple template parameter of a custom type in the middle of the path")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="test://schema/a"
xmlns:tst2="test://schema/b"
>
<grammars>
<include href="test://simple.xsd"/>
<include href="test://simple-too.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="path">
<resource path="to">
<resource path="my">
<resource id="yn" path="{yn}">
<param name="yn" style="template" type="tst:yesno"/>
<resource path="resource">
<method href="#getMethod" />
</resource>
</resource>
<resource id="tf" path="{tf}">
<param name="tf" style="template" type="tst2:truefalse"/>
<resource path="resource">
<method href="#otherGetMethod" />
</resource>
</resource>
</resource>
</resource>
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
<method id="otherGetMethod" name="GET">
<response status="200 203"/>
</method>
</application>
register("test://simple.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/a">
<simpleType name="yesno">
<restriction base="xsd:string">
<enumeration value="yes"/>
<enumeration value="no"/>
</restriction>
</simpleType>
</schema>)
register("test://simple-too.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/b">
<simpleType name="truefalse">
<restriction base="xsd:string">
<enumeration value="true"/>
<enumeration value="false"/>
</restriction>
</simpleType>
</schema>)
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
customTemplatesInMiddleAssertions(checker)
}
scenario("The WADL in mix format contains multiple template parameters of a custom type in the middle of the path") {
Given("A WADL in mix format with multiple template parameters of a custom type in the middle of the path")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="test://schema/a"
xmlns:tst2="test://schema/b"
>
<grammars>
<include href="test://simple.xsd"/>
<include href="test://simple-too.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my">
<resource id="yn" path="{yn}">
<param name="yn" style="template" type="tst:yesno"/>
<resource path="resource">
<method href="#getMethod" />
</resource>
</resource>
<resource id="tf" path="{tf}">
<param name="tf" style="template" type="tst2:truefalse"/>
<resource path="resource">
<method href="#otherGetMethod" />
</resource>
</resource>
</resource>
</resources>
<method id="getMethod" name="GET">
<response status="200 203"/>
</method>
<method id="otherGetMethod" name="GET">
<response status="200 203"/>
</method>
</application>
register("test://simple.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/a">
<simpleType name="yesno">
<restriction base="xsd:string">
<enumeration value="yes"/>
<enumeration value="no"/>
</restriction>
</simpleType>
</schema>)
register("test://simple-too.xsd",
<schema elementFormDefault="qualified"
attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test://schema/b">
<simpleType name="truefalse">
<restriction base="xsd:string">
<enumeration value="true"/>
<enumeration value="false"/>
</restriction>
</simpleType>
</schema>)
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
customTemplatesInMiddleAssertions(checker)
}
scenario("The WADL contains a URL with special regex symbols") {
Given("a WADL that contains an URL winh special regex symbols")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="\\^-.${}*+|#()[]">
<method name=".-"/>
</resource>
<resource path="^ABC[D]EFG#">
<method name="-GET..IT-"/>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
assert (checker, Start, URL("\\\\\\\\\\\\^\\\\-\\\\.\\\\$\\\\{\\\\}\\\\*\\\\+\\\\|\\\\#\\\\(\\\\)\\\\[\\\\]"), Method("\\\\.\\\\-"))
assert (checker, Start, URL("\\\\^ABC\\\\[D\\\\]EFG\\\\#"), Method("\\\\-GET\\\\.\\\\.IT\\\\-"))
}
}
//
// The following assertions are used to test ReqType and
// ReqTypeFail nodes, they are used in the next couple of tests.
//
def reqTypeAssertions(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("any"), Method("POST"), AnyReqType)
assert (checker, Start, URL("text"), Method("POST"), ReqType("(text/)(.*)"))
assert (checker, Start, URL("v"), Method("POST"), ReqType("(text/plain;charset=UTF8)()"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
scenario("The WADL contains PUT and POST operations accepting various media types") {
Given ("a WADL that contains multiple PUT and POST operation with various media types")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
reqTypeAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting various media types, with dups optimization on") {
Given ("a WADL that contains multiple PUT and POST operation with various media types")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, dupConfig)
reqTypeAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
}
//
// The following scenarios test the remove duplicate optimization
// when there are no duplicates. They are equivalent but they are
// written in slightly different WADL form the assertions below
// must apply to all of them.
//
def noDupAsserts(checker : NodeSeq) : Unit = {
Then("The paths in both resources should match")
assert (checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("GET"))
assert (checker, "count(//chk:step[@type='URL' and @match='path']) = 1")
assert (checker, "count(//chk:step[@type='URL' and @match='to']) = 1")
assert (checker, "count(//chk:step[@type='URL' and @match='my']) = 1")
assert (checker, "count(//chk:step[@type='URL' and @match='resource']) = 1")
assert (checker, "count(//chk:step[@type='METHOD' and @match='GET']) = 1")
}
scenario("The WADL does not contain any duplicate resources, but remove dup optimization is on") {
Given("a WADL that contains no duplicate nodes")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource">
<method name="GET">
<response status="200 203"/>
</method>
</resource>
</resources>
</application>
When("the WADL is translated, with dup remove on")
val checker_dupon = builder.build(inWADL, dupConfig)
And ("the WADL is translated, with dup remove off")
val checker_dupoff = builder.build(inWADL, stdConfig)
noDupAsserts(checker_dupon)
noDupAsserts(checker_dupoff)
}
scenario("The WADL, in tree format, does not contain any duplicate nodes, but remove dup optimization is on") {
Given("a WADL in tree format that contains no duplicate nodes")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path">
<resource path="to">
<resource path="my">
<resource path="resource">
<method name="GET">
<response status="200 203"/>
</method>
</resource>
</resource>
</resource>
</resource>
</resources>
</application>
When("the WADL is translated, with dup remove on")
val checker_dupon = builder.build(inWADL, dupConfig)
And ("the WADL is translated, with dup remove off")
val checker_dupoff = builder.build(inWADL, stdConfig)
noDupAsserts(checker_dupon)
noDupAsserts(checker_dupoff)
}
scenario("The WADL, in mix format, does not contain any duplicate nodes, but remove dup optimization is on") {
Given("a WADL in mix format that contains no duplicate nodes")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my">
<resource path="resource">
<method name="GET">
<response status="200 203"/>
</method>
</resource>
</resource>
</resources>
</application>
When("the WADL is translated, with dup remove on")
val checker_dupon = builder.build(inWADL, dupConfig)
And ("the WADL is translated, with dup remove off")
val checker_dupoff = builder.build(inWADL, stdConfig)
noDupAsserts(checker_dupon)
noDupAsserts(checker_dupoff)
}
//
// The following scenarios test the remove duplicate optimization
// when there is a single duplicate. They are equivalent but they are
// written in slightly different WADL form the assertions below
// must apply to all of them.
//
def singleDupAsserts(checker_dupon : NodeSeq, checker_dupoff : NodeSeq) : Unit = {
Then("Paths should exist in both checkers")
assert (checker_dupon, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("GET"))
assert (checker_dupon, Start, URL("path"), URL("to"), URL("another"), URL("resource"), Method("GET"))
assert (checker_dupoff, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("GET"))
assert (checker_dupoff, Start, URL("path"), URL("to"), URL("another"), URL("resource"), Method("GET"))
And("there should be a duplicate resource node when dup is off")
assert (checker_dupoff, "count(//chk:step[@type='URL' and @match='path']) = 1")
assert (checker_dupoff, "count(//chk:step[@type='URL' and @match='to']) = 1")
assert (checker_dupoff, "count(//chk:step[@type='URL' and @match='my']) = 1")
assert (checker_dupoff, "count(//chk:step[@type='URL' and @match='resource']) = 2")
assert (checker_dupoff, "count(//chk:step[@type='URL' and @match='another']) = 1")
assert (checker_dupoff, "count(//chk:step[@type='METHOD' and @match='GET']) = 1")
And("there should *not* be a duplicate resource node when dup is on")
assert (checker_dupon, "count(//chk:step[@type='URL' and @match='path']) = 1")
assert (checker_dupon, "count(//chk:step[@type='URL' and @match='to']) = 1")
assert (checker_dupon, "count(//chk:step[@type='URL' and @match='my']) = 1")
assert (checker_dupon, "count(//chk:step[@type='URL' and @match='resource']) = 1")
assert (checker_dupon, "count(//chk:step[@type='URL' and @match='another']) = 1")
assert (checker_dupon, "count(//chk:step[@type='METHOD' and @match='GET']) = 1")
}
scenario("The WADL contain a single duplicate and remove dup optimization is on") {
Given("a WADL that contains a single duplicate")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource">
<method href="#res"/>
</resource>
<resource path="path/to/another/resource">
<method href="#res"/>
</resource>
</resources>
<method id="res" name="GET">
<response status="200 203"/>
</method>
</application>
When("the WADL is translated, with dup remove on")
val checker_dupon = builder.build(inWADL, dupConfig)
And ("the WADL is translated, with dup remove off")
val checker_dupoff = builder.build(inWADL, stdConfig)
singleDupAsserts(checker_dupon, checker_dupoff)
}
scenario("The WADL, in tree format, contains a single duplicate node and remove dup optimization is on") {
Given("a WADL in tree format contains a single duplicate")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path">
<resource path="to">
<resource path="my">
<resource path="resource">
<method href="#res"/>
</resource>
</resource>
<resource path="another">
<resource path="resource">
<method href="#res"/>
</resource>
</resource>
</resource>
</resource>
</resources>
<method id="res" name="GET">
<response status="200 203"/>
</method>
</application>
When("the WADL is translated, with dup remove on")
val checker_dupon = builder.build(inWADL, dupConfig)
And ("the WADL is translated, with dup remove off")
val checker_dupoff = builder.build(inWADL, stdConfig)
singleDupAsserts(checker_dupon, checker_dupoff)
}
scenario("The WADL, in mix format, contain a single duplicate and remove dup optimization is on") {
Given("a WADL, in mix format, that contains a single duplicate")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my">
<resource path="resource">
<method href="#res"/>
</resource>
</resource>
<resource path="path/to/another">
<resource path="resource">
<method href="#res"/>
</resource>
</resource>
</resources>
<method id="res" name="GET">
<response status="200 203"/>
</method>
</application>
When("the WADL is translated, with dup remove on")
val checker_dupon = builder.build(inWADL, dupConfig)
And ("the WADL is translated, with dup remove off")
val checker_dupoff = builder.build(inWADL, stdConfig)
singleDupAsserts(checker_dupon, checker_dupoff)
}
//
// The following scenarios test the remove duplicate optimization
// when there is a single duplicate. They are equivalent but they are
// written in slightly different WADL form the assertions below
// must apply to all of them.
//
def multipleDupAsserts(checker_dupon : NodeSeq, checker_dupoff : NodeSeq) : Unit = {
Then("Paths should exist in both checkers")
assert (checker_dupon, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("GET"))
assert (checker_dupon, Start, URL("path"), URL("to"), URL("another"), URL("resource"), Method("GET"))
assert (checker_dupon, Start, URL("what"), URL("about"), URL("this"), URL("resource"), Method("GET"))
assert (checker_dupon, Start, URL("what"), URL("about"), URL("this"), URL("resource"), URL("resource2"), Method("GET"))
assert (checker_dupon, Start, URL("and"), URL("another"), URL("resource"), Method("GET"))
assert (checker_dupon, Start, URL("and"), URL("another"), URL("resource2"), Method("GET"))
assert (checker_dupon, Start, URL("resource2"), Method("GET"))
assert (checker_dupoff, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("GET"))
assert (checker_dupoff, Start, URL("path"), URL("to"), URL("another"), URL("resource"), Method("GET"))
assert (checker_dupoff, Start, URL("what"), URL("about"), URL("this"), URL("resource"), Method("GET"))
assert (checker_dupoff, Start, URL("what"), URL("about"), URL("this"), URL("resource"), URL("resource2"), Method("GET"))
assert (checker_dupoff, Start, URL("and"), URL("another"), URL("resource"), Method("GET"))
assert (checker_dupoff, Start, URL("and"), URL("another"), URL("resource2"), Method("GET"))
assert (checker_dupoff, Start, URL("resource2"), Method("GET"))
And("there should be a number of duplicate resource node when dup is off")
assert (checker_dupoff, "count(//chk:step[@type='URL' and @match='resource']) = 4")
assert (checker_dupoff, "count(//chk:step[@type='URL' and @match='resource2']) = 3")
And("there should *not* be many duplicate resources dup is on, resource will be duplicate 'cus it's used in 2 different ways")
assert (checker_dupon, "count(//chk:step[@type='URL' and @match='resource']) = 2")
assert (checker_dupon, "count(//chk:step[@type='URL' and @match='resource2']) = 1")
And("there should be the same number of methods in each")
assert (checker_dupon, "count(//chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker_dupoff, "count(//chk:step[@type='METHOD' and @match='GET']) = 2")
}
scenario("The WADL contain multiple duplicates and remove dup optimization is on") {
Given("a WADL that contains multiple duplicates")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource">
<method href="#res"/>
</resource>
<resource path="path/to/another/resource">
<method href="#res"/>
</resource>
<resource path="and/another/resource">
<method href="#res"/>
</resource>
<resource path="what/about/this/resource">
<method href="#res"/>
</resource>
<resource path="what/about/this/resource/resource2">
<method href="#res2"/>
</resource>
<resource path="and/another/resource2">
<method href="#res2"/>
</resource>
<resource path="resource2">
<method href="#res2"/>
</resource>
</resources>
<method id="res" name="GET">
<response status="200 203"/>
</method>
<method id="res2" name="GET">
<response status="200 203"/>
</method>
</application>
When("the WADL is translated, with dup remove on")
val checker_dupon = builder.build(inWADL, dupConfig)
And ("the WADL is translated, with dup remove off")
val checker_dupoff = builder.build(inWADL, stdConfig)
multipleDupAsserts(checker_dupon, checker_dupoff)
}
scenario("The WADL, in tree format, contains multiple duplicates and remove dup optimization is on") {
Given("a WADL in tree format contains multiple duplicates")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="resource2">
<method href="#res2"/>
</resource>
<resource path="and">
<resource path="another">
<resource path="resource">
<method href="#res"/>
</resource>
<resource path="resource2">
<method href="#res2"/>
</resource>
</resource>
</resource>
<resource path="what">
<resource path="about">
<resource path="this">
<resource path="resource">
<method href="#res"/>
<resource path="resource2">
<method href="#res2"/>
</resource>
</resource>
</resource>
</resource>
</resource>
<resource path="path">
<resource path="to">
<resource path="another">
<resource path="resource">
<method href="#res"/>
</resource>
</resource>
<resource path="my">
<resource path="resource">
<method href="#res"/>
</resource>
</resource>
</resource>
</resource>
</resources>
<method id="res" name="GET">
<response status="200 203"/>
</method>
<method id="res2" name="GET">
<response status="200 203"/>
</method>
</application>
When("the WADL is translated, with dup remove on")
val checker_dupon = builder.build(inWADL, dupConfig)
And ("the WADL is translated, with dup remove off")
val checker_dupoff = builder.build(inWADL, stdConfig)
multipleDupAsserts(checker_dupon, checker_dupoff)
}
scenario("The WADL, in mixed format, contains multiple duplicates and remove dup optimization is on") {
Given("a WADL, in mixed format, that contains multiple duplicates")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to">
<resource path="my/resource">
<method href="#res"/>
</resource>
<resource path="another/resource">
<method href="#res"/>
</resource>
</resource>
<resource path="and/another/resource">
<method href="#res"/>
</resource>
<resource path="what/about/this/resource">
<method href="#res"/>
<resource path="resource2">
<method href="#res2"/>
</resource>
</resource>
<resource path="and/another/resource2">
<method href="#res2"/>
</resource>
<resource path="resource2">
<method href="#res2"/>
</resource>
</resources>
<method id="res" name="GET">
<response status="200 203"/>
</method>
<method id="res2" name="GET">
<response status="200 203"/>
</method>
</application>
When("the WADL is translated, with dup remove on")
val checker_dupon = builder.build(inWADL, dupConfig)
And ("the WADL is translated, with dup remove off")
val checker_dupoff = builder.build(inWADL, stdConfig)
multipleDupAsserts(checker_dupon, checker_dupoff)
}
//
// The following used by the next scenarios
//
val multi_post_tests : List[(String, Boolean, NodeSeq)] = List(
("With IDs", true,
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource">
<method id="action1" name="POST">
<response status="201"/>
</method>
<method id="action2" name="POST">
<response status="201"/>
</method>
<method id="action3" name="POST">
<response status="201"/>
</method>
<method id="action4" name="POST">
<response status="201"/>
</method>
</resource>
</resources>
</application>),
("With RAXIds", true,
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource">
<method rax:id="action1" name="POST">
<response status="201"/>
</method>
<method rax:id="action2" name="POST">
<response status="201"/>
</method>
<method rax:id="action3" name="POST">
<response status="201"/>
</method>
<method rax:id="action4" name="POST">
<response status="201"/>
</method>
</resource>
</resources>
</application>),
("With mix RAXIDs and IDs in resourceTypes", true,
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource">
<method rax:id="action1" name="POST">
<response status="201"/>
</method>
<method rax:id="action2" name="POST">
<response status="201"/>
</method>
<method rax:id="action3" name="POST">
<response status="201"/>
</method>
<method rax:id="action4" name="POST">
<response status="201"/>
</method>
</resource>
</resources>
<resource_type id="test">
<method id="action1" name="POST">
<response status="201"/>
</method>
<method id="action2" name="POST">
<response status="201"/>
</method>
<method id="action3" name="POST">
<response status="201"/>
</method>
<method id="action4" name="POST">
<response status="201"/>
</method>
</resource_type>
</application>),
("With mix RAXIDs and IDs in resourceTypes (not all ids)", false,
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource">
<method rax:id="action1" name="POST">
<response status="201"/>
</method>
<method name="POST">
<response status="201"/>
</method>
<method name="POST">
<response status="201"/>
</method>
<method name="POST">
<response status="201"/>
</method>
</resource>
</resources>
<resource_type id="test">
<method id="action1" name="POST">
<response status="201"/>
</method>
<method name="POST">
<response status="201"/>
</method>
<method name="POST">
<response status="201"/>
</method>
<method name="POST">
<response status="201"/>
</method>
</resource_type>
</application>),
("With mix RAXIds and IDs", true,
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource">
<method id="action1" name="POST">
<response status="201"/>
</method>
<method rax:id="action2" name="POST">
<response status="201"/>
</method>
<method id="action3" rax:id="action3" name="POST">
<response status="201"/>
</method>
<method rax:id="action4" name="POST">
<response status="201"/>
</method>
</resource>
</resources>
</application>),
("Without IDs", false,
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="path/to/my/resource">
<method name="POST">
<response status="201"/>
</method>
<method name="POST">
<response status="201"/>
</method>
<method name="POST">
<response status="201"/>
</method>
<method name="POST">
<response status="201"/>
</method>
</resource>
</resources>
</application>))
for (t <- multi_post_tests) {
scenario("The WADL contains a single resource with multiple methods of the same type "+t._1) {
Given("a WADL that contains a single resource with multiple methods of the same type"+t._1)
val inWADL = t._3
When("the wadl is translated")
val checker = builder.build (inWADL, stdConfig)
Then("There should be a total of 5 POST method steps...4 specified plus 1 collecting them")
assert(checker, "count(//chk:step[@type='METHOD']) = 5")
And ("All paths should go through POST step.")
assert(checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("POST"), Method("POST"), Accept)
if (t._2) {
assert(checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("POST"), Label("action1"))
assert(checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("POST"), Label("action2"))
assert(checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("POST"), Label("action3"))
assert(checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("POST"), Label("action4"))
} else {
assert(checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("POST"))
assert(checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("POST"))
assert(checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("POST"))
assert(checker, Start, URL("path"), URL("to"), URL("my"), URL("resource"), Method("POST"))
}
And ("One of the post steps is labeled ε, the rest are labeled according to thier ID")
if (t._2) {
assert(checker, "//chk:step[@type='METHOD' and @label='action1']")
assert(checker, "//chk:step[@type='METHOD' and @label='action2']")
assert(checker, "//chk:step[@type='METHOD' and @label='action3']")
assert(checker, "//chk:step[@type='METHOD' and @label='action4']")
}
assert(checker, "//chk:step[@type='METHOD' and @label='ε']")
}
}
//
// The following assertions are used to test WellFormXML and
// ContentError nodes. They are used in the next couple of tests.
//
def wellFormedAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
scenario("The WADL contains PUT and POST operations accepting various media types where well formness is checked") {
Given ("a WADL that contains multiple PUT and POST operation with various media types")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 4")
}
scenario("The WADL contains PUT and POST operations accepting various media types where well formness is checked, with dupson") {
Given ("a WADL that contains multiple PUT and POST operation with various media types")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars/>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
//
// The following assertions are used to test XSD and ContentError
// nodes. They are used in the next couple of tests.
//
def xsdAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// Like XSD assertions above, but take into account grammar transformation
//
def xsdGrammarTransformAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
xsdAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 4")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD (well formed not specified)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD (well formed not specified)")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, false, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
xsdAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 4")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD (only grammar transform option is specified)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD (only grammar transform option is specified)")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, false, false, false, 1, false, true))
Then("The following assertions should also hold:")
reqTypeAssertions(checker)
wellFormedAssertions(checker)
xsdGrammarTransformAssertions(checker)
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 4")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD (only grammar transform option is specified, warns disabled)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD (only grammar transform option is specified, warns disabled)")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(false, false, false, false, false, 1, false, true)
config.enableWarnHeaders = false
val checker = builder.build (inWADL, config)
Then("The following assertions should also hold:")
reqTypeAssertions(checker)
wellFormedAssertions(checker)
xsdAssertions(checker)
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 4")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, but no grammar is actually specified") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 4")
And("There should be no XSD steps, since no grammar was specified")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 0")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, but ignore XSD extension is used (set to false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
>
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request rax:ignoreXSD="false">
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request rax:ignoreXSD="false">
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, false, 1,
false, false, false, "XalanC",
false, false, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
xsdAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 4")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, but ignore XSD extension is used (set to 0)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
>
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request rax:ignoreXSD="0">
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request rax:ignoreXSD="0">
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, false, 1,
false, false, false, "XalanC",
false, false, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
xsdAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 4")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, but ignore XSD extension is used (set to true)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
>
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request rax:ignoreXSD="true">
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request rax:ignoreXSD="true">
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, false, 1,
false, false, false, "XalanC",
false, false, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 4")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, but ignore XSD extension is used (set to 1)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
>
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request rax:ignoreXSD="1">
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request rax:ignoreXSD="1">
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, false, 1,
false, false, false, "XalanC",
false, false, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 4")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, but ignore XSD extension is used (set to true, in representation)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
>
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml" rax:ignoreXSD="true"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml" rax:ignoreXSD="true"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, false, 1,
false, false, false, "XalanC",
false, false, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 4")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, but ignore XSD extension is used (set to true, in representation, mixed)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
>
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml" rax:ignoreXSD="true"/>
<representation mediaType="application/atom+xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request rax:ignoreXSD="true">
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, false, 1,
false, false, false, "XalanC",
false, false, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
And("The following assertions should also hold:")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/atom\\\\+xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/atom\\\\+xml)(;.*)?"), WellXML, ContentFail)
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/atom\\\\+xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/atom\\\\+xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 5")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, with dupson") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, with dupson")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
xsdAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
//
// The following assertions are used to test XSD, XPath and ContentError
// nodes. They are used in the next couple of tests.
//
def xsdElementAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
}
//
// Like the assertions above but only one XPath type is specified
//
def xsdElementAssertions2(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"), ContentFail)
}
//
// Here, were not doing XSD validation
//
def elementAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e", "Expecting the root element to be: tst:e"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a", "Expecting the root element to be: tst:a"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD with elements specified and checked") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD with elemenst specified")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml" element="tst:e"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
xsdElementAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XPATH']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 4")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD with elements specified and checked. The same element is used for POST and PUT") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD with elemenst specified")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml" element="tst:e"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:e"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
xsdElementAssertions2(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XPATH']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 4")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD with elements specified and checked. The same element is used for POST and PUT, dups on") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD with elemenst specified")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml" element="tst:e"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:e"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
xsdElementAssertions2(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XPATH']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml no XSD validation with elements specified and checked") {
Given ("a WADL that contains multiple PUT and POST operation with XML elements specified")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml" element="tst:e"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, false, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
elementAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='XPATH']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 4")
}
scenario("The WADL contains PUT and POST operations accepting xml no XSD validation, no WELL Formed with elements specified and checked") {
Given ("a WADL that contains multiple PUT and POST operation with XML elements specified")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml" element="tst:e"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, false, false, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
elementAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='XPATH']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 4")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD with elements checked, but none specified") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<representation mediaType="application/xml" />
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml" />
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
<resource path="/any">
<method name="POST">
<request>
<representation mediaType="*/*"/>
</request>
</method>
</resource>
<resource path="/text">
<method name="POST">
<request>
<representation mediaType="text/*"/>
</request>
</method>
</resource>
<resource path="/v">
<method name="POST">
<request>
<representation mediaType="text/plain;charset=UTF8"/>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true))
reqTypeAssertions(checker)
wellFormedAssertions(checker)
xsdAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(.*)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/)(.*)']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(text/plain;charset=UTF8)()']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XPATH']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 4")
}
scenario("The WADL contains a POST operation accepting xml which must validate against an XSD with elements specified and multiple required plain params") {
Given ("a WADL that contains a POST operation with XML that must validate against an XSD with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), ContentFail)
}
scenario("The WADL contains a POST operation with plain params but a missing mediaType, should validaate but not create XPaths") {
Given ("a WADL that contains a POST operation with XML that must validate against an XSD with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true))
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 0")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), Accept)
}
scenario("The WADL contains a POST operation accepting xml which must validate against an XSD with elements specified and multiple required plain params (rax:code extension)") {
Given ("a WADL that contains a POST operation with XML that must validate against an XSD with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" rax:code="401" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" rax:code="500" required="true"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id", 401), XPath("/tst:a/@stepType", 500), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id", 401), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id", 401), XPath("/tst:a/@stepType", 500), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml which must validate against an XSD with elements specified and multiple required plain params (with rax:message extension)") {
Given ("a WADL that contains a POST operation with XML that must validate against an XSD with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true" rax:message="Missing id attribute"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true" rax:message="Missing stepType attribute"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true, false, false, "Xalan",
false, false, false, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id","Missing id attribute"), XPath("/tst:a/@stepType", "Missing stepType attribute"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id","Missing id attribute"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id","Missing id attribute"), XPath("/tst:a/@stepType", "Missing stepType attribute"), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml which must validate against an XSD with elements specified and multiple required plain params (with rax:message, rax:code extension)") {
Given ("a WADL that contains a POST operation with XML that must validate against an XSD with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true" rax:message="Missing id attribute" rax:code="401"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true" rax:message="Missing stepType attribute" rax:code="500"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true, false, false, "Xalan",
false, false, false, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id","Missing id attribute", 401), XPath("/tst:a/@stepType", "Missing stepType attribute", 500), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id","Missing id attribute", 401), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id","Missing id attribute", 401), XPath("/tst:a/@stepType", "Missing stepType attribute", 500), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml which must validate against an XSD with elements specified and multiple required plain params (different namespaces)") {
Given ("a WADL that contains a POST operation with XML that must validate against an XSD with elemenst specified and multiple plain params")
val inWADL =
<wadl:application xmlns:wadl="http://wadl.dev.java.net/2009/02">
<wadl:grammars>
<wadl:include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</wadl:grammars>
<wadl:resources base="https://test.api.openstack.com" xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<wadl:resource path="/a/b">
<wadl:method name="POST">
<wadl:request>
<wadl:representation mediaType="application/xml" element="tst:a">
<wadl:param name="id" style="plain" path="/tst:a/@id" required="true"/>
<wadl:param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
</wadl:representation>
</wadl:request>
</wadl:method>
</wadl:resource>
</wadl:resources>
</wadl:application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml which must validate against an XSD with elements specified and multiple required plain params (wellform checks to false)") {
Given ("a WADL that contains a POST operation with XML that must validate against an XSD with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, false, true, true, 1, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml which must validate against an XSD with elements specified and multiple required plain params (different reps)") {
Given ("a WADL that contains a POST operation with XML that must validate against an XSD with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
</representation>
<representation mediaType="application/xml" element="tst:e">
<param name="id" style="plain" path="/tst:e/tst:id" required="true"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 4")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"),
XPath("/tst:e/tst:id"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"),
XPath("/tst:e/tst:id"), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml which must validate against an XSD with elements specified and multiple required plain params (different reps, multiple params)") {
Given ("a WADL that contains a POST operation with XML that must validate against an XSD with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
</representation>
<representation mediaType="application/xml" element="tst:e">
<param name="id" style="plain" path="/tst:e/tst:id" required="true"/>
<param name="stepType" style="plain" path="/tst:e/tst:stepType" required="true"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 5")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"),
XPath("/tst:e/tst:id"), XPath("/tst:e/tst:stepType"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"),
XPath("/tst:e/tst:id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"),
XPath("/tst:e/tst:id"), XPath("/tst:e/tst:stepType"), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml which must validate against an XSD with elements specified and multiple required plain params (different reps, multiple params, same element in multiple reps)") {
Given ("a WADL that contains a POST operation with XML that must validate against an XSD with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
</representation>
<representation mediaType="application/xml" element="tst:e">
<param name="id" style="plain" path="/tst:e/tst:id" required="true"/>
</representation>
<representation mediaType="application/xml" element="tst:e">
<param name="stepType" style="plain" path="/tst:e/tst:stepType" required="true"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 6")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e']) = 2")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"),
XPath("/tst:e/tst:id"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"),
XPath("/tst:e/tst:stepType"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml which must validate against an XSD with elements specified and multiple required plain params (different reps, multiple params, same element in multiple reps, rax message extension)") {
Given ("a WADL that contains a POST operation with XML that must validate against an XSD with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true" rax:message="Missing id in tst:a"/>
</representation>
<representation mediaType="application/xml" element="tst:e">
<param name="id" style="plain" path="/tst:e/tst:id" required="true" rax:message="Missing id in tst:e"/>
</representation>
<representation mediaType="application/xml" element="tst:e">
<param name="stepType" style="plain" path="/tst:e/tst:stepType" required="true" rax:message="Missing stepType in tst:e"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true, false, false, "Xalan",
false, false, false, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 6")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e']) = 2")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id", "Missing id in tst:a"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id", "Missing id in tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"),
XPath("/tst:e/tst:id", "Missing id in tst:e"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"),
XPath("/tst:e/tst:stepType", "Missing stepType in tst:e"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml which must validate against an XSD with elements specified and multiple required plain params (different reps, multiple params, same element in multiple reps, rax:message, rax:code extensions)") {
Given ("a WADL that contains a POST operation with XML that must validate against an XSD with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true" rax:message="Missing id in tst:a" rax:code="500"/>
</representation>
<representation mediaType="application/xml" element="tst:e">
<param name="id" style="plain" path="/tst:e/tst:id" required="true" rax:message="Missing id in tst:e" rax:code="501"/>
</representation>
<representation mediaType="application/xml" element="tst:e">
<param name="stepType" style="plain" path="/tst:e/tst:stepType" required="true" rax:message="Missing stepType in tst:e" rax:code="502"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true, false, false, "Xalan",
false, false, false, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 6")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e']) = 2")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id", "Missing id in tst:a", 500), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id", "Missing id in tst:a", 500), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"),
XPath("/tst:e/tst:id", "Missing id in tst:e", 501), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"),
XPath("/tst:e/tst:stepType", "Missing stepType in tst:e", 502), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml which must validate against an XSD with elements specified and multiple required plain params (different reps, multiple params, same element in multiple reps, dups on)") {
Given ("a WADL that contains a POST operation with XML that must validate against an XSD with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
</representation>
<representation mediaType="application/xml" element="tst:e">
<param name="id" style="plain" path="/tst:e/tst:id" required="true"/>
</representation>
<representation mediaType="application/xml" element="tst:e">
<param name="stepType" style="plain" path="/tst:e/tst:stepType" required="true"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 5")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"),
XPath("/tst:e/tst:id"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"),
XPath("/tst:e/tst:stepType"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml which must validate against an XSD with elements specified and multiple required plain params (different reps, multiple params one with required == false)") {
Given ("a WADL that contains a POST operation with XML that must validate against an XSD with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
</representation>
<representation mediaType="application/xml" element="tst:e">
<param name="id" style="plain" path="/tst:e/tst:id" required="true"/>
<param name="stepType" style="plain" path="/tst:e/tst:stepType" required="false"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 4")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:e/tst:stepType']) = 0")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"),
XPath("/tst:e/tst:id"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:e","Expecting the root element to be: tst:e"),
XPath("/tst:e/tst:id"), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml with elements specified and multiple required plain params") {
Given ("a WADL that contains a POST operation with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, true, false, true, 1, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml with elements specified and multiple required plain params (no XSD, element, or well-form checks)") {
Given ("a WADL that contains a POST operation with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, false, false, false, 1, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 2")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML,
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a/@id"), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml with elements specified and multiple required plain params (no element check)") {
Given ("a WADL that contains a POST operation with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, false, 1, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 2")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML,
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a/@id"),
ContentFail)
}
scenario("The WADL contains a POST operation accepting xml with no elements specified and multiple required plain params") {
Given ("a WADL that contains a POST operation with elemenst specified and multiple plain params")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 2")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML,
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a/@id"),
ContentFail)
}
scenario("The WADL contains a POST operation accepting valid xml with elements specified and multiple required plain params, and a single XSL transform") {
Given ("a WADL that contains a POST operation with elemets specified and multiple plain params and a single XSL transform")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
<rax:preprocess href="src/test/resources/xsl/testXSL1.xsl"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
register("test://app/src/test/resources/xsl/testXSL1.xsl",
XML.loadFile("src/test/resources/xsl/testXSL1.xsl"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true, true, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, XSD, SetHeaderAlways("Warning"), SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, ContentFail)
}
scenario("The WADL contains a POST operation accepting valid xml with elements specified and multiple required plain params, and a single XSL transform (disabled warn headers)") {
Given ("a WADL that contains a POST operation with elemets specified and multiple plain params and a single XSL transform (disabled warn headers)")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
<rax:preprocess href="src/test/resources/xsl/testXSL1.xsl"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
register("test://app/src/test/resources/xsl/testXSL1.xsl",
XML.loadFile("src/test/resources/xsl/testXSL1.xsl"))
When("the wadl is translated")
val config = TestConfig(false, false, true, true, true, 1, true, true, true)
config.enableWarnHeaders = false
val checker = builder.build (inWADL, config)
Then("The following assertions should hold")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, ContentFail)
}
scenario("The WADL contains a POST operation accepting valid xml with elements specified and multiple required plain params, and a single embeded XSL transform") {
Given ("a WADL that contains a POST operation with elemets specified and multiple plain params and a single XSL transform")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
<rax:preprocess>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
version="1.0">
<xsl:template match="/">
<tst:success didIt="true">Yup, that worked</tst:success>
</xsl:template>
</xsl:stylesheet>
</rax:preprocess>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true, true, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert(checker, "chk:checker/chk:step[@type='XSL']/xsl:stylesheet")
assert(checker, "chk:checker/chk:step[@type='XSL' and not(@href)]/xsl:stylesheet")
assert(checker, "chk:checker/chk:step[@type='XSL']/xsl:stylesheet/xsl:template")
assert(checker, "chk:checker/chk:step[@type='XSL']/xsl:stylesheet/xsl:template/tst:success")
assert(checker, "chk:checker/chk:step[@type='XSL']/xsl:stylesheet/xsl:template/tst:success/@didIt")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, XSD, SetHeaderAlways("Warning"), SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, ContentFail)
}
scenario("The WADL contains a POST operation accepting valid xml with elements specified and multiple required plain params, and a single embeded XSL transform (dups on)") {
Given ("a WADL that contains a POST operation with elemets specified and multiple plain params and a single XSL transform")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
<rax:preprocess>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
version="1.0">
<xsl:template match="/">
<tst:success didIt="true">Yup, that worked</tst:success>
</xsl:template>
</xsl:stylesheet>
</rax:preprocess>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1, true, true, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert(checker, "chk:checker/chk:step[@type='XSL']/xsl:stylesheet")
assert(checker, "chk:checker/chk:step[@type='XSL' and not(@href)]/xsl:stylesheet")
assert(checker, "chk:checker/chk:step[@type='XSL']/xsl:stylesheet/xsl:template")
assert(checker, "chk:checker/chk:step[@type='XSL']/xsl:stylesheet/xsl:template/tst:success")
assert(checker, "chk:checker/chk:step[@type='XSL']/xsl:stylesheet/xsl:template/tst:success/@didIt")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, XSD, SetHeaderAlways("Warning"), SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, ContentFail)
}
scenario("The WADL contains a POST operation accepting valid xml with elements specified and multiple required plain params, and a single embeded XSL transform (dups on, joins on)") {
Given ("a WADL that contains a POST operation with elemets specified and multiple plain params and a single XSL transform")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
<rax:preprocess>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
version="1.0">
<xsl:template match="/">
<tst:success didIt="true">Yup, that worked</tst:success>
</xsl:template>
</xsl:stylesheet>
</rax:preprocess>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1, true, true, true, "XalanC", true))
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 2")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 0")
assert(checker, "chk:checker/chk:step[@type='XSL']/xsl:stylesheet")
assert(checker, "chk:checker/chk:step[@type='XSL' and not(@href)]/xsl:stylesheet")
assert(checker, "chk:checker/chk:step[@type='XSL']/xsl:stylesheet/xsl:template")
assert(checker, "chk:checker/chk:step[@type='XSL']/xsl:stylesheet/xsl:template/tst:success")
assert(checker, "chk:checker/chk:step[@type='XSL']/xsl:stylesheet/xsl:template/tst:success/@didIt")
assert(checker, "chk:checker/chk:step[@type='XSL']/xsl:transform/xsl:template/xsl:choose/xsl:when[@test = '/tst:a']")
assert(checker, "in-scope-prefixes(chk:checker/chk:step[@type='XSL']/xsl:transform/xsl:template/xsl:choose/xsl:when[@test = '/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', chk:checker/chk:step[@type='XSL']/xsl:transform/xsl:template/xsl:choose/xsl:when[@test = '/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "chk:checker/chk:step[@type='XSL']/xsl:transform/xsl:template/xsl:choose/xsl:when[@test = '/tst:a/@id']")
assert(checker, "in-scope-prefixes(chk:checker/chk:step[@type='XSL']/xsl:transform/xsl:template/xsl:choose/xsl:when[@test = '/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', chk:checker/chk:step[@type='XSL']/xsl:transform/xsl:template/xsl:choose/xsl:when[@test = '/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "chk:checker/chk:step[@type='XSL']/xsl:transform/xsl:template/xsl:choose/xsl:when[@test = '/tst:a/@stepType']")
assert(checker, "in-scope-prefixes(chk:checker/chk:step[@type='XSL']/xsl:transform/xsl:template/xsl:choose/xsl:when[@test = '/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', chk:checker/chk:step[@type='XSL']/xsl:transform/xsl:template/xsl:choose/xsl:when[@test = '/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), XSL, XSL, XSD, SetHeaderAlways("Warning"), SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), XSL, XSL, ContentFail)
}
scenario("The WADL contains a POST operation accepting valid xml with elements specified and multiple required plain params, and a multiple XSL transform") {
Given ("a WADL that contains a POST operation with elemets specified and multiple plain params and multiple XSL transform")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
<rax:preprocess href="src/test/resources/xsl/testXSL1.xsl"/>
<rax:preprocess href="src/test/resources/xsl/testXSL2.xsl"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
register("test://app/src/test/resources/xsl/testXSL1.xsl",
XML.loadFile("src/test/resources/xsl/testXSL1.xsl"))
register("test://app/src/test/resources/xsl/testXSL2.xsl",
XML.loadFile("src/test/resources/xsl/testXSL2.xsl"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true, true, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 2")
assert(checker, "count(/chk:checker/chk:step[@type='XSL' and @version='1']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XSL' and @version='2']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, XSL, XSD, SetHeaderAlways("Warning"), SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, XSL, ContentFail)
}
scenario("The WADL contains a POST operation accepting valid xml with elements specified and multiple required plain params, and a multiple XSL transforms in different reps") {
Given ("a WADL that contains a POST operation with elemets specified and multiple plain params and multiple XSL transform in diffrent reps")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
<rax:preprocess href="src/test/resources/xsl/testXSL1.xsl"/>
</representation>
<representation mediaType="application/atom+xml" element="tst:a">
<rax:preprocess href="src/test/resources/xsl/testXSL2.xsl"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
register("test://app/src/test/resources/xsl/testXSL1.xsl",
XML.loadFile("src/test/resources/xsl/testXSL1.xsl"))
register("test://app/src/test/resources/xsl/testXSL2.xsl",
XML.loadFile("src/test/resources/xsl/testXSL2.xsl"))
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1, true, true, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a'][1]) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a'][1]) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a'][2]) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a'][2]) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 2")
assert(checker, "count(/chk:checker/chk:step[@type='XSL' and @version='1']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XSL' and @version='2']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 4")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 2")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, XSD, SetHeaderAlways("Warning"), SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/atom\\\\+xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XSL, XSD, SetHeaderAlways("Warning"), SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/atom\\\\+xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/atom\\\\+xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/atom\\\\+xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XSL, ContentFail)
}
scenario("The WADL contains a POST operation accepting valid xml with elements specified and multiple required plain params, and a multiple XSL transforms in different reps (dups on)") {
Given ("a WADL that contains a POST operation with elemets specified and multiple plain params and multiple XSL transform in diffrent reps (dups on)")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
<rax:preprocess href="src/test/resources/xsl/testXSL1.xsl"/>
</representation>
<representation mediaType="application/atom+xml" element="tst:a">
<rax:preprocess href="src/test/resources/xsl/testXSL2.xsl"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
register("test://app/src/test/resources/xsl/testXSL1.xsl",
XML.loadFile("src/test/resources/xsl/testXSL1.xsl"))
register("test://app/src/test/resources/xsl/testXSL2.xsl",
XML.loadFile("src/test/resources/xsl/testXSL2.xsl"))
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1, true, true, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a'][1]) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a'][1]) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a'][2]) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a'][2]) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 2")
assert(checker, "count(/chk:checker/chk:step[@type='XSL' and @version='1']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XSL' and @version='2']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 4")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 2")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, XSD, SetHeaderAlways("Warning"), SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/atom\\\\+xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XSL, XSD, SetHeaderAlways("Warning"), SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/atom\\\\+xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/atom\\\\+xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/atom\\\\+xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XSL, ContentFail)
}
scenario("The WADL contains a POST operation accepting valid xml with elements specified and multiple required plain params, and a multiple XSL transforms in different reps (dups on, join on)") {
Given ("a WADL that contains a POST operation with elemets specified and multiple plain params and multiple XSL transform in diffrent reps (dups on, join on)")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
<rax:preprocess href="src/test/resources/xsl/testXSL1.xsl"/>
</representation>
<representation mediaType="application/atom+xml" element="tst:a">
<rax:preprocess href="src/test/resources/xsl/testXSL2.xsl"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
register("test://app/src/test/resources/xsl/testXSL1.xsl",
XML.loadFile("src/test/resources/xsl/testXSL1.xsl"))
register("test://app/src/test/resources/xsl/testXSL2.xsl",
XML.loadFile("src/test/resources/xsl/testXSL2.xsl"))
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1, true, true, true, "XalanC", true))
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 4")
assert(checker, "count(/chk:checker/chk:step[@type='XSL' and @version='1']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XSL' and @version='2']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 0")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), XSL, XSL, XSD, SetHeaderAlways("Warning"), SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/atom\\\\+xml)(;.*)?"), XSL,
XSL, XSD, SetHeaderAlways("Warning"), SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/atom\\\\+xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
}
scenario("The WADL contains a POST operation accepting valid xml with elements specified and multiple required plain params, and a multiple XSL transforms in different reps (dups on, join on, xpath2)") {
Given ("a WADL that contains a POST operation with elemets specified and multiple plain params and multiple XSL transform in diffrent reps (dups on, join on, xpath2)")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
<rax:preprocess href="src/test/resources/xsl/testXSL1.xsl"/>
</representation>
<representation mediaType="application/atom+xml" element="tst:a">
<rax:preprocess href="src/test/resources/xsl/testXSL2.xsl"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
register("test://app/src/test/resources/xsl/testXSL1.xsl",
XML.loadFile("src/test/resources/xsl/testXSL1.xsl"))
register("test://app/src/test/resources/xsl/testXSL2.xsl",
XML.loadFile("src/test/resources/xsl/testXSL2.xsl"))
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 2, true, true, true, "XalanC", true))
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 4")
assert(checker, "count(/chk:checker/chk:step[@type='XSL' and @version='1']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XSL' and @version='2']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 0")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), XSL, XSL, XSD, SetHeaderAlways("Warning"), SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/atom\\\\+xml)(;.*)?"), XSL,
XSL, XSD, SetHeaderAlways("Warning"), SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/atom\\\\+xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
}
scenario("The WADL contains a POST operation accepting valid xml with elements specified and multiple required plain params, and a multiple XSL transforms in different reps (dups on 2)") {
Given ("a WADL that contains a POST operation with elemets specified and multiple plain params and multiple XSL transform in diffrent reps (dups on 2)")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
<rax:preprocess href="src/test/resources/xsl/testXSL1.xsl"/>
</representation>
<representation mediaType="application/atom+xml" element="tst:a">
<rax:preprocess href="src/test/resources/xsl/testXSL1.xsl"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
register("test://app/src/test/resources/xsl/testXSL1.xsl",
XML.loadFile("src/test/resources/xsl/testXSL1.xsl"))
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1, true, true, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a'][1]) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a'][1]) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a'][2]) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a'][2]) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XSL' and @version='1']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XSL' and @version='2']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 4")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 2")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, XSD, SetHeaderAlways("Warning"), SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/atom\\\\+xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XSL, XSD, SetHeaderAlways("Warning"), SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/atom\\\\+xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/atom\\\\+xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/atom\\\\+xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XSL, ContentFail)
}
scenario("The WADL contains a POST operation accepting xml with elements specified and multiple required plain params, and a single XSL transform") {
Given ("a WADL that contains a POST operation with elemets specified and multiple plain params and a single XSL transform")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
<rax:preprocess href="src/test/resources/xsl/testXSL1.xsl"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
register("test://app/src/test/resources/xsl/testXSL1.xsl",
XML.loadFile("src/test/resources/xsl/testXSL1.xsl"))
val checker = builder.build (inWADL, TestConfig(false, false, true, false, true, 1, true, false, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml with elements specified and multiple required plain params, and a single XSL transform (warn disabled)") {
Given ("a WADL that contains a POST operation with elemets specified and multiple plain params and a single XSL transform")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
<rax:preprocess href="src/test/resources/xsl/testXSL1.xsl"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
register("test://app/src/test/resources/xsl/testXSL1.xsl",
XML.loadFile("src/test/resources/xsl/testXSL1.xsl"))
When("the wadl is translated")
val config = TestConfig(false, false, true, false, true, 1, true, false, true)
config.enableWarnHeaders = false
val checker = builder.build (inWADL, config)
Then("The following assertions should hold")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml with elements specified and multiple required plain params, and a single XSL transform (no well form check)") {
Given ("a WADL that contains a POST operation with elemets specified and multiple plain params and a single XSL transform (no well form check)")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
<rax:preprocess href="src/test/resources/xsl/testXSL1.xsl"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
register("test://app/src/test/resources/xsl/testXSL1.xsl",
XML.loadFile("src/test/resources/xsl/testXSL1.xsl"))
val checker = builder.build (inWADL, TestConfig(false, false, false, false, true, 1, true, false, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 3")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a","Expecting the root element to be: tst:a"),
XPath("/tst:a/@id"), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml with elements specified (but check disabled) and multiple required plain params, and a single XSL transform (no well form check)") {
Given ("a WADL that contains a POST operation with elemets specified (but check disabled) and multiple plain params and a single XSL transform (no well form check)")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
<rax:preprocess href="src/test/resources/xsl/testXSL1.xsl"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
register("test://app/src/test/resources/xsl/testXSL1.xsl",
XML.loadFile("src/test/resources/xsl/testXSL1.xsl"))
val checker = builder.build (inWADL, TestConfig(false, false, false, false, false, 1, true, false, true))
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "in-scope-prefixes(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'tst'")
assert(checker, "namespace-uri-for-prefix('tst', /chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 'http://www.rackspace.com/repose/wadl/checker/step/test'")
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 2")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 1")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML,
XPath("/tst:a/@id"), XPath("/tst:a/@stepType"), XSL, SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XPath("/tst:a/@id"), ContentFail)
}
scenario("The WADL contains a POST operation accepting xml with elements specified (but check disabled) and multiple required plain params (check disabled) , and a single XSL transform (no well form check)") {
Given ("a WADL that contains a POST operation with elemets specified (but check disabled) and multiple plain params (check disabled) and a single XSL transform (no well form check)")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:tst="http://www.rackspace.com/repose/wadl/checker/step/test"
xmlns:rax="http://docs.rackspace.com/api">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="POST">
<request>
<representation mediaType="application/xml" element="tst:a">
<param name="id" style="plain" path="/tst:a/@id" required="true"/>
<param name="stepType" style="plain" path="/tst:a/@stepType" required="true"/>
<rax:preprocess href="src/test/resources/xsl/testXSL1.xsl"/>
</representation>
</request>
</method>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
register("test://app/src/test/resources/xsl/testXSL1.xsl",
XML.loadFile("src/test/resources/xsl/testXSL1.xsl"))
val checker = builder.build (inWADL, TestConfig(false, false, false, false, false, 1, false, false, true))
assert(checker, "count(/chk:checker/chk:step[@type='XSD']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 1")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@id']) = 0")
assert(checker, "count(/chk:checker/chk:step[@type='XPATH' and @match='/tst:a/@stepType']) = 0")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSL, SetHeaderAlways("Warning"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
}
//
// The following assertions are used to test ReqType and
// ReqTypeFail nodes, and header nodes they are used in the next
// couple of tests. These assume that anyMatch is not in effect for
// header params so we expect HeaderAll Steps.
//
def reqTypeAndHeaderAllAssertions(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
//
// The following assertions are used to test ReqType and
// ReqTypeFail nodes, and header nodes they are used in the next
// couple of tests.
//
def reqTypeAndHeaderAssertions(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
//
// Like reqTypeAndHeaderAssertions except we also check default values.
//
def reqTypeAndHeaderAssertionsWithDefaults(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"), Header("X-TEST", "(?s).*"),
Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
//
// Like reqTypeAndHeaderAssertions, but assumes that duplicates
// have been removed
//
def reqTypeAndHeaderDupsOnAssertions(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
//
// like reqTypeAndHeaderDupsOnAssertions but assuming that anyMatch is false so we use HeaderAllSteps
//
def reqTypeAndHeaderAllDupsOnAssertions(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
//
// Like reqTypeAndHeaderDufsOnAssertion but with default headers enabled
//
def reqTypeAndHeaderDupsOnAssertionsWithDefaults(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
//
// The following assertions are used to test WellFormXML,
// ContentError, and header nodes. They are used in the next couple of tests.
//
def wellFormedAndHeaderAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
//
// Like wellFormedAndHeader assertions, but assume that anyMatch is
// not in effect for header params, so we expect HeaderAll steps.
//
def wellFormedAndHeaderAllAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
//
// Like wellFormedAndHeaderAssertions except we also check default values.
//
def wellFormedAndHeaderAssertionsWithDefaults(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
//
// Like wellFormedAndHeaderAssertions, but assumes that remove dups
// optimization is on, and duplicates have been removed
//
def wellFormedAndHeaderDupsOnAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
//
// Like wellFormedAndHeaderDupsOnAssertions but assuming anyMatch
// == false, so we use HeaderAll steps.
//
def wellFormedAndHeaderAllDupsOnAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
//
// Like wellFormedAndHeaderDupsOnAssertions but with default headers enabled
//
def wellFormedAndHeaderDupsOnAssertionsWithDefaults(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
//
// The following assertions are used to test XSD, ContentError, and
// header nodes. They are used in the next couple of tests.
//
def xsdAndHeaderAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"),Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"),Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// like xsdAndHeaderAllAssertions except we assume that anyMatch is
// not in effect for header params so we expect HeaderAll Steps.
//
def xsdAndHeaderAllAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"),Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// Like xsdAndHeaderAssertions except we also check default values.
//
def xsdAndHeaderAssertionsWithDefaults(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"),Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"),Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// Like xsdAndHeaderAssertions, but it's assumed that remove dups opt is on
//
def xsdAndHeaderDupsOnAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"),
Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"),
Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"),
Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"),
Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// like xsdAndHeaderDupsOnAssertions but with anyMatch == false, so assume HeaderAll steps
//
def xsdAndHeaderAllDupsOnAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"),
Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"),
Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"),
Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"),
Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// Like xsdAndHeaderDupsOnAnssertions but with default headers enabled
//
def xsdAndHeaderDupsOnAssertionsWithDefaults(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"),
Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"),
Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"),
Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"),
Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def raxCodeHeaderAssertions(checker : NodeSeq) : Unit = {
And("The header states should have the appropriate header codes")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","foo", 402), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","bar", 403), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","foo", 402), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","bar", 403), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","foo", 402), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","bar", 403), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","foo", 402), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","bar", 403),Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// Like raxCodeHeaderAssertions, but assuming HeaderAll (anyMatch disabled)
//
def raxCodeHeaderAllAssertions(checker : NodeSeq) : Unit = {
And("The header states should have the appropriate header codes")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAll("X-FOO","foo|bar", 402), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAll("X-FOO","foo|bar", 402), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAll("X-FOO","foo|bar", 402), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// Like raxCodeHeaderAssertions but with default headers enabled
//
def raxCodeHeaderAssertionsWithDefaults(checker : NodeSeq) : Unit = {
And("The header states should have the appropriate header codes")
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","foo", 402), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","bar", 403), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","foo", 402), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","bar", 403), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","foo", 402), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","bar", 403), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","foo", 402), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","bar", 403),Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def raxMessageHeaderAssertions(checker : NodeSeq) : Unit = {
And("The header states should have the appropriate header codes")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAny("X-FOO","foo", "X-FOO,foo,bad"),
Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAny("X-FOO","bar", "X-FOO,bar,bad"),
Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAny("X-FOO","foo", "X-FOO,foo,bad"),
Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAny("X-FOO","bar", "X-FOO,bar,bad"),
Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAny("X-FOO","foo", "X-FOO,foo,bad"),
Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAny("X-FOO","bar", "X-FOO,bar,bad"),
Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAny("X-FOO","foo", "X-FOO,foo,bad"),
Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAny("X-FOO","bar", "X-FOO,bar,bad"),
Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// Like raxMessageHeaderAssertions but assume anyMatch is false
//
def raxMessageHeaderAllAssertions(checker : NodeSeq) : Unit = {
And("The header states should have the appropriate header codes")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAll("X-FOO","foo|bar", "X-FOO,foo,bad"),
Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAll("X-FOO","foo|bar", "X-FOO,foo,bad"),
Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAll("X-FOO","foo|bar", "X-FOO,foo,bad"),
Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAll("X-FOO","foo|bar", "X-FOO,foo,bad"),
Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// Like raxMessageHeaderAssertions but with default headers enabled
//
def raxMessageHeaderAssertionsWithDefaults(checker : NodeSeq) : Unit = {
And("The header states should have the appropriate header codes")
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAny("X-FOO","foo", "X-FOO,foo,bad"),
Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAny("X-FOO","bar", "X-FOO,bar,bad"),
Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAny("X-FOO","foo", "X-FOO,foo,bad"),
Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAny("X-FOO","bar", "X-FOO,bar,bad"),
Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAny("X-FOO","foo", "X-FOO,foo,bad"),
Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAny("X-FOO","bar", "X-FOO,bar,bad"),
Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAny("X-FOO","foo", "X-FOO,foo,bad"),
Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "X-TEST, bad"),
Header("X-TEST2", "(?s).*", "X-TEST2, bad"), HeaderAny("X-FOO","bar", "X-FOO,bar,bad"),
Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def raxSameCodeHeaderDupsAssertion(checker : NodeSeq) : Unit = {
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 401),
HeaderAny("X-FOO","foo|bar", 401), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 401),
HeaderAny("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 401),
HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 401),
HeaderAny("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// like raxSameCodeHeaderDupsAssertion but assuming anyMatch is
// false, so expecting HeaderAll steps.
//
def raxSameCodeHeaderAllDupsAssertion(checker : NodeSeq) : Unit = {
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 401),
HeaderAll("X-FOO","foo|bar", 401), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 401),
HeaderAll("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 401),
HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 401),
HeaderAll("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// Like raxSameCodeHeaderDupsAssertion but with default headers enabled
//
def raxSameCodeHeaderDupsAssertionWithDefaults(checker : NodeSeq) : Unit = {
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 401),
HeaderAny("X-FOO","foo|bar", 401), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 401),
HeaderAny("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 401),
HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 401),
HeaderAny("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def raxSameMessageHeaderDupsAssertion(checker : NodeSeq) : Unit = {
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "No!"), Header("X-TEST2", "(?s).*", "No!"),
HeaderAny("X-FOO","foo|bar", "No!"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "No!"), Header("X-TEST2", "(?s).*", "No!"),
HeaderAny("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "No!"), Header("X-TEST2", "(?s).*", "No!"),
HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "No!"), Header("X-TEST2", "(?s).*", "No!"),
HeaderAny("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// like raxSameMessageHeaderDupsAssertion but assume anyMatch ==
// false so expect HeaderAll setp
//
def raxSameMessageHeaderAllDupsAssertion(checker : NodeSeq) : Unit = {
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "No!"), Header("X-TEST2", "(?s).*", "No!"),
HeaderAll("X-FOO","foo|bar", "No!"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "No!"), Header("X-TEST2", "(?s).*", "No!"),
HeaderAll("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "No!"), Header("X-TEST2", "(?s).*", "No!"),
HeaderAll("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*", "No!"), Header("X-TEST2", "(?s).*", "No!"),
HeaderAll("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// Like raxSameMessageHeaderDupsAssertion but with default headers enabled
//
def raxSameMessageHeaderDupsAssertionWithDefaults(checker : NodeSeq) : Unit = {
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "No!"), Header("X-TEST2", "(?s).*", "No!"),
HeaderAny("X-FOO","foo|bar", "No!"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "No!"), Header("X-TEST2", "(?s).*", "No!"),
HeaderAny("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "No!"), Header("X-TEST2", "(?s).*", "No!"),
HeaderAny("X-FOO","foo|bar"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "No!"), Header("X-TEST2", "(?s).*", "No!"),
HeaderAny("X-FOO","foo|bar"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// The following assertions are used to test ReqType and
// ReqTypeFail nodes, and XSD header nodes they are used in the
// next couple of tests.
//
def reqTypeAndXSDHeaderAssertions(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
//
// The following assertions are used to test WellFormXML,
// ContentError, and XSD header nodes. They are used in the next
// couple of tests.
//
def wellFormedAndXSDHeaderAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
//
// The following assertions are used to test XSD, ContentError, and
// XSD header nodes. They are used in the next couple of tests.
//
def xsdAndXSDHeaderAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// The following assertions are used to test ReqType and
// ReqTypeFail nodes, and header and xsd header nodes they are used
// in the next couple of tests.
//
def reqTypeAndHeaderXSDHeaderAssertions(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
//
// The following assertions are used to test WellFormXML,
// ContentError, and header and xsd header nodes. They are used in
// the next couple of tests.
//
def wellFormedAndHeaderXSDHeaderAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
//
// The following assertions are used to test XSD, ContentError, and
// header and xsd header nodes. They are used in the next couple of
// tests.
//
def xsdAndHeaderXSDHeaderAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// The following assertions are used to test ReqType and
// ReqTypeFail nodes, and header and xsd header nodes they are used
// in the next couple of tests.
//
def reqTypeAndHeaderXSDHeader2Assertions(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqTypeFail)
}
//
// The following assertions are used to test WellFormXML,
// ContentError, and header and xsd header nodes. They are used in
// the next couple of tests.
//
def wellFormedAndHeaderXSDHeader2Assertions(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
}
//
// The following assertions are used to test XSD, ContentError, and
// header and xsd header nodes. They are used in the next couple of
// tests.
//
def xsdAndHeaderXSDHeader2Assertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("PUT"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true" fixed="foo"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true" fixed="bar"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (anymatch == false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST2" style="header" type="xsd:string" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="false" type="xsd:string" required="true" repeating="true" fixed="foo"/>
<param name="X-FOO" style="header" rax:anyMatch="0" type="xsd:string" required="true" repeating="true" fixed="bar"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAllAssertions(checker)
wellFormedAndHeaderAllAssertions(checker)
xsdAndHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (anymatch disabled)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true" fixed="foo"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true" fixed="bar"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.enableAnyMatchExtension = false
val checker = builder.build (inWADL, config)
reqTypeAndHeaderAllAssertions(checker)
wellFormedAndHeaderAllAssertions(checker)
xsdAndHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked, default headers must be ignored if feature is off") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true" default="FOO"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true" default="BAR"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true" fixed="foo" default="foo"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true" fixed="bar"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked, default headers must be ignored if feature is off, if raxroles is enabled X-ROLES header should be ignored") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-ROLES" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"
default="c:creator"/>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true" default="FOO"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true" default="BAR"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true" fixed="foo" default="foo"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true" fixed="bar"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val cfg = TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
cfg.enableRaxRolesExtension = true
val checkerLog = log (Level.WARN) {
val checker = builder.build (inWADL, cfg)
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
And ("An appropriate warning message should be provided")
assert(checkerLog, "you are not allowed to specify an X-ROLES header request parameter")
assert(checkerLog, "The X-ROLES header parameter will be ignored")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked, default headers must be ignored if feature is off, if raxroles is enabled x-RoLeS header should be ignored") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="x-RoLeS" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"
default="c:creator"/>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true" default="FOO"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val cfg = TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
cfg.enableRaxRolesExtension = true
val checkerLog = log (Level.WARN) {
val checker = builder.build (inWADL, cfg)
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
And ("An appropriate warning message should be provided")
assert(checkerLog, "you are not allowed to specify an X-ROLES header request parameter")
assert(checkerLog, "The X-ROLES header parameter will be ignored")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked, default headers must be ignored if feature is off, if raxroles is enabled X-ROLES header should be ignored (method)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<param name="X-ROLES" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"
default="c:creator"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val cfg = TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
cfg.enableRaxRolesExtension = true
val checkerLog = log (Level.WARN) {
val checker = builder.build (inWADL, cfg)
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
And ("An appropriate warning message should be provided")
assert(checkerLog, "you are not allowed to specify an X-ROLES header request parameter")
assert(checkerLog, "The X-ROLES header parameter will be ignored")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked, default headers must be ignored if feature is off, if raxroles is enabled X-ROLES header should be ignored (mixed)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-ROLES" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"
default="c:creator"/>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<param name="X-ROLES" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"
default="c:creator"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val cfg = TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
cfg.enableRaxRolesExtension = true
val checkerLog = log (Level.WARN) {
val checker = builder.build (inWADL, cfg)
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
And ("An appropriate warning message should be provided")
assert(checkerLog, "you are not allowed to specify an X-ROLES header request parameter")
assert(checkerLog, "The X-ROLES header parameter will be ignored")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked, default headers must be ignored if feature is off, if raxroles is enabled X-ROLES header in response should be ignored") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
<response>
<param name="X-ROLES" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"
default="c:creator"/>
</response>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val cfg = TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
cfg.enableRaxRolesExtension = true
val checkerLog = log (Level.WARN) {
val checker = builder.build (inWADL, cfg)
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
And ("No warning messages should be provided")
assertEmpty(checkerLog)
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked, errors to default headers must be ignored if feature is off (fixed mismatch)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" default="bar" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked, errors to default headers must be ignored if feature is off (multiple defaults)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" default="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked, default headers should be set") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked, default headers should be set")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.setParamDefaults=true
val checker = builder.build (inWADL, config)
reqTypeAndHeaderAssertionsWithDefaults(checker)
wellFormedAndHeaderAssertionsWithDefaults(checker)
xsdAndHeaderAssertionsWithDefaults(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked, default headers should be set, if rax roles is enabled X-ROLES header should be ignored") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked, default headers should be set")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-ROLES" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"
default="c:creator"/>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<param name="X-ROLES" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"
default="c:creator"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.setParamDefaults=true
config.enableRaxRolesExtension=true
val checkerLog = log (Level.WARN) {
val checker = builder.build (inWADL, config)
reqTypeAndHeaderAssertionsWithDefaults(checker)
wellFormedAndHeaderAssertionsWithDefaults(checker)
xsdAndHeaderAssertionsWithDefaults(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
And ("An appropriate warning message should be provided")
assert(checkerLog, "you are not allowed to specify an X-ROLES header request parameter")
assert(checkerLog, "The X-ROLES header parameter will be ignored")
}
scenario("If a default fixed header and default values are set, an error should occur") {
Given ("A WADL where default parameters do not match fixed, and defaults are set")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" default="bar" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.setParamDefaults=true
When ("the WADL is translated")
Then ("A WADLException should be thrown")
val checkerLog = log (Level.ERROR) {
intercept[WADLException] {
val checker = builder.build (inWADL, config)
}
}
And ("There is a proper message detailing the error.")
assert(checkerLog, "header param X-FOO")
assert(checkerLog, "@default value \\"bar\\"")
assert(checkerLog, "does not match @fixed value \\"foo\\"")
}
scenario("If multiple defaults are set for the same header value and defaults are enabled, an error should occur") {
Given ("A WADL where there are multiple defualts set for for the same header, and defaults are set")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" default="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.setParamDefaults=true
When ("the WADL is translated")
Then ("A WADLException should be thrown")
val checkerLog = log (Level.ERROR) {
intercept[WADLException] {
val checker = builder.build (inWADL, config)
}
}
And ("There is a proper message detailing the error.")
assert (checkerLog,"Multiple headers X-FOO have multiple @default vaules.")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (rax:code)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="404" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="402" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="403" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
raxCodeHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (rax:code, anyMatch==false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" type="xsd:string" rax:code="401" required="true" repeating="true"/>
<param name="X-TEST2" style="header" type="xsd:string" rax:code="404" required="true" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" rax:code="402" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" rax:code="403" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAllAssertions(checker)
wellFormedAndHeaderAllAssertions(checker)
xsdAndHeaderAllAssertions(checker)
raxCodeHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (rax:message)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:message="X-TEST, bad" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:message="X-TEST2, bad" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="X-FOO,foo,bad" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="X-FOO,bar,bad" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
raxMessageHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (rax:message, anyMatch == false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="0" type="xsd:string" rax:message="X-TEST, bad" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="false" type="xsd:string" rax:message="X-TEST2, bad" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="0" type="xsd:string" rax:message="X-FOO,foo,bad" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="false" type="xsd:string" rax:message="X-FOO,bar,bad" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.enableAnyMatchExtension = false
val checker = builder.build (inWADL, config)
reqTypeAndHeaderAllAssertions(checker)
wellFormedAndHeaderAllAssertions(checker)
xsdAndHeaderAllAssertions(checker)
raxMessageHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (rax:code, rax:message)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="X-TEST, bad" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="404" rax:message="X-TEST2, bad" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="402" rax:message="X-FOO,foo,bad" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="403" rax:message="X-FOO,bar,bad" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
raxMessageHeaderAssertions(checker)
raxCodeHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (rax:code, rax:message, anyMatch == false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" type="xsd:string" rax:code="401" rax:message="X-TEST, bad" required="true" repeating="true"/>
<param name="X-TEST2" style="header" type="xsd:string" rax:code="404" rax:message="X-TEST2, bad" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="false" type="xsd:string" rax:code="402" rax:message="X-FOO,foo,bad" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="false" type="xsd:string" rax:code="403" rax:message="X-FOO,bar,bad" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAllAssertions(checker)
wellFormedAndHeaderAllAssertions(checker)
xsdAndHeaderAllAssertions(checker)
raxMessageHeaderAllAssertions(checker)
raxCodeHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (rax:code, rax:message) default values should be ignored if the feature is truned off") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="X-TEST, bad" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="404" rax:message="X-TEST2, bad" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="402" rax:message="X-FOO,foo,bad" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="403" rax:message="X-FOO,bar,bad" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
raxMessageHeaderAssertions(checker)
raxCodeHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (rax:code, rax:message) default values should be set") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked default values should be set")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="X-TEST, bad" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="404" rax:message="X-TEST2, bad" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="402" rax:message="X-FOO,foo,bad" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="403" rax:message="X-FOO,bar,bad" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.setParamDefaults=true
val checker = builder.build (inWADL, config)
reqTypeAndHeaderAssertionsWithDefaults(checker)
wellFormedAndHeaderAssertionsWithDefaults(checker)
xsdAndHeaderAssertionsWithDefaults(checker)
raxMessageHeaderAssertionsWithDefaults(checker)
raxCodeHeaderAssertionsWithDefaults(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderDupsOnAssertions(checker)
wellFormedAndHeaderDupsOnAssertions(checker)
xsdAndHeaderDupsOnAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, anyMatch=false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="0" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="false" type="xsd:string" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="0" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="false" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAllDupsOnAssertions(checker)
wellFormedAndHeaderAllDupsOnAssertions(checker)
xsdAndHeaderAllDupsOnAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, anyMatch disabled)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.enableAnyMatchExtension = false
val checker = builder.build (inWADL, config)
reqTypeAndHeaderAllDupsOnAssertions(checker)
wellFormedAndHeaderAllDupsOnAssertions(checker)
xsdAndHeaderAllDupsOnAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on), if raxroles is enabled then X-ROLES header should be ignored") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-ROLES" style="header" rax:anyMatch="true" type="xsd:string" required="true"
default="c:creator" repeating="true"/>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<param name="X-ROLES" style="header" rax:anyMatch="true" type="xsd:string" required="true"
default="c:creator" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.enableRaxRolesExtension=true
val checkerLog = log (Level.WARN) {
val checker = builder.build (inWADL, config)
reqTypeAndHeaderDupsOnAssertions(checker)
wellFormedAndHeaderDupsOnAssertions(checker)
xsdAndHeaderDupsOnAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
And ("An appropriate warning message should be provided")
assert(checkerLog, "you are not allowed to specify an X-ROLES header request parameter")
assert(checkerLog, "The X-ROLES header parameter will be ignored")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on), default headers should be ignored if feature is off") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderDupsOnAssertions(checker)
wellFormedAndHeaderDupsOnAssertions(checker)
xsdAndHeaderDupsOnAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on), default headers should be set") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked, default headers should be set")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.setParamDefaults=true
val checker = builder.build (inWADL, config)
reqTypeAndHeaderDupsOnAssertionsWithDefaults(checker)
wellFormedAndHeaderDupsOnAssertionsWithDefaults(checker)
xsdAndHeaderDupsOnAssertionsWithDefaults(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on), default headers should be set, if raxroles is set X-ROLES header params should be ignored") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked, default headers should be set")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-ROLES" style="header" rax:anyMatch="true" type="xsd:string" required="true"
default="c:creator" repeating="true"/>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<param name="X-ROLES" style="header" rax:anyMatch="true" type="xsd:string" required="true"
default="c:creator" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.setParamDefaults=true
config.enableRaxRolesExtension=true
val checkerLog = log (Level.WARN) {
val checker = builder.build (inWADL, config)
reqTypeAndHeaderDupsOnAssertionsWithDefaults(checker)
wellFormedAndHeaderDupsOnAssertionsWithDefaults(checker)
xsdAndHeaderDupsOnAssertionsWithDefaults(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
And ("An appropriate warning message should be provided")
assert(checkerLog, "you are not allowed to specify an X-ROLES header request parameter")
assert(checkerLog, "The X-ROLES header parameter will be ignored")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, rax:code (same))") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderDupsOnAssertions(checker)
wellFormedAndHeaderDupsOnAssertions(checker)
xsdAndHeaderDupsOnAssertions(checker)
raxSameCodeHeaderDupsAssertion(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, rax:code (same), anyMatch==false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" type="xsd:string" rax:code="401" required="true" repeating="true"/>
<param name="X-TEST2" style="header" type="xsd:string" rax:code="401" required="true" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" rax:code="401" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" rax:code="401" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAllDupsOnAssertions(checker)
wellFormedAndHeaderAllDupsOnAssertions(checker)
xsdAndHeaderAllDupsOnAssertions(checker)
raxSameCodeHeaderAllDupsAssertion(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, rax:message (same))") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderDupsOnAssertions(checker)
wellFormedAndHeaderDupsOnAssertions(checker)
xsdAndHeaderDupsOnAssertions(checker)
raxSameMessageHeaderDupsAssertion(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, rax:message (same), anyMatch==false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="false" type="xsd:string" rax:message="No!" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="false" type="xsd:string" rax:message="No!" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="false" type="xsd:string" rax:message="No!" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="false" type="xsd:string" rax:message="No!" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAllDupsOnAssertions(checker)
wellFormedAndHeaderAllDupsOnAssertions(checker)
xsdAndHeaderAllDupsOnAssertions(checker)
raxSameMessageHeaderAllDupsAssertion(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, rax:code, rax:message (same))") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" rax:code="401" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" rax:code="401" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" rax:code="401" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" rax:code="401" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderDupsOnAssertions(checker)
wellFormedAndHeaderDupsOnAssertions(checker)
xsdAndHeaderDupsOnAssertions(checker)
raxSameMessageHeaderDupsAssertion(checker)
raxSameCodeHeaderDupsAssertion(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, rax:code, rax:message (same), anyMatch==false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="0" type="xsd:string" rax:message="No!" rax:code="401" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="0" type="xsd:string" rax:message="No!" rax:code="401" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="0" type="xsd:string" rax:message="No!" rax:code="401" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="0" type="xsd:string" rax:message="No!" rax:code="401" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAllDupsOnAssertions(checker)
wellFormedAndHeaderAllDupsOnAssertions(checker)
xsdAndHeaderAllDupsOnAssertions(checker)
raxSameMessageHeaderAllDupsAssertion(checker)
raxSameCodeHeaderAllDupsAssertion(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, rax:code, rax:message (same)) default headers should be ignored if the feature is off") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" rax:code="401" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" rax:code="401" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" rax:code="401" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" rax:code="401" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderDupsOnAssertions(checker)
wellFormedAndHeaderDupsOnAssertions(checker)
xsdAndHeaderDupsOnAssertions(checker)
raxSameMessageHeaderDupsAssertion(checker)
raxSameCodeHeaderDupsAssertion(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, rax:code, rax:message (same)) default headers should be set") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked default headers should be set")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" rax:code="401" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" rax:code="401" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" rax:code="401" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" rax:code="401" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.setParamDefaults=true
val checker = builder.build (inWADL, config)
reqTypeAndHeaderDupsOnAssertionsWithDefaults(checker)
wellFormedAndHeaderDupsOnAssertionsWithDefaults(checker)
xsdAndHeaderDupsOnAssertionsWithDefaults(checker)
raxSameMessageHeaderDupsAssertionWithDefaults(checker)
raxSameCodeHeaderDupsAssertionWithDefaults(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, rax:code (different))") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="404" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="402" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="403" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
raxCodeHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, rax:code (different), anyMatch==false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="0" type="xsd:string" rax:code="401" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="false" type="xsd:string" rax:code="404" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="false" type="xsd:string" rax:code="402" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="0" type="xsd:string" rax:code="403" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAllAssertions(checker)
wellFormedAndHeaderAllAssertions(checker)
xsdAndHeaderAllAssertions(checker)
raxCodeHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, rax:message (different))") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:message="X-TEST, bad" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:message="X-TEST2, bad" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="X-FOO,foo,bad" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="X-FOO,bar,bad" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
raxMessageHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, rax:message (different), anyMatch==false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="false" type="xsd:string" rax:message="X-TEST, bad" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="false" type="xsd:string" rax:message="X-TEST2, bad" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="false" type="xsd:string" rax:message="X-FOO,foo,bad" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="false" type="xsd:string" rax:message="X-FOO,bar,bad" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAllAssertions(checker)
wellFormedAndHeaderAllAssertions(checker)
xsdAndHeaderAllAssertions(checker)
raxMessageHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, rax:code, rax:message (different))") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="X-TEST, bad" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="404" rax:message="X-TEST2, bad" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="402" rax:message="X-FOO,foo,bad" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="403" rax:message="X-FOO,bar,bad" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
raxMessageHeaderAssertions(checker)
raxCodeHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, rax:code, rax:message (different), anyMatch==false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" type="xsd:string" rax:code="401" rax:message="X-TEST, bad" required="true" repeating="true"/>
<param name="X-TEST2" style="header" type="xsd:string" rax:code="404" rax:message="X-TEST2, bad" required="true" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" rax:code="402" rax:message="X-FOO,foo,bad" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" rax:code="403" rax:message="X-FOO,bar,bad" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAllAssertions(checker)
wellFormedAndHeaderAllAssertions(checker)
xsdAndHeaderAllAssertions(checker)
raxMessageHeaderAllAssertions(checker)
raxCodeHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, rax:code, rax:message (different)) default headers should be ignored if the feature is not set") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="X-TEST, bad" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="404" rax:message="X-TEST2, bad" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="402" rax:message="X-FOO,foo,bad" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="403" rax:message="X-FOO,bar,bad" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
raxMessageHeaderAssertions(checker)
raxCodeHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, required headers must be checked (remove dups on, rax:code, rax:message (different)) default headers should be set") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, required headers must be checked default headers should be set")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="X-TEST, bad" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="404" rax:message="X-TEST2, bad" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="402" rax:message="X-FOO,foo,bad" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="403" rax:message="X-FOO,bar,bad" required="true" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config =TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.setParamDefaults=true
val checker = builder.build (inWADL, config)
reqTypeAndHeaderAssertionsWithDefaults(checker)
wellFormedAndHeaderAssertionsWithDefaults(checker)
xsdAndHeaderAssertionsWithDefaults(checker)
raxMessageHeaderAssertionsWithDefaults(checker)
raxCodeHeaderAssertionsWithDefaults(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header must be checked, non-req should be ignored") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header must be checked, non-req should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:string" required="false" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST3" style="header" rax:anyMatch="true" type="xsd:string" required="false" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="false" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAssertions(checker)
wellFormedAndHeaderAssertions(checker)
xsdAndHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header must be checked, non-req should be ignored, anyMatch ==false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header must be checked, non-req should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" type="xsd:string" required="false" repeating="true"/>
<param name="X-TEST2" style="header" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST3" style="header" type="xsd:string" required="false" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" required="false" fixed="bar" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderAllAssertions(checker)
wellFormedAndHeaderAllAssertions(checker)
xsdAndHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required XSD header must be checked") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required XSD header must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndXSDHeaderAssertions(checker)
wellFormedAndXSDHeaderAssertions(checker)
xsdAndXSDHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 5")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required XSD header must be checked, anyMatch==false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required XSD header must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST-INT" style="header" rax:anyMatch="false" type="xsd:int" required="true" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndXSDHeaderAssertions(checker)
wellFormedAndXSDHeaderAssertions(checker)
xsdAndXSDHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 5")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required XSD header must be checked, non-req should be ignored") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required XSD header must be checked, non-req should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:string" required="false" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndXSDHeaderAssertions(checker)
wellFormedAndXSDHeaderAssertions(checker)
xsdAndXSDHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 5")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required XSD header must be checked, non-req should be ignored, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required XSD header must be checked, non-req should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST-INT" style="header" rax:anyMatch="0" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="0" type="xsd:string" required="false" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndXSDHeaderAssertions(checker)
wellFormedAndXSDHeaderAssertions(checker)
xsdAndXSDHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 5")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required XSD header and header must be checked") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required XSD header and header must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderXSDHeaderAssertions(checker)
wellFormedAndHeaderXSDHeaderAssertions(checker)
xsdAndHeaderXSDHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 6")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required XSD header and header must be checked, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required XSD header and header must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="false" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="false" type="xsd:int" required="true" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderXSDHeaderAssertions(checker)
wellFormedAndHeaderXSDHeaderAssertions(checker)
xsdAndHeaderXSDHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 6")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required XSD header and header must be checked, non-req should be ignored") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required XSD header and header must be checked, non-req should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:string" required="false" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderXSDHeaderAssertions(checker)
wellFormedAndHeaderXSDHeaderAssertions(checker)
xsdAndHeaderXSDHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 6")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required XSD header and header must be checked, non-req should be ignored, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required XSD header and header must be checked, non-req should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="0" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="false" type="xsd:string" required="false" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderXSDHeaderAssertions(checker)
wellFormedAndHeaderXSDHeaderAssertions(checker)
xsdAndHeaderXSDHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 6")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required XSD header and header must be checked, multiple similar Headers") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required XSD header and header must be checked, multiple similar Headers")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderXSDHeader2Assertions(checker)
wellFormedAndHeaderXSDHeader2Assertions(checker)
xsdAndHeaderXSDHeader2Assertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 8")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required XSD header and header must be checked, multiple similar Headers, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required XSD header and header must be checked, multiple similar Headers")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="false" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="false" type="xsd:int" required="true" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="false" type="xsd:int" required="true" repeating="true"/>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderXSDHeader2Assertions(checker)
wellFormedAndHeaderXSDHeader2Assertions(checker)
xsdAndHeaderXSDHeader2Assertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 8")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required XSD header and header must be checked, multiple similar Headers, non req headers should be ignored") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required XSD header and header must be checked, multiple similar Headers, nonrequired headers should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:string" required="false" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER-INT" style="header" rax:anyMatch="true" type="xsd:int" required="false" repeating="true"/>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderXSDHeader2Assertions(checker)
wellFormedAndHeaderXSDHeader2Assertions(checker)
xsdAndHeaderXSDHeader2Assertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 8")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required XSD header and header must be checked, multiple similar Headers, non req headers should be ignored, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required XSD header and header must be checked, multiple similar Headers, nonrequired headers should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="false" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="false" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="0" type="xsd:string" required="false" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="0" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER-INT" style="header" type="xsd:int" required="false" repeating="true"/>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndHeaderXSDHeader2Assertions(checker)
wellFormedAndHeaderXSDHeader2Assertions(checker)
xsdAndHeaderXSDHeader2Assertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 8")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required XSD header and header must be checked, multiple similar Headers, opt on") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required XSD header and header must be checked, multiple similar Headers, opt on")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
true, true))
reqTypeAndHeaderXSDHeader2Assertions(checker)
wellFormedAndHeaderXSDHeader2Assertions(checker)
xsdAndHeaderXSDHeader2Assertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required XSD header and header must be checked, multiple similar Headers, opt on, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required XSD header and header must be checked, multiple similar Headers, opt on")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<param name="X-TEST" style="header" rax:anyMatch="false" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="false" type="xsd:int" required="true" repeating="true"/>
<method name="PUT">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="false" type="xsd:int" required="true" repeating="true"/>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
true, true))
reqTypeAndHeaderXSDHeader2Assertions(checker)
wellFormedAndHeaderXSDHeader2Assertions(checker)
xsdAndHeaderXSDHeader2Assertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
//
// The following assertions are used to test ReqType and
// ReqTypeFail nodes, and header nodes on PUT request they are used
// in the next couple of tests.
//
def reqTypeAndReqHeaderAssertions(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
def reqTypeAndReqHeaderAllAssertions(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
def reqTypeAndReqHeaderAssertionsWithDefaults(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
//
// Like reqTypeAndReqHeaderAssertions, but we assume remove dups optimization
//
def reqTypeAndReqHeaderDupsOnAssertions(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
def reqTypeAndReqHeaderAllDupsOnAssertions(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
def reqTypeAndReqHeaderDupsOnAssertionsWithDefaults(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
//
// The following assertions are used to test WellFormXML,
// ContentError, and header nodes. They are used in the next couple of tests.
//
def wellFormedAndReqHeaderAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
def wellFormedAndReqHeaderAllAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
def wellFormedAndReqHeaderAssertionsWithDefaults(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
//
// Like wellFormedAndReqHeaderAssertions, but we assume remove dups on optimization
//
def wellFormedAndReqHeaderDupsOnAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
def wellFormedAndReqHeaderAllDupsOnAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
def wellFormedAndReqHeaderDupsOnAssertionsWithDefaults(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
//
// The following assertions are used to test XSD, ContentError, and
// header nodes. They are used in the next couple of tests.
//
def xsdAndReqHeaderAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def xsdAndReqHeaderAllAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def xsdAndReqHeaderAssertionsWithDefaults(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","bar"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// Like xsdAndReqHeaderAssertions, but we assume remove dups optimization
//
def xsdAndReqHeaderDupsOnAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"),
ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"),
ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def xsdAndReqHeaderAllDupsOnAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"),
ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAll("X-FOO","foo|bar"),
ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def xsdAndReqHeaderDupsOnAssertionsWithDefaults(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"),
ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*"), Header("X-TEST2", "(?s).*"), HeaderAny("X-FOO","foo|bar"),
ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def raxCodeReqHeaderAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain header assertions with correct error code")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","foo", 402), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","bar", 403), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","foo", 402), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","bar", 403), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def raxCodeReqHeaderAllAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain header assertions with correct error code")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAll("X-FOO","foo|bar", 402), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAll("X-FOO","foo|bar", 402), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def raxCodeReqHeaderAssertionsWithDefaults(checker : NodeSeq) : Unit = {
And("The machine should contain header assertions with correct error code")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","foo", 402), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","bar", 403), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","foo", 402), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401), Header("X-TEST2", "(?s).*", 404),
HeaderAny("X-FOO","bar", 403), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def raxCodeReqHeaderDupsOnAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain header assertions with the correct error code")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", 401),
Header("X-TEST2", "(?s).*", 401), HeaderAny("X-FOO","foo|bar", 401),
ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", 401),
Header("X-TEST2", "(?s).*", 401), HeaderAny("X-FOO","foo|bar", 401),
ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def raxCodeReqHeaderAllDupsOnAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain header assertions with the correct error code")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", 401),
Header("X-TEST2", "(?s).*", 401), HeaderAll("X-FOO","foo|bar", 401),
ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", 401),
Header("X-TEST2", "(?s).*", 401), HeaderAll("X-FOO","foo|bar", 401),
ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def raxCodeReqHeaderDupsOnAssertionsWithDefaults(checker : NodeSeq) : Unit = {
And("The machine should cantain header assertions with the correct error code")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401),
Header("X-TEST2", "(?s).*", 401), HeaderAny("X-FOO","foo|bar", 401),
ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", 401),
Header("X-TEST2", "(?s).*", 401), HeaderAny("X-FOO","foo|bar", 401),
ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def raxMessageReqHeaderDupsOnAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain header assertions with the correct error code")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", "No!"),
Header("X-TEST2", "(?s).*", "No!"), HeaderAny("X-FOO","foo|bar", "No!"),
ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", "No!"),
Header("X-TEST2", "(?s).*", "No!"), HeaderAny("X-FOO","foo|bar", "No!"),
ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def raxMessageReqHeaderAllDupsOnAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain header assertions with the correct error code")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", "No!"),
Header("X-TEST2", "(?s).*", "No!"), HeaderAll("X-FOO","foo|bar", "No!"),
ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", "No!"),
Header("X-TEST2", "(?s).*", "No!"), HeaderAll("X-FOO","foo|bar", "No!"),
ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def raxMessageReqHeaderDupsOnAssertionsWithDefaults(checker : NodeSeq) : Unit = {
And("The machine should cantain header assertions with the correct error code")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "No!"),
Header("X-TEST2", "(?s).*", "No!"), HeaderAny("X-FOO","foo|bar", "No!"),
ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "No!"),
Header("X-TEST2", "(?s).*", "No!"), HeaderAny("X-FOO","foo|bar", "No!"),
ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def raxMessageReqHeaderAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain header assertions with correct error code")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", "No1"), Header("X-TEST2", "(?s).*", "No4"),
HeaderAny("X-FOO","foo", "No2"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", "No1"), Header("X-TEST2", "(?s).*", "No4"),
HeaderAny("X-FOO","bar", "No3"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", "No1"), Header("X-TEST2", "(?s).*", "No4"),
HeaderAny("X-FOO","foo", "No2"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", "No1"), Header("X-TEST2", "(?s).*", "No4"),
HeaderAny("X-FOO","bar", "No3"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def raxMessageReqHeaderAllAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain header assertions with correct error code")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", "No1"), Header("X-TEST2", "(?s).*", "No4"),
HeaderAll("X-FOO","foo|bar", "No2"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*", "No1"), Header("X-TEST2", "(?s).*", "No4"),
HeaderAll("X-FOO","foo|bar", "No2"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def raxMessageReqHeaderAssertionsWithDefaults(checker : NodeSeq) : Unit = {
And("The machine should contain header assertions with correct error code")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "No1"), Header("X-TEST2", "(?s).*", "No4"),
HeaderAny("X-FOO","foo", "No2"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "No1"), Header("X-TEST2", "(?s).*", "No4"),
HeaderAny("X-FOO","bar", "No3"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "No1"), Header("X-TEST2", "(?s).*", "No4"),
HeaderAny("X-FOO","foo", "No2"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST", "FOO"), SetHeader("X-TEST2","BAR"), SetHeader("X-FOO","foo"),
Header("X-TEST", "(?s).*", "No1"), Header("X-TEST2", "(?s).*", "No4"),
HeaderAny("X-FOO","bar", "No3"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// The following assertions are used to test ReqType and
// ReqTypeFail nodes, and XSD header nodes they are used in the
// next couple of tests.
//
def reqTypeAndReqXSDHeaderAssertions(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
//
// The following assertions are used to test WellFormXML,
// ContentError, and XSD header nodes. They are used in the next
// couple of tests.
//
def wellFormedAndReqXSDHeaderAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
//
// The following assertions are used to test XSD, ContentError, and
// XSD header nodes. They are used in the next couple of tests.
//
def xsdAndReqXSDHeaderAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// The following assertions are used to test ReqType and
// ReqTypeFail nodes, and header and xsd header nodes they are used
// in the next couple of tests.
//
def reqTypeAndReqHeaderXSDHeaderAssertions(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), Method("POST"), ReqTypeFail)
}
//
// The following assertions are used to test WellFormXML,
// ContentError, and header and xsd header nodes. They are used in
// the next couple of tests.
//
def wellFormedAndReqHeaderXSDHeaderAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
}
//
// The following assertions are used to test XSD, ContentError, and
// header and xsd header nodes. They are used in the next couple of
// tests.
//
def xsdAndReqHeaderXSDHeaderAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// The following assertions are used to test ReqType and
// ReqTypeFail nodes, and header and xsd header nodes they are used
// in the next couple of tests.
//
def reqTypeAndReqHeaderXSDHeader2Assertions(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqTypeFail)
}
//
// The following assertions are used to test WellFormXML,
// ContentError, and header and xsd header nodes. They are used in
// the next couple of tests.
//
def wellFormedAndReqHeaderXSDHeader2Assertions(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
}
//
// The following assertions are used to test XSD, ContentError, and
// header and xsd header nodes. They are used in the next couple of
// tests.
//
def xsdAndReqHeaderXSDHeader2Assertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// The following assertions are used to test ReqType and
// ReqTypeFail nodes, and header and xsd header nodes they are used
// in the next couple of tests.
//
def reqTypeAndReqHeaderXSDHeader2MixAssertions(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqTypeFail)
}
def reqTypeAndReqHeaderXSDHeader2MixAssertionsWithDefaults(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST-INT", "99"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST-INT", "99"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), SetHeader("X-TEST-INT", "999"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), SetHeader("X-TEST-OTHER", "2015-11-28"), HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqType("(application/json)(;.*)?"))
assert (checker, Start, URL("c"), SetHeader("X-TEST-INT", "999"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), SetHeader("X-TEST-OTHER", "2015-11-28"), HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), SetHeader("X-TEST-INT", "999"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST-INT", "99"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST-INT", "99"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqTypeFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), SetHeader("X-TEST-INT", "999"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), SetHeader("X-TEST-OTHER", "2015-11-28"), HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqTypeFail)
}
//
// The following assertions are used to test WellFormXML,
// ContentError, and header and xsd header nodes. They are used in
// the next couple of tests.
//
def wellFormedAndReqHeaderXSDHeader2MixAssertions(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqType("(application/xml)(;.*)?"), WellXML)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqType("(application/xml)(;.*)?"), ContentFail)
}
def wellFormedAndReqHeaderXSDHeader2MixAssertionsWithDefaults(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST-INT", "99"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST-INT", "99"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), SetHeader("X-TEST-INT", "999"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), SetHeader("X-TEST-OTHER", "2015-11-28"),
HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqType("(application/json)(;.*)?"), WellJSON)
assert (checker, Start, URL("c"), SetHeader("X-TEST-INT", "999"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), SetHeader("X-TEST-OTHER", "2015-11-28"),
HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqType("(application/xml)(;.*)?"), WellXML)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST-INT", "99"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST-INT", "99"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), SetHeader("X-TEST-INT", "999"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), SetHeader("X-TEST-OTHER", "2015-11-28"),
HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqType("(application/json)(;.*)?"), ContentFail)
assert (checker, Start, URL("c"), SetHeader("X-TEST-INT", "999"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), SetHeader("X-TEST-OTHER", "2015-11-28"),
HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqType("(application/xml)(;.*)?"), ContentFail)
}
//
// The following assertions are used to test XSD, ContentError, and
// header and xsd header nodes. They are used in the next couple of
// tests.
//
def xsdAndReqHeaderXSDHeader2MixAssertions(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
def xsdAndReqHeaderXSDHeader2MixAssertionsWithDefaults(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST-INT", "99"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), SetHeader("X-TEST-INT", "99"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
assert (checker, Start, URL("c"), SetHeader("X-TEST-INT", "999"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), SetHeader("X-TEST-OTHER", "2015-11-28"),
HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("c"), SetHeader("X-TEST-INT", "999"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), SetHeader("X-TEST-OTHER", "2015-11-28"),
HeaderXSD("X-TEST-OTHER", "xsd:date"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAssertions(checker)
wellFormedAndReqHeaderAssertions(checker)
xsdAndReqHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="false" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="false" type="xsd:string" required="true" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAllAssertions(checker)
wellFormedAndReqHeaderAllAssertions(checker)
xsdAndReqHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked default values should be ignored if the feature is not set") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAssertions(checker)
wellFormedAndReqHeaderAssertions(checker)
xsdAndReqHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked default values should be set") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked default values should be set")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.setParamDefaults=true
val checker = builder.build (inWADL, config)
reqTypeAndReqHeaderAssertionsWithDefaults(checker)
wellFormedAndReqHeaderAssertionsWithDefaults(checker)
xsdAndReqHeaderAssertionsWithDefaults(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (method ref)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method href="#headerMethod"/>
<method href="#postOnAB"/>
</resource>
<resource path="/c">
<method href="#postOnC"/>
<method href="#getOnC"/>
</resource>
</resources>
<method id="headerMethod" name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method id="postOnAB" name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
<method id="postOnC" name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method id="getOnC" name="GET"/>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAssertions(checker)
wellFormedAndReqHeaderAssertions(checker)
xsdAndReqHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (method ref) with default values set") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked with default values set")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method href="#headerMethod"/>
<method href="#postOnAB"/>
</resource>
<resource path="/c">
<method href="#postOnC"/>
<method href="#getOnC"/>
</resource>
</resources>
<method id="headerMethod" name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method id="postOnAB" name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
<method id="postOnC" name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method id="getOnC" name="GET"/>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.setParamDefaults=true
val checker = builder.build (inWADL, config)
reqTypeAndReqHeaderAssertionsWithDefaults(checker)
wellFormedAndReqHeaderAssertionsWithDefaults(checker)
xsdAndReqHeaderAssertionsWithDefaults(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (rax:code)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="404" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="402" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="403" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAssertions(checker)
wellFormedAndReqHeaderAssertions(checker)
xsdAndReqHeaderAssertions(checker)
raxCodeReqHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (rax:code), anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="false" type="xsd:string" rax:code="401" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="false" type="xsd:string" rax:code="404" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="false" type="xsd:string" rax:code="402" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="false" type="xsd:string" rax:code="403" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAllAssertions(checker)
wellFormedAndReqHeaderAllAssertions(checker)
xsdAndReqHeaderAllAssertions(checker)
raxCodeReqHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (rax:message)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No1" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No4" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No2" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No3" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAssertions(checker)
wellFormedAndReqHeaderAssertions(checker)
xsdAndReqHeaderAssertions(checker)
raxMessageReqHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (rax:message, anyMatch=false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" type="xsd:string" rax:message="No1" required="true" repeating="true"/>
<param name="X-TEST2" style="header" type="xsd:string" rax:message="No4" required="true" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" rax:message="No2" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" rax:message="No3" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAllAssertions(checker)
wellFormedAndReqHeaderAllAssertions(checker)
xsdAndReqHeaderAllAssertions(checker)
raxMessageReqHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (rax:code, rax:message)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="No1" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="404" rax:message="No4" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="402" rax:message="No2" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="403" rax:message="No3" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAssertions(checker)
wellFormedAndReqHeaderAssertions(checker)
xsdAndReqHeaderAssertions(checker)
raxCodeReqHeaderAssertions(checker)
raxMessageReqHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (rax:code, rax:message, anyMatch=false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" type="xsd:string" rax:code="401" rax:message="No1" required="true" repeating="true"/>
<param name="X-TEST2" style="header" type="xsd:string" rax:code="404" rax:message="No4" required="true" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" rax:code="402" rax:message="No2" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" rax:code="403" rax:message="No3" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAllAssertions(checker)
wellFormedAndReqHeaderAllAssertions(checker)
xsdAndReqHeaderAllAssertions(checker)
raxCodeReqHeaderAllAssertions(checker)
raxMessageReqHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (rax:code, rax:message) with defaults set") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked with defaults set")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="No1" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="404" rax:message="No4" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="402" rax:message="No2" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="403" rax:message="No3" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.setParamDefaults=true
val checker = builder.build (inWADL, config)
reqTypeAndReqHeaderAssertionsWithDefaults(checker)
wellFormedAndReqHeaderAssertionsWithDefaults(checker)
xsdAndReqHeaderAssertionsWithDefaults(checker)
raxCodeReqHeaderAssertionsWithDefaults(checker)
raxMessageReqHeaderAssertionsWithDefaults(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (dups on)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderDupsOnAssertions(checker)
wellFormedAndReqHeaderDupsOnAssertions(checker)
xsdAndReqHeaderDupsOnAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (dups on, anyMatch=false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST2" style="header" type="xsd:string" required="true" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAllDupsOnAssertions(checker)
wellFormedAndReqHeaderAllDupsOnAssertions(checker)
xsdAndReqHeaderAllDupsOnAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (dups on, rax:code(same))") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderDupsOnAssertions(checker)
wellFormedAndReqHeaderDupsOnAssertions(checker)
xsdAndReqHeaderDupsOnAssertions(checker)
raxCodeReqHeaderDupsOnAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (dups on, rax:code(same), anyMatch=false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="0" type="xsd:string" rax:code="401" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="0" type="xsd:string" rax:code="401" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="0" type="xsd:string" rax:code="401" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="0" type="xsd:string" rax:code="401" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAllDupsOnAssertions(checker)
wellFormedAndReqHeaderAllDupsOnAssertions(checker)
xsdAndReqHeaderAllDupsOnAssertions(checker)
raxCodeReqHeaderAllDupsOnAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (dups on, rax:message(same))") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No!" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderDupsOnAssertions(checker)
wellFormedAndReqHeaderDupsOnAssertions(checker)
xsdAndReqHeaderDupsOnAssertions(checker)
raxMessageReqHeaderDupsOnAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (dups on, rax:message(same), anyMatch=false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" type="xsd:string" rax:message="No!" required="true" repeating="true"/>
<param name="X-TEST2" style="header" type="xsd:string" rax:message="No!" required="true" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" rax:message="No!" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" rax:message="No!" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAllDupsOnAssertions(checker)
wellFormedAndReqHeaderAllDupsOnAssertions(checker)
xsdAndReqHeaderAllDupsOnAssertions(checker)
raxMessageReqHeaderAllDupsOnAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (dups on, rax:code, rax:message(same))") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="No!" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="No!" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="No!" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="No!" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderDupsOnAssertions(checker)
wellFormedAndReqHeaderDupsOnAssertions(checker)
xsdAndReqHeaderDupsOnAssertions(checker)
raxCodeReqHeaderDupsOnAssertions(checker)
raxMessageReqHeaderDupsOnAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (dups on, rax:code, rax:message(same), anyMatch=false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="0" type="xsd:string" rax:code="401" rax:message="No!" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="0" type="xsd:string" rax:code="401" rax:message="No!" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="0" type="xsd:string" rax:code="401" rax:message="No!" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="false" type="xsd:string" rax:code="401" rax:message="No!" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAllDupsOnAssertions(checker)
wellFormedAndReqHeaderAllDupsOnAssertions(checker)
xsdAndReqHeaderAllDupsOnAssertions(checker)
raxCodeReqHeaderAllDupsOnAssertions(checker)
raxMessageReqHeaderAllDupsOnAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (dups on, rax:code, rax:message(same)) defaults should be set") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked and defaults should be set")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="No!" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="No!" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="No!" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="No!" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.setParamDefaults=true
val checker = builder.build (inWADL, config)
reqTypeAndReqHeaderDupsOnAssertionsWithDefaults(checker)
wellFormedAndReqHeaderDupsOnAssertionsWithDefaults(checker)
xsdAndReqHeaderDupsOnAssertionsWithDefaults(checker)
raxCodeReqHeaderDupsOnAssertionsWithDefaults(checker)
raxMessageReqHeaderDupsOnAssertionsWithDefaults(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (dups on, rax:code(diff))") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="404" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="402" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="403" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAssertions(checker)
wellFormedAndReqHeaderAssertions(checker)
xsdAndReqHeaderAssertions(checker)
raxCodeReqHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (dups on, rax:code(diff), anyMatch=false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" type="xsd:string" rax:code="401" required="true" repeating="true"/>
<param name="X-TEST2" style="header" type="xsd:string" rax:code="404" required="true" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" rax:code="402" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" rax:code="403" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAllAssertions(checker)
wellFormedAndReqHeaderAllAssertions(checker)
xsdAndReqHeaderAllAssertions(checker)
raxCodeReqHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (dups on, rax:message(diff))") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No1" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No4" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No2" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:message="No3" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAssertions(checker)
wellFormedAndReqHeaderAssertions(checker)
xsdAndReqHeaderAssertions(checker)
raxMessageReqHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (dups on, rax:message(diff), anyMatch==false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="0" type="xsd:string" rax:message="No1" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="0" type="xsd:string" rax:message="No4" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="false" type="xsd:string" rax:message="No2" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="false" type="xsd:string" rax:message="No3" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAllAssertions(checker)
wellFormedAndReqHeaderAllAssertions(checker)
xsdAndReqHeaderAllAssertions(checker)
raxMessageReqHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (dups on, rax:code, rax:message(diff))") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="No1" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="404" rax:message="No4" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="402" rax:message="No2" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="403" rax:message="No3" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAssertions(checker)
wellFormedAndReqHeaderAssertions(checker)
xsdAndReqHeaderAssertions(checker)
raxCodeReqHeaderAssertions(checker)
raxMessageReqHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (dups on, rax:code, rax:message(diff), anyMatch=false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="0" type="xsd:string" rax:code="401" rax:message="No1" required="true" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="0" type="xsd:string" rax:code="404" rax:message="No4" required="true" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="0" type="xsd:string" rax:code="402" rax:message="No2" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="0" type="xsd:string" rax:code="403" rax:message="No3" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAllAssertions(checker)
wellFormedAndReqHeaderAllAssertions(checker)
xsdAndReqHeaderAllAssertions(checker)
raxCodeReqHeaderAllAssertions(checker)
raxMessageReqHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked (dups on, rax:code, rax:message(diff)) with default values set") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT that must be checked with default values set")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" rax:code="401" rax:message="No1" required="true" default="FOO" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" rax:code="404" rax:message="No4" required="true" default="BAR" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="402" rax:message="No2" required="true" fixed="foo" default="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" rax:code="403" rax:message="No3" required="true" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.setParamDefaults=true
val checker = builder.build (inWADL, config)
reqTypeAndReqHeaderAssertionsWithDefaults(checker)
wellFormedAndReqHeaderAssertionsWithDefaults(checker)
xsdAndReqHeaderAssertionsWithDefaults(checker)
raxCodeReqHeaderAssertionsWithDefaults(checker)
raxMessageReqHeaderAssertionsWithDefaults(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked, non-req should be ignored") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT must be checked, non-req should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:string" required="false" repeating="true"/>
<param name="X-TEST2" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST3" style="header" rax:anyMatch="true" type="xsd:string" required="false" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<param name="X-FOO" style="header" rax:anyMatch="true" type="xsd:string" required="false" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAssertions(checker)
wellFormedAndReqHeaderAssertions(checker)
xsdAndReqHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required header on a PUT that must be checked, non-req should be ignored, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required header on a PUT must be checked, non-req should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" type="xsd:string" required="false" repeating="true"/>
<param name="X-TEST2" style="header" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST3" style="header" type="xsd:string" required="false" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<param name="X-FOO" style="header" type="xsd:string" required="false" fixed="bar" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderAllAssertions(checker)
wellFormedAndReqHeaderAllAssertions(checker)
xsdAndReqHeaderAllAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 7")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header must be checked") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqXSDHeaderAssertions(checker)
wellFormedAndReqXSDHeaderAssertions(checker)
xsdAndReqXSDHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 5")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header must be checked (anyMatch == false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST-INT" style="header" rax:anyMatch="false" type="xsd:int" required="true" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqXSDHeaderAssertions(checker)
wellFormedAndReqXSDHeaderAssertions(checker)
xsdAndReqXSDHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 5")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header must be checked, non-req should be ignored") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header must be checked, non-req should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:string" required="false" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqXSDHeaderAssertions(checker)
wellFormedAndReqXSDHeaderAssertions(checker)
xsdAndReqXSDHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 5")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header must be checked, non-req should be ignored, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header must be checked, non-req should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST-INT" style="header" rax:anyMatch="false" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="false" type="xsd:string" required="false" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqXSDHeaderAssertions(checker)
wellFormedAndReqXSDHeaderAssertions(checker)
xsdAndReqXSDHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 5")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and header must be checked") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and header must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeaderAssertions(checker)
wellFormedAndReqHeaderXSDHeaderAssertions(checker)
xsdAndReqHeaderXSDHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 6")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and header must be checked, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and header must be checked")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="false" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="false" type="xsd:int" required="true" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeaderAssertions(checker)
wellFormedAndReqHeaderXSDHeaderAssertions(checker)
xsdAndReqHeaderXSDHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 6")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required XSD request header and request header must be checked, non-req should be ignored") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required XSD request header and request header must be checked, non-req should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:string" required="false" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeaderAssertions(checker)
wellFormedAndReqHeaderXSDHeaderAssertions(checker)
xsdAndReqHeaderXSDHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 6")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required XSD request header and request header must be checked, non-req should be ignored, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required XSD request header and request header must be checked, non-req should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="false" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="false" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="false" type="xsd:string" required="false" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<method name="POST">
<request>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeaderAssertions(checker)
wellFormedAndReqHeaderXSDHeaderAssertions(checker)
xsdAndReqHeaderXSDHeaderAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 6")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeader2Assertions(checker)
wellFormedAndReqHeaderXSDHeader2Assertions(checker)
xsdAndReqHeaderXSDHeader2Assertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 8")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="false" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="false" type="xsd:int" required="true" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="0" type="xsd:int" required="true" repeating="true"/>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeader2Assertions(checker)
wellFormedAndReqHeaderXSDHeader2Assertions(checker)
xsdAndReqHeaderXSDHeader2Assertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 8")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, non req headers should be ignored") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, nonrequired headers should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:string" required="false" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER-INT" style="header" rax:anyMatch="true" type="xsd:int" required="false" repeating="true"/>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeader2Assertions(checker)
wellFormedAndReqHeaderXSDHeader2Assertions(checker)
xsdAndReqHeaderXSDHeader2Assertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 8")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, non req headers should be ignored, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, nonrequired headers should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" type="xsd:string" required="false" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER-INT" style="header" type="xsd:int" required="false" repeating="true"/>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeader2Assertions(checker)
wellFormedAndReqHeaderXSDHeader2Assertions(checker)
xsdAndReqHeaderXSDHeader2Assertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 8")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, opt on") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, opt on")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
true, true))
reqTypeAndReqHeaderXSDHeader2Assertions(checker)
wellFormedAndReqHeaderXSDHeader2Assertions(checker)
xsdAndReqHeaderXSDHeader2Assertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, opt on, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, opt on")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="0" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="false" type="xsd:int" required="true" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" type="xsd:int" required="true" repeating="true"/>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
true, true))
reqTypeAndReqHeaderXSDHeader2Assertions(checker)
wellFormedAndReqHeaderXSDHeader2Assertions(checker)
xsdAndReqHeaderXSDHeader2Assertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, mixed, multiple similar Headers") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<method name="POST">
<request>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:date" required="true" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeader2MixAssertions(checker)
wellFormedAndReqHeaderXSDHeader2MixAssertions(checker)
xsdAndReqHeaderXSDHeader2MixAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 9")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, mixed, multiple similar Headers, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" type="xsd:int" required="true" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" type="xsd:int" required="true" repeating="true"/>
<method name="POST">
<request>
<param name="X-TEST-OTHER" style="header" type="xsd:date" required="true" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeader2MixAssertions(checker)
wellFormedAndReqHeaderXSDHeader2MixAssertions(checker)
xsdAndReqHeaderXSDHeader2MixAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 9")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, mixed, multiple similar Headers default values should be ignored if feature is not set") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" default="99" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" default="999" repeating="true"/>
<method name="POST">
<request>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:date" required="true" default="2015-11-28" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeader2MixAssertions(checker)
wellFormedAndReqHeaderXSDHeader2MixAssertions(checker)
xsdAndReqHeaderXSDHeader2MixAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 9")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, mixed, multiple similar Headers default values should be set") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers default values should be set")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" default="99" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" default="999" repeating="true"/>
<method name="POST">
<request>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:date" required="true" default="2015-11-28" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val config = TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true)
config.setParamDefaults=true
val checker = builder.build (inWADL, config)
reqTypeAndReqHeaderXSDHeader2MixAssertionsWithDefaults(checker)
wellFormedAndReqHeaderXSDHeader2MixAssertionsWithDefaults(checker)
xsdAndReqHeaderXSDHeader2MixAssertionsWithDefaults(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 9")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, mixed, non req headers should be ignored") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, nonrequired headers should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:string" required="false" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER-INT" style="header" rax:anyMatch="true" type="xsd:int" required="false" repeating="true"/>
<method name="POST">
<request>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:date" required="true" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeader2MixAssertions(checker)
wellFormedAndReqHeaderXSDHeader2MixAssertions(checker)
xsdAndReqHeaderXSDHeader2MixAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 9")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, mixed, non req headers should be ignored, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, nonrequired headers should be ignored")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="false" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="false" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="false" type="xsd:string" required="false" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="0" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER-INT" style="header" rax:anyMatch="0" type="xsd:int" required="false" repeating="true"/>
<method name="POST">
<request>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="0" type="xsd:date" required="true" repeating="true"/>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeader2MixAssertions(checker)
wellFormedAndReqHeaderXSDHeader2MixAssertions(checker)
xsdAndReqHeaderXSDHeader2MixAssertions(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 3")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 9")
}
//
// The following assertions are used to test ReqType and
// ReqTypeFail nodes, and header and xsd header nodes they are used
// in the next couple of tests. Some Header nodes do not have a ReqType.
//
def reqTypeAndReqHeaderXSDHeader2MixAssertionsNoReqType(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSD("X-TEST-OTHER", "xsd:date"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSD("X-TEST-OTHER", "xsd:date"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSD("X-TEST-OTHER", "xsd:date"), Accept)
}
//
// The following assertions are used to test WellFormXML,
// ContentError, and header and xsd header nodes. They are used in
// the next couple of tests. Some Header nodes do not have a ReqType.
//
def wellFormedAndReqHeaderXSDHeader2MixAssertionsNoReqType(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSD("X-TEST-OTHER", "xsd:date"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSD("X-TEST-OTHER", "xsd:date"), Accept)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
}
//
// The following assertions are used to test XSD, ContentError, and
// header and xsd header nodes. They are used in the next couple of
// tests. Some Header nodes do not have a ReqType.
//
def xsdAndReqHeaderXSDHeader2MixAssertionsNoReqType(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), Header("X-TEST", "(?s).*"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, mixed, non req headers should be ignored, checks should occur even if no represetation type is specified.") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, nonrequired headers should be ignored. No representation types are sepecified.")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:string" required="false" repeating="true"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER-INT" style="header" rax:anyMatch="true" type="xsd:int" required="false" repeating="true"/>
<method name="POST">
<request>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:date" required="true" repeating="true"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeader2MixAssertionsNoReqType(checker)
wellFormedAndReqHeaderXSDHeader2MixAssertionsNoReqType(checker)
xsdAndReqHeaderXSDHeader2MixAssertionsNoReqType(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 5")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, mixed, non req headers should be ignored, checks should occur even if no represetation type is specified., anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, nonrequired headers should be ignored. No representation types are sepecified.")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" type="xsd:string" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" type="xsd:string" required="false" repeating="true"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER-INT" style="header" type="xsd:int" required="false" repeating="true"/>
<method name="POST">
<request>
<param name="X-TEST-OTHER" style="header" type="xsd:date" required="true" repeating="true"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeader2MixAssertionsNoReqType(checker)
wellFormedAndReqHeaderXSDHeader2MixAssertionsNoReqType(checker)
xsdAndReqHeaderXSDHeader2MixAssertionsNoReqType(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 5")
}
//
// The following assertions are used to test ReqType and
// ReqTypeFail nodes, and header and xsd header nodes they are used
// in the next couple of tests. Some Header nodes do not have a ReqType.
// Other headers are of differnt types but have the same name.
//
def reqTypeAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameName(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAny("X-TEST", "foo"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAny("X-TEST", "bar"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderXSDAny("X-TEST", "xsd:int"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSDAny("X-TEST-OTHER", "xsd:date"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderAny("X-TEST-OTHER", "22"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSDAny("X-TEST-OTHER", "xsd:date"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSDAny("X-TEST-OTHER", "xsd:dateTime"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderAny("X-TEST-OTHER", "22"), Accept)
}
//
// like reqTypeAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameName
// but assuming anyMatch=false so we use HeaderAll steps.
//
def reqTypeAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameAll(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAllWithMatchAndTypes("X-TEST", "foo|bar", "xsd:int"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderAllWithMatchAndTypes("X-TEST-OTHER", "22","xsd:date xsd:dateTime"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderAllWithMatchAndTypes("X-TEST-OTHER", "22","xsd:date xsd:dateTime"), Accept)
}
//
// Like reqTypeAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameName but remove dups enabled
//
def reqTypeAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameDups(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAny("X-TEST", "foo|bar"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderXSDAny("X-TEST", "xsd:int"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSDAny("X-TEST-OTHER", "xsd:date"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSDAny("X-TEST-OTHER", "xsd:dateTime"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderAny("X-TEST-OTHER", "22"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSDAny("X-TEST-OTHER", "xsd:date"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSDAny("X-TEST-OTHER", "xsd:dateTime"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderAny("X-TEST-OTHER", "22"), Accept)
}
//
// like
// reqTypeAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameDups
// but with anyMatch=false so use HeaderAll steps.
//
def reqTypeAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameDupsAll(checker : NodeSeq) : Unit = {
Then("The machine should contain paths to all ReqTypes")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAllWithMatchAndTypes("X-TEST", "foo|bar", "xsd:int"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"))
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderAllWithMatchAndTypes("X-TEST-OTHER", "22", "xsd:date xsd:dateTime"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("GET"))
And("ReqTypeFail states should be after PUT and POST states")
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqTypeFail)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderAllWithMatchAndTypes("X-TEST-OTHER", "22", "xsd:date xsd:dateTime"), Accept)
}
//
// The following assertions are used to test WellFormXML,
// ContentError, and header and xsd header nodes. They are used in
// the next couple of tests. Some Header nodes do not have a ReqType.
// Other headers are of differnt types but have the same name.
//
def wellFormedAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameName(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAny("X-TEST", "foo"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAny("X-TEST", "bar"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderXSDAny("X-TEST", "xsd:int"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSDAny("X-TEST-OTHER", "xsd:date"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSDAny("X-TEST-OTHER", "xsd:dateTime"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderAny("X-TEST-OTHER", "22"), Accept)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAny("X-TEST", "foo"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAny("X-TEST", "bar"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
}
//
// like
// wellFormedAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameName
// but assuming anyMatch=false so we use HeaderAll steps.
//
def wellFormedAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameAll(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAllWithMatchAndTypes("X-TEST", "foo|bar", "xsd:int"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderAllWithMatchAndTypes("X-TEST-OTHER", "22", "xsd:date xsd:dateTime"), Accept)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAll("X-TEST", "foo|bar"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
}
//
// Like wellFormedAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameName but with remove dups enabled
//
def wellFormedAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameDups(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAny("X-TEST", "foo|bar"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderXSDAny("X-TEST", "xsd:int"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSDAny("X-TEST-OTHER", "xsd:date"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderXSDAny("X-TEST-OTHER", "xsd:dateTime"), Accept)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderAny("X-TEST-OTHER", "22"), Accept)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAny("X-TEST", "foo|bar"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
}
//
// like
// wellFormedAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameDups
// but with anyMatch = false so assume HeaderAll steps.
//
def wellFormedAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameDupsAll(checker : NodeSeq) : Unit = {
And("The machine should contain paths to WellXML and WELLJSON types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAllWithMatchAndTypes("X-TEST", "foo|bar", "xsd:int"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML)
assert (checker, Start, URL("c"), HeaderXSD("X-TEST-INT", "xsd:int"), Method("POST"), HeaderAllWithMatchAndTypes("X-TEST-OTHER", "22", "xsd:date xsd:dateTime"), Accept)
And("There should be content failed states")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAll("X-TEST", "foo|bar"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), ContentFail)
}
//
// The following assertions are used to test XSD, ContentError, and
// header and xsd header nodes. They are used in the next couple of
// tests. Some Header nodes do not have a ReqType.
// Other headers are of differnt types but have the same name.
//
def xsdAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameName(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAny("X-TEST", "foo"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAny("X-TEST", "bar"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderXSDAny("X-TEST", "xsd:int"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// xsdAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameName but with
// anyMatch=false so assume HeaderAll steps.
//
def xsdAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameAll(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAllWithMatchAndTypes("X-TEST", "foo|bar","xsd:int"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// Like xsdAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameDups but with remove dups enabled
//
def xsdAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameDups(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAny("X-TEST", "foo|bar"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderXSDAny("X-TEST", "xsd:int"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
//
// like xsdAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameDups
// but with anyMatch=false so assume HeaderAll steps.
//
def xsdAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameDupsAll(checker : NodeSeq) : Unit = {
And("The machine should cantain paths to XSD types")
assert (checker, Start, URL("a"), URL("b"), Method("PUT"), HeaderAllWithMatchAndTypes("X-TEST", "foo|bar", "xsd:int"), HeaderXSD("X-TEST-INT", "xsd:int"), Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, XSD, Accept)
assert (checker, Start, URL("a"), URL("b"), Method("POST"), ReqType("(application/xml)(;.*)?"), WellXML, ContentFail)
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, mixed (with same name), non req headers should be ignored, checks should occur even if no represetation type is specified.") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers (with same name), nonrequired headers should be ignored. No representation types are sepecified.")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:string" required="false" repeating="true"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER-INT" style="header" rax:anyMatch="true" type="xsd:int" required="false" repeating="true"/>
<method name="POST">
<request>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:date" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:dateTime" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:int" required="true" fixed="22" repeating="true"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameName(checker)
wellFormedAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameName(checker)
xsdAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameName(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 5")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, mixed (with same name), non req headers should be ignored, checks should occur even if no represetation type is specified, anyMatch=false") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers (with same name), nonrequired headers should be ignored. No representation types are sepecified.")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-TEST" style="header" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<param name="X-TEST" style="header" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" type="xsd:string" required="false" repeating="true"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="false" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER-INT" style="header" rax:anyMatch="false" type="xsd:int" required="false" repeating="true"/>
<method name="POST">
<request>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="0" type="xsd:date" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="0" type="xsd:dateTime" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="0" type="xsd:int" required="true" fixed="22" repeating="true"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(false, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameAll(checker)
wellFormedAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameAll(checker)
xsdAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameAll(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 5")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, mixed (with same name), non req headers should be ignored, checks should occur even if no represetation type is specified. (dups on)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers (with same name), nonrequired headers should be ignored. No representation types are sepecified. (dups on)")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<param name="X-TEST" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:string" required="false" repeating="true"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" rax:anyMatch="true" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER-INT" style="header" rax:anyMatch="true" type="xsd:int" required="false" repeating="true"/>
<method name="POST">
<request>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:date" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:dateTime" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" rax:anyMatch="true" type="xsd:int" required="true" fixed="22" repeating="true"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameDups(checker)
wellFormedAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameDups(checker)
xsdAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameDups(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
scenario("The WADL contains PUT and POST operations accepting xml which must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers, mixed (with same name), non req headers should be ignored, checks should occur even if no represetation type is specified. (dups on, anyMatch=false)") {
Given ("a WADL that contains multiple PUT and POST operation with XML that must validate against an XSD, a required request XSD header and request header must be checked, multiple similar Headers (with same name), nonrequired headers should be ignored. No representation types are sepecified. (dups on, anyMatch=false)")
val inWADL =
<application xmlns="http://wadl.dev.java.net/2009/02"
xmlns:rax="http://docs.rackspace.com/api"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<grammars>
<include href="src/test/resources/xsd/test-urlxsd.xsd"/>
</grammars>
<resources base="https://test.api.openstack.com">
<resource path="/a/b">
<method name="PUT">
<request>
<param name="X-TEST" style="header" type="xsd:string" required="true" fixed="foo" repeating="true"/>
<param name="X-TEST" style="header" type="xsd:string" required="true" fixed="bar" repeating="true"/>
<param name="X-TEST" style="header" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-INT" style="header" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" type="xsd:string" required="false" repeating="true"/>
</request>
</method>
<method name="POST">
<request>
<representation mediaType="application/xml"/>
</request>
</method>
</resource>
<resource path="/c">
<param name="X-TEST-INT" style="header" type="xsd:int" required="true" repeating="true"/>
<param name="X-TEST-OTHER-INT" style="header" type="xsd:int" required="false" repeating="true"/>
<method name="POST">
<request>
<param name="X-TEST-OTHER" style="header" type="xsd:date" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" type="xsd:dateTime" required="true" repeating="true"/>
<param name="X-TEST-OTHER" style="header" type="xsd:int" required="true" fixed="22" repeating="true"/>
</request>
</method>
<method name="GET"/>
</resource>
</resources>
</application>
register("test://app/src/test/resources/xsd/test-urlxsd.xsd",
XML.loadFile("src/test/resources/xsd/test-urlxsd.xsd"))
When("the wadl is translated")
val checker = builder.build (inWADL, TestConfig(true, false, true, true, true, 1,
true, false, true, "XalanC",
false, true))
reqTypeAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameDupsAll(checker)
wellFormedAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameDupsAll(checker)
xsdAndReqHeaderXSDHeader2MixAssertionsNoReqTypeSameNameDupsAll(checker)
And("The following assertions should also hold:")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='POST']) = 2")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='PUT']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='METHOD' and @match='GET']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE' and @match='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='REQ_TYPE_FAIL' and @notMatch='(?i)(application/xml)(;.*)?|(?i)(application/json)(;.*)?']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='WELL_JSON']) = 0")
assert (checker, "count(/chk:checker/chk:step[@type='XSD']) = 1")
assert (checker, "count(/chk:checker/chk:step[@type='CONTENT_FAIL']) = 1")
}
}
|
wdschei/api-checker
|
core/src/test/scala/com/rackspace/com/papi/components/checker/wadl/WADLCheckerSpec.scala
|
Scala
|
apache-2.0
| 1,001,516 |
/**
* This file is part of the TA Buddy project.
* Copyright (c) 2012-2014 Alexey Aksenov [email protected]
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Global License version 3
* as published by the Free Software Foundation with the addition of the
* following permission added to Section 15 as permitted in Section 7(a):
* FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED
* BY Limited Liability Company «MEZHGALAKTICHESKIJ TORGOVYJ ALIANS»,
* Limited Liability Company «MEZHGALAKTICHESKIJ TORGOVYJ ALIANS» DISCLAIMS
* THE WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Global License for more details.
* You should have received a copy of the GNU Affero General Global License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA, 02110-1301 USA, or download the license from the following URL:
* http://www.gnu.org/licenses/agpl.html
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Global License.
*
* In accordance with Section 7(b) of the GNU Affero General Global License,
* you must retain the producer line in every report, form or document
* that is created or manipulated using TA Buddy.
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial activities involving the TA Buddy software without
* disclosing the source code of your own applications.
* These activities include: offering paid services to customers,
* serving files in a web or/and network application,
* shipping TA Buddy with a closed source product.
*
* For more information, please contact Digimead Team at this
* address: [email protected]
*/
package org.digimead.tabuddy.desktop.core.support
import java.util.concurrent.ConcurrentHashMap
import scala.collection.JavaConverters.mapAsScalaMapConverter
import scala.collection.immutable
/**
* Condition map that allow to invoke test F(conditions) after each change.
*/
trait ConditionMap[T] {
protected val conditions = new ConcurrentHashMap[String, T].asScala
private val testLock = new Object
/** Invoke user test. */
def test(): Unit = testLock.synchronized { test(conditions.toMap[String, T]) }
/** Set new value. */
def set(key: String, value: Option[T]) = testLock.synchronized {
value match {
case Some(value) ⇒
conditions(key) = value
test
case None ⇒
conditions -= key
test
}
}
/** User test that is based on condition map. */
protected def test(map: immutable.Map[String, T]): Unit
}
|
digimead/digi-TABuddy-desktop
|
part-core/src/main/scala/org/digimead/tabuddy/desktop/core/support/ConditionMap.scala
|
Scala
|
agpl-3.0
| 3,125 |
package bgstats.model
case class RenderedBreakpoint[M](
breakpoint: Breakpoint[M],
abilities: Abilities) {
lazy val achieved: Boolean =
abilities.values.getOrElse(breakpoint.ability, 0) >= breakpoint.minimum
}
|
BardurArantsson/bg-stats
|
src/main/scala/bgstats/model/RenderedBreakpoint.scala
|
Scala
|
apache-2.0
| 223 |
package com.sk.app.proxmock.application.domain.providers.body
import com.jayway.restassured.RestAssured._
import com.sk.app.proxmock.BaseIntegrationTest
import org.hamcrest.Matchers._
/**
* Created by szymo on 25/11/2016.
*/
class StaticBodyProviderTest extends BaseIntegrationTest("/mock") {
val expectedBody = "expectedBodyValue"
override def endpointsYaml(): String =
s"""
|- path: ${url("static/body/provider")}
| method: GET
| action:
| mockResponse:
| body:
| static: "$expectedBody"
"""
"StaticBodyProvider" should "return specified body with no changes (as is)" in {
get(url("static/body/provider"))
.`then`()
.body(equalTo(expectedBody))
}
}
|
szymonkudzia/proxmock
|
sources/src/test/scala/com/sk/app/proxmock/application/domain/providers/body/StaticBodyProviderTest.scala
|
Scala
|
mit
| 748 |
// Copyright 2016 zakski.
// See the LICENCE.txt file distributed with this work for additional
// information regarding copyright ownership.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.szadowsz.maeve.core.instruction.target.multi.feeder
import com.szadowsz.maeve.core.instruction.target.multi.MultiTarget
import scala.collection.mutable.ArrayBuffer
/**
* Trait for the scenario in which we need to add to the target sequence mid run.
*
* Created on 18/10/2016.
*/
trait FeederTarget[T <: Any,P <: FeederTarget[T,P]] extends MultiTarget[T,P] {
override val seq: ArrayBuffer[T]
/**
* Method to add a value to the end of the queue
*
* @param value the added value
*/
def addToQueue(value : T) : Unit = seq += value
}
|
zakski/project-maeve
|
src/main/scala/com/szadowsz/maeve/core/instruction/target/multi/feeder/FeederTarget.scala
|
Scala
|
apache-2.0
| 1,272 |
package chapter08
/**
* 8.4 간단한 형태의 함수 리터럴
*/
object c08_i04 {
val someNumbers = List(-11, -10, 0, 5, 10)
someNumbers.filter((x: Int) => x > 0)
/*
* 함수 리터럴을 좀 더 간단하게 만드는 방법은 인자의 타입을 제거하는 것
* someNumbers 는 List[Int] 이므로
* 스칼라 컴파일러는 인자로 넘겨진 x가 Int 타입인 것을 추론할 수 있다.
*
* 이를 타깃 타이핑이라 함
*/
someNumbers.filter(x => x > 0)
}
|
seraekim/srkim-lang-scala
|
src/main/java/chapter08/c08_i04.scala
|
Scala
|
bsd-3-clause
| 506 |
/**
* Copyright (C) 2016 Pau Carré Cardona - All Rights Reserved
* You may use, distribute and modify this code under the
* terms of the Apache License v2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt).
*/
package db
import core.Crop
import db.Dataset._
import slick.driver.H2Driver.api._
class BoundingBoxTable(tag: Tag) extends Table[BoundingBox](tag, "BOUNDING_BOX") {
def name = column[String]("FILE_NAME", O.PrimaryKey)
def top = column[Int]("TOP")
def left = column[Int]("LEFT")
def bottom = column[Int]("BOTTOM")
def right = column[Int]("RIGHT")
def width = column[Int]("WIDTH")
def height = column[Int]("HEIGHT")
def dataset = column[Dataset]("DATASET")
def * = (name, top, left, bottom, right, width, height, dataset) <>(BoundingBox.tupled, BoundingBox.unapply)
}
case class BoundingBox(name: String, top: Int,
left: Int, bottom: Int, right: Int, width: Int, height: Int, dataset: Dataset) {
def toCrop = Crop(left, right, top, bottom)
def div(denominator: Double) = BoundingBox(
name = name,
top = (top.toDouble / denominator).ceil.toInt,
left = (left.toDouble / denominator).ceil.toInt,
bottom = (bottom.toDouble / denominator).ceil.toInt,
right = (right.toDouble / denominator).ceil.toInt,
width = (width.toDouble / denominator).ceil.toInt,
height = (height.toDouble / denominator).ceil.toInt,
dataset = dataset)
}
|
paucarre/tiefvision
|
src/scala/tiefvision-web/app/db/BoundingBoxTable.scala
|
Scala
|
apache-2.0
| 1,449 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.jdbc
import java.sql.{Connection, Types}
import org.apache.spark.sql.execution.datasources.jdbc.{JDBCOptions, JdbcUtils}
import org.apache.spark.sql.types._
private object PostgresDialect extends JdbcDialect {
override def canHandle(url: String): Boolean = url.startsWith("jdbc:postgresql")
override def getCatalystType(
sqlType: Int, typeName: String, size: Int, md: MetadataBuilder): Option[DataType] = {
if (sqlType == Types.REAL) {
Some(FloatType)
} else if (sqlType == Types.SMALLINT) {
Some(ShortType)
} else if (sqlType == Types.BIT && typeName.equals("bit") && size != 1) {
Some(BinaryType)
} else if (sqlType == Types.OTHER) {
Some(StringType)
} else if (sqlType == Types.ARRAY) {
val scale = md.build.getLong("scale").toInt
// postgres array type names start with underscore
toCatalystType(typeName.drop(1), size, scale).map(ArrayType(_))
} else None
}
private def toCatalystType(
typeName: String,
precision: Int,
scale: Int): Option[DataType] = typeName match {
case "bool" => Some(BooleanType)
case "bit" => Some(BinaryType)
case "int2" => Some(ShortType)
case "int4" => Some(IntegerType)
case "int8" | "oid" => Some(LongType)
case "float4" => Some(FloatType)
case "money" | "float8" => Some(DoubleType)
case "text" | "varchar" | "char" | "cidr" | "inet" | "json" | "jsonb" | "uuid" =>
Some(StringType)
case "bytea" => Some(BinaryType)
case "timestamp" | "timestamptz" | "time" | "timetz" => Some(TimestampType)
case "date" => Some(DateType)
case "numeric" | "decimal" => Some(DecimalType.bounded(precision, scale))
case _ => None
}
override def getJDBCType(dt: DataType): Option[JdbcType] = dt match {
case StringType => Some(JdbcType("TEXT", Types.CHAR))
case BinaryType => Some(JdbcType("BYTEA", Types.BINARY))
case BooleanType => Some(JdbcType("BOOLEAN", Types.BOOLEAN))
case FloatType => Some(JdbcType("FLOAT4", Types.FLOAT))
case DoubleType => Some(JdbcType("FLOAT8", Types.DOUBLE))
case ShortType => Some(JdbcType("SMALLINT", Types.SMALLINT))
case t: DecimalType => Some(
JdbcType(s"NUMERIC(${t.precision},${t.scale})", java.sql.Types.NUMERIC))
case ArrayType(et, _) if et.isInstanceOf[AtomicType] =>
getJDBCType(et).map(_.databaseTypeDefinition)
.orElse(JdbcUtils.getCommonJDBCType(et).map(_.databaseTypeDefinition))
.map(typeName => JdbcType(s"$typeName[]", java.sql.Types.ARRAY))
case ByteType => throw new IllegalArgumentException(s"Unsupported type in postgresql: $dt");
case _ => None
}
override def getTableExistsQuery(table: String): String = {
s"SELECT 1 FROM $table LIMIT 1"
}
override def isCascadingTruncateTable(): Option[Boolean] = Some(false)
/**
* The SQL query used to truncate a table. For Postgres, the default behaviour is to
* also truncate any descendant tables. As this is a (possibly unwanted) side-effect,
* the Postgres dialect adds 'ONLY' to truncate only the table in question
* @param table The table to truncate
* @param cascade Whether or not to cascade the truncation. Default value is the value of
* isCascadingTruncateTable(). Cascading a truncation will truncate tables
* with a foreign key relationship to the target table. However, it will not
* truncate tables with an inheritance relationship to the target table, as
* the truncate query always includes "ONLY" to prevent this behaviour.
* @return The SQL query to use for truncating a table
*/
override def getTruncateQuery(
table: String,
cascade: Option[Boolean] = isCascadingTruncateTable): String = {
cascade match {
case Some(true) => s"TRUNCATE TABLE ONLY $table CASCADE"
case _ => s"TRUNCATE TABLE ONLY $table"
}
}
override def beforeFetch(connection: Connection, properties: Map[String, String]): Unit = {
super.beforeFetch(connection, properties)
// According to the postgres jdbc documentation we need to be in autocommit=false if we actually
// want to have fetchsize be non 0 (all the rows). This allows us to not have to cache all the
// rows inside the driver when fetching.
//
// See: https://jdbc.postgresql.org/documentation/head/query.html#query-with-cursor
//
if (properties.getOrElse(JDBCOptions.JDBC_BATCH_FETCH_SIZE, "0").toInt > 0) {
connection.setAutoCommit(false)
}
}
}
|
tejasapatil/spark
|
sql/core/src/main/scala/org/apache/spark/sql/jdbc/PostgresDialect.scala
|
Scala
|
apache-2.0
| 5,368 |
/*
* Copyright 2014 Databricks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.databricks.spark
import org.apache.commons.csv.CSVFormat
import org.apache.hadoop.io.compress.CompressionCodec
import org.apache.spark.sql.{DataFrame, SQLContext}
import com.databricks.spark.csv.util.TextFile
package object csv {
/**
* Adds a method, `csvFile`, to SQLContext that allows reading CSV data.
*/
implicit class CsvContext(sqlContext: SQLContext) {
def csvFile(filePath: String,
useHeader: Boolean = true,
delimiter: Char = ',',
quote: Char = '"',
escape: Character = null,
comment: Character = null,
mode: String = "PERMISSIVE",
parserLib: String = "COMMONS",
ignoreLeadingWhiteSpace: Boolean = false,
ignoreTrailingWhiteSpace: Boolean = false,
charset: String = TextFile.DEFAULT_CHARSET.name(),
inferSchema: Boolean = false) = {
val csvRelation = CsvRelation(
location = filePath,
useHeader = useHeader,
delimiter = delimiter,
quote = quote,
escape = escape,
comment = comment,
parseMode = mode,
parserLib = parserLib,
ignoreLeadingWhiteSpace = ignoreLeadingWhiteSpace,
ignoreTrailingWhiteSpace = ignoreTrailingWhiteSpace,
charset = charset,
inferCsvSchema = inferSchema)(sqlContext)
sqlContext.baseRelationToDataFrame(csvRelation)
}
def tsvFile(filePath: String,
useHeader: Boolean = true,
parserLib: String = "COMMONS",
ignoreLeadingWhiteSpace: Boolean = false,
ignoreTrailingWhiteSpace: Boolean = false,
charset: String = TextFile.DEFAULT_CHARSET.name(),
inferSchema: Boolean = false) = {
val csvRelation = CsvRelation(
location = filePath,
useHeader = useHeader,
delimiter = '\\t',
quote = '"',
escape = '\\\\',
comment = '#',
parseMode = "PERMISSIVE",
parserLib = parserLib,
ignoreLeadingWhiteSpace = ignoreLeadingWhiteSpace,
ignoreTrailingWhiteSpace = ignoreTrailingWhiteSpace,
charset = charset,
inferCsvSchema = inferSchema)(sqlContext)
sqlContext.baseRelationToDataFrame(csvRelation)
}
}
implicit class CsvSchemaRDD(dataFrame: DataFrame) {
/**
* Saves DataFrame as csv files. By default uses ',' as delimiter, and includes header line.
*/
def saveAsCsvFile(path: String, parameters: Map[String, String] = Map(),
compressionCodec: Class[_ <: CompressionCodec] = null): Unit = {
// TODO(hossein): For nested types, we may want to perform special work
val delimiter = parameters.getOrElse("delimiter", ",")
val delimiterChar = if (delimiter.length == 1) {
delimiter.charAt(0)
} else {
throw new Exception("Delimiter cannot be more than one character.")
}
val escape = parameters.getOrElse("escape", null)
val escapeChar: Character = if (escape == null) {
null
} else if (escape.length == 1) {
escape.charAt(0)
} else {
throw new Exception("Escape character cannot be more than one character.")
}
val quoteChar = parameters.get("quote") match {
case Some(s) => {
if (s.length == 1) {
Some(s.charAt(0))
} else {
throw new Exception("Quotation cannot be more than one character.")
}
}
case None => None
}
val csvFormatBase = CSVFormat.DEFAULT
.withDelimiter(delimiterChar)
.withEscape(escapeChar)
.withSkipHeaderRecord(false)
.withNullString("null")
val csvFormat = quoteChar match {
case Some(c) => csvFormatBase.withQuote(c)
case _ => csvFormatBase
}
val generateHeader = parameters.getOrElse("header", "false").toBoolean
val header = if (generateHeader) {
csvFormat.format(dataFrame.columns.map(_.asInstanceOf[AnyRef]):_*)
} else {
"" // There is no need to generate header in this case
}
val strRDD = dataFrame.rdd.mapPartitionsWithIndex { case (index, iter) =>
val csvFormatBase = CSVFormat.DEFAULT
.withDelimiter(delimiterChar)
.withEscape(escapeChar)
.withSkipHeaderRecord(false)
.withNullString("null")
val csvFormat = quoteChar match {
case Some(c) => csvFormatBase.withQuote(c)
case _ => csvFormatBase
}
new Iterator[String] {
var firstRow: Boolean = generateHeader
override def hasNext = iter.hasNext || firstRow
override def next: String = {
if(!iter.isEmpty) {
val row = csvFormat.format(iter.next.toSeq.map(_.asInstanceOf[AnyRef]):_*)
if (firstRow) {
firstRow = false
header + csvFormat.getRecordSeparator() + row
} else {
row
}
} else {
firstRow = false
header
}
}
}
}
compressionCodec match {
case null => strRDD.saveAsTextFile(path)
case codec => strRDD.saveAsTextFile(path, codec)
}
}
}
}
|
saurfang/spark-csv
|
src/main/scala/com/databricks/spark/csv/package.scala
|
Scala
|
apache-2.0
| 5,955 |
package chat.tox.antox.activities
import java.util.regex.Pattern
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v4.app.NavUtils
import android.support.v7.app.AppCompatActivity
import android.text.Html
import android.text.method.LinkMovementMethod
import android.text.util.Linkify
import android.view.{WindowManager, MenuItem}
import android.widget.TextView
import chat.tox.antox.R
class ToxMeInfoActivity extends AppCompatActivity{
protected override def onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_toxme_info)
getSupportActionBar.setHomeButtonEnabled(true)
getSupportActionBar.setDisplayHomeAsUpEnabled(true)
getWindow.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
getWindow.setStatusBarColor(Color.parseColor("#202020"))
getSupportActionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#24221f")))
val toxMeWebsite = findViewById(R.id.toxme_info_website).asInstanceOf[TextView]
toxMeWebsite.setMovementMethod(LinkMovementMethod.getInstance)
toxMeWebsite.setText(Html.fromHtml(getResources.getString(R.string.toxme_website)))
val sourceURLTextView = findViewById(R.id.toxme_source).asInstanceOf[TextView]
val pattern = Pattern.compile("https://github.com/LittleVulpix/toxme")
Linkify.addLinks(sourceURLTextView, pattern, "")
}
override def onOptionsItemSelected(item: MenuItem): Boolean ={
item.getItemId match{
case android.R.id.home =>
finish()
true
case _ =>
super.onOptionsItemSelected(item)
}
}
}
|
wiiam/Antox
|
app/src/main/scala/chat/tox/antox/activities/ToxMeInfoActivity.scala
|
Scala
|
gpl-3.0
| 1,696 |
// https://leetcode.com/problems/longest-common-prefix
object Solution {
def longestCommonPrefix(strings: Array[String]): String =
strings reduceOption commonPrefix getOrElse ""
def commonPrefix(x: String, y: String): String =
if (y startsWith x) x else commonPrefix(x.init, y)
}
|
airt/codegames
|
leetcode/014-longest-common-prefix.scala
|
Scala
|
mit
| 296 |
object SCL6716{
val l: List[String] = List("another string").collect(/*start*/_ match { case s: String => s }/*end*/)
}
//PartialFunction[String, NotInferedB]
|
ilinum/intellij-scala
|
testdata/typeInference/bugs5/SCL6716.scala
|
Scala
|
apache-2.0
| 161 |
/**
* Copyright (c) 2015, Cloudera, Inc. All Rights Reserved.
*
* Cloudera, Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"). You may not use this file except in
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for
* the specific language governing permissions and limitations under the
* License.
*/
package com.cloudera.sparkts
import breeze.linalg._
import com.cloudera.sparkts.TimeSeriesStatisticalTests._
import org.apache.commons.math.stat.regression.OLSMultipleLinearRegression
import org.apache.commons.math3.random.MersenneTwister
import org.scalatest.{FunSuite, ShouldMatchers}
class TimeSeriesStatisticalTestsSuite extends FunSuite with ShouldMatchers {
test("breusch-godfrey") {
// Replicating the example provided by R package lmtest for bgtest
val rand = new MersenneTwister(5L)
val n = 100
val coef = 0.5 // coefficient for lagged series
val x = Array.fill(n / 2)(Array(1.0, -1.0)).flatten
// stationary series
val y1 = x.map(_ + 1 + rand.nextGaussian())
// AR(1) series, recursive filter with coef coefficient
val y2 = y1.scanLeft(0.0) { case (prior, curr) => prior * coef + curr }.tail
val pthreshold = 0.05
val OLS1 = new OLSMultipleLinearRegression()
OLS1.newSampleData(y1, x.map(Array(_)))
val resids1 = OLS1.estimateResiduals()
val OLS2 = new OLSMultipleLinearRegression()
OLS2.newSampleData(y2, x.map(Array(_)))
val resids2 = OLS2.estimateResiduals()
// there should be no evidence of serial correlation
bgtest(new DenseVector(resids1), new DenseMatrix(x.length, 1, x), 1)._2 should be > pthreshold
bgtest(new DenseVector(resids1), new DenseMatrix(x.length, 1, x), 4)._2 should be > pthreshold
// there should be evidence of serial correlation
bgtest(new DenseVector(resids2), new DenseMatrix(x.length, 1, x), 1)._2 should be < pthreshold
bgtest(new DenseVector(resids2), new DenseMatrix(x.length, 1, x), 4)._2 should be < pthreshold
}
test("breusch-pagan") {
// Replicating the example provided by R package lmtest for bptest
val rand = new MersenneTwister(5L)
val n = 100
val x = Array.fill(n / 2)(Array(-1.0, 1.0)).flatten
// homoskedastic residuals with variance 1 throughout
val err1 = Array.fill(n)(rand.nextGaussian)
// heteroskedastic residuals with alternating variance of 1 and 4
val varFactor = 2
val err2 = err1.zipWithIndex.map { case (x, i) => if(i % 2 == 0) x * varFactor else x }
// generate dependent variables
val y1 = x.zip(err1).map { case (xi, ei) => xi + ei + 1 }
val y2 = x.zip(err2).map { case (xi, ei) => xi + ei + 1 }
// create models and calculate residuals
val OLS1 = new OLSMultipleLinearRegression()
OLS1.newSampleData(y1, x.map(Array(_)))
val resids1 = OLS1.estimateResiduals()
val OLS2 = new OLSMultipleLinearRegression()
OLS2.newSampleData(y2, x.map(Array(_)))
val resids2 = OLS2.estimateResiduals()
val pthreshold = 0.05
// there should be no evidence of heteroskedasticity
bptest(new DenseVector(resids1), new DenseMatrix(x.length, 1, x))._2 should be > pthreshold
// there should be evidence of heteroskedasticity
bptest(new DenseVector(resids2), new DenseMatrix(x.length, 1, x))._2 should be < pthreshold
}
test("ljung-box test") {
val rand = new MersenneTwister(5L)
val n = 100
val indep = Array.fill(n)(rand.nextGaussian)
val vecIndep = new DenseVector(indep)
val (stat1, pval1) = lbtest(vecIndep, 1)
pval1 > 0.05
// serially correlated
val coef = 0.3
val dep = indep.scanLeft(0.0) { case (prior, curr) => prior * coef + curr }.tail
val vecDep = new DenseVector(dep)
val (stat2, pval2) = lbtest(vecDep, 2)
pval2 < 0.05
}
}
|
pronix/spark-timeseries
|
src/test/scala/com/cloudera/sparkts/TimeSeriesStatisticalTestsSuite.scala
|
Scala
|
apache-2.0
| 4,086 |
package org.bizzle.tester.criteria
/**
* Created by IntelliJ IDEA.
* User: Jason
* Date: 12/19/11
* Time: 9:21 PM
*/
sealed trait TestingFlag
object TestingFlag {
val flags = Set[TestToggleFlag](Talkative, StackTrace)
}
sealed trait TestToggleFlag extends TestingFlag {
implicit def flag2Criteria(that: TestToggleFlag) = TestCriteriaToggleFlag(that)
}
case object Talkative extends TestToggleFlag // Enables the "Here, let me draw that for you on the map!" thing in PathFindingCore tests; overall, gives tests permission to println
case object StackTrace extends TestToggleFlag // Signifies the desire to see stacktraces when tests fail as a result of throwing exceptions
sealed trait TestRunningnessFlag extends TestingFlag {
protected def isRunning : Boolean
/*none */ def flip : TestRunningnessFlag = TestRunningnessFlag(!isRunning)
}
object TestRunningnessFlag {
def apply(isRunning: Boolean) = if (isRunning) RunTest else SkipTest
}
case object RunTest extends TestRunningnessFlag {
override protected def isRunning = true
}
case object SkipTest extends TestRunningnessFlag {
override protected def isRunning = false
}
|
TheBizzle/Tester
|
src/main/org/bizzle/tester/criteria/TestingFlag.scala
|
Scala
|
bsd-3-clause
| 1,177 |
/*
* Copyright (c) 2013-2015 Commonwealth Computer Research, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License, Version 2.0 which
* accompanies this distribution and is available at
* http://www.opensource.org/licenses/apache2.0.php.
*/
package org.locationtech.geomesa.curve
import org.junit.runner.RunWith
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner
@RunWith(classOf[JUnitRunner])
class Z3RangeTest extends Specification {
"Z3Range" should {
val zmin = Z3(2, 2, 0)
val zmax = Z3(3, 6, 0)
val range = Z3Range(zmin, zmax)
"require ordered min and max" >> {
Z3Range(Z3(2, 2, 0), Z3(1, 4, 0)) // should be valid
Z3Range(zmax, zmin) should throwA[IllegalArgumentException]
}
"support cut" >> {
"for uncuttable ranges" >> {
val range = Z3Range(zmin, zmin)
Z3.cut(range, Z3(0, 0, 0), inRange = false) must beEmpty
}
"for out of range zs" >> {
val zcut = Z3(5, 1, 0)
Z3.cut(range, zcut, inRange = false) mustEqual
List(Z3Range(zmin, Z3(3, 3, 0)), Z3Range(Z3(2, 4, 0), zmax))
}
"for in range zs" >> {
val zcut = Z3(3, 4, 0)
Z3.cut(range, zcut, inRange = true) mustEqual
List(Z3Range(zmin, Z3(3, 4, 0)), Z3Range(Z3(2, 5, 0), zmax))
}.pendingUntilFixed("should cut point be included in outputs?")
}
"support length" >> {
range.length mustEqual 130
}
"support overlaps" >> {
range.overlapsInUserSpace(range) must beTrue
range.overlapsInUserSpace(Z3Range(Z3(3, 0, 0), Z3(3, 2, 0))) must beTrue
range.overlapsInUserSpace(Z3Range(Z3(0, 0, 0), Z3(2, 2, 0))) must beTrue
range.overlapsInUserSpace(Z3Range(Z3(1, 6, 0), Z3(4, 6, 0))) must beTrue
range.overlapsInUserSpace(Z3Range(Z3(2, 0, 0), Z3(3, 1, 0))) must beFalse
range.overlapsInUserSpace(Z3Range(Z3(4, 6, 0), Z3(6, 7, 0))) must beFalse
}
"support contains ranges" >> {
range.containsInUserSpace(range) must beTrue
range.containsInUserSpace(Z3Range(Z3(2, 2, 0), Z3(3, 3, 0))) must beTrue
range.containsInUserSpace(Z3Range(Z3(3, 5, 0), Z3(3, 6, 0))) must beTrue
range.containsInUserSpace(Z3Range(Z3(2, 2, 0), Z3(4, 3, 0))) must beFalse
range.containsInUserSpace(Z3Range(Z3(2, 1, 0), Z3(3, 3, 0))) must beFalse
range.containsInUserSpace(Z3Range(Z3(2, 1, 0), Z3(3, 7, 0))) must beFalse
}
}
}
|
giserh/geomesa
|
geomesa-z3/src/test/scala/org/locationtech/geomesa/curve/Z3RangeTest.scala
|
Scala
|
apache-2.0
| 2,513 |
package com.ponkotuy.parser
import scala.util.parsing.combinator._
object PCQParser extends RegexParsers {
override def skipWhitespace = true
override val whiteSpace = """(#.*\\n|\\s)+""".r
def name = """[a-z\\_]\\w*""".r
def typ = """[A-Z]\\w*""".r
def column = name ~ typ ^^ { case n ~ t => Column(n, t) }
def columns = "{" ~> rep(column) <~ "}"
def table = "table" ~> name ~ columns ^^ { case n ~ cs => Table(n, cs) }
def apply(input: String): Either[String, Any] = parseAll(table, input) match {
case Success(result, _) => Right(result)
case NoSuccess(msg, _) => Left(msg)
}
case class Table(name: String, columns: List[Column])
case class Column(name: String, typ: String)
}
|
ponkotuy/ScalaDBCompiler
|
src/main/scala/com/ponkotuy/parser/PCQParser.scala
|
Scala
|
mit
| 711 |
/*
* Copyright 2022 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package iht.controllers.application.declaration
import iht.config.AppConfig
import iht.connector.IhtConnector
import iht.controllers.ControllerHelper
import iht.controllers.application.ApplicationControllerTest
import iht.forms.ApplicationForms._
import iht.metrics.IhtMetrics
import iht.models.application.assets._
import iht.models.application.basicElements.ShareableBasicEstateElement
import iht.models.application.exemptions.{AllExemptions, PartnerExemption}
import iht.models.application.tnrb.TnrbEligibiltyModel
import iht.models.enums.StatsSource
import iht.models.{CoExecutor, ContactDetails}
import iht.testhelpers.CommonBuilder
import iht.utils.ApplicationStatus
import iht.views.html.application.declaration.declaration
import iht.views.html.estateReports.estateReports_error_serviceUnavailable
import org.joda.time.LocalDate
import org.mockito.ArgumentMatchers._
import org.mockito.Mockito.when
import play.api.http.Status.OK
import play.api.mvc.MessagesControllerComponents
import play.api.test.Helpers._
import play.api.test.{FakeHeaders, FakeRequest}
import uk.gov.hmrc.http.{GatewayTimeoutException, HeaderCarrier, UpstreamErrorResponse}
import uk.gov.hmrc.play.bootstrap.frontend.controller.FrontendController
import scala.concurrent.Future
class DeclarationControllerTest extends ApplicationControllerTest {
// Implicit objects required by play framework.
implicit val headerCarrier = FakeHeaders()
implicit val request = FakeRequest()
implicit val hc = new HeaderCarrier
val ihtReferenceNo = "XXX"
protected abstract class TestController extends FrontendController(mockControllerComponents) with DeclarationController {
override val cc: MessagesControllerComponents = mockControllerComponents
override implicit val appConfig: AppConfig = mockAppConfig
override val declarationView: declaration = app.injector.instanceOf[declaration]
override val estateReportsErrorServiceUnavailableView: estateReports_error_serviceUnavailable = app.injector.instanceOf[estateReports_error_serviceUnavailable]
}
def declarationController = new TestController {
override val cachingConnector = mockCachingConnector
override val ihtConnector = mockIhtConnector
override val authConnector = mockAuthConnector
override lazy val metrics: IhtMetrics = mock[IhtMetrics]
}
def declarationControllerNotAuthorised = new TestController {
override val cachingConnector = mockCachingConnector
override val ihtConnector = mockIhtConnector
override val authConnector = mockAuthConnector
override lazy val metrics: IhtMetrics = mock[IhtMetrics]
}
def mockForApplicationStatus(requiredStatus: String, coExecutorsEnabled: Boolean = false) = {
val coExecutorsFromLookup = if (coExecutorsEnabled) {
Seq(CoExecutor(None, "firstName", None, "lastName", LocalDate.now(), "nino", None, None, ContactDetails("phoneNo"), None, None))
} else {
Seq.empty[CoExecutor]
}
val regDetails = CommonBuilder.buildRegistrationDetails copy(
ihtReference = Some(ihtReferenceNo),
status = requiredStatus,
coExecutors = coExecutorsFromLookup
)
createMockToGetRegDetailsFromCacheNoOption(mockCachingConnector, Future.successful(Some(regDetails)))
createMockToGetCaseDetails(mockIhtConnector, regDetails)
createMockToGetRegDetailsFromCache(mockCachingConnector, Some(regDetails))
}
"declaration controller" must {
"return correct riskMessageFromEdh when there is no money entered" in {
val testConnector = mock[IhtConnector]
val regDetails = CommonBuilder.buildRegistrationDetails
val appDetails = CommonBuilder.buildApplicationDetails
createMockToGetRealtimeRiskMessage(testConnector, Option("Risk Message"))
await(declarationController.realTimeRiskingMessage(appDetails, regDetails.ihtReference.get, "AB123456C", testConnector)) mustBe Some("Risk Message")
}
"return correct riskMessageFromEdh when there is money value of zero" in {
val testConnector = mock[IhtConnector]
val regDetails = CommonBuilder.buildRegistrationDetails
createMockToGetRealtimeRiskMessage(testConnector, Option("Risk Message"))
val appDetails = {
val allAssets = CommonBuilder.buildAllAssets.copy(
money = Some(CommonBuilder.buildShareableBasicElementExtended.copy(
Some(BigDecimal(0)), None, Some(true), Some(false)))
)
CommonBuilder.buildApplicationDetails.copy(allAssets = Some(allAssets))
}
await(declarationController.realTimeRiskingMessage(appDetails, regDetails.ihtReference.get, "AB123456C", testConnector)) mustBe Some("Risk Message")
}
"return None when there is money value which is non-zero" in {
val testConnector = mock[IhtConnector]
val regDetails = CommonBuilder.buildRegistrationDetails
val riskMessage = Some("Risk Message")
createMockToGetRealtimeRiskMessage(testConnector, riskMessage)
val appDetails = {
val allAssets = CommonBuilder.buildAllAssets.copy(
money = Some(CommonBuilder.buildShareableBasicElementExtended.copy(
Some(BigDecimal(10)), None, Some(true), Some(false)))
)
CommonBuilder.buildApplicationDetails.copy(allAssets = Some(allAssets))
}
await(declarationController.realTimeRiskingMessage(appDetails, regDetails.ihtReference.get, "AB123456C", testConnector)) mustBe None
}
"return correct riskMessageFromEdh when there is money value of None" in {
val testConnector = mock[IhtConnector]
val regDetails = CommonBuilder.buildRegistrationDetails
val riskMessage = Some("Risk Message")
createMockToGetRealtimeRiskMessage(testConnector, riskMessage)
val appDetails = {
val allAssets = CommonBuilder.buildAllAssets.copy(
money = Some(CommonBuilder.buildShareableBasicElementExtended.copy(
None, None, Some(true), Some(false)))
)
CommonBuilder.buildApplicationDetails.copy(allAssets = Some(allAssets))
}
await(declarationController.realTimeRiskingMessage(appDetails, regDetails.ihtReference.get, "AB123456C", testConnector)) mustBe riskMessage
}
"return None when there is an error in getting risk message" in {
val testConnector = mock[IhtConnector]
val regDetails = CommonBuilder.buildRegistrationDetails
val appDetails = CommonBuilder.buildApplicationDetails
val riskMessage = Some("Risk Message")
createMockToGetRealtimeRiskMessage(testConnector, riskMessage)
when(testConnector.getRealtimeRiskingMessage(any(), any())(any()))
.thenThrow(new RuntimeException("error"))
a[RuntimeException] mustBe thrownBy{
await(declarationController.realTimeRiskingMessage(appDetails, regDetails.ihtReference.get, "AB123456C", testConnector))
}
}
"return correct riskMessageFromEdh when the money entered is of value 0 and shared value is None" in {
val testConnector = mock[IhtConnector]
val regDetails = CommonBuilder.buildRegistrationDetails
val appDetails = CommonBuilder.buildApplicationDetails
val riskMessage = Some("Risk Message")
createMockToGetRealtimeRiskMessage(testConnector, riskMessage)
val ad = appDetails.copy(allAssets = Some(CommonBuilder.buildAllAssets.copy(
money = Some(ShareableBasicEstateElement(
value = Some(BigDecimal(0)),
shareValue = None,
isOwned = None,
isOwnedShare = None)))))
await(declarationController.realTimeRiskingMessage(ad, regDetails.ihtReference.get, "AB123456C", testConnector)) mustBe riskMessage
}
"return correct riskMessageFromEdh when the money owed and shared value are entered as 0" in {
val testConnector = mock[IhtConnector]
val regDetails = CommonBuilder.buildRegistrationDetails
val appDetails = CommonBuilder.buildApplicationDetails
val ad = appDetails.copy(allAssets = Some(CommonBuilder.buildAllAssets.copy(
money = Some(ShareableBasicEstateElement(
value = Some(BigDecimal(0)),
shareValue = Some(BigDecimal(0)),
isOwned = None,
isOwnedShare = None)))))
val riskMessage = Some("Risk Message")
createMockToGetRealtimeRiskMessage(testConnector, riskMessage)
await(declarationController.realTimeRiskingMessage(ad, regDetails.ihtReference.get, "AB123456C", testConnector)) mustBe riskMessage
}
"return riskMessageFromEdh as None when there is non zero money value" in {
val regDetails = CommonBuilder.buildRegistrationDetails
val appDetails = CommonBuilder.buildApplicationDetails
val ad = appDetails.copy(allAssets = Some(CommonBuilder.buildAllAssets.copy(
money = Some(ShareableBasicEstateElement(
value = Some(BigDecimal(100)),
shareValue = None,
isOwned = None,
isOwnedShare = None)))))
await(declarationController.realTimeRiskingMessage(ad, regDetails.ihtReference.get, "AB123456C", mockIhtConnector)) mustBe empty
}
"redirect to GG login page on PageLoad if the user is not logged in" in {
val result = declarationController.onPageLoad()(createFakeRequest(isAuthorised = false))
status(result) must be(SEE_OTHER)
redirectLocation(result) must be (Some(loginUrl))
}
"redirect to login page on Submit if the user is not logged in" in {
val result = declarationControllerNotAuthorised.onSubmit(createFakeRequest(isAuthorised = false))
status(result) must be(SEE_OTHER)
redirectLocation(result).get must be(loginUrl)
}
"respond with OK on page load for valueLessThanNilRateBand, single executor" in {
createMockToGetRegDetailsFromCacheNoOption(mockCachingConnector)
createMockToGetSingleValueFromCache(mockCachingConnector, same("declarationType"), Some("valueLessThanNilRateBand"))
createMockToGetSingleValueFromCache(mockCachingConnector, same("isMultipleExecutor"), Some("false"))
createMockToGetSingleValueFromCache(mockCachingConnector, same("shouldDisplayRealtimeRiskingMessage"), Some("false"))
createMockToGetApplicationDetails(mockIhtConnector, Some(CommonBuilder.buildApplicationDetailsWithAllAssets.copy(
allAssets = Some(CommonBuilder.buildAllAssets.copy(money = None)))))
createMockToGetRealtimeRiskMessage(mockIhtConnector)
val result = declarationController.onPageLoad()(createFakeRequest())
status(result) mustBe OK
}
"respond with OK on page load for valueLessThanNilRateBand, single executor and show risk message where message not found in messages file" in {
val testRiskMessage = "Risk message is present"
createMockToGetRegDetailsFromCacheNoOption(mockCachingConnector, Future.successful(Some(CommonBuilder.buildRegistrationDetails)))
createMockToGetSingleValueFromCache(mockCachingConnector, same("declarationType"), Some("valueLessThanNilRateBand"))
createMockToGetSingleValueFromCache(mockCachingConnector, same("isMultipleExecutor"), Some("false"))
createMockToGetApplicationDetails(mockIhtConnector, Some(CommonBuilder.buildApplicationDetailsWithAllAssets.copy(
allAssets = Some(CommonBuilder.buildAllAssetsWithAllSectionsFilled.copy(money = None)))))
createMockToGetRealtimeRiskMessage(mockIhtConnector, Some(testRiskMessage))
val rd = CommonBuilder.buildRegistrationDetailsWithDeceasedDetails
createMockToGetRegDetailsFromCache(mockCachingConnector, Some(rd))
val result = declarationController.onPageLoad()(createFakeRequest())
contentAsString(result) must include(testRiskMessage)
status(result) mustBe OK
}
"respond with OK on page load for valueLessThanNilRateBand, single executor and show risk message where message is found in messages file" in {
val testRiskMessage = messagesApi("iht.application.declaration.risking.money.message")
createMockToGetRegDetailsFromCacheNoOption(mockCachingConnector, Future.successful(Some(CommonBuilder.buildRegistrationDetails)))
createMockToGetSingleValueFromCache(mockCachingConnector, same("declarationType"), Some("valueLessThanNilRateBand"))
createMockToGetSingleValueFromCache(mockCachingConnector, same("isMultipleExecutor"), Some("false"))
createMockToGetApplicationDetails(mockIhtConnector, Some(CommonBuilder.buildApplicationDetailsWithAllAssets.copy(
allAssets = Some(CommonBuilder.buildAllAssetsWithAllSectionsFilled.copy(money = None)))))
createMockToGetRealtimeRiskMessage(mockIhtConnector, Some(testRiskMessage))
val rd = CommonBuilder.buildRegistrationDetailsWithDeceasedDetails
createMockToGetRegDetailsFromCache(mockCachingConnector, Some(rd))
val deceasedName = rd.deceasedDetails.map(_.name).getOrElse("")
val result = declarationController.onPageLoad()(createFakeRequest())
val expectedRiskMessage = messagesApi("iht.application.declaration.risking.money.message.amended", deceasedName)
contentAsString(result) must include(expectedRiskMessage)
status(result) mustBe OK
}
"respond with NOT_IMPLEMENTED on page submit for valueLessThanNilRateBand, multiple executor, tick in box" in {
createMockToGetRegDetailsFromCacheNoOption(mockCachingConnector)
createMockToGetSingleValueFromCache(mockCachingConnector, same("declarationType"), Some("valueLessThanNilRateBand"))
createMockToGetSingleValueFromCache(mockCachingConnector, same("isMultipleExecutor"), Some("true"))
createMockToGetApplicationDetails(mockIhtConnector)
createMockToSaveApplicationDetails(mockIhtConnector)
createMockToSubmitApplication(mockIhtConnector)
createMockToGetProbateDetails(mockIhtConnector)
createMockToStoreProbateDetailsInCache(mockCachingConnector)
mockForApplicationStatus(ApplicationStatus.AwaitingReturn)
val applicantDetailsForm1 = declarationForm.fill(true)
implicit val request = createFakeRequest().withFormUrlEncodedBody(applicantDetailsForm1.data.toSeq: _*)
val result = declarationController.onSubmit()(request)
status(result) mustBe SEE_OTHER
}
"respond with redirect on page submit for valueLessThanNilRateBand, single executor" in {
createMockToGetRegDetailsFromCacheNoOption(mockCachingConnector)
createMockToGetSingleValueFromCache(mockCachingConnector, same("declarationType"), Some("valueLessThanNilRateBand"))
createMockToGetSingleValueFromCache(mockCachingConnector, same("isMultipleExecutor"), Some("false"))
createMockToGetApplicationDetails(mockIhtConnector)
createMockToSaveApplicationDetails(mockIhtConnector)
createMockToSubmitApplication(mockIhtConnector)
createMockToGetProbateDetails(mockIhtConnector)
createMockToGetCaseDetails(mockIhtConnector)
createMockToStoreProbateDetailsInCache(mockCachingConnector)
val result = declarationController.onSubmit()(createFakeRequest())
status(result) mustBe SEE_OTHER
}
"respond with INTERNAL_SERVER_ERROR when exception contains 'Service Unavailable' and statusCode 502" in {
createMockToGetRegDetailsFromCacheNoOption(mockCachingConnector, Future.failed(UpstreamErrorResponse("Service Unavailable", 502, 502)))
val result = declarationController.onSubmit()(createFakeRequest())
status(result) mustBe INTERNAL_SERVER_ERROR
}
"respond with redirect to Received Declaration page after the successful submission " in {
createMockToGetSingleValueFromCache(mockCachingConnector, same("declarationType"), Some("valueLessThanNilRateBand"))
createMockToGetSingleValueFromCache(mockCachingConnector, same("isMultipleExecutor"), Some("false"))
createMockToGetApplicationDetails(mockIhtConnector)
createMockToSaveApplicationDetails(mockIhtConnector)
createMockToSubmitApplication(mockIhtConnector)
createMockToGetProbateDetails(mockIhtConnector)
createMockToStoreProbateDetailsInCache(mockCachingConnector)
mockForApplicationStatus(ApplicationStatus.AwaitingReturn)
val result = declarationController.onSubmit()(createFakeRequest())
status(result) mustBe SEE_OTHER
redirectLocation(result) must be(Some(iht.controllers.application.declaration.routes.DeclarationReceivedController.onPageLoad().url))
}
"must increase the stats counter metric for ADDITIONAL_EXECUTOR_APP " in {
val regDetails = CommonBuilder.buildRegistrationDetails copy(ihtReference=Some("XXX"),
coExecutors = Seq(CommonBuilder.buildCoExecutor,
CommonBuilder.buildCoExecutor))
createMockToGetRegDetailsFromCacheNoOption(mockCachingConnector, Future.successful(Some(regDetails)))
createMockToGetSingleValueFromCache(mockCachingConnector, same("declarationType"), Some("valueLessThanNilRateBand"))
createMockToGetSingleValueFromCache(mockCachingConnector, same("isMultipleExecutor"), Some("true"))
createMockToGetApplicationDetails(mockIhtConnector)
createMockToSaveApplicationDetails(mockIhtConnector)
createMockToSubmitApplication(mockIhtConnector)
createMockToGetProbateDetails(mockIhtConnector)
createMockToGetCaseDetails(mockIhtConnector)
createMockToStoreProbateDetailsInCache(mockCachingConnector)
val applicantDetailsForm1 = declarationForm.fill(true)
implicit val request = createFakeRequest().withFormUrlEncodedBody(applicantDetailsForm1.data.toSeq: _*)
val result = declarationController.onSubmit()(request)
status(result) mustBe SEE_OTHER
}
"must redirect to non lead executor page when submitApplication return 403" in {
val regDetails = CommonBuilder.buildRegistrationDetails copy(ihtReference=Some("XXX"),
coExecutors = Seq(CommonBuilder.buildCoExecutor,
CommonBuilder.buildCoExecutor))
createMockToGetRegDetailsFromCacheNoOption(mockCachingConnector, Future.successful(Some(regDetails)))
createMockToGetApplicationDetails(mockIhtConnector)
createMockToSaveApplicationDetails(mockIhtConnector)
when(mockIhtConnector.submitApplication(any(),any(),any())(any(), any())).thenReturn(Future.successful(None))
mockForApplicationStatus(ApplicationStatus.AwaitingReturn)
val result = declarationController.onSubmit()(createFakeRequest())
status(result) mustBe SEE_OTHER
redirectLocation(result) mustBe Some(iht.controllers.routes.NonLeadExecutorController.onPageLoad().url)
}
"statsSource should return Some assets only" in {
val result = declarationController.statsSource(
CommonBuilder.buildApplicationDetails, BigDecimal(0), BigDecimal(0), BigDecimal(0), BigDecimal(1))
result must be(Some(StatsSource.ASSETS_ONLY_APP))
}
"statsSource should return Some assets and debts only" in {
val result = declarationController.statsSource(
CommonBuilder.buildApplicationDetails, BigDecimal(0), BigDecimal(1), BigDecimal(0), BigDecimal(1))
result must be(Some(StatsSource.ASSETS_AND_DEBTS_ONLY_APP))
}
"statsSource should return Some assets, debts, exemptions and TNRB" in {
val tnrbEligibiltyModel = TnrbEligibiltyModel(None, None, None, None, None, None, None, None, None, None, None)
val ad = CommonBuilder.buildApplicationDetails copy( increaseIhtThreshold = Some(tnrbEligibiltyModel) )
val result = declarationController.statsSource(ad, BigDecimal(1), BigDecimal(1), BigDecimal(1), BigDecimal(1))
result must be(Some(StatsSource.ASSET_DEBTS_EXEMPTIONS_TNRB_APP))
}
"statsSource should return None" in {
val result = declarationController.statsSource(CommonBuilder.buildApplicationDetails, BigDecimal(0), BigDecimal(0), BigDecimal(0), BigDecimal(-1))
result must be(None)
}
"calculateReasonForBeingBelowLimit should return Some ReasonForBeingBelowLimitSpouseCivilPartnerOrCharityExemption" in {
val ad = CommonBuilder.buildApplicationDetails copy(
allAssets =Some(AllAssets(money=Some(ShareableBasicEstateElement(Some(BigDecimal(325001)), Some(BigDecimal(0)))))),
allExemptions = Some(AllExemptions(partner=Some(PartnerExemption(None, None, None, None, None, None, Some(BigDecimal(2))))))
)
val result = declarationController.calculateReasonForBeingBelowLimit(ad)
result must be(Some(ControllerHelper.ReasonForBeingBelowLimitSpouseCivilPartnerOrCharityExemption))
}
"calculateReasonForBeingBelowLimit should return Some ReasonForBeingBelowLimitTNRB" in {
val ad = CommonBuilder.buildApplicationDetails copy(
allAssets =Some(AllAssets(money=Some(ShareableBasicEstateElement(Some(BigDecimal(326001)), Some(BigDecimal(0)))))),
allExemptions = Some(AllExemptions(partner=Some(PartnerExemption(None, None, None, None, None, None, Some(BigDecimal(2))))))
)
val result = declarationController.calculateReasonForBeingBelowLimit(ad)
result must be(Some(ControllerHelper.ReasonForBeingBelowLimitTNRB))
}
"calculateReasonForBeingBelowLimit should return None" in {
val ad = CommonBuilder.buildApplicationDetails copy(
allAssets =Some(AllAssets(money=Some(ShareableBasicEstateElement(Some(BigDecimal(1000001)), Some(BigDecimal(0))))))
)
val result = declarationController.calculateReasonForBeingBelowLimit(ad)
result must be(None)
}
"submissionException should return errorServiceUnavailable" in {
val ex = new GatewayTimeoutException("")
declarationController.submissionException(ex) must be(ControllerHelper.errorServiceUnavailable)
}
"submissionException should return errorServiceUnavailable also" in {
Seq("Request timed out", "Connection refused", "Service Unavailable", ControllerHelper.desErrorCode503) foreach { exceptionText =>
val ex = new RuntimeException(exceptionText)
declarationController.submissionException(ex) must be(ControllerHelper.errorServiceUnavailable)
}
}
"submissionException should return errorRequestTimeout" in {
Seq(ControllerHelper.desErrorCode502, ControllerHelper.desErrorCode504) foreach { exceptionText =>
val ex = new RuntimeException(exceptionText)
declarationController.submissionException(ex) must be(ControllerHelper.errorRequestTimeOut)
}
}
"submissionException should return errorSystem" in {
val ex = new RuntimeException("test")
declarationController.submissionException(ex) must be(ControllerHelper.errorSystem)
}
"submissionException should return errorSystem also" in {
val ex = new Throwable
declarationController.submissionException(ex) must be(ControllerHelper.errorSystem)
}
"on submit redirect to estate overview if the application status is not AwaitingReturn" in {
createMockToGetSingleValueFromCache(mockCachingConnector, same("declarationType"), Some("valueLessThanNilRateBand"))
createMockToGetSingleValueFromCache(mockCachingConnector, same("isMultipleExecutor"), Some("false"))
createMockToGetApplicationDetails(mockIhtConnector)
createMockToSaveApplicationDetails(mockIhtConnector)
createMockToSubmitApplication(mockIhtConnector)
createMockToGetProbateDetails(mockIhtConnector)
mockForApplicationStatus(ApplicationStatus.InReview)
val result = declarationController.onSubmit()(createFakeRequest())
status(result) mustBe SEE_OTHER
redirectLocation(result) must be(Some(iht.controllers.estateReports.routes.YourEstateReportsController.onPageLoad().url))
}
behave like controllerOnPageLoadWithNoExistingRegistrationDetails(mockCachingConnector,
declarationController.onPageLoad(createFakeRequest()))
}
"on submit make sure error handling code works" in {
createMockToGetSingleValueFromCache(mockCachingConnector, same("declarationType"), Some("valueLessThanNilRateBand"))
createMockToGetSingleValueFromCache(mockCachingConnector, same("isMultipleExecutor"), Some("false"))
createMockToGetApplicationDetails(mockIhtConnector)
createMockToSaveApplicationDetails(mockIhtConnector)
createMockToSubmitApplication(mockIhtConnector)
createMockToGetProbateDetails(mockIhtConnector)
mockForApplicationStatus(ApplicationStatus.InReview, true)
when(mockIhtConnector.getRealtimeRiskingMessage(any(), any())(any())).thenReturn(Future.successful(Some("result")))
val result = declarationController.onSubmit()(createFakeRequest())
status(result) mustBe BAD_REQUEST
}
}
|
hmrc/iht-frontend
|
test/iht/controllers/application/declaration/DeclarationControllerTest.scala
|
Scala
|
apache-2.0
| 25,171 |
/*
* Copyright (c) 2018. Fengguo Wei and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0
* which accompanies this distribution, and is available at
* https://www.apache.org/licenses/LICENSE-2.0
*
* Detailed contributors are listed in the CONTRIBUTOR.md
*/
import sbt._
import Keys._
import scala.language.implicitConversions
import scala.language.postfixOps
object Common {
def newProject(projectName: String, base: File): Project =
Project(projectName, base).settings(
name := projectName,
organization := "com.github.arguslab",
scalaVersion := ArgusVersions.scalaVersion,
unmanagedSourceDirectories in Compile += baseDirectory.value / "gen"
)
def newProject(projectName: String): Project =
newProject(projectName, file(projectName))
def unmanagedJarsFrom(sdkDirectory: File, subdirectories: String*): Classpath = {
val sdkPathFinder = subdirectories.foldLeft(PathFinder.empty) { (finder, dir) =>
finder +++ (sdkDirectory / dir)
}
(sdkPathFinder * globFilter("*.jar")).classpath
}
def ivyHomeDir: File =
Option(System.getProperty("sbt.ivy.home")).fold(Path.userHome / ".ivy2")(file)
}
|
arguslab/Argus-SAF
|
project/Common.scala
|
Scala
|
apache-2.0
| 1,257 |
// Databricks notebook source
// MAGIC %md
// MAGIC
// MAGIC ## Lit
// MAGIC - https://arxiv.org/pdf/1612.01474.pdf
// MAGIC - https://towardsdatascience.com/3-methods-for-parallelization-in-spark-6a1a4333b473
// MAGIC - https://medium.com/@Sushil_Kumar/artificial-neural-network-with-spark-mllib-9474570239d8
// MAGIC
// MAGIC ## Docs
// MAGIC https://spark.apache.org/docs/latest/api/scala/org/apache/spark/ml/classification/MultilayerPerceptronClassifier.html
// MAGIC
// MAGIC Independently create
// COMMAND ----------
// MAGIC %scala
// MAGIC val ensemble // List of models
// MAGIC val ensemble.map()
|
lamastex/scalable-data-science
|
dbcArchives/2021/000_0-sds-3-x-projects/student-project-08_group-DistributedEnsemble/development/00_Introduction.scala
|
Scala
|
unlicense
| 612 |
package org.jetbrains.plugins.scala
package annotator
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.lang.annotation.{Annotation, AnnotationHolder}
import com.intellij.psi.{PsiElement, PsiMethod, PsiNamedElement, PsiParameter}
import org.jetbrains.plugins.scala.annotator.createFromUsage._
import org.jetbrains.plugins.scala.annotator.importsTracker.ImportTracker
import org.jetbrains.plugins.scala.annotator.quickfix.ReportHighlightingErrorQuickFix
import org.jetbrains.plugins.scala.codeInspection.varCouldBeValInspection.ValToVarQuickFix
import org.jetbrains.plugins.scala.extensions._
import org.jetbrains.plugins.scala.lang.psi.ScalaPsiUtil
import org.jetbrains.plugins.scala.lang.psi.api.base.patterns.{ScConstructorPattern, ScInfixPattern, ScPattern}
import org.jetbrains.plugins.scala.lang.psi.api.base.types.ScSimpleTypeElement
import org.jetbrains.plugins.scala.lang.psi.api.base.{ScReferenceElement, ScStableCodeReferenceElement}
import org.jetbrains.plugins.scala.lang.psi.api.expr._
import org.jetbrains.plugins.scala.lang.psi.api.statements.params.{ScParameter, ScParameters}
import org.jetbrains.plugins.scala.lang.psi.api.statements.{ScFunction, ScValue}
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.ScTypeDefinition
import org.jetbrains.plugins.scala.lang.psi.impl.expr.ScInterpolatedPrefixReference
import org.jetbrains.plugins.scala.lang.psi.impl.toplevel.synthetic.ScSyntheticFunction
import org.jetbrains.plugins.scala.lang.psi.types._
import org.jetbrains.plugins.scala.lang.psi.types.api.ScTypePresentation
import org.jetbrains.plugins.scala.lang.psi.types.nonvalue.Parameter
import org.jetbrains.plugins.scala.lang.psi.types.result.TypingContext
import org.jetbrains.plugins.scala.lang.resolve.ScalaResolveResult
import org.jetbrains.plugins.scala.project.ProjectContext
/**
* Pavel.Fatin, 31.05.2010
*/
trait ApplicationAnnotator {
def annotateReference(reference: ScReferenceElement, holder: AnnotationHolder) {
for {result <- reference.multiResolve(false)
r = result.asInstanceOf[ScalaResolveResult]} {
ImportTracker.registerUsedImports(reference, r)
if (r.isAssignment) {
annotateAssignmentReference(reference, holder)
}
if (!r.isApplicable()) {
r.element match {
case f@(_: ScFunction | _: PsiMethod | _: ScSyntheticFunction) =>
reference.getContext match {
case genCall: ScGenericCall =>
val missing = for (MissedTypeParameter(p) <- r.problems) yield p.name
missing match {
case Seq() =>
case as =>
holder.createErrorAnnotation(genCall.typeArgs.getOrElse(genCall),
"Unspecified type parameters: " + as.mkString(", "))
}
r.problems.foreach {
case MissedTypeParameter(_) =>
// handled in bulk above
case DoesNotTakeTypeParameters =>
holder.createErrorAnnotation(genCall.typeArgs.getOrElse(genCall), f.name + " does not take type parameters")
case ExcessTypeArgument(arg) if inSameFile(arg, holder) =>
holder.createErrorAnnotation(arg, "Too many type arguments for " + f.name)
case DefaultTypeParameterMismatch(expected, actual) => genCall.typeArgs match {
case Some(typeArgs) =>
val message: String = ScalaBundle.message("type.mismatch.default.args.expected.actual", expected, actual)
holder.createErrorAnnotation(typeArgs, message)
case _ =>
}
case _ =>
//holder.createErrorAnnotation(call.argsElement, "Not applicable to " + signatureOf(f))
}
case call: MethodInvocation =>
val missed =
for (MissedValueParameter(p) <- r.problems) yield p.name + ": " + p.paramType.presentableText
if (missed.nonEmpty) {
holder.createErrorAnnotation(call.argsElement,
"Unspecified value parameters: " + missed.mkString(", "))
addCreateFromUsagesQuickFixes(reference, holder)
}
val (problems, fun) = call.applyOrUpdateElement match {
case Some(rr) =>
(rr.problems, rr.element)
case _ => (r.problems, f)
}
problems.foreach {
case DoesNotTakeParameters() =>
holder.createErrorAnnotation(call.argsElement, fun.name + " does not take parameters")
addCreateFromUsagesQuickFixes(reference, holder)
case ExcessArgument(argument) if inSameFile(argument, holder) =>
holder.createErrorAnnotation(argument, "Too many arguments for method " + nameOf(fun))
addCreateFromUsagesQuickFixes(reference, holder)
case TypeMismatch(expression, expectedType) if inSameFile(expression, holder) =>
for (t <- expression.getType(TypingContext.empty)) {
//TODO show parameter name
val (expectedText, actualText) = ScTypePresentation.different(expectedType, t)
val message = ScalaBundle.message("type.mismatch.expected.actual", expectedText, actualText)
val annotation = holder.createErrorAnnotation(expression, message)
annotation.registerFix(ReportHighlightingErrorQuickFix)
addCreateFromUsagesQuickFixes(reference, holder)
}
case MissedValueParameter(_) => // simultaneously handled above
case UnresolvedParameter(_) => // don't show function inapplicability, unresolved
case MalformedDefinition() =>
holder.createErrorAnnotation(call.getInvokedExpr, f.name + " has malformed definition")
case ExpansionForNonRepeatedParameter(expression) if inSameFile(expression, holder) =>
holder.createErrorAnnotation(expression, "Expansion for non-repeated parameter")
case PositionalAfterNamedArgument(argument) if inSameFile(argument, holder) =>
holder.createErrorAnnotation(argument, "Positional after named argument")
case ParameterSpecifiedMultipleTimes(assignment) if inSameFile(assignment, holder) =>
holder.createErrorAnnotation(assignment.getLExpression, "Parameter specified multiple times")
case WrongTypeParameterInferred => //todo: ?
case ExpectedTypeMismatch => //will be reported later
case ElementApplicabilityProblem(element, actual, expected) if inSameFile(element, holder) =>
val (actualType, expectedType) = ScTypePresentation.different(actual, expected)
holder.createErrorAnnotation(element, ScalaBundle.message("type.mismatch.found.required",
actualType, expectedType))
case _ =>
holder.createErrorAnnotation(call.argsElement, "Not applicable to " + signatureOf(f))
}
case _ =>
r.problems.foreach {
case MissedParametersClause(_) if !reference.isInstanceOf[ScInterpolatedPrefixReference] =>
holder.createErrorAnnotation(reference, "Missing arguments for method " + nameOf(f))
addCreateFromUsagesQuickFixes(reference, holder)
case _ =>
}
}
case _ =>
}
}
}
}
/**
* Annotates: val a = 1; a += 1;
*/
private def annotateAssignmentReference(reference: ScReferenceElement, holder: AnnotationHolder) {
val qualifier = reference.getContext match {
case x: ScMethodCall => x.getEffectiveInvokedExpr match {
case x: ScReferenceExpression => x.qualifier
case _ => None
}
case x: ScInfixExpr => Some(x.lOp)
case _ => None
}
val refElementOpt = qualifier.flatMap(_.asOptionOf[ScReferenceElement])
val ref: Option[PsiElement] = refElementOpt.flatMap(_.resolve().toOption)
val reassignment = ref.exists(ScalaPsiUtil.isReadonly)
if (reassignment) {
val annotation = holder.createErrorAnnotation(reference, "Reassignment to val")
ref.get match {
case named: PsiNamedElement if ScalaPsiUtil.nameContext(named).isInstanceOf[ScValue] =>
annotation.registerFix(new ValToVarQuickFix(ScalaPsiUtil.nameContext(named).asInstanceOf[ScValue]))
case _ =>
}
}
}
def annotateMethodInvocation(call: MethodInvocation, holder: AnnotationHolder) {
implicit val ctx: ProjectContext = call
//do we need to check it:
call.getEffectiveInvokedExpr match {
case ref: ScReferenceElement =>
ref.bind() match {
case Some(r) if r.notCheckedResolveResult || r.isDynamic => //it's unhandled case
case _ =>
call.applyOrUpdateElement match {
case Some(r) if r.isDynamic => //it's still unhandled
case _ => return //it's definetely handled case
}
}
case _ => //unhandled case (only ref expressions was checked)
}
val problems = call.applyOrUpdateElement.map(_.problems).getOrElse(call.applicationProblems)
val missed = for (MissedValueParameter(p) <- problems) yield p.name + ": " + p.paramType.presentableText
if(missed.nonEmpty)
holder.createErrorAnnotation(call.argsElement, "Unspecified value parameters: " + missed.mkString(", "))
//todo: better error explanation?
//todo: duplicate
problems.foreach {
case DoesNotTakeParameters() =>
val annotation = holder.createErrorAnnotation(call.argsElement, "Application does not take parameters")
(call, call.getInvokedExpr) match {
case (c: ScMethodCall, InstanceOfClass(td: ScTypeDefinition)) =>
annotation.registerFix(new CreateApplyQuickFix(td, c))
case _ =>
}
case ExcessArgument(argument) =>
holder.createErrorAnnotation(argument, "Too many arguments")
case TypeMismatch(expression, expectedType) =>
for(t <- expression.getType(TypingContext.empty)) {
//TODO show parameter name
val (expectedText, actualText) = ScTypePresentation.different(expectedType, t)
val message = ScalaBundle.message("type.mismatch.expected.actual", expectedText, actualText)
val annotation = holder.createErrorAnnotation(expression, message)
annotation.registerFix(ReportHighlightingErrorQuickFix)
}
case MissedValueParameter(_) => // simultaneously handled above
case UnresolvedParameter(_) => // don't show function inapplicability, unresolved
case MalformedDefinition() =>
holder.createErrorAnnotation(call.getInvokedExpr, "Application has malformed definition")
case ExpansionForNonRepeatedParameter(expression) =>
holder.createErrorAnnotation(expression, "Expansion for non-repeated parameter")
case PositionalAfterNamedArgument(argument) =>
holder.createErrorAnnotation(argument, "Positional after named argument")
case ParameterSpecifiedMultipleTimes(assignment) =>
holder.createErrorAnnotation(assignment.getLExpression, "Parameter specified multiple times")
case ExpectedTypeMismatch => // it will be reported later
case DefaultTypeParameterMismatch(_, _) => //it will be reported later
case _ => holder.createErrorAnnotation(call.argsElement, "Not applicable")
}
}
protected def registerCreateFromUsageFixesFor(ref: ScReferenceElement, annotation: Annotation) {
ref match {
case (exp: ScReferenceExpression) childOf (_: ScMethodCall) =>
annotation.registerFix(new CreateMethodQuickFix(exp))
if (ref.refName.headOption.exists(_.isUpper))
annotation.registerFix(new CreateCaseClassQuickFix(exp))
case (exp: ScReferenceExpression) childOf (infix: ScInfixExpr) if infix.operation == exp =>
annotation.registerFix(new CreateMethodQuickFix(exp))
case (exp: ScReferenceExpression) childOf ((_: ScGenericCall) childOf (_: ScMethodCall)) =>
annotation.registerFix(new CreateMethodQuickFix(exp))
case (exp: ScReferenceExpression) childOf (_: ScGenericCall) =>
annotation.registerFix(new CreateParameterlessMethodQuickFix(exp))
case exp: ScReferenceExpression =>
annotation.registerFix(new CreateParameterlessMethodQuickFix(exp))
annotation.registerFix(new CreateValueQuickFix(exp))
annotation.registerFix(new CreateVariableQuickFix(exp))
annotation.registerFix(new CreateObjectQuickFix(exp))
case (_: ScStableCodeReferenceElement) childOf (st: ScSimpleTypeElement) if st.singleton =>
case (stRef: ScStableCodeReferenceElement) childOf (Both(p: ScPattern, (_: ScConstructorPattern | _: ScInfixPattern))) =>
annotation.registerFix(new CreateCaseClassQuickFix(stRef))
annotation.registerFix(new CreateExtractorObjectQuickFix(stRef, p))
case stRef: ScStableCodeReferenceElement =>
annotation.registerFix(new CreateTraitQuickFix(stRef))
annotation.registerFix(new CreateClassQuickFix(stRef))
annotation.registerFix(new CreateCaseClassQuickFix(stRef))
case _ =>
}
}
private def nameOf(f: PsiNamedElement) = f.name + signatureOf(f)
private def signatureOf(f: PsiNamedElement): String = f match {
case f: ScFunction =>
if (f.parameters.isEmpty) "" else formatParamClauses(f.paramClauses)
case m: PsiMethod =>
val params = m.parameters
if (params.isEmpty) "" else formatJavaParams(params)
case syn: ScSyntheticFunction =>
if (syn.paramClauses.isEmpty) "" else syn.paramClauses.map(formatSyntheticParams).mkString
}
private def formatParamClauses(paramClauses: ScParameters) = {
def formatParams(parameters: Seq[ScParameter], types: Seq[ScType]) = {
val parts = parameters.zip(types).map {
case (p, t) => t.presentableText + (if(p.isRepeatedParameter) "*" else "")
}
parenthesise(parts)
}
paramClauses.clauses.map(clause => formatParams(clause.parameters, clause.paramTypes)).mkString
}
private def formatJavaParams(parameters: Seq[PsiParameter]): String = {
val types = ScalaPsiUtil.mapToLazyTypesSeq(parameters)
val parts = parameters.zip(types).map {
case (p, t) => t().presentableText + (if(p.isVarArgs) "*" else "")
}
parenthesise(parts)
}
private def formatSyntheticParams(parameters: Seq[Parameter]) = {
val parts = parameters.map {
p => p.paramType.presentableText + (if (p.isRepeated) "*" else "")
}
parenthesise(parts)
}
private def parenthesise(items: Seq[_]) = items.mkString("(", ", ", ")")
private def addCreateFromUsagesQuickFixes(ref: ScReferenceElement, holder: AnnotationHolder) = {
val annotation = holder.createErrorAnnotation(ref, ScalaBundle.message("cannot.resolve.such.signature", ref.refName))
annotation.setHighlightType(ProblemHighlightType.INFORMATION)
registerCreateFromUsageFixesFor(ref, annotation)
}
private def inSameFile(elem: PsiElement, holder: AnnotationHolder): Boolean = {
elem != null && elem.getContainingFile == holder.getCurrentAnnotationSession.getFile
}
}
|
loskutov/intellij-scala
|
src/org/jetbrains/plugins/scala/annotator/ApplicationAnnotator.scala
|
Scala
|
apache-2.0
| 15,586 |
import com.google.inject.{Guice, AbstractModule}
import play.api.GlobalSettings
import play.api.mvc.RequestHeader
import services.{SimpleUUIDGenerator, UUIDGenerator}
import play.api.mvc.Results._
import scala.concurrent.Future
/**
* Set up the Guice injector and provide the mechanism for return objects from the dependency graph.
*/
object Global extends GlobalSettings {
/**
* Bind types such that whenever UUIDGenerator is required, an instance of SimpleUUIDGenerator will be used.
*/
val injector = Guice.createInjector(new AbstractModule {
protected def configure() {
bind(classOf[UUIDGenerator]).to(classOf[SimpleUUIDGenerator])
}
})
override def onBadRequest(request: RequestHeader, error: String) = {
Future.successful(BadRequest("Bad Request: " + error))
}
override def onHandlerNotFound(request: RequestHeader) = {
Future.successful(NotFound(
views.html.notFoundPage()
))
}
/**
* Controllers must be resolved through the application context. There is a special method of GlobalSettings
* that we can override to resolve a given controller. This resolution is required by the Play router.
*/
override def getControllerInstance[A](controllerClass: Class[A]): A = injector.getInstance(controllerClass)
}
|
mawentao007/Mongo-play-angular
|
app/Global.scala
|
Scala
|
apache-2.0
| 1,291 |
package de.sciss
import net.didion.jwnl.data.POS
package object wordnet {
type Synset = net.didion.jwnl.data.Synset
type POS = net.didion.jwnl.data.POS
val Noun = POS.NOUN
val Verb = POS.VERB
val Adjective = POS.ADJECTIVE
val Adjverb = POS.ADVERB
}
|
Sciss/ScalaWordNet
|
src/main/scala/de/sciss/wordnet/package.scala
|
Scala
|
gpl-2.0
| 279 |
/*
* Copyright 2001-2014 Artima, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.scalatest
import collection.GenTraversable
import SharedHelpers._
import Matchers._
import FailureMessages.decorateToStringValue
import org.scalactic.Entry
class OneElementOfContainMatcherSpec extends Spec {
object `oneElementOf ` {
def checkStackDepth(e: exceptions.StackDepthException, left: Any, right: GenTraversable[Any], lineNumber: Int) {
e.message should be (Some(FailureMessages.didNotContainOneElementOf(left, right)))
e.failedCodeFileName should be (Some("OneElementOfContainMatcherSpec.scala"))
e.failedCodeLineNumber should be (Some(lineNumber))
}
def `should succeeded when left List contains same elements in same order as right List` {
List(1, 3, 5, 8) should contain oneElementOf Seq(7, 8, 9)
Array(1, 3, 5, 8) should contain oneElementOf Seq(7, 8, 9)
javaList(1, 3, 5, 8) should contain oneElementOf Seq(7, 8, 9)
Set(1, 3, 5, 8) should contain oneElementOf Seq(7, 8, 9)
javaSet(1, 3, 5, 8) should contain oneElementOf Seq(7, 8, 9)
Map(1 -> "one", 3 -> "three", 5 -> "five", 8 -> "eight") should contain oneElementOf Seq(7 -> "seven", 8 -> "eight", 9 -> "nine")
javaMap(Entry(1, "one"), Entry(3, "three"), Entry(5, "five"), Entry(8, "eight")) should contain oneElementOf Seq(Entry(7, "seven"), Entry(8, "eight"), Entry(9, "nine"))
}
def `should succeeded when right List contains at least one element in right List` {
List(1, 2, 3) should contain oneElementOf Seq(5, 3, 8)
Array(1, 2, 3) should contain oneElementOf Seq(5, 3, 8)
javaList(1, 2, 3) should contain oneElementOf Seq(5, 3, 8)
Set(1, 2, 3) should contain oneElementOf Seq(5, 3, 8)
javaSet(1, 2, 3) should contain oneElementOf Seq(5, 3, 8)
Map(1 -> "one", 2 -> "two", 3 -> "three") should contain oneElementOf Seq(5 -> "five", 3 -> "three", 8 -> "eight")
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should contain oneElementOf Seq(Entry(5, "five"), Entry(3, "three"), Entry(8, "eight"))
}
def `should throw NotAllowedException when oneElementOf contains duplicate element` {
val e1 = intercept[exceptions.NotAllowedException] {
List(1, 2, 3) should contain oneElementOf Seq(6, 7, 6)
}
e1.getMessage() should be (FailureMessages.oneElementOfDuplicate)
val e2 = intercept[exceptions.NotAllowedException] {
Set(1, 2, 3) should contain oneElementOf Seq(6, 7, 6)
}
e2.getMessage() should be (FailureMessages.oneElementOfDuplicate)
val e3 = intercept[exceptions.NotAllowedException] {
Array(1, 2, 3) should contain oneElementOf Seq(6, 7, 6)
}
e3.getMessage() should be (FailureMessages.oneElementOfDuplicate)
}
def `should throw TestFailedException with correct stack depth and message when left and right List are same size but does not contain any same element` {
val left1 = List(1, 2, 3)
val e1 = intercept[exceptions.TestFailedException] {
left1 should contain oneElementOf Seq(7, 8, 9)
}
checkStackDepth(e1, left1, Seq(7, 8, 9), thisLineNumber - 2)
val left2 = javaList(1, 2, 3)
val e2 = intercept[exceptions.TestFailedException] {
left2 should contain oneElementOf Seq(7, 8, 9)
}
checkStackDepth(e2, left2, Seq(7, 8, 9), thisLineNumber - 2)
val left3 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val e3 = intercept[exceptions.TestFailedException] {
left3 should contain oneElementOf Seq(7 -> "seven", 8 -> "eight", 9 -> "nine")
}
checkStackDepth(e3, left3, Seq(7 -> "seven", 8 -> "eight", 9 -> "nine"), thisLineNumber - 2)
val left4 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val e4 = intercept[exceptions.TestFailedException] {
left4 should contain oneElementOf Seq(Entry(7, "seven"), Entry(8, "eight"), Entry(9, "nine"))
}
checkStackDepth(e4, left4, Seq(Entry(7, "seven"), Entry(8, "eight"), Entry(9, "nine")), thisLineNumber - 2)
val left5 = Array(1, 2, 3)
val e5 = intercept[exceptions.TestFailedException] {
left5 should contain oneElementOf Seq(7, 8, 9)
}
checkStackDepth(e5, left5, Seq(7, 8, 9), thisLineNumber - 2)
}
def `should throw TestFailedException with correct stack depth and message when left List is shorter than right List and does not contain any same element` {
val left1 = List(1, 2, 3)
val e1 = intercept[exceptions.TestFailedException] {
left1 should contain oneElementOf Seq(6, 7, 8, 9)
}
checkStackDepth(e1, left1, Seq(6, 7, 8, 9), thisLineNumber - 2)
val left2 = javaList(1, 2, 3)
val e2 = intercept[exceptions.TestFailedException] {
left2 should contain oneElementOf Seq(6, 7, 8, 9)
}
checkStackDepth(e2, left2, Seq(6, 7, 8, 9), thisLineNumber - 2)
val left3 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val e3 = intercept[exceptions.TestFailedException] {
left3 should contain oneElementOf Seq(6 -> "six", 7 -> "seven", 8 -> "eight", 9 -> "nine")
}
checkStackDepth(e3, left3, Seq(6 -> "six", 7 -> "seven", 8 -> "eight", 9 -> "nine"), thisLineNumber - 2)
val left4 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val e4 = intercept[exceptions.TestFailedException] {
left4 should contain oneElementOf Seq(Entry(6, "six"), Entry(7, "seven"), Entry(8, "eight"), Entry(9, "nine"))
}
checkStackDepth(e4, left4, Seq(Entry(6, "six"), Entry(7, "seven"), Entry(8, "eight"), Entry(9, "nine")), thisLineNumber - 2)
val left5 = Array(1, 2, 3)
val e5 = intercept[exceptions.TestFailedException] {
left5 should contain oneElementOf Seq(6, 7, 8, 9)
}
checkStackDepth(e5, left5, Seq(6, 7, 8, 9), thisLineNumber - 2)
}
def `should throw TestFailedException with correct stack depth and message when left List is longer than right List and does not contain any same element` {
val left1 = List(1, 2, 3)
val e1 = intercept[exceptions.TestFailedException] {
left1 should contain oneElementOf Seq(8, 5)
}
checkStackDepth(e1, left1, Seq(8, 5), thisLineNumber - 2)
val left2 = javaList(1, 2, 3)
val e2 = intercept[exceptions.TestFailedException] {
left2 should contain oneElementOf Seq(8, 5)
}
checkStackDepth(e2, left2, Seq(8, 5), thisLineNumber - 2)
val left3 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val e3 = intercept[exceptions.TestFailedException] {
left3 should contain oneElementOf Seq(8 -> "eight", 5 -> "five")
}
checkStackDepth(e3, left3, Seq(8 -> "eight", 5 -> "five"), thisLineNumber - 2)
val left4 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val e4 = intercept[exceptions.TestFailedException] {
left4 should contain oneElementOf Seq(Entry(8, "eight"), Entry(5, "five"))
}
checkStackDepth(e4, left4, Seq(Entry(8, "eight"), Entry(5, "five")), thisLineNumber - 2)
val left5 = Array(1, 2, 3)
val e5 = intercept[exceptions.TestFailedException] {
left5 should contain oneElementOf Seq(8, 5)
}
checkStackDepth(e5, left5, Seq(8, 5), thisLineNumber - 2)
}
def `should throw TestFailedException with correct stack depth and message when left and right List contain all same element in different order` {
val left1 = List(1, 2, 3)
val e1 = intercept[exceptions.TestFailedException] {
left1 should contain oneElementOf Seq(3, 2, 1)
}
checkStackDepth(e1, left1, Seq(3, 2, 1), thisLineNumber - 2)
val left2 = javaList(1, 2, 3)
val e2 = intercept[exceptions.TestFailedException] {
left2 should contain oneElementOf Seq(3, 2, 1)
}
checkStackDepth(e2, left2, Seq(3, 2, 1), thisLineNumber - 2)
val left3 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val e3 = intercept[exceptions.TestFailedException] {
left3 should contain oneElementOf Seq(3 -> "three", 2 -> "two", 1 -> "one")
}
checkStackDepth(e3, left3, Seq(3 -> "three", 2 -> "two", 1 -> "one"), thisLineNumber - 2)
val left4 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val e4 = intercept[exceptions.TestFailedException] {
left4 should contain oneElementOf Seq(Entry(3, "three"), Entry(2, "two"), Entry(1, "one"))
}
checkStackDepth(e4, left4, Seq(Entry(3, "three"), Entry(2, "two"), Entry(1, "one")), thisLineNumber - 2)
val left5 = Array(1, 2, 3)
val e5 = intercept[exceptions.TestFailedException] {
left5 should contain oneElementOf Seq(3, 2, 1)
}
checkStackDepth(e5, left5, Seq(3, 2, 1), thisLineNumber - 2)
}
def `should throw TestFailedException with correct stack depth and message when left and right List contain all same element in same order` {
val left1 = List(1, 2, 3)
val e1 = intercept[exceptions.TestFailedException] {
left1 should contain oneElementOf Seq(1, 2, 3)
}
checkStackDepth(e1, left1, Seq(1, 2, 3), thisLineNumber - 2)
val left2 = javaList(1, 2, 3)
val e2 = intercept[exceptions.TestFailedException] {
left2 should contain oneElementOf Seq(1, 2, 3)
}
checkStackDepth(e2, left2, Seq(1, 2, 3), thisLineNumber - 2)
val left3 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val e3 = intercept[exceptions.TestFailedException] {
left3 should contain oneElementOf Seq(1 -> "one", 2 -> "two", 3 -> "three")
}
checkStackDepth(e3, left3, Seq(1 -> "one", 2 -> "two", 3 -> "three"), thisLineNumber - 2)
val left4 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val e4 = intercept[exceptions.TestFailedException] {
left4 should contain oneElementOf Seq(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
}
checkStackDepth(e4, left4, Seq(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")), thisLineNumber - 2)
val left5 = Array(1, 2, 3)
val e5 = intercept[exceptions.TestFailedException] {
left5 should contain oneElementOf Seq(1, 2, 3)
}
checkStackDepth(e5, left5, Seq(1, 2, 3), thisLineNumber - 2)
}
def `should throw TestFailedException with correct stack depth and message when left and right List contain more than one same element` {
val left1 = List(1, 2, 3)
val e1 = intercept[exceptions.TestFailedException] {
left1 should contain oneElementOf Seq(5, 1, 2)
}
checkStackDepth(e1, left1, Seq(5, 1, 2), thisLineNumber - 2)
val left2 = javaList(1, 2, 3)
val e2 = intercept[exceptions.TestFailedException] {
left2 should contain oneElementOf Seq(5, 1, 2)
}
checkStackDepth(e2, left2, Seq(5, 1, 2), thisLineNumber - 2)
val left3 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val e3 = intercept[exceptions.TestFailedException] {
left3 should contain oneElementOf Seq(5 -> "five", 1 -> "one", 2 -> "two")
}
checkStackDepth(e3, left3, Seq(5 -> "five", 1 -> "one", 2 -> "two"), thisLineNumber - 2)
val left4 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val e4 = intercept[exceptions.TestFailedException] {
left4 should contain oneElementOf Seq(Entry(5, "five"), Entry(1, "one"), Entry(2, "two"))
}
checkStackDepth(e4, left4, Seq(Entry(5, "five"), Entry(1, "one"), Entry(2, "two")), thisLineNumber - 2)
val left5 = Array(1, 2, 3)
val e5 = intercept[exceptions.TestFailedException] {
left5 should contain oneElementOf Seq(5, 1, 2)
}
checkStackDepth(e5, left5, Seq(5, 1, 2), thisLineNumber - 2)
}
}
object `not oneElementOf ` {
def checkStackDepth(e: exceptions.StackDepthException, left: Any, right: GenTraversable[Any], lineNumber: Int) {
val leftText = FailureMessages.decorateToStringValue(left)
e.message should be (Some(FailureMessages.containedOneElementOf(left, right)))
e.failedCodeFileName should be (Some("OneElementOfContainMatcherSpec.scala"))
e.failedCodeLineNumber should be (Some(lineNumber))
}
def `should succeed when left List contains different elements as right List` {
List(1, 2, 3) should not contain oneElementOf (Seq(7, 8, 9))
Array(1, 2, 3) should not contain oneElementOf (Seq(7, 8, 9))
javaList(1, 2, 3) should not contain oneElementOf (Seq(7, 8, 9))
Set(1, 2, 3) should not contain oneElementOf (Seq(7, 8, 9))
javaSet(1, 2, 3) should not contain oneElementOf (Seq(7, 8, 9))
Map(1 -> "one", 2 -> "two", 3 -> "three") should not contain oneElementOf (Seq(7 -> "seven", 8 -> "eight", 9 -> "nine"))
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should not contain oneElementOf (Seq(Entry(7, "seven"), Entry(8, "eight"), Entry(9, "nine")))
}
def `should throw TestFailedException with correct stack depth and message when left and right List contain at least one same element` {
val left1 = List(1, 2, 3)
val e1 = intercept[exceptions.TestFailedException] {
left1 should not contain oneElementOf (Seq(5, 1, 7))
}
checkStackDepth(e1, left1, Seq(5, 1, 7), thisLineNumber - 2)
val left2 = javaList(1, 2, 3)
val e2 = intercept[exceptions.TestFailedException] {
left2 should not contain oneElementOf (Seq(5, 1, 7))
}
checkStackDepth(e2, left2, Seq(5, 1, 7), thisLineNumber - 2)
val left3 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val e3 = intercept[exceptions.TestFailedException] {
left3 should not contain oneElementOf (Seq(5 -> "five", 1 -> "one", 7 -> "seven"))
}
checkStackDepth(e3, left3, Seq(5 -> "five", 1 -> "one", 7 -> "seven"), thisLineNumber - 2)
val left4 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val e4 = intercept[exceptions.TestFailedException] {
left4 should not contain oneElementOf (Seq(Entry(5, "five"), Entry(1, "one"), Entry(7, "seven")))
}
checkStackDepth(e4, left4, Seq(Entry(5, "five"), Entry(1, "one"), Entry(7, "seven")), thisLineNumber - 2)
val left5 = Array(1, 2, 3)
val e5 = intercept[exceptions.TestFailedException] {
left5 should not contain oneElementOf (Seq(5, 1, 7))
}
checkStackDepth(e5, left5, Seq(5, 1, 7), thisLineNumber - 2)
}
def `should succeeded when right List contains all elements in left List in different order` {
List(1, 2, 3) should not contain oneElementOf (Seq(1, 3, 2))
Array(1, 2, 3) should not contain oneElementOf (Seq(1, 3, 2))
javaList(1, 2, 3) should not contain oneElementOf (Seq(1, 3, 2))
Set(1, 2, 3) should not contain oneElementOf (Seq(1, 3, 2))
javaSet(1, 2, 3) should not contain oneElementOf (Seq(1, 3, 2))
Map(1 -> "one", 2 -> "two", 3 -> "three") should not contain oneElementOf (Seq(1 -> "one", 3 -> "three", 2 -> "twp"))
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should not contain oneElementOf (Seq(Entry(1, "one"), Entry(3, "three"), Entry(2, "twp")))
}
def `should succeeded when right List contains all elements in left List in same order` {
List(1, 2, 3) should not contain oneElementOf (Seq(1, 2, 3))
Array(1, 2, 3) should not contain oneElementOf (Seq(1, 2, 3))
javaList(1, 2, 3) should not contain oneElementOf (Seq(1, 2, 3))
Set(1, 2, 3) should not contain oneElementOf (Seq(1, 2, 3))
javaSet(1, 2, 3) should not contain oneElementOf (Seq(1, 2, 3))
Map(1 -> "one", 2 -> "two", 3 -> "three") should not contain oneElementOf (Seq(1 -> "one", 2 -> "two", 3 -> "three"))
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should not contain oneElementOf (Seq(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")))
}
def `should succeeded when right List contains more than one element in right List` {
List(1, 2, 3) should not contain oneElementOf (Seq(5, 3, 2))
Array(1, 2, 3) should not contain oneElementOf (Seq(5, 3, 2))
javaList(1, 2, 3) should not contain oneElementOf (Seq(5, 3, 2))
Set(1, 2, 3) should not contain oneElementOf (Seq(5, 3, 2))
javaSet(1, 2, 3) should not contain oneElementOf (Seq(5, 3, 2))
Map(1 -> "one", 2 -> "two", 3 -> "three") should not contain oneElementOf (Seq(5 -> "five", 3 -> "three", 2 -> "two"))
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should not contain oneElementOf (Seq(Entry(5, "five"), Entry(3, "three"), Entry(2, "two")))
}
}
}
|
SRGOM/scalatest
|
scalatest-test/src/test/scala/org/scalatest/OneElementOfContainMatcherSpec.scala
|
Scala
|
apache-2.0
| 17,217 |
/*
Copyright 2009 David Hall, Daniel Ramage
Licensed under the Apache License, Version 2.0 (the "License")
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package breeze.util
import org.scalatest._
import org.scalatest.funsuite._
import org.scalatestplus.scalacheck._
class IndexTest extends AnyFunSuite with Checkers {
test("CompositeIndex") {
val index = Index(List("a", "b", "c", "d"))
val index2 = Index(List("e", "f", "g", "h"))
val comp = new CompositeIndex(index, index2)
assert(comp(1 -> "e") === 4)
assert(comp(0 -> "e") === -1)
}
test("PairIndex") {
val index = Index(List("a", "b", "c", "d"))
val index2 = Index(List("e", "f", "g", "h"))
val comp = new PairIndex(index, index2)
assert(comp("a" -> "e") === 0)
assert(comp("e" -> "e") === -1)
}
test("EitherIndex") {
val index = Index(List("a", "b", "c", "d"))
val index2 = Index(List("e", "f", "g", "h"))
val comp = new EitherIndex(index, index2)
assert(comp(Right("e")) === 4)
assert(comp(Left("e")) === -1)
}
test("EnumerationIndex") {
object E extends Enumeration {
val A, B, C, D = Value
}
val index: Index[E.Value] = EnumerationIndex(E)
assert(index.get(0) === E.A)
assert(index.get(1) === E.B)
assert(index(E.A) === 0)
}
test("HashIndex serialization") {
val index = new HashIndex[String]()
for (x <- Seq("a", "b", "c", "de")) {
index.index(x)
}
import breeze.util._
val bytes = serializeToBytes(index)
assert(deserializeFromBytes[HashIndex[String]](bytes) == index)
}
test("HashIndex") {
val index = new HashIndex[String]()
for (x <- Seq("a", "b", "c", "de")) {
index.index(x)
}
assert(index.get(3) == "de")
assert(index.get(0) == "a")
}
}
|
scalanlp/breeze
|
math/src/test/scala/breeze/util/IndexTest.scala
|
Scala
|
apache-2.0
| 2,212 |
package net.sansa_stack.rdf.spark.io.turtle
import net.sansa_stack.rdf.common.annotation.Experimental
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{ FileSystem, FSDataInputStream, Path, Seekable }
import org.apache.hadoop.io.{ LongWritable, Text }
import org.apache.hadoop.io.compress._
import org.apache.hadoop.mapreduce.{ InputSplit, RecordReader, TaskAttemptContext }
import org.apache.hadoop.mapreduce.lib.input.{ CompressedSplitLineReader, FileInputFormat, FileSplit, SplitLineReader }
import org.apache.hadoop.util.LineReader
import org.apache.log4j.Logger
import org.slf4j.LoggerFactory
import util.control.Breaks._
/**
* @author Lorenz Buehmann
*/
@Experimental
class TurtleRecordReader(val recordDelimiterBytes: Array[Byte]) extends RecordReader[LongWritable, Text] {
val LOG = LoggerFactory.getLogger(classOf[TurtleRecordReader])
val MAX_LINE_LENGTH = "mapreduce.input.linerecordreader.line.maxlength"
var start, end, pos = 0L
var reader: SplitLineReader = null
var key = new LongWritable
var value = new Text
private var fileIn: FSDataInputStream = null
private var filePosition: Seekable = null
private var maxLineLength = 0
private var isCompressedInput = false
private var decompressor: Decompressor = null
override def initialize(inputSplit: InputSplit, context: TaskAttemptContext): Unit = {
// split position in data (start one byte earlier to detect if
// the split starts in the middle of a previous record)
val split = inputSplit.asInstanceOf[FileSplit]
val job = context.getConfiguration
maxLineLength = job.getInt(MAX_LINE_LENGTH, Integer.MAX_VALUE)
start = split.getStart
end = start + split.getLength
val file = split.getPath
// open the file and seek to the start of the split
val fs = file.getFileSystem(job)
fileIn = fs.open(file)
val codec = new CompressionCodecFactory(job).getCodec(file)
if (null != codec) {
isCompressedInput = true
decompressor = CodecPool.getDecompressor(codec)
if (codec.isInstanceOf[SplittableCompressionCodec]) {
val cIn = codec.asInstanceOf[SplittableCompressionCodec].createInputStream(fileIn, decompressor, start, end, SplittableCompressionCodec.READ_MODE.BYBLOCK)
reader = new CompressedSplitLineReader(cIn, job, recordDelimiterBytes)
start = cIn.getAdjustedStart
end = cIn.getAdjustedEnd
filePosition = cIn
} else {
reader = new SplitLineReader(codec.createInputStream(fileIn, decompressor), job, recordDelimiterBytes)
filePosition = fileIn
}
} else {
fileIn.seek(start)
reader = new SkipLineReader(fileIn, job, recordDelimiterBytes, split.getLength)
filePosition = fileIn
}
// If this is not the first split, we always throw away first record
// because we always (except the last split) read one extra line in
// next() method.
if (start != 0) start += reader.readLine(new Text, 0, maxBytesToConsume(start))
pos = start
}
private def maxBytesToConsume(pos: Long) =
if (isCompressedInput) Integer.MAX_VALUE
else Math.max(Math.min(Integer.MAX_VALUE, end - pos), maxLineLength).toInt
private def getFilePosition: Long = {
if (isCompressedInput && null != filePosition) filePosition.getPos
else pos
}
override def nextKeyValue(): Boolean = {
if (key == null) key = new LongWritable
key.set(pos)
if (value == null) value = new Text
var newSize = 0
// We always read one extra line, which lies outside the upper
// split limit i.e. (end - 1)
var break = false
while (!break && (getFilePosition <= end || reader.needAdditionalRecordAfterSplit)) {
// breakable {
if (pos == 0) {
newSize = skipUtfByteOrderMark
} else {
newSize = reader.readLine(value, maxLineLength, maxBytesToConsume(pos))
pos += newSize
}
// if(value.toString.startsWith("#")) println("Comment: " + value.toString)
if ((newSize == 0) || (newSize < maxLineLength)) break = true
// line too long. try again
// LOG.warn("Skipped line of size " + newSize + " at pos " + (pos - newSize))
// }
}
val ret = if (newSize == 0) {
key = null
value = null
false
} else {
true
}
ret
}
override def getCurrentKey: LongWritable = key
override def getProgress: Float =
if (start == end) {
0.0f
} else Math.min(1.0f, (pos - start) / (end - start).asInstanceOf[Float])
override def getCurrentValue: Text = value
override def close(): Unit = reader.close()
private def skipUtfByteOrderMark = { // Strip BOM(Byte Order Mark)
// Text only support UTF-8, we only need to check UTF-8 BOM
// (0xEF,0xBB,0xBF) at the start of the text stream.
val newMaxLineLength = Math.min(3L + maxLineLength.toLong, Integer.MAX_VALUE).toInt
var newSize = reader.readLine(value, newMaxLineLength, maxBytesToConsume(pos))
// Even we read 3 extra bytes for the first line,
// we won't alter existing behavior (no backwards incompat issue).
// Because the newSize is less than maxLineLength and
// the number of bytes copied to Text is always no more than newSize.
// If the return size from readLine is not less than maxLineLength,
// we will discard the current line and read the next line.
pos += newSize
var textLength = value.getLength
var textBytes = value.getBytes
if ((textLength >= 3) && (textBytes(0) == 0xEF.toByte) && (textBytes(1) == 0xBB.toByte) && (textBytes(2) == 0xBF.toByte)) { // find UTF-8 BOM, strip it.
LOG.info("Found UTF-8 BOM and skipped it")
textLength -= 3
newSize -= 3
if (textLength > 0) { // It may work to use the same buffer and not do the copyBytes
textBytes = value.copyBytes
value.set(textBytes, 3, textLength)
} else value.clear()
}
newSize
}
}
|
SANSA-Stack/Spark-RDF
|
sansa-rdf-spark/src/main/scala/net/sansa_stack/rdf/spark/io/turtle/TurtleRecordReader.scala
|
Scala
|
gpl-3.0
| 5,959 |
package com.skisel.skeleton.ws
import akka.actor._
import com.skisel.skeleton.sample.Pinger.PingEvent
import com.skisel.skeleton.sample.{SampleResponse, SampleActor, SampleRequest}
import com.skisel.skeleton.utils.Broadcaster
import Broadcaster.{RemoveListener, AddListener}
import com.skisel.skeleton.ws.RequestResponseActor.{Response, Request}
import play.api.libs.json.{Json, JsValue}
case class InMessage(json: JsValue)
case class OutMessage(message: AnyRef)
case class Clean(actorRef: ActorRef)
class ConnectionActor(out: ActorRef, broadcaster: ActorRef)
extends Actor
with ActorLogging{
var actors: Set[ActorRef] = Set()
var schedulers: Set[Cancellable] = Set()
override def preStart(): Unit = broadcaster.tell(AddListener(self), Actor.noSender)
override def postStop(): Unit = {
broadcaster.tell(RemoveListener(self), Actor.noSender)
schedulers.foreach {
_.cancel()
}
}
def receive = {
case InMessage(json) =>
log.info(s">>> json: ${json.toString()}")
json match {
case json: JsValue if (json \\ "type").as[String] == "sample-incoming" =>
val args = json \\ "args"
val idOpt = (json \\ "requestId").asOpt[String]
val data = args.as[SampleRequest]
val actor = context.actorOf(Props[SampleActor])
context.watch(actor)
val idz: Option[String] = idOpt
idz match {
case Some(id) => actor ! Request(id, data)
case None => actor ! data
}
import context.dispatcher
import scala.concurrent.duration._
schedulers += context.system.scheduler.scheduleOnce(30 seconds, self, Clean(actor))
case _ =>
log info "Invalid request"
}
case OutMessage(message) =>
message match {
case message: PingEvent =>
Json.obj(
"type" -> "ping-event",
"args" -> Json.toJson(message)
)
case Response(requestId, Left(message: SampleResponse)) =>
Json.obj(
"type" -> "sample-outgoing",
"requestId" -> requestId,
"args" -> Json.toJson(message)
)
case Response(requestId, Right(ResponseFailure(errorMsg))) =>
Json.obj(
"type" -> "sample-outgoing",
"requestId" -> requestId,
"errMsg" -> errorMsg
)
}
case Clean(actor) if actors.contains(actor) =>
actor ! PoisonPill
case Clean(_) => //was cleaned already
case Terminated(actor) =>
actors -= actor
case other =>
throw new RuntimeException(s"Could not match: $other")
}
}
|
skisel/skeleton
|
app/com/skisel/skeleton/ws/ConnectionActor.scala
|
Scala
|
apache-2.0
| 2,661 |
package breeze.linalg
/*
Copyright 2012 David Hall
Licensed under the Apache License, Version 2.0 (the "License")
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import org.scalatest._
import org.scalatest.junit._
import org.scalatest.prop._
import org.junit.runner.RunWith
import breeze.math.Complex
import breeze.numerics._
import org.scalatest.matchers.ShouldMatchers
import breeze.util.DoubleImplicits
@RunWith(classOf[JUnitRunner])
class DenseMatrixTest extends FunSuite with Checkers with Matchers with DoubleImplicits {
test("Slicing") {
val m = DenseMatrix((0,1,2),
(3,4,5))
// slice sub-matrix
val s1 = m(0 to 1, 1 to 2)
assert(s1 === DenseMatrix((1,2),(4,5)))
s1 += 1
assert(m === DenseMatrix((0,2,3),(3,5,6)))
// slice row
val s2 = m(0, ::)
assert(s2 === DenseVector(0,2,3).t)
s2 *= 2
assert(m === DenseMatrix((0,4,6),(3,5,6)))
// slice column
val s3 : DenseVector[Int] = m(::, 1)
assert(s3 === DenseVector(4,5))
s3 -= 1
assert(m === DenseMatrix((0,3,6),(3,4,6)))
// slice rows
val s4 = m(1 to 1, ::)
assert(s4 === DenseMatrix((3,4,6)))
val mbig = DenseMatrix(
(0,1,2,3,4,5),
(3,4,5,6,7,8),
(3,4,5,6,7,8),
(5,4,5,9,7,8)
)
val sbig1 = mbig(::, 0 to 2 by 2)
assert(sbig1 === DenseMatrix(
(0,2),
(3,5),
(3,5),
(5,5)
))
// slice columns
val s5 = m(::, 1 to 2)
assert(s5 === DenseMatrix((3,6),(4,6)))
// slice part of a row
val s6a = m(0, 1 to 2)
s6a += 1
assert(m === DenseMatrix((0,4,7),(3,4,6)))
// slice part of a column
val s7a = m(0 to 1, 0)
s7a += 2
val s7b = m(0 to 1,0)
s7b += 1
assert(m === DenseMatrix((3,4,7),(6,4,6)))
}
test("Multiple Slicing") {
val m = new DenseMatrix[Int](6, 6, (1 to 36).toArray)
val slice1 = m(1 to 3, 1 to 3)
assert(slice1(::, 1) === DenseVector(14, 15, 16))
assert(slice1(::, 1 to 2) === DenseMatrix((14, 20), (15, 21), (16, 22)))
}
test("Transpose") {
val m = DenseMatrix((1,2,3),(4,5,6))
// check that the double transpose gives us back the original
assert(m.t.t == m)
// check static type and write-through
val t = m.t
assert(t === DenseMatrix((1,4),(2,5),(3,6)))
t(0,1) = 0
assert(m === DenseMatrix((1,2,3),(0,5,6)))
}
test("Sliced Transpose") {
val m = DenseMatrix((0, 1, 2),
(3, 4, 5))
// column of original looks same as row of tranpose
val sm1 = m(::, 1)
val smt1 = m.t(1, ::)
assert(sm1.t === smt1)
val sm2 = m(::, 2)
val smt2 = m.t(2, ::)
assert(sm2.t === smt2)
val sm1c = m(1, ::)
val smt1c = m.t(::, 1)
assert(sm1c === smt1c.t)
val sm2c = m(0, ::)
val smt2c = m.t(::, 0)
assert(sm2c === smt2c.t)
// slice sub-matrix
val s1 = m(0 to 1, 1 to 2)
assert(s1 === DenseMatrix((1, 2), (4, 5)))
val t1 = s1.t
assert(t1 === DenseMatrix((1, 4), (2, 5)))
val t1b = m.t(1 to 2, 0 to 1)
assert(t1 === t1b)
val s2 = m(0 to 1, 1)
val t2 = m.t(1, 0 to 1)
assert(s2 === t2.t)
val s3 = m(0, 0 to 1)
val t3 = m.t(0 to 1, 0)
assert(s3.t === t3)
{
val s2 = m(0 to 1, ::)
val t2 = m.t(::, 0 to 1)
assert(s2.t === t2)
assert(s2 === t2.t)
val s3 = m(::, 0 to 1)
val t3 = m.t(0 to 1, ::)
assert(s3.t === t3)
assert(s3 === t3.t)
}
}
test("Min/Max") {
val m = DenseMatrix((1,0,0),(2,3,-1))
assert(argmin(m) === (1,2))
assert(argmax(m) === (1,1))
assert(min(m) === -1)
assert(max(m) === 3)
assert(minMax(m) === (-1, 3))
assert(ptp(m) === 4)
}
test("elementwise max") {
val v = DenseVector(2, 0, 3, 2, -1).asDenseMatrix
val v2 = DenseVector(3, -1, 3, 4, -4).asDenseMatrix
assert(max(v, v2) === DenseVector(3, 0, 3, 4, -1).asDenseMatrix)
assert(max(v, 2) === DenseVector(2, 2, 3, 2, 2).asDenseMatrix)
assert(min(v, 2) === DenseVector(2, 0, 2, 2, -1).asDenseMatrix)
}
test("Min/Max[Float]") {
val m = convert(DenseMatrix((1,0,0),(2,3,-1)), Float)
assert(argmin(m) === (1,2))
assert(argmax(m) === (1,1))
assert(min(m) === -1)
assert(max(m) === 3)
assert(minMax(m) === (-1.0f, 3.0f))
assert(ptp(m) === 4)
}
test("Min/Max[Double]") {
val m = convert(DenseMatrix((1,0,0),(2,3,-1)), Double)
assert(argmin(m) === (1,2))
assert(argmax(m) === (1,1))
assert(min(m) === -1)
assert(max(m) === 3)
assert(minMax(m) === (-1.0, 3.0))
assert(ptp(m) === 4)
}
test("Min/Max[Long]") {
val m = convert(DenseMatrix((1,0,0),(2,3,-1)), Long)
assert(argmin(m) === (1,2))
assert(argmax(m) === (1,1))
assert(min(m) === -1)
assert(max(m) === 3)
assert(minMax(m) === (-1L, 3L))
assert(ptp(m) === 4)
}
test("MapValues") {
val a : DenseMatrix[Int] = DenseMatrix((1,0,0),(2,3,-1))
val b1 : DenseMatrix[Int] = a.mapValues(_ + 1)
assert(b1 === DenseMatrix((2,1,1),(3,4,0)))
val b2 : DenseMatrix[Double] = a.mapValues(_ + 1.0)
assert(b2 === DenseMatrix((2.0,1.0,1.0),(3.0,4.0,0.0)))
val b3 = a.t.mapValues(_ + 1)
assert(b3 === DenseMatrix((2,3), (1,4), (1,0)))
}
/*
test("Map Triples") {
val a : DenseMatrix[Int] = DenseMatrix((1,0,0),(2,3,-1))
val b1 : DenseMatrix[Int] = a.mapTriples((i,j,v) => i + v)
assert(b1 === DenseMatrix((1,0,0),(3,4,0)))
val b2 : DenseMatrix[Double] = a.mapTriples((i,j,v) => j + v.toDouble)
assert(b2 === DenseMatrix((1.0,1.0,2.0),(2.0,4.0,1.0)))
}
test("Triples") {
val a : DenseMatrix[Int] = DenseMatrix((1,0,0),(2,3,-1))
var s = 0
// foreach
s = 0
for ((i,j,v) <- a.triples) s += v
assert(s === sum(a))
// filter
s = 0
for ((i,j,v) <- a.triples; if i % 2 == 0 || j % 2 == 0) s += v
assert(s === 1+2-1)
// // map
// val b1 : DenseMatrix[Double] = for ((i,j,v) <- a) yield v * 2.0
// assert(b1 === DenseMatrix((2.0,0.0,0.0),(4.0,6.0,-2.0)))
//
// // map with filter
// val b2 : DenseMatrix[Int] = for ((i,j,v) <- a; if j == 0) yield v * 2
// assert(b2 === DenseMatrix((2,0,0),(4,0,0)))
}
*/
test("set") {
{
val a = DenseMatrix.zeros[Int](2,2)
val b = DenseMatrix((1,0),(2,3))
a := b
assert(a === b)
}
val a = DenseMatrix.zeros[Int](2,3)
val b = DenseMatrix((1,0,5),(2,3,-1))
a := b
assert(a === b)
}
test("horzcat") {
val a : DenseMatrix[Int] = DenseMatrix((1,0,5),(2,3,-1))
val result: DenseMatrix[Int] = DenseMatrix((1,0,5,1,0, 5),(2,3,-1,2,3,-1))
assert(DenseMatrix.horzcat(a,a) === result)
}
test("vertcat") {
val a : DenseMatrix[Int] = DenseMatrix((1,0,5),(2,3,-1))
val result: DenseMatrix[Int] = DenseMatrix((1,0,5),(2,3,-1),(1,0,5),(2,3,-1))
assert(DenseMatrix.vertcat(a,a) === result)
}
test("Multiply") {
val a = DenseMatrix((1.0, 2.0, 3.0),(4.0, 5.0, 6.0))
val b = DenseMatrix((7.0, -2.0, 8.0),(-3.0, -3.0, 1.0),(12.0, 0.0, 5.0))
val c = DenseVector(6.0,2.0,3.0)
val cs = SparseVector(6.0,2.0,3.0)
assert(a * b === DenseMatrix((37.0, -8.0, 25.0), (85.0, -23.0, 67.0)))
assert(a * c === DenseVector(19.0,52.0))
assert(b * c === DenseVector(62.0, -21.0, 87.0))
assert(a * cs === DenseVector(19.0,52.0))
assert(b * cs === DenseVector(62.0, -21.0, 87.0))
assert(b.t * c === DenseVector(72.0, -18.0, 65.0))
assert(a.t * DenseVector(4.0, 3.0) === DenseVector(16.0, 23.0, 30.0))
assert(c.t * a.t === (a * c).t)
// should be dense
val x:DenseMatrix[Double] = a * a.t
assert(x === DenseMatrix((14.0,32.0),(32.0,77.0)))
// should be dense
val y:DenseMatrix[Double] = a.t * a
assert(y === DenseMatrix((17.0,22.0,27.0),(22.0,29.0,36.0),(27.0,36.0,45.0)))
val z : DenseMatrix[Double] = b * (b + 1.0)
assert(z === DenseMatrix((164.0,5.0,107.0),(-5.0,10.0,-27.0),(161.0,-7.0,138.0)))
}
test("Multiply Int") {
val a = DenseMatrix((1, 2, 3),(4, 5, 6))
val b = DenseMatrix((7, -2, 8),(-3, -3, 1),(12, 0, 5))
val c = DenseVector(6,2,3)
assert(a * b === DenseMatrix((37, -8, 25), (85, -23, 67)))
assert(a * c === DenseVector(19,52))
assert(b * c === DenseVector(62, -21, 87))
assert(b.t * c === DenseVector(72, -18, 65))
assert(a.t * DenseVector(4, 3) === DenseVector(16, 23, 30))
// should be dense
val x = a * a.t
assert(x === DenseMatrix((14,32),(32,77)))
// should be dense
val y = a.t * a
assert(y === DenseMatrix((17,22,27),(22,29,36),(27,36,45)))
val z : DenseMatrix[Int] = b * ((b + 1):DenseMatrix[Int])
assert(z === DenseMatrix((164,5,107),(-5,10,-27),(161,-7,138)))
}
test("Multiply Boolean") {
val a = DenseMatrix((true, true, true),(true, true, true))
val b = DenseMatrix((true, false, true),(true, false, true),(true, false, true))
assert(a * b === DenseMatrix((true, false, true),(true, false, true)))
}
test("Multiply Float") {
val a = DenseMatrix((1.0f, 2.0f, 3.0f),(4.0f, 5.0f, 6.0f))
val b = DenseMatrix((7.0f, -2.0f, 8.0f),(-3.0f, -3.0f, 1.0f),(12.0f, 0.0f, 5.0f))
val c = DenseVector(6.0f,2.0f,3.0f)
val cs = SparseVector(6.0f,2.0f,3.0f)
assert(a * b === DenseMatrix((37.0f, -8.0f, 25.0f), (85.0f, -23.0f, 67.0f)))
assert(a * c === DenseVector(19.0f,52.0f))
assert(b * c === DenseVector(62.0f, -21.0f, 87.0f))
assert(a * cs === DenseVector(19.0f,52.0f))
assert(b * cs === DenseVector(62.0f, -21.0f, 87.0f))
assert(b.t * c === DenseVector(72.0f, -18.0f, 65.0f))
assert(a.t * DenseVector(4.0f, 3.0f) === DenseVector(16.0f, 23.0f, 30.0f))
// should be dense
val x = a * a.t
assert(x === DenseMatrix((14.0f,32.0f),(32.0f,77.0f)))
// should be dense
val y = a.t * a
assert(y === DenseMatrix((17.0f,22.0f,27.0f),(22.0f,29.0f,36.0f),(27.0f,36.0f,45.0f)))
val z : DenseMatrix[Float] = b * (b + 1.0f)
assert(z === DenseMatrix((164.0f,5.0f,107.0f),(-5.0f,10.0f,-27.0f),(161.0f,-7.0f,138.0f)))
}
test("Multiply Complex") {
val a = DenseMatrix((Complex(1,1), Complex(2,2), Complex(3,3)),
(Complex(4,4), Complex(5,5), Complex(6,6)))
val b = DenseMatrix((Complex(7,7), Complex(-2,-2), Complex(8,8)),
(Complex(-3,-3), Complex(-3,-3), Complex(1,1)),
(Complex(12,12), Complex(0,0), Complex(5,5)))
val c = DenseVector(Complex(6,0), Complex(2,0), Complex(3,0))
val cs = SparseVector(Complex(6,0), Complex(2,0), Complex(3,0))
val value: DenseMatrix[Complex] = a * b
assert(value === DenseMatrix((Complex(0,74), Complex(0,-16), Complex(0,50)),
(Complex(0,170), Complex(0,-46), Complex(0,134))))
assert(b * c === DenseVector(Complex(62,62), Complex(-21,-21), Complex(87,87)))
assert(b * cs === DenseVector(Complex(62,62), Complex(-21,-21), Complex(87,87)))
assert(b.t * c === DenseVector(Complex(72,-72), Complex(-18,18), Complex(65,-65)))
}
test("Multiply BigDecimal") {
val a = DenseMatrix((1, 2, 3),(4, 5, 6)).mapValues(BigDecimal(_))
val b = DenseMatrix((7, -2, 8),(-3, -3, 1),(12, 0, 5)).mapValues(BigDecimal(_))
val c = DenseVector(6,2,3).mapValues(BigDecimal(_))
assert(a.*(b)(DenseMatrix.op_DM_DM_Semiring[BigDecimal]) === DenseMatrix((37, -8, 25), (85, -23, 67)).mapValues(BigDecimal(_)))
assert(a * c === DenseVector(19,52).mapValues(BigDecimal(_)))
assert(b * c === DenseVector(62, -21, 87).mapValues(BigDecimal(_)))
assert(b.t * c === DenseVector(72, -18, 65).mapValues(BigDecimal(_)))
assert(a.t * DenseVector(4, 3).mapValues(BigDecimal(_)) === DenseVector(16, 23, 30).mapValues(BigDecimal(_)))
// should be dense
val x = a * a.t
assert(x === DenseMatrix((14,32),(32,77)).mapValues(BigDecimal(_)))
// should be dense
val y = a.t * a
assert(y === DenseMatrix((17,22,27),(22,29,36),(27,36,45)).mapValues(BigDecimal(_)))
val z : DenseMatrix[BigDecimal] = b * ((b + BigDecimal(1)):DenseMatrix[BigDecimal])
assert(z === DenseMatrix((164,5,107),(-5,10,-27),(161,-7,138)).mapValues(BigDecimal(_)))
}
test("toDenseVector") {
val a = DenseMatrix((1,2,3), (4,5,6))
val b = a(0 to 1, 1 to 2)
val c = b.t
assert(a.toDenseVector === DenseVector(1,4,2,5,3,6))
assert(b.toDenseVector === DenseVector(2,5,3,6))
assert(c.toDenseVector === DenseVector(2,3,5,6))
}
test("flattenView") {
val a = DenseMatrix((1,2,3), (4,5,6))
a.flatten(true)(2) = 4
assert(a === DenseMatrix((1,4,3), (4,5,6)))
}
test("Trace") {
assert(trace(DenseMatrix((1,2),(4,5))) === 1 + 5)
assert(trace(DenseMatrix((1,2,3),(3,4,5),(5,6,7))) == 1 + 4 + 7)
assert(trace(DenseMatrix((1,2,3),(4,5,6),(7,8,9))) === 1 + 5 + 9)
}
test("Reshape") {
val m : DenseMatrix[Int] = DenseMatrix((1,2,3),(4,5,6))
val r : DenseMatrix[Int] = m.reshape(3, 2, true)
assert(m.data eq r.data)
assert(r.rows === 3)
assert(r.cols === 2)
assert(r === DenseMatrix((1,5),(4,3),(2,6)))
}
test("Reshape transpose") {
val m : DenseMatrix[Int] = DenseMatrix((1,2,3),(4,5,6)).t
val r : DenseMatrix[Int] = m.reshape(2, 3, true)
assert(m.data eq r.data)
assert(r.rows === 2)
assert(r.cols === 3)
assert(r === DenseMatrix((1,5),(4,3),(2,6)).t)
}
test("Solve") {
// square solve
val r1 : DenseMatrix[Double] = DenseMatrix((1.0,3.0),(2.0,0.0)) \ DenseMatrix((1.0,2.0),(3.0,4.0))
assert(r1 === DenseMatrix((1.5, 2.0), (-1.0/6, 0.0)))
// matrix-vector solve
val r2 : DenseVector[Double] = DenseMatrix((1.0,3.0,4.0),(2.0,0.0,6.0)) \ DenseVector(1.0,3.0)
assert( norm(r2 - DenseVector(0.1813186813186811, -0.3131868131868131, 0.43956043956043944), inf) < 1E-5)
// wide matrix solve
val r3 : DenseMatrix[Double] = DenseMatrix((1.0,3.0,4.0),(2.0,0.0,6.0)) \ DenseMatrix((1.0,2.0),(3.0,4.0))
matricesNearlyEqual(r3,
DenseMatrix((0.1813186813186811, 0.2197802197802196),
(-0.3131868131868131, -0.1978021978021977),
(0.43956043956043944, 0.5934065934065933)))
// tall matrix solve
val r4 : DenseMatrix[Double] = DenseMatrix((1.0,3.0),(2.0,0.0),(4.0,6.0)) \ DenseMatrix((1.0,4.0),(2.0,5.0),(3.0,6.0))
assert( max(abs(r4 - DenseMatrix((0.9166666666666667, 1.9166666666666672),
(-0.08333333333333352, -0.08333333333333436)))) < 1E-5)
}
test("Solve Float") {
// square solve
val r1 : DenseMatrix[Float] = DenseMatrix((1.0f,3.0f),(2.0f,0.0f)) \ DenseMatrix((1.0f,2.0f),(3.0f,4.0f))
assert(r1 === DenseMatrix((1.5f, 2.0f), (-1.0f/6, 0.0f)))
// matrix-vector solve
val r2 : DenseVector[Float] = DenseMatrix((1.0f,3.0f,4.0f),(2.0f,0.0f,6.0f)) \ DenseVector(1.0f,3.0f)
assert( norm(r2 - DenseVector(0.1813186813186811f, -0.3131868131868131f, 0.43956043956043944f)) < 1E-5)
// wide matrix solve
val r3 : DenseMatrix[Float] = DenseMatrix((1.0f,3.0f,4.0f),(2.0f,0.0f,6.0f)) \ DenseMatrix((1.0f,2.0f),(3.0f,4.0f))
assert( max(abs(r3 - DenseMatrix((0.1813186813186811f, 0.2197802197802196f),
(-0.3131868131868131f, -0.1978021978021977f),
(0.43956043956043944f, 0.5934065934065933f)))) < 1E-5)
// tall matrix solve
val r4 : DenseMatrix[Float] = DenseMatrix((1.0f,3.0f),(2.0f,0.0f),(4.0f,6.0f)) \ DenseMatrix((1.0f,4.0f),(2.0f,5.0f),(3.0f,6.0f))
assert( max(abs(r4 - DenseMatrix((0.9166666666666667f, 1.9166666666666672f),
(-0.08333333333333352f, -0.08333333333333436f)))) < 1E-5)
}
test("GH#29 transpose solve is broken") {
val A = DenseMatrix((1.0,0.0),(1.0,-1.0))
val t = DenseVector(1.0,0.0)
assert(A \ t === DenseVector(1.0, 1.0))
assert(A.t \ t === DenseVector(1.0, 0.0))
}
test("sum") {
// Test square and rectangular matrices
val A = DenseMatrix((1.0, 3.0), (2.0, 4.0))
assert(sum(A, Axis._0) === DenseVector(3.0, 7.0).t)
assert(sum(A(::, *)) === DenseVector(3.0, 7.0).t)
assert(sum(DenseMatrix((1.0,3.0,5.0),(2.0,4.0,6.0)), Axis._0) === DenseVector(3.0, 7.0,11.0).t)
assert(sum(DenseMatrix((1.0,3.0),(2.0,4.0),(5.0, 6.0)), Axis._0) === DenseVector(8.0, 13.0).t)
assert(sum(A, Axis._1) === DenseVector(4.0, 6.0))
assert(sum(DenseMatrix((1.0,3.0,5.0),(2.0,4.0,6.0)), Axis._1) === DenseVector(9.0, 12.0))
assert(sum(DenseMatrix((1.0,3.0),(2.0,4.0),(5.0, 6.0)), Axis._1) === DenseVector(4.0, 6.0, 11.0))
assert(sum(A) === 10.0)
}
test("normalize rows and columns") {
val A = DenseMatrix((1.0, 3.0), (2.0, 4.0))
assert(normalize(A, Axis._0, 1) === DenseMatrix((1.0/3.0, 3.0/7.0), (2.0/3.0,4.0/7.0)))
assert(normalize(A, Axis._1, 1) === DenseMatrix((1.0/4.0, 3.0/4.0), (2.0/6.0,4.0/6.0)))
// handle odd sized matrices (test for a bug.)
val dm = DenseMatrix.tabulate(2,5)( (i,j) => i * j * 1.0 + 1)
dm := normalize(dm, Axis._1, 2)
assert(abs(sum(dm(0,::).t.map(x => x * x)) - 1.0) < 1E-4, dm.toString + " not normalized!")
}
test("Generic Dense ops") {
// mostly for coverage
val a = DenseMatrix.create[String](1,1, Array("SSS"))
intercept[IndexOutOfBoundsException] {
a(3,3) = ":("
assert(false, "Shouldn't be here!")
}
assert(a(0,0) === "SSS")
intercept[IndexOutOfBoundsException] {
a(3,3)
assert(false, "Shouldn't be here!")
}
a(0,0) = ":("
assert(a(0,0) === ":(")
a := ":)"
assert(a(0,0) === ":)")
val b = DenseMatrix.zeros[String](1,1)
b := a
assert(b === a)
}
test("toString with no rows doesn't throw") {
DenseMatrix.zeros[Double](0, 2).toString
}
test("GH #30: Shaped solve of transposed and slice matrix does not work") {
val A=DenseMatrix((1.0,0.0),(1.0,-1.0))
val i = DenseMatrix.eye[Double](2)
val res = i \ A.t(::,1)
assert(res === DenseVector(1.0,-1.0))
val res2 = i \ A(1,::).t
assert(res2 === DenseVector(1.0,-1.0))
}
test("GH #148: out of bounds slice throws") {
val temp2 = DenseMatrix.tabulate(5,5)( (x: Int, y: Int) => x + y*10 )
intercept[IndexOutOfBoundsException] {
temp2( Range( 4, 6 ), 3 )
}
}
test("softmax on dm slices") {
val a = DenseMatrix((1.0, 2.0, 3.0))
assert(softmax(a(::, 1)) === 2.0)
}
test("Delete") {
val a = DenseMatrix((1, 2, 3),(4, 5, 6), (7,8,9))
assert(a.delete(0, Axis._0) === DenseMatrix((4, 5, 6), (7,8,9)))
assert(a.delete(1, Axis._0) === DenseMatrix((1, 2, 3), (7,8,9)))
assert(a.delete(2, Axis._0) === DenseMatrix((1, 2, 3), (4,5,6)))
assert(a.delete(0, Axis._1) === DenseMatrix((2, 3), (5,6), (8,9)))
assert(a.delete(1, Axis._1) === DenseMatrix((1, 3), (4,6), (7,9)))
assert(a.delete(2, Axis._1) === DenseMatrix((1, 2), (4,5), (7,8)))
assert(a.delete(Seq(0,2), Axis._1) === DenseMatrix(2, 5, 8))
assert(a.delete(Seq(1, 2), Axis._1) === DenseMatrix(1, 4, 7))
assert(a.delete(Seq(0,2), Axis._0) === DenseMatrix((4, 5, 6)))
assert(a.delete(Seq(1,2), Axis._0) === DenseMatrix((1, 2, 3)))
}
test("Big Int zeros are the right thing") {
val dm = DenseMatrix.zeros[BigInt](1,1)
assert(dm(0, 0) === BigInt(0))
}
test("BigInt multiply") {
val m = DenseMatrix((BigInt(1), BigInt(1)), (BigInt(1), BigInt(0)))
val m2 = DenseMatrix((1, 1), (1, 0))
assert(m * m === convert(m2 * m2, Int))
}
test("comparisons") {
val one = DenseMatrix.ones[Double](5, 6)
val zero = DenseMatrix.zeros[Double](5, 6)
assert( (one :> zero) === DenseMatrix.ones[Boolean](5, 6))
}
test("Some ill-typedness") {
import shapeless.test.illTyped
illTyped {
"""
val one = DenseMatrix.ones[Double](5, 6)
val z = DenseVector.zeros[Double](5)
(z + one)
"""
}
}
test("ensure we don't crash on weird strides") {
val dm = DenseMatrix.zeros[Double](3,3)
assert( (dm(::, 0 until 0) * dm(0 until 0, ::)) === dm)
assert( (dm(0 until 0, ::) * dm(::, 0 until 0)) === DenseMatrix.zeros[Double](0, 0))
// assert( (dm(::, 2 until 0 by -1) * dm(2 until 0 by -1, ::)) === dm)
}
test("Ensure a += a.t gives the right result") {
val dm = DenseMatrix.rand[Double](3,3)
val dmdmt = dm + dm.t
dm += dm.t
assert(dm === dmdmt)
}
test("#221") {
val data = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val mat = new DenseMatrix(rows = 10, data, offset = 0).t
val area = mat(3 until 6, 2 until 7)
assert(area === DenseMatrix((3,4,5,6,7),
(3,4,5,6,7),
(3,4,5,6,7)))
assert(area.t === DenseMatrix((3,4,5,6,7),
(3,4,5,6,7),
(3,4,5,6,7)).t)
val sl2t = area.t(0 until area.cols, 1 until area.rows)
assert(sl2t.offset === area.offset + area.majorStride, sl2t.data(area.offset + area.majorStride) + " " + area.offset)
assert(sl2t.t === DenseMatrix( (3,4,5,6,7),
(3,4,5,6,7)))
val sl2 = area(1 until area.rows, 0 until area.cols)
assert(sl2 === DenseMatrix( (3,4,5,6,7),
(3,4,5,6,7)))
}
test("DenseMatrix construction with list of lists") {
val dm = DenseMatrix(List(List(1, 2, 3, 0, 0, 0, 0, 0, 0), List(0, 0, 0, 1, 2, 3, 0, 0, 0), List(0, 0, 0, 0, 0, 0, 1, 2, 3)):_*)
}
test("#265: slices of :: and IndexedSeq") {
val dm = DenseMatrix( (0, 1, 2), (3, 4, 5))
assert(dm(::, IndexedSeq(2,1, 0)).toDenseMatrix === fliplr(dm))
assert(dm(IndexedSeq(1, 0), ::).toDenseMatrix === flipud(dm))
}
test("#278: don't crash on solve when majorStride == 0") {
val d = DenseVector[Double]()
val m = DenseMatrix.tabulate(0,0) { case x => 0.0 }
assert( m \ d === d)
}
test("#283: slice of dm by dm boolean") {
val dm = DenseMatrix( (0, 1, 2), (3, 4, 5))
dm(dm :>= 2) := 3
assert(dm === DenseMatrix( (0, 1, 3), (3, 3, 3)))
}
test("#286: argsort diverging implicit") {
val dm = DenseMatrix( (0.1f), (0.0f))
assert(argsort(dm) === IndexedSeq((1, 0), (0, 0)))
}
test("#289: sigmoid dm slice") {
val m = DenseMatrix.zeros[Double](10, 10)
assert(sigmoid(m(::,0 to 5)) === DenseMatrix.fill(10, 6)(0.5))
assert(sigmoid(m(::,3 to 5)) === DenseMatrix.fill(10, 3)(0.5))
}
def matricesNearlyEqual(A: DenseMatrix[Double], B: DenseMatrix[Double], threshold: Double = 1E-6) {
for(i <- 0 until A.rows; j <- 0 until A.cols)
A(i,j) should be (B(i, j) +- threshold)
}
test("#336 argmax for Dense Matrices") {
val m = DenseMatrix.zeros[Double](3, 3)
m(2, ::) := DenseVector(1.0, 2.0, 3.0).t
assert(argmax(m(2, ::).t) === 2)
assert(max(m(2, ::).t) === 3.0)
}
test("lhs scalars") {
assert(1.0 :/ (DenseMatrix.fill(2,2)(10.0)) === DenseMatrix.fill(2,2)(1/10.0))
assert(1.0 :- (DenseMatrix.fill(2,2)(10.0)) === DenseMatrix.fill(2,2)(-9.0))
}
test("mapping ufunc") {
val r = DenseMatrix.rand(100, 100)
val explicit = new DenseMatrix(100, 100, r.data.map(math.sin))
assert(sin(r) == explicit)
sin.inPlace(r)
assert(explicit == r)
}
test("mapping ufunc, strides") {
val r = (DenseMatrix.rand(100, 100)).apply(10 until 27, 4 until 37 by 4)
var explicit = new DenseMatrix(100, 100, r.data.map(math.sin))
explicit = explicit(10 until 27, 4 until 37 by 4)
assert(sin(r) == explicit)
sin.inPlace(r)
assert(explicit == r)
}
test("#449") {
val m = DenseMatrix.rand(10, 10)
m(List(1, 2, 3), 0 to 0) := 5d //WORKS FINE
m(List(1, 2, 3), 0) := 5d //NOT WORKING
m(1 to 3, 0) := 5d //WORKING
m(List(1, 2, 3), 0 to 0) := m(List(1, 2, 3), 0 to 0) //WORKS FINE
m(List(1, 2, 3), 0) := m(List(1, 2, 3), 0) //NOT WORKING
m(1 to 3, 0) := m(1 to 3, 0) //WORKS FINE
}
test("#476: DM * DV when rows == 0") {
val m = DenseMatrix.zeros[Double](0, 10)
val v = DenseVector.zeros[Double](10)
assert(m * v == DenseVector.zeros[Double](0))
val m2 = DenseMatrix.zeros[Double](10, 0)
val v2 = DenseVector.zeros[Double](0)
assert(m2 * v2 == DenseVector.zeros[Double](10))
}
test("#534: DenseMatrix construction from empty row sequence") {
val rows = Seq.empty[Seq[Double]]
val matrix = DenseMatrix(rows: _*)
assert(matrix.rows == 0)
assert(matrix.cols == 0)
}
}
|
claydonkey/breeze
|
math/src/test/scala/breeze/linalg/DenseMatrixTest.scala
|
Scala
|
apache-2.0
| 24,863 |
package com.github.mdr.mash.ns.core
import com.github.mdr.mash.functions.{ BoundParams, MashFunction, ParameterModel }
import com.github.mdr.mash.runtime.{ MashObject, MashValue }
object NoArgFunction extends MashFunction("core.noArg") {
val NoArgValue: MashValue = MashObject.empty.withClass(NoArgClass)
def option(x: MashValue): Option[MashValue] = x match {
case NoArgValue ⇒ None
case _ ⇒ Some(x)
}
val params = ParameterModel.Empty
def call(boundParams: BoundParams): MashValue = NoArgValue
override def summaryOpt = Some("Value that represents no argument being provided, for use as sentinel values in default arguments")
}
|
mdr/mash
|
src/main/scala/com/github/mdr/mash/ns/core/NoArgFunction.scala
|
Scala
|
mit
| 671 |
import java.io._
import collection._
object Test {
def serializeDeserialize[T <: AnyRef](obj: T) = {
val buffer = new ByteArrayOutputStream
val out = new ObjectOutputStream(buffer)
out.writeObject(obj)
val in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray))
in.readObject.asInstanceOf[T]
}
def main(args: Array[String]): Unit = {
val values = mutable.Map(1 -> 1).values
assert(serializeDeserialize(values).toList == values.toList)
val keyset = mutable.Map(1 -> 1).keySet
assert(serializeDeserialize(keyset) == keyset)
val imkeyset = immutable.Map(1 -> 1).keySet
assert(serializeDeserialize(imkeyset) == imkeyset)
val defaultmap = immutable.Map(1 -> 1).withDefaultValue(1)
assert(serializeDeserialize(defaultmap) == defaultmap)
val minusmap = mutable.Map(1 -> 1).withDefault(x => -x)
assert(serializeDeserialize(minusmap) == minusmap)
}
}
|
lrytz/scala
|
test/files/run/t5018.scala
|
Scala
|
apache-2.0
| 935 |
/*
* Copyright 2016 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.ct.computations
import uk.gov.hmrc.ct.box.{CtBoxIdentifier, CtInteger, Linked}
case class CP274(value: Int) extends CtBoxIdentifier("Qualifying expenditure other machinery and plant") with CtInteger
object CP274 extends Linked[CP253, CP274]{
override def apply(source: CP253): CP274 = CP274(source.value)
}
|
ahudspith-equalexperts/ct-calculations
|
src/main/scala/uk/gov/hmrc/ct/computations/CP274.scala
|
Scala
|
apache-2.0
| 939 |
package nest.sparkle.time.server
import spray.json.DefaultJsonProtocol
/** served to the javascript client so it can find the web socket port */
case class JsServiceConfig(webSocketPort:Int, adminUploadPort:Int)
object JsServiceConfigJson extends DefaultJsonProtocol {
implicit val JsServiceConfigFormat = jsonFormat2(JsServiceConfig)
}
|
mighdoll/sparkle
|
protocol/src/main/scala/nest/sparkle/time/server/JsServiceConfig.scala
|
Scala
|
apache-2.0
| 342 |
package com.szadowsz.starform.model.star.calc
import com.szadowsz.starform.model.star.constants.FoggBaseStarConst
import com.szadowsz.starform.rand.RandGenTrait
import com.szadowsz.starform.system.bodies.star.FoggStar
/**
* Created on 13/04/2017.
*/
case class FoggStarCalc(override val sConst: FoggBaseStarConst) extends StarCalc[FoggStar] {
/**
* Method to pseudo-randomly generate the mass of a star in solar mass.
*
* @note The solar mass is a standard unit of mass in astronomy that is used to indicate the masses of other stars, as well as clusters, nebulae and
* galaxies. It is equal to the mass of the Sun, about two nonillion kilograms. As per section "2. The Microcomputer Model" in "Extra-solar Planetary
* Systems: A Microcomputer Simulation", we are aiming for a star of a mass between 0.6 and 1.3 solar masses.
*
* @see p. 502, Extra-solar Planetary Systems: A Microcomputer Simulation - Martyn J. Fogg
* @see method generate_stellar_system, line 89 in main.c - Mat Burdick (accrete)
* @see method generate_stellar_system, line 68 in gensys.c - Keris (starform)
* @see method generate_stellar_system, line 81 in starform.c - Mat Burdick (starform)
* @see constructor StarSystem, line 50 in StarSystem.java - Carl Burke (starform)
*
* @param rand pseudo-random number generator interface
* @return generated mass in terms of solar mass
*/
def stellarMass(rand: RandGenTrait): Double = (sConst.UPPER_SOLAR_MASS - sConst.LOWER_SOLAR_MASS) * rand.nextDouble() + sConst.LOWER_SOLAR_MASS
/**
* Method to approximate the luminosity of a star for a given mass. See eq. 1-3 in section "3. Characteristics of The Primary Star" in Extra-solar Planetary
* Systems: A Microcomputer Simulation.
*
* @note The solar luminosity, is a unit of radiant flux (power emitted in the form of photons) conventionally used by astronomers to measure the luminosity
* of stars. One solar luminosity is equal to the current accepted luminosity of the Sun, which is 3.839×1026 W, or 3.839×1033 erg/s. The value is
* slightly higher, 3.939×1026 W (equivalent to 4.382×109 kg/s or 1.9×10?16 M?/d) if the solar neutrino radiation is included as well as
* electromagnetic radiation. The Sun is a weakly variable star and its luminosity therefore fluctuates. The major fluctuation is the eleven-year
* solar cycle (sunspot cycle), which causes a periodic variation of about ±0.1%. Any other variation over the last 200–300 years is thought to be
* much smaller than this.
*
* @see p. 502 Extra-solar Planetary Systems: A Microcomputer Simulation - Martyn J. Fogg
* @see method luminosity, line 10 in enviro.c - Mat Burdick (accrete)
* @see method luminosity, line 11 in accrete.c - Keris (starform)
* @see method luminosity, line 10 in accrete.c - Mat Burdick (starform)
* @see method LUMINOSITY, line 182 in Star.java - Carl Burke (starform)
*
* @param stellarMass star's mass in terms of solar mass
* @return star's luminosity in terms of solar luminosity
*/
def stellarLuminosity(stellarMass: Double): Double = {
if (stellarMass < 1.0) {
Math.pow(stellarMass, 1.75 * (stellarMass - 0.1) + 3.325)
} else {
Math.pow(stellarMass, 0.5 * (2.0 - stellarMass) + 4.4)
}
}
override def initStar(rand: RandGenTrait): FoggStar = {
val mass: Double = stellarMass(rand)
val luminosity: Double = stellarLuminosity(mass)
val lifespan: Double = stellarMSLifespan(mass, luminosity)
val age: Double = stellarAge(rand, lifespan)
val meanHabitableRadius: Double = ecosphereRadius(luminosity)
val innerHabitableRadius: Double = greenhouseRadius(meanHabitableRadius)
new FoggStar(mass, luminosity, lifespan, age, innerHabitableRadius, meanHabitableRadius)
}
}
|
zakski/accrete-starform-stargen
|
recreations/composite/src/main/scala/com/szadowsz/starform/model/star/calc/FoggStarCalc.scala
|
Scala
|
apache-2.0
| 3,886 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package org.apache.toree.utils
import joptsimple.util.KeyValuePair
/**
* Provides utility methods for jsimple-opt key pair values.
*/
object KeyValuePairUtils {
val DefaultDelimiter = ","
/**
* Transforms the provided string into a list of KeyValuePair objects.
* @param keyValuePairString The string representing the series of keys and
* values
* @param delimiter The delimiter used for splitting up the string
* @return The list of KeyValuePair objects
*/
def stringToKeyValuePairSeq(
keyValuePairString: String,
delimiter: String = DefaultDelimiter
): Seq[KeyValuePair] = {
require(keyValuePairString != null, "KeyValuePair string cannot be null!")
keyValuePairString
.split(delimiter)
.map(_.trim)
.filterNot(_.isEmpty)
.map(KeyValuePair.valueOf)
.toSeq
}
/**
* Transforms the provided list of KeyValuePair elements into a string.
* @param keyValuePairSeq The sequence of KeyValuePair objects
* @param delimiter The separator between string KeyValuePair
* @return The resulting string from the list of KeyValuePair objects
*/
def keyValuePairSeqToString(
keyValuePairSeq: Seq[KeyValuePair],
delimiter: String = DefaultDelimiter
): String = {
require(keyValuePairSeq != null, "KeyValuePair sequence cannot be null!")
keyValuePairSeq
.map(pair => pair.key.trim + "=" + pair.value.trim)
.mkString(delimiter)
}
}
|
chipsenkbeil/incubator-toree
|
kernel-api/src/main/scala/org/apache/toree/utils/KeyValuePairUtils.scala
|
Scala
|
apache-2.0
| 2,286 |
/*
* Copyright 2014-2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.atlas.eval.graph
import com.netflix.atlas.core.model.DataExpr
import com.netflix.atlas.core.model.MathExpr
import com.netflix.atlas.core.model.Query
import com.netflix.atlas.core.model.Query.KeyValueQuery
import com.netflix.atlas.core.model.StyleExpr
import com.typesafe.scalalogging.StrictLogging
/**
* Helper to analyze a set of expressions and try to automatically set a reasonable
* human readable legend.
*/
private[graph] object SimpleLegends extends StrictLogging {
def generate(exprs: List[StyleExpr]): List[StyleExpr] = {
try {
// Extract key/value pairs from all expressions
val kvs = exprs
.map(e => e -> extractKeyValues(e))
.filterNot(_._2.isEmpty)
.toMap
if (kvs.isEmpty) {
exprs
} else {
// Figure out the unique set
val common = kvs.values.reduce(intersect)
exprs.map { expr =>
if (hasExplicitLegend(expr)) {
expr
} else if (kvs.contains(expr)) {
val kv = kvs(expr)
val uniq = diff(kv, common)
if (uniq.nonEmpty)
generateLegend(expr, uniq)
else if (common.nonEmpty)
generateLegend(expr, common)
else
expr
} else {
expr
}
}
}
} catch {
// This is a nice to have presentation detail. In case it fails for any reason we
// just fallback to the defaults. Under normal usage this is not expected to ever
// be reached.
case e: Exception =>
logger.warn("failed to generate simple legend, using default", e)
exprs
}
}
private def hasExplicitLegend(expr: StyleExpr): Boolean = {
expr.settings.contains("legend")
}
private def withLegend(expr: StyleExpr, legend: String): StyleExpr = {
val label = if (expr.offset > 0L) s"$legend (offset=$$atlas.offset)" else legend
expr.copy(settings = expr.settings + ("legend" -> label))
}
private def keyValues(query: Query): Map[String, String] = {
query match {
case Query.And(q1, q2) => keyValues(q1) ++ keyValues(q2)
case Query.Equal(k, v) => Map(k -> v)
case Query.LessThan(k, v) => Map(k -> v)
case Query.LessThanEqual(k, v) => Map(k -> v)
case Query.GreaterThan(k, v) => Map(k -> v)
case Query.GreaterThanEqual(k, v) => Map(k -> v)
case Query.Regex(k, v) => Map(k -> v)
case Query.RegexIgnoreCase(k, v) => Map(k -> v)
case Query.Not(q: KeyValueQuery) => keyValues(q).map(t => t._1 -> s"!${t._2}")
case _ => Map.empty
}
}
private def generateLegend(expr: StyleExpr, kv: Map[String, String]): StyleExpr = {
if (expr.expr.isGrouped) {
val fmt = expr.expr.finalGrouping.mkString("$", " $", "")
withLegend(expr, fmt)
} else if (kv.contains("name")) {
withLegend(expr, kv("name"))
} else {
val legend = kv.toList.sortWith(_._1 < _._1).map(_._2).mkString(" ")
withLegend(expr, legend)
}
}
private def extractKeyValues(expr: StyleExpr): Map[String, String] = {
val dataExprs = removeNamedRewrites(expr).expr.dataExprs
if (dataExprs.isEmpty)
Map.empty
else
dataExprs.map(de => keyValues(de.query)).reduce(intersect)
}
private def removeNamedRewrites(expr: StyleExpr): StyleExpr = {
// Custom averages like dist-avg and node-avg are done with rewrites that can
// lead to confusing legends. For the purposes here those can be rewritten to
// a simple aggregate like sum based on the display expression.
expr
.rewrite {
case MathExpr.NamedRewrite(n, q: Query, _, _, _) if n.endsWith("-avg") =>
DataExpr.Sum(q)
}
.asInstanceOf[StyleExpr]
}
private def intersect(m1: Map[String, String], m2: Map[String, String]): Map[String, String] = {
m1.toSet.intersect(m2.toSet).toMap
}
private def diff(m1: Map[String, String], m2: Map[String, String]): Map[String, String] = {
m1.toSet.diff(m2.toSet).toMap
}
}
|
brharrington/atlas
|
atlas-eval/src/main/scala/com/netflix/atlas/eval/graph/SimpleLegends.scala
|
Scala
|
apache-2.0
| 4,716 |
package nmcb.chronos
import org.scalatest.{FlatSpec, Matchers}
/**
* [] is period A
* () is period B
*
* ---[ ]--( )---
* ---[ ( ] )---
* ---[ ( ) ]---
*
* ---( )--[ ]---
* ---( [ ) ]---
* ---( [ ] )---
*/
class PeriodTest extends FlatSpec with Matchers {
val t1 = Time("01:00")
val t2 = Time("11:00")
val t3 = Time("13:00")
val t4 = Time("23:00")
val a1 = Period(t1, t2)
val a2 = Period(t1, t3)
val a3 = Period(t1, t4)
val a4 = Period(t3, t4)
val a5 = Period(t2, t4)
val a6 = Period(t2, t3)
val b1 = Period(t3, t4)
val b2 = Period(t2, t4)
val b3 = Period(t2, t3)
val b4 = Period(t1, t2)
val b5 = Period(t1, t3)
val b6 = Period(t1, t4)
"a period" should "union another period" in {
(a1 union b1) shouldBe (Right((Period(t1, t2), Period(t3, t4))))
(a2 union b2) shouldBe (Left(Period(t1, t4)))
(a3 union b3) shouldBe (Left(Period(t1, t4)))
(a4 union b4) shouldBe (Right((Period(t1, t2), Period(t3, t4))))
(a5 union b5) shouldBe (Left(Period(t1, t4)))
(a6 union b6) shouldBe (Left(Period(t1, t4)))
}
it should "intersect another period" in {
(a1 intersection b1) shouldBe (None)
(a2 intersection b2) shouldBe (Some(Period(t2, t3)))
(a3 intersection b3) shouldBe (Some(Period(t2, t3)))
(a4 intersection b4) shouldBe (None)
(a5 intersection b5) shouldBe (Some(Period(t2, t3)))
(a6 intersection b6) shouldBe (Some(Period(t2, t3)))
}
it should "diff another period" in {
(a1 diff b1) shouldBe (Some(Left(a1)))
(a2 diff b2) shouldBe (Some(Left(Period(t1, t2))))
(a3 diff b3) shouldBe (Some(Right((Period(t1, t2), Period(t3, t4)))))
(a4 diff b4) shouldBe (Some(Left(a4)))
(a5 diff b5) shouldBe (Some(Left(Period(t3, t4))))
(a6 diff b6) shouldBe (None)
}
}
|
nmcb/chronos
|
src/test/scala/nmcb/chronos/PeriodTest.scala
|
Scala
|
artistic-2.0
| 1,797 |
package com.artclod.mathml.scalar
import com.artclod.mathml._
import com.artclod.mathml.scalar.concept.Constant
import scala.util.{Success, _}
import scala.xml._
case class Logbase(val value: Constant)
extends MathMLElem(MathML.h.prefix, "logbase", MathML.h.attributes, MathML.h.scope, false, Seq(value): _*) with NoMathMLChildren {
def eval(boundVariables: Map[String, Double]) = Failure(new UnsupportedOperationException("Logbase should not get evaled, use eval on the surrounding element."))
def constant: Option[Constant] = None
def variables: Set[String] = Set()
def simplifyStep() = this
def derivative(wrt: String): MathMLElem = throw new UnsupportedOperationException("Logbase should not get derived, use derive on the surrounding element.")
val v : BigDecimal = value match {
case c: CnInteger => BigDecimal(c.v)
case c: CnReal => c.v
}
override def toMathJS: String = value.toMathJS
}
object Logbase {
def apply(v: BigDecimal): Logbase = Logbase(Cn(v))
def apply(e: Elem): Try[Logbase] = MathML(e) match {
case Failure(a) => Failure(a)
case Success(a) => a match {
case c: CnInteger => Logbase(Cn(c.v))
case c: CnReal => Logbase(Cn(c.v))
case _ => Failure(new IllegalArgumentException("Could not create Logbase from " + e))
}
}
}
|
kristiankime/calc-tutor
|
app/com/artclod/mathml/scalar/Logbase.scala
|
Scala
|
mit
| 1,283 |
package mesosphere.marathon
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicBoolean
import java.util.{ Timer, TimerTask }
import javax.inject.{ Inject, Named }
import akka.actor.{ ActorRef, ActorSystem, Props }
import akka.pattern.ask
import akka.util.Timeout
import com.google.common.util.concurrent.AbstractExecutionThreadService
import com.twitter.common.base.ExceptionalCommand
import com.twitter.common.zookeeper.Candidate
import com.twitter.common.zookeeper.Candidate.Leader
import com.twitter.common.zookeeper.Group.JoinException
import mesosphere.marathon.MarathonSchedulerActor._
import mesosphere.marathon.Protos.MarathonTask
import mesosphere.marathon.health.HealthCheckManager
import mesosphere.marathon.state.{ AppDefinition, AppRepository, Migration, PathId, Timestamp }
import mesosphere.marathon.tasks.TaskTracker
import mesosphere.marathon.upgrade.DeploymentActor.DeploymentStepInfo
import mesosphere.marathon.upgrade.DeploymentPlan
import mesosphere.mesos.util.FrameworkIdUtil
import mesosphere.util.PromiseActor
import org.apache.log4j.Logger
import scala.concurrent.duration.{ MILLISECONDS, _ }
import scala.concurrent.{ Await, Future, Promise }
import scala.util.{ Failure, Random, Success }
/**
* Wrapper class for the scheduler
*/
class MarathonSchedulerService @Inject() (
healthCheckManager: HealthCheckManager,
@Named(ModuleNames.NAMED_CANDIDATE) candidate: Option[Candidate],
config: MarathonConf,
frameworkIdUtil: FrameworkIdUtil,
@Named(ModuleNames.NAMED_LEADER_ATOMIC_BOOLEAN) leader: AtomicBoolean,
appRepository: AppRepository,
taskTracker: TaskTracker,
scheduler: MarathonScheduler,
system: ActorSystem,
migration: Migration,
@Named("schedulerActor") schedulerActor: ActorRef) extends AbstractExecutionThreadService with Leader {
import mesosphere.util.ThreadPoolContext.context
implicit val zkTimeout = config.zkFutureTimeout
val latch = new CountDownLatch(1)
// Time to wait before trying to reconcile app tasks after driver starts
val reconciliationInitialDelay =
Duration(config.reconciliationInitialDelay(), MILLISECONDS)
// Interval between task reconciliation operations
val reconciliationInterval =
Duration(config.reconciliationInterval(), MILLISECONDS)
val reconciliationTimer = new Timer("reconciliationTimer")
val log = Logger.getLogger(getClass.getName)
val frameworkId = frameworkIdUtil.fetch
frameworkId match {
case Some(id) =>
log.info(s"Setting framework ID to ${id.getValue}")
case None =>
log.info("No previous framework ID found")
}
// This is a little ugly as we are using a mutable variable. But drivers can't
// be reused (i.e. once stopped they can't be started again. Thus,
// we have to allocate a new driver before each run or after each stop.
var driver = MarathonSchedulerDriver.newDriver(config, scheduler, frameworkId)
implicit val timeout: Timeout = 5.seconds
def deploy(plan: DeploymentPlan, force: Boolean = false): Future[Unit] = {
log.info(s"Deploy plan:$plan with force:$force")
val promise = Promise[AnyRef]()
val receiver = system.actorOf(Props(classOf[PromiseActor], promise))
schedulerActor.tell(Deploy(plan, force), receiver)
promise.future.map {
case DeploymentStarted(_) => ()
case CommandFailed(_, t) => throw t
}
}
def listApps(): Iterable[AppDefinition] =
Await.result(appRepository.apps(), config.zkTimeoutDuration)
def listAppVersions(appId: PathId): Iterable[Timestamp] =
Await.result(appRepository.listVersions(appId), config.zkTimeoutDuration)
def listRunningDeployments(): Future[Seq[(DeploymentPlan, DeploymentStepInfo)]] =
(schedulerActor ? RetrieveRunningDeployments)
.mapTo[RunningDeployments]
.map(_.plans)
def getApp(appId: PathId): Option[AppDefinition] = {
Await.result(appRepository.currentVersion(appId), config.zkTimeoutDuration)
}
def getApp(appId: PathId, version: Timestamp): Option[AppDefinition] = {
Await.result(appRepository.app(appId, version), config.zkTimeoutDuration)
}
def killTasks(
appId: PathId,
tasks: Iterable[MarathonTask],
scale: Boolean): Iterable[MarathonTask] = {
schedulerActor ! KillTasks(appId, tasks.map(_.getId).toSet, scale)
tasks
}
//Begin Service interface
override def startUp(): Unit = {
log.info("Starting up")
super.startUp()
}
override def run(): Unit = {
log.info("Beginning run")
// The first thing we do is offer our leadership. If using Zookeeper for
// leadership election then we will wait to be elected. If we aren't (i.e.
// no HA) then we take over leadership run the driver immediately.
offerLeadership()
// Start the timer that handles reconciliation
schedulePeriodicOperations()
// Block on the latch which will be countdown only when shutdown has been
// triggered. This is to prevent run()
// from exiting.
latch.await()
log.info("Completed run")
}
override def triggerShutdown(): Unit = {
log.info("Shutdown triggered")
leader.set(false)
stopDriver()
log.info("Cancelling reconciliation timer")
reconciliationTimer.cancel()
log.info("Removing the blocking of run()")
// The countdown latch blocks run() from exiting. Counting down the latch removes the block.
latch.countDown()
super.triggerShutdown()
}
def runDriver(abdicateCmdOption: Option[ExceptionalCommand[JoinException]]): Unit = {
log.info("Running driver")
// The following block asynchronously runs the driver. Note that driver.run()
// blocks until the driver has been stopped (or aborted).
Future {
driver.run()
} onComplete {
case Success(_) =>
log.info("Driver future completed. Executing optional abdication command.")
// If there is an abdication command we need to execute it so that our
// leadership is given up. Note that executing the abdication command
// does a few things: - It causes onDefeated() to be executed (which is
// part of the Leader interface). - It removes us as a leadership
// candidate. We must offer out leadership candidacy if we ever want to
// become the leader again in the future.
//
// If we don't have a abdication command we simply mark ourselves as
// not the leader
abdicateCmdOption match {
case Some(cmd) => cmd.execute()
case _ => leader.set(false)
}
// If we are shutting down then don't offer leadership. But if we
// aren't then the driver was stopped via external means. For example,
// our leadership could have been defeated or perhaps it was
// abdicated. Therefore, for these cases we offer our leadership again.
if (isRunning) {
offerLeadership()
}
case Failure(t) =>
log.error("Exception while running driver", t)
}
}
def stopDriver(): Unit = {
log.info("Stopping driver")
// Stopping the driver will cause the driver run() method to return.
driver.stop(true) // failover = true
// We need to allocate a new driver as drivers can't be reused. Once they
// are in the stopped state they cannot be restarted. See the Mesos C++
// source code for the MesosScheduleDriver.
driver = MarathonSchedulerDriver.newDriver(config, scheduler, frameworkId)
}
def isLeader = {
leader.get()
}
def getLeader: Option[String] = {
candidate.flatMap { c =>
if (c.getLeaderData.isPresent)
Some(new String(c.getLeaderData.get))
else
None
}
}
//End Service interface
//Begin Leader interface, which is required for CandidateImpl.
override def onDefeated(): Unit = {
log.info("Defeated (Leader Interface)")
// Our leadership has been defeated and thus we call the defeatLeadership() method.
defeatLeadership()
}
override def onElected(abdicateCmd: ExceptionalCommand[JoinException]): Unit = {
log.info("Elected (Leader Interface)")
//execute tasks, only the leader is allowed to
migration.migrate()
// We have been elected. Thus, elect leadership with the abdication command.
electLeadership(Some(abdicateCmd))
}
//End Leader interface
private def defeatLeadership(): Unit = {
log.info("Defeat leadership")
// Our leadership has been defeated. Thus, update leadership and stop the driver.
// Note that abdication command will be ran upon driver shutdown.
leader.set(false)
// Stop all health checks
healthCheckManager.removeAll()
stopDriver()
}
private def electLeadership(abdicateOption: Option[ExceptionalCommand[JoinException]]): Unit = {
log.info("Elect leadership")
// We have been elected as leader. Thus, update leadership and run the driver.
leader.set(true)
runDriver(abdicateOption)
// Create health checks for any existing apps
listApps foreach healthCheckManager.reconcileWith
}
def abdicateLeadership(): Unit = {
log.info("Abdicating")
// To abdicate we defeat our leadership
defeatLeadership()
}
private def offerLeadership(): Unit = {
log.info("Offering leadership")
candidate.synchronized {
candidate match {
case Some(c) =>
// In this case we care using Zookeeper for leadership candidacy.
// Thus, offer our leadership.
log.info("Using HA and therefore offering leadership")
c.offerLeadership(this)
case _ =>
// In this case we aren't using Zookeeper for leadership election.
// Thus, we simply elect ourselves as leader.
log.info("Not using HA and therefore electing as leader by default")
electLeadership(None)
}
}
}
private def schedulePeriodicOperations(): Unit = {
reconciliationTimer.schedule(
new TimerTask {
def run() {
if (isLeader) {
schedulerActor ! ReconcileTasks
}
else log.info("Not leader therefore not reconciling tasks")
}
},
reconciliationInitialDelay.toMillis,
reconciliationInterval.toMillis
)
// Tasks are only expunged once after the application launches
// Wait until reconciliation is definitely finished so that we are guaranteed
// to have loaded in all apps
reconciliationTimer.schedule(
new TimerTask {
def run() {
taskTracker.expungeOrphanedTasks()
}
},
reconciliationInitialDelay.toMillis + reconciliationInterval.toMillis
)
}
private def newAppPort(app: AppDefinition): Integer = {
// TODO this is pretty expensive, find a better way
val assignedPorts = listApps().flatMap(_.ports).toSet
val portSum = config.localPortMax() - config.localPortMin()
// prevent infinite loop if all ports are taken
if (assignedPorts.size >= portSum)
throw new PortRangeExhaustedException(config.localPortMin(), config.localPortMax())
var port = 0
do {
port = config.localPortMin() + Random.nextInt(portSum)
} while (assignedPorts.contains(port))
port
}
}
|
tnachen/marathon
|
src/main/scala/mesosphere/marathon/MarathonSchedulerService.scala
|
Scala
|
apache-2.0
| 11,228 |
package mesosphere.marathon.state
import java.io.{ ByteArrayInputStream, ByteArrayOutputStream, ObjectInputStream, ObjectOutputStream }
import javax.inject.Inject
import mesosphere.marathon.Protos.StorageVersion
import mesosphere.marathon.state.PathId._
import mesosphere.marathon.state.StorageVersions._
import mesosphere.marathon.tasks.TaskTracker
import mesosphere.marathon.tasks.TaskTracker.{ InternalApp, App }
import mesosphere.marathon.{ BuildInfo, MarathonConf, StorageException }
import mesosphere.util.BackToTheFuture.futureToFutureOption
import mesosphere.util.ThreadPoolContext.context
import mesosphere.util.{ BackToTheFuture, Logging }
import com.codahale.metrics.MetricRegistry
import org.apache.mesos.state.{ State, Variable }
import scala.collection.JavaConverters._
import scala.concurrent.duration.Duration
import scala.concurrent.{ Await, Future }
import scala.util.{ Failure, Success, Try }
class Migration @Inject() (
state: State,
appRepo: AppRepository,
groupRepo: GroupRepository,
config: MarathonConf,
registry: MetricRegistry,
implicit val timeout: BackToTheFuture.Timeout = BackToTheFuture.Implicits.defaultTimeout)
extends Logging {
type MigrationAction = (StorageVersion, () => Future[Any])
/**
* All the migrations, that have to be applied.
* They get applied after the master has been elected.
*/
def migrations: List[MigrationAction] = List(
StorageVersions(0, 5, 0) -> {
() => changeApps(app => app.copy(id = app.id.toString.toLowerCase.replaceAll("_", "-").toRootPath))
},
StorageVersions(0, 7, 0) -> {
() =>
changeTasks(app => new InternalApp(app.appName.canonicalPath(), app.tasks, app.shutdown))
changeApps(app => app.copy(id = app.id.canonicalPath()))
putAppsIntoGroup()
}
)
def applyMigrationSteps(from: StorageVersion): Future[List[StorageVersion]] = {
val result = migrations.filter(_._1 > from).sortBy(_._1).map {
case (migrateVersion, change) =>
log.info(
s"Migration for storage: ${from.str} to current: ${current.str}: " +
s"apply change for version: ${migrateVersion.str} "
)
change.apply().map(_ => migrateVersion)
}
Future.sequence(result)
}
def migrate(): StorageVersion = {
val result = for {
changes <- currentStorageVersion.flatMap(applyMigrationSteps)
storedVersion <- storeCurrentVersion
} yield storedVersion
result.onComplete {
case Success(version) => log.info(s"Migration successfully applied for version ${version.str}")
case Failure(ex) => log.error(s"Migration failed! $ex")
}
Await.result(result, Duration.Inf)
}
private val storageVersionName = "internal:storage:version"
def currentStorageVersion: Future[StorageVersion] = {
state.fetch(storageVersionName).map {
case Some(variable) => Try(StorageVersion.parseFrom(variable.value())).getOrElse(StorageVersions.empty)
case None => throw new StorageException("Failed to read storage version")
}
}
def storeCurrentVersion: Future[StorageVersion] = {
state.fetch(storageVersionName) flatMap {
case Some(variable) =>
state.store(variable.mutate(StorageVersions.current.toByteArray)) map {
case Some(newVar) => StorageVersion.parseFrom(newVar.value)
case None => throw new StorageException(s"Failed to store storage version")
}
case None => throw new StorageException("Failed to read storage version")
}
}
// specific migration helper methods
private def changeApps(fn: AppDefinition => AppDefinition): Future[Any] = {
appRepo.apps().flatMap { apps =>
val mappedApps = apps.map { app => appRepo.store(fn(app)) }
Future.sequence(mappedApps)
}
}
private def changeTasks(fn: InternalApp => InternalApp): Future[Any] = {
val taskTracker = new TaskTracker(state, config, registry)
def fetchApp(appId: PathId): Option[InternalApp] = {
val bytes = state.fetch("tasks:" + appId.safePath).get().value
if (bytes.length > 0) {
val source = new ObjectInputStream(new ByteArrayInputStream(bytes))
val fetchedTasks = taskTracker.legacyDeserialize(appId, source).map {
case (key, task) =>
val builder = task.toBuilder.clearOBSOLETEStatuses()
task.getOBSOLETEStatusesList.asScala.lastOption.foreach(builder.setStatus)
key -> builder.build()
}
Some(new InternalApp(appId, fetchedTasks, false))
}
else None
}
def store(app: InternalApp): Future[Seq[Variable]] = {
val oldVar = state.fetch("tasks:" + app.appName.safePath).get()
val bytes = new ByteArrayOutputStream()
val output = new ObjectOutputStream(bytes)
Future.sequence(app.tasks.values.toSeq.map(taskTracker.store(app.appName, _)))
}
appRepo.allPathIds().flatMap { apps =>
val res = apps.flatMap(fetchApp).map{ app => store(fn(app)) }
Future.sequence(res)
}
}
private def putAppsIntoGroup(): Future[Any] = {
groupRepo.group("root").map(_.getOrElse(Group.empty)).map { group =>
appRepo.apps().flatMap { apps =>
val updatedGroup = apps.foldLeft(group) { (group, app) =>
val updatedApp = app.copy(id = app.id.canonicalPath())
group.updateApp(updatedApp.id, _ => updatedApp, Timestamp.now())
}
groupRepo.store("root", updatedGroup)
}
}
}
}
object StorageVersions {
val VersionRegex = """^(\\d+)\\.(\\d+)\\.(\\d+).*""".r
def apply(major: Int, minor: Int, patch: Int): StorageVersion = {
StorageVersion
.newBuilder()
.setMajor(major)
.setMinor(minor)
.setPatch(patch)
.build()
}
def current: StorageVersion = {
BuildInfo.version match {
case VersionRegex(major, minor, patch) =>
StorageVersions(
major.toInt,
minor.toInt,
patch.toInt
)
}
}
implicit class OrderedStorageVersion(val version: StorageVersion) extends AnyVal with Ordered[StorageVersion] {
override def compare(that: StorageVersion): Int = {
def by(left: Int, right: Int, fn: => Int): Int = if (left.compareTo(right) != 0) left.compareTo(right) else fn
by(version.getMajor, that.getMajor, by(version.getMinor, that.getMinor, by(version.getPatch, that.getPatch, 0)))
}
def str: String = s"Version(${version.getMajor}, ${version.getMinor}, ${version.getPatch})"
}
def empty: StorageVersion = StorageVersions(0, 0, 0)
}
|
14Zen/marathon
|
src/main/scala/mesosphere/marathon/state/Migration.scala
|
Scala
|
apache-2.0
| 6,551 |
package ohnosequences.blast.api
import ohnosequences.cosas._, types._
/*
This trait models a command part of the `BLAST` suite, like `blastn`, `blastp`, or `makeblastdb`.
All the BLAST suite commands, together with their arguments, options and default values
are defined in separate files in the (commands/)[commands/] folder (but in the same `api` namespace).
*/
// sealed
trait AnyBlastCommand {
/* This label **should** match the **name** of the command */
lazy val name: Seq[String] = Seq(this.toString)
type Arguments <: AnyBlastOptionsRecord
type Options <: AnyBlastOptionsRecord
type ArgumentsVals <: Arguments#Raw
type OptionsVals <: Options#Raw
/* default values for options; they are *optional*, so should have default values. */
val defaults: Options := OptionsVals
/* valid output fields for this command */
type ValidOutputFields <: AnyBlastOutputFields
}
/*
An expression is a BLAST command with all the needed arguments given and ready to be executed
*/
trait AnyBlastExpression {
type Command <: AnyBlastCommand
val command: Command
type OutputRecord <: AnyBlastOutputRecord.For[Command]
val outputRecord: OutputRecord
val argumentValues: Command#ArgumentsVals
val optionValues: Command#OptionsVals
// implicitly:
val argValsToSeq: BlastOptionsToSeq[Command#ArgumentsVals]
val optValsToSeq: BlastOptionsToSeq[Command#OptionsVals]
/* For command values we generate a `Seq[String]` which is valid command expression that you can
execute (assuming BLAST installed) using `scala.sys.process` or anything similar. */
def toSeq: Seq[String] =
command.name ++
argValsToSeq(argumentValues) ++
optValsToSeq(optionValues) ++
outputRecord.toSeq
}
case class BlastExpression[
C <: AnyBlastCommand,
R <: AnyBlastOutputRecord.For[C]
](val command: C
)(val outputRecord: R,
val argumentValues: C#ArgumentsVals,
val optionValues: C#OptionsVals
)(implicit
val argValsToSeq: BlastOptionsToSeq[C#ArgumentsVals],
val optValsToSeq: BlastOptionsToSeq[C#OptionsVals]
) extends AnyBlastExpression {
type Command = C
type OutputRecord = R
}
|
ohnosequences/blast
|
src/main/scala/api/expressions.scala
|
Scala
|
agpl-3.0
| 2,141 |
package com.twitter.finagle.factory
import com.twitter.finagle._
import com.twitter.util.{Future, Time, Await}
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar
import com.twitter.conversions.time._
@RunWith(classOf[JUnitRunner])
class ServiceFactoryCacheTest extends FunSuite with MockitoSugar {
test("cache, evict") (Time.withCurrentTimeFrozen { tc =>
var factories: Map[Int, Int] = Map.empty
var news: Map[Int, Int] = Map.empty
case class SF(i: Int) extends ServiceFactory[String, String] {
assert(!(factories contains i))
factories += (i -> 0)
news += (i -> (1+news.getOrElse(i, 0)))
def apply(conn: ClientConnection) = Future.value(new Service[String, String] {
factories = factories + (i -> (factories(i)+1))
def apply(req: String) = Future.value(i.toString)
override def close(deadline: Time) = {
factories += (i -> (factories(i) - 1))
Future.Done
}
})
def close(deadline: Time) = {
factories -= i
Future.Done
}
}
val newFactory: Int => ServiceFactory[String, String] = { i => SF(i) }
val cache = new ServiceFactoryCache[Int, String, String](newFactory, maxCacheSize=2)
assert(factories.isEmpty)
val s1 = Await.result(cache(1, ClientConnection.nil))
assert(factories === Map(1->1))
val s2 = Await.result(cache(2, ClientConnection.nil))
assert(factories === Map(1->1, 2->1))
val s3 = Await.result(cache(3, ClientConnection.nil))
assert(factories === Map(1->1, 2->1, 3->1))
Await.result(s3.close())
assert(factories === Map(1->1, 2->1))
Await.result(s2.close())
tc.advance(1.second)
assert(factories === Map(1->1, 2->0))
Await.result(s1.close())
tc.advance(1.second)
assert(factories === Map(1->0, 2->0))
assert(news === Map(1->1, 2->1, 3->1))
val s3x = Await.result(cache(3, ClientConnection.nil))
assert(factories === Map(1->0, 3->1))
assert(news === Map(1->1, 2->1, 3->2))
val s1x, s1y = Await.result(cache(1, ClientConnection.nil))
assert(factories === Map(1->2, 3->1))
assert(news === Map(1->1, 2->1, 3->2))
val s2x = Await.result(cache(2, ClientConnection.nil))
assert(factories === Map(1->2, 3->1, 2->1))
assert(news === Map(1->1, 2->2, 3->2))
})
}
|
JustinTulloss/finagle
|
finagle-core/src/test/scala/com/twitter/finagle/factory/ServiceFactoryCacheTest.scala
|
Scala
|
apache-2.0
| 2,405 |
/* tree-converter.scala
* Copyright (C) 2012 Grégoire Détrez
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.grammaticalframework.parser
/**
* This convert abstract trees to intermediate trees and vice-versa
* */
import org.grammaticalframework.intermediateTrees._
// import pgf.abstractTrees.{
// Tree => ETree
// , Lambda => ELambda
// , Application => EApplication
// , Literal => ELiteral
// , MetaVariable => EMetaVariable
// , Function => EFunction
// , Variable => EVariable
// , TypeSignature => ETypeSignature
// , ImpliciteArgument => EImpliciterArgument
// }
import org.grammaticalframework.Trees.Absyn.{
Tree => ETree
, Lambda => ELambda
, Application => EApplication
, Literal => ELiteral
, MetaVariable => EMetaVariable
, Function => EFunction
, Variable => EVariable
, StringLiteral
// , TypeSignature => ETypeSignature
// , ImpliciteArgument => EImpliciterArgument
}
object TreeConverter {
def intermediate2abstract (t : Tree): ETree = {
def c2a(t : Tree, vars:List[String]): ETree = t match {
// Here we have to convert sugarized λ-abstraction (λx,y,z → ...)
// to canonical ones (λx→λy→λz→...)
case Lambda(lvars, body) =>
lvars.foldRight(c2a(body, lvars.map(_._2).reverse ++ vars))(mkELambda)
// Here variables are index by name but abstract
// syntax uses de Bruijn indices
case Variable(x) => new EVariable(vars.indexOf(x))
// Here we have to desugarized applicaton :
// f a b c becomes (((f a) b) c)
case Application(fun,args) =>
args.map(c2a(_, vars)).foldLeft(new EFunction(fun):ETree)(mkEApp)
case Literal(value) => new ELiteral(new StringLiteral(value))
case MetaVariable(id) => new EMetaVariable(id)
}
def mkEApp(f : ETree, x : ETree):ETree = new EApplication(f,x)
def mkELambda(v :(Boolean, String) , body:ETree ):ETree = v match {
case (bindType, name) => new ELambda(name, body)
}
c2a(t, Nil)
}
// tree2expr ys (Fun x ts) = foldl EApp (EFun x) (List.map (tree2expr ys) ts)
// tree2expr ys (Abs xs t) = foldr (\\(b,x) e -> EAbs b x e) (tree2expr (List.map snd (reverse xs)++ys) t) xs
// tree2expr ys (Var x) = case List.lookup x (zip ys [0..]) of
// Just i -> EVar i
// Nothing -> error "unknown variable"
// class IllegalLiteralOfFunctionType extends Exception
// class IllegalBetaRedex extends Exception
// class IllegalFunctionMetaVariable extends Exception
// def abstract2intermediate(t : ETree):Tree = {
// /** Here we have to transform single argument
// * λ-abstraction into sugarized ones (λx→λy→... to λx,y→...)
// * To do that, we accumulate the variables in bindings
// * Applied to an expression that is not a λ-abstraction
// * it just calls mkTree on it */
// def mkLambda(t : ETree, bindings:List[(Boolean, String)], vars:List[String]):Tree =
// t match {
// case ELambda(bindType, cid, body) => {val bindings1 = (bindType, cid)::bindings
// mkLambda(body, bindings1, vars)}
// // We don't care about local types...
// case ETypeSignature(t, _) => mkLambda(t, bindings, vars)
// // for any other expression :
// case e => bindings match {
// case Nil => mkTree(e, Nil, vars)
// case _ => new Lambda (bindings.reverse, mkTree(e, Nil , vars))
// }
// }
// /** take an abstract tree e and turn it into an
// * intermediate tree.
// * @param args is the list of arguments e is applied to
// * @param vars is the list of binded variable
// * */
// def mkTree(e : ETree, args : List[Tree], vars:List[String] ):Tree = e match {
// case EApplication(e1,e2) => {
// /** here we call mkLambda on e2, and not mkTree,
// * because e2 could be a λ-abstraction */
// val args1 = mkLambda(e2,Nil,vars)::args
// mkTree(e1, args1, vars)
// }
// case ELiteral(l) => args match {
// case Nil => new Literal(l)
// case _ => throw new IllegalLiteralOfFunctionType
// }
// case EMetaVariable(n) => args match {
// case Nil => new MetaVariable(n)
// case _ => throw new IllegalFunctionMetaVariable
// }
// case ELambda(_, x, e) => throw new IllegalBetaRedex
// case EVariable(i) => new Variable(vars(i))
// case EFunction(f) => new Application(f, args)
// case ETypeSignature(e,_) => mkTree(e, args, vars)
// case e => {
// println(e)
// throw new Exception(e.toString)
// }
// }
// mkLambda(t, Nil, Nil)
// }
}
|
GrammaticalFramework/JPGF
|
src/org/grammaticalframework/parser/tree-converter.scala
|
Scala
|
lgpl-2.1
| 5,453 |
/*
* Copyright 2001-2013 Artima, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.scalatest.matchers
import org.scalatest._
import org.scalatest.prop.Checkers
import org.scalacheck._
import Arbitrary._
import Prop._
import org.scalatest.exceptions.TestFailedException
import FailureMessages._
class ShouldContainKeySpec extends Spec with ShouldMatchers with Checkers with ReturnsNormallyThrowsAssertion {
// Checking for a specific size
object `The 'contain key (Int)' syntax` {
object `on scala.collection.immutable.Map` {
def `should do nothing if map contains specified key` {
Map("one" -> 1, "two" -> 2) should contain key ("two")
Map("one" -> 1, "two" -> 2) should (contain key ("two"))
Map(1 -> "one", 2 -> "two") should contain key (2)
}
def `should do nothing if map does not contain the specified key and used with not` {
Map("one" -> 1, "two" -> 2) should not { contain key ("three") }
Map("one" -> 1, "two" -> 2) should not contain key ("three")
Map("one" -> 1, "two" -> 2) should (not contain key ("three"))
}
def `should do nothing when map contains specified key and used in a logical-and expression` {
Map("one" -> 1, "two" -> 2) should { contain key ("two") and (contain key ("one")) }
Map("one" -> 1, "two" -> 2) should ((contain key ("two")) and (contain key ("one")))
Map("one" -> 1, "two" -> 2) should (contain key ("two") and contain key ("one"))
}
def `should do nothing when map contains specified key and used in a logical-or expression` {
Map("one" -> 1, "two" -> 2) should { contain key ("cat") or (contain key ("one")) }
Map("one" -> 1, "two" -> 2) should ((contain key ("cat")) or (contain key ("one")))
Map("one" -> 1, "two" -> 2) should (contain key ("cat") or contain key ("one"))
}
def `should do nothing when map does not contain the specified key and used in a logical-and expression with not` {
Map("one" -> 1, "two" -> 2) should { not { contain key ("five") } and not { contain key ("three") }}
Map("one" -> 1, "two" -> 2) should ((not contain key ("five")) and (not contain key ("three")))
Map("one" -> 1, "two" -> 2) should (not contain key ("five") and not contain key ("three"))
}
def `should do nothing when map does not contain the specified key and used in a logical-or expression with not` {
Map("one" -> 1, "two" -> 2) should { not { contain key ("two") } or not { contain key ("three") }}
Map("one" -> 1, "two" -> 2) should ((not contain key ("two")) or (not contain key ("three")))
Map("one" -> 1, "two" -> 2) should (not contain key ("two") or not contain key ("three"))
}
def `should throw TestFailedException if map does not contain the specified key` {
val caught1 = intercept[TestFailedException] {
Map("one" -> 1, "two" -> 2) should contain key ("three")
}
assert(caught1.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"three\\"")
}
def `should throw TestFailedException if contains the specified key when used with not` {
val caught1 = intercept[TestFailedException] {
Map("one" -> 1, "two" -> 2) should (not contain key ("two"))
}
assert(caught1.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
val caught2 = intercept[TestFailedException] {
Map("one" -> 1, "two" -> 2) should not (contain key ("two"))
}
assert(caught2.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
val caught3 = intercept[TestFailedException] {
Map("one" -> 1, "two" -> 2) should not contain key ("two")
}
assert(caught3.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
}
def `should throw an TestFailedException when map doesn't contain specified key and used in a logical-and expression` {
val caught1 = intercept[TestFailedException] {
Map("one" -> 1, "two" -> 2) should { contain key ("five") and (contain key ("two")) }
}
assert(caught1.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"five\\"")
val caught2 = intercept[TestFailedException] {
Map("one" -> 1, "two" -> 2) should ((contain key ("five")) and (contain key ("two")))
}
assert(caught2.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"five\\"")
val caught3 = intercept[TestFailedException] {
Map("one" -> 1, "two" -> 2) should (contain key ("five") and contain key ("two"))
}
assert(caught3.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"five\\"")
}
def `should throw an TestFailedException when map doesn't contain specified key and used in a logical-or expression` {
val caught1 = intercept[TestFailedException] {
Map("one" -> 1, "two" -> 2) should { contain key ("fifty five") or (contain key ("twenty two")) }
}
assert(caught1.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"fifty five\\", and Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"twenty two\\"")
val caught2 = intercept[TestFailedException] {
Map("one" -> 1, "two" -> 2) should ((contain key ("fifty five")) or (contain key ("twenty two")))
}
assert(caught2.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"fifty five\\", and Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"twenty two\\"")
val caught3 = intercept[TestFailedException] {
Map("one" -> 1, "two" -> 2) should (contain key ("fifty five") or contain key ("twenty two"))
}
assert(caught3.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"fifty five\\", and Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"twenty two\\"")
}
def `should throw an TestFailedException when map contains specified key and used in a logical-and expression with not` {
val caught1 = intercept[TestFailedException] {
Map("one" -> 1, "two" -> 2) should { not { contain key ("three") } and not { contain key ("two") }}
}
assert(caught1.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"three\\", but Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
val caught2 = intercept[TestFailedException] {
Map("one" -> 1, "two" -> 2) should ((not contain key ("three")) and (not contain key ("two")))
}
assert(caught2.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"three\\", but Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
val caught3 = intercept[TestFailedException] {
Map("one" -> 1, "two" -> 2) should (not contain key ("three") and not contain key ("two"))
}
assert(caught3.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"three\\", but Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
}
def `should throw an TestFailedException when map contains specified key and used in a logical-or expression with not` {
val caught1 = intercept[TestFailedException] {
Map("one" -> 1, "two" -> 2) should { not { contain key ("two") } or not { contain key ("two") }}
}
assert(caught1.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\", and Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
val caught2 = intercept[TestFailedException] {
Map("one" -> 1, "two" -> 2) should ((not contain key ("two")) or (not contain key ("two")))
}
assert(caught2.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\", and Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
val caught3 = intercept[TestFailedException] {
Map("one" -> 1, "two" -> 2) should (not contain key ("two") or not contain key ("two"))
}
assert(caught3.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\", and Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
}
def `should work on parallel form` {
Map("one" -> 1, "two" -> 2).par should contain key ("two")
}
}
object `on scala.collection.mutable.Map` {
import scala.collection.mutable
def `should do nothing if map contains specified key` {
mutable.Map("one" -> 1, "two" -> 2) should contain key ("two")
mutable.Map("one" -> 1, "two" -> 2) should (contain key ("two"))
mutable.Map(1 -> "one", 2 -> "two") should contain key (2)
}
def `should do nothing if map does not contain the specified key and used with not` {
mutable.Map("one" -> 1, "two" -> 2) should not { contain key ("three") }
mutable.Map("one" -> 1, "two" -> 2) should not contain key ("three")
mutable.Map("one" -> 1, "two" -> 2) should (not contain key ("three"))
}
def `should do nothing when map contains specified key and used in a logical-and expression` {
mutable.Map("one" -> 1, "two" -> 2) should { contain key ("two") and (contain key ("one")) }
mutable.Map("one" -> 1, "two" -> 2) should ((contain key ("two")) and (contain key ("one")))
mutable.Map("one" -> 1, "two" -> 2) should (contain key ("two") and contain key ("one"))
}
def `should do nothing when map contains specified key and used in a logical-or expression` {
mutable.Map("one" -> 1, "two" -> 2) should { contain key ("cat") or (contain key ("one")) }
mutable.Map("one" -> 1, "two" -> 2) should ((contain key ("cat")) or (contain key ("one")))
mutable.Map("one" -> 1, "two" -> 2) should (contain key ("cat") or contain key ("one"))
}
def `should do nothing when map does not contain the specified key and used in a logical-and expression with not` {
mutable.Map("one" -> 1, "two" -> 2) should { not { contain key ("five") } and not { contain key ("three") }}
mutable.Map("one" -> 1, "two" -> 2) should ((not contain key ("five")) and (not contain key ("three")))
mutable.Map("one" -> 1, "two" -> 2) should (not contain key ("five") and not contain key ("three"))
}
def `should do nothing when map does not contain the specified key and used in a logical-or expression with not` {
mutable.Map("one" -> 1, "two" -> 2) should { not { contain key ("two") } or not { contain key ("three") }}
mutable.Map("one" -> 1, "two" -> 2) should ((not contain key ("two")) or (not contain key ("three")))
mutable.Map("one" -> 1, "two" -> 2) should (not contain key ("two") or not contain key ("three"))
}
def `should throw TestFailedException if map does not contain the specified key` {
val map = mutable.Map("one" -> 1, "two" -> 2)
val caught1 = intercept[TestFailedException] {
map should contain key ("three")
}
assert(caught1.getMessage === decorateToStringValue(map) + " did not contain key \\"three\\"")
}
def `should throw TestFailedException if contains the specified key when used with not` {
val map1 = mutable.Map("one" -> 1, "two" -> 2)
val caught1 = intercept[TestFailedException] {
map1 should (not contain key ("two"))
}
assert(caught1.getMessage === decorateToStringValue(map1) + " contained key \\"two\\"")
val map2 = mutable.Map("one" -> 1, "two" -> 2)
val caught2 = intercept[TestFailedException] {
map2 should not (contain key ("two"))
}
assert(caught2.getMessage === decorateToStringValue(map2) + " contained key \\"two\\"")
val map3 = mutable.Map("one" -> 1, "two" -> 2)
val caught3 = intercept[TestFailedException] {
map3 should not contain key ("two")
}
assert(caught3.getMessage === decorateToStringValue(map3) + " contained key \\"two\\"")
}
def `should throw an TestFailedException when map doesn't contain specified key and used in a logical-and expression` {
val map1 = mutable.Map("one" -> 1, "two" -> 2)
val caught1 = intercept[TestFailedException] {
map1 should { contain key ("five") and (contain key ("two")) }
}
assert(caught1.getMessage === decorateToStringValue(map1) + " did not contain key \\"five\\"")
val map2 = mutable.Map("one" -> 1, "two" -> 2)
val caught2 = intercept[TestFailedException] {
map2 should ((contain key ("five")) and (contain key ("two")))
}
assert(caught2.getMessage === decorateToStringValue(map2) + " did not contain key \\"five\\"")
val map3 = mutable.Map("one" -> 1, "two" -> 2)
val caught3 = intercept[TestFailedException] {
map3 should (contain key ("five") and contain key ("two"))
}
assert(caught3.getMessage === decorateToStringValue(map3) + " did not contain key \\"five\\"")
}
def `should throw an TestFailedException when map doesn't contain specified key and used in a logical-or expression` {
val map1 = mutable.Map("one" -> 1, "two" -> 2)
val caught1 = intercept[TestFailedException] {
map1 should { contain key ("fifty five") or (contain key ("twenty two")) }
}
assert(caught1.getMessage === decorateToStringValue(map1) + " did not contain key \\"fifty five\\", and " + decorateToStringValue(map1) + " did not contain key \\"twenty two\\"")
val map2 = mutable.Map("one" -> 1, "two" -> 2)
val caught2 = intercept[TestFailedException] {
map2 should ((contain key ("fifty five")) or (contain key ("twenty two")))
}
assert(caught2.getMessage === decorateToStringValue(map2) + " did not contain key \\"fifty five\\", and " + decorateToStringValue(map2) + " did not contain key \\"twenty two\\"")
val map3 = mutable.Map("one" -> 1, "two" -> 2)
val caught3 = intercept[TestFailedException] {
map3 should (contain key ("fifty five") or contain key ("twenty two"))
}
assert(caught3.getMessage === decorateToStringValue(map3) + " did not contain key \\"fifty five\\", and " + decorateToStringValue(map3) + " did not contain key \\"twenty two\\"")
}
def `should throw an TestFailedException when map contains specified key and used in a logical-and expression with not` {
val map1 = mutable.Map("one" -> 1, "two" -> 2)
val caught1 = intercept[TestFailedException] {
map1 should { not { contain key ("three") } and not { contain key ("two") }}
}
assert(caught1.getMessage === decorateToStringValue(map1) + " did not contain key \\"three\\", but " + decorateToStringValue(map1) + " contained key \\"two\\"")
val map2 = mutable.Map("one" -> 1, "two" -> 2)
val caught2 = intercept[TestFailedException] {
map2 should ((not contain key ("three")) and (not contain key ("two")))
}
assert(caught2.getMessage === decorateToStringValue(map2) + " did not contain key \\"three\\", but " + decorateToStringValue(map2) + " contained key \\"two\\"")
val map3 = mutable.Map("one" -> 1, "two" -> 2)
val caught3 = intercept[TestFailedException] {
map3 should (not contain key ("three") and not contain key ("two"))
}
assert(caught3.getMessage === decorateToStringValue(map3) + " did not contain key \\"three\\", but " + decorateToStringValue(map3) + " contained key \\"two\\"")
}
def `should throw an TestFailedException when map contains specified key and used in a logical-or expression with not` {
val map1 = mutable.Map("one" -> 1, "two" -> 2)
val caught1 = intercept[TestFailedException] {
map1 should { not { contain key ("two") } or not { contain key ("two") }}
}
assert(caught1.getMessage === decorateToStringValue(map1) + " contained key \\"two\\", and " + decorateToStringValue(map1) + " contained key \\"two\\"")
val map2 = mutable.Map("one" -> 1, "two" -> 2)
val caught2 = intercept[TestFailedException] {
map2 should ((not contain key ("two")) or (not contain key ("two")))
}
assert(caught2.getMessage === decorateToStringValue(map2) + " contained key \\"two\\", and " + decorateToStringValue(map2) + " contained key \\"two\\"")
val map3 = mutable.Map("one" -> 1, "two" -> 2)
val caught3 = intercept[TestFailedException] {
map3 should (not contain key ("two") or not contain key ("two"))
}
assert(caught3.getMessage === decorateToStringValue(map3) + " contained key \\"two\\", and " + decorateToStringValue(map3) + " contained key \\"two\\"")
}
def `should work on parallel form` {
mutable.Map("one" -> 1, "two" -> 2).par should contain key ("two")
}
}
object `on scala.collection.Map` {
val map: scala.collection.Map[String, Int] = Map("one" -> 1, "two" -> 2)
def `should do nothing if map contains specified key` {
map should contain key ("two")
map should (contain key ("two"))
}
def `should do nothing if map does not contain the specified key and used with not` {
map should not { contain key ("three") }
map should not contain key ("three")
map should (not contain key ("three"))
}
def `should do nothing when map contains specified key and used in a logical-and expression` {
map should { contain key ("two") and (contain key ("one")) }
map should ((contain key ("two")) and (contain key ("one")))
map should (contain key ("two") and contain key ("one"))
}
def `should do nothing when map contains specified key and used in a logical-or expression` {
map should { contain key ("cat") or (contain key ("one")) }
map should ((contain key ("cat")) or (contain key ("one")))
map should (contain key ("cat") or contain key ("one"))
}
def `should do nothing when map does not contain the specified key and used in a logical-and expression with not` {
map should { not { contain key ("five") } and not { contain key ("three") }}
map should ((not contain key ("five")) and (not contain key ("three")))
map should (not contain key ("five") and not contain key ("three"))
}
def `should do nothing when map does not contain the specified key and used in a logical-or expression with not` {
map should { not { contain key ("two") } or not { contain key ("three") }}
map should ((not contain key ("two")) or (not contain key ("three")))
map should (not contain key ("two") or not contain key ("three"))
}
def `should throw TestFailedException if map does not contain the specified key` {
val caught1 = intercept[TestFailedException] {
map should contain key ("three")
}
assert(caught1.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"three\\"")
}
def `should throw TestFailedException if contains the specified key when used with not` {
val caught1 = intercept[TestFailedException] {
map should (not contain key ("two"))
}
assert(caught1.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
val caught2 = intercept[TestFailedException] {
map should not (contain key ("two"))
}
assert(caught2.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
val caught3 = intercept[TestFailedException] {
map should not contain key ("two")
}
assert(caught3.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
}
def `should throw an TestFailedException when map doesn't contain specified key and used in a logical-and expression` {
val caught1 = intercept[TestFailedException] {
map should { contain key ("five") and (contain key ("two")) }
}
assert(caught1.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"five\\"")
val caught2 = intercept[TestFailedException] {
map should ((contain key ("five")) and (contain key ("two")))
}
assert(caught2.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"five\\"")
val caught3 = intercept[TestFailedException] {
map should (contain key ("five") and contain key ("two"))
}
assert(caught3.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"five\\"")
}
def `should throw an TestFailedException when map doesn't contain specified key and used in a logical-or expression` {
val caught1 = intercept[TestFailedException] {
map should { contain key ("fifty five") or (contain key ("twenty two")) }
}
assert(caught1.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"fifty five\\", and Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"twenty two\\"")
val caught2 = intercept[TestFailedException] {
map should ((contain key ("fifty five")) or (contain key ("twenty two")))
}
assert(caught2.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"fifty five\\", and Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"twenty two\\"")
val caught3 = intercept[TestFailedException] {
map should (contain key ("fifty five") or contain key ("twenty two"))
}
assert(caught3.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"fifty five\\", and Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"twenty two\\"")
}
def `should throw an TestFailedException when map contains specified key and used in a logical-and expression with not` {
val caught1 = intercept[TestFailedException] {
map should { not { contain key ("three") } and not { contain key ("two") }}
}
assert(caught1.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"three\\", but Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
val caught2 = intercept[TestFailedException] {
map should ((not contain key ("three")) and (not contain key ("two")))
}
assert(caught2.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"three\\", but Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
val caught3 = intercept[TestFailedException] {
map should (not contain key ("three") and not contain key ("two"))
}
assert(caught3.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) did not contain key \\"three\\", but Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
}
def `should throw an TestFailedException when map contains specified key and used in a logical-or expression with not` {
val caught1 = intercept[TestFailedException] {
map should { not { contain key ("two") } or not { contain key ("two") }}
}
assert(caught1.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\", and Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
val caught2 = intercept[TestFailedException] {
map should ((not contain key ("two")) or (not contain key ("two")))
}
assert(caught2.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\", and Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
val caught3 = intercept[TestFailedException] {
map should (not contain key ("two") or not contain key ("two"))
}
assert(caught3.getMessage === "Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\", and Map(\\"one\\" -> 1, \\"two\\" -> 2) contained key \\"two\\"")
}
def `should work on parallel form` {
map.par should contain key ("two")
}
}
object `on scala.collection.immutable.HashMap` {
import scala.collection.immutable.HashMap
def `should do nothing if map contains specified key` {
HashMap("one" -> 1, "two" -> 2) should contain key ("two")
HashMap("one" -> 1, "two" -> 2) should (contain key ("two"))
HashMap(1 -> "one", 2 -> "two") should contain key (2)
}
def `should do nothing if map does not contain the specified key and used with not` {
HashMap("one" -> 1, "two" -> 2) should not { contain key ("three") }
HashMap("one" -> 1, "two" -> 2) should not contain key ("three")
HashMap("one" -> 1, "two" -> 2) should (not contain key ("three"))
}
def `should do nothing when map contains specified key and used in a logical-and expression` {
HashMap("one" -> 1, "two" -> 2) should { contain key ("two") and (contain key ("one")) }
HashMap("one" -> 1, "two" -> 2) should ((contain key ("two")) and (contain key ("one")))
HashMap("one" -> 1, "two" -> 2) should (contain key ("two") and contain key ("one"))
}
def `should do nothing when map contains specified key and used in a logical-or expression` {
HashMap("one" -> 1, "two" -> 2) should { contain key ("cat") or (contain key ("one")) }
HashMap("one" -> 1, "two" -> 2) should ((contain key ("cat")) or (contain key ("one")))
HashMap("one" -> 1, "two" -> 2) should (contain key ("cat") or contain key ("one"))
}
def `should do nothing when map does not contain the specified key and used in a logical-and expression with not` {
HashMap("one" -> 1, "two" -> 2) should { not { contain key ("five") } and not { contain key ("three") }}
HashMap("one" -> 1, "two" -> 2) should ((not contain key ("five")) and (not contain key ("three")))
HashMap("one" -> 1, "two" -> 2) should (not contain key ("five") and not contain key ("three"))
}
def `should do nothing when map does not contain the specified key and used in a logical-or expression with not` {
HashMap("one" -> 1, "two" -> 2) should { not { contain key ("two") } or not { contain key ("three") }}
HashMap("one" -> 1, "two" -> 2) should ((not contain key ("two")) or (not contain key ("three")))
HashMap("one" -> 1, "two" -> 2) should (not contain key ("two") or not contain key ("three"))
}
def `should throw TestFailedException if map does not contain the specified key` {
val caught1 = intercept[TestFailedException] {
HashMap("one" -> 1, "two" -> 2) should contain key ("three")
}
//assert(caught1.getMessage === "Map(one -> 1, two -> 2) did not contain key \\"three\\"")
caught1.getMessage should fullyMatch regex ("Map(.*) did not contain key \\"three\\"")
}
def `should throw TestFailedException if contains the specified key when used with not` {
val caught1 = intercept[TestFailedException] {
HashMap("one" -> 1, "two" -> 2) should (not contain key ("two"))
}
//assert(caught1.getMessage === "Map(one -> 1, two -> 2) contained key \\"two\\"")
caught1.getMessage should fullyMatch regex ("Map(.*) contained key \\"two\\"")
val caught2 = intercept[TestFailedException] {
HashMap("one" -> 1, "two" -> 2) should not (contain key ("two"))
}
//assert(caught2.getMessage === "Map(one -> 1, two -> 2) contained key \\"two\\"")
caught1.getMessage should fullyMatch regex ("Map(.*) contained key \\"two\\"")
val caught3 = intercept[TestFailedException] {
HashMap("one" -> 1, "two" -> 2) should not contain key ("two")
}
//assert(caught3.getMessage === "Map(one -> 1, two -> 2) contained key \\"two\\"")
caught1.getMessage should fullyMatch regex ("Map(.*) contained key \\"two\\"")
}
def `should throw an TestFailedException when map doesn't contain specified key and used in a logical-and expression` {
val caught1 = intercept[TestFailedException] {
HashMap("one" -> 1, "two" -> 2) should { contain key ("five") and (contain key ("two")) }
}
//assert(caught1.getMessage === "Map(one -> 1, two -> 2) did not contain key \\"five\\"")
caught1.getMessage should fullyMatch regex ("Map(.*) did not contain key \\"five\\"")
val caught2 = intercept[TestFailedException] {
HashMap("one" -> 1, "two" -> 2) should ((contain key ("five")) and (contain key ("two")))
}
//assert(caught2.getMessage === "Map(one -> 1, two -> 2) did not contain key \\"five\\"")
caught1.getMessage should fullyMatch regex ("Map(.*) did not contain key \\"five\\"")
val caught3 = intercept[TestFailedException] {
HashMap("one" -> 1, "two" -> 2) should (contain key ("five") and contain key ("two"))
}
//assert(caught3.getMessage === "Map(one -> 1, two -> 2) did not contain key \\"five\\"")
caught1.getMessage should fullyMatch regex ("Map(.*) did not contain key \\"five\\"")
}
def `should throw an TestFailedException when map doesn't contain specified key and used in a logical-or expression` {
val caught1 = intercept[TestFailedException] {
HashMap("one" -> 1, "two" -> 2) should { contain key ("fifty five") or (contain key ("twenty two")) }
}
//assert(caught1.getMessage === "Map(one -> 1, two -> 2) did not contain key \\"fifty five\\", and Map(one -> 1, two -> 2) did not contain key \\"twenty two\\"")
caught1.getMessage should fullyMatch regex ("Map(.*) did not contain key \\"fifty five\\", and Map(.*) did not contain key \\"twenty two\\"")
val caught2 = intercept[TestFailedException] {
HashMap("one" -> 1, "two" -> 2) should ((contain key ("fifty five")) or (contain key ("twenty two")))
}
//assert(caught2.getMessage === "Map(one -> 1, two -> 2) did not contain key \\"fifty five\\", and Map(one -> 1, two -> 2) did not contain key \\"twenty two\\"")
caught1.getMessage should fullyMatch regex ("Map(.*) did not contain key \\"fifty five\\", and Map(.*) did not contain key \\"twenty two\\"")
val caught3 = intercept[TestFailedException] {
HashMap("one" -> 1, "two" -> 2) should (contain key ("fifty five") or contain key ("twenty two"))
}
// assert(caught3.getMessage === "Map(one -> 1, two -> 2) did not contain key \\"fifty five\\", and Map(one -> 1, two -> 2) did not contain key \\"twenty two\\"")
caught1.getMessage should fullyMatch regex ("Map(.*) did not contain key \\"fifty five\\", and Map(.*) did not contain key \\"twenty two\\"")
}
def `should throw an TestFailedException when map contains specified key and used in a logical-and expression with not` {
val caught1 = intercept[TestFailedException] {
HashMap("one" -> 1, "two" -> 2) should { not { contain key ("three") } and not { contain key ("two") }}
}
//assert(caught1.getMessage === "Map(one -> 1, two -> 2) did not contain key \\"three\\", but Map(one -> 1, two -> 2) contained key \\"two\\"")
caught1.getMessage should fullyMatch regex ("Map(.*) did not contain key \\"three\\", but Map(.*) contained key \\"two\\"")
val caught2 = intercept[TestFailedException] {
HashMap("one" -> 1, "two" -> 2) should ((not contain key ("three")) and (not contain key ("two")))
}
//assert(caught2.getMessage === "Map(one -> 1, two -> 2) did not contain key \\"three\\", but Map(one -> 1, two -> 2) contained key \\"two\\"")
caught1.getMessage should fullyMatch regex ("Map(.*) did not contain key \\"three\\", but Map(.*) contained key \\"two\\"")
val caught3 = intercept[TestFailedException] {
HashMap("one" -> 1, "two" -> 2) should (not contain key ("three") and not contain key ("two"))
}
//assert(caught3.getMessage === "Map(one -> 1, two -> 2) did not contain key \\"three\\", but Map(one -> 1, two -> 2) contained key \\"two\\"")
caught1.getMessage should fullyMatch regex ("Map(.*) did not contain key \\"three\\", but Map(.*) contained key \\"two\\"")
}
def `should throw an TestFailedException when map contains specified key and used in a logical-or expression with not` {
val caught1 = intercept[TestFailedException] {
HashMap("one" -> 1, "two" -> 2) should { not { contain key ("two") } or not { contain key ("two") }}
}
//assert(caught1.getMessage === "Map(one -> 1, two -> 2) contained key \\"two\\", and Map(one -> 1, two -> 2) contained key \\"two\\"")
caught1.getMessage should fullyMatch regex ("Map(.*) contained key \\"two\\", and Map(.*) contained key \\"two\\"")
val caught2 = intercept[TestFailedException] {
HashMap("one" -> 1, "two" -> 2) should ((not contain key ("two")) or (not contain key ("two")))
}
//assert(caught2.getMessage === "Map(one -> 1, two -> 2) contained key \\"two\\", and Map(one -> 1, two -> 2) contained key \\"two\\"")
caught1.getMessage should fullyMatch regex ("Map(.*) contained key \\"two\\", and Map(.*) contained key \\"two\\"")
val caught3 = intercept[TestFailedException] {
HashMap("one" -> 1, "two" -> 2) should (not contain key ("two") or not contain key ("two"))
}
//assert(caught3.getMessage === "Map(one -> 1, two -> 2) contained key \\"two\\", and Map(one -> 1, two -> 2) contained key \\"two\\"")
caught1.getMessage should fullyMatch regex ("Map(.*) contained key \\"two\\", and Map(.*) contained key \\"two\\"")
}
def `should work on parallel form` {
HashMap("one" -> 1, "two" -> 2).par should contain key ("two")
}
}
object `on scala.collection.mutable.HashMap` {
import scala.collection.mutable
def `should do nothing if map contains specified key` {
mutable.HashMap("one" -> 1, "two" -> 2) should contain key ("two")
mutable.HashMap("one" -> 1, "two" -> 2) should (contain key ("two"))
mutable.HashMap(1 -> "one", 2 -> "two") should contain key (2)
}
def `should do nothing if map does not contain the specified key and used with not` {
mutable.HashMap("one" -> 1, "two" -> 2) should not { contain key ("three") }
mutable.HashMap("one" -> 1, "two" -> 2) should not contain key ("three")
mutable.HashMap("one" -> 1, "two" -> 2) should (not contain key ("three"))
}
def `should do nothing when map contains specified key and used in a logical-and expression` {
mutable.HashMap("one" -> 1, "two" -> 2) should { contain key ("two") and (contain key ("one")) }
mutable.HashMap("one" -> 1, "two" -> 2) should ((contain key ("two")) and (contain key ("one")))
mutable.HashMap("one" -> 1, "two" -> 2) should (contain key ("two") and contain key ("one"))
}
def `should do nothing when map contains specified key and used in a logical-or expression` {
mutable.HashMap("one" -> 1, "two" -> 2) should { contain key ("cat") or (contain key ("one")) }
mutable.HashMap("one" -> 1, "two" -> 2) should ((contain key ("cat")) or (contain key ("one")))
mutable.HashMap("one" -> 1, "two" -> 2) should (contain key ("cat") or contain key ("one"))
}
def `should do nothing when map does not contain the specified key and used in a logical-and expression with not` {
mutable.HashMap("one" -> 1, "two" -> 2) should { not { contain key ("five") } and not { contain key ("three") }}
mutable.HashMap("one" -> 1, "two" -> 2) should ((not contain key ("five")) and (not contain key ("three")))
mutable.HashMap("one" -> 1, "two" -> 2) should (not contain key ("five") and not contain key ("three"))
}
def `should do nothing when map does not contain the specified key and used in a logical-or expression with not` {
mutable.HashMap("one" -> 1, "two" -> 2) should { not { contain key ("two") } or not { contain key ("three") }}
mutable.HashMap("one" -> 1, "two" -> 2) should ((not contain key ("two")) or (not contain key ("three")))
mutable.HashMap("one" -> 1, "two" -> 2) should (not contain key ("two") or not contain key ("three"))
}
def `should throw TestFailedException if map does not contain the specified key` {
val map = mutable.HashMap("one" -> 1, "two" -> 2)
val caught1 = intercept[TestFailedException] {
map should contain key ("three")
}
assert(caught1.getMessage === decorateToStringValue(map) + " did not contain key \\"three\\"")
}
def `should throw TestFailedException if contains the specified key when used with not` {
val map1 = mutable.HashMap("one" -> 1, "two" -> 2)
val caught1 = intercept[TestFailedException] {
map1 should (not contain key ("two"))
}
assert(caught1.getMessage === decorateToStringValue(map1) + " contained key \\"two\\"")
val map2 = mutable.HashMap("one" -> 1, "two" -> 2)
val caught2 = intercept[TestFailedException] {
map2 should not (contain key ("two"))
}
assert(caught2.getMessage === decorateToStringValue(map2) + " contained key \\"two\\"")
val map3 = mutable.HashMap("one" -> 1, "two" -> 2)
val caught3 = intercept[TestFailedException] {
map3 should not contain key ("two")
}
assert(caught3.getMessage === decorateToStringValue(map3) + " contained key \\"two\\"")
}
def `should throw an TestFailedException when map doesn't contain specified key and used in a logical-and expression` {
val map1 = mutable.HashMap("one" -> 1, "two" -> 2)
val caught1 = intercept[TestFailedException] {
map1 should { contain key ("five") and (contain key ("two")) }
}
assert(caught1.getMessage === decorateToStringValue(map1) + " did not contain key \\"five\\"")
val map2 = mutable.HashMap("one" -> 1, "two" -> 2)
val caught2 = intercept[TestFailedException] {
map2 should ((contain key ("five")) and (contain key ("two")))
}
assert(caught2.getMessage === decorateToStringValue(map2) + " did not contain key \\"five\\"")
val map3 = mutable.HashMap("one" -> 1, "two" -> 2)
val caught3 = intercept[TestFailedException] {
map3 should (contain key ("five") and contain key ("two"))
}
assert(caught3.getMessage === decorateToStringValue(map3) + " did not contain key \\"five\\"")
}
def `should throw an TestFailedException when map doesn't contain specified key and used in a logical-or expression` {
val map1 = mutable.HashMap("one" -> 1, "two" -> 2)
val caught1 = intercept[TestFailedException] {
map1 should { contain key ("fifty five") or (contain key ("twenty two")) }
}
assert(caught1.getMessage === decorateToStringValue(map1) + " did not contain key \\"fifty five\\", and " + decorateToStringValue(map1) + " did not contain key \\"twenty two\\"")
val map2 = mutable.HashMap("one" -> 1, "two" -> 2)
val caught2 = intercept[TestFailedException] {
map2 should ((contain key ("fifty five")) or (contain key ("twenty two")))
}
assert(caught2.getMessage === decorateToStringValue(map2) + " did not contain key \\"fifty five\\", and " + decorateToStringValue(map2) + " did not contain key \\"twenty two\\"")
val map3 = mutable.HashMap("one" -> 1, "two" -> 2)
val caught3 = intercept[TestFailedException] {
map3 should (contain key ("fifty five") or contain key ("twenty two"))
}
assert(caught3.getMessage === decorateToStringValue(map3) + " did not contain key \\"fifty five\\", and " + decorateToStringValue(map3) + " did not contain key \\"twenty two\\"")
}
def `should throw an TestFailedException when map contains specified key and used in a logical-and expression with not` {
val map1 = mutable.HashMap("one" -> 1, "two" -> 2)
val caught1 = intercept[TestFailedException] {
map1 should { not { contain key ("three") } and not { contain key ("two") }}
}
assert(caught1.getMessage === decorateToStringValue(map1) + " did not contain key \\"three\\", but " + decorateToStringValue(map1) + " contained key \\"two\\"")
val map2 = mutable.HashMap("one" -> 1, "two" -> 2)
val caught2 = intercept[TestFailedException] {
map2 should ((not contain key ("three")) and (not contain key ("two")))
}
assert(caught2.getMessage === decorateToStringValue(map2) + " did not contain key \\"three\\", but " + decorateToStringValue(map2) + " contained key \\"two\\"")
val map3 = mutable.HashMap("one" -> 1, "two" -> 2)
val caught3 = intercept[TestFailedException] {
map3 should (not contain key ("three") and not contain key ("two"))
}
assert(caught3.getMessage === decorateToStringValue(map3) + " did not contain key \\"three\\", but " + decorateToStringValue(map3) + " contained key \\"two\\"")
}
def `should throw an TestFailedException when map contains specified key and used in a logical-or expression with not` {
val map1 = mutable.HashMap("one" -> 1, "two" -> 2)
val caught1 = intercept[TestFailedException] {
map1 should { not { contain key ("two") } or not { contain key ("two") }}
}
assert(caught1.getMessage === decorateToStringValue(map1) + " contained key \\"two\\", and " + decorateToStringValue(map1) + " contained key \\"two\\"")
val map2 = mutable.HashMap("one" -> 1, "two" -> 2)
val caught2 = intercept[TestFailedException] {
map2 should ((not contain key ("two")) or (not contain key ("two")))
}
assert(caught2.getMessage === decorateToStringValue(map2) + " contained key \\"two\\", and " + decorateToStringValue(map2) + " contained key \\"two\\"")
val map3 = mutable.HashMap("one" -> 1, "two" -> 2)
val caught3 = intercept[TestFailedException] {(
map3 should (not contain key ("two") or not contain key ("two")))
}
assert(caught3.getMessage === decorateToStringValue(map3) + " contained key \\"two\\", and " + decorateToStringValue(map3) + " contained key \\"two\\"")
}
def `should work on parallel form` {
mutable.HashMap("one" -> 1, "two" -> 2).par should contain key ("two")
}
}
object `on java.util.Map` {
val javaMap: java.util.Map[String, Int] = new java.util.HashMap
javaMap.put("one",1)
javaMap.put("two", 2)
def `should do nothing if map contains specified key` {
javaMap should contain key ("two")
javaMap should (contain key ("two"))
}
def `should do nothing if map does not contain the specified key and used with not` {
javaMap should not { contain key ("three") }
javaMap should not contain key ("three")
javaMap should (not contain key ("three"))
}
def `should do nothing when map contains specified key and used in a logical-and expression` {
javaMap should { contain key ("two") and (contain key ("one")) }
javaMap should ((contain key ("two")) and (contain key ("one")))
javaMap should (contain key ("two") and contain key ("one"))
}
def `should do nothing when map contains specified key and used in a logical-or expression` {
javaMap should { contain key ("cat") or (contain key ("one")) }
javaMap should ((contain key ("cat")) or (contain key ("one")))
javaMap should (contain key ("cat") or contain key ("one"))
}
def `should do nothing when map does not contain the specified key and used in a logical-and expression with not` {
javaMap should { not { contain key ("five") } and not { contain key ("three") }}
javaMap should ((not contain key ("five")) and (not contain key ("three")))
javaMap should (not contain key ("five") and not contain key ("three"))
}
def `should do nothing when map does not contain the specified key and used in a logical-or expression with not` {
javaMap should { not { contain key ("two") } or not { contain key ("three") }}
javaMap should ((not contain key ("two")) or (not contain key ("three")))
javaMap should (not contain key ("two") or not contain key ("three"))
}
def `should throw TestFailedException if map does not contain the specified key` {
val caught1 = intercept[TestFailedException] {
javaMap should contain key ("three")
}
caught1.getMessage should (be === "{\\"one\\"=1, \\"two\\"=2} did not contain key \\"three\\"" or
be === "{\\"two\\"=2, \\"one\\"=1} did not contain key \\"three\\"")
}
def `should throw TestFailedException if contains the specified key when used with not` {
val caught1 = intercept[TestFailedException] {
javaMap should (not contain key ("two"))
}
caught1.getMessage should (be === "{\\"one\\"=1, \\"two\\"=2} contained key \\"two\\"" or
be === "{\\"two\\"=2, \\"one\\"=1} contained key \\"two\\"")
val caught2 = intercept[TestFailedException] {
javaMap should not (contain key ("two"))
}
caught2.getMessage should (be === "{\\"one\\"=1, \\"two\\"=2} contained key \\"two\\"" or
be === "{\\"two\\"=2, \\"one\\"=1} contained key \\"two\\"")
val caught3 = intercept[TestFailedException] {
javaMap should not contain key ("two")
}
caught3.getMessage should (be === "{\\"one\\"=1, \\"two\\"=2} contained key \\"two\\"" or
be === "{\\"two\\"=2, \\"one\\"=1} contained key \\"two\\"")
}
def `should throw an TestFailedException when map doesn't contain specified key and used in a logical-and expression` {
val caught1 = intercept[TestFailedException] {
javaMap should { contain key ("five") and (contain key ("two")) }
}
caught1.getMessage should (be === "{\\"one\\"=1, \\"two\\"=2} did not contain key \\"five\\"" or
be === "{\\"two\\"=2, \\"one\\"=1} did not contain key \\"five\\"")
val caught2 = intercept[TestFailedException] {
javaMap should ((contain key ("five")) and (contain key ("two")))
}
caught2.getMessage should (be === "{\\"one\\"=1, \\"two\\"=2} did not contain key \\"five\\"" or
be === "{\\"two\\"=2, \\"one\\"=1} did not contain key \\"five\\"")
val caught3 = intercept[TestFailedException] {
javaMap should (contain key ("five") and contain key ("two"))
}
caught3.getMessage should (be === "{\\"one\\"=1, \\"two\\"=2} did not contain key \\"five\\"" or
be === "{\\"two\\"=2, \\"one\\"=1} did not contain key \\"five\\"")
}
def `should throw an TestFailedException when map doesn't contain specified key and used in a logical-or expression` {
val caught1 = intercept[TestFailedException] {
javaMap should { contain key ("fifty five") or (contain key ("twenty two")) }
}
caught1.getMessage should (be === "{\\"one\\"=1, \\"two\\"=2} did not contain key \\"fifty five\\", and {\\"one\\"=1, \\"two\\"=2} did not contain key \\"twenty two\\"" or
be === "{\\"two\\"=2, \\"one\\"=1} did not contain key \\"fifty five\\", and {\\"two\\"=2, \\"one\\"=1} did not contain key \\"twenty two\\"")
val caught2 = intercept[TestFailedException] {
javaMap should ((contain key ("fifty five")) or (contain key ("twenty two")))
}
caught2.getMessage should (be === "{\\"one\\"=1, \\"two\\"=2} did not contain key \\"fifty five\\", and {\\"one\\"=1, \\"two\\"=2} did not contain key \\"twenty two\\"" or
be === "{\\"two\\"=2, \\"one\\"=1} did not contain key \\"fifty five\\", and {\\"two\\"=2, \\"one\\"=1} did not contain key \\"twenty two\\"")
val caught3 = intercept[TestFailedException] {
javaMap should (contain key ("fifty five") or contain key ("twenty two"))
}
caught3.getMessage should (be === "{\\"one\\"=1, \\"two\\"=2} did not contain key \\"fifty five\\", and {\\"one\\"=1, \\"two\\"=2} did not contain key \\"twenty two\\"" or
be === "{\\"two\\"=2, \\"one\\"=1} did not contain key \\"fifty five\\", and {\\"two\\"=2, \\"one\\"=1} did not contain key \\"twenty two\\"")
}
def `should throw an TestFailedException when map contains specified key and used in a logical-and expression with not` {
val caught1 = intercept[TestFailedException] {
javaMap should { not { contain key ("three") } and not { contain key ("two") }}
}
caught1.getMessage should (be === "{\\"one\\"=1, \\"two\\"=2} did not contain key \\"three\\", but {\\"one\\"=1, \\"two\\"=2} contained key \\"two\\"" or
be === "{\\"two\\"=2, \\"one\\"=1} did not contain key \\"three\\", but {\\"two\\"=2, \\"one\\"=1} contained key \\"two\\"")
val caught2 = intercept[TestFailedException] {
javaMap should ((not contain key ("three")) and (not contain key ("two")))
}
caught2.getMessage should (be === "{\\"one\\"=1, \\"two\\"=2} did not contain key \\"three\\", but {\\"one\\"=1, \\"two\\"=2} contained key \\"two\\"" or
be === "{\\"two\\"=2, \\"one\\"=1} did not contain key \\"three\\", but {\\"two\\"=2, \\"one\\"=1} contained key \\"two\\"")
val caught3 = intercept[TestFailedException] {
javaMap should (not contain key ("three") and not contain key ("two"))
}
caught3.getMessage should (be === "{\\"one\\"=1, \\"two\\"=2} did not contain key \\"three\\", but {\\"one\\"=1, \\"two\\"=2} contained key \\"two\\"" or
be === "{\\"two\\"=2, \\"one\\"=1} did not contain key \\"three\\", but {\\"two\\"=2, \\"one\\"=1} contained key \\"two\\"")
}
def `should throw an TestFailedException when map contains specified key and used in a logical-or expression with not` {
val caught1 = intercept[TestFailedException] {
javaMap should { not { contain key ("two") } or not { contain key ("two") }}
}
caught1.getMessage should (be === "{\\"one\\"=1, \\"two\\"=2} contained key \\"two\\", and {\\"one\\"=1, \\"two\\"=2} contained key \\"two\\"" or
be === "{\\"two\\"=2, \\"one\\"=1} contained key \\"two\\", and {\\"two\\"=2, \\"one\\"=1} contained key \\"two\\"")
val caught2 = intercept[TestFailedException] {
javaMap should ((not contain key ("two")) or (not contain key ("two")))
}
caught2.getMessage should (be === "{\\"one\\"=1, \\"two\\"=2} contained key \\"two\\", and {\\"one\\"=1, \\"two\\"=2} contained key \\"two\\"" or
be === "{\\"two\\"=2, \\"one\\"=1} contained key \\"two\\", and {\\"two\\"=2, \\"one\\"=1} contained key \\"two\\"")
val caught3 = intercept[TestFailedException] {
javaMap should (not contain key ("two") or not contain key ("two"))
}
caught3.getMessage should (be === "{\\"one\\"=1, \\"two\\"=2} contained key \\"two\\", and {\\"one\\"=1, \\"two\\"=2} contained key \\"two\\"" or
be === "{\\"two\\"=2, \\"one\\"=1} contained key \\"two\\", and {\\"two\\"=2, \\"one\\"=1} contained key \\"two\\"")
}
}
}
}
|
travisbrown/scalatest
|
src/test/scala/org/scalatest/matchers/ShouldContainKeySpec.scala
|
Scala
|
apache-2.0
| 51,845 |
package com.pfalabs.tiny.features
trait FeatureProvider {
def getFeature(name: String): Feature;
}
|
stillalex/tiny
|
features/src/main/scala/com/pfalabs/tiny/features/FeatureProvider.scala
|
Scala
|
apache-2.0
| 103 |
/*
* Copyright (c) 2011-15 Miles Sabin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package shapeless
import org.junit.Test
import org.junit.Assert._
import shapeless.test.illTyped
class NatTests {
import nat._
import ops.nat._
trait Check[N <: Nat]
def check(expected: Nat)(actually : => Check[expected.N]) {}
@Test
def testNat {
implicitly[Succ[_1] =:= _2]
implicitly[Pred.Aux[_19, _18]]
def pred(n: Nat)(implicit pred : Pred[n.N]) = new Check[pred.Out] {}
val pd1 = pred(19)
check(18)(pd1)
implicitly[Sum.Aux[_2, _3, _5]]
def sum(a: Nat, b: Nat)(implicit sum : Sum[a.N, b.N]) = new Check[sum.Out] {}
val s1 = sum(2, 3)
check(5)(s1)
implicitly[Diff.Aux[_5, _1, _4]]
def diff(a: Nat, b: Nat)(implicit diff : Diff[a.N, b.N]) = new Check[diff.Out] {}
val diff1 = diff(5, 1)
check(4)(diff1)
implicitly[Prod.Aux[_2, _3, _6]]
implicitly[Prod.Aux[_4, _5, _20]]
def prod(a: Nat, b: Nat)(implicit prod : Prod[a.N, b.N]) = new Check[prod.Out] {}
val p1 = prod(2, 3)
check(6)(p1)
val p2 = prod(4, 5)
check(20)(p2)
implicitly[Div.Aux[_7, _2, _3]]
implicitly[Div.Aux[_22, _11, _2]]
implicitly[Div.Aux[_15, _3, _5]]
def div(a: Nat, b: Nat)(implicit div : Div[a.N, b.N]) = new Check[div.Out] {}
val d1 = div(7, 2)
check(3)(d1)
val d2 = div(22, 11)
check(2)(d2)
val d3 = div(15, 3)
check(5)(d3)
implicitly[Mod.Aux[_7, _2, _1]]
implicitly[Mod.Aux[_22, _5, _2]]
implicitly[Mod.Aux[_9, _3, _0]]
def mod(a: Nat, b: Nat)(implicit mod : Mod[a.N, b.N]) = new Check[mod.Out] {}
val m1 = mod(7, 2)
check(1)(m1)
val m2 = mod(22, 5)
check(2)(m2)
val m3 = mod(9, 3)
check(0)(m3)
implicitly[LT[_3, _5]]
implicitly[LT[_10, _15]]
implicitly[LTEq[_2, _2]]
implicitly[LTEq[_2, _3]]
illTyped(""" implicitly[LT[_5, _5]] """)
illTyped(""" implicitly[LTEq[_6, _5]] """)
def relativeToN_LT[N <: Nat]: Unit = {
implicitly[LT[_0, Succ[N]]]
implicitly[LT[N, Succ[N]]]
implicitly[LTEq[_0, N]]
implicitly[LTEq[N, N]]
implicitly[LTEq[N, Succ[N]]]
illTyped(""" implicitly[LT[_0, N]] """)
illTyped(""" implicitly[LT[N, N]] """)
illTyped(""" implicitly[LTEq[_1, N]] """)
illTyped(""" implicitly[LTEq[Succ[N], N]] """)
}
implicitly[GT[_5, _3]]
implicitly[GT[_15, _10]]
implicitly[GTEq[_2, _2]]
implicitly[GTEq[_3, _2]]
illTyped(""" implicitly[GT[_5, _5]] """)
illTyped(""" implicitly[GTEq[_5, _6]] """)
def relativeToN_GT[N <: Nat]: Unit = {
implicitly[GT[Succ[N], _0]]
implicitly[GT[Succ[N], N]]
implicitly[GTEq[N, _0]]
implicitly[GTEq[N, N]]
implicitly[GTEq[Succ[N], N]]
illTyped(""" implicitly[GT[N, _0]] """)
illTyped(""" implicitly[GT[N, N]] """)
illTyped(""" implicitly[GTEq[N, _1]] """)
illTyped(""" implicitly[GTEq[N, Succ[N]]] """)
}
implicitly[Min.Aux[_0, _0, _0]]
implicitly[Min.Aux[_5, _2, _2]]
implicitly[Min.Aux[_3, _8, _3]]
def min[A <: Nat, B <: Nat](implicit min : Min[A, B]) = new Check[min.Out] {}
val min1 = min[_3, _4]
check(3)(min1)
val min2 = min[_5, _4]
check(4)(min2)
implicitly[Max.Aux[_0, _0, _0]]
implicitly[Max.Aux[_5, _2, _5]]
implicitly[Max.Aux[_3, _8, _8]]
def max[A <: Nat, B <: Nat](implicit max : Max[A, B]) = new Check[max.Out] {}
val max1 = max[_3, _4]
check(4)(max1)
val max2 = max[_5, _4]
check(5)(max2)
implicitly[Pow.Aux[_0, _8, _1]]
implicitly[Pow.Aux[_9, _0, _0]]
implicitly[Pow.Aux[_3, _2, _8]]
def pow[A <: Nat, B <: Nat](implicit pow : Pow[A, B]) = new Check[pow.Out] {}
val e1 = pow[_3, _1]
check(1)(e1)
val e2 = pow[_2, _3]
check(9)(e2)
val e3 = pow[_2, _4]
check(16)(e3)
implicitly[Range.Aux[_0,_0, HNil]]
implicitly[Range.Aux[_0,_2, _0::_1::HNil]]
implicitly[Range.Aux[_1,_1, HNil]]
implicitly[Range.Aux[_1,_2,_1::HNil]]
implicitly[Range.Aux[_1,_4, _1::_2::_3::HNil]]
val r1 = the[Range[_0,_0]]
val r2 = the[Range[_0,_1]]
val r3 = the[Range[_1,_1]]
val r4 = the[Range[_1,_5]]
import shapeless.testutil._
assertTypedEquals[HNil](HNil, r1())
assertTypedEquals[_0::HNil](_0::HNil, r2())
assertTypedEquals[HNil](HNil, r3())
assertTypedEquals[_1::_2::_3::_4::HNil](_1::_2::_3::_4::HNil, r4())
// GCD tests
implicitly[GCD.Aux[_0, _0, _0]]
implicitly[GCD.Aux[_0, _1, _1]]
implicitly[GCD.Aux[_1, _0, _1]]
implicitly[GCD.Aux[_9, _6, _3]]
implicitly[GCD.Aux[_12, _6, _6]]
// LCM tests
implicitly[LCM.Aux[_0, _1, _0]]
implicitly[LCM.Aux[_1, _0, _0]]
implicitly[LCM.Aux[_2, _3, _6]]
implicitly[LCM.Aux[_4, _6, _12]]
// Type level
assertEquals(0, toInt[_0])
assertEquals(1, toInt[_1])
assertEquals(2, toInt[_2])
assertEquals(3, toInt[_3])
assertEquals(4, toInt[_4])
assertEquals(5, toInt[_5])
assertEquals(6, toInt[_6])
assertEquals(7, toInt[_7])
assertEquals(8, toInt[_8])
assertEquals(9, toInt[_9])
assertEquals(10, toInt[_10])
assertEquals(11, toInt[_11])
assertEquals(12, toInt[_12])
assertEquals(13, toInt[_13])
assertEquals(14, toInt[_14])
assertEquals(15, toInt[_15])
assertEquals(16, toInt[_16])
assertEquals(17, toInt[_17])
assertEquals(18, toInt[_18])
assertEquals(19, toInt[_19])
assertEquals(20, toInt[_20])
assertEquals(21, toInt[_21])
assertEquals(22, toInt[_22])
// Value level
assertEquals(0, toInt(_0))
assertEquals(1, toInt(_1))
assertEquals(2, toInt(_2))
assertEquals(3, toInt(_3))
assertEquals(4, toInt(_4))
assertEquals(5, toInt(_5))
assertEquals(6, toInt(_6))
assertEquals(7, toInt(_7))
assertEquals(8, toInt(_8))
assertEquals(9, toInt(_9))
assertEquals(10, toInt(_10))
assertEquals(11, toInt(_11))
assertEquals(12, toInt(_12))
assertEquals(13, toInt(_13))
assertEquals(14, toInt(_14))
assertEquals(15, toInt(_15))
assertEquals(16, toInt(_16))
assertEquals(17, toInt(_17))
assertEquals(18, toInt(_18))
assertEquals(19, toInt(_19))
assertEquals(20, toInt(_20))
assertEquals(21, toInt(_21))
assertEquals(22, toInt(_22))
// Value level, using syntax
assertEquals(0, _0.toInt)
assertEquals(1, _1.toInt)
assertEquals(2, _2.toInt)
assertEquals(3, _3.toInt)
assertEquals(4, _4.toInt)
assertEquals(5, _5.toInt)
assertEquals(6, _6.toInt)
assertEquals(7, _7.toInt)
assertEquals(8, _8.toInt)
assertEquals(9, _9.toInt)
assertEquals(10, _10.toInt)
assertEquals(11, _11.toInt)
assertEquals(12, _12.toInt)
assertEquals(13, _13.toInt)
assertEquals(14, _14.toInt)
assertEquals(15, _15.toInt)
assertEquals(16, _16.toInt)
assertEquals(17, _17.toInt)
assertEquals(18, _18.toInt)
assertEquals(19, _19.toInt)
assertEquals(20, _20.toInt)
assertEquals(21, _21.toInt)
assertEquals(22, _22.toInt)
}
}
|
liff/shapeless
|
core/src/test/scala/shapeless/nat.scala
|
Scala
|
apache-2.0
| 7,613 |
package routes
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.HttpCookie
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import com.github.scribejava.core.oauth.OAuth20Service
import com.google.inject.Inject
import com.google.inject.name.Named
import common.errors.AmbigousResult
import common.implicits.RichDBIO._
import common.implicits.RichFuture._
import model.User
import model.facebook.{FacebookAuth, FacebookOauth2Response}
import jwt.model.JwtContent
import jwt.service.JwtAuthService
import org.mindrot.jbcrypt.BCrypt
import repositories.UserRepository
import repositories.auth.FacebookAuthRepository
import services.ExternalApiService
import spray.json._
import scala.concurrent.ExecutionContext
import scala.util.{Failure, Success}
class FacebookAuthController @Inject()(
@Named("facebook") oauth2Service: OAuth20Service,
externalApiService: ExternalApiService,
userRepository: UserRepository,
facebookAuthRepository: FacebookAuthRepository,
jwtAuthService: JwtAuthService[JwtContent]
)(implicit val executionContext: ExecutionContext) {
val routes: Route =
(path("auth" / "facebook") & get) {
redirect(oauth2Service.getAuthorizationUrl, StatusCodes.Found)
} ~ (path("auth" / "facebook" / "callback") & get) {
parameters('state.?, 'code) {
(state, code) =>
onComplete {
for {
facebookAuthInfo <- externalApiService.getUserInfo[FacebookOauth2Response](
code,
"https://graph.facebook.com/me?fields=id,name,email",
oauth2Service
)
user <- facebookAuthRepository.findOne(facebookAuthInfo.id).run.flatMap {
case Some(fUser) =>
userRepository.findOne(fUser.userId).run failOnNone AmbigousResult(
s"User with id: ${fUser.userId} stored in facebook auth table, but not in the user table"
)
case None =>
for {
user <- userRepository
.save(
User(
username = facebookAuthInfo.name,
email = facebookAuthInfo.email,
password = BCrypt.hashpw(facebookAuthInfo.id, BCrypt.gensalt),
role = "user",
isActive = true
)
)
.run
_ <- facebookAuthRepository
.save(FacebookAuth(Some(facebookAuthInfo.id), facebookAuthInfo.name, user.id.get))
.run
} yield user
}
} yield jwtAuthService.createTokens(JwtContent(user.id.get), user.password)
} {
case Success(tokens) =>
setCookie(
HttpCookie("access-token", value = tokens.accessToken),
HttpCookie("refresh-token", value = tokens.refreshToken)
) {
state match {
case Some(redirectUrl) => redirect(s"$redirectUrl?data=${tokens.toJson.toString}", StatusCodes.Found)
case None => redirect("/profile", StatusCodes.Found)
}
}
case Failure(_) => redirect("/login", StatusCodes.Found)
}
}
}
}
|
sysgears/apollo-universal-starter-kit
|
modules/user/server-scala/src/main/scala/routes/FacebookAuthController.scala
|
Scala
|
mit
| 3,432 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.carbondata.view
import java.sql.Timestamp
import org.apache.carbondata.core.preagg.TimeSeriesUDF
object MVFunctions {
val DUMMY_FUNCTION = "mv"
val TIME_SERIES_FUNCTION = "timeseries"
}
case class TimeSeriesFunction() extends ((Timestamp, String) => Timestamp) with Serializable{
override def apply(v1: Timestamp, v2: String): Timestamp = {
TimeSeriesUDF.INSTANCE.applyUDF(v1, v2)
}
}
|
zzcclp/carbondata
|
integration/spark/src/main/scala/org/apache/carbondata/view/MVFunctions.scala
|
Scala
|
apache-2.0
| 1,226 |
package core
import akka.actor.{Props,Actor}
class TenantActor extends Actor {
import UserActor._
import messages.TenantMessages._
val userActor = context.actorOf(Props[UserActor])
def receive: Receive = {
case CreateTenant(tenent) =>
case UserCreated(tenant, user) =>
userActor ! user
case RoleGroupRegistered(group) =>
}
}
|
hsihealth/aim_prototype
|
src/main/scala/core/tenant_actor.scala
|
Scala
|
apache-2.0
| 357 |
/**
* Copyright (C) 2009 Orbeon, Inc.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version
* 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.webapp
import org.orbeon.oxf.pipeline.InitUtils.runWithServletContext
import javax.servlet.{ServletException, ServletContextEvent, ServletContextListener}
import org.orbeon.oxf.util.ScalaUtils._
// For backward compatibility
class OrbeonServletContextListenerDelegate extends OrbeonServletContextListener
/**
* This listener listens for HTTP context lifecycle changes.
*/
class OrbeonServletContextListener extends ServletContextListener {
private val InitProcessorPrefix = "oxf.context-initialized-processor."
private val InitInputPrefix = "oxf.context-initialized-processor.input."
private val DestroyProcessorPrefix = "oxf.context-destroyed-processor."
private val DestroyInputPrefix = "oxf.context-destroyed-processor.input."
private implicit val logger = ProcessorService.Logger
def logPrefix = "Context listener"
def initParameters = Map()
def contextInitialized(event: ServletContextEvent): Unit =
withRootException("context creation", new ServletException(_)) {
runWithServletContext(event.getServletContext, None, logger, logPrefix, "Context initialized.", InitProcessorPrefix, InitInputPrefix)
}
def contextDestroyed(event: ServletContextEvent): Unit =
withRootException("context destruction", new ServletException(_)) {
runWithServletContext(event.getServletContext, None, logger, logPrefix, "Context destroyed.", DestroyProcessorPrefix, DestroyInputPrefix)
// NOTE: This calls all listeners, because the listeners are stored in the actual web app context's attributes
WebAppContext(event.getServletContext).webAppDestroyed()
}
}
|
martinluther/orbeon-forms
|
src/main/scala/org/orbeon/oxf/webapp/OrbeonServletContextListener.scala
|
Scala
|
lgpl-2.1
| 2,354 |
package actors
import actors.DrtStaticParameters.expireAfterMillis
import actors.PartitionedPortStateActor.GetFlights
import actors.daily.PassengersActor
import actors.persistent.AlertsActor
import actors.persistent.QueueLikeActor.UpdatedMillis
import actors.persistent.arrivals.CirriumLiveArrivalsActor
import actors.persistent.staffing._
import actors.routing.FlightsRouterActor
import actors.supervised.RestartOnStop
import akka.NotUsed
import akka.actor.{ActorRef, ActorSystem, Cancellable, Props, Scheduler}
import akka.pattern.ask
import akka.stream.scaladsl.{Sink, Source, SourceQueueWithComplete}
import akka.stream.{Materializer, OverflowStrategy, UniqueKillSwitch}
import akka.util.Timeout
import com.typesafe.config.ConfigFactory
import controllers.{Deskstats, PaxFlow, UserRoleProviderLike}
import drt.chroma.chromafetcher.ChromaFetcher.{ChromaForecastFlight, ChromaLiveFlight}
import drt.chroma.chromafetcher.{ChromaFetcher, ChromaFlightMarshallers}
import drt.chroma.{ChromaFeedType, ChromaLive}
import drt.http.ProdSendAndReceive
import drt.server.feeds.acl.AclFeed
import drt.server.feeds.bhx.{BHXClient, BHXFeed}
import drt.server.feeds.chroma.{ChromaForecastFeed, ChromaLiveFeed}
import drt.server.feeds.cirium.CiriumFeed
import drt.server.feeds.common.{ArrivalFeed, HttpClient}
import drt.server.feeds.gla.{GlaFeed, ProdGlaFeedRequester}
import drt.server.feeds.lcy.{LCYClient, LCYFeed}
import drt.server.feeds.legacy.bhx.{BHXForecastFeedLegacy, BHXLiveFeedLegacy}
import drt.server.feeds.lgw.{LGWAzureClient, LGWFeed}
import drt.server.feeds.lhr.LHRFlightFeed
import drt.server.feeds.lhr.sftp.LhrSftpLiveContentProvider
import drt.server.feeds.ltn.{LtnFeedRequester, LtnLiveFeed}
import drt.server.feeds.mag.{MagFeed, ProdFeedRequester}
import drt.shared.CrunchApi.MillisSinceEpoch
import drt.shared.FlightsApi.{Flights, FlightsWithSplits}
import drt.shared.Terminals.Terminal
import drt.shared._
import drt.shared.api.Arrival
import drt.shared.coachTime.CoachWalkTime
import manifests.ManifestLookupLike
import manifests.queues.SplitsCalculator
import org.joda.time.DateTimeZone
import play.api.Configuration
import queueus.{AdjustmentsNoop, ChildEGateAdjustments, PaxTypeQueueAllocation, QueueAdjustments}
import server.feeds.{ArrivalsFeedResponse, ArrivalsFeedSuccess, ManifestsFeedResponse}
import services.PcpArrival.{GateOrStandWalkTime, gateOrStandWalkTimeCalculator, walkTimeMillisProviderFromCsv}
import services._
import services.arrivals.{ArrivalsAdjustments, ArrivalsAdjustmentsLike}
import services.crunch.CrunchSystem.paxTypeQueueAllocator
import services.crunch.desklimits.{PortDeskLimits, TerminalDeskLimitsLike}
import services.crunch.deskrecs._
import services.crunch.{CrunchProps, CrunchSystem}
import services.graphstages.{Crunch, FlightFilter}
import scala.collection.immutable.SortedMap
import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.language.postfixOps
trait DrtSystemInterface extends UserRoleProviderLike {
implicit val materializer: Materializer
implicit val ec: ExecutionContext
implicit val system: ActorSystem
val now: () => SDateLike = () => SDate.now()
val purgeOldLiveSnapshots = false
val purgeOldForecastSnapshots = true
val manifestLookupService: ManifestLookupLike
val config: Configuration = new Configuration(ConfigFactory.load)
val airportConfig: AirportConfig
val params: DrtConfigParameters = DrtConfigParameters(config)
val journalType: StreamingJournalLike = StreamingJournal.forConfig(config)
val gateWalkTimesProvider: GateOrStandWalkTime = walkTimeMillisProviderFromCsv(params.gateWalkTimesFilePath)
val standWalkTimesProvider: GateOrStandWalkTime = walkTimeMillisProviderFromCsv(params.standWalkTimesFilePath)
private val minBackoffSeconds = config.get[Int]("persistence.on-stop-backoff.minimum-seconds")
private val maxBackoffSeconds = config.get[Int]("persistence.on-stop-backoff.maximum-seconds")
val restartOnStop: RestartOnStop = RestartOnStop(minBackoffSeconds seconds, maxBackoffSeconds seconds)
val alertsActor: ActorRef = restartOnStop.actorOf(Props(new AlertsActor(now)), "alerts-actor")
val liveBaseArrivalsActor: ActorRef = restartOnStop.actorOf(Props(new CirriumLiveArrivalsActor(params.snapshotMegaBytesLiveArrivals, now, expireAfterMillis)), name = "live-base-arrivals-actor")
val arrivalsImportActor: ActorRef = system.actorOf(Props(new ArrivalsImportActor()), name = "arrivals-import-actor")
val crunchQueueActor: ActorRef
val deploymentQueueActor: ActorRef
val minuteLookups: MinuteLookupsLike
val portStateActor: ActorRef
val shiftsActor: ActorRef
val fixedPointsActor: ActorRef
val staffMovementsActor: ActorRef
val baseArrivalsActor: ActorRef
val forecastArrivalsActor: ActorRef
val liveArrivalsActor: ActorRef
val manifestsRouterActor: ActorRef
val flightsActor: ActorRef
val queuesActor: ActorRef
val staffActor: ActorRef
val queueUpdates: ActorRef
val staffUpdates: ActorRef
val flightUpdates: ActorRef
lazy private val feedActors: Map[FeedSource, ActorRef] = Map(
LiveFeedSource -> liveArrivalsActor,
LiveBaseFeedSource -> liveBaseArrivalsActor,
ForecastFeedSource -> forecastArrivalsActor,
AclFeedSource -> baseArrivalsActor,
ApiFeedSource -> manifestsRouterActor
)
lazy val feedActorsForPort: Map[FeedSource, ActorRef] = feedActors.filter {
case (feedSource: FeedSource, _) => isValidFeedSource(feedSource)
}
val maybeAclFeed: Option[AclFeed] =
if (params.aclDisabled) None
else
for {
host <- params.aclHost
username <- params.aclUsername
keyPath <- params.aclKeyPath
} yield AclFeed(host, username, keyPath, airportConfig.feedPortCode, AclFeed.aclToPortMapping(airportConfig.portCode), params.aclMinFileSizeInBytes)
val maxDaysToConsider: Int = 14
val passengersActorProvider: () => ActorRef = () => system.actorOf(Props(new PassengersActor(maxDaysToConsider, aclPaxAdjustmentDays, now)), name = "passengers-actor")
val aggregatedArrivalsActor: ActorRef
val aclPaxAdjustmentDays: Int = config.get[Int]("acl.adjustment.number-of-days-in-average")
val optimiser: TryCrunch = OptimiserWithFlexibleProcessors.crunch
val portDeskRecs: PortDesksAndWaitsProviderLike = PortDesksAndWaitsProvider(airportConfig, optimiser, FlightFilter.forPortConfig(airportConfig))
val deskLimitsProviders: Map[Terminal, TerminalDeskLimitsLike] = if (config.get[Boolean]("crunch.flex-desks"))
PortDeskLimits.flexed(airportConfig)
else
PortDeskLimits.fixed(airportConfig)
val paxTypeQueueAllocation: PaxTypeQueueAllocation = paxTypeQueueAllocator(airportConfig)
val splitAdjustments: QueueAdjustments = if (params.adjustEGateUseByUnder12s)
ChildEGateAdjustments(airportConfig.assumedAdultsPerChild)
else
AdjustmentsNoop
def run(): Unit
def coachWalkTime: CoachWalkTime
def walkTimeProvider(flight: Arrival): MillisSinceEpoch = {
val defaultWalkTimeMillis = airportConfig.defaultWalkTimeMillis.getOrElse(flight.Terminal, 300000L)
gateOrStandWalkTimeCalculator(gateWalkTimesProvider, standWalkTimesProvider, defaultWalkTimeMillis, coachWalkTime)(flight)
}
def pcpArrivalTimeCalculator: Arrival => MilliDate =
PaxFlow.pcpArrivalTimeForFlight(airportConfig.timeToChoxMillis, airportConfig.firstPaxOffMillis)(walkTimeProvider)
def isValidFeedSource(fs: FeedSource): Boolean = airportConfig.feedSources.contains(fs)
def startCrunchSystem(initialPortState: Option[PortState],
initialForecastBaseArrivals: Option[SortedMap[UniqueArrival, Arrival]],
initialForecastArrivals: Option[SortedMap[UniqueArrival, Arrival]],
initialLiveBaseArrivals: Option[SortedMap[UniqueArrival, Arrival]],
initialLiveArrivals: Option[SortedMap[UniqueArrival, Arrival]],
refreshArrivalsOnStart: Boolean,
refreshManifestsOnStart: Boolean,
startDeskRecs: () => (UniqueKillSwitch, UniqueKillSwitch)): CrunchSystem[Cancellable] = {
val voyageManifestsLiveSource: Source[ManifestsFeedResponse, SourceQueueWithComplete[ManifestsFeedResponse]] = Source.queue[ManifestsFeedResponse](1, OverflowStrategy.backpressure)
val arrivalAdjustments: ArrivalsAdjustmentsLike = ArrivalsAdjustments.adjustmentsForPort(airportConfig.portCode)
val simulator: TrySimulator = OptimiserWithFlexibleProcessors.runSimulationOfWork
val crunchInputs = CrunchSystem(CrunchProps(
airportConfig = airportConfig,
pcpArrival = pcpArrivalTimeCalculator,
portStateActor = portStateActor,
flightsActor = flightsActor,
maxDaysToCrunch = params.forecastMaxDays,
expireAfterMillis = DrtStaticParameters.expireAfterMillis,
actors = Map(
"shifts" -> shiftsActor,
"fixed-points" -> fixedPointsActor,
"staff-movements" -> staffMovementsActor,
"forecast-base-arrivals" -> baseArrivalsActor,
"forecast-arrivals" -> forecastArrivalsActor,
"live-base-arrivals" -> liveBaseArrivalsActor,
"live-arrivals" -> liveArrivalsActor,
"aggregated-arrivals" -> aggregatedArrivalsActor,
"deployment-request" -> deploymentQueueActor
),
useNationalityBasedProcessingTimes = params.useNationalityBasedProcessingTimes,
manifestsLiveSource = voyageManifestsLiveSource,
voyageManifestsActor = manifestsRouterActor,
simulator = simulator,
initialPortState = initialPortState,
initialForecastBaseArrivals = initialForecastBaseArrivals.getOrElse(SortedMap()),
initialForecastArrivals = initialForecastArrivals.getOrElse(SortedMap()),
initialLiveBaseArrivals = initialLiveBaseArrivals.getOrElse(SortedMap()),
initialLiveArrivals = initialLiveArrivals.getOrElse(SortedMap()),
arrivalsForecastBaseSource = baseArrivalsSource(maybeAclFeed),
arrivalsForecastSource = forecastArrivalsSource(airportConfig.feedPortCode),
arrivalsLiveBaseSource = liveBaseArrivalsSource(airportConfig.feedPortCode),
arrivalsLiveSource = liveArrivalsSource(airportConfig.feedPortCode),
passengersActorProvider = passengersActorProvider,
initialShifts = initialState[ShiftAssignments](shiftsActor).getOrElse(ShiftAssignments(Seq())),
initialFixedPoints = initialState[FixedPointAssignments](fixedPointsActor).getOrElse(FixedPointAssignments(Seq())),
initialStaffMovements = initialState[StaffMovements](staffMovementsActor).map(_.movements).getOrElse(Seq[StaffMovement]()),
refreshArrivalsOnStart = refreshArrivalsOnStart,
refreshManifestsOnStart = refreshManifestsOnStart,
adjustEGateUseByUnder12s = params.adjustEGateUseByUnder12s,
optimiser = optimiser,
aclPaxAdjustmentDays = aclPaxAdjustmentDays,
startDeskRecs = startDeskRecs,
arrivalsAdjustments = arrivalAdjustments
))
crunchInputs
}
def arrivalsNoOp: Source[ArrivalsFeedResponse, Cancellable] = Source.tick[ArrivalsFeedResponse](100 days, 100 days, ArrivalsFeedSuccess(Flights(Seq()), SDate.now()))
def baseArrivalsSource(maybeAclFeed: Option[AclFeed]): Source[ArrivalsFeedResponse, Cancellable] = maybeAclFeed match {
case None => arrivalsNoOp
case Some(aclFeed) =>
Source.tick(1 second, 10 minutes, NotUsed).map { _ =>
system.log.info(s"Requesting ACL feed")
aclFeed.requestArrivals
}
}
val startDeskRecs: () => (UniqueKillSwitch, UniqueKillSwitch) = () => {
val staffToDeskLimits = PortDeskLimits.flexedByAvailableStaff(airportConfig) _
implicit val timeout: Timeout = new Timeout(1 second)
val splitsCalculator = SplitsCalculator(paxTypeQueueAllocation, airportConfig.terminalPaxSplits, splitAdjustments)
val deskRecsProducer = DynamicRunnableDeskRecs.crunchRequestsToQueueMinutes(
arrivalsProvider = OptimisationProviders.arrivalsProvider(portStateActor),
liveManifestsProvider = OptimisationProviders.liveManifestsProvider(manifestsRouterActor),
historicManifestsProvider = OptimisationProviders.historicManifestsProvider(airportConfig.portCode, manifestLookupService),
splitsCalculator = splitsCalculator,
splitsSink = portStateActor,
flightsToLoads = portDeskRecs.flightsToLoads,
loadsToQueueMinutes = portDeskRecs.loadsToDesks,
maxDesksProviders = deskLimitsProviders)
val (crunchRequestQueue, deskRecsKillSwitch) = RunnableOptimisation.createGraph(portStateActor, deskRecsProducer).run()
val deploymentsProducer = DynamicRunnableDeployments.crunchRequestsToDeployments(
OptimisationProviders.loadsProvider(minuteLookups.queueMinutesActor),
OptimisationProviders.staffMinutesProvider(minuteLookups.staffMinutesActor, airportConfig.terminals),
staffToDeskLimits,
portDeskRecs.loadsToSimulations
)
val (deploymentRequestQueue, deploymentsKillSwitch) = RunnableOptimisation.createGraph(portStateActor, deploymentsProducer).run()
crunchQueueActor ! SetCrunchRequestQueue(crunchRequestQueue)
deploymentQueueActor ! SetCrunchRequestQueue(deploymentRequestQueue)
if (params.recrunchOnStart) queueDaysToReCrunch(crunchQueueActor)
(deskRecsKillSwitch, deploymentsKillSwitch)
}
def queueDaysToReCrunch(crunchQueueActor: ActorRef): Unit = {
val today = now()
val millisToCrunchStart = Crunch.crunchStartWithOffset(portDeskRecs.crunchOffsetMinutes) _
val daysToReCrunch = (0 until params.forecastMaxDays).map(d => {
millisToCrunchStart(today.addDays(d)).millisSinceEpoch
})
crunchQueueActor ! UpdatedMillis(daysToReCrunch)
}
def startScheduledFeedImports(crunchInputs: CrunchSystem[Cancellable]): Unit = {
if (airportConfig.feedPortCode == PortCode("LHR")) params.maybeBlackJackUrl.map(csvUrl => {
val requestIntervalMillis = 5 * MilliTimes.oneMinuteMillis
Deskstats.startBlackjack(csvUrl, crunchInputs.actualDeskStats, requestIntervalMillis milliseconds, () => SDate.now().addDays(-1))
})
}
def subscribeStaffingActors(crunchInputs: CrunchSystem[Cancellable]): Unit = {
shiftsActor ! AddShiftSubscribers(List(crunchInputs.shifts))
fixedPointsActor ! AddFixedPointSubscribers(List(crunchInputs.fixedPoints))
staffMovementsActor ! AddStaffMovementsSubscribers(List(crunchInputs.staffMovements))
}
def liveBaseArrivalsSource(portCode: PortCode): Source[ArrivalsFeedResponse, Cancellable] = {
if (config.get[Boolean]("feature-flags.use-cirium-feed")) {
log.info(s"Using Cirium Live Base Feed")
CiriumFeed(config.get[String]("feeds.cirium.host"), portCode).tickingSource(30 seconds)
}
else {
log.info(s"Using Noop Base Live Feed")
arrivalsNoOp
}
}
def liveArrivalsSource(portCode: PortCode): Source[ArrivalsFeedResponse, Cancellable] =
portCode.iata match {
case "LHR" =>
val host = config.get[String]("feeds.lhr.sftp.live.host")
val username = config.get[String]("feeds.lhr.sftp.live.username")
val password = config.get[String]("feeds.lhr.sftp.live.password")
val contentProvider = () => LhrSftpLiveContentProvider(host, username, password).latestContent
LHRFlightFeed(contentProvider)
case "LGW" =>
val lgwNamespace = params.maybeLGWNamespace.getOrElse(throw new Exception("Missing LGW Azure Namespace parameter"))
val lgwSasToKey = params.maybeLGWSASToKey.getOrElse(throw new Exception("Missing LGW SAS Key for To Queue"))
val lgwServiceBusUri = params.maybeLGWServiceBusUri.getOrElse(throw new Exception("Missing LGW Service Bus Uri"))
val azureClient = LGWAzureClient(LGWFeed.serviceBusClient(lgwNamespace, lgwSasToKey, lgwServiceBusUri))
LGWFeed(azureClient)(system).source()
case "BHX" if params.bhxIataEndPointUrl.nonEmpty =>
BHXFeed(BHXClient(params.bhxIataUsername, params.bhxIataEndPointUrl), 80 seconds, 1 milliseconds)
case "BHX" =>
BHXLiveFeedLegacy(params.maybeBhxSoapEndPointUrl.getOrElse(throw new Exception("Missing BHX live feed URL")))
case "LCY" if params.lcyLiveEndPointUrl.nonEmpty =>
LCYFeed(LCYClient(new HttpClient, params.lcyLiveUsername, params.lcyLiveEndPointUrl, params.lcyLiveUsername, params.lcyLivePassword), 80 seconds, 1 milliseconds)
case "LTN" =>
val url = params.maybeLtnLiveFeedUrl.getOrElse(throw new Exception("Missing live feed url"))
val username = params.maybeLtnLiveFeedUsername.getOrElse(throw new Exception("Missing live feed username"))
val password = params.maybeLtnLiveFeedPassword.getOrElse(throw new Exception("Missing live feed password"))
val token = params.maybeLtnLiveFeedToken.getOrElse(throw new Exception("Missing live feed token"))
val timeZone = params.maybeLtnLiveFeedTimeZone match {
case Some(tz) => DateTimeZone.forID(tz)
case None => DateTimeZone.UTC
}
val requester = LtnFeedRequester(url, token, username, password)
LtnLiveFeed(requester, timeZone).tickingSource(30 seconds)
case "MAN" | "STN" | "EMA" =>
if (config.get[Boolean]("feeds.mag.use-legacy")) {
log.info(s"Using legacy MAG live feed")
createLiveChromaFlightFeed(ChromaLive).chromaVanillaFlights(30 seconds)
} else {
log.info(s"Using new MAG live feed")
val privateKey: String = config.get[String]("feeds.mag.private-key")
val claimIss: String = config.get[String]("feeds.mag.claim.iss")
val claimRole: String = config.get[String]("feeds.mag.claim.role")
val claimSub: String = config.get[String]("feeds.mag.claim.sub")
MagFeed(privateKey, claimIss, claimRole, claimSub, now, airportConfig.portCode, ProdFeedRequester).tickingSource
}
case "GLA" =>
val liveUrl = params.maybeGlaLiveUrl.getOrElse(throw new Exception("Missing GLA Live Feed Url"))
val livePassword = params.maybeGlaLivePassword.getOrElse(throw new Exception("Missing GLA Live Feed Password"))
val liveToken = params.maybeGlaLiveToken.getOrElse(throw new Exception("Missing GLA Live Feed Token"))
val liveUsername = params.maybeGlaLiveUsername.getOrElse(throw new Exception("Missing GLA Live Feed Username"))
GlaFeed(liveUrl, liveToken, livePassword, liveUsername, ProdGlaFeedRequester).tickingSource
case "PIK" =>
CiriumFeed(config.get[String]("feeds.cirium.host"), portCode).tickingSource(30 seconds)
case _ => arrivalsNoOp
}
def forecastArrivalsSource(portCode: PortCode): Source[ArrivalsFeedResponse, Cancellable] = {
val feed = portCode match {
case PortCode("LHR") | PortCode("LGW") | PortCode("STN") => createArrivalFeed
case PortCode("BHX") => BHXForecastFeedLegacy(params.maybeBhxSoapEndPointUrl.getOrElse(throw new Exception("Missing BHX feed URL")))
case _ => system.log.info(s"No Forecast Feed defined.")
arrivalsNoOp
}
feed
}
def createLiveChromaFlightFeed(feedType: ChromaFeedType): ChromaLiveFeed = {
ChromaLiveFeed(new ChromaFetcher[ChromaLiveFlight](feedType, ChromaFlightMarshallers.live) with ProdSendAndReceive)
}
def createForecastChromaFlightFeed(feedType: ChromaFeedType): ChromaForecastFeed = {
ChromaForecastFeed(new ChromaFetcher[ChromaForecastFlight](feedType, ChromaFlightMarshallers.forecast) with ProdSendAndReceive)
}
def createArrivalFeed: Source[ArrivalsFeedResponse, Cancellable] = {
implicit val timeout: Timeout = new Timeout(10 seconds)
val arrivalFeed = ArrivalFeed(arrivalsImportActor)
Source
.tick(10 seconds, 5 seconds, NotUsed)
.mapAsync(1)(_ => arrivalFeed.requestFeed)
}
def initialState[A](askableActor: ActorRef): Option[A] = Await.result(initialStateFuture[A](askableActor), 2 minutes)
def initialFlightsPortState(actor: ActorRef, forecastMaxDays: Int): Future[Option[PortState]] = {
val from = now().getLocalLastMidnight.addDays(-1)
val to = from.addDays(forecastMaxDays)
val request = GetFlights(from.millisSinceEpoch, to.millisSinceEpoch)
FlightsRouterActor.runAndCombine(actor
.ask(request)(new Timeout(15 seconds)).mapTo[Source[FlightsWithSplits, NotUsed]])
.map { fws =>
Option(PortState(fws.flights.values, Iterable(), Iterable()))
}
}
def initialStateFuture[A](askableActor: ActorRef): Future[Option[A]] = {
val actorPath = askableActor.actorRef.path
queryActorWithRetry[A](askableActor, GetState)
.map {
case Some(state: A) if state.isInstanceOf[A] =>
log.debug(s"Got initial state (Some(${state.getClass})) from $actorPath")
Option(state)
case None =>
log.warn(s"Got no state (None) from $actorPath")
None
}
.recoverWith {
case t =>
log.error(s"Failed to get response from $askableActor", t)
Future(None)
}
}
def queryActorWithRetry[A](actor: ActorRef, toAsk: Any): Future[Option[A]] = {
val future = actor.ask(toAsk)(new Timeout(2 minutes)).map {
case Some(state: A) if state.isInstanceOf[A] => Option(state)
case state: A if !state.isInstanceOf[Option[A]] => Option(state)
case _ => None
}
implicit val scheduler: Scheduler = system.scheduler
Retry.retry(future, RetryDelays.fibonacci, 3, 5 seconds)
}
def getFeedStatus: Future[Seq[FeedSourceStatuses]] = Source(feedActorsForPort)
.mapAsync(1) {
case (_, actor) => queryActorWithRetry[FeedSourceStatuses](actor, GetFeedStatuses)
}
.collect { case Some(fs) => fs }
.withAttributes(StreamSupervision.resumeStrategyWithLog("getFeedStatus"))
.runWith(Sink.seq)
}
|
UKHomeOffice/drt-scalajs-spa-exploration
|
server/src/main/scala/actors/DrtSystemInterface.scala
|
Scala
|
apache-2.0
| 21,758 |
package org.dele.text.maen.matchers
import org.dele.text.maen.ErrorHandling.{SubMatchCheckerErrorUnknownCheckerId, SubMatchCheckerLibErrorUnknownTemplate}
import org.dele.text.maen.matchers.TMatcher.{MId, TMatcherDep}
import org.dele.text.maen.{ConfValueStringParser, TInput}
import org.dele.text.maen.ConfValueStringParser.Parsed
import org.dele.text.maen.ConfValueStringParser.Parsed
import org.dele.text.maen.TInput
import scala.collection.mutable.ListBuffer
/**
* Created by jiaji on 2016-03-12.
*/
import SubMatchCheckerLib._
import TSubMatchChecker._
class SubMatchCheckerLib(staticDefs:Iterable[(String, Parsed)], dynDefs:Iterable[(String, TDynamicChecker)]) {
/*
def resolve(implicit paramTransform: String => String, gen:PartialFunction[Parsed, TSubMatchChecker]):SubMatchCheckerLib = {
defs.foreach(
d => {
val id = d._1
val defi = d._2
val parsed = ConfValueStringParser.parse(defi)
val transformedParams = parsed.paras.map(_.map(paramTransform))
_map += id -> gen(Parsed(parsed.id, transformedParams))
}
)
this
}
*/
val builtInCreator = new PartialFunction[Parsed, TSubMatchChecker] {
def isDefinedAt(p:Parsed):Boolean = isStaticChecker(p)
def apply(p:Parsed):TSubMatchChecker = p.id match {
case "None" => matchesInBetween_None(p.paras(0))
case "All" => matchesInBetween_All(p.paras(0))
case NoCheckId => NoCheck
case HeadCheckId => HeadChecker
case TailCheckId => TailChecker
case ListNGramId => ListNGramChecker
case _ => throw SubMatchCheckerErrorUnknownCheckerId(p.id)
}
}
val (staticCheckerMap:Map[String, TSubMatchChecker], dynamicCheckerMap:Map[String, TDynamicChecker]) = {
val staticCheckers = ListBuffer[(String, TSubMatchChecker)]()
val dynamicCheckers = ListBuffer[(String, TDynamicChecker)]()
staticDefs.foreach(
d => {
val id = d._1
val parsed = d._2
//val parsed = ConfValueStringParser.parse(defi)
//val transformedParams = parsed.paras.map(_.map(paramTransform))
if (builtInCreator.isDefinedAt(parsed)) {
staticCheckers += id -> builtInCreator(parsed)
}
else if(parsed.id == "And") {
dynamicCheckers += id -> And(parsed.paras(0), this)
}
else {
throw SubMatchCheckerLibErrorUnknownTemplate(parsed.id)
}
}
)
(BuildInCheckers ++ staticCheckers.toMap, (dynDefs ++ dynamicCheckers).toMap)
}
def getDepMatcherIds(checkerId:String):Set[MId] =
if (staticCheckerMap.contains(checkerId)) staticCheckerMap.get(checkerId).get.depMatcherIds else Set()
//private val _map:mutable.Map[String, TSubMatchChecker] = mutable.Map()
//def getStatic(id:String):TSubMatchChecker = staticCheckerMap.get(id).get
def getCheckers(ids:Iterable[String]):(Iterable[TSubMatchChecker], Iterable[TDynamicChecker]) = {
val staticIds = ids.filter(staticCheckerMap.contains)
val dynamicIds = ids.filter(dynamicCheckerMap.contains)
val staticMatchers = staticIds.map(staticCheckerMap.get(_).get)
(staticMatchers, dynamicIds.map(dynamicCheckerMap.get(_).get))
}
def forInput(input:TInput):Map[String, TSubMatchChecker] = staticCheckerMap ++
dynamicCheckerMap.map(p => (p._1, p._2.gen(input))).filter(p => (p._2.isDefined)).map(p => (p._1, p._2.get))
}
object SubMatchCheckerLib {
/*
def c(m:Map[String,TSubMatchChecker]):SubMatchCheckerLib = {
val r = new SubMatchCheckerLib
r ++= m
}
*/
trait TDynamicChecker extends TMatcherDep {
override def depMatcherIds:Set[MId] = TMatcher.EmptyIdSet
def gen(input:TInput):Option[TSubMatchChecker]
}
val NoCheckId = "NoCheck"
val HeadCheckId = "HeadCheck"
val TailCheckId = "TailCheck"
val ListNGramId = "Lng"
import TSubMatchChecker._
val BuildInCheckers:Map[String, TSubMatchChecker] = Map(
NoCheckId -> NoCheck,
HeadCheckId -> HeadChecker,
TailCheckId -> TailChecker,
ListNGramId -> ListNGramChecker
)
private val _TemplateNames:Set[String] = Set(NoCheckId, HeadCheckId, TailCheckId, ListNGramId, "None", "All")
def isStaticChecker(p:Parsed):Boolean = _TemplateNames.contains(p.id)
def isStaticChecker(id:String):Boolean = _TemplateNames.contains(id)
private[SubMatchCheckerLib] class _andCheckersFromLib(checkerIds:Iterable[String], checkerLib:SubMatchCheckerLib) extends TDynamicChecker {
lazy private val checkers = checkerLib.getCheckers(checkerIds)
lazy private val staticCheckers = checkers._1
lazy private val dynamicCheckers = checkers._2
lazy private val isStatic = dynamicCheckers.isEmpty
def gen(input:TInput):Option[TSubMatchChecker] = {
val checkers = if (isStatic) staticCheckers else staticCheckers ++ dynamicCheckers.flatMap(_.gen(input))
if (checkers.size == 1) Option(checkers.toList(0)) else Option(new _andCheckers(checkers))
}
override def depMatcherIds:Set[MId] = getCheckerDepIds(staticCheckers) ++ getCheckerDepIds(dynamicCheckers)
}
private[matchers] def And(checkerIds:Iterable[String], checkerLib:SubMatchCheckerLib):TDynamicChecker = new _andCheckersFromLib(checkerIds, checkerLib)
}
|
new2scala/text-util
|
maen/src/main/scala/org/dele/text/maen/matchers/SubMatchCheckerLib.scala
|
Scala
|
apache-2.0
| 5,190 |
object Test {
def main(args: Array[String]): Unit = println("hello dotty!")
}
|
lampepfl/dotty
|
tests/run/hello.scala
|
Scala
|
apache-2.0
| 80 |
/*
* Copyright (c) 2016 SnappyData, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package org.apache.spark.scheduler.cluster
import io.snappydata.impl.LeadImpl
import io.snappydata.util.ServiceUtils
import io.snappydata.{Constant, Property}
import org.slf4j.LoggerFactory
import org.apache.spark.SparkContext
import org.apache.spark.scheduler._
/**
* Snappy's cluster manager that is responsible for creating
* scheduler and scheduler backend.
*/
class SnappyEmbeddedModeClusterManager extends ExternalClusterManager {
val logger = LoggerFactory.getLogger(getClass)
SnappyClusterManager.init(this)
var schedulerBackend: SnappyCoarseGrainedSchedulerBackend = _
override def createTaskScheduler(sc: SparkContext, masterURL: String): TaskScheduler = {
// If there is an application that is trying to join snappy
// as lead in embedded mode, we need the locator to connect
// to the snappy distributed system and hence the locator is
// passed in masterurl itself.
if (sc.master.startsWith(Constant.SNAPPY_URL_PREFIX)) {
val locator = sc.master.replaceFirst(Constant.SNAPPY_URL_PREFIX, "").trim
val (prop, value) = {
if (locator.indexOf("mcast-port") >= 0) {
val split = locator.split("=")
(split(0).trim, split(1).trim)
}
else if (locator.isEmpty ||
locator == "" ||
locator == "null" ||
!ServiceUtils.LOCATOR_URL_PATTERN.matcher(locator).matches()
) {
throw new Exception(s"locator info not provided in the snappy embedded url ${sc.master}")
}
(Property.Locators.name, locator)
}
logger.info(s"setting from url $prop with $value")
sc.conf.set(prop, value)
sc.conf.set(Property.Embedded.name, "true")
}
new SnappyTaskSchedulerImpl(sc)
}
override def canCreate(masterURL: String): Boolean =
masterURL.startsWith("snappydata")
override def createSchedulerBackend(sc: SparkContext, masterURL: String,
scheduler: TaskScheduler): SchedulerBackend = {
sc.addSparkListener(new BlockManagerIdListener(sc))
schedulerBackend = new SnappyCoarseGrainedSchedulerBackend(
scheduler.asInstanceOf[TaskSchedulerImpl], sc.env.rpcEnv)
schedulerBackend
}
def initialize(scheduler: TaskScheduler,
backend: SchedulerBackend): Unit = {
assert(scheduler.isInstanceOf[TaskSchedulerImpl])
val schedulerImpl = scheduler.asInstanceOf[TaskSchedulerImpl]
schedulerImpl.initialize(backend)
LeadImpl.invokeLeadStart(schedulerImpl.sc)
}
def stopLead(): Unit = {
LeadImpl.invokeLeadStop(null)
}
}
object SnappyClusterManager {
private[this] var _cm: SnappyEmbeddedModeClusterManager = _
def init(mgr: SnappyEmbeddedModeClusterManager): Unit = {
_cm = mgr
}
def cm: Option[SnappyEmbeddedModeClusterManager] = Option(_cm)
}
|
vjr/snappydata
|
cluster/src/main/scala/org/apache/spark/scheduler/cluster/SnappyEmbeddedModeClusterManager.scala
|
Scala
|
apache-2.0
| 3,450 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.catalyst.expressions
import org.apache.commons.codec.digest.DigestUtils
import org.apache.spark.sql.AnalysisException
import org.apache.spark.sql.catalyst.expressions.MaskExpressionsUtils._
import org.apache.spark.sql.catalyst.expressions.MaskLike._
import org.apache.spark.sql.catalyst.expressions.codegen.{CodegenContext, CodeGenerator, ExprCode}
import org.apache.spark.sql.types._
import org.apache.spark.unsafe.types.UTF8String
trait MaskLike {
def upper: String
def lower: String
def digit: String
protected lazy val upperReplacement: Int = getReplacementChar(upper, defaultMaskedUppercase)
protected lazy val lowerReplacement: Int = getReplacementChar(lower, defaultMaskedLowercase)
protected lazy val digitReplacement: Int = getReplacementChar(digit, defaultMaskedDigit)
protected val maskUtilsClassName: String = classOf[MaskExpressionsUtils].getName
def inputStringLengthCode(inputString: String, length: String): String = {
s"${CodeGenerator.JAVA_INT} $length = $inputString.codePointCount(0, $inputString.length());"
}
def appendMaskedToStringBuilderCode(
ctx: CodegenContext,
sb: String,
inputString: String,
offset: String,
numChars: String): String = {
val i = ctx.freshName("i")
val codePoint = ctx.freshName("codePoint")
s"""
|for (${CodeGenerator.JAVA_INT} $i = 0; $i < $numChars; $i++) {
| ${CodeGenerator.JAVA_INT} $codePoint = $inputString.codePointAt($offset);
| $sb.appendCodePoint($maskUtilsClassName.transformChar($codePoint,
| $upperReplacement, $lowerReplacement,
| $digitReplacement, $defaultMaskedOther));
| $offset += Character.charCount($codePoint);
|}
""".stripMargin
}
def appendUnchangedToStringBuilderCode(
ctx: CodegenContext,
sb: String,
inputString: String,
offset: String,
numChars: String): String = {
val i = ctx.freshName("i")
val codePoint = ctx.freshName("codePoint")
s"""
|for (${CodeGenerator.JAVA_INT} $i = 0; $i < $numChars; $i++) {
| ${CodeGenerator.JAVA_INT} $codePoint = $inputString.codePointAt($offset);
| $sb.appendCodePoint($codePoint);
| $offset += Character.charCount($codePoint);
|}
""".stripMargin
}
def appendMaskedToStringBuilder(
sb: java.lang.StringBuilder,
inputString: String,
startOffset: Int,
numChars: Int): Int = {
var offset = startOffset
(1 to numChars) foreach { _ =>
val codePoint = inputString.codePointAt(offset)
sb.appendCodePoint(transformChar(
codePoint,
upperReplacement,
lowerReplacement,
digitReplacement,
defaultMaskedOther))
offset += Character.charCount(codePoint)
}
offset
}
def appendUnchangedToStringBuilder(
sb: java.lang.StringBuilder,
inputString: String,
startOffset: Int,
numChars: Int): Int = {
var offset = startOffset
(1 to numChars) foreach { _ =>
val codePoint = inputString.codePointAt(offset)
sb.appendCodePoint(codePoint)
offset += Character.charCount(codePoint)
}
offset
}
}
trait MaskLikeWithN extends MaskLike {
def n: Int
protected lazy val charCount: Int = if (n < 0) 0 else n
}
/**
* Utils for mask operations.
*/
object MaskLike {
val defaultCharCount = 4
val defaultMaskedUppercase: Int = 'X'
val defaultMaskedLowercase: Int = 'x'
val defaultMaskedDigit: Int = 'n'
val defaultMaskedOther: Int = MaskExpressionsUtils.UNMASKED_VAL
def extractCharCount(e: Expression): Int = e match {
case Literal(i, IntegerType | NullType) =>
if (i == null) defaultCharCount else i.asInstanceOf[Int]
case Literal(_, dt) => throw new AnalysisException("Expected literal expression of type " +
s"${IntegerType.simpleString}, but got literal of ${dt.simpleString}")
case other => throw new AnalysisException(s"Expected literal expression, but got ${other.sql}")
}
def extractReplacement(e: Expression): String = e match {
case Literal(s, StringType | NullType) => if (s == null) null else s.toString
case Literal(_, dt) => throw new AnalysisException("Expected literal expression of type " +
s"${StringType.simpleString}, but got literal of ${dt.simpleString}")
case other => throw new AnalysisException(s"Expected literal expression, but got ${other.sql}")
}
}
/**
* Masks the input string. Additional parameters can be set to change the masking chars for
* uppercase letters, lowercase letters and digits.
*/
// scalastyle:off line.size.limit
@ExpressionDescription(
usage = "_FUNC_(str[, upper[, lower[, digit]]]) - Masks str. By default, upper case letters are converted to \\"X\\", lower case letters are converted to \\"x\\" and numbers are converted to \\"n\\". You can override the characters used in the mask by supplying additional arguments: the second argument controls the mask character for upper case letters, the third argument for lower case letters and the fourth argument for numbers.",
examples = """
Examples:
> SELECT _FUNC_("abcd-EFGH-8765-4321", "U", "l", "#");
llll-UUUU-####-####
""")
// scalastyle:on line.size.limit
case class Mask(child: Expression, upper: String, lower: String, digit: String)
extends UnaryExpression with ExpectsInputTypes with MaskLike {
def this(child: Expression) = this(child, null.asInstanceOf[String], null, null)
def this(child: Expression, upper: Expression) =
this(child, extractReplacement(upper), null, null)
def this(child: Expression, upper: Expression, lower: Expression) =
this(child, extractReplacement(upper), extractReplacement(lower), null)
def this(child: Expression, upper: Expression, lower: Expression, digit: Expression) =
this(child, extractReplacement(upper), extractReplacement(lower), extractReplacement(digit))
override def nullSafeEval(input: Any): Any = {
val str = input.asInstanceOf[UTF8String].toString
val length = str.codePointCount(0, str.length())
val sb = new java.lang.StringBuilder(length)
appendMaskedToStringBuilder(sb, str, 0, length)
UTF8String.fromString(sb.toString)
}
override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, (input: String) => {
val sb = ctx.freshName("sb")
val length = ctx.freshName("length")
val offset = ctx.freshName("offset")
val inputString = ctx.freshName("inputString")
s"""
|String $inputString = $input.toString();
|${inputStringLengthCode(inputString, length)}
|StringBuilder $sb = new StringBuilder($length);
|${CodeGenerator.JAVA_INT} $offset = 0;
|${appendMaskedToStringBuilderCode(ctx, sb, inputString, offset, length)}
|${ev.value} = UTF8String.fromString($sb.toString());
""".stripMargin
})
}
override def dataType: DataType = StringType
override def inputTypes: Seq[AbstractDataType] = Seq(StringType)
}
/**
* Masks the first N chars of the input string. N defaults to 4. Additional parameters can be set
* to change the masking chars for uppercase letters, lowercase letters and digits.
*/
// scalastyle:off line.size.limit
@ExpressionDescription(
usage = "_FUNC_(str[, n[, upper[, lower[, digit]]]]) - Masks the first n values of str. By default, n is 4, upper case letters are converted to \\"X\\", lower case letters are converted to \\"x\\" and numbers are converted to \\"n\\". You can override the characters used in the mask by supplying additional arguments: the second argument controls the mask character for upper case letters, the third argument for lower case letters and the fourth argument for numbers.",
examples = """
Examples:
> SELECT _FUNC_("1234-5678-8765-4321", 4);
nnnn-5678-8765-4321
""")
// scalastyle:on line.size.limit
case class MaskFirstN(
child: Expression,
n: Int,
upper: String,
lower: String,
digit: String)
extends UnaryExpression with ExpectsInputTypes with MaskLikeWithN {
def this(child: Expression) =
this(child, defaultCharCount, null, null, null)
def this(child: Expression, n: Expression) =
this(child, extractCharCount(n), null, null, null)
def this(child: Expression, n: Expression, upper: Expression) =
this(child, extractCharCount(n), extractReplacement(upper), null, null)
def this(child: Expression, n: Expression, upper: Expression, lower: Expression) =
this(child, extractCharCount(n), extractReplacement(upper), extractReplacement(lower), null)
def this(
child: Expression,
n: Expression,
upper: Expression,
lower: Expression,
digit: Expression) =
this(child,
extractCharCount(n),
extractReplacement(upper),
extractReplacement(lower),
extractReplacement(digit))
override def nullSafeEval(input: Any): Any = {
val str = input.asInstanceOf[UTF8String].toString
val length = str.codePointCount(0, str.length())
val endOfMask = if (charCount > length) length else charCount
val sb = new java.lang.StringBuilder(length)
val offset = appendMaskedToStringBuilder(sb, str, 0, endOfMask)
appendUnchangedToStringBuilder(sb, str, offset, length - endOfMask)
UTF8String.fromString(sb.toString)
}
override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, (input: String) => {
val sb = ctx.freshName("sb")
val length = ctx.freshName("length")
val offset = ctx.freshName("offset")
val inputString = ctx.freshName("inputString")
val endOfMask = ctx.freshName("endOfMask")
s"""
|String $inputString = $input.toString();
|${inputStringLengthCode(inputString, length)}
|${CodeGenerator.JAVA_INT} $endOfMask = $charCount > $length ? $length : $charCount;
|${CodeGenerator.JAVA_INT} $offset = 0;
|StringBuilder $sb = new StringBuilder($length);
|${appendMaskedToStringBuilderCode(ctx, sb, inputString, offset, endOfMask)}
|${appendUnchangedToStringBuilderCode(
ctx, sb, inputString, offset, s"$length - $endOfMask")}
|${ev.value} = UTF8String.fromString($sb.toString());
|""".stripMargin
})
}
override def dataType: DataType = StringType
override def inputTypes: Seq[AbstractDataType] = Seq(StringType)
override def prettyName: String = "mask_first_n"
}
/**
* Masks the last N chars of the input string. N defaults to 4. Additional parameters can be set
* to change the masking chars for uppercase letters, lowercase letters and digits.
*/
// scalastyle:off line.size.limit
@ExpressionDescription(
usage = "_FUNC_(str[, n[, upper[, lower[, digit]]]]) - Masks the last n values of str. By default, n is 4, upper case letters are converted to \\"X\\", lower case letters are converted to \\"x\\" and numbers are converted to \\"n\\". You can override the characters used in the mask by supplying additional arguments: the second argument controls the mask character for upper case letters, the third argument for lower case letters and the fourth argument for numbers.",
examples = """
Examples:
> SELECT _FUNC_("1234-5678-8765-4321", 4);
1234-5678-8765-nnnn
""", since = "2.4.0")
// scalastyle:on line.size.limit
case class MaskLastN(
child: Expression,
n: Int,
upper: String,
lower: String,
digit: String)
extends UnaryExpression with ExpectsInputTypes with MaskLikeWithN {
def this(child: Expression) =
this(child, defaultCharCount, null, null, null)
def this(child: Expression, n: Expression) =
this(child, extractCharCount(n), null, null, null)
def this(child: Expression, n: Expression, upper: Expression) =
this(child, extractCharCount(n), extractReplacement(upper), null, null)
def this(child: Expression, n: Expression, upper: Expression, lower: Expression) =
this(child, extractCharCount(n), extractReplacement(upper), extractReplacement(lower), null)
def this(
child: Expression,
n: Expression,
upper: Expression,
lower: Expression,
digit: Expression) =
this(child,
extractCharCount(n),
extractReplacement(upper),
extractReplacement(lower),
extractReplacement(digit))
override def nullSafeEval(input: Any): Any = {
val str = input.asInstanceOf[UTF8String].toString
val length = str.codePointCount(0, str.length())
val startOfMask = if (charCount >= length) 0 else length - charCount
val sb = new java.lang.StringBuilder(length)
val offset = appendUnchangedToStringBuilder(sb, str, 0, startOfMask)
appendMaskedToStringBuilder(sb, str, offset, length - startOfMask)
UTF8String.fromString(sb.toString)
}
override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, (input: String) => {
val sb = ctx.freshName("sb")
val length = ctx.freshName("length")
val offset = ctx.freshName("offset")
val inputString = ctx.freshName("inputString")
val startOfMask = ctx.freshName("startOfMask")
s"""
|String $inputString = $input.toString();
|${inputStringLengthCode(inputString, length)}
|${CodeGenerator.JAVA_INT} $startOfMask = $charCount >= $length ?
| 0 : $length - $charCount;
|${CodeGenerator.JAVA_INT} $offset = 0;
|StringBuilder $sb = new StringBuilder($length);
|${appendUnchangedToStringBuilderCode(ctx, sb, inputString, offset, startOfMask)}
|${appendMaskedToStringBuilderCode(
ctx, sb, inputString, offset, s"$length - $startOfMask")}
|${ev.value} = UTF8String.fromString($sb.toString());
|""".stripMargin
})
}
override def dataType: DataType = StringType
override def inputTypes: Seq[AbstractDataType] = Seq(StringType)
override def prettyName: String = "mask_last_n"
}
/**
* Masks all but the first N chars of the input string. N defaults to 4. Additional parameters can
* be set to change the masking chars for uppercase letters, lowercase letters and digits.
*/
// scalastyle:off line.size.limit
@ExpressionDescription(
usage = "_FUNC_(str[, n[, upper[, lower[, digit]]]]) - Masks all but the first n values of str. By default, n is 4, upper case letters are converted to \\"X\\", lower case letters are converted to \\"x\\" and numbers are converted to \\"n\\". You can override the characters used in the mask by supplying additional arguments: the second argument controls the mask character for upper case letters, the third argument for lower case letters and the fourth argument for numbers.",
examples = """
Examples:
> SELECT _FUNC_("1234-5678-8765-4321", 4);
1234-nnnn-nnnn-nnnn
""", since = "2.4.0")
// scalastyle:on line.size.limit
case class MaskShowFirstN(
child: Expression,
n: Int,
upper: String,
lower: String,
digit: String)
extends UnaryExpression with ExpectsInputTypes with MaskLikeWithN {
def this(child: Expression) =
this(child, defaultCharCount, null, null, null)
def this(child: Expression, n: Expression) =
this(child, extractCharCount(n), null, null, null)
def this(child: Expression, n: Expression, upper: Expression) =
this(child, extractCharCount(n), extractReplacement(upper), null, null)
def this(child: Expression, n: Expression, upper: Expression, lower: Expression) =
this(child, extractCharCount(n), extractReplacement(upper), extractReplacement(lower), null)
def this(
child: Expression,
n: Expression,
upper: Expression,
lower: Expression,
digit: Expression) =
this(child,
extractCharCount(n),
extractReplacement(upper),
extractReplacement(lower),
extractReplacement(digit))
override def nullSafeEval(input: Any): Any = {
val str = input.asInstanceOf[UTF8String].toString
val length = str.codePointCount(0, str.length())
val startOfMask = if (charCount > length) length else charCount
val sb = new java.lang.StringBuilder(length)
val offset = appendUnchangedToStringBuilder(sb, str, 0, startOfMask)
appendMaskedToStringBuilder(sb, str, offset, length - startOfMask)
UTF8String.fromString(sb.toString)
}
override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, (input: String) => {
val sb = ctx.freshName("sb")
val length = ctx.freshName("length")
val offset = ctx.freshName("offset")
val inputString = ctx.freshName("inputString")
val startOfMask = ctx.freshName("startOfMask")
s"""
|String $inputString = $input.toString();
|${inputStringLengthCode(inputString, length)}
|${CodeGenerator.JAVA_INT} $startOfMask = $charCount > $length ? $length : $charCount;
|${CodeGenerator.JAVA_INT} $offset = 0;
|StringBuilder $sb = new StringBuilder($length);
|${appendUnchangedToStringBuilderCode(ctx, sb, inputString, offset, startOfMask)}
|${appendMaskedToStringBuilderCode(
ctx, sb, inputString, offset, s"$length - $startOfMask")}
|${ev.value} = UTF8String.fromString($sb.toString());
|""".stripMargin
})
}
override def dataType: DataType = StringType
override def inputTypes: Seq[AbstractDataType] = Seq(StringType)
override def prettyName: String = "mask_show_first_n"
}
/**
* Masks all but the last N chars of the input string. N defaults to 4. Additional parameters can
* be set to change the masking chars for uppercase letters, lowercase letters and digits.
*/
// scalastyle:off line.size.limit
@ExpressionDescription(
usage = "_FUNC_(str[, n[, upper[, lower[, digit]]]]) - Masks all but the last n values of str. By default, n is 4, upper case letters are converted to \\"X\\", lower case letters are converted to \\"x\\" and numbers are converted to \\"n\\". You can override the characters used in the mask by supplying additional arguments: the second argument controls the mask character for upper case letters, the third argument for lower case letters and the fourth argument for numbers.",
examples = """
Examples:
> SELECT _FUNC_("1234-5678-8765-4321", 4);
nnnn-nnnn-nnnn-4321
""", since = "2.4.0")
// scalastyle:on line.size.limit
case class MaskShowLastN(
child: Expression,
n: Int,
upper: String,
lower: String,
digit: String)
extends UnaryExpression with ExpectsInputTypes with MaskLikeWithN {
def this(child: Expression) =
this(child, defaultCharCount, null, null, null)
def this(child: Expression, n: Expression) =
this(child, extractCharCount(n), null, null, null)
def this(child: Expression, n: Expression, upper: Expression) =
this(child, extractCharCount(n), extractReplacement(upper), null, null)
def this(child: Expression, n: Expression, upper: Expression, lower: Expression) =
this(child, extractCharCount(n), extractReplacement(upper), extractReplacement(lower), null)
def this(
child: Expression,
n: Expression,
upper: Expression,
lower: Expression,
digit: Expression) =
this(child,
extractCharCount(n),
extractReplacement(upper),
extractReplacement(lower),
extractReplacement(digit))
override def nullSafeEval(input: Any): Any = {
val str = input.asInstanceOf[UTF8String].toString
val length = str.codePointCount(0, str.length())
val endOfMask = if (charCount >= length) 0 else length - charCount
val sb = new java.lang.StringBuilder(length)
val offset = appendMaskedToStringBuilder(sb, str, 0, endOfMask)
appendUnchangedToStringBuilder(sb, str, offset, length - endOfMask)
UTF8String.fromString(sb.toString)
}
override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, (input: String) => {
val sb = ctx.freshName("sb")
val length = ctx.freshName("length")
val offset = ctx.freshName("offset")
val inputString = ctx.freshName("inputString")
val endOfMask = ctx.freshName("endOfMask")
s"""
|String $inputString = $input.toString();
|${inputStringLengthCode(inputString, length)}
|${CodeGenerator.JAVA_INT} $endOfMask = $charCount >= $length ? 0 : $length - $charCount;
|${CodeGenerator.JAVA_INT} $offset = 0;
|StringBuilder $sb = new StringBuilder($length);
|${appendMaskedToStringBuilderCode(ctx, sb, inputString, offset, endOfMask)}
|${appendUnchangedToStringBuilderCode(
ctx, sb, inputString, offset, s"$length - $endOfMask")}
|${ev.value} = UTF8String.fromString($sb.toString());
|""".stripMargin
})
}
override def dataType: DataType = StringType
override def inputTypes: Seq[AbstractDataType] = Seq(StringType)
override def prettyName: String = "mask_show_last_n"
}
/**
* Returns a hashed value based on str.
*/
// scalastyle:off line.size.limit
@ExpressionDescription(
usage = "_FUNC_(str) - Returns a hashed value based on str. The hash is consistent and can be used to join masked values together across tables.",
examples = """
Examples:
> SELECT _FUNC_("abcd-EFGH-8765-4321");
60c713f5ec6912229d2060df1c322776
""")
// scalastyle:on line.size.limit
case class MaskHash(child: Expression)
extends UnaryExpression with ExpectsInputTypes {
override def nullSafeEval(input: Any): Any = {
UTF8String.fromString(DigestUtils.md5Hex(input.asInstanceOf[UTF8String].toString))
}
override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, (input: String) => {
val digestUtilsClass = classOf[DigestUtils].getName.stripSuffix("$")
s"""
|${ev.value} = UTF8String.fromString($digestUtilsClass.md5Hex($input.toString()));
|""".stripMargin
})
}
override def dataType: DataType = StringType
override def inputTypes: Seq[AbstractDataType] = Seq(StringType)
override def prettyName: String = "mask_hash"
}
|
lxsmnv/spark
|
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/maskExpressions.scala
|
Scala
|
apache-2.0
| 22,957 |
package gie.app.gbb.model.import_export
object ImportImpl {
def apply(inRoot: java.io.File) = ImportImpl00(inRoot)
}
|
igorge/gbb
|
src/main/scala/code/model/export_import/import.scala
|
Scala
|
gpl-2.0
| 123 |
package io.aos.ebnf.spl.semantic
import io.aos.ebnf.spl.semantic.DataSourceMetadata;
import io.aos.ebnf.spl.semantic.SplSemanticAnalyzer;
import org.scalatest.junit.ShouldMatchersForJUnit
import org.scalatest.junit.JUnitSuite
import org.junit.Test
import io.aos.ebnf.spl.ast._
import io.aos.ebnf.spl.parser.SplParser
import org.junit.Before
class BugTest extends JUnitSuite with ShouldMatchersForJUnit {
@Before def setup() {
DataSourceMetadata.registerUpdater(OfflineDataSourceMetadata.load)
}
@Test def testComplexWhere() {
val ast = SplParser.generateTree("SELECT visitorid,conversionvisits.conversionvalue,urls.URL WHERE (conversionflag NOT EXISTS) AND (urls.URL IN ('url') OR NOT urls.timestamp > '2012-02-01') USING customer2.visitors")
val annotatedAst = SplSemanticAnalyzer.buildAnnotatedSyntaxTree(ast.get)
annotatedAst.isRight should be(true)
val q = annotatedAst.right.get
q should equal(
SelectQuery(
Some(List(TypedField("visitorid", DataType.StringType), TypedField("conversionvisits.conversionvalue", DataType.DoubleType, Some("conversionvisits")), TypedField("urls.URL", DataType.StringType, Some("urls")))),
WhereClause(
TypedAndOperator(
TypedCondition(TypedField("conversionflag", DataType.BooleanType), ExistsOperator(true), None),
TypedOrNotOperator(
TypedCondition(TypedField("urls.URL", DataType.StringType, Some("urls")), InOperator(List("url"), false), None),
TypedCondition(TypedField("urls.timestamp", DataType.DateType, Some("urls")), ComparisonOperator(">", "2012-02-01"), None),
Some("urls")),
None)),
DataSource("customer2-visitors")))
}
}
|
echalkpad/t4f-data
|
parser/ebnf/src/test/scala/io/aos/ebnf/spl/semantic/BugTest.scala
|
Scala
|
apache-2.0
| 1,732 |
/*
* Copyright 2001-2013 Artima, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.scalactic
import org.scalatest._
import scala.collection.GenSeq
import scala.collection.GenMap
import scala.collection.GenSet
import scala.collection.GenIterable
import scala.collection.GenTraversable
import scala.collection.GenTraversableOnce
class FreshConversionCheckedSeqEqualityConstraintsSpec extends Spec with NonImplicitAssertions with CheckedEquality {
// TODO: Need to explicitly enable the implicit conversion
case class Super(size: Int)
class Sub(sz: Int) extends Super(sz)
val super1: Super = new Super(1)
val sub1: Sub = new Sub(1)
val super2: Super = new Super(2)
val sub2: Sub = new Sub(2)
val nullSuper: Super = null
case class Fruit(name: String)
class Apple extends Fruit("apple")
class Orange extends Fruit("orange")
implicit class IntWrapper(val value: Int) {
override def equals(o: Any): Boolean =
o match {
case that: IntWrapper => this.value == that.value
case _ => false
}
override def hashCode: Int = value.hashCode
}
object `the SeqEqualityConstraints trait` {
def `should allow any Seq to be compared with any other Seq, so long as the element types of the two Seq's have a recursive EqualityConstraint` {
assert(Vector(1, 2, 3) === List(1, 2, 3))
assert(Vector(1, 2, 3) === List(1L, 2L, 3L))
assert(Vector(1L, 2L, 3L) === List(1, 2, 3))
// Test for something convertible
assertTypeError("Vector(new IntWrapper(1), new IntWrapper(2), new IntWrapper(3)) === List(1, 2, 3)")
assertTypeError("Vector(1, 2, 3) === List(new IntWrapper(1), new IntWrapper(2), new IntWrapper(3))")
assert(Vector(new Apple, new Apple) === List(new Fruit("apple"), new Fruit("apple")))
assert(List(new Fruit("apple"), new Fruit("apple")) === Vector(new Apple, new Apple))
assertTypeError("Vector(new Apple, new Apple) === List(new Orange, new Orange)")
assertTypeError("List(new Orange, new Orange) === Vector(new Apple, new Apple)")
}
def `should allow an Array to be compared with any other Seq, so long as the element types of the two objects have a recursive EqualityConstraint` {
assert(Array(1, 2, 3) === List(1, 2, 3))
assert(Array(1, 2, 3) === List(1L, 2L, 3L))
assert(Array(1L, 2L, 3L) === List(1, 2, 3))
// Test for something convertible
assertTypeError("Array(new IntWrapper(1), new IntWrapper(2), new IntWrapper(3)) === List(1, 2, 3)")
assertTypeError("Array(1, 2, 3) === List(new IntWrapper(1), new IntWrapper(2), new IntWrapper(3))")
assert(Array(new Apple, new Apple) === List(new Fruit("apple"), new Fruit("apple")))
assert(Array(new Fruit("apple"), new Fruit("apple")) === Vector(new Apple, new Apple))
assertTypeError("Array(new Apple, new Apple) === List(new Orange, new Orange)")
assertTypeError("Array(new Orange, new Orange) === Vector(new Apple, new Apple)")
}
def `should allow any Seq to be compared with an Array, so long as the element types of the two objects have a recursive EqualityConstraint` {
assert(Vector(1, 2, 3) === Array(1, 2, 3))
assert(Vector(1, 2, 3) === Array(1L, 2L, 3L))
assert(Vector(1L, 2L, 3L) === Array(1, 2, 3))
// Test for something convertible
assertTypeError("Vector(new IntWrapper(1), new IntWrapper(2), new IntWrapper(3)) === Array(1, 2, 3)")
assertTypeError("Vector(1, 2, 3) === Array(new IntWrapper(1), new IntWrapper(2), new IntWrapper(3))")
assert(Vector(new Apple, new Apple) === Array(new Fruit("apple"), new Fruit("apple")))
assert(List(new Fruit("apple"), new Fruit("apple")) === Array(new Apple, new Apple))
assertTypeError("Vector(new Apple, new Apple) === Array(new Orange, new Orange)")
assertTypeError("List(new Orange, new Orange) === Array(new Apple, new Apple)")
}
}
}
|
travisbrown/scalatest
|
src/test/scala/org/scalactic/FreshConversionCheckedSeqEqualityConstraintsSpec.scala
|
Scala
|
apache-2.0
| 4,443 |
package changestream
import java.io.File
import akka.actor.{Props}
import akka.testkit.TestProbe
import changestream.actors.PositionSaver._
import changestream.actors.{PositionSaver, StdoutActor}
import changestream.events.{Delete, Insert, MutationWithInfo, Update}
import changestream.helpers.{Config, Database, Fixtures}
import com.github.mauricio.async.db.RowData
import com.typesafe.config.ConfigFactory
import scala.language.postfixOps
import akka.pattern.ask
import spray.json._
import scala.concurrent.duration._
import scala.concurrent.Await
import scala.io.Source
import scala.util.Random
class ChangeStreamISpec extends Database with Config {
// Bootstrap the config
val tempFile = File.createTempFile("positionSaverISpec", ".pos")
System.setProperty("config.resource", "test.conf")
System.setProperty("MYSQL_SERVER_ID", Random.nextLong.toString)
System.setProperty("POSITION_SAVER_FILE_PATH", tempFile.getPath)
System.setProperty("POSITION_SAVER_MAX_RECORDS", "2")
System.setProperty("POSITION_SAVER_MAX_WAIT", "100000")
ConfigFactory.invalidateCaches()
// Wire in the probes
lazy val positionSaver = ChangeStreamEventListener.system.actorOf(Props(new PositionSaver()), name = "positionSaverActor")
lazy val emitter = ChangeStreamEventListener.system.actorOf(Props(new StdoutActor(_ => positionSaver)), name = "emitterActor")
val emitterProbe = TestProbe()
// Create the app thread
val app = new Thread {
override def run = ChangeStream.main(Array())
override def interrupt = {
Await.result(ChangeStreamEventListener.shutdown(), 60 seconds)
super.interrupt
}
}
override def beforeAll(): Unit = {
ChangeStreamEventListener.setPositionSaver(positionSaver)
ChangeStreamEventListener.setEmitter(emitterProbe.ref)
app.start
ensureConnected
super.beforeAll()
}
override def afterAll(): Unit = {
tempFile.delete()
super.afterAll()
}
def ensureConnected = {
Thread.sleep(500)
var c = 0
while(!ChangeStream.isConnected && c < 50) {
Thread.sleep(100)
c += 1
}
}
def ensureDisconnected = {
Thread.sleep(500)
var c = 0
while(ChangeStream.isConnected && c < 50) {
Thread.sleep(100)
c += 1
}
}
def expectMutation:MutationWithInfo = {
val message = emitterProbe.expectMsgType[MutationWithInfo](5000.milliseconds)
emitterProbe.forward(emitter)
message
}
def getLiveBinLogPosition: String = {
val result = Await.result(connection.sendQuery("show master status;"), 5000.milliseconds)
result.rows match {
case Some(resultSet) => {
val row : RowData = resultSet.head
val file = row("File").asInstanceOf[String]
val position = row("Position").asInstanceOf[Long]
s"${file}:${position}"
}
case None =>
throw new Exception("Couldn't get binlog position")
}
}
def getStoredBinLogPosition: String = {
val bufferedSource = Source.fromFile(tempFile, "UTF-8")
val position = bufferedSource.getLines.mkString
bufferedSource.close
position
}
def assertValidEvent( //scalastyle:ignore
mutation: String,
database: String = "changestream_test",
table: String = "users",
queryRowCount: Int = 1,
transactionCurrentRow: Int = 1,
primaryKeyField: String = "id",
currentRow: Int = 1,
sql: Option[String] = None,
isLastMutation: Boolean = false
): Unit = {
val message = expectMutation
message.formattedMessage.isDefined should be(true)
val json = message.formattedMessage.get.parseJson.asJsObject.fields
json("mutation") should equal(JsString(mutation))
json should contain key ("sequence")
json("database") should equal(JsString(database))
json("table") should equal(JsString(table))
json("transaction").asJsObject.fields("current_row") should equal(JsNumber(transactionCurrentRow))
if(isLastMutation) {
json("transaction").asJsObject.fields("last_mutation") should equal(JsTrue)
} else {
json("transaction").asJsObject.fields.keys shouldNot contain("last_mutation")
}
json("query").asJsObject.fields("timestamp").asInstanceOf[JsNumber].value.toLong.compareTo(Fixtures.timestamp - 60000) should be(1)
json("query").asJsObject.fields("row_count") should equal(JsNumber(queryRowCount))
json("query").asJsObject.fields("current_row") should equal(JsNumber(currentRow))
if(sql != None) {
json("query").asJsObject.fields("sql") should equal(JsString(sql.get.trim))
}
json("primary_key").asJsObject.fields.keys should contain(primaryKeyField)
}
def validateNoEvents = emitterProbe.expectNoMessage(5 seconds)
def waitAndClear(count: Int = 1) = {
(1 to count).foreach(idx =>
expectMutation
)
}
"when handling an INSERT statement" should {
"affecting a single row, generates a single insert event" in {
queryAndWait(INSERT)
assertValidEvent("insert", sql = Some(INSERT), isLastMutation = true)
}
}
"when handling an INSERT statement" should {
"affecting multiple rows, generates multiple insert events" in {
queryAndWait(INSERT_MULTI)
assertValidEvent("insert", queryRowCount = 2, currentRow = 1, transactionCurrentRow = 1, sql = Some(INSERT_MULTI))
assertValidEvent("insert", queryRowCount = 2, currentRow = 2, transactionCurrentRow = 2, sql = Some(INSERT_MULTI), isLastMutation = true)
}
}
"when handling an UPDATE statement" should {
"affecting a single row, generates a single update event" in {
queryAndWait(INSERT)
waitAndClear()
queryAndWait(UPDATE)
assertValidEvent("update", sql = Some(UPDATE), isLastMutation = true)
}
}
"when handling an UPDATE statement" should {
"affecting multiple rows" in {
queryAndWait(INSERT_MULTI)
waitAndClear(2)
queryAndWait(UPDATE_ALL)
assertValidEvent("update", queryRowCount = 2, currentRow = 1, transactionCurrentRow = 1, sql = Some(UPDATE_ALL))
assertValidEvent("update", queryRowCount = 2, currentRow = 2, transactionCurrentRow = 2, sql = Some(UPDATE_ALL), isLastMutation = true)
}
}
"when handling an DELETE statement" should {
"affecting a single row, generates a single delete event" in {
queryAndWait(INSERT)
waitAndClear()
queryAndWait(DELETE)
assertValidEvent("delete", sql = Some(DELETE), isLastMutation = true)
}
"affecting multiple rows" in {
queryAndWait(INSERT)
queryAndWait(INSERT)
waitAndClear(2)
queryAndWait(DELETE_ALL)
assertValidEvent("delete", queryRowCount = 2, currentRow = 1, transactionCurrentRow = 1, sql = Some(DELETE_ALL))
assertValidEvent("delete", queryRowCount = 2, currentRow = 2, transactionCurrentRow = 2, sql = Some(DELETE_ALL), isLastMutation = true)
}
}
"when doing things in a transaction" should {
"a successfully committed transaction" should {
"buffers one change event to be able to properly tag the last event ina transaction" in {
queryAndWait("begin")
queryAndWait(INSERT)
queryAndWait(INSERT)
queryAndWait(UPDATE_ALL)
queryAndWait(DELETE_ALL)
validateNoEvents
queryAndWait("commit")
assertValidEvent("insert", queryRowCount = 1, transactionCurrentRow = 1, currentRow = 1, sql = Some(INSERT))
assertValidEvent("insert", queryRowCount = 1, transactionCurrentRow = 2, currentRow = 1, sql = Some(INSERT))
assertValidEvent("update", queryRowCount = 2, transactionCurrentRow = 3, currentRow = 1, sql = Some(UPDATE_ALL))
assertValidEvent("update", queryRowCount = 2, transactionCurrentRow = 4, currentRow = 2, sql = Some(UPDATE_ALL))
assertValidEvent("delete", queryRowCount = 2, transactionCurrentRow = 5, currentRow = 1, sql = Some(DELETE_ALL))
assertValidEvent("delete", queryRowCount = 2, transactionCurrentRow = 6, currentRow = 2, sql = Some(DELETE_ALL), isLastMutation = true)
}
}
"a rolled back transaction" should {
"generates no change events" in {
queryAndWait("begin")
queryAndWait(INSERT)
queryAndWait(INSERT)
queryAndWait(UPDATE_ALL)
queryAndWait(DELETE_ALL)
queryAndWait("rollback")
validateNoEvents
}
}
}
"when starting up" should {
"start from 'real time' when there is no last known position" in {
ChangeStream.disconnectClient
Await.result(positionSaver ? SavePositionRequest(None), 1000 milliseconds)
queryAndWait(INSERT)
ChangeStream.getConnectedAndWait(None)
ensureConnected
queryAndWait(UPDATE)
expectMutation.mutation shouldBe a[Update]
}
"start reading from the last known position when there is a last known position and no override is passed" in {
ChangeStream.disconnectClient
Await.result(positionSaver ? SavePositionRequest(Some(getLiveBinLogPosition)), 1000 milliseconds)
queryAndWait(INSERT)
ChangeStream.getConnectedAndWait(None)
ensureConnected
queryAndWait(UPDATE)
expectMutation.mutation shouldBe a[Insert]
expectMutation.mutation shouldBe a[Update]
}
"start from override when override is passed" in {
ChangeStream.disconnectClient
Await.result(positionSaver ? SavePositionRequest(Some(getLiveBinLogPosition)), 1000 milliseconds)
// this event should be skipped due to the override
queryAndWait(INSERT)
val overridePosition = getLiveBinLogPosition
// this event should arrive first
queryAndWait(UPDATE)
ChangeStream.getConnectedAndWait(Some(overridePosition))
ensureConnected
// advance the live position to be "newer" than the override (should arrive second)
queryAndWait(DELETE)
expectMutation.mutation shouldBe a[Update]
expectMutation.mutation shouldBe a[Delete]
}
"exit gracefully when a TERM signal is received" in {
ChangeStream.disconnectClient
Await.result(positionSaver ? SavePositionRequest(Some(getLiveBinLogPosition)), 1000 milliseconds)
val startingPosition = getStoredBinLogPosition
ChangeStream.getConnectedAndWait(None)
ensureConnected
queryAndWait(INSERT) // should not persist immediately because of the max events = 2
val insertMutation = expectMutation
insertMutation.mutation shouldBe a[Insert]
Thread.sleep(1000)
getStoredBinLogPosition should be(startingPosition)
ChangeStream.disconnectClient
ensureDisconnected
Await.result(ChangeStreamEventListener.persistPosition, 60.seconds)
getStoredBinLogPosition should be(insertMutation.nextPosition)
queryAndWait(UPDATE) // should not immediately persist
ChangeStream.getConnectedAndWait(None)
ensureConnected
queryAndWait(DELETE) // should persist because it is the second event processed by the saver
queryAndWait(INSERT) // should not immediately persist
expectMutation.mutation shouldBe a[Update]
expectMutation.mutation shouldBe a[Delete]
//at this point, our saved position is not fully up to date
val finalMutation = expectMutation
finalMutation.mutation shouldBe a[Insert]
getStoredBinLogPosition shouldNot be(finalMutation.nextPosition)
app.interrupt
//should save any pending position pre-exit
getStoredBinLogPosition should be(finalMutation.nextPosition)
}
}
}
|
mavenlink/changestream
|
src/test/scala/changestream/ChangeStreamISpec.scala
|
Scala
|
mit
| 11,685 |
package com.tajpure.scheme.compiler.parser
import com.tajpure.scheme.compiler.Constants
import com.tajpure.scheme.compiler.ast.Bool
import com.tajpure.scheme.compiler.ast.Delimeter
import com.tajpure.scheme.compiler.ast.FloatNum
import com.tajpure.scheme.compiler.ast.IntNum
import com.tajpure.scheme.compiler.ast.Node
import com.tajpure.scheme.compiler.ast.Str
import com.tajpure.scheme.compiler.ast.Symbol
import com.tajpure.scheme.compiler.exception.ParserException
import com.tajpure.scheme.compiler.util.FileUtils
import com.tajpure.scheme.compiler.util.Log
import com.tajpure.scheme.compiler.ast.CharNum
import com.tajpure.scheme.compiler.ast.Quote
class LexParser(_source:String, _path: String) {
def this(_path: String) {
this(null, _path)
}
var offset: Int = 0
var row: Int = 0
var col: Int = 0
val source: String = _source match {
case null => FileUtils.read(_path)
case "" => FileUtils.read(_path)
case default => _source
}
val file: String = FileUtils.unifyPath(_path)
if (source == null) {
Log.error("failed to read the file:" + file)
}
Delimeter.addDelimiterPair(Constants.PAREN_BEGIN, Constants.PAREN_END)
def forward() {
if (source.charAt(offset) != '\\n') {
col += 1
} else {
row += 1
col = 0
}
offset += 1
}
def skip(n: Int) {
(1 to n).foreach( _ => forward())
}
def skipSpacesAndTab(): Boolean = {
if (offset < source.length && (source.charAt(offset) == ' ' || source.charAt(offset) == '\\t')) {
skip(1)
skipSpacesAndTab()
true
}
else {
false
}
}
def skipComments(): Boolean = {
if (source.startsWith(Constants.COMMENTS, offset)) {
while (offset < source.length && source.charAt(offset) != '\\n') {
skip(1)
}
if (offset < source.length) {
forward();
}
true
}
else {
false
}
}
def skipEnter(): Boolean = {
if (offset < source.length && (source.charAt(offset) == '\\r' || source.charAt(offset) == '\\n')) {
forward()
true
} else {
false
}
}
def skipSpacesAndComments() {
if (skipSpacesAndTab() || skipComments() || skipEnter()) {
skipSpacesAndComments()
}
}
def scanString(): Node = {
val start: Int = offset
val startRow: Int = row
val startCol: Int = col
skip(Constants.STRING_BEGIN.length())
def loop() {
if (offset >= source.length() || source.charAt(offset) == '\\n') {
throw new ParserException("string format error:", startRow, startCol, offset);
}
else if (source.startsWith(Constants.STRING_END, offset)) {
skip(Constants.STRING_END.length())
}
else {
forward()
loop()
}
}
loop()
val end: Int = offset
val content: String = source.substring(start + Constants.STRING_BEGIN.length(), end - Constants.STRING_END.length())
new Str(content, file, start, end, row, col)
}
def scanChar(): Node = {
val start: Int = offset
val startRow: Int = row
val startCol: Int = col
skip(Constants.CHAR_PREFIX.length())
if (source.charAt(offset) == ' ') {
skip(1)
}
else if (Character.isLetter(source.charAt(offset))) {
def loop() {
if (Character.isLetter(source.charAt(offset))) {
skip(1)
loop()
}
}
loop()
}
else {
throw new ParserException("character can't be null", startRow, startCol, offset)
}
val end: Int = offset
val content: String = source.substring(start, end)
new CharNum(content, file, start, end, row, col)
}
def isNumberOrChar(ch: Char): Boolean = {
Character.isLetterOrDigit(ch) || ch == '.' || ch == '+' || ch == '-'
}
def scanNumber(): Node = {
val start: Int = offset
val startRow: Int = row
val startCol: Int = col
var isInt: Boolean = true
def loop() {
if (offset > source.length()) {
throw new ParserException("number format error", startRow, startCol, offset)
}
else if (offset == source.length()) {
// avoid string index out of range
}
else if (isNumberOrChar(source.charAt(offset))) {
if (source.charAt(offset) == '.') {
isInt = false
}
forward()
loop()
}
}
loop()
val end: Int = offset
val content: String = source.substring(start, end)
if (isInt) {
new IntNum(content, file, start, end, startRow, startCol)
}
else {
new FloatNum(content, file, start, end, startRow, startCol)
}
}
def scanQuote(): Node = {
val start: Int = offset
val startRow: Int = row
val startCol: Int = col
def loop() {
if (offset < source.length && (source.charAt(offset) == Constants.QUOTE)) {
skip(1)
loop()
}
else if (offset < source.length && source.startsWith(Constants._QUOTE, offset)) {
skip(Constants._QUOTE.length())
loop()
}
}
loop()
val end: Int = offset
val content: String = source.substring(start, end)
new Quote(content, file, start, end, row, col)
}
def isIdentifierChar(ch: Char): Boolean = {
Character.isLetterOrDigit(ch) || Constants.IDENT_CHARS.contains(ch)
}
def scanSymbol(): Node = {
val start: Int = offset
val startRow: Int = row
val startCol: Int = col
def loop() {
if (offset < source.length && isIdentifierChar(source.charAt(offset))) {
forward()
loop()
}
}
loop()
val content = source.substring(start, offset)
new Symbol(content, file, start, offset, startRow, startCol)
}
@throws(classOf[ParserException])
def nextToken(): Node = {
skipSpacesAndComments()
if (offset >= source.length()) {
null
}
else {
val cur = source.charAt(offset)
if (Delimeter.isDelimiter(cur)) {
val ret: Node = new Delimeter(Character.toString(cur), file, offset, offset + 1, row, col)
forward()
ret
}
else if (source.startsWith(Constants.STRING_BEGIN, offset)) {
scanString()
}
else if (source.charAt(offset) == Constants.QUOTE || source.startsWith(Constants._QUOTE, offset)) {
scanQuote()
}
else if (Character.isDigit(source.charAt(offset)) ||
((source.charAt(offset) == '+' || source.charAt(offset) == '-')
&& offset + 1 < source.length() && Character.isDigit(source.charAt(offset + 1)))) {
scanNumber()
}
else if (source.startsWith(Constants.CHAR_PREFIX, offset)) {
scanChar()
}
else if (isIdentifierChar(source.charAt(offset))) {
scanSymbol()
}
else {
throw new ParserException("unrecognized syntax: " + source.substring(offset, offset + 1),
row, col, offset)
}
}
}
}
//object LexParser extends App {
//
// def lex(source: String): String = {
// val lexer: LexParser = new LexParser(source, "/visual")
// var tokens: List[Node] = List[Node]()
// var n: Node = lexer.nextToken()
//
// def loop() {
// if (n != null) {
// tokens = tokens :+ n
// try {
// n = lexer.nextToken()
// loop()
// }
// catch {
// case pe: ParserException => Log.error(pe.toString())
// case e: Exception => Log.error(e.toString())
// }
// }
// }
// loop()
// tokens.toString()
// }
//
// println(lex("(define x 1)"))
//
//}
|
tajpure/SoScheme
|
src/main/scala/com/tajpure/scheme/compiler/parser/LexParser.scala
|
Scala
|
gpl-3.0
| 7,600 |
/*
* Copyright 2016 Uncharted Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package software.uncharted.sparkpipe.ops.community.twitter.entities
import org.scalatest._
class PackageSpec extends FunSpec {
describe("ops.community.twitter.entities") {
}
}
|
unchartedsoftware/sparkpipe-twitter-ops
|
src/test/scala/software/uncharted/sparkpipe/ops/community/twitter/entities/packageSpec.scala
|
Scala
|
apache-2.0
| 790 |
/*
* Copyright 2016 Dennis Vriend
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.dnvriend
import scalaz._
import Scalaz._
object Person {
def validateNonEmpty(fieldName: String, value: String): ValidationNel[String, String] =
Option(value).filter(_.trim.nonEmpty).toSuccessNel(s"Field '$fieldName' must not be empty")
def validateName(name: String): ValidationNel[String, String] =
validateNonEmpty("name", name)
def validateGt(fieldName: String, maxValue: Int, value: Int): ValidationNel[String, Int] =
Option(value).filter(_ > maxValue).toSuccessNel(s"Field '$fieldName' with value '$value' must be greater than '$maxValue'")
def validateLt(fieldName: String, maxValue: Int, value: Int): ValidationNel[String, Int] =
Option(value).filter(_ < maxValue).toSuccessNel(s"Field '$fieldName' with value '$value' must be less than '$maxValue'")
def validateAge(age: Int): ValidationNel[String, Int] =
validateGt("age", -1, age) *> validateLt("age", 140, age)
def validate(name: String, age: Int): ValidationNel[String, Person] =
(validateName(name) |@| validateAge(age))(Person.apply)
}
final case class Person(name: String, age: Int)
|
dnvriend/study-category-theory
|
typeclasses/src/test/scala/com/github/dnvriend/Person.scala
|
Scala
|
apache-2.0
| 1,710 |
package minCostFlow
import optimus.optimization._
object Graph {
type Vertex = Int
type Vertices = IndexedSeq[Vertex]
type Edge = Int
type Supply = IndexedSeq[Int]
type Edges = IndexedSeq[(Vertex, Vertex)]
type CostValue = Int
type Cost = IndexedSeq[CostValue]
type ReducedCost = Cost
type Capacity = IndexedSeq[Int]
type Flow = IndexedSeq[Int]
type Potential = IndexedSeq[Int]
type Excess = IndexedSeq[Int]
type Cut = Seq[Int]
def getSource(edge: Edge, edges: IndexedSeq[(Vertex, Vertex)]): Vertex = edges(edge)._1
def getTarget(edge: Edge, edges: IndexedSeq[(Vertex, Vertex)]): Vertex = edges(edge)._2
case class Simple(supply: Supply, edges: Edges, cost: Cost, capacity: Capacity) extends Graph
}
trait Graph {
import Graph._
val supply : Supply
val edges : Edges
val cost : Cost
val capacity : Capacity
def createIntegerProgram(): (MIProblem, IndexedSeq[MPIntVar]) = {
import optimus.algebra._
implicit val problem = MIProblem(SolverLib.gurobi)
val flow = Range(0, edges.length).map {
case i =>
MPIntVar("flow" + i, Range(0, capacity(i) + 1))
// using a float var improves performance on last year's data
// from 1.5 s to 1.2 sec, which isn't significant enough.
// MPFloatVar("flow" + i, 0.0, capacity(i))
}
val flowWithIndex = flow.zipWithIndex
val capacityConstraints = for ((x, i) <- flowWithIndex) yield x <= capacity(i)
val edgesWithIndex = edges.zipWithIndex
val supplyConstraints = for {
v <- 0 until supply.length
outgoingFlow = (for { ((u, w), i) <- edgesWithIndex ; if u == v } yield flow(i)).fold[Expression](0)(_ + _)
incomingFlow = (for { ((u, w), i) <- edgesWithIndex ; if w == v } yield flow(i)).fold[Expression](0)(_ + _)
}
yield outgoingFlow - incomingFlow := supply(v)
val constraints = capacityConstraints ++ supplyConstraints
minimize { (for ((x, i) <- flowWithIndex) yield x * cost(i)).fold[Expression](0)(_ + _) }
subjectTo(constraints: _*)
(problem, flow)
}
}
|
yfcai/tutorial-assignment
|
main/minCostFlow.Graph.scala
|
Scala
|
unlicense
| 2,145 |
/* Copyright (C) 2008-2014 University of Massachusetts Amherst.
This file is part of "FACTORIE" (Factor graphs, Imperative, Extensible)
http://factorie.cs.umass.edu, http://github.com/factorie
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
package cc.factorie.app.nlp.phrase
import java.io._
import cc.factorie.app.chain.ChainModel
import cc.factorie.app.chain.Observations._
import cc.factorie.app.nlp._
import cc.factorie.app.nlp.load._
import cc.factorie.app.nlp.pos.PennPosTag
import cc.factorie.optimize.Trainer
import cc.factorie.util.{BinarySerializer, HyperparameterMain}
import cc.factorie.variable._
import scala.io.Source
import scala.reflect.ClassTag
/**
* User: cellier
* Date: 10/7/13
* Time: 2:49 PM
* Chunker based on Sha & Pereira '03 using a linear chain crf.
*/
/*
* Takes as a type parameter an extension from load.Load2000.ChunkTag
* BILOUChunkTag and BIOChunkTag can be trained using conll2000 data
* NestedChunkTag requires custom data tagged in the BILOUNestedChunkDomain notation
* For NP retrieval of the tags generated by this class, app.nlp.mention.NPChunkMentionFinder can be used
*/
class ChainChunker[L<:ChunkTag](chunkDomain: CategoricalDomain[String], newChunkLabel: (Token) => L)(implicit m: ClassTag[L]) extends DocumentAnnotator {
def process(document: Document) = {
document.sentences.foreach(s => {
if (s.nonEmpty) {
s.tokens.foreach(t => if (!t.attr.contains(m.runtimeClass)) t.attr += newChunkLabel(t))
features(s)
model.maximize(s.tokens.map(_.attr[L]))(null)
}
})
document
}
def prereqAttrs = Seq(classOf[Token], classOf[Sentence],classOf[PennPosTag])
def postAttrs = Seq(m.runtimeClass)
def tokenAnnotationString(token: Token) = { val label = token.attr[L]; if (label ne null) label.categoryValue else "(null)" }
def serialize(stream: OutputStream) {
import cc.factorie.util.CubbieConversions._
val dstream = new DataOutputStream(stream)
BinarySerializer.serialize(ChunkFeaturesDomain.dimensionDomain, dstream)
BinarySerializer.serialize(model, dstream)
dstream.close()
}
def deserialize(stream: InputStream) {
import cc.factorie.util.CubbieConversions._
val dstream = new DataInputStream(stream)
BinarySerializer.deserialize(ChunkFeaturesDomain.dimensionDomain, dstream)
BinarySerializer.deserialize(model, dstream)
dstream.close()
}
def train(trainSentences:Seq[Sentence], testSentences:Seq[Sentence], useFullFeatures:Boolean = false, lrate:Double = 0.1, decay:Double = 0.01, cutoff:Int = 2, doBootstrap:Boolean = true, useHingeLoss:Boolean = false, numIterations: Int = 5, l1Factor:Double = 0.000001, l2Factor:Double = 0.000001)(implicit random: scala.util.Random) {
ChunkFeaturesDomain.setFeatureSet(useFullFeatures)
trainSentences.foreach(s=>features(s))
print("Features for Training Generated: ")
if(useFullFeatures) println("Full Set") else println("Subset Set")
ChunkFeaturesDomain.freeze()
testSentences.foreach(features)
def evaluate() {
(trainSentences ++ testSentences).foreach(s => model.maximize(s.tokens.map(_.attr[L]))(null))
val segmentEvaluation = new cc.factorie.app.chain.SegmentEvaluation[L](chunkDomain.categories.filter(_.length > 2).map(_.substring(2)))
for (sentence <- testSentences) segmentEvaluation += sentence.tokens.map(_.attr[L])
println(segmentEvaluation)
println("Train accuracy: "+ HammingObjective.accuracy(trainSentences.flatMap(s => s.tokens.map(_.attr[L]))))
println("Test accuracy: "+ HammingObjective.accuracy(testSentences.flatMap(s => s.tokens.map(_.attr[L]))))
}
val examples = trainSentences.map(sentence => new model.ChainStructuredSVMExample(sentence.tokens.map(_.attr[L]))).toSeq
val optimizer = new cc.factorie.optimize.AdaGradRDA(rate=lrate, l1=l1Factor/examples.length, l2=l2Factor/examples.length)
Trainer.onlineTrain(model.parameters, examples, maxIterations=numIterations, optimizer=optimizer, evaluate=evaluate, useParallelTrainer = false)
}
object ChunkFeaturesDomain extends CategoricalVectorDomain[String]{var fullFeatureSet: Boolean = false; def setFeatureSet(full:Boolean){fullFeatureSet = full}}
class ChunkFeatures(val token:Token) extends BinaryFeatureVectorVariable[String] { def domain = ChunkFeaturesDomain; override def skipNonCategories = true }
val model = new ChainModel[ChunkTag, ChunkFeatures, Token](chunkDomain,
ChunkFeaturesDomain,
l => l.token.attr[ChunkFeatures],
l => l.token,
t => t.attr[L]){
useObsMarkov = false
}
def features(sentence: Sentence): Unit = {
import cc.factorie.app.strings.simplifyDigits
val tokens = sentence.tokens.zipWithIndex
for ((token,i) <- tokens) {
if(token.attr[ChunkFeatures] ne null)
token.attr.remove[ChunkFeatures]
val features = token.attr += new ChunkFeatures(token)
val rawWord = token.string
val posTag = token.attr[PennPosTag]
features += "SENTLOC="+i
features += "P="+posTag
features += "Raw="+rawWord
val shape = cc.factorie.app.strings.stringShape(rawWord, 2)
features += "WS="+shape
if (token.isPunctuation) features += "PUNCTUATION"
if(ChunkFeaturesDomain.fullFeatureSet){
val word = simplifyDigits(rawWord).toLowerCase
if (word.length > 5) { features += "P="+cc.factorie.app.strings.prefix(word, 4); features += "S="+cc.factorie.app.strings.suffix(word, 4) }
features += "STEM=" + cc.factorie.app.strings.porterStem(word)
features += "WSIZE=" + rawWord.length
}
features += "BIAS"
}
addNeighboringFeatureConjunctions(sentence.tokens, (t: Token) => t.attr[ChunkFeatures], "W=[^@]*$", List(-2), List(-1), List(1),List(2), List(-1,0), List(0,1))
addNeighboringFeatureConjunctions(sentence.tokens, (t: Token) => t.attr[ChunkFeatures], "P=[^@]*$", List(-2), List(-1), List(1), List(2), List(-2,-1), List(-1,0), List(0,1), List(1,2),List(-2,-1,0),List(-1,0,1),List(0,1,2))
}
}
object BILOUChainChunker extends ChainChunker[BILOUChunkTag](BILOUChunkDomain.dimensionDomain, (t) => new BILOUChunkTag(t,"O")) {
deserialize(new FileInputStream(new java.io.File("BILOUChainChunker.factorie")))
}
object BIOChainChunker extends ChainChunker[BIOChunkTag](BIOChunkDomain.dimensionDomain, (t) => new BIOChunkTag(t,"O")) {
deserialize(new FileInputStream(new java.io.File("BIOChainChunker.factorie")))
}
object NestedChainChunker extends ChainChunker[BILOUNestedChunkTag](BILOUNestedChunkDomain.dimensionDomain, (t) => new BILOUNestedChunkTag(t,"O:O"))
{
deserialize(new FileInputStream(new java.io.File("NESTEDChainChunker.factorie")))
}
/*
* By Default:
* Takes conll2000 BIO tagged data as input
* Coverts to and trains on BILOU encoding
*/
object ChainChunkerTrainer extends HyperparameterMain {
def generateErrorOutput(sentence: Sentence): String ={
val sb = new StringBuffer
sentence.tokens.map{t=>sb.append("%s %20s %10s %10s %s\\n".format(if (t.attr.all[ChunkTag].head.valueIsTarget) " " else "*", t.string, t.attr[PennPosTag], t.attr.all[ChunkTag].head.target.categoryValue, t.attr.all[ChunkTag].head.categoryValue))}.mkString("\\n")
}
def evaluateParameters(args: Array[String]): Double = {
implicit val random = new scala.util.Random(0)
val opts = new ChunkerOpts
opts.parse(args)
assert(opts.trainFile.wasInvoked)
val chunk = opts.trainingEncoding.value match {
case "BILOU" => new ChainChunker[BILOUChunkTag](BILOUChunkDomain.dimensionDomain, (t) => new BILOUChunkTag(t,"O"))
case "BIO" => new ChainChunker[BIOChunkTag](BIOChunkDomain.dimensionDomain, (t) => new BIOChunkTag(t,"O"))
//Nested NP Chunker has to be trained from custom training data annotated in the NestedBILOUChunkTag domain style
case "NESTED" => new ChainChunker[BILOUNestedChunkTag](BILOUNestedChunkDomain.dimensionDomain, (t) => new BILOUNestedChunkTag(t,"O:O"))
}
val trainDocs = LoadConll2000.fromSource(Source.fromFile(opts.trainFile.value),opts.inputEncoding.value)
val testDocs = LoadConll2000.fromSource(Source.fromFile(opts.testFile.value),opts.inputEncoding.value)
println("Read %d training tokens.".format(trainDocs.map(_.tokenCount).sum))
println("Read %d testing tokens.".format(testDocs.map(_.tokenCount).sum))
val trainPortionToTake = if(opts.trainPortion.wasInvoked) opts.trainPortion.value.toDouble else 1.0
val testPortionToTake = if(opts.testPortion.wasInvoked) opts.testPortion.value.toDouble else 1.0
val trainSentencesFull = trainDocs.flatMap(_.sentences).filter(!_.isEmpty)
val trainSentences = trainSentencesFull.take((trainPortionToTake*trainSentencesFull.length).floor.toInt)
val testSentencesFull = testDocs.flatMap(_.sentences).filter(!_.isEmpty)
val testSentences = testSentencesFull.take((testPortionToTake*testSentencesFull.length).floor.toInt)
//If we want to load in BIO training data like conll2000, convert to BILOU encoding so BILOU training can be performed
if(opts.trainingEncoding.value == "BILOU" && opts.inputEncoding.value =="BIO") {
LoadConll2000.convertBIOtoBILOU(testSentences)
LoadConll2000.convertBIOtoBILOU(trainSentences)
}else{
//Else make sure training encoding and input encoding match
if(opts.trainingEncoding.value != opts.inputEncoding.value) throw new Exception("Specified Training Encoding: " + opts.trainingEncoding.value + " does not match Document Encoding: " + opts.inputEncoding.value)
}
chunk.train(trainSentences, testSentences, opts.useFullFeatures.value,
opts.rate.value, opts.delta.value, opts.cutoff.value, opts.updateExamples.value, opts.useHingeLoss.value, l1Factor=opts.l1.value, l2Factor=opts.l2.value)
if (opts.saveModel.value) {
chunk.serialize(new FileOutputStream(new File(opts.modelFile.value)))
println("Model Serialized")
}
val acc = HammingObjective.accuracy(testDocs.flatMap(d => d.sentences.flatMap(s => s.tokens.map(_.attr.all[ChunkTag].head))))
if(opts.targetAccuracy.wasInvoked) assert(acc > opts.targetAccuracy.value.toDouble, "Did not reach accuracy requirement")
if(opts.errorOutput.value) {
val writer = new PrintWriter(new File("ChainChunkingOutput.txt" ))
testSentences.foreach{s=>writer.write(generateErrorOutput(s)); writer.write("")}
writer.close()
}
acc
}
}
object ChainChunkerOptimizer {
def main(args: Array[String]) {
val opts = new ChunkerOpts
opts.parse(args)
opts.saveModel.setValue(false)
val l1 = cc.factorie.util.HyperParameter(opts.l1, new cc.factorie.util.LogUniformDoubleSampler(1e-10, 1e2))
val l2 = cc.factorie.util.HyperParameter(opts.l2, new cc.factorie.util.LogUniformDoubleSampler(1e-10, 1e2))
val rate = cc.factorie.util.HyperParameter(opts.rate, new cc.factorie.util.LogUniformDoubleSampler(1e-4, 1e4))
val delta = cc.factorie.util.HyperParameter(opts.delta, new cc.factorie.util.LogUniformDoubleSampler(1e-4, 1e4))
val cutoff = cc.factorie.util.HyperParameter(opts.cutoff, new cc.factorie.util.SampleFromSeq(List(0,1,2,3)))
val qs = new cc.factorie.util.QSubExecutor(60, "cc.factorie.app.nlp.chunk.ChainChunkingTrainer")
val optimizer = new cc.factorie.util.HyperParameterSearcher(opts, Seq(l1, l2, rate, delta, cutoff), qs.execute, 200, 180, 60)
val result = optimizer.optimize()
println("Got results: " + result.mkString(" "))
println("Best l1: " + opts.l1.value + " best l2: " + opts.l2.value)
opts.saveModel.setValue(true)
println("Running best configuration...")
import scala.concurrent.Await
import scala.concurrent.duration._
Await.result(qs.execute(opts.values.flatMap(_.unParse).toArray), 5.hours)
println("Done")
}
}
class ChunkerOpts extends cc.factorie.util.DefaultCmdOptions with SharedNLPCmdOptions{
val conllPath = new CmdOption("rcv1Path", "../../data/conll2000", "DIR", "Path to folder containing RCV1-v2 dataset.")
val outputPath = new CmdOption("ouputPath", "../../data/conll2000/output.txt", "FILE", "Path to write output for evaluation.")
val modelFile = new CmdOption("model", "ChainChunker.factorie", "FILENAME", "Filename for the model (saving a trained model or reading a running model.")
val testFile = new CmdOption("test", "src/main/resources/test.txt", "FILENAME", "test file.")
val trainFile = new CmdOption("train", "src/main/resources/train.txt", "FILENAME", "training file.")
val l1 = new CmdOption("l1", 0.000001,"FLOAT","l1 regularization weight")
val l2 = new CmdOption("l2", 0.00001,"FLOAT","l2 regularization weight")
val rate = new CmdOption("rate", 10.0,"FLOAT","base learning rate")
val delta = new CmdOption("delta", 100.0,"FLOAT","learning rate decay")
val cutoff = new CmdOption("cutoff", 2, "INT", "Discard features less frequent than this before training.")
val updateExamples = new CmdOption("update-examples", true, "BOOL", "Whether to update examples in later iterations during training.")
val useHingeLoss = new CmdOption("use-hinge-loss", false, "BOOL", "Whether to use hinge loss (or log loss) during training.")
val saveModel = new CmdOption("save-model", false, "BOOL", "Whether to save the trained model.")
val runText = new CmdOption("run", "", "FILENAME", "Plain text file on which to run.")
val numIters = new CmdOption("num-iterations","5","INT","number of passes over the data for training")
val inputEncoding = new CmdOption("input-encoding","BIO","String","NESTED, BIO, BILOU - Encoding file used for training is in.")
val trainingEncoding = new CmdOption("train-encoding", "BILOU","String","NESTED, BIO, BILOU - labels to use during training.")
val useFullFeatures = new CmdOption("full-features", false,"BOOL", "True to use the full feature set, False to use a smaller feature set which is the default.")
val errorOutput = new CmdOption("print-output", false,"BOOL", "True to print output to file for error analysis and debugging purposes.")
}
|
patverga/factorie
|
src/main/scala/cc/factorie/app/nlp/phrase/ChainChunker.scala
|
Scala
|
apache-2.0
| 14,511 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.