Update vanadium.js to node 4.4.1
Also:
* Update all package.json dependencies to latest version.
* Remove browserify.
* Remove extension.
* Remove integration tests.
The unit, vdl, and vom tests remain and are passing.
MultiPart: 1/5
Change-Id: I957311b32c6efa95be36e306ac6afc69df6ad215
diff --git a/Makefile b/Makefile
index 1f4f585..c8afcc4 100644
--- a/Makefile
+++ b/Makefile
@@ -1,13 +1,11 @@
-NODE_DIR := $(shell jiri profile list --info Target.InstallationDir v23:nodejs)
-PATH := node_modules/.bin:$(NODE_DIR)/bin:$(PATH)
+NODE_BIN := $(shell jiri profile env --profiles=v23:base,v23:nodejs NODE_BIN=)
+PATH := node_modules/.bin:$(NODE_BIN):$(PATH)
-NODE_BIN := $(JIRI_ROOT)/release/javascript/core/node_modules/.bin
-GOPATH := $(JIRI_ROOT)/release/javascript/core/go
-GOBIN := $(JIRI_ROOT)/release/javascript/core/go/bin
+NODE_MODULES_BIN := $(JIRI_ROOT)/release/javascript/core/node_modules/.bin
VDLPATH := $(JIRI_ROOT)/release/go/src:$(GOPATH)/src
VDLROOT := $(JIRI_ROOT)/release/go/src/v.io/v23/vdlroot
VGO := GOPATH="$(GOPATH)" VDLPATH="$(VDLPATH)" jiri go
-GO_FILES := $(shell find go/src $(JIRI_ROOT)/release/go/src/v.io -name "*.go")
+GO_FILES := $(shell find $(JIRI_ROOT)/release/go/src/v.io -name "*.go")
NODE_MODULE_JS_FILES := $(shell find node_modules -name *.js | sed 's/ /\\ /')
@@ -17,56 +15,11 @@
# NOTE: we run npm using 'node npm' to avoid relying on the shebang line in the
# npm script, which can exceed the Linux shebang length limit on Jenkins.
-NPM := $(NODE_DIR)/bin/npm
+NPM := $(NODE_BIN)/npm
.DEFAULT_GOAL := all
-# Default browserify options: create a standalone bundle, and use sourcemaps.
-BROWSERIFY_OPTS := --standalone vanadium --debug
-# Names that should not be mangled by minification.
-RESERVED_NAMES := 'context,ctx,callback,cb,$$stream,serverCall'
-# Don't mangle RESERVED_NAMES, and screw ie8.
-MANGLE_OPTS := --mangle [--except $(RESERVED_NAMES) --screw_ie8 ]
-# Don't remove unused variables from function arguments, which could mess up signatures.
-# Also don't evaulate constant expressions, since we rely on them to conditionally require modules only in node.
-COMPRESS_OPTS := --compress [ --no-unused --no-evaluate ]
-
-# Browserify and extract sourcemap, but do not minify.
-define BROWSERIFY
- mkdir -p $(dir $2)
- browserify $1 $(BROWSERIFY_OPTS) | exorcist $2.map > $2
-endef
-
-# Browserify, minify, and extract sourcemap.
-define BROWSERIFY-MIN
- mkdir -p $(dir $2)
- browserify $1 $(BROWSERIFY_OPTS) --g [ uglifyify $(MANGLE_OPTS) $(COMPRESS_OPTS) ] | exorcist $2.map > $2
-endef
-
-# When running browser tests on non-Darwin machines, set the --headless flag.
-# This uses Xvfb underneath the hood (inside prova => browser-launcher =>
-# headless), which is not supported on OS X.
-# See: https://github.com/kesla/node-headless/
-ifndef NOHEADLESS
- ifneq ($(UNAME),Darwin)
- HEADLESS := --headless
- endif
-endif
-
-ifdef STOPONFAIL
- STOPONFAIL := --stopOnFirstFailure
-endif
-
-ifndef NOTAP
- TAP := --tap
-endif
-
-ifndef NOQUIT
- QUIT := --quit
-endif
-
ifdef XUNIT
- TAP := --tap # TAP must be set for xunit to work
OUTPUT_TRANSFORM := tap-xunit
endif
@@ -78,50 +31,19 @@
NODE_OUTPUT_LOCAL := | tee $(NODE_OUTPUT_LOCAL)
endif
-ifdef BROWSER_OUTPUT
- BROWSER_OUTPUT_LOCAL = $(BROWSER_OUTPUT)
- ifdef OUTPUT_TRANSFORM
- BROWSER_OUTPUT_LOCAL := >($(OUTPUT_TRANSFORM) --package=javascript.browser > $(BROWSER_OUTPUT_LOCAL))
- endif
- BROWSER_OUTPUT_LOCAL := | tee $(BROWSER_OUTPUT_LOCAL)
-endif
-
-PROVA_OPTS := --includeFilenameAsPackage $(TAP) $(QUIT) $(STOPONFAIL)
-
-BROWSER_OPTS := --browser --transform envify --launch chrome $(HEADLESS)
-
JS_SRC_FILES = $(shell find src -name "*.js" | sed 's/ /\\ /')
-# Common services needed for all integration tests. Must be a comma-seperated
-# string with no spaces.
-COMMON_SERVICES := "test_serviced"
-
-LOADTEST_SERVICE := "stressd"
-
all: gen-vdl lint build docs
-build: dist docs extension/vanadium.zip
-
-dist/vanadium.js: src/vanadium.js $(JS_SRC_FILES) $(NODE_MODULES_JS_FILES) | node_modules
- $(call BROWSERIFY,$<,$@)
-
-dist/vanadium.min.js: src/vanadium.js $(JS_SRC_FILES) $(NODE_MODULES_JS_FILES) | node_modules
- $(call BROWSERIFY-MIN,$<,$@)
-
-dist: dist/vanadium.js dist/vanadium.min.js
-
-extension/vanadium.zip: node_modules
- $(MAKE) -C extension vanadium.zip
+build: docs
test-precheck: gen-vdl-test node_modules lint dependency-check
-test: test-unit test-integration test-vdl test-vom
+test: test-unit test-vdl test-vom
-test-vdl: test-vdl-node test-vdl-browser
+test-vdl: test-vdl-node
# This generates the VDL files and asks git if there are any changed files.
-# We don't have to check the extension since it does not check in VDL files.
-#
# The alternative is to use the vdl audit command, but that requires checking
# after both vdl commands in gen-vdl-impl as opposed to a single git status.
test-vdl-audit: gen-vdl
@@ -132,7 +54,7 @@
exit 1; \
fi
-test-vom: test-vom-node test-vom-browser
+test-vom: test-vom-node
# This generates the output of the vdl files in src/gen-vdl/v.io/<package-path>
# The command will generate all the dependent files as well.
@@ -143,8 +65,8 @@
# This generates the output of the vdl files in test/vdl-out/gen-vdl/v.io/<package-path>
# The command will generate all the dependent files as well.
gen-vdl-test: JS_VDL_DIR := "$(JIRI_ROOT)/release/javascript/core/test/vdl-out"
-gen-vdl-test: EXTRA_VDL_PATHS := "javascript-test/..." "v.io/x/js.core/..."
-gen-vdl-test: VDLPATH := "$(JIRI_ROOT)/release/go/src:$(JIRI_ROOT)/release/javascript/core/test/vdl-in/src:$(JIRI_ROOT)/release/javascript/core/go/src"
+gen-vdl-test: EXTRA_VDL_PATHS := "javascript-test/..."
+gen-vdl-test: VDLPATH := "$(JIRI_ROOT)/release/go/src:$(JIRI_ROOT)/release/javascript/core/test/vdl-in/src"
gen-vdl-test: JS_VDL_PATH_TO_CORE := "../../src"
gen-vdl-test: gen-vdl-impl
@@ -187,86 +109,32 @@
endif
test-vdl-node: test-precheck
- prova test/vdl/test-*.js $(PROVA_OPTS) $(NODE_OUTPUT_LOCAL)
-
-test-vdl-browser: test-precheck
- prova test/vdl/test-*.js $(PROVA_OPTS) $(BROWSER_OPTS) $(BROWSER_OUTPUT_LOCAL)
+ tape test/vdl/test-*.js $(NODE_OUTPUT_LOCAL)
test-vom-node: test-precheck
- prova test/vom/test-*.js $(PROVA_OPTS) $(NODE_OUTPUT_LOCAL)
+ tape test/vom/test-*.js $(NODE_OUTPUT_LOCAL)
-test-vom-browser: test-precheck
- prova test/vom/test-*.js $(PROVA_OPTS) $(BROWSER_OPTS) $(BROWSER_OUTPUT_LOCAL)
-
-test-unit: test-unit-node test-unit-browser
+test-unit: test-unit-node
test-unit-node: test-precheck
- prova test/unit/test-*.js $(PROVA_OPTS) $(NODE_OUTPUT_LOCAL)
-
-test-unit-browser: test-precheck
- prova test/unit/test-*.js $(PROVA_OPTS) $(BROWSER_OPTS) $(BROWSER_OUTPUT_LOCAL)
-
-test-integration: lint test-integration-node test-integration-browser
-
-test-integration-node: test-precheck go/bin
- node test/integration/runner.js --services=$(COMMON_SERVICES) -- \
- prova test/integration/test-*.js $(PROVA_OPTS) $(NODE_OUTPUT_LOCAL)
-
-test-integration-browser: test-precheck go/bin
- node test/integration/runner.js --services=$(COMMON_SERVICES) -- \
- make test-integration-browser-runner
-
-test-integration-browser-runner: BROWSER_OPTS := --options="--load-extension=$(PWD)/extension/build-test/,--ignore-certificate-errors,--enable-logging=stderr" $(BROWSER_OPTS)
-test-integration-browser-runner:
- @$(RM) -fr extension/build-test
- $(MAKE) -C extension build-test
- prova test/integration/test-*.js --log=./tmp/chrome.log $(PROVA_OPTS) $(BROWSER_OPTS) $(BROWSER_OUTPUT_LOCAL) $(SAVE_CHROME_LOGS)
-
-test-load-node: test-precheck go/bin
- node test/integration/runner.js --services=$(LOADTEST_SERVICE) -- \
- prova test/load/test-*.js $(PROVA_OPTS) $(NODE_OUTPUT_LOCAL)
-
-
-test-load-browser: test-precheck go/bin
- node test/integration/runner.js --services=$(LOADTEST_SERVICE) -- \
- make test-load-browser-runner
-
-test-load-browser-runner: BROWSER_OPTS := --options="--load-extension=$(PWD)/extension/build-test/,--ignore-certificate-errors,--enable-logging=stderr" $(BROWSER_OPTS)
-test-load-browser-runner:
- @$(RM) -fr extension/build-test
- $(MAKE) -C extension build-test
- prova test/load/test-*.js --log=./tmp/chrome.log $(PROVA_OPTS) $(BROWSER_OPTS) $(BROWSER_OUTPUT_LOCAL) $(SAVE_CHROME_LOGS)
-
-
-
-
-go/bin: $(GO_FILES)
- @$(VGO) build -o $(GOBIN)/servicerunner -a -tags wspr v.io/x/ref/cmd/servicerunner
- @$(VGO) build -o $(GOBIN)/principal v.io/x/ref/cmd/principal
- @$(VGO) build -o $(GOBIN)/test_serviced v.io/x/js.core/test_service/test_serviced
- @$(VGO) build -o $(GOBIN)/stressd v.io/x/js.core/stress/stressd
+ tape test/unit/test-*.js $(NODE_OUTPUT_LOCAL)
lint: node_modules
ifdef NOLINT
@echo "Skipping lint - disabled by NOLINT environment variable"
else
jshint .
- $(MAKE) -C extension lint
endif
dependency-check: node_modules
dependency-check package.json --entry src/vanadium.js
clean:
- @$(RM) -fr dist
@$(RM) -fr docs
- @$(RM) -fr go/bin
- @$(RM) -fr go/pkg
@$(RM) -fr node_modules
@$(RM) -fr npm-debug.log
@$(RM) -fr tmp
@$(RM) -fr xunit.xml
- $(MAKE) -C extension clean
DOCSTRAP_LOC:= node_modules/ink-docstrap
docs: $(JS_SRC_FILES) jsdocs/docstrap-template/compiled/site.vanadium.css | node_modules
@@ -291,7 +159,7 @@
# Copy our raw LESS style assets to docstrap
cp -f jsdocs/docstrap-template/styles/*.* ${DOCSTRAP_LOC}/styles
# Rebuilt the styles
- cd ${DOCSTRAP_LOC}; ${NODE_BIN}/grunt less
+ cd ${DOCSTRAP_LOC}; ${NODE_MODULES_BIN}/grunt less
# Copy back the compiled style file from docstrap
cp -f ${DOCSTRAP_LOC}/template/static/styles/site.cosmo.css jsdocs/docstrap-template/compiled/site.vanadium.css
# Rebuild docs
@@ -301,7 +169,7 @@
cd ${DOCSTRAP_LOC}; node $(NPM) install
node_modules/ink-docstrap/bower_components:
- cd ${DOCSTRAP_LOC}; ${NODE_BIN}/bower install
+ cd ${DOCSTRAP_LOC}; ${NODE_MODULES_BIN}/bower install
# serve-docs
#
@@ -330,14 +198,12 @@
@which npm > /dev/null || { echo "npm is not in the path. Did you remember to run 'jiri profile install v23:nodejs'?"; exit 1; }
.PHONY: all build clean dependency-check lint test
-.PHONY: test-integration test-integration-node test-integration-browser
-.PHONY: test-unit test-unit-node test-unit-browser
+.PHONY: test-unit test-unit-node
.PHONY: check-that-npm-is-in-path
.PHONY: gen-vdl gen-vdl-test gen-vdl-test-expected gen-vdl-impl gen-vdl-test-expected-impl
# Prevent the tests from running in parallel, which causes problems because it
# starts multiple instances of the services at once, and also because it
# interleaves the test output.
-.NOTPARALLEL: test-integration test-integration-browser test-integration-node
-.NOTPARALLEL: test-unit test-unit-node test-unit-browser
-.NOTPARALLEL: test-vdl test-vdl-node test-vdl-browser
+.NOTPARALLEL: test-unit test-unit-node
+.NOTPARALLEL: test-vdl test-vdl-node
diff --git a/extension/.jshintrc b/extension/.jshintrc
deleted file mode 100644
index d332d55..0000000
--- a/extension/.jshintrc
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "camelcase": true,
- "curly": true,
- "eqeqeq": true,
- "expr": true,
- "forin": true,
- "freeze": true,
- "immed": true,
- "indent": 2,
- "latedef": "nofunc",
- "maxlen": 80,
- "newcap": true,
- "noarg": true,
- "nonbsp": true,
- "nonew": true,
- "quotmark": "single",
- "sub": true,
- "trailing": true,
- "undef": true,
- "unused": "vars",
- "esnext": true,
- "devel": true,
- "node": true,
- "browser": true,
-
- "globals": {
- "chrome": false
- }
-}
diff --git a/extension/Makefile b/extension/Makefile
deleted file mode 100644
index d0b5b26..0000000
--- a/extension/Makefile
+++ /dev/null
@@ -1,166 +0,0 @@
-NODE_DIR := $(shell jiri profile list --info Target.InstallationDir v23:nodejs)
-PATH := node_modules/.bin:${NODE_DIR}/bin:$(PATH)
-VDLPATH := $(JIRI_ROOT)/release/go/src
-VDLROOT := $(JIRI_ROOT)/release/go/src/v.io/v23/vdlroot
-WSPR_ROOT := $(JIRI_ROOT)/release/go/src/v.io/x/ref/services/wspr
-SHELL := /bin/bash -e -o pipefail
-.DEFAULT_GOAL := all
-
-# NOTE: we run npm using 'node npm' to avoid relying on the shebang line in the
-# npm script, which can exceed the Linux shebang length limit on Jenkins.
-NPM := $(NODE_DIR)/bin/npm
-
-JS_FILES = $(shell find src -name "*.js" -o -name "*.css")
-
-define BROWSERIFY
- mkdir -p $(dir $2)
- browserify $1 --transform brfs --debug --outfile $2
-endef
-
-define BROWSERIFY-TEST
- mkdir -p $(dir $2)
- browserify $1 --transform brfs --transform envify --debug --outfile $2
-endef
-
-define COMPILE-NACL-PLUGIN
- mkdir -p $(dir $2)
- unset GOARCH GOOS; jiri -v go -v --profiles=v23:nacl --target=amd64p32-nacl build -v -o $2 $1
-endef
-
-all: vanadium.zip
-
-build/html: html/*
- mkdir -p build
- cp -r html build
-
-build/images: images/*
- mkdir -p build
- cp -r images build
-
-build/manifest.json: manifest.json
- mkdir -p build
- cp manifest.json build
-
-build/js/background.js: src/background/index.js $(JS_FILES) gen-vdl node_modules
- $(call BROWSERIFY,$<,$@)
-
-build/js/content.js: src/content/index.js $(JS_FILES) node_modules
- $(call BROWSERIFY,$<,$@)
-
-build/js/options.js: src/background/options.js $(JS_FILES) node_modules
- $(call BROWSERIFY,$<,$@)
-
-build/js/addcaveats.js: src/background/addcaveats.js $(JS_FILES) node_modules
- $(call BROWSERIFY,$<,$@)
-
-build/js: build/js/background.js build/js/content.js build/js/options.js build/js/addcaveats.js
-
-build/nacl/main.nmf: nacl
- mkdir -p $(dir $@)
- cp -r nacl/main.nmf $@
-
-build/nacl/main-64.nexe: $(JIRI_ROOT)/release/go/src/v.io/x/ref/services/wspr/browsprd/main_nacl.go
- @$(call COMPILE-NACL-PLUGIN,$<,$@)
-
-build/nacl: build/nacl/main.nmf build/nacl/main-64.nexe
-
-build: build/html build/images build/manifest.json build/js build/nacl
-
-build-dev: build
- patch build/manifest.json < manifest-test.json.patch # Adds "key" as first line.
-
-vanadium.zip: build
- zip -r $@ ./build/*
-
-build-test/html: html/*
- mkdir -p build-test
- cp -r html build-test
-
-build-test/images: images/*
- mkdir -p build-test
- cp -r images build-test
-
-build-test/manifest.json: manifest.json
- mkdir -p build-test
- cp manifest.json build-test
- patch build-test/manifest.json < manifest-test.json.patch # Adds "key" as first line.
-
-build-test/js/background.js: src/background/index.js $(JS_FILES) gen-vdl node_modules
- $(call BROWSERIFY-TEST,$<,$@)
-
-build-test/js/content.js: src/content/index.js $(JS_FILES) node_modules
- $(call BROWSERIFY-TEST,$<,$@)
-
-build-test/js/options.js: src/background/options.js $(JS_FILES) node_modules
- $(call BROWSERIFY-TEST,$<,$@)
-
-build-test/js/addcaveats.js: src/background/addcaveats.js $(JS_FILES) node_modules
- $(call BROWSERIFY-TEST,$<,$@)
-
-# The EXTENSION_SETTINGS env variable is used by the extension to set the default settings variables.
-build-test/js: export EXTENSION_SETTINGS := {"namespaceRoot": "$(V23_NAMESPACE)",\
- "proxy": "test/proxy",\
- "identityd": "$(IDENTITYD)",\
- "identitydBlessingUrl": "$(IDENTITYD_BLESSING_URL)",\
- "logLevel": "1",\
- "logModule": "wspr.go=3"}
-# The TEST_ACCESS_TOKEN and TEST_CAVEATS env variables allow the tests to run without user input.
-build-test/js: export TEST_ACCESS_TOKEN := test-access-token
-build-test/js: export TEST_CAVEATS := 24h
-# The ALLOW_INTENTIONAL_CRASH env variable is used to test that the extension can restart after a crash.
-build-test/js: export ALLOW_INTENTIONAL_CRASH := true
-build-test/js: build-test/js/background.js build-test/js/content.js build-test/js/options.js build-test/js/addcaveats.js
-
-build-test/nacl/main.nmf: nacl
- mkdir -p $(dir $@)
- cp -r nacl/main.nmf $@
-
-build-test/nacl/main-64.nexe: $(WSPR_ROOT)/browsprd/main_nacl.go
- $(call COMPILE-NACL-PLUGIN,$<,$@)
-
-build-test/nacl: build-test/nacl/main.nmf build-test/nacl/main-64.nexe
-
-build-test: build-test/html build-test/images build-test/manifest.json build-test/js build-test/nacl
-
-gen-vdl: $(WSPR_ROOT)/internal/channel/channel.vdl $(WSPR_ROOT)/internal/browspr/browspr.vdl $(WSPR_ROOT)/internal/account/account.vdl
- VDLPATH=$(VDLPATH) VDLROOT=$(VDLROOT) vdl generate -lang=javascript \
- -js-out-dir="$(JIRI_ROOT)/release/javascript/core/extension/vdl" \
- -js-relative-path-to-core=../../src $(dir $^)
- # TODO(bjornick): We build the vdlroot stuff with a different set of command line options because the package
- # path does not equal the directory path of the source file. This is not ideal, but bjornick and toddw will
- # discuss how to fix this later.
- VDLPATH=$(VDLPATH) VDLROOT=$(VDLROOT) vdl generate -lang=javascript \
- -js-relative-path-to-core=../../../../../src \
- -js-out-dir="$(JIRI_ROOT)/release/javascript/core/extension/vdl" \
- $(VDLROOT)/...
-
-example-server: example/index.bundle.js
- static "example" -H '{"Cache-Control": "no-cache, must-revalidate"}'
-
-example/index.bundle.js: example/index.js node_modules
- browserify $< --transform brfs --global-transform envify --debug --outfile $@
-
-lint: node_modules
- jshint src/ example/index.js
-
-dependency-check: node_modules
- dependency-check package.json --entry src/background/index.js --entry src/content/index.js
-
-clean:
- @$(RM) -fr node_modules npm-debug.log
- @$(RM) -fr vanadium.zip build build-test
-
-node_modules: package.json | check-that-npm-is-in-path
- @node $(NPM) prune
- @node $(NPM) install --quiet
-
-check-that-npm-is-in-path:
- @which npm > /dev/null || { echo "npm is not in the path. Did you remember to run 'jiri profile install v23:nodejs'?"; exit 1; }
-
-.PHONY: all build build-dev clean dependency-check gen-vdl lint
-
-# Always rebuild the plugin.
-.PHONY: nacl/main-64.nexe
-
-# Always rebuild the example server.
-.PHONY: example/index.bundle.js
diff --git a/extension/README.md b/extension/README.md
deleted file mode 100644
index b420b84..0000000
--- a/extension/README.md
+++ /dev/null
@@ -1,25 +0,0 @@
-# The Veyron Extension
-
-## Developing with an unpacked extension:
- $ make clean && make
-
-This will build an unpacked extension in the ./extension directory.
-
-To load the unpacked extension in Chrome:
-1. Click Hamburger menu -> Tools -> Extensions
-2. Click "Load unpacked extension..."
-3. Navigate to ./extension and click "OK".
-
-## Publishing a new version of the extension:
-
-Note: You must be a member of the vanadium-extension-managers group to publish.
-
-1. Bump the version number in manifest.json.
-2. Build a zip file with "make veyron.zip"
-3. Upload and publish the extension on https://chrome.google.com/webstore/developer/dashboard
-
-## Running the example server
- $ make example-server
-
-This will run an example web app at http://localhost:8080. The web app has a
-log-in button that communicates with the extension to start the blessing flow.
diff --git a/extension/example/index.html b/extension/example/index.html
deleted file mode 100644
index 2fcf88d..0000000
--- a/extension/example/index.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<html>
-<head>
- <title>Example App</title>
- <script type="text/javascript" src="./index.bundle.js"></script>
-</head>
-
-<body>
- Example App
- <br>
- <a href="#" id="login-link">Login</a>
-</body>
-</html>
diff --git a/extension/example/index.js b/extension/example/index.js
deleted file mode 100644
index dd8d33b..0000000
--- a/extension/example/index.js
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var vanadium = window.vanadium = require('../../src/vanadium.js');
-
-var vanadiumConfig = {
- authenticate: true
-};
-
-document.addEventListener('DOMContentLoaded', function(){
- var loginLink = document.getElementById('login-link');
- loginLink.addEventListener('click', handleLogin);
-
- console.log('example app loaded');
-});
-
-function handleLogin(e){
- e.preventDefault();
- console.log('login clicked');
-
- vanadium.init(vanadiumConfig, function(err, rt){
- if (err) {
- return console.error(err);
- }
-
- var accountName = rt.accountName;
- console.log('got runtime with accountName: ' + accountName);
- alert('Hello ' + accountName + '!');
- });
-}
diff --git a/extension/html/addcaveats.html b/extension/html/addcaveats.html
deleted file mode 100644
index c6425be..0000000
--- a/extension/html/addcaveats.html
+++ /dev/null
@@ -1,83 +0,0 @@
-<!doctype html>
-<html>
-<head>
- <meta
- name="viewport"
- content="width=device-width,
- initial-scale=1,
- maximum-scale=1,
- user-scalable=no,
- minimal-ui">
- <meta
- name="apple-mobile-web-app-capable"
- content="yes">
-
- <meta
- name="apple-mobile-web-app-status-bar-style"
- content="black">
-
-
- <!--TODO(suharshs,nlacasse): Consider bundling all external assets inside the extension.-->
- <link href='http://fonts.googleapis.com/css?family=Source+Code+Pro:400,500|Roboto:500,400italic,300,500italic,300italic,400'
- rel='stylesheet'
- type='text/css'>
- <link rel="stylesheet" href="https://v.io/identity.css">
-
- <link rel="apple-touch-icon" sizes="57x57" href="https://v.io/favicons/apple-touch-icon-57x57.png">
- <link rel="apple-touch-icon" sizes="114x114" href="https://v.io/favicons/apple-touch-icon-114x114.png">
- <link rel="apple-touch-icon" sizes="72x72" href="https://v.io/favicons/apple-touch-icon-72x72.png">
- <link rel="apple-touch-icon" sizes="144x144" href="https://v.io/favicons/apple-touch-icon-144x144.png">
- <link rel="apple-touch-icon" sizes="60x60" href="https://v.io/favicons/apple-touch-icon-60x60.png">
- <link rel="apple-touch-icon" sizes="120x120" href="https://v.io/favicons/apple-touch-icon-120x120.png">
- <link rel="apple-touch-icon" sizes="76x76" href="https://v.io/favicons/apple-touch-icon-76x76.png">
- <link rel="apple-touch-icon" sizes="152x152" href="https://v.io/favicons/apple-touch-icon-152x152.png">
- <link rel="apple-touch-icon" sizes="180x180" href="https://v.io/favicons/apple-touch-icon-180x180.png">
- <link rel="icon" type="image/png" href="https://v.io/favicons/favicon-192x192.png" sizes="192x192">
- <link rel="icon" type="image/png" href="https://v.io/favicons/favicon-160x160.png" sizes="160x160">
- <link rel="icon" type="image/png" href="https://v.io/favicons/favicon-96x96.png" sizes="96x96">
- <link rel="icon" type="image/png" href="https://v.io/favicons/favicon-16x16.png" sizes="16x16">
- <link rel="icon" type="image/png" href="https://v.io/favicons/favicon-32x32.png" sizes="32x32">
- <meta name="msapplication-TileColor" content="#da532c">
- <meta name="msapplication-TileImage" content="https://v.io/favicons/mstile-144x144.png">
-
- <script src="/js/addcaveats.js"></script>
- <title>Request for Blessings</title>
-</head>
-
-<body class="default-layout">
-
-<header>
- <nav class="left">
- <a href="#" class="logo">Vanadium</a>
- </nav>
-
- <nav class="main">
- <a href="#">Grants for Blessings</a>
- </nav>
-
- <nav class="right">
- <a class="origin" href="#"></a>
- </nav>
-</header>
-
-<main style="max-width: 80%; margin-left: 10px;">
- <h2>Allow access to <span class="origin"></span> for 10 days?</h2>
- <h4 id="warning" class="hidden">WARNING: <span class="origin"></span> is not secure (not https). Vanadium's security model may be compromised.</h4>
- <p>This web page will be able to see your email address and public keys. Only allow access to web pages you trust.</p>
- <!--TODO(suharshs,nlacasse,aghasemi): We can remove this hidden css class to allow the user to select specific caveats.-->
- <div class="hidden">
- <input type="text" id="ExpiryCaveat" placeholder="i.e. 2h45m. Valid time units are ns, us (or µs), ms, s, m, h. Defaults to 240h.">
- </div>
- <p id="tos">By clicking "Allow", you consent to be bound by Google's general <a href="https://www.google.com/intl/en/policies/terms/">Terms of Service</a>,
- the <a href="https://developers.google.com/terms/">Google APIs Terms of Service</a>,
- and Google's general <a href="https://www.google.com/intl/en/policies/privacy/">Privacy Policy</a>.</p>
- <div class="grid">
- <button id="submit-caveats" class="cell button-passive" type="submit">Allow</button>
- <button id="cancel" class="cell button-passive">Deny</button>
- <div class="cell"></div>
- <div class="cell"></div>
- </div>
-</main>
-
-</body>
-</html>
diff --git a/extension/html/background.html b/extension/html/background.html
deleted file mode 100644
index dd77ef5..0000000
--- a/extension/html/background.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<html>
-<head>
- <title>Veyron Background Page</title>
- <script type="text/javascript" src="/js/background.js"></script>
-</head>
-<body></body>
-</html>
diff --git a/extension/html/options.html b/extension/html/options.html
deleted file mode 100644
index 56ca049..0000000
--- a/extension/html/options.html
+++ /dev/null
@@ -1,6 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <script src="/js/options.js"></script>
- </head>
-</html>
diff --git a/extension/images/1x1.png b/extension/images/1x1.png
deleted file mode 100644
index 17f1d2e..0000000
--- a/extension/images/1x1.png
+++ /dev/null
Binary files differ
diff --git a/extension/images/icon_128.png b/extension/images/icon_128.png
deleted file mode 100644
index 54bdbaa..0000000
--- a/extension/images/icon_128.png
+++ /dev/null
Binary files differ
diff --git a/extension/manifest-test.json.patch b/extension/manifest-test.json.patch
deleted file mode 100644
index 457e77a..0000000
--- a/extension/manifest-test.json.patch
+++ /dev/null
@@ -1,5 +0,0 @@
---- manifest.json 2015-01-08 13:00:37.812010013 -0800
-+++ manifest-test.json 2015-01-08 13:01:50.273312593 -0800
-@@ -1,1 +1,2 @@
- {
-+ "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuhTUCoxtpDZJKSd4JPMGSPitzCOIMCgpa+nL3JrPc3XpW6rGu9qIB3TiUfFKdbFnCVRUgCZI8fxAg0QYYjVcIbU0tclA5fOJwiRTm2B2JByYMblDCqTlTMcpESLEJjk6N2O0Nx0CLMewkOCts+hBFHZtfTBdc54+sVHvY5XSll8DpLglDX4lsX5eGV6amzRGy8hANwe3Soy1eaPOxx8EsEfRFRCHUj40wlqa8EdO0uX/OQl+/HNZnhmYumujC9jYw9ZF3jTVBGb347Vo8mPaQ9BDVOm4GW2j5r7QDdJG7zIcKz+c2I8bQ/kRfce1cW5nV2Jcqq8uAzU+9DBuVu5udQIDAQAB",
diff --git a/extension/manifest.json b/extension/manifest.json
deleted file mode 100644
index 0588885..0000000
--- a/extension/manifest.json
+++ /dev/null
@@ -1,36 +0,0 @@
-{
- "name": "Vanadium Extension",
- "version": "0.1.34",
- "description": "Access and create Vanadium services from JavaScript.",
- "manifest_version": 2,
- "icons": {
- "128": "images/icon_128.png"
- },
- "options_page": "html/options.html",
- "background": {
- "page": "html/background.html",
- "persistent": true
- },
- "content_scripts": [{
- "matches": ["<all_urls>"],
- "all_frames": true,
- "js": ["js/content.js"]
- }],
- "permissions": [
- "<all_urls>",
- "identity",
- "unlimitedStorage"
- ],
- "web_accessible_resources": [
- "images/1x1.png",
- "js/background.js.map",
- "js/content.js.map",
- "js/options.js.map"
- ],
- "oauth2": {
- "client_id": "632758215260-46rubj75aqsiejncfva2j2rabosj4r8k.apps.googleusercontent.com",
- "scopes": [
- "email"
- ]
- }
-}
diff --git a/extension/nacl/main.nmf b/extension/nacl/main.nmf
deleted file mode 100644
index 0c058b2..0000000
--- a/extension/nacl/main.nmf
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "program": {
- "x86-64": {
- "url": "main-64.nexe"
- }
- }
-}
-
diff --git a/extension/package.json b/extension/package.json
deleted file mode 100644
index 6ddc351..0000000
--- a/extension/package.json
+++ /dev/null
@@ -1,39 +0,0 @@
-{
- "name": "Vanadium-Extension",
- "version": "0.0.1",
- "description": "## Goals: ### Short-term: Extension provides UI to manage identities WSPR holds on to all private keys and never exposes them. The extension works with WSPR to manage identities. A webapp should not be able to see all identities known to WSPR.",
- "scripts": {
- "start": "make example-server",
- "test": "echo \"Error: no test specified\" && exit 1"
- },
- "author": "vanadium",
- "license": "MIT",
- "dependencies": {
- "debug": "^2.1.1",
- "domready": "~1.0.7",
- "insert-css": "^0.2.0",
- "lodash": "^3.0.0",
- "mercury": "^12.0.0",
- "xtend": "^4.0.0",
- "eventemitter2": "~0.4.14",
- "es6-shim": "^0.20.2",
- "superagent": "~0.21.0",
- "inherits": "~2.0.1"
- },
- "devDependencies": {
- "brfs": "^1.2.0",
- "browserify": "^8.1.1",
- "dependency-check": "^1.1.5",
- "jshint": "^2.6.0",
- "node-static": "^0.7.4",
- "envify": "~3.2.0",
- "esprima": "~1.2.2"
- },
- "directories": {
- "example": "example"
- },
- "repository": {
- "type": "git",
- "url": "https://vandium.googlesource.com/vanadium-extension"
- }
-}
diff --git a/extension/src/background/addcaveats.js b/extension/src/background/addcaveats.js
deleted file mode 100644
index 7059519..0000000
--- a/extension/src/background/addcaveats.js
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var domready = require('domready');
-var url = require('url');
-
-var params = url.parse(document.URL, true).query;
-
-domready(function() {
- document.getElementById('submit-caveats').addEventListener('click',
- function() {
- sendCaveats(false);
- });
- var originElems = document.getElementsByClassName('origin');
- for (var i = 0; i < originElems.length; i++) {
- originElems[i].innerText = params.origin;
- }
- // If the origin is not https, display a warning to the user.
- if (params.origin.indexOf('https') !== 0) {
- document.getElementById('warning').classList.remove('hidden');
- }
-
- // Setup the cancel button.
- document.getElementById('cancel').addEventListener('click', function() {
- sendCaveats(true);
- });
-
- if (process.env.TEST_CAVEATS) {
- // Set the value of the expiry caveat and submit the form.
- document.getElementById('ExpiryCaveat').value = process.env.TEST_CAVEATS;
- sendCaveats();
- }
-});
-
-// We only currently support Expiry because other caveats don't make sense to
-// the end user and Revocation is not yet supported in WSPR.
-var caveatNames = ['ExpiryCaveat'];
-
-function sendCaveats(cancel) {
- var caveats = [];
- for (var i = 0; i < caveatNames.length; i++) {
- var caveatArgs = document.getElementById(caveatNames[i]).value;
- if (caveatNames[i] === 'ExpiryCaveat' && !caveatArgs) {
- caveats.push({
- type: 'ExpiryCaveat',
- args: '240h'
- });
- } else if (caveatArgs) {
- caveats.push({
- type: caveatNames[i],
- args: caveatArgs
- });
- }
- }
- var backgroundPort = chrome.runtime.connect();
- backgroundPort.postMessage({
- type: 'assocAccount:finish',
- origin: params.origin,
- caveats: caveats,
- cancel: cancel
- });
- backgroundPort.disconnect();
-}
diff --git a/extension/src/background/auth-handler.js b/extension/src/background/auth-handler.js
deleted file mode 100644
index 90b3815..0000000
--- a/extension/src/background/auth-handler.js
+++ /dev/null
@@ -1,326 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-/**
- * @fileoverview Handles auth requests to Nacl.
- */
-
-var getOrigin = require('./util').getOrigin;
-
-module.exports = AuthHandler;
-
-function AuthHandler(channel) {
- if (!(this instanceof AuthHandler)) {
- return new AuthHandler(channel);
- }
-
- this._channel = channel;
-
- // Map from origins to the Vanadium app ports of tabs with active requests.
- // This keeps track of existing auth tabs for an origin so new ones are not
- // started.
- this._outstandingAuthRequests = {};
-
- // Map from caveat tab id to origin.
- this._caveatTabOrigins = {};
-
- // Handle tabs being closed.
- chrome.tabs.onRemoved.addListener(this.onRemovedTab.bind(this));
-}
-
-AuthHandler.prototype.onRemovedTab = function(tabId) {
- var origin = this._caveatTabOrigins[tabId];
- if (!origin) {
- return; // Not one of the caveat tabs.
- }
-
- delete this._caveatTabOrigins[tabId];
-
- if (origin in this._outstandingAuthRequests) {
- this.finishAuth({
- origin: origin,
- cancel: true,
- });
- }
-};
-
-// Get an access token from the chrome.identity API.
-// See https://developer.chrome.com/apps/app_identity
-AuthHandler.prototype.getAccessToken = function(cb) {
- if (process.env.TEST_ACCESS_TOKEN) {
- return process.nextTick(cb.bind(null, null, process.env.TEST_ACCESS_TOKEN));
- }
-
- // This will return an access token for the profile that the user is
- // signed in to chrome as. If the user is not signed in to chrome, an
- // OAuth window will pop up and ask them to sign in.
- //
- // For now, we don't have a way to ask the user which profile they would
- // like to use. However, once the `chrome.identity.getAccounts` API call
- // gets out of dev/beta channel, we can get a list of accounts and prompt
- // the user for which one they would like to use with vanadium.
- chrome.identity.getAuthToken({
- interactive: true
- }, function(token) {
- // Wrap in process.nextTick so chrome stack traces can use sourceMap.
- process.nextTick(function(){
- if (chrome.runtime.lastError) {
- console.error('Error getting auth token.', chrome.runtime.lastError);
- return cb(chrome.runtime.lastError);
- }
-
- return cb(null, token);
- });
- });
-};
-
-// Get the name of all accounts from wspr. Will be empty if no root account
-// exists.
-AuthHandler.prototype.getAccounts = function(cb) {
- this._channel.performRpc('auth:get-accounts', {}, cb);
-};
-
-// Get an access token from the user and use it to create the root account on
-// wspr.
-AuthHandler.prototype.createAccount = function(cb) {
- var ah = this;
- this.getAccessToken(function(err, token) {
- if (err) {
- return cb(err);
- }
-
- // If getAccessToken returns an empty token we shouldn't send it to the
- // identity server. Instead we directly pass an error to the callback which
- // will purge the cache and try again.
- if (!token) {
- return cb(new Error('getAccessToken returned an empty token.'), null,
- token);
- }
-
- ah._channel.performRpc('auth:create-account', {token: token},
- function(err, createdAccount) {
- cb(err, createdAccount, token);
- });
- });
-};
-
-// Check if an origin is already associated with an account on wspr.
-AuthHandler.prototype.originHasAccount = function(origin, cb) {
- this._channel.performRpc('auth:origin-has-account', {origin: origin}, cb);
-};
-
-// Associate the account with the origin on wspr.
-AuthHandler.prototype.associateAccount =
- function(account, origin, caveats, cb) {
- this._channel.performRpc('auth:associate-account', {
- account: account,
- origin: origin,
- caveats: caveats
- }, cb);
-};
-
-// Pop up a new tab asking the user to chose their caveats.
-AuthHandler.prototype.getCaveats = function(account, origin, appPort) {
- // Store the account name on the appPort.
- appPort.account = account;
-
- var outstandingAuthRequests = this._outstandingAuthRequests;
- var caveatTabOrigins = this._caveatTabOrigins;
- if (origin in this._outstandingAuthRequests) {
- outstandingAuthRequests[origin].push(appPort);
-
- // Switch to the corresponding open caveat tab.
- for (var tabId in caveatTabOrigins) {
- if (caveatTabOrigins[tabId] === origin) {
- var tabIdAsNumber = +tabId;
- chrome.tabs.update(tabIdAsNumber, {active: true});
- break;
- }
- }
-
- return;
- }
- outstandingAuthRequests[origin] = [appPort];
-
- // Get currently active tab in the window.
- var windowId = appPort.sender.tab.windowId;
- chrome.tabs.query({active: true, windowId: windowId}, function(tabs) {
- // Store the current tab id so we can switch back to it after the addcaveats
- // tab is removed. Note that the currently active tab might not be the same
- // as the tab that is requesting authentication.
- if (tabs && tabs[0] && tabs[0].id) {
- appPort.currentTabId = tabs[0].id;
- }
-
- chrome.tabs.create({
- url: chrome.extension.getURL('html/addcaveats.html') + '?origin=' +
- encodeURIComponent(origin)
- }, function(tab) {
- caveatTabOrigins[tab.id] = origin;
- });
- });
-};
-
-// Handle incoming 'auth' message.
-AuthHandler.prototype.handleAuthMessage = function(appPort) {
- appPort.postMessage({
- type: 'auth:received'
- });
-
- var origin;
- try {
- origin = getOrigin(appPort.sender.url);
- } catch (err) {
- return sendErrorToContentScript('auth', appPort, err);
- }
-
- var ah = this;
-
- this.getAccounts(function(err, accounts) {
- if (err) {
- return sendErrorToContentScript('auth', appPort, err);
- }
-
- if (!accounts || accounts.length === 0) {
- // No account exists. Create one and then call getCaveats.
- var retry = true;
- var createAccountCallback = function(err, createdAccount, token) {
- if (err) {
- // If the token we received from chrome.identity.getAuthToken failed
- // to authenticate for the identity server, it may because that the
- // cached token has expired.
- // So, we remove the token from the cache and retry once.
- // TODO(suharshs,nlacasse): Filter by a more specific set of errors.
- if (retry && token) {
- retry = false;
- return chrome.identity.removeCachedAuthToken({
- 'token': token
- }, function(){
- ah.createAccount(createAccountCallback);
- });
- } else if (retry) {
- // If the token was not returned from getAuthToken, force the logout
- // of the user and try again.
- // This usually happens when a user has changed their password from
- // a different browser instance and the current browser isn't logged
- // into their new account.
- return chrome.identity.launchWebAuthFlow({
- 'url': 'https://accounts.google.com/logout'
- }, function(tokenUrl) {
- ah.createdAccount(createAccountCallback);
- });
- }
- return sendErrorToContentScript('auth', appPort, err);
- }
- ah.getCaveats(createdAccount, origin, appPort);
- };
-
- ah.createAccount(createAccountCallback);
- } else {
- // At least one account already exists. Use the first one.
- var account = accounts[0];
-
- // Check if origin is associated.
- ah.originHasAccount(origin, function(err, hasAccount) {
- if (err) {
- return sendErrorToContentScript('auth', appPort, err);
- }
-
- if (hasAccount) {
- // Origin already associated. Return success.
- appPort.postMessage({
- type: 'auth:success',
- account: account
- });
- } else {
- // No origin associated. Get caveats and then associate.
- ah.getCaveats(account, origin, appPort);
- }
- });
- }
- });
-};
-
-AuthHandler.prototype.handleFinishAuth = function(caveatsPort, msg) {
- if (caveatsPort.sender.url.indexOf(chrome.extension.getURL(
- 'html/addcaveats.html')) !== 0) {
- console.error('invalid requester for associateAccount:finish');
- return;
- }
-
-
- this.finishAuth(msg);
-
- // Close the caveats tab.
- // Note: This triggers a call onRemovedTab().
- chrome.tabs.remove(caveatsPort.sender.tab.id);
-};
-
-AuthHandler.prototype.finishAuth = function(msg) {
- var appPorts = this._outstandingAuthRequests[msg.origin];
- delete this._outstandingAuthRequests[msg.origin];
- if (!Array.isArray(appPorts)) {
- console.error('Finish auth flow request received for unknown origin');
- return;
- }
-
- var self = this;
- appPorts.forEach(function(appPort) {
- if (msg.origin !== getOrigin(appPort.sender.url)) {
- console.error('Invalid origin.');
- return;
- }
-
- if (msg.cancel) {
- return sendErrorToContentScript('auth', appPort,
- new Error('User declined to bless origin.'));
- }
-
- if (msg.origin !== getOrigin(appPort.sender.url)) {
- return sendErrorToContentScript('auth', appPort,
- new Error('Invalid origin.'));
- }
-
- if (!appPort.account) {
- return sendErrorToContentScript('auth', appPort,
- new Error('No port.account.'));
- }
-
- if (!msg.caveats || msg.caveats.length === 0) {
- return sendErrorToContentScript('auth', appPort,
- new Error('No caveats selected'));
- }
-
- self.associateAccount(appPort.account, msg.origin, msg.caveats,
- function(err) {
- if (err) {
- return sendErrorToContentScript('auth', appPort, err);
- }
- appPort.postMessage({
- type: 'auth:success',
- account: appPort.account
- });
- });
- });
-};
-
-// Convert an Error object into a bare Object with the same properties. We do
-// this because port.postMessage calls JSON.stringify, which ignores the message
-// and stack properties on Error objects.
-function errorToObject(err) {
- var obj = {};
- Object.getOwnPropertyNames(err).forEach(function(key) {
- obj[key] = err[key];
- });
- return obj;
-}
-
-// Helper functions to send error message back to calling content script.
-function sendErrorToContentScript(type, port, err) {
- console.error(err);
- port.postMessage({
- type: type + ':error',
- error: errorToObject(err)
- });
-}
diff --git a/extension/src/background/channel.js b/extension/src/background/channel.js
deleted file mode 100644
index ed2264b..0000000
--- a/extension/src/background/channel.js
+++ /dev/null
@@ -1,168 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-/**
- * @fileoverview Channel RPCs to Nacl plugin.
- */
-
-var vom = require('../../../src/vom');
-var TaskSequence = require('../../../src/lib/task-sequence');
-var channelVdl =
- require('../../vdl/v.io/x/ref/services/wspr/internal/channel');
-var browsprVdl =
- require('../../vdl/v.io/x/ref/services/wspr/internal/browspr');
-var vlog = require('../../../src/lib/vlog');
-
-module.exports = RpcChannel;
-
-function uint8ArrayToArrayBuffer(arr) {
- return arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.length);
-}
-
-function RpcChannel(sendMessage) {
- if (!(this instanceof RpcChannel)) {
- return new RpcChannel(sendMessage);
- }
- this.sendMessage = sendMessage;
- this.lastSeq = 0;
- this.handlers = {};
- this.pendingCallbacks = {};
- this.decodeQueue = new TaskSequence();
-}
-
-RpcChannel.prototype.registerRpcHandler = function(type, func) {
- this.handlers[type] = func;
-};
-
-RpcChannel.prototype.performRpc = function(type, val, callback) {
- if (typeof val !== 'object') {
- throw new Error('val must be of type object, was ' + (typeof val));
- }
-
- var BrowsprMessage;
- switch(type) {
- case 'start':
- BrowsprMessage = browsprVdl.StartMessage;
- break;
- case 'auth:get-accounts':
- BrowsprMessage = browsprVdl.GetAccountsMessage;
- break;
- case 'auth:create-account':
- BrowsprMessage = browsprVdl.CreateAccountMessage;
- break;
- case 'auth:origin-has-account':
- BrowsprMessage = browsprVdl.OriginHasAccountMessage;
- break;
- case 'auth:associate-account':
- BrowsprMessage = browsprVdl.AssociateAccountMessage;
- break;
- case 'create-instance':
- BrowsprMessage = browsprVdl.CreateInstanceMessage;
- break;
- case 'cleanup':
- BrowsprMessage = browsprVdl.CleanupMessage;
- break;
- default:
- throw new Error('Unknown RPC type', type);
- }
-
- callback = callback || function(){};
- var seq = ++this.lastSeq;
- this.pendingCallbacks[seq] = callback;
- var request = new channelVdl.Request({
- type: type,
- seq: seq,
- body: new BrowsprMessage(val)
- });
- this._sendVomEncodedMessage(new channelVdl.Message({
- request: request
- }));
-};
-
-RpcChannel.prototype._sendVomEncodedMessage = function(msg) {
- var writer = new vom.ByteMessageWriter();
- var enc = new vom.Encoder(writer);
- enc.encode(msg);
- var encodedBytes = writer.getBytes();
- this._postMessage(uint8ArrayToArrayBuffer(encodedBytes));
-};
-
-RpcChannel.prototype._handleRequest = function(req) {
- var type = req.type;
- var handler = this.handlers[type];
- if (handler === undefined) {
- throw new Error('Undefined handler for type \'' + type + '\'');
- }
- var result;
- var err;
- try {
- result = handler(req.body);
- } catch (e) {
- err = e.message;
- // TODO(bprosnitz) Nil is not handled yet in VOM2.
- // Remove this when it is implemented.
- result = 'ResultMessageToBeRemovedWhenVOM2IsComplete';
- }
- var response = new channelVdl.Response({
- reqSeq: req.Seq,
- err: err || '',
- body: result
- });
- this._sendVomEncodedMessage(new channelVdl.Message({
- response: response
- }));
-};
-
-RpcChannel.prototype._handleResponse = function(resp) {
- var seq = resp.reqSeq;
- var cb = this.pendingCallbacks[seq];
- delete this.pendingCallbacks[seq];
- if (cb === undefined) {
- throw new Error('Received response with no matching sequence number '+
- JSON.stringify(resp));
- }
- if (resp.err !== '') {
- return cb(new Error(resp.err));
- }
- // TODO(nlacasse,bpronitz): Is it OK to just call "val" on the body like this?
- var body = resp.body && resp.body.val;
- cb(null, body);
-};
-
-RpcChannel.prototype._handleMessageTask = function(msg) {
- var msgBytes = new Uint8Array(msg);
- var reader = new vom.ByteArrayMessageReader(msgBytes);
- var dec = new vom.Decoder(reader);
- var channel = this;
- return dec.decode().then(function(jsMsg) {
- if (jsMsg._type.name === channelVdl.Message.name) {
- throw new Error('Message does not have correct Message type: ' +
- JSON.stringify(jsMsg));
- } else if (jsMsg.request) {
- return channel._handleRequest(jsMsg.request);
- } else if (jsMsg.response) {
- return channel._handleResponse(jsMsg.response);
- } else {
- var err = new Error('Message has Message type, but no "request" or ' +
- '"response" fields: ' + JSON.stringify(jsMsg));
- vlog.logger.error(err + ': ' + err.stack);
- }
- }, function(err) {
- vlog.logger.error(err + ': ' + err.stack);
- });
-};
-RpcChannel.prototype.handleMessage = function(msg) {
- // We add this to the task queue to make sure that the decode callback for
- // all the messages are peformed in order.
- this.decodeQueue.addTask(this._handleMessageTask.bind(this, msg));
-};
-
-RpcChannel.prototype._postMessage = function(msg) {
- this.sendMessage({
- type: 'browsprRpc',
- instanceId: -1,
- origin: '',
- body: msg,
- });
-};
diff --git a/extension/src/background/index.js b/extension/src/background/index.js
deleted file mode 100644
index 15aee31..0000000
--- a/extension/src/background/index.js
+++ /dev/null
@@ -1,324 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var _ = require('lodash');
-var debug = require('debug')('background:index');
-var domready = require('domready');
-
-var AuthHandler = require('./auth-handler');
-var extensionErrors = require('../../../src/browser/extension-errors');
-var getOrigin = require('./util').getOrigin;
-var Nacl = require('./nacl');
-
-
-domready(function() {
- // Start!
- var bp = new BackgroundPage();
- chrome.runtime.onConnect.addListener(
- bp.handleNewContentScriptConnection.bind(bp));
-
- // Set bp on the window so it will be accessable from options page.
- window.bp = bp;
- // Expose the state object so options page and background can share it and
- // stay in sync.
- bp.state = require('../state');
-});
-
-function BackgroundPage() {
- if (!(this instanceof BackgroundPage)) {
- return new BackgroundPage();
- }
-
- // Map that stores instanceId -> port so messages can be routed back to the
- // port they came from.
- this.ports = {};
-
- // Map that stores port -> instanceId list so browspr can cleanup the
- // instances corresponding when the port when the port closes.
- this.instanceIds = new Map();
-
- debug('background script loaded');
-}
-
-// Start listening to messages from the Nacl plugin.
-BackgroundPage.prototype.registerNaclListeners = function() {
- this.nacl.on('message', this.handleMessageFromNacl.bind(this));
- this.nacl.on('crash', this.handleNaclCrash.bind(this));
-};
-
-// Handle messages coming from Nacl by send them to the associated port.
-BackgroundPage.prototype.handleMessageFromNacl = function(msg) {
- var instanceId = msg.instanceId;
- var port = this.ports[instanceId];
- if (!port) {
- console.error('Message received not matching instance id: ', instanceId);
- return;
- }
- port.postMessage(msg);
-};
-
-
-// Handle messages coming from a content script.
-BackgroundPage.prototype.handleMessageFromContentScript = function(port, msg) {
- var bp = this;
-
- if (!this.naclPluginIsActive()) {
- // Start the plugin if it is not started.
- this.startNaclPlugin(handleMessage.bind(bp, port, msg));
- } else {
- handleMessage(port, msg);
- }
-
- function handleMessage(port, msg) {
- // Wrap in process.nextTick so chrome stack traces can use sourceMap.
- process.nextTick(function() {
- debug('background received message from content script.', msg);
-
- // Dispatch on the type of the message.
- switch (msg.type) {
- // From vanadium app.
- case 'browsprMsg':
- return bp.handleBrowsprMessage(port, msg);
- case 'browsprCleanup':
- return bp.handleBrowsprCleanup(port, msg);
- case 'createInstance':
- return bp.handleCreateInstance(port, msg);
- case 'auth':
- return bp.authHandler.handleAuthMessage(port);
-
- // From bless.
- case 'assocAccount:finish':
- return bp.authHandler.handleFinishAuth(port, msg);
-
- // ONLY for tests.
- case 'intentionallyPanic':
- return bp._triggerIntentionalPanic();
-
- default:
- console.error('unknown message.', msg);
- }
- });
- }
-};
-
-// Trigger a panic in the plug-in (only for tests).
-BackgroundPage.prototype._triggerIntentionalPanic = function() {
- if (process.env.ALLOW_INTENTIONAL_CRASH) {
- var panicMsg = {
- type: 'intentionallyPanic',
- instanceId: 0,
- origin: '',
- body: ''
- };
- this.nacl.sendMessage(panicMsg);
- }
-};
-
-// Handle a content script connecting to this background script.
-BackgroundPage.prototype.handleNewContentScriptConnection = function(port) {
- port.onMessage.addListener(
- this.handleMessageFromContentScript.bind(this, port));
-
- var bp = this;
- port.onDisconnect.addListener(function() {
- var instanceIds = bp.instanceIds.get(port) || [];
- instanceIds.forEach(function(instanceId) {
- bp.handleBrowsprCleanup(port, {body: {instanceId: instanceId}});
- });
- });
-};
-
-// Clean up an instance, and tell Nacl to clean it up as well.
-BackgroundPage.prototype.handleBrowsprCleanup = function(port, msg) {
- function sendCleanupFinishedMessage() {
- safePostMessage(port, {type: 'browsprCleanupFinished'});
- }
-
- if (!this.naclPluginIsActive()) {
- // If the plugin isn't started, no need to clean it up.
- sendCleanupFinishedMessage();
- return;
- }
-
- var instanceId = msg.body.instanceId;
-
- if (!this.ports[instanceId]) {
- return console.error('Got cleanup message from instance ' + instanceId +
- ' with no associated port.');
- }
-
- if (this.ports[instanceId] !== port) {
- return console.error('Got cleanup message for instance ' + instanceId +
- ' that does not match port.');
- }
-
- var bp = this;
- var now = Date.now();
- this.nacl.cleanupInstance(instanceId, function() {
- var end = Date.now();
- console.log('Cleaned up instance: ' + instanceId + ' in ' +
- (end - now) + ' ms');
- bp.instanceIds.set(port, _.remove(bp.instanceIds.get(port), [instanceId]));
- if (bp.instanceIds.get(port).length === 0) {
- bp.instanceIds.delete(port);
- }
- delete bp.ports[instanceId];
- sendCleanupFinishedMessage();
- bp.stopNaclPluginIfUnused();
- });
-};
-
-BackgroundPage.prototype.isValidMessageForPort = function(msg, port) {
- var body = msg.body;
- if (!body) {
- console.error('Got message with no body: ', msg);
- return false;
- }
- if (!body.instanceId) {
- console.error('Got message with no instanceId: ', msg);
- return false;
- }
- if (this.ports[body.instanceId] && this.ports[body.instanceId] !== port) {
- console.error('Got browspr message with instanceId ' +
- body.instanceId + ' that does not match port.');
- return false;
- }
- return true;
-};
-
-BackgroundPage.prototype.assocPortAndInstanceId = function(port, instanceId) {
- // Store the instanceId->port.
- this.ports[instanceId] = port;
- // Store the port->instanceId.
- this.instanceIds.set(port,
- _.union(this.instanceIds.get(port) || [], [instanceId]));
-
- // Cache the origin on the port object.
- port.origin = port.origin || getOrigin(port.sender.url);
-};
-
-
-// Handle an createInstance message.
-BackgroundPage.prototype.handleCreateInstance = function(port, msg) {
- if (!this.isValidMessageForPort(msg, port)) {
- return console.error('Invalid port for message. Ignoring.');
- }
-
- var body = msg.body;
- this.assocPortAndInstanceId(port, body.instanceId);
-
- this.nacl.channel.performRpc('create-instance', {
- instanceId: body.instanceId,
- origin: port.origin,
- namespaceRoots: body.settings.namespaceRoots,
- proxy: body.settings.proxy
- }, function(err) {
- if (err) {
- return safePostMessage(port, {type: 'createInstance:error', error: err});
- }
- safePostMessage(port, {type: 'createInstance:success'});
- });
-};
-
-// Handle messages that will be sent to Nacl.
-BackgroundPage.prototype.handleBrowsprMessage = function(port, msg) {
- if (!this.isValidMessageForPort(msg, port)) {
- return;
- }
-
- var body = msg.body;
- this.assocPortAndInstanceId(port, body.instanceId);
-
- var naclMsg = {
- type: msg.type,
- instanceId: parseInt(body.instanceId),
- origin: port.origin,
- body: body.msg
- };
- return this.nacl.sendMessage(naclMsg);
-};
-
-// Return true if the nacl plug-in is running.
-BackgroundPage.prototype.naclPluginIsActive = function() {
- return this.hasOwnProperty('nacl') && this.nacl.isReady;
-};
-
-// Start the nacl plug-in -- add it to the page and register handlers.
-BackgroundPage.prototype.startNaclPlugin = function(cb) {
- var bp = this;
- cb = cb || function() {};
-
- if (!bp.nacl) {
- bp.nacl = new Nacl();
- bp.registerNaclListeners();
- bp.nacl.once('ready', function() {
- bp.authHandler = new AuthHandler(bp.nacl.channel);
- });
- }
-
- bp.nacl.once('ready', cb.bind(bp));
-};
-
-// Stop the nacl plugin if it is not currently used.
-BackgroundPage.prototype.stopNaclPluginIfUnused = function() {
- if (Object.keys(this.ports).length === 0) {
- this.stopNaclPlugin();
- }
-};
-
-// Stop the nacl plug-in - remove it from the page and clean up state.
-BackgroundPage.prototype.stopNaclPlugin = function() {
- this.nacl.destroy();
- delete this.nacl;
-};
-
-// Stop and start the nacl plug-in
-BackgroundPage.prototype.restartNaclPlugin = function(cb) {
- cb = cb || function() {};
- if (this.naclPluginIsActive()) {
- this.stopNaclPlugin();
- }
- this.startNaclPlugin(cb);
-};
-
-// Returns an array of all active port objects.
-BackgroundPage.prototype.getAllPorts = function() {
- var ports = [];
- _.forEach(this.ports, function(portArray) {
- ports = ports.concat(portArray);
- });
- // Sort the ports array so that _.uniq can use a faster search algorithm.
- ports = _.sortBy(ports);
- // The second argument to _.uniq is whether the array is sorted.
- return _.uniq(ports, true);
-};
-
-// Restart nacl when it crashes.
-BackgroundPage.prototype.handleNaclCrash = function(msg) {
- // Log the crash to the extension's console.
- console.error('NACL plugin crashed.');
- if (msg) {
- console.error(msg);
- }
-
- // Restart the plugin
- this.stopNaclPlugin();
-
- // Notify all content scripts about the failure.
- var crashNotificationMsg = {
- type: 'crash',
- body: new extensionErrors.ExtensionCrashError(msg)
- };
- this.getAllPorts().forEach(function(port) {
- safePostMessage(port, crashNotificationMsg);
- });
-};
-
-function safePostMessage(port, msg) {
- try {
- port.postMessage(msg);
- } catch (e) {
- // Port no longer exists. Safe to ignore.
- }
-}
diff --git a/extension/src/background/nacl.js b/extension/src/background/nacl.js
deleted file mode 100644
index c87bc59..0000000
--- a/extension/src/background/nacl.js
+++ /dev/null
@@ -1,175 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var domready = require('domready');
-var EE = require('events').EventEmitter;
-var inherits = require('inherits');
-
-var Channel = require('./channel');
-var QueuedRpcChannelWrapper = require('./queued_channel');
-var state = require('../state');
-
-// Clean the extension blessing whenever the extension is updated.
-// See https://developer.chrome.com/extensions/runtime#event-onInstalled
-var cleanBlessingsOnStart = false;
-chrome.runtime.onInstalled.addListener(function(details) {
- if (details.reason === 'update') {
- cleanBlessingsOnStart = true;
- }
-});
-
-module.exports = Nacl;
-
-function Nacl() {
- if (!(this instanceof Nacl)) {
- return new Nacl();
- }
-
- EE.call(this);
-
- this._queuedMessages = [];
-
- // Wait until the dom is ready, then add 'load' and 'message' listeners on the
- // nacl plugin that will trigger events on this object.
- var nacl = this;
- domready(function(){
- nacl._naclElt = _createNaclElement();
- document.body.appendChild(nacl._naclElt);
-
- // 'load' listener must have useCapture argument set to 'true'.
- nacl._naclElt.addEventListener('load', nacl.emit.bind(nacl, 'load'), true);
- nacl._naclElt.addEventListener('crash', nacl.emit.bind(nacl, 'crash', null),
- true);
- nacl._naclElt.addEventListener('message', function(e) {
- var msg = e.data;
- if (msg instanceof ArrayBuffer) {
- // Message is response from a channel RPC.
- return nacl._directChannel.handleMessage(msg);
- }
- nacl.emit('message', msg);
- });
-
- // Channel for bi-directional RPCs.
- nacl._directChannel = new Channel(nacl._naclElt.postMessage.bind(nacl));
- nacl.channel = new QueuedRpcChannelWrapper(nacl._directChannel);
-
- // Send a signal to initialize the nacl plug-in.
- nacl._start();
- });
-}
-
-inherits(Nacl, EE);
-
-// Create an embed tag that will contain the nacl plugin.
-function _createNaclElement() {
- var naclElt = document.createElement('embed');
-
- var idAttr = document.createAttribute('id');
- idAttr.value = 'nacl';
- naclElt.setAttributeNode(idAttr);
-
- var srcAttr = document.createAttribute('src');
- srcAttr.value = '/nacl/main.nmf';
- naclElt.setAttributeNode(srcAttr);
-
- var typeAttr = document.createAttribute('type');
- typeAttr.value = 'application/x-nacl';
- naclElt.setAttributeNode(typeAttr);
-
- return naclElt;
-}
-
-// Send message from content script to Nacl.
-Nacl.prototype.sendMessage = function(msg) {
- if (!this._initialized) {
- this._queuedMessages.push(msg);
- return;
- }
- this._naclElt.postMessage(msg);
-};
-
-Nacl.prototype._start = function() {
- var nacl = this;
- var settings = state.settings();
- console.log(settings);
-
- this.getBlessingRoot(settings.identitydBlessingUrl.value,
- function(err, identityBlessingRoot) {
- if (err) {
- return nacl.emit('crash', err.message);
- }
-
- var body = {
- cleanupBlessings: cleanBlessingsOnStart,
- identitydBlessingRoot: identityBlessingRoot,
- identityd: settings.identityd.value,
- namespaceRoot: settings.namespaceRoot.value,
- proxy: settings.proxy.value,
- logLevel: parseInt(settings.logLevel.value) || 0,
- logModule: settings.logModule.value || ''
- };
-
- cleanBlessingsOnStart = false;
-
- nacl._directChannel.performRpc('start', body, function(err) {
- if (err) {
- return nacl.emit('crash', err.message);
- }
-
- nacl._initialized = true;
- nacl._sendQueuedMessages();
- nacl.channel.ready();
- nacl.isReady = true;
- nacl.emit('ready');
- });
- });
-};
-
-Nacl.prototype._sendQueuedMessages = function() {
- var nacl = this;
- this._queuedMessages.forEach(function(msg) {
- nacl._naclElt.postMessage(msg);
- });
- this._queuedMessages = [];
- console.log('Sent queued messages');
-};
-
-// Cache blessind root so we don't fetch it every time we start NaCl.
-var cachedBlessingRoot = null;
-Nacl.prototype.getBlessingRoot = function(url, cb) {
- if (cachedBlessingRoot) {
- return process.nextTick(function() {
- cb(null, cachedBlessingRoot);
- });
- }
-
- console.log('Requesting blessing root from ' + url);
- var request = require('superagent');
- request
- .get(url)
- .accept('application/json')
- .end(function(err, res) {
- if (err) {
- cb(err);
- } else if (res.error) {
- cb(new Error('' + res.status + ': ' + res.message));
- } else {
- cachedBlessingRoot = res.body;
- cb(null, cachedBlessingRoot);
- }
- });
-};
-
-Nacl.prototype.cleanupInstance = function(instanceId, cb) {
- this.channel.performRpc('cleanup', {
- instanceId: instanceId
- }, cb);
-};
-
-// Destroy state associated with this Nacl instance.
-// In particular, this removed the added embed tag.
-Nacl.prototype.destroy = function() {
- this._naclElt.parentNode.removeChild(this._naclElt);
- this._naclElt = null;
-};
diff --git a/extension/src/background/options.js b/extension/src/background/options.js
deleted file mode 100644
index fc374b1..0000000
--- a/extension/src/background/options.js
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var domready = require('domready');
-var mercury = require('mercury');
-var settings = require('../components/settings');
-if (typeof window !== 'undefined') {
- window.debug = require('debug');
-}
-
-domready(function() {
- chrome.runtime.getBackgroundPage(function(bpWindow) {
- // Use the state object from the background page, so options and background
- // stay in sync.
- var state = bpWindow.bp.state;
- mercury.app(document.body, state, render);
- });
-});
-
-function render(state, _diff) {
- return settings.render(state.settings);
-}
diff --git a/extension/src/background/queued_channel.js b/extension/src/background/queued_channel.js
deleted file mode 100644
index 1d5a559..0000000
--- a/extension/src/background/queued_channel.js
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-/**
- * @fileoverview Channel RPCs where all messages are enqueued until a ready
- * signal is received and then all RPC messages are sent.
- */
-
-module.exports = QueuedRpcChannelWrapper;
-
-function QueuedRpcChannelWrapper(rpcChannel) {
- this._rpcChannel = rpcChannel;
- this._ready = false;
- this._queuedRpcs = [];
-}
-
-QueuedRpcChannelWrapper.prototype.registerRpcHandler = function(type, func) {
- this._rpcChannel.registerRpcHandler(type, func);
-};
-
-QueuedRpcChannelWrapper.prototype.performRpc = function(type, val, callback) {
- if (!this._ready) {
- this._queuedRpcs.push({
- type: type,
- val: val,
- callback: callback
- });
- return;
- }
-
- this._rpcChannel.performRpc(type, val, callback);
-};
-
-QueuedRpcChannelWrapper.prototype.ready = function() {
- this._ready = true;
- var rpcChannel = this._rpcChannel;
- this._queuedRpcs.forEach(function(rpc) {
- rpcChannel.performRpc(rpc.type, rpc.val, rpc.callback);
- });
-};
diff --git a/extension/src/background/util.js b/extension/src/background/util.js
deleted file mode 100644
index 5e858b8..0000000
--- a/extension/src/background/util.js
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-module.exports = {
- getOrigin: getOrigin
-};
-
-// Parse a url and return the origin.
-function getOrigin(url) {
- var URL = require('url');
- var parsed = URL.parse(url);
- return parsed.protocol + '//' + parsed.host;
-}
diff --git a/extension/src/components/settings/index.css b/extension/src/components/settings/index.css
deleted file mode 100644
index a873de8..0000000
--- a/extension/src/components/settings/index.css
+++ /dev/null
@@ -1,37 +0,0 @@
-/* Copyright 2015 The Vanadium Authors. All rights reserved. */
-/* Use of this source code is governed by a BSD-style */
-/* license that can be found in the LICENSE file. */
-
-
-form.settings {
- box-sizing: border-box;
- max-width: 50%;
- min-width: 360px;
- margin: 0 auto;
- padding: 1.125em;
-}
-
-form.settings .input {
- border-bottom: 1px solid grey;
-}
-
-form.settings .input:first-of-type {
- border-top: 1px solid grey;
-}
-
-form.settings label,
-form.settings input {
- box-sizing: border-box;
- display: inline-block;
- width: 50%;
- padding: 1.125em;
-}
-
-form.settings label {
- width: 20%;
- text-align: right;
-}
-
-form.settings input.button {
- width: 20%;
-}
diff --git a/extension/src/components/settings/index.js b/extension/src/components/settings/index.js
deleted file mode 100644
index a84ad00..0000000
--- a/extension/src/components/settings/index.js
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var _ = require('lodash');
-var debug = require('debug')('component:settings');
-var mercury = require('mercury');
-var h = mercury.h;
-var xtend = require('xtend');
-
-var setting = require('./setting');
-
-// Temporary method of dealing with CSS
-var fs = require('fs');
-var insert = require('insert-css');
-var css = fs.readFileSync(__dirname + '/index.css');
-
-module.exports = create;
-module.exports.render = render;
-
-var defaults = {
- identityd: 'identity/dev.v.io/u/google',
- identitydBlessingUrl: 'https://dev.v.io/auth/blessing-root',
- namespaceRoot: '/(dev.v.io:role:vprod:service:mounttabled)@ns.dev.v.io:8101',
- proxy: 'proxy',
- logLevel: '0',
- logModule: ''
-};
-
-function render(settings) {
- debug('rendering', settings);
- insert(css);
-
- return h('div', [
- h('h3', 'Vanadium NaCl Plugin Options'),
- 'These settings are used to configure the Vanadium NaCl plugin.',
- 'You should use the defaults unless you know what you are doing.',
- h('br'),
- h('br'),
- 'NOTE: You must reload the plugin (see button below) ' +
- 'for any changes to take effect.',
- h('br'),
- h('br'),
- h('form.settings', _.map(settings, setting.render)),
- h('br'),
- h('br'),
- h('a', {
- href: '#',
- 'ev-click': mercury.clickEvent(reloadExtension)
- }, 'Reload plugin'),
- h('br'),
- h('br'),
- 'Manage your identities here: chrome://identity-internals/'
- ]);
-}
-
-function create() {
- debug('initializing');
-
- var settingsObj = defaults;
-
- var state = mercury.varhash({});
-
- if (process.env.EXTENSION_SETTINGS) {
- // Load the settings from the environment variable.
- var envSettings;
- try {
- envSettings = JSON.parse(process.env.EXTENSION_SETTINGS);
- } catch(e) {
- throw new Error('Could not parse settings from environment: ', e);
- }
- settingsObj = xtend(settingsObj, envSettings);
- }
-
- hydrateState(state, settingsObj);
-
- return {
- state: state
- };
-}
-
-// Hydrate the state varhash with settings from obj.
-function hydrateState(state, obj) {
- _.forEach(obj, function(value, key) {
- state.put(key, setting(key, value, defaults[key]).state);
- });
-}
-
-// Reload the extension.
-function reloadExtension() {
- chrome.runtime.getBackgroundPage(function(bpWindow) {
- // bpWindow is the 'window' object of the background page.
- bpWindow.bp.restartNaclPlugin();
- });
-}
diff --git a/extension/src/components/settings/setting.js b/extension/src/components/settings/setting.js
deleted file mode 100644
index efc279b..0000000
--- a/extension/src/components/settings/setting.js
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var mercury = require('mercury');
-var h = mercury.h;
-var debug = require('debug')('component:setting');
-
-module.exports = create;
-module.exports.render = render;
-
-function render(setting) {
- debug('rendering', setting);
- var id = 'setting-' + setting.key;
-
- return h('.input', [
- h('label', { for: id }, setting.key),
- h('input', {
- id: id,
- name: 'value',
- type: 'text',
- value: setting.value,
- 'ev-event': mercury.changeEvent(setting.events.update)
- }),
- h('input.button', {
- id: id,
- name: 'default',
- type: 'button',
- value: 'Restore\ndefault',
- 'ev-event': mercury.event(setting.events.restoreDefault)
- })
- ]);
-}
-
-function create(key, value, defaultValue) {
- debug('initializing', key, 'to', value, 'with default', defaultValue);
-
- var state = mercury.struct({
- key: mercury.value(key || null),
- value: mercury.value(value || null),
- defaultValue: mercury.value(defaultValue || null),
- events: mercury.input([ 'update', 'restoreDefault' ])
- });
-
- state.events.update = function(data) {
- debug('updating', data);
- state.value.set(data.value);
- };
-
- state.events.restoreDefault = function(){
- state.value.set(defaultValue);
- };
-
- return { state: state };
-}
diff --git a/extension/src/content/event-proxy.js b/extension/src/content/event-proxy.js
deleted file mode 100644
index 08a055c..0000000
--- a/extension/src/content/event-proxy.js
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var EE = require('eventemitter2').EventEmitter2;
-var inherits = require('inherits');
-
-var types = require('../../../src/browser/event-proxy-message-types');
-
-// PageEventProxy sends messages to the web page, and listens for messages
-// coming from the web page.
-// Note: We need to be careful to not expose the messages to iframes of
-// different origins. dispatchEvent is used instead of postMessage to origin '*'
-// because it isolates message to the sender's origin.
-// Tests showing this: https://gist.github.com/bprosnitz/89db637b2e798ce05a6a
-function PageEventProxy(){
- if (!(this instanceof PageEventProxy)) {
- return new PageEventProxy();
- }
- EE.call(this);
- var proxy = this;
- window.addEventListener(types.TO_EXTENSION, function(ev) {
- proxy.emit(ev.detail.type, ev.detail.body);
- });
-
- // Respond to "is_ready" events with "ready" events.
- window.addEventListener(types.EXTENSION_IS_READY, function() {
- window.dispatchEvent(new CustomEvent(types.EXTENSION_READY));
- });
-}
-inherits(PageEventProxy, EE);
-
-PageEventProxy.prototype.send = function(type, body) {
- window.dispatchEvent(
- new window.CustomEvent(types.TO_PAGE, {
- detail: {
- type: type,
- body: body
- }
- })
- );
-};
-
-module.exports = new PageEventProxy();
diff --git a/extension/src/content/index.js b/extension/src/content/index.js
deleted file mode 100644
index 09d32ef..0000000
--- a/extension/src/content/index.js
+++ /dev/null
@@ -1,112 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var debug = require('debug')('content-script:index');
-
-var pageEventProxy = require('./event-proxy');
-var random = require('../../../src/lib/random');
-
-// Port to communicate with background js.
-// One content script runs per iframe / tabs so there may be multiple ports
-// per page.
-var _backgroundPort;
-function getBackgroundPort() {
- // Lazily connect to background port.
- if (!_backgroundPort) {
- _backgroundPort = chrome.runtime.connect();
- _backgroundPort.onMessage.addListener(backgroundPageMessageForwarder);
- }
- return _backgroundPort;
-}
-
-// We generate and send different instanceIds to the background page than those
-// coming from the web app. This prevents the web app from intentionally
-// colliding with instanceIds from apps on other tabs. The two maps below are
-// used to map between the two instanceIds.
-var backgroundToPage = {};
-var pageToBackground = {};
-
-// If the plug-in crashed, the state of the connected Vanadium instances
-// are invalid. We will block any further messages.
-var invalidated = false;
-
-// Whitelist of message types to allow from the web app.
-var messageTypeWhitelist = [
- 'auth',
- 'browsprCleanup',
- 'browsprMsg',
- 'createInstance'
-];
-if (process.env.ALLOW_INTENTIONAL_CRASH) {
- messageTypeWhitelist.push('intentionallyPanic');
-}
-
-function isAllowedMessage(type) {
- return messageTypeWhitelist.indexOf(type) >= 0;
-}
-
-// Forward messages from the webApp to the background page.
-pageEventProxy.onAny(function(body) {
- if (invalidated && !process.env.ALLOW_INTENTIONAL_CRASH) {
- pageEventProxy.send('error', 'Refusing to send Vanadium message. ' +
- 'Plug-in crashed and page must be reloaded.');
- return;
- }
-
- // 'this' is bound to event emitter2 instance, which sets 'this.event' to the
- // type of the event.
- var type = this.event;
- debug('content script received message of type', type, 'from page:', body);
-
- if (!isAllowedMessage(type)) {
- var err = new Error('Ignoring message with unknown type: ' + type);
- console.error(err);
- pageEventProxy.send('error', { message: err.message });
- return;
- }
-
- // Swap the instanceId with a generated one.
- if (body && body.instanceId) {
- var outgoingInstanceId = pageToBackground[body.instanceId] ||
- random.int32();
- pageToBackground[body.instanceId] = outgoingInstanceId;
- backgroundToPage[outgoingInstanceId] = body.instanceId;
- body.instanceId = outgoingInstanceId;
- }
-
- try {
- getBackgroundPort().postMessage({
- type: this.event,
- body: body
- });
- } catch (err) {
- pageEventProxy.send('error', 'Error posting message, ' +
- 'you may need to reload this tab. ' + err);
- }
-});
-
-// Forward any messages from the background page to the webApp.
-function backgroundPageMessageForwarder(msg) {
- debug('content script received message of type', msg.type,
- 'from background script:', msg.body);
-
- if (msg.type === 'crash') {
- // Block any future messages, as we don't currently have a way to
- // be sure the response will be correct.
- invalidated = true;
-
- pageEventProxy.send('crash', msg.body);
-
- return;
- }
-
- // Swap the instanceId with the original one.
- if (msg.instanceId) {
- msg.instanceId = backgroundToPage[msg.instanceId];
- }
-
- pageEventProxy.send(msg.type, msg);
-}
-
-debug('content script loaded');
diff --git a/extension/src/state.js b/extension/src/state.js
deleted file mode 100644
index 335091a..0000000
--- a/extension/src/state.js
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var mercury = require('mercury');
-var settings = require('./components/settings');
-var state;
-
-module.exports = state = mercury.struct({
- error: mercury.value(null),
- settings: settings().state
-});
-
diff --git a/go/src/v.io/x/js.core/stress/stress.vdl b/go/src/v.io/x/js.core/stress/stress.vdl
deleted file mode 100644
index 6858b7d..0000000
--- a/go/src/v.io/x/js.core/stress/stress.vdl
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package stress
-
-import (
- "time"
- "v.io/v23/security/access"
-)
-
-type StressResults struct {
- Iterations int64
- Qps float64
- MsecsPerRpc float64
-}
-
-type Stress interface {
- // Echo returns the payload that it receives.
- Echo(Payload []byte) ([]byte | error) {access.Read}
-
- // ServerEcho runs as many calls to Echo on the name provided in the duration
- // specified and returns the peformance results.
- ServerEcho(totalTime time.Duration, name string) (StressResults | error) {access.Read}
-}
diff --git a/go/src/v.io/x/js.core/stress/stress.vdl.go b/go/src/v.io/x/js.core/stress/stress.vdl.go
deleted file mode 100644
index 864888f..0000000
--- a/go/src/v.io/x/js.core/stress/stress.vdl.go
+++ /dev/null
@@ -1,293 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// This file was auto-generated by the vanadium vdl tool.
-// Package: stress
-
-package stress
-
-import (
- "fmt"
- "time"
- "v.io/v23"
- "v.io/v23/context"
- "v.io/v23/rpc"
- "v.io/v23/security/access"
- "v.io/v23/vdl"
- _ "v.io/v23/vdlroot/time"
-)
-
-var _ = __VDLInit() // Must be first; see __VDLInit comments for details.
-
-//////////////////////////////////////////////////
-// Type definitions
-
-type StressResults struct {
- Iterations int64
- Qps float64
- MsecsPerRpc float64
-}
-
-func (StressResults) __VDLReflect(struct {
- Name string `vdl:"v.io/x/js.core/stress.StressResults"`
-}) {
-}
-
-func (m *StressResults) FillVDLTarget(t vdl.Target, tt *vdl.Type) error {
- fieldsTarget1, err := t.StartFields(tt)
- if err != nil {
- return err
- }
-
- keyTarget2, fieldTarget3, err := fieldsTarget1.StartField("Iterations")
- if err != vdl.ErrFieldNoExist && err != nil {
- return err
- }
- if err != vdl.ErrFieldNoExist {
- if err := fieldTarget3.FromInt(int64(m.Iterations), tt.NonOptional().Field(0).Type); err != nil {
- return err
- }
- if err := fieldsTarget1.FinishField(keyTarget2, fieldTarget3); err != nil {
- return err
- }
- }
- keyTarget4, fieldTarget5, err := fieldsTarget1.StartField("Qps")
- if err != vdl.ErrFieldNoExist && err != nil {
- return err
- }
- if err != vdl.ErrFieldNoExist {
- if err := fieldTarget5.FromFloat(float64(m.Qps), tt.NonOptional().Field(1).Type); err != nil {
- return err
- }
- if err := fieldsTarget1.FinishField(keyTarget4, fieldTarget5); err != nil {
- return err
- }
- }
- keyTarget6, fieldTarget7, err := fieldsTarget1.StartField("MsecsPerRpc")
- if err != vdl.ErrFieldNoExist && err != nil {
- return err
- }
- if err != vdl.ErrFieldNoExist {
- if err := fieldTarget7.FromFloat(float64(m.MsecsPerRpc), tt.NonOptional().Field(2).Type); err != nil {
- return err
- }
- if err := fieldsTarget1.FinishField(keyTarget6, fieldTarget7); err != nil {
- return err
- }
- }
- if err := t.FinishFields(fieldsTarget1); err != nil {
- return err
- }
- return nil
-}
-
-func (m *StressResults) MakeVDLTarget() vdl.Target {
- return &StressResultsTarget{Value: m}
-}
-
-type StressResultsTarget struct {
- Value *StressResults
- iterationsTarget vdl.Int64Target
- qpsTarget vdl.Float64Target
- msecsPerRpcTarget vdl.Float64Target
- vdl.TargetBase
- vdl.FieldsTargetBase
-}
-
-func (t *StressResultsTarget) StartFields(tt *vdl.Type) (vdl.FieldsTarget, error) {
-
- if ttWant := vdl.TypeOf((*StressResults)(nil)).Elem(); !vdl.Compatible(tt, ttWant) {
- return nil, fmt.Errorf("type %v incompatible with %v", tt, ttWant)
- }
- return t, nil
-}
-func (t *StressResultsTarget) StartField(name string) (key, field vdl.Target, _ error) {
- switch name {
- case "Iterations":
- t.iterationsTarget.Value = &t.Value.Iterations
- target, err := &t.iterationsTarget, error(nil)
- return nil, target, err
- case "Qps":
- t.qpsTarget.Value = &t.Value.Qps
- target, err := &t.qpsTarget, error(nil)
- return nil, target, err
- case "MsecsPerRpc":
- t.msecsPerRpcTarget.Value = &t.Value.MsecsPerRpc
- target, err := &t.msecsPerRpcTarget, error(nil)
- return nil, target, err
- default:
- return nil, nil, fmt.Errorf("field %s not in struct v.io/x/js.core/stress.StressResults", name)
- }
-}
-func (t *StressResultsTarget) FinishField(_, _ vdl.Target) error {
- return nil
-}
-func (t *StressResultsTarget) FinishFields(_ vdl.FieldsTarget) error {
-
- return nil
-}
-
-// Create zero values for each type.
-var (
- __VDLZeroStressResults = StressResults{}
-)
-
-//////////////////////////////////////////////////
-// Interface definitions
-
-// StressClientMethods is the client interface
-// containing Stress methods.
-type StressClientMethods interface {
- // Echo returns the payload that it receives.
- Echo(_ *context.T, Payload []byte, _ ...rpc.CallOpt) ([]byte, error)
- // ServerEcho runs as many calls to Echo on the name provided in the duration
- // specified and returns the peformance results.
- ServerEcho(_ *context.T, totalTime time.Duration, name string, _ ...rpc.CallOpt) (StressResults, error)
-}
-
-// StressClientStub adds universal methods to StressClientMethods.
-type StressClientStub interface {
- StressClientMethods
- rpc.UniversalServiceMethods
-}
-
-// StressClient returns a client stub for Stress.
-func StressClient(name string) StressClientStub {
- return implStressClientStub{name}
-}
-
-type implStressClientStub struct {
- name string
-}
-
-func (c implStressClientStub) Echo(ctx *context.T, i0 []byte, opts ...rpc.CallOpt) (o0 []byte, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "Echo", []interface{}{i0}, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implStressClientStub) ServerEcho(ctx *context.T, i0 time.Duration, i1 string, opts ...rpc.CallOpt) (o0 StressResults, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "ServerEcho", []interface{}{i0, i1}, []interface{}{&o0}, opts...)
- return
-}
-
-// StressServerMethods is the interface a server writer
-// implements for Stress.
-type StressServerMethods interface {
- // Echo returns the payload that it receives.
- Echo(_ *context.T, _ rpc.ServerCall, Payload []byte) ([]byte, error)
- // ServerEcho runs as many calls to Echo on the name provided in the duration
- // specified and returns the peformance results.
- ServerEcho(_ *context.T, _ rpc.ServerCall, totalTime time.Duration, name string) (StressResults, error)
-}
-
-// StressServerStubMethods is the server interface containing
-// Stress methods, as expected by rpc.Server.
-// There is no difference between this interface and StressServerMethods
-// since there are no streaming methods.
-type StressServerStubMethods StressServerMethods
-
-// StressServerStub adds universal methods to StressServerStubMethods.
-type StressServerStub interface {
- StressServerStubMethods
- // Describe the Stress interfaces.
- Describe__() []rpc.InterfaceDesc
-}
-
-// StressServer returns a server stub for Stress.
-// It converts an implementation of StressServerMethods into
-// an object that may be used by rpc.Server.
-func StressServer(impl StressServerMethods) StressServerStub {
- stub := implStressServerStub{
- impl: impl,
- }
- // Initialize GlobState; always check the stub itself first, to handle the
- // case where the user has the Glob method defined in their VDL source.
- if gs := rpc.NewGlobState(stub); gs != nil {
- stub.gs = gs
- } else if gs := rpc.NewGlobState(impl); gs != nil {
- stub.gs = gs
- }
- return stub
-}
-
-type implStressServerStub struct {
- impl StressServerMethods
- gs *rpc.GlobState
-}
-
-func (s implStressServerStub) Echo(ctx *context.T, call rpc.ServerCall, i0 []byte) ([]byte, error) {
- return s.impl.Echo(ctx, call, i0)
-}
-
-func (s implStressServerStub) ServerEcho(ctx *context.T, call rpc.ServerCall, i0 time.Duration, i1 string) (StressResults, error) {
- return s.impl.ServerEcho(ctx, call, i0, i1)
-}
-
-func (s implStressServerStub) Globber() *rpc.GlobState {
- return s.gs
-}
-
-func (s implStressServerStub) Describe__() []rpc.InterfaceDesc {
- return []rpc.InterfaceDesc{StressDesc}
-}
-
-// StressDesc describes the Stress interface.
-var StressDesc rpc.InterfaceDesc = descStress
-
-// descStress hides the desc to keep godoc clean.
-var descStress = rpc.InterfaceDesc{
- Name: "Stress",
- PkgPath: "v.io/x/js.core/stress",
- Methods: []rpc.MethodDesc{
- {
- Name: "Echo",
- Doc: "// Echo returns the payload that it receives.",
- InArgs: []rpc.ArgDesc{
- {"Payload", ``}, // []byte
- },
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // []byte
- },
- Tags: []*vdl.Value{vdl.ValueOf(access.Tag("Read"))},
- },
- {
- Name: "ServerEcho",
- Doc: "// ServerEcho runs as many calls to Echo on the name provided in the duration\n// specified and returns the peformance results.",
- InArgs: []rpc.ArgDesc{
- {"totalTime", ``}, // time.Duration
- {"name", ``}, // string
- },
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // StressResults
- },
- Tags: []*vdl.Value{vdl.ValueOf(access.Tag("Read"))},
- },
- },
-}
-
-var __VDLInitCalled bool
-
-// __VDLInit performs vdl initialization. It is safe to call multiple times.
-// If you have an init ordering issue, just insert the following line verbatim
-// into your source files in this package, right after the "package foo" clause:
-//
-// var _ = __VDLInit()
-//
-// The purpose of this function is to ensure that vdl initialization occurs in
-// the right order, and very early in the init sequence. In particular, vdl
-// registration and package variable initialization needs to occur before
-// functions like vdl.TypeOf will work properly.
-//
-// This function returns a dummy value, so that it can be used to initialize the
-// first var in the file, to take advantage of Go's defined init order.
-func __VDLInit() struct{} {
- if __VDLInitCalled {
- return struct{}{}
- }
-
- // Register types.
- vdl.Register((*StressResults)(nil))
-
- return struct{}{}
-}
diff --git a/go/src/v.io/x/js.core/stress/stressd/main.go b/go/src/v.io/x/js.core/stress/stressd/main.go
deleted file mode 100644
index 1e82936..0000000
--- a/go/src/v.io/x/js.core/stress/stressd/main.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "runtime"
-
- "v.io/v23"
- "v.io/v23/security"
- "v.io/x/lib/vlog"
- "v.io/x/ref/lib/signals"
- _ "v.io/x/ref/runtime/factories/generic"
-)
-
-func main() {
- runtime.GOMAXPROCS(runtime.NumCPU())
- ctx, shutdown := v23.Init()
- defer shutdown()
-
- ctx, _, err := v23.WithNewServer(ctx, "", NewStressService(), security.AllowEveryone())
- if err != nil {
- vlog.Fatalf("NewServer failed: %v", err)
- }
- <-signals.ShutdownOnSignals(ctx)
-}
diff --git a/go/src/v.io/x/js.core/stress/stressd/server.go b/go/src/v.io/x/js.core/stress/stressd/server.go
deleted file mode 100644
index 0f041dd..0000000
--- a/go/src/v.io/x/js.core/stress/stressd/server.go
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "bytes"
- "fmt"
- "time"
-
- "v.io/v23/context"
- "v.io/v23/rpc"
- "v.io/x/js.core/stress"
-)
-
-const payloadSize = 1000
-
-type impl struct{}
-
-func NewStressService() stress.StressServerStub {
- return stress.StressServer(&impl{})
-}
-
-func (s *impl) Echo(_ *context.T, _ rpc.ServerCall, payload []byte) ([]byte, error) {
- return payload, nil
-}
-
-func (s *impl) ServerEcho(ctx *context.T, _ rpc.ServerCall, totalTime time.Duration, name string) (stress.StressResults, error) {
- stub := stress.StressClient(name)
- payload := make([]byte, payloadSize)
- for i := range payload {
- payload[i] = byte(i & 0xff)
- }
- var iterations int64
- var res stress.StressResults
- start := time.Now()
- for {
- got, err := stub.Echo(ctx, payload)
- if err != nil {
- return res, err
- }
- if !bytes.Equal(got, payload) {
- return res, fmt.Errorf("Echo returned %v, but expected %v", got, payload)
- }
- iterations++
-
- if time.Since(start) >= totalTime {
- break
- }
- }
- duration := time.Since(start).Seconds()
- res.Iterations = iterations
- res.Qps = float64(iterations) / duration
- res.MsecsPerRpc = 1000 / res.Qps
- return res, nil
-}
diff --git a/go/src/v.io/x/js.core/test_service/cache.vdl b/go/src/v.io/x/js.core/test_service/cache.vdl
deleted file mode 100644
index 4292cfe..0000000
--- a/go/src/v.io/x/js.core/test_service/cache.vdl
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package test_service
-
-// KeyPageResult is a page of 10 keys.
-type KeyPageResult [10]string
-
-// A Cache service mimics the memcache interface.
-type Cache interface {
- // Set sets a value for a key.
- Set(key string, value any) error
-
- // Get returns the value for a key. If the value is not found, returns
- // a not found error.
- Get(key string) (any | error)
-
- // Same as Get, but casts the return argument to an byte.
- GetAsByte(key string) (byte | error)
- // Same as Get, but casts the return argument to an int32.
- GetAsInt32(key string) (int32 | error)
- // Same as Get, but casts the return argument to an int64.
- GetAsInt64(key string) (int64 | error)
- // Same as Get, but casts the return argument to an uint32.
- GetAsUint32(key string) (uint32 | error)
- // Same as Get, but casts the return argument to an uint64.
- GetAsUint64(key string) (uint64 | error)
- // Same as Get, but casts the return argument to an float32.
- GetAsFloat32(key string) (float32 | error)
- // Same as Get, but casts the return argument to an float64.
- GetAsFloat64(key string) (float64 | error)
- // Same as Get, but casts the return argument to a string.
- GetAsString(key string) (string | error)
- // Same as Get, but casts the return argument to a bool.
- GetAsBool(key string) (bool | error)
- // Same as Get, but casts the return argument to an error.
- GetAsError(key string) (error | error)
-
- // AsMap returns the full contents of the cache as a map.
- AsMap() (map[string]any | error)
-
- // KeyValuePairs returns the full contents of the cache as a slice of pairs.
- KeyValuePairs() ([]KeyValuePair | error)
-
- // MostRecentSet returns the key and value and the timestamp for the most
- // recent set operation
- // TODO(bprosnitz) support type types and change time to native time type
- MostRecentSet() (value KeyValuePair, time int64 | error)
-
- // KeyPage indexes into the keys (in alphanumerically sorted order) and
- // returns the indexth page of 10 keys.
- KeyPage(index int64) (KeyPageResult | error)
-
- // Size returns the total number of entries in the cache.
- Size() (int64 | error)
-
- // MultiGet sets up a stream that allows fetching multiple keys.
- MultiGet() stream<string, any> error
-}
-
-// KeyValuePair is a representation of a cached key and value pair.
-type KeyValuePair struct {
- Key string
- Value any
-}
diff --git a/go/src/v.io/x/js.core/test_service/cancel_collector.vdl b/go/src/v.io/x/js.core/test_service/cancel_collector.vdl
deleted file mode 100644
index f5c2e1c..0000000
--- a/go/src/v.io/x/js.core/test_service/cancel_collector.vdl
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package test_service
-
-// CancelCollector is a test interface for use in testing cancellation and deadlines.
-type CancelCollector interface {
- // A function that never returns, but records the status of the given key.
- NeverReturn(key int64) error
-
- // Wait for the call with the given key to have the given status. Possible statuses are:
- // "running", and, "cancelled". Returns the number of nanoseconds left on
- // the deadline of the specified call when the call first began.
- WaitForStatus(key int64, status string) (timeout int64 | error)
-}
diff --git a/go/src/v.io/x/js.core/test_service/doc.go b/go/src/v.io/x/js.core/test_service/doc.go
deleted file mode 100644
index 949abfd..0000000
--- a/go/src/v.io/x/js.core/test_service/doc.go
+++ /dev/null
@@ -1,6 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package test_service is a veyron service that is used for integration testing of the JavaScript API
-package test_service
diff --git a/go/src/v.io/x/js.core/test_service/error_thrower.vdl b/go/src/v.io/x/js.core/test_service/error_thrower.vdl
deleted file mode 100644
index 07d16cd..0000000
--- a/go/src/v.io/x/js.core/test_service/error_thrower.vdl
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package test_service
-
-// A testing interface with methods that throw various types of errors
-type ErrorThrower interface {
- // Throws v23/vError.Aborted error
- ThrowAborted() error
-
- // Throws v23/vError.BadArg error
- ThrowBadArg() error
-
- // Throws v23/vError.BadProtocol error
- ThrowBadProtocol() error
-
- // Throws v23/vError.Internal error
- ThrowInternal() error
-
- // Throws v23/vError.NoAccess error
- ThrowNoAccess() error
-
- // Throws v23/vError.NoExist error
- ThrowNoExist() error
-
- // Throws v23/vError.NoExistOrNoAccess error
- ThrowNoExistOrNoAccess() error
-
- // Throws v23/vError.Unknown error
- ThrowUnknown() error
-
- // Throws normal Go error
- ThrowGoError() error
-
- // Throws custom error created by using Standard
- ThrowCustomStandardError() error
-}
diff --git a/go/src/v.io/x/js.core/test_service/invoke_method_caveat_id.vdl b/go/src/v.io/x/js.core/test_service/invoke_method_caveat_id.vdl
deleted file mode 100644
index ee4e315..0000000
--- a/go/src/v.io/x/js.core/test_service/invoke_method_caveat_id.vdl
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package test_service
-
-import (
- "v.io/v23/uniqueid"
- "v.io/v23/security"
-)
-
-type InvokableTestMethod interface {
- AMethod() (string | error)
-}
-
-type InvokeMethodWithCaveatedIdentity interface {
- Invoke(name string, cavDesc security.CaveatDescriptor, cavParam any) error
-}
-
-type TestCaveatData struct {
- A string
- B any // Use any for value so that we can confirm VDL is being used properly.
-}
-
-const (
- ConditionallyValidatingTestCaveat = security.CaveatDescriptor{
- Id: uniqueid.Id{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff},
- ParamType: typeobject(TestCaveatData),
- }
-)
diff --git a/go/src/v.io/x/js.core/test_service/native.vdl b/go/src/v.io/x/js.core/test_service/native.vdl
deleted file mode 100644
index 69d3a86..0000000
--- a/go/src/v.io/x/js.core/test_service/native.vdl
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package test_service
-
-import "time"
-
-type NativeTest interface {
- PassTime(t time.Time) (time.Time | error)
-
- PassError(e error) error
-}
diff --git a/go/src/v.io/x/js.core/test_service/test_service.vdl.go b/go/src/v.io/x/js.core/test_service/test_service.vdl.go
deleted file mode 100644
index 4d68751..0000000
--- a/go/src/v.io/x/js.core/test_service/test_service.vdl.go
+++ /dev/null
@@ -1,1756 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// This file was auto-generated by the vanadium vdl tool.
-// Package: test_service
-
-package test_service
-
-import (
- "fmt"
- "io"
- "reflect"
- "time"
- "v.io/v23"
- "v.io/v23/context"
- "v.io/v23/rpc"
- "v.io/v23/security"
- "v.io/v23/uniqueid"
- "v.io/v23/vdl"
- _ "v.io/v23/vdlroot/time"
- "v.io/v23/vom"
-)
-
-var _ = __VDLInit() // Must be first; see __VDLInit comments for details.
-
-//////////////////////////////////////////////////
-// Type definitions
-
-// KeyPageResult is a page of 10 keys.
-type KeyPageResult [10]string
-
-func (KeyPageResult) __VDLReflect(struct {
- Name string `vdl:"v.io/x/js.core/test_service.KeyPageResult"`
-}) {
-}
-
-func (m *KeyPageResult) FillVDLTarget(t vdl.Target, tt *vdl.Type) error {
- listTarget1, err := t.StartList(tt, 10)
- if err != nil {
- return err
- }
- for i, elem3 := range *m {
- elemTarget2, err := listTarget1.StartElem(i)
- if err != nil {
- return err
- }
- if err := elemTarget2.FromString(string(elem3), tt.NonOptional().Elem()); err != nil {
- return err
- }
- if err := listTarget1.FinishElem(elemTarget2); err != nil {
- return err
- }
- }
- if err := t.FinishList(listTarget1); err != nil {
- return err
- }
- return nil
-}
-
-func (m *KeyPageResult) MakeVDLTarget() vdl.Target {
- return &KeyPageResultTarget{Value: m}
-}
-
-// KeyPageResult
-type KeyPageResultTarget struct {
- Value *KeyPageResult
- elemTarget vdl.StringTarget
- vdl.TargetBase
- vdl.ListTargetBase
-}
-
-func (t *KeyPageResultTarget) StartList(tt *vdl.Type, len int) (vdl.ListTarget, error) {
-
- if ttWant := vdl.TypeOf((*KeyPageResult)(nil)); !vdl.Compatible(tt, ttWant) {
- return nil, fmt.Errorf("type %v incompatible with %v", tt, ttWant)
- }
- return t, nil
-}
-func (t *KeyPageResultTarget) StartElem(index int) (elem vdl.Target, _ error) {
- t.elemTarget.Value = &(*t.Value)[index]
- target, err := &t.elemTarget, error(nil)
- return target, err
-}
-func (t *KeyPageResultTarget) FinishElem(elem vdl.Target) error {
- return nil
-}
-func (t *KeyPageResultTarget) FinishList(elem vdl.ListTarget) error {
-
- return nil
-}
-
-// KeyValuePair is a representation of a cached key and value pair.
-type KeyValuePair struct {
- Key string
- Value *vom.RawBytes
-}
-
-func (KeyValuePair) __VDLReflect(struct {
- Name string `vdl:"v.io/x/js.core/test_service.KeyValuePair"`
-}) {
-}
-
-func (m *KeyValuePair) FillVDLTarget(t vdl.Target, tt *vdl.Type) error {
- fieldsTarget1, err := t.StartFields(tt)
- if err != nil {
- return err
- }
-
- keyTarget2, fieldTarget3, err := fieldsTarget1.StartField("Key")
- if err != vdl.ErrFieldNoExist && err != nil {
- return err
- }
- if err != vdl.ErrFieldNoExist {
- if err := fieldTarget3.FromString(string(m.Key), tt.NonOptional().Field(0).Type); err != nil {
- return err
- }
- if err := fieldsTarget1.FinishField(keyTarget2, fieldTarget3); err != nil {
- return err
- }
- }
- keyTarget4, fieldTarget5, err := fieldsTarget1.StartField("Value")
- if err != vdl.ErrFieldNoExist && err != nil {
- return err
- }
- if err != vdl.ErrFieldNoExist {
-
- if m.Value == nil {
- if err := fieldTarget5.FromNil(tt.NonOptional().Field(1).Type); err != nil {
- return err
- }
- } else {
- if err := m.Value.FillVDLTarget(fieldTarget5, tt.NonOptional().Field(1).Type); err != nil {
- return err
- }
- }
- if err := fieldsTarget1.FinishField(keyTarget4, fieldTarget5); err != nil {
- return err
- }
- }
- if err := t.FinishFields(fieldsTarget1); err != nil {
- return err
- }
- return nil
-}
-
-func (m *KeyValuePair) MakeVDLTarget() vdl.Target {
- return &KeyValuePairTarget{Value: m}
-}
-
-type KeyValuePairTarget struct {
- Value *KeyValuePair
- keyTarget vdl.StringTarget
-
- vdl.TargetBase
- vdl.FieldsTargetBase
-}
-
-func (t *KeyValuePairTarget) StartFields(tt *vdl.Type) (vdl.FieldsTarget, error) {
-
- if ttWant := vdl.TypeOf((*KeyValuePair)(nil)).Elem(); !vdl.Compatible(tt, ttWant) {
- return nil, fmt.Errorf("type %v incompatible with %v", tt, ttWant)
- }
- return t, nil
-}
-func (t *KeyValuePairTarget) StartField(name string) (key, field vdl.Target, _ error) {
- switch name {
- case "Key":
- t.keyTarget.Value = &t.Value.Key
- target, err := &t.keyTarget, error(nil)
- return nil, target, err
- case "Value":
- target, err := vdl.ReflectTarget(reflect.ValueOf(&t.Value.Value))
- return nil, target, err
- default:
- return nil, nil, fmt.Errorf("field %s not in struct v.io/x/js.core/test_service.KeyValuePair", name)
- }
-}
-func (t *KeyValuePairTarget) FinishField(_, _ vdl.Target) error {
- return nil
-}
-func (t *KeyValuePairTarget) FinishFields(_ vdl.FieldsTarget) error {
-
- return nil
-}
-
-type TestCaveatData struct {
- A string
- B *vom.RawBytes // Use any for value so that we can confirm VDL is being used properly.
-}
-
-func (TestCaveatData) __VDLReflect(struct {
- Name string `vdl:"v.io/x/js.core/test_service.TestCaveatData"`
-}) {
-}
-
-func (m *TestCaveatData) FillVDLTarget(t vdl.Target, tt *vdl.Type) error {
- fieldsTarget1, err := t.StartFields(tt)
- if err != nil {
- return err
- }
-
- keyTarget2, fieldTarget3, err := fieldsTarget1.StartField("A")
- if err != vdl.ErrFieldNoExist && err != nil {
- return err
- }
- if err != vdl.ErrFieldNoExist {
- if err := fieldTarget3.FromString(string(m.A), tt.NonOptional().Field(0).Type); err != nil {
- return err
- }
- if err := fieldsTarget1.FinishField(keyTarget2, fieldTarget3); err != nil {
- return err
- }
- }
- keyTarget4, fieldTarget5, err := fieldsTarget1.StartField("B")
- if err != vdl.ErrFieldNoExist && err != nil {
- return err
- }
- if err != vdl.ErrFieldNoExist {
-
- if m.B == nil {
- if err := fieldTarget5.FromNil(tt.NonOptional().Field(1).Type); err != nil {
- return err
- }
- } else {
- if err := m.B.FillVDLTarget(fieldTarget5, tt.NonOptional().Field(1).Type); err != nil {
- return err
- }
- }
- if err := fieldsTarget1.FinishField(keyTarget4, fieldTarget5); err != nil {
- return err
- }
- }
- if err := t.FinishFields(fieldsTarget1); err != nil {
- return err
- }
- return nil
-}
-
-func (m *TestCaveatData) MakeVDLTarget() vdl.Target {
- return &TestCaveatDataTarget{Value: m}
-}
-
-type TestCaveatDataTarget struct {
- Value *TestCaveatData
- aTarget vdl.StringTarget
-
- vdl.TargetBase
- vdl.FieldsTargetBase
-}
-
-func (t *TestCaveatDataTarget) StartFields(tt *vdl.Type) (vdl.FieldsTarget, error) {
-
- if ttWant := vdl.TypeOf((*TestCaveatData)(nil)).Elem(); !vdl.Compatible(tt, ttWant) {
- return nil, fmt.Errorf("type %v incompatible with %v", tt, ttWant)
- }
- return t, nil
-}
-func (t *TestCaveatDataTarget) StartField(name string) (key, field vdl.Target, _ error) {
- switch name {
- case "A":
- t.aTarget.Value = &t.Value.A
- target, err := &t.aTarget, error(nil)
- return nil, target, err
- case "B":
- target, err := vdl.ReflectTarget(reflect.ValueOf(&t.Value.B))
- return nil, target, err
- default:
- return nil, nil, fmt.Errorf("field %s not in struct v.io/x/js.core/test_service.TestCaveatData", name)
- }
-}
-func (t *TestCaveatDataTarget) FinishField(_, _ vdl.Target) error {
- return nil
-}
-func (t *TestCaveatDataTarget) FinishFields(_ vdl.FieldsTarget) error {
-
- return nil
-}
-
-// Create zero values for each type.
-var (
- __VDLZeroKeyPageResult = KeyPageResult{}
- __VDLZeroKeyValuePair = KeyValuePair{}
- __VDLZeroTestCaveatData = TestCaveatData{}
-)
-
-//////////////////////////////////////////////////
-// Const definitions
-
-var ConditionallyValidatingTestCaveat = security.CaveatDescriptor{
- Id: uniqueid.Id{
- 0,
- 17,
- 34,
- 51,
- 68,
- 85,
- 102,
- 119,
- 136,
- 153,
- 170,
- 187,
- 204,
- 221,
- 238,
- 255,
- },
- ParamType: vdl.TypeOf((*TestCaveatData)(nil)).Elem(),
-}
-
-//////////////////////////////////////////////////
-// Interface definitions
-
-// CacheClientMethods is the client interface
-// containing Cache methods.
-//
-// A Cache service mimics the memcache interface.
-type CacheClientMethods interface {
- // Set sets a value for a key.
- Set(_ *context.T, key string, value *vom.RawBytes, _ ...rpc.CallOpt) error
- // Get returns the value for a key. If the value is not found, returns
- // a not found error.
- Get(_ *context.T, key string, _ ...rpc.CallOpt) (*vom.RawBytes, error)
- // Same as Get, but casts the return argument to an byte.
- GetAsByte(_ *context.T, key string, _ ...rpc.CallOpt) (byte, error)
- // Same as Get, but casts the return argument to an int32.
- GetAsInt32(_ *context.T, key string, _ ...rpc.CallOpt) (int32, error)
- // Same as Get, but casts the return argument to an int64.
- GetAsInt64(_ *context.T, key string, _ ...rpc.CallOpt) (int64, error)
- // Same as Get, but casts the return argument to an uint32.
- GetAsUint32(_ *context.T, key string, _ ...rpc.CallOpt) (uint32, error)
- // Same as Get, but casts the return argument to an uint64.
- GetAsUint64(_ *context.T, key string, _ ...rpc.CallOpt) (uint64, error)
- // Same as Get, but casts the return argument to an float32.
- GetAsFloat32(_ *context.T, key string, _ ...rpc.CallOpt) (float32, error)
- // Same as Get, but casts the return argument to an float64.
- GetAsFloat64(_ *context.T, key string, _ ...rpc.CallOpt) (float64, error)
- // Same as Get, but casts the return argument to a string.
- GetAsString(_ *context.T, key string, _ ...rpc.CallOpt) (string, error)
- // Same as Get, but casts the return argument to a bool.
- GetAsBool(_ *context.T, key string, _ ...rpc.CallOpt) (bool, error)
- // Same as Get, but casts the return argument to an error.
- GetAsError(_ *context.T, key string, _ ...rpc.CallOpt) (error, error)
- // AsMap returns the full contents of the cache as a map.
- AsMap(*context.T, ...rpc.CallOpt) (map[string]*vom.RawBytes, error)
- // KeyValuePairs returns the full contents of the cache as a slice of pairs.
- KeyValuePairs(*context.T, ...rpc.CallOpt) ([]KeyValuePair, error)
- // MostRecentSet returns the key and value and the timestamp for the most
- // recent set operation
- // TODO(bprosnitz) support type types and change time to native time type
- MostRecentSet(*context.T, ...rpc.CallOpt) (value KeyValuePair, time int64, _ error)
- // KeyPage indexes into the keys (in alphanumerically sorted order) and
- // returns the indexth page of 10 keys.
- KeyPage(_ *context.T, index int64, _ ...rpc.CallOpt) (KeyPageResult, error)
- // Size returns the total number of entries in the cache.
- Size(*context.T, ...rpc.CallOpt) (int64, error)
- // MultiGet sets up a stream that allows fetching multiple keys.
- MultiGet(*context.T, ...rpc.CallOpt) (CacheMultiGetClientCall, error)
-}
-
-// CacheClientStub adds universal methods to CacheClientMethods.
-type CacheClientStub interface {
- CacheClientMethods
- rpc.UniversalServiceMethods
-}
-
-// CacheClient returns a client stub for Cache.
-func CacheClient(name string) CacheClientStub {
- return implCacheClientStub{name}
-}
-
-type implCacheClientStub struct {
- name string
-}
-
-func (c implCacheClientStub) Set(ctx *context.T, i0 string, i1 *vom.RawBytes, opts ...rpc.CallOpt) (err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "Set", []interface{}{i0, i1}, nil, opts...)
- return
-}
-
-func (c implCacheClientStub) Get(ctx *context.T, i0 string, opts ...rpc.CallOpt) (o0 *vom.RawBytes, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "Get", []interface{}{i0}, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implCacheClientStub) GetAsByte(ctx *context.T, i0 string, opts ...rpc.CallOpt) (o0 byte, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "GetAsByte", []interface{}{i0}, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implCacheClientStub) GetAsInt32(ctx *context.T, i0 string, opts ...rpc.CallOpt) (o0 int32, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "GetAsInt32", []interface{}{i0}, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implCacheClientStub) GetAsInt64(ctx *context.T, i0 string, opts ...rpc.CallOpt) (o0 int64, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "GetAsInt64", []interface{}{i0}, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implCacheClientStub) GetAsUint32(ctx *context.T, i0 string, opts ...rpc.CallOpt) (o0 uint32, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "GetAsUint32", []interface{}{i0}, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implCacheClientStub) GetAsUint64(ctx *context.T, i0 string, opts ...rpc.CallOpt) (o0 uint64, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "GetAsUint64", []interface{}{i0}, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implCacheClientStub) GetAsFloat32(ctx *context.T, i0 string, opts ...rpc.CallOpt) (o0 float32, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "GetAsFloat32", []interface{}{i0}, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implCacheClientStub) GetAsFloat64(ctx *context.T, i0 string, opts ...rpc.CallOpt) (o0 float64, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "GetAsFloat64", []interface{}{i0}, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implCacheClientStub) GetAsString(ctx *context.T, i0 string, opts ...rpc.CallOpt) (o0 string, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "GetAsString", []interface{}{i0}, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implCacheClientStub) GetAsBool(ctx *context.T, i0 string, opts ...rpc.CallOpt) (o0 bool, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "GetAsBool", []interface{}{i0}, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implCacheClientStub) GetAsError(ctx *context.T, i0 string, opts ...rpc.CallOpt) (o0 error, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "GetAsError", []interface{}{i0}, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implCacheClientStub) AsMap(ctx *context.T, opts ...rpc.CallOpt) (o0 map[string]*vom.RawBytes, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "AsMap", nil, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implCacheClientStub) KeyValuePairs(ctx *context.T, opts ...rpc.CallOpt) (o0 []KeyValuePair, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "KeyValuePairs", nil, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implCacheClientStub) MostRecentSet(ctx *context.T, opts ...rpc.CallOpt) (o0 KeyValuePair, o1 int64, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "MostRecentSet", nil, []interface{}{&o0, &o1}, opts...)
- return
-}
-
-func (c implCacheClientStub) KeyPage(ctx *context.T, i0 int64, opts ...rpc.CallOpt) (o0 KeyPageResult, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "KeyPage", []interface{}{i0}, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implCacheClientStub) Size(ctx *context.T, opts ...rpc.CallOpt) (o0 int64, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "Size", nil, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implCacheClientStub) MultiGet(ctx *context.T, opts ...rpc.CallOpt) (ocall CacheMultiGetClientCall, err error) {
- var call rpc.ClientCall
- if call, err = v23.GetClient(ctx).StartCall(ctx, c.name, "MultiGet", nil, opts...); err != nil {
- return
- }
- ocall = &implCacheMultiGetClientCall{ClientCall: call}
- return
-}
-
-// CacheMultiGetClientStream is the client stream for Cache.MultiGet.
-type CacheMultiGetClientStream interface {
- // RecvStream returns the receiver side of the Cache.MultiGet client stream.
- RecvStream() interface {
- // Advance stages an item so that it may be retrieved via Value. Returns
- // true iff there is an item to retrieve. Advance must be called before
- // Value is called. May block if an item is not available.
- Advance() bool
- // Value returns the item that was staged by Advance. May panic if Advance
- // returned false or was not called. Never blocks.
- Value() *vom.RawBytes
- // Err returns any error encountered by Advance. Never blocks.
- Err() error
- }
- // SendStream returns the send side of the Cache.MultiGet client stream.
- SendStream() interface {
- // Send places the item onto the output stream. Returns errors
- // encountered while sending, or if Send is called after Close or
- // the stream has been canceled. Blocks if there is no buffer
- // space; will unblock when buffer space is available or after
- // the stream has been canceled.
- Send(item string) error
- // Close indicates to the server that no more items will be sent;
- // server Recv calls will receive io.EOF after all sent items.
- // This is an optional call - e.g. a client might call Close if it
- // needs to continue receiving items from the server after it's
- // done sending. Returns errors encountered while closing, or if
- // Close is called after the stream has been canceled. Like Send,
- // blocks if there is no buffer space available.
- Close() error
- }
-}
-
-// CacheMultiGetClientCall represents the call returned from Cache.MultiGet.
-type CacheMultiGetClientCall interface {
- CacheMultiGetClientStream
- // Finish performs the equivalent of SendStream().Close, then blocks until
- // the server is done, and returns the positional return values for the call.
- //
- // Finish returns immediately if the call has been canceled; depending on the
- // timing the output could either be an error signaling cancelation, or the
- // valid positional return values from the server.
- //
- // Calling Finish is mandatory for releasing stream resources, unless the call
- // has been canceled or any of the other methods return an error. Finish should
- // be called at most once.
- Finish() error
-}
-
-type implCacheMultiGetClientCall struct {
- rpc.ClientCall
- valRecv *vom.RawBytes
- errRecv error
-}
-
-func (c *implCacheMultiGetClientCall) RecvStream() interface {
- Advance() bool
- Value() *vom.RawBytes
- Err() error
-} {
- return implCacheMultiGetClientCallRecv{c}
-}
-
-type implCacheMultiGetClientCallRecv struct {
- c *implCacheMultiGetClientCall
-}
-
-func (c implCacheMultiGetClientCallRecv) Advance() bool {
- c.c.valRecv = nil
- c.c.errRecv = c.c.Recv(&c.c.valRecv)
- return c.c.errRecv == nil
-}
-func (c implCacheMultiGetClientCallRecv) Value() *vom.RawBytes {
- return c.c.valRecv
-}
-func (c implCacheMultiGetClientCallRecv) Err() error {
- if c.c.errRecv == io.EOF {
- return nil
- }
- return c.c.errRecv
-}
-func (c *implCacheMultiGetClientCall) SendStream() interface {
- Send(item string) error
- Close() error
-} {
- return implCacheMultiGetClientCallSend{c}
-}
-
-type implCacheMultiGetClientCallSend struct {
- c *implCacheMultiGetClientCall
-}
-
-func (c implCacheMultiGetClientCallSend) Send(item string) error {
- return c.c.Send(item)
-}
-func (c implCacheMultiGetClientCallSend) Close() error {
- return c.c.CloseSend()
-}
-func (c *implCacheMultiGetClientCall) Finish() (err error) {
- err = c.ClientCall.Finish()
- return
-}
-
-// CacheServerMethods is the interface a server writer
-// implements for Cache.
-//
-// A Cache service mimics the memcache interface.
-type CacheServerMethods interface {
- // Set sets a value for a key.
- Set(_ *context.T, _ rpc.ServerCall, key string, value *vom.RawBytes) error
- // Get returns the value for a key. If the value is not found, returns
- // a not found error.
- Get(_ *context.T, _ rpc.ServerCall, key string) (*vom.RawBytes, error)
- // Same as Get, but casts the return argument to an byte.
- GetAsByte(_ *context.T, _ rpc.ServerCall, key string) (byte, error)
- // Same as Get, but casts the return argument to an int32.
- GetAsInt32(_ *context.T, _ rpc.ServerCall, key string) (int32, error)
- // Same as Get, but casts the return argument to an int64.
- GetAsInt64(_ *context.T, _ rpc.ServerCall, key string) (int64, error)
- // Same as Get, but casts the return argument to an uint32.
- GetAsUint32(_ *context.T, _ rpc.ServerCall, key string) (uint32, error)
- // Same as Get, but casts the return argument to an uint64.
- GetAsUint64(_ *context.T, _ rpc.ServerCall, key string) (uint64, error)
- // Same as Get, but casts the return argument to an float32.
- GetAsFloat32(_ *context.T, _ rpc.ServerCall, key string) (float32, error)
- // Same as Get, but casts the return argument to an float64.
- GetAsFloat64(_ *context.T, _ rpc.ServerCall, key string) (float64, error)
- // Same as Get, but casts the return argument to a string.
- GetAsString(_ *context.T, _ rpc.ServerCall, key string) (string, error)
- // Same as Get, but casts the return argument to a bool.
- GetAsBool(_ *context.T, _ rpc.ServerCall, key string) (bool, error)
- // Same as Get, but casts the return argument to an error.
- GetAsError(_ *context.T, _ rpc.ServerCall, key string) (error, error)
- // AsMap returns the full contents of the cache as a map.
- AsMap(*context.T, rpc.ServerCall) (map[string]*vom.RawBytes, error)
- // KeyValuePairs returns the full contents of the cache as a slice of pairs.
- KeyValuePairs(*context.T, rpc.ServerCall) ([]KeyValuePair, error)
- // MostRecentSet returns the key and value and the timestamp for the most
- // recent set operation
- // TODO(bprosnitz) support type types and change time to native time type
- MostRecentSet(*context.T, rpc.ServerCall) (value KeyValuePair, time int64, _ error)
- // KeyPage indexes into the keys (in alphanumerically sorted order) and
- // returns the indexth page of 10 keys.
- KeyPage(_ *context.T, _ rpc.ServerCall, index int64) (KeyPageResult, error)
- // Size returns the total number of entries in the cache.
- Size(*context.T, rpc.ServerCall) (int64, error)
- // MultiGet sets up a stream that allows fetching multiple keys.
- MultiGet(*context.T, CacheMultiGetServerCall) error
-}
-
-// CacheServerStubMethods is the server interface containing
-// Cache methods, as expected by rpc.Server.
-// The only difference between this interface and CacheServerMethods
-// is the streaming methods.
-type CacheServerStubMethods interface {
- // Set sets a value for a key.
- Set(_ *context.T, _ rpc.ServerCall, key string, value *vom.RawBytes) error
- // Get returns the value for a key. If the value is not found, returns
- // a not found error.
- Get(_ *context.T, _ rpc.ServerCall, key string) (*vom.RawBytes, error)
- // Same as Get, but casts the return argument to an byte.
- GetAsByte(_ *context.T, _ rpc.ServerCall, key string) (byte, error)
- // Same as Get, but casts the return argument to an int32.
- GetAsInt32(_ *context.T, _ rpc.ServerCall, key string) (int32, error)
- // Same as Get, but casts the return argument to an int64.
- GetAsInt64(_ *context.T, _ rpc.ServerCall, key string) (int64, error)
- // Same as Get, but casts the return argument to an uint32.
- GetAsUint32(_ *context.T, _ rpc.ServerCall, key string) (uint32, error)
- // Same as Get, but casts the return argument to an uint64.
- GetAsUint64(_ *context.T, _ rpc.ServerCall, key string) (uint64, error)
- // Same as Get, but casts the return argument to an float32.
- GetAsFloat32(_ *context.T, _ rpc.ServerCall, key string) (float32, error)
- // Same as Get, but casts the return argument to an float64.
- GetAsFloat64(_ *context.T, _ rpc.ServerCall, key string) (float64, error)
- // Same as Get, but casts the return argument to a string.
- GetAsString(_ *context.T, _ rpc.ServerCall, key string) (string, error)
- // Same as Get, but casts the return argument to a bool.
- GetAsBool(_ *context.T, _ rpc.ServerCall, key string) (bool, error)
- // Same as Get, but casts the return argument to an error.
- GetAsError(_ *context.T, _ rpc.ServerCall, key string) (error, error)
- // AsMap returns the full contents of the cache as a map.
- AsMap(*context.T, rpc.ServerCall) (map[string]*vom.RawBytes, error)
- // KeyValuePairs returns the full contents of the cache as a slice of pairs.
- KeyValuePairs(*context.T, rpc.ServerCall) ([]KeyValuePair, error)
- // MostRecentSet returns the key and value and the timestamp for the most
- // recent set operation
- // TODO(bprosnitz) support type types and change time to native time type
- MostRecentSet(*context.T, rpc.ServerCall) (value KeyValuePair, time int64, _ error)
- // KeyPage indexes into the keys (in alphanumerically sorted order) and
- // returns the indexth page of 10 keys.
- KeyPage(_ *context.T, _ rpc.ServerCall, index int64) (KeyPageResult, error)
- // Size returns the total number of entries in the cache.
- Size(*context.T, rpc.ServerCall) (int64, error)
- // MultiGet sets up a stream that allows fetching multiple keys.
- MultiGet(*context.T, *CacheMultiGetServerCallStub) error
-}
-
-// CacheServerStub adds universal methods to CacheServerStubMethods.
-type CacheServerStub interface {
- CacheServerStubMethods
- // Describe the Cache interfaces.
- Describe__() []rpc.InterfaceDesc
-}
-
-// CacheServer returns a server stub for Cache.
-// It converts an implementation of CacheServerMethods into
-// an object that may be used by rpc.Server.
-func CacheServer(impl CacheServerMethods) CacheServerStub {
- stub := implCacheServerStub{
- impl: impl,
- }
- // Initialize GlobState; always check the stub itself first, to handle the
- // case where the user has the Glob method defined in their VDL source.
- if gs := rpc.NewGlobState(stub); gs != nil {
- stub.gs = gs
- } else if gs := rpc.NewGlobState(impl); gs != nil {
- stub.gs = gs
- }
- return stub
-}
-
-type implCacheServerStub struct {
- impl CacheServerMethods
- gs *rpc.GlobState
-}
-
-func (s implCacheServerStub) Set(ctx *context.T, call rpc.ServerCall, i0 string, i1 *vom.RawBytes) error {
- return s.impl.Set(ctx, call, i0, i1)
-}
-
-func (s implCacheServerStub) Get(ctx *context.T, call rpc.ServerCall, i0 string) (*vom.RawBytes, error) {
- return s.impl.Get(ctx, call, i0)
-}
-
-func (s implCacheServerStub) GetAsByte(ctx *context.T, call rpc.ServerCall, i0 string) (byte, error) {
- return s.impl.GetAsByte(ctx, call, i0)
-}
-
-func (s implCacheServerStub) GetAsInt32(ctx *context.T, call rpc.ServerCall, i0 string) (int32, error) {
- return s.impl.GetAsInt32(ctx, call, i0)
-}
-
-func (s implCacheServerStub) GetAsInt64(ctx *context.T, call rpc.ServerCall, i0 string) (int64, error) {
- return s.impl.GetAsInt64(ctx, call, i0)
-}
-
-func (s implCacheServerStub) GetAsUint32(ctx *context.T, call rpc.ServerCall, i0 string) (uint32, error) {
- return s.impl.GetAsUint32(ctx, call, i0)
-}
-
-func (s implCacheServerStub) GetAsUint64(ctx *context.T, call rpc.ServerCall, i0 string) (uint64, error) {
- return s.impl.GetAsUint64(ctx, call, i0)
-}
-
-func (s implCacheServerStub) GetAsFloat32(ctx *context.T, call rpc.ServerCall, i0 string) (float32, error) {
- return s.impl.GetAsFloat32(ctx, call, i0)
-}
-
-func (s implCacheServerStub) GetAsFloat64(ctx *context.T, call rpc.ServerCall, i0 string) (float64, error) {
- return s.impl.GetAsFloat64(ctx, call, i0)
-}
-
-func (s implCacheServerStub) GetAsString(ctx *context.T, call rpc.ServerCall, i0 string) (string, error) {
- return s.impl.GetAsString(ctx, call, i0)
-}
-
-func (s implCacheServerStub) GetAsBool(ctx *context.T, call rpc.ServerCall, i0 string) (bool, error) {
- return s.impl.GetAsBool(ctx, call, i0)
-}
-
-func (s implCacheServerStub) GetAsError(ctx *context.T, call rpc.ServerCall, i0 string) (error, error) {
- return s.impl.GetAsError(ctx, call, i0)
-}
-
-func (s implCacheServerStub) AsMap(ctx *context.T, call rpc.ServerCall) (map[string]*vom.RawBytes, error) {
- return s.impl.AsMap(ctx, call)
-}
-
-func (s implCacheServerStub) KeyValuePairs(ctx *context.T, call rpc.ServerCall) ([]KeyValuePair, error) {
- return s.impl.KeyValuePairs(ctx, call)
-}
-
-func (s implCacheServerStub) MostRecentSet(ctx *context.T, call rpc.ServerCall) (KeyValuePair, int64, error) {
- return s.impl.MostRecentSet(ctx, call)
-}
-
-func (s implCacheServerStub) KeyPage(ctx *context.T, call rpc.ServerCall, i0 int64) (KeyPageResult, error) {
- return s.impl.KeyPage(ctx, call, i0)
-}
-
-func (s implCacheServerStub) Size(ctx *context.T, call rpc.ServerCall) (int64, error) {
- return s.impl.Size(ctx, call)
-}
-
-func (s implCacheServerStub) MultiGet(ctx *context.T, call *CacheMultiGetServerCallStub) error {
- return s.impl.MultiGet(ctx, call)
-}
-
-func (s implCacheServerStub) Globber() *rpc.GlobState {
- return s.gs
-}
-
-func (s implCacheServerStub) Describe__() []rpc.InterfaceDesc {
- return []rpc.InterfaceDesc{CacheDesc}
-}
-
-// CacheDesc describes the Cache interface.
-var CacheDesc rpc.InterfaceDesc = descCache
-
-// descCache hides the desc to keep godoc clean.
-var descCache = rpc.InterfaceDesc{
- Name: "Cache",
- PkgPath: "v.io/x/js.core/test_service",
- Doc: "// A Cache service mimics the memcache interface.",
- Methods: []rpc.MethodDesc{
- {
- Name: "Set",
- Doc: "// Set sets a value for a key.",
- InArgs: []rpc.ArgDesc{
- {"key", ``}, // string
- {"value", ``}, // *vom.RawBytes
- },
- },
- {
- Name: "Get",
- Doc: "// Get returns the value for a key. If the value is not found, returns\n// a not found error.",
- InArgs: []rpc.ArgDesc{
- {"key", ``}, // string
- },
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // *vom.RawBytes
- },
- },
- {
- Name: "GetAsByte",
- Doc: "// Same as Get, but casts the return argument to an byte.",
- InArgs: []rpc.ArgDesc{
- {"key", ``}, // string
- },
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // byte
- },
- },
- {
- Name: "GetAsInt32",
- Doc: "// Same as Get, but casts the return argument to an int32.",
- InArgs: []rpc.ArgDesc{
- {"key", ``}, // string
- },
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // int32
- },
- },
- {
- Name: "GetAsInt64",
- Doc: "// Same as Get, but casts the return argument to an int64.",
- InArgs: []rpc.ArgDesc{
- {"key", ``}, // string
- },
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // int64
- },
- },
- {
- Name: "GetAsUint32",
- Doc: "// Same as Get, but casts the return argument to an uint32.",
- InArgs: []rpc.ArgDesc{
- {"key", ``}, // string
- },
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // uint32
- },
- },
- {
- Name: "GetAsUint64",
- Doc: "// Same as Get, but casts the return argument to an uint64.",
- InArgs: []rpc.ArgDesc{
- {"key", ``}, // string
- },
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // uint64
- },
- },
- {
- Name: "GetAsFloat32",
- Doc: "// Same as Get, but casts the return argument to an float32.",
- InArgs: []rpc.ArgDesc{
- {"key", ``}, // string
- },
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // float32
- },
- },
- {
- Name: "GetAsFloat64",
- Doc: "// Same as Get, but casts the return argument to an float64.",
- InArgs: []rpc.ArgDesc{
- {"key", ``}, // string
- },
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // float64
- },
- },
- {
- Name: "GetAsString",
- Doc: "// Same as Get, but casts the return argument to a string.",
- InArgs: []rpc.ArgDesc{
- {"key", ``}, // string
- },
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // string
- },
- },
- {
- Name: "GetAsBool",
- Doc: "// Same as Get, but casts the return argument to a bool.",
- InArgs: []rpc.ArgDesc{
- {"key", ``}, // string
- },
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // bool
- },
- },
- {
- Name: "GetAsError",
- Doc: "// Same as Get, but casts the return argument to an error.",
- InArgs: []rpc.ArgDesc{
- {"key", ``}, // string
- },
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // error
- },
- },
- {
- Name: "AsMap",
- Doc: "// AsMap returns the full contents of the cache as a map.",
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // map[string]*vom.RawBytes
- },
- },
- {
- Name: "KeyValuePairs",
- Doc: "// KeyValuePairs returns the full contents of the cache as a slice of pairs.",
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // []KeyValuePair
- },
- },
- {
- Name: "MostRecentSet",
- Doc: "// MostRecentSet returns the key and value and the timestamp for the most\n// recent set operation\n// TODO(bprosnitz) support type types and change time to native time type",
- OutArgs: []rpc.ArgDesc{
- {"value", ``}, // KeyValuePair
- {"time", ``}, // int64
- },
- },
- {
- Name: "KeyPage",
- Doc: "// KeyPage indexes into the keys (in alphanumerically sorted order) and\n// returns the indexth page of 10 keys.",
- InArgs: []rpc.ArgDesc{
- {"index", ``}, // int64
- },
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // KeyPageResult
- },
- },
- {
- Name: "Size",
- Doc: "// Size returns the total number of entries in the cache.",
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // int64
- },
- },
- {
- Name: "MultiGet",
- Doc: "// MultiGet sets up a stream that allows fetching multiple keys.",
- },
- },
-}
-
-// CacheMultiGetServerStream is the server stream for Cache.MultiGet.
-type CacheMultiGetServerStream interface {
- // RecvStream returns the receiver side of the Cache.MultiGet server stream.
- RecvStream() interface {
- // Advance stages an item so that it may be retrieved via Value. Returns
- // true iff there is an item to retrieve. Advance must be called before
- // Value is called. May block if an item is not available.
- Advance() bool
- // Value returns the item that was staged by Advance. May panic if Advance
- // returned false or was not called. Never blocks.
- Value() string
- // Err returns any error encountered by Advance. Never blocks.
- Err() error
- }
- // SendStream returns the send side of the Cache.MultiGet server stream.
- SendStream() interface {
- // Send places the item onto the output stream. Returns errors encountered
- // while sending. Blocks if there is no buffer space; will unblock when
- // buffer space is available.
- Send(item *vom.RawBytes) error
- }
-}
-
-// CacheMultiGetServerCall represents the context passed to Cache.MultiGet.
-type CacheMultiGetServerCall interface {
- rpc.ServerCall
- CacheMultiGetServerStream
-}
-
-// CacheMultiGetServerCallStub is a wrapper that converts rpc.StreamServerCall into
-// a typesafe stub that implements CacheMultiGetServerCall.
-type CacheMultiGetServerCallStub struct {
- rpc.StreamServerCall
- valRecv string
- errRecv error
-}
-
-// Init initializes CacheMultiGetServerCallStub from rpc.StreamServerCall.
-func (s *CacheMultiGetServerCallStub) Init(call rpc.StreamServerCall) {
- s.StreamServerCall = call
-}
-
-// RecvStream returns the receiver side of the Cache.MultiGet server stream.
-func (s *CacheMultiGetServerCallStub) RecvStream() interface {
- Advance() bool
- Value() string
- Err() error
-} {
- return implCacheMultiGetServerCallRecv{s}
-}
-
-type implCacheMultiGetServerCallRecv struct {
- s *CacheMultiGetServerCallStub
-}
-
-func (s implCacheMultiGetServerCallRecv) Advance() bool {
- s.s.errRecv = s.s.Recv(&s.s.valRecv)
- return s.s.errRecv == nil
-}
-func (s implCacheMultiGetServerCallRecv) Value() string {
- return s.s.valRecv
-}
-func (s implCacheMultiGetServerCallRecv) Err() error {
- if s.s.errRecv == io.EOF {
- return nil
- }
- return s.s.errRecv
-}
-
-// SendStream returns the send side of the Cache.MultiGet server stream.
-func (s *CacheMultiGetServerCallStub) SendStream() interface {
- Send(item *vom.RawBytes) error
-} {
- return implCacheMultiGetServerCallSend{s}
-}
-
-type implCacheMultiGetServerCallSend struct {
- s *CacheMultiGetServerCallStub
-}
-
-func (s implCacheMultiGetServerCallSend) Send(item *vom.RawBytes) error {
- return s.s.Send(item)
-}
-
-// CancelCollectorClientMethods is the client interface
-// containing CancelCollector methods.
-//
-// CancelCollector is a test interface for use in testing cancellation and deadlines.
-type CancelCollectorClientMethods interface {
- // A function that never returns, but records the status of the given key.
- NeverReturn(_ *context.T, key int64, _ ...rpc.CallOpt) error
- // Wait for the call with the given key to have the given status. Possible statuses are:
- // "running", and, "cancelled". Returns the number of nanoseconds left on
- // the deadline of the specified call when the call first began.
- WaitForStatus(_ *context.T, key int64, status string, _ ...rpc.CallOpt) (timeout int64, _ error)
-}
-
-// CancelCollectorClientStub adds universal methods to CancelCollectorClientMethods.
-type CancelCollectorClientStub interface {
- CancelCollectorClientMethods
- rpc.UniversalServiceMethods
-}
-
-// CancelCollectorClient returns a client stub for CancelCollector.
-func CancelCollectorClient(name string) CancelCollectorClientStub {
- return implCancelCollectorClientStub{name}
-}
-
-type implCancelCollectorClientStub struct {
- name string
-}
-
-func (c implCancelCollectorClientStub) NeverReturn(ctx *context.T, i0 int64, opts ...rpc.CallOpt) (err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "NeverReturn", []interface{}{i0}, nil, opts...)
- return
-}
-
-func (c implCancelCollectorClientStub) WaitForStatus(ctx *context.T, i0 int64, i1 string, opts ...rpc.CallOpt) (o0 int64, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "WaitForStatus", []interface{}{i0, i1}, []interface{}{&o0}, opts...)
- return
-}
-
-// CancelCollectorServerMethods is the interface a server writer
-// implements for CancelCollector.
-//
-// CancelCollector is a test interface for use in testing cancellation and deadlines.
-type CancelCollectorServerMethods interface {
- // A function that never returns, but records the status of the given key.
- NeverReturn(_ *context.T, _ rpc.ServerCall, key int64) error
- // Wait for the call with the given key to have the given status. Possible statuses are:
- // "running", and, "cancelled". Returns the number of nanoseconds left on
- // the deadline of the specified call when the call first began.
- WaitForStatus(_ *context.T, _ rpc.ServerCall, key int64, status string) (timeout int64, _ error)
-}
-
-// CancelCollectorServerStubMethods is the server interface containing
-// CancelCollector methods, as expected by rpc.Server.
-// There is no difference between this interface and CancelCollectorServerMethods
-// since there are no streaming methods.
-type CancelCollectorServerStubMethods CancelCollectorServerMethods
-
-// CancelCollectorServerStub adds universal methods to CancelCollectorServerStubMethods.
-type CancelCollectorServerStub interface {
- CancelCollectorServerStubMethods
- // Describe the CancelCollector interfaces.
- Describe__() []rpc.InterfaceDesc
-}
-
-// CancelCollectorServer returns a server stub for CancelCollector.
-// It converts an implementation of CancelCollectorServerMethods into
-// an object that may be used by rpc.Server.
-func CancelCollectorServer(impl CancelCollectorServerMethods) CancelCollectorServerStub {
- stub := implCancelCollectorServerStub{
- impl: impl,
- }
- // Initialize GlobState; always check the stub itself first, to handle the
- // case where the user has the Glob method defined in their VDL source.
- if gs := rpc.NewGlobState(stub); gs != nil {
- stub.gs = gs
- } else if gs := rpc.NewGlobState(impl); gs != nil {
- stub.gs = gs
- }
- return stub
-}
-
-type implCancelCollectorServerStub struct {
- impl CancelCollectorServerMethods
- gs *rpc.GlobState
-}
-
-func (s implCancelCollectorServerStub) NeverReturn(ctx *context.T, call rpc.ServerCall, i0 int64) error {
- return s.impl.NeverReturn(ctx, call, i0)
-}
-
-func (s implCancelCollectorServerStub) WaitForStatus(ctx *context.T, call rpc.ServerCall, i0 int64, i1 string) (int64, error) {
- return s.impl.WaitForStatus(ctx, call, i0, i1)
-}
-
-func (s implCancelCollectorServerStub) Globber() *rpc.GlobState {
- return s.gs
-}
-
-func (s implCancelCollectorServerStub) Describe__() []rpc.InterfaceDesc {
- return []rpc.InterfaceDesc{CancelCollectorDesc}
-}
-
-// CancelCollectorDesc describes the CancelCollector interface.
-var CancelCollectorDesc rpc.InterfaceDesc = descCancelCollector
-
-// descCancelCollector hides the desc to keep godoc clean.
-var descCancelCollector = rpc.InterfaceDesc{
- Name: "CancelCollector",
- PkgPath: "v.io/x/js.core/test_service",
- Doc: "// CancelCollector is a test interface for use in testing cancellation and deadlines.",
- Methods: []rpc.MethodDesc{
- {
- Name: "NeverReturn",
- Doc: "// A function that never returns, but records the status of the given key.",
- InArgs: []rpc.ArgDesc{
- {"key", ``}, // int64
- },
- },
- {
- Name: "WaitForStatus",
- Doc: "// Wait for the call with the given key to have the given status. Possible statuses are:\n// \"running\", and, \"cancelled\". Returns the number of nanoseconds left on\n// the deadline of the specified call when the call first began.",
- InArgs: []rpc.ArgDesc{
- {"key", ``}, // int64
- {"status", ``}, // string
- },
- OutArgs: []rpc.ArgDesc{
- {"timeout", ``}, // int64
- },
- },
- },
-}
-
-// ErrorThrowerClientMethods is the client interface
-// containing ErrorThrower methods.
-//
-// A testing interface with methods that throw various types of errors
-type ErrorThrowerClientMethods interface {
- // Throws v23/vError.Aborted error
- ThrowAborted(*context.T, ...rpc.CallOpt) error
- // Throws v23/vError.BadArg error
- ThrowBadArg(*context.T, ...rpc.CallOpt) error
- // Throws v23/vError.BadProtocol error
- ThrowBadProtocol(*context.T, ...rpc.CallOpt) error
- // Throws v23/vError.Internal error
- ThrowInternal(*context.T, ...rpc.CallOpt) error
- // Throws v23/vError.NoAccess error
- ThrowNoAccess(*context.T, ...rpc.CallOpt) error
- // Throws v23/vError.NoExist error
- ThrowNoExist(*context.T, ...rpc.CallOpt) error
- // Throws v23/vError.NoExistOrNoAccess error
- ThrowNoExistOrNoAccess(*context.T, ...rpc.CallOpt) error
- // Throws v23/vError.Unknown error
- ThrowUnknown(*context.T, ...rpc.CallOpt) error
- // Throws normal Go error
- ThrowGoError(*context.T, ...rpc.CallOpt) error
- // Throws custom error created by using Standard
- ThrowCustomStandardError(*context.T, ...rpc.CallOpt) error
-}
-
-// ErrorThrowerClientStub adds universal methods to ErrorThrowerClientMethods.
-type ErrorThrowerClientStub interface {
- ErrorThrowerClientMethods
- rpc.UniversalServiceMethods
-}
-
-// ErrorThrowerClient returns a client stub for ErrorThrower.
-func ErrorThrowerClient(name string) ErrorThrowerClientStub {
- return implErrorThrowerClientStub{name}
-}
-
-type implErrorThrowerClientStub struct {
- name string
-}
-
-func (c implErrorThrowerClientStub) ThrowAborted(ctx *context.T, opts ...rpc.CallOpt) (err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "ThrowAborted", nil, nil, opts...)
- return
-}
-
-func (c implErrorThrowerClientStub) ThrowBadArg(ctx *context.T, opts ...rpc.CallOpt) (err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "ThrowBadArg", nil, nil, opts...)
- return
-}
-
-func (c implErrorThrowerClientStub) ThrowBadProtocol(ctx *context.T, opts ...rpc.CallOpt) (err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "ThrowBadProtocol", nil, nil, opts...)
- return
-}
-
-func (c implErrorThrowerClientStub) ThrowInternal(ctx *context.T, opts ...rpc.CallOpt) (err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "ThrowInternal", nil, nil, opts...)
- return
-}
-
-func (c implErrorThrowerClientStub) ThrowNoAccess(ctx *context.T, opts ...rpc.CallOpt) (err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "ThrowNoAccess", nil, nil, opts...)
- return
-}
-
-func (c implErrorThrowerClientStub) ThrowNoExist(ctx *context.T, opts ...rpc.CallOpt) (err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "ThrowNoExist", nil, nil, opts...)
- return
-}
-
-func (c implErrorThrowerClientStub) ThrowNoExistOrNoAccess(ctx *context.T, opts ...rpc.CallOpt) (err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "ThrowNoExistOrNoAccess", nil, nil, opts...)
- return
-}
-
-func (c implErrorThrowerClientStub) ThrowUnknown(ctx *context.T, opts ...rpc.CallOpt) (err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "ThrowUnknown", nil, nil, opts...)
- return
-}
-
-func (c implErrorThrowerClientStub) ThrowGoError(ctx *context.T, opts ...rpc.CallOpt) (err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "ThrowGoError", nil, nil, opts...)
- return
-}
-
-func (c implErrorThrowerClientStub) ThrowCustomStandardError(ctx *context.T, opts ...rpc.CallOpt) (err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "ThrowCustomStandardError", nil, nil, opts...)
- return
-}
-
-// ErrorThrowerServerMethods is the interface a server writer
-// implements for ErrorThrower.
-//
-// A testing interface with methods that throw various types of errors
-type ErrorThrowerServerMethods interface {
- // Throws v23/vError.Aborted error
- ThrowAborted(*context.T, rpc.ServerCall) error
- // Throws v23/vError.BadArg error
- ThrowBadArg(*context.T, rpc.ServerCall) error
- // Throws v23/vError.BadProtocol error
- ThrowBadProtocol(*context.T, rpc.ServerCall) error
- // Throws v23/vError.Internal error
- ThrowInternal(*context.T, rpc.ServerCall) error
- // Throws v23/vError.NoAccess error
- ThrowNoAccess(*context.T, rpc.ServerCall) error
- // Throws v23/vError.NoExist error
- ThrowNoExist(*context.T, rpc.ServerCall) error
- // Throws v23/vError.NoExistOrNoAccess error
- ThrowNoExistOrNoAccess(*context.T, rpc.ServerCall) error
- // Throws v23/vError.Unknown error
- ThrowUnknown(*context.T, rpc.ServerCall) error
- // Throws normal Go error
- ThrowGoError(*context.T, rpc.ServerCall) error
- // Throws custom error created by using Standard
- ThrowCustomStandardError(*context.T, rpc.ServerCall) error
-}
-
-// ErrorThrowerServerStubMethods is the server interface containing
-// ErrorThrower methods, as expected by rpc.Server.
-// There is no difference between this interface and ErrorThrowerServerMethods
-// since there are no streaming methods.
-type ErrorThrowerServerStubMethods ErrorThrowerServerMethods
-
-// ErrorThrowerServerStub adds universal methods to ErrorThrowerServerStubMethods.
-type ErrorThrowerServerStub interface {
- ErrorThrowerServerStubMethods
- // Describe the ErrorThrower interfaces.
- Describe__() []rpc.InterfaceDesc
-}
-
-// ErrorThrowerServer returns a server stub for ErrorThrower.
-// It converts an implementation of ErrorThrowerServerMethods into
-// an object that may be used by rpc.Server.
-func ErrorThrowerServer(impl ErrorThrowerServerMethods) ErrorThrowerServerStub {
- stub := implErrorThrowerServerStub{
- impl: impl,
- }
- // Initialize GlobState; always check the stub itself first, to handle the
- // case where the user has the Glob method defined in their VDL source.
- if gs := rpc.NewGlobState(stub); gs != nil {
- stub.gs = gs
- } else if gs := rpc.NewGlobState(impl); gs != nil {
- stub.gs = gs
- }
- return stub
-}
-
-type implErrorThrowerServerStub struct {
- impl ErrorThrowerServerMethods
- gs *rpc.GlobState
-}
-
-func (s implErrorThrowerServerStub) ThrowAborted(ctx *context.T, call rpc.ServerCall) error {
- return s.impl.ThrowAborted(ctx, call)
-}
-
-func (s implErrorThrowerServerStub) ThrowBadArg(ctx *context.T, call rpc.ServerCall) error {
- return s.impl.ThrowBadArg(ctx, call)
-}
-
-func (s implErrorThrowerServerStub) ThrowBadProtocol(ctx *context.T, call rpc.ServerCall) error {
- return s.impl.ThrowBadProtocol(ctx, call)
-}
-
-func (s implErrorThrowerServerStub) ThrowInternal(ctx *context.T, call rpc.ServerCall) error {
- return s.impl.ThrowInternal(ctx, call)
-}
-
-func (s implErrorThrowerServerStub) ThrowNoAccess(ctx *context.T, call rpc.ServerCall) error {
- return s.impl.ThrowNoAccess(ctx, call)
-}
-
-func (s implErrorThrowerServerStub) ThrowNoExist(ctx *context.T, call rpc.ServerCall) error {
- return s.impl.ThrowNoExist(ctx, call)
-}
-
-func (s implErrorThrowerServerStub) ThrowNoExistOrNoAccess(ctx *context.T, call rpc.ServerCall) error {
- return s.impl.ThrowNoExistOrNoAccess(ctx, call)
-}
-
-func (s implErrorThrowerServerStub) ThrowUnknown(ctx *context.T, call rpc.ServerCall) error {
- return s.impl.ThrowUnknown(ctx, call)
-}
-
-func (s implErrorThrowerServerStub) ThrowGoError(ctx *context.T, call rpc.ServerCall) error {
- return s.impl.ThrowGoError(ctx, call)
-}
-
-func (s implErrorThrowerServerStub) ThrowCustomStandardError(ctx *context.T, call rpc.ServerCall) error {
- return s.impl.ThrowCustomStandardError(ctx, call)
-}
-
-func (s implErrorThrowerServerStub) Globber() *rpc.GlobState {
- return s.gs
-}
-
-func (s implErrorThrowerServerStub) Describe__() []rpc.InterfaceDesc {
- return []rpc.InterfaceDesc{ErrorThrowerDesc}
-}
-
-// ErrorThrowerDesc describes the ErrorThrower interface.
-var ErrorThrowerDesc rpc.InterfaceDesc = descErrorThrower
-
-// descErrorThrower hides the desc to keep godoc clean.
-var descErrorThrower = rpc.InterfaceDesc{
- Name: "ErrorThrower",
- PkgPath: "v.io/x/js.core/test_service",
- Doc: "// A testing interface with methods that throw various types of errors",
- Methods: []rpc.MethodDesc{
- {
- Name: "ThrowAborted",
- Doc: "// Throws v23/vError.Aborted error",
- },
- {
- Name: "ThrowBadArg",
- Doc: "// Throws v23/vError.BadArg error",
- },
- {
- Name: "ThrowBadProtocol",
- Doc: "// Throws v23/vError.BadProtocol error",
- },
- {
- Name: "ThrowInternal",
- Doc: "// Throws v23/vError.Internal error",
- },
- {
- Name: "ThrowNoAccess",
- Doc: "// Throws v23/vError.NoAccess error",
- },
- {
- Name: "ThrowNoExist",
- Doc: "// Throws v23/vError.NoExist error",
- },
- {
- Name: "ThrowNoExistOrNoAccess",
- Doc: "// Throws v23/vError.NoExistOrNoAccess error",
- },
- {
- Name: "ThrowUnknown",
- Doc: "// Throws v23/vError.Unknown error",
- },
- {
- Name: "ThrowGoError",
- Doc: "// Throws normal Go error",
- },
- {
- Name: "ThrowCustomStandardError",
- Doc: "// Throws custom error created by using Standard",
- },
- },
-}
-
-// InvokableTestMethodClientMethods is the client interface
-// containing InvokableTestMethod methods.
-type InvokableTestMethodClientMethods interface {
- AMethod(*context.T, ...rpc.CallOpt) (string, error)
-}
-
-// InvokableTestMethodClientStub adds universal methods to InvokableTestMethodClientMethods.
-type InvokableTestMethodClientStub interface {
- InvokableTestMethodClientMethods
- rpc.UniversalServiceMethods
-}
-
-// InvokableTestMethodClient returns a client stub for InvokableTestMethod.
-func InvokableTestMethodClient(name string) InvokableTestMethodClientStub {
- return implInvokableTestMethodClientStub{name}
-}
-
-type implInvokableTestMethodClientStub struct {
- name string
-}
-
-func (c implInvokableTestMethodClientStub) AMethod(ctx *context.T, opts ...rpc.CallOpt) (o0 string, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "AMethod", nil, []interface{}{&o0}, opts...)
- return
-}
-
-// InvokableTestMethodServerMethods is the interface a server writer
-// implements for InvokableTestMethod.
-type InvokableTestMethodServerMethods interface {
- AMethod(*context.T, rpc.ServerCall) (string, error)
-}
-
-// InvokableTestMethodServerStubMethods is the server interface containing
-// InvokableTestMethod methods, as expected by rpc.Server.
-// There is no difference between this interface and InvokableTestMethodServerMethods
-// since there are no streaming methods.
-type InvokableTestMethodServerStubMethods InvokableTestMethodServerMethods
-
-// InvokableTestMethodServerStub adds universal methods to InvokableTestMethodServerStubMethods.
-type InvokableTestMethodServerStub interface {
- InvokableTestMethodServerStubMethods
- // Describe the InvokableTestMethod interfaces.
- Describe__() []rpc.InterfaceDesc
-}
-
-// InvokableTestMethodServer returns a server stub for InvokableTestMethod.
-// It converts an implementation of InvokableTestMethodServerMethods into
-// an object that may be used by rpc.Server.
-func InvokableTestMethodServer(impl InvokableTestMethodServerMethods) InvokableTestMethodServerStub {
- stub := implInvokableTestMethodServerStub{
- impl: impl,
- }
- // Initialize GlobState; always check the stub itself first, to handle the
- // case where the user has the Glob method defined in their VDL source.
- if gs := rpc.NewGlobState(stub); gs != nil {
- stub.gs = gs
- } else if gs := rpc.NewGlobState(impl); gs != nil {
- stub.gs = gs
- }
- return stub
-}
-
-type implInvokableTestMethodServerStub struct {
- impl InvokableTestMethodServerMethods
- gs *rpc.GlobState
-}
-
-func (s implInvokableTestMethodServerStub) AMethod(ctx *context.T, call rpc.ServerCall) (string, error) {
- return s.impl.AMethod(ctx, call)
-}
-
-func (s implInvokableTestMethodServerStub) Globber() *rpc.GlobState {
- return s.gs
-}
-
-func (s implInvokableTestMethodServerStub) Describe__() []rpc.InterfaceDesc {
- return []rpc.InterfaceDesc{InvokableTestMethodDesc}
-}
-
-// InvokableTestMethodDesc describes the InvokableTestMethod interface.
-var InvokableTestMethodDesc rpc.InterfaceDesc = descInvokableTestMethod
-
-// descInvokableTestMethod hides the desc to keep godoc clean.
-var descInvokableTestMethod = rpc.InterfaceDesc{
- Name: "InvokableTestMethod",
- PkgPath: "v.io/x/js.core/test_service",
- Methods: []rpc.MethodDesc{
- {
- Name: "AMethod",
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // string
- },
- },
- },
-}
-
-// InvokeMethodWithCaveatedIdentityClientMethods is the client interface
-// containing InvokeMethodWithCaveatedIdentity methods.
-type InvokeMethodWithCaveatedIdentityClientMethods interface {
- Invoke(_ *context.T, name string, cavDesc security.CaveatDescriptor, cavParam *vom.RawBytes, _ ...rpc.CallOpt) error
-}
-
-// InvokeMethodWithCaveatedIdentityClientStub adds universal methods to InvokeMethodWithCaveatedIdentityClientMethods.
-type InvokeMethodWithCaveatedIdentityClientStub interface {
- InvokeMethodWithCaveatedIdentityClientMethods
- rpc.UniversalServiceMethods
-}
-
-// InvokeMethodWithCaveatedIdentityClient returns a client stub for InvokeMethodWithCaveatedIdentity.
-func InvokeMethodWithCaveatedIdentityClient(name string) InvokeMethodWithCaveatedIdentityClientStub {
- return implInvokeMethodWithCaveatedIdentityClientStub{name}
-}
-
-type implInvokeMethodWithCaveatedIdentityClientStub struct {
- name string
-}
-
-func (c implInvokeMethodWithCaveatedIdentityClientStub) Invoke(ctx *context.T, i0 string, i1 security.CaveatDescriptor, i2 *vom.RawBytes, opts ...rpc.CallOpt) (err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "Invoke", []interface{}{i0, i1, i2}, nil, opts...)
- return
-}
-
-// InvokeMethodWithCaveatedIdentityServerMethods is the interface a server writer
-// implements for InvokeMethodWithCaveatedIdentity.
-type InvokeMethodWithCaveatedIdentityServerMethods interface {
- Invoke(_ *context.T, _ rpc.ServerCall, name string, cavDesc security.CaveatDescriptor, cavParam *vom.RawBytes) error
-}
-
-// InvokeMethodWithCaveatedIdentityServerStubMethods is the server interface containing
-// InvokeMethodWithCaveatedIdentity methods, as expected by rpc.Server.
-// There is no difference between this interface and InvokeMethodWithCaveatedIdentityServerMethods
-// since there are no streaming methods.
-type InvokeMethodWithCaveatedIdentityServerStubMethods InvokeMethodWithCaveatedIdentityServerMethods
-
-// InvokeMethodWithCaveatedIdentityServerStub adds universal methods to InvokeMethodWithCaveatedIdentityServerStubMethods.
-type InvokeMethodWithCaveatedIdentityServerStub interface {
- InvokeMethodWithCaveatedIdentityServerStubMethods
- // Describe the InvokeMethodWithCaveatedIdentity interfaces.
- Describe__() []rpc.InterfaceDesc
-}
-
-// InvokeMethodWithCaveatedIdentityServer returns a server stub for InvokeMethodWithCaveatedIdentity.
-// It converts an implementation of InvokeMethodWithCaveatedIdentityServerMethods into
-// an object that may be used by rpc.Server.
-func InvokeMethodWithCaveatedIdentityServer(impl InvokeMethodWithCaveatedIdentityServerMethods) InvokeMethodWithCaveatedIdentityServerStub {
- stub := implInvokeMethodWithCaveatedIdentityServerStub{
- impl: impl,
- }
- // Initialize GlobState; always check the stub itself first, to handle the
- // case where the user has the Glob method defined in their VDL source.
- if gs := rpc.NewGlobState(stub); gs != nil {
- stub.gs = gs
- } else if gs := rpc.NewGlobState(impl); gs != nil {
- stub.gs = gs
- }
- return stub
-}
-
-type implInvokeMethodWithCaveatedIdentityServerStub struct {
- impl InvokeMethodWithCaveatedIdentityServerMethods
- gs *rpc.GlobState
-}
-
-func (s implInvokeMethodWithCaveatedIdentityServerStub) Invoke(ctx *context.T, call rpc.ServerCall, i0 string, i1 security.CaveatDescriptor, i2 *vom.RawBytes) error {
- return s.impl.Invoke(ctx, call, i0, i1, i2)
-}
-
-func (s implInvokeMethodWithCaveatedIdentityServerStub) Globber() *rpc.GlobState {
- return s.gs
-}
-
-func (s implInvokeMethodWithCaveatedIdentityServerStub) Describe__() []rpc.InterfaceDesc {
- return []rpc.InterfaceDesc{InvokeMethodWithCaveatedIdentityDesc}
-}
-
-// InvokeMethodWithCaveatedIdentityDesc describes the InvokeMethodWithCaveatedIdentity interface.
-var InvokeMethodWithCaveatedIdentityDesc rpc.InterfaceDesc = descInvokeMethodWithCaveatedIdentity
-
-// descInvokeMethodWithCaveatedIdentity hides the desc to keep godoc clean.
-var descInvokeMethodWithCaveatedIdentity = rpc.InterfaceDesc{
- Name: "InvokeMethodWithCaveatedIdentity",
- PkgPath: "v.io/x/js.core/test_service",
- Methods: []rpc.MethodDesc{
- {
- Name: "Invoke",
- InArgs: []rpc.ArgDesc{
- {"name", ``}, // string
- {"cavDesc", ``}, // security.CaveatDescriptor
- {"cavParam", ``}, // *vom.RawBytes
- },
- },
- },
-}
-
-// NativeTestClientMethods is the client interface
-// containing NativeTest methods.
-type NativeTestClientMethods interface {
- PassTime(_ *context.T, t time.Time, _ ...rpc.CallOpt) (time.Time, error)
- PassError(_ *context.T, e error, _ ...rpc.CallOpt) error
-}
-
-// NativeTestClientStub adds universal methods to NativeTestClientMethods.
-type NativeTestClientStub interface {
- NativeTestClientMethods
- rpc.UniversalServiceMethods
-}
-
-// NativeTestClient returns a client stub for NativeTest.
-func NativeTestClient(name string) NativeTestClientStub {
- return implNativeTestClientStub{name}
-}
-
-type implNativeTestClientStub struct {
- name string
-}
-
-func (c implNativeTestClientStub) PassTime(ctx *context.T, i0 time.Time, opts ...rpc.CallOpt) (o0 time.Time, err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "PassTime", []interface{}{i0}, []interface{}{&o0}, opts...)
- return
-}
-
-func (c implNativeTestClientStub) PassError(ctx *context.T, i0 error, opts ...rpc.CallOpt) (err error) {
- err = v23.GetClient(ctx).Call(ctx, c.name, "PassError", []interface{}{&i0}, nil, opts...)
- return
-}
-
-// NativeTestServerMethods is the interface a server writer
-// implements for NativeTest.
-type NativeTestServerMethods interface {
- PassTime(_ *context.T, _ rpc.ServerCall, t time.Time) (time.Time, error)
- PassError(_ *context.T, _ rpc.ServerCall, e error) error
-}
-
-// NativeTestServerStubMethods is the server interface containing
-// NativeTest methods, as expected by rpc.Server.
-// There is no difference between this interface and NativeTestServerMethods
-// since there are no streaming methods.
-type NativeTestServerStubMethods NativeTestServerMethods
-
-// NativeTestServerStub adds universal methods to NativeTestServerStubMethods.
-type NativeTestServerStub interface {
- NativeTestServerStubMethods
- // Describe the NativeTest interfaces.
- Describe__() []rpc.InterfaceDesc
-}
-
-// NativeTestServer returns a server stub for NativeTest.
-// It converts an implementation of NativeTestServerMethods into
-// an object that may be used by rpc.Server.
-func NativeTestServer(impl NativeTestServerMethods) NativeTestServerStub {
- stub := implNativeTestServerStub{
- impl: impl,
- }
- // Initialize GlobState; always check the stub itself first, to handle the
- // case where the user has the Glob method defined in their VDL source.
- if gs := rpc.NewGlobState(stub); gs != nil {
- stub.gs = gs
- } else if gs := rpc.NewGlobState(impl); gs != nil {
- stub.gs = gs
- }
- return stub
-}
-
-type implNativeTestServerStub struct {
- impl NativeTestServerMethods
- gs *rpc.GlobState
-}
-
-func (s implNativeTestServerStub) PassTime(ctx *context.T, call rpc.ServerCall, i0 time.Time) (time.Time, error) {
- return s.impl.PassTime(ctx, call, i0)
-}
-
-func (s implNativeTestServerStub) PassError(ctx *context.T, call rpc.ServerCall, i0 error) error {
- return s.impl.PassError(ctx, call, i0)
-}
-
-func (s implNativeTestServerStub) Globber() *rpc.GlobState {
- return s.gs
-}
-
-func (s implNativeTestServerStub) Describe__() []rpc.InterfaceDesc {
- return []rpc.InterfaceDesc{NativeTestDesc}
-}
-
-// NativeTestDesc describes the NativeTest interface.
-var NativeTestDesc rpc.InterfaceDesc = descNativeTest
-
-// descNativeTest hides the desc to keep godoc clean.
-var descNativeTest = rpc.InterfaceDesc{
- Name: "NativeTest",
- PkgPath: "v.io/x/js.core/test_service",
- Methods: []rpc.MethodDesc{
- {
- Name: "PassTime",
- InArgs: []rpc.ArgDesc{
- {"t", ``}, // time.Time
- },
- OutArgs: []rpc.ArgDesc{
- {"", ``}, // time.Time
- },
- },
- {
- Name: "PassError",
- InArgs: []rpc.ArgDesc{
- {"e", ``}, // error
- },
- },
- },
-}
-
-var __VDLInitCalled bool
-
-// __VDLInit performs vdl initialization. It is safe to call multiple times.
-// If you have an init ordering issue, just insert the following line verbatim
-// into your source files in this package, right after the "package foo" clause:
-//
-// var _ = __VDLInit()
-//
-// The purpose of this function is to ensure that vdl initialization occurs in
-// the right order, and very early in the init sequence. In particular, vdl
-// registration and package variable initialization needs to occur before
-// functions like vdl.TypeOf will work properly.
-//
-// This function returns a dummy value, so that it can be used to initialize the
-// first var in the file, to take advantage of Go's defined init order.
-func __VDLInit() struct{} {
- if __VDLInitCalled {
- return struct{}{}
- }
-
- // Register types.
- vdl.Register((*KeyPageResult)(nil))
- vdl.Register((*KeyValuePair)(nil))
- vdl.Register((*TestCaveatData)(nil))
-
- return struct{}{}
-}
diff --git a/go/src/v.io/x/js.core/test_service/test_serviced/cache_impl.go b/go/src/v.io/x/js.core/test_service/test_serviced/cache_impl.go
deleted file mode 100644
index 08c0d2d..0000000
--- a/go/src/v.io/x/js.core/test_service/test_serviced/cache_impl.go
+++ /dev/null
@@ -1,213 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "fmt"
- "reflect"
- "sort"
- "sync"
- "time"
-
- "v.io/v23/context"
- "v.io/v23/rpc"
- "v.io/v23/verror"
- "v.io/v23/vom"
- "v.io/x/js.core/test_service"
-)
-
-const pkgPath = "release/javascript/core/test_service/test_serviced"
-
-var errIndexOutOfBounds = verror.Register(pkgPath+".errIndexOutOfBounds", verror.NoRetry, "{1:}{2:} Page index out of bounds{:_}")
-
-// A simple in-memory implementation of a Cache service.
-type cacheImpl struct {
- mu sync.Mutex
- cache map[string]*vom.RawBytes
- mostRecent test_service.KeyValuePair
- lastUpdateTime time.Time
-}
-
-// NewCached returns a new implementation of CacheServerMethods.
-func NewCached() test_service.CacheServerMethods {
- return &cacheImpl{cache: make(map[string]*vom.RawBytes)}
-}
-
-// Set sets a value for a key. This should never return an error.
-func (c *cacheImpl) Set(ctx *context.T, _ rpc.ServerCall, key string, value *vom.RawBytes) error {
- c.mu.Lock()
- ctx.VI(0).Info("Set called with %v", key)
- c.cache[key] = value
- c.mostRecent = test_service.KeyValuePair{Key: key, Value: value}
- c.lastUpdateTime = time.Now()
- c.mu.Unlock()
- return nil
-}
-
-// Get returns the value for a key. If the key is not in the map, it returns
-// an error.
-func (c *cacheImpl) Get(ctx *context.T, _ rpc.ServerCall, key string) (*vom.RawBytes, error) {
- c.mu.Lock()
- defer c.mu.Unlock()
- if value, ok := c.cache[key]; ok {
- return value, nil
- }
- return nil, verror.New(verror.ErrNoExist, ctx, key)
-}
-
-// getWithTypeCheck gets the key and tests if its type matches the given time, erroring if it does
-// not.
-// This exists mostly to shorted the Get* methods below.
-func (c *cacheImpl) getWithTypeCheck(key string, rt reflect.Type) (interface{}, error) {
- v, err := c.Get(nil, nil, key)
- if err != nil {
- return reflect.Zero(rt).Interface(), err
- }
- if !reflect.TypeOf(v).AssignableTo(rt) {
- return reflect.Zero(rt).Interface(),
- fmt.Errorf("Cannot convert %v (type %v) to type %v", v, reflect.TypeOf(v), rt)
- }
- return v, nil
-}
-
-// Same as Get, but casts the return argument to an int32.
-func (c *cacheImpl) GetAsInt32(_ *context.T, _ rpc.ServerCall, key string) (int32, error) {
- v, err := c.getWithTypeCheck(key, reflect.TypeOf(int32(0)))
- return v.(int32), err
-}
-
-// Same as Get, but casts the return argument to an int64.
-func (c *cacheImpl) GetAsInt64(_ *context.T, _ rpc.ServerCall, key string) (int64, error) {
- v, err := c.getWithTypeCheck(key, reflect.TypeOf(int64(0)))
- return v.(int64), err
-}
-
-// Same as Get, but casts the return argument to an uint8.
-func (c *cacheImpl) GetAsByte(_ *context.T, _ rpc.ServerCall, key string) (byte, error) {
- v, err := c.getWithTypeCheck(key, reflect.TypeOf(byte(0)))
- return v.(uint8), err
-}
-
-// Same as Get, but casts the return argument to an uint32.
-func (c *cacheImpl) GetAsUint32(_ *context.T, _ rpc.ServerCall, key string) (uint32, error) {
- v, err := c.getWithTypeCheck(key, reflect.TypeOf(uint32(0)))
- return v.(uint32), err
-}
-
-// Same as Get, but casts the return argument to an uint64.
-func (c *cacheImpl) GetAsUint64(_ *context.T, _ rpc.ServerCall, key string) (uint64, error) {
- v, err := c.getWithTypeCheck(key, reflect.TypeOf(uint64(0)))
- return v.(uint64), err
-}
-
-// Same as Get, but casts the return argument to a float32.
-func (c *cacheImpl) GetAsFloat32(_ *context.T, _ rpc.ServerCall, key string) (float32, error) {
- v, err := c.getWithTypeCheck(key, reflect.TypeOf(float32(0)))
- return v.(float32), err
-}
-
-// Same as Get, but casts the return argument to a float64.
-func (c *cacheImpl) GetAsFloat64(_ *context.T, _ rpc.ServerCall, key string) (float64, error) {
- v, err := c.getWithTypeCheck(key, reflect.TypeOf(float64(0)))
- return v.(float64), err
-}
-
-// Same as Get, but casts the return argument to a string.
-func (c *cacheImpl) GetAsString(_ *context.T, _ rpc.ServerCall, key string) (string, error) {
- v, err := c.getWithTypeCheck(key, reflect.TypeOf(""))
- return v.(string), err
-}
-
-// Same as Get, but casts the return argument to a bool.
-func (c *cacheImpl) GetAsBool(_ *context.T, _ rpc.ServerCall, key string) (bool, error) {
- v, err := c.getWithTypeCheck(key, reflect.TypeOf(false))
- return v.(bool), err
-}
-
-// Same as Get, but converts the string return argument to an error.
-func (c *cacheImpl) GetAsError(_ *context.T, _ rpc.ServerCall, key string) (storedError error, callError error) {
- v, err := c.getWithTypeCheck(key, reflect.TypeOf([]error{}).Elem())
- return v.(error), err
-}
-
-// AsMap returns the full contents of the cache as a map.
-func (c *cacheImpl) AsMap(*context.T, rpc.ServerCall) (map[string]*vom.RawBytes, error) {
- return c.cache, nil
-}
-
-// KeyValuePairs returns the full contents of the cache as a slice of pairs.
-func (c *cacheImpl) KeyValuePairs(*context.T, rpc.ServerCall) ([]test_service.KeyValuePair, error) {
- c.mu.Lock()
- kvp := make([]test_service.KeyValuePair, 0, len(c.cache))
- for key, val := range c.cache {
- kvp = append(kvp, test_service.KeyValuePair{key, val})
- }
- c.mu.Unlock()
- return kvp, nil
-}
-
-// MostRecentSet returns the key and value and the timestamp for the most
-// recent set operation
-// TODO(bprosnitz) support type types and change time to native time type
-func (c *cacheImpl) MostRecentSet(ctx *context.T, _ rpc.ServerCall) (test_service.KeyValuePair, int64, error) {
- var err error
- c.mu.Lock()
- defer c.mu.Unlock()
- if c.lastUpdateTime.IsZero() {
- err = verror.New(verror.ErrNoExist, ctx)
- }
- return c.mostRecent, c.lastUpdateTime.Unix(), err
-}
-
-// KeyPage indexes into the keys (in alphanumerically sorted order) and
-// returns the indexth page of 10 keys.
-func (c *cacheImpl) KeyPage(ctx *context.T, _ rpc.ServerCall, index int64) (test_service.KeyPageResult, error) {
- results := test_service.KeyPageResult{}
-
- c.mu.Lock()
- keys := sort.StringSlice{}
- for key, _ := range c.cache {
- keys = append(keys, key)
- }
- c.mu.Unlock()
- keys.Sort()
-
- lowIndex := int(index) * 10
- if index < 0 || len(keys) <= lowIndex {
- return results, verror.New(errIndexOutOfBounds, ctx, index)
- }
- highIndex := lowIndex + 9
- if highIndex > len(keys)-1 {
- highIndex = len(keys) - 1
- }
-
- for i := 0; lowIndex+i <= highIndex; i++ {
- results[i] = keys[lowIndex+i]
- }
-
- return results, nil
-}
-
-// Size returns the total number of entries in the cache.
-func (c *cacheImpl) Size(*context.T, rpc.ServerCall) (int64, error) {
- return int64(len(c.cache)), nil
-}
-
-// MultiGet handles a stream of get requests. Returns an error if one of the
-// keys in the stream is not in the map or if there was an issue reading
-// the stream.
-func (c *cacheImpl) MultiGet(ctx *context.T, call test_service.CacheMultiGetServerCall) error {
- for call.RecvStream().Advance() {
- key := call.RecvStream().Value()
- c.mu.Lock()
- value, ok := c.cache[key]
- c.mu.Unlock()
- if !ok {
- return verror.New(verror.ErrNoExist, ctx, key)
- }
- call.SendStream().Send(value)
- }
- return call.RecvStream().Err()
-}
diff --git a/go/src/v.io/x/js.core/test_service/test_serviced/cancel_collector_impl.go b/go/src/v.io/x/js.core/test_service/test_serviced/cancel_collector_impl.go
deleted file mode 100644
index 7b16771..0000000
--- a/go/src/v.io/x/js.core/test_service/test_serviced/cancel_collector_impl.go
+++ /dev/null
@@ -1,103 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "sync"
- "time"
-
- "v.io/v23/context"
- "v.io/v23/rpc"
- "v.io/x/js.core/test_service"
-)
-
-type callStatus int
-
-const (
- unknown = callStatus(iota)
- running
- cancelled
-)
-
-func statusFromString(s string) callStatus {
- switch s {
- case "running":
- return running
- case "cancelled":
- return cancelled
- default:
- return unknown
- }
-}
-
-// NewCancelCollector returns a new implementation of CancelCollectorServerMethods.
-func NewCancelCollector() test_service.CancelCollectorServerMethods {
- return &cancelCollectorImpl{
- infoMap: make(map[int64]*callInfo),
- }
-}
-
-type callInfo struct {
- status callStatus
- timeout int64
- cond *sync.Cond
-}
-
-type cancelCollectorImpl struct {
- mu sync.Mutex
- infoMap map[int64]*callInfo
-}
-
-func (c *cancelCollectorImpl) setStatus(key int64, status callStatus) {
- c.mu.Lock()
- defer c.mu.Unlock()
-
- info := c.infoMap[key]
- if info.status < status {
- info.status = status
- info.cond.Broadcast()
- }
-}
-
-func (c *cancelCollectorImpl) getInfoLocked(key int64) *callInfo {
- info, ok := c.infoMap[key]
- if !ok {
- info = &callInfo{
- cond: sync.NewCond(&c.mu),
- }
- c.infoMap[key] = info
- }
- return info
-}
-
-func (c *cancelCollectorImpl) NeverReturn(ctx *context.T, _ rpc.ServerCall, key int64) error {
- timeout := int64(0x7FFFFFFFFFFFFFFF / 1000000)
- if deadline, ok := ctx.Deadline(); ok {
- timeout = int64(deadline.Sub(time.Now())) / 1000000
- }
-
- c.mu.Lock()
- info := c.getInfoLocked(key)
- info.timeout = timeout
- c.mu.Unlock()
-
- c.setStatus(key, running)
- <-ctx.Done()
- c.setStatus(key, cancelled)
- return nil
-}
-
-func (c *cancelCollectorImpl) WaitForStatus(_ *context.T, _ rpc.ServerCall, key int64, statusStr string) (int64, error) {
- status := statusFromString(statusStr)
-
- c.mu.Lock()
- defer c.mu.Unlock()
-
- info := c.getInfoLocked(key)
- for status > info.status {
- info.cond.Wait()
- }
- return info.timeout, nil
-}
diff --git a/go/src/v.io/x/js.core/test_service/test_serviced/error_thrower_impl.go b/go/src/v.io/x/js.core/test_service/test_serviced/error_thrower_impl.go
deleted file mode 100644
index cd7f622..0000000
--- a/go/src/v.io/x/js.core/test_service/test_serviced/error_thrower_impl.go
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "errors"
-
- "v.io/v23/context"
- "v.io/v23/rpc"
- "v.io/v23/verror"
- "v.io/x/js.core/test_service"
-)
-
-// NewErrorThrower returns a new implementation of ErrorThrowerServerMethods.
-func NewErrorThrower() test_service.ErrorThrowerServerMethods {
- return &errorThrowerImpl{}
-}
-
-type errorThrowerImpl struct{}
-
-func (e *errorThrowerImpl) ThrowAborted(ctx *context.T, _ rpc.ServerCall) error {
- return verror.New(verror.ErrAborted, ctx)
-}
-
-func (e *errorThrowerImpl) ThrowBadArg(ctx *context.T, _ rpc.ServerCall) error {
- return verror.New(verror.ErrBadArg, ctx)
-}
-
-func (e *errorThrowerImpl) ThrowBadProtocol(ctx *context.T, _ rpc.ServerCall) error {
- return verror.New(verror.ErrBadProtocol, ctx)
-}
-
-func (e *errorThrowerImpl) ThrowInternal(ctx *context.T, _ rpc.ServerCall) error {
- return verror.New(verror.ErrInternal, ctx)
-}
-
-func (e *errorThrowerImpl) ThrowNoAccess(ctx *context.T, _ rpc.ServerCall) error {
- return verror.New(verror.ErrNoAccess, ctx)
-}
-
-func (e *errorThrowerImpl) ThrowNoExist(ctx *context.T, _ rpc.ServerCall) error {
- return verror.New(verror.ErrNoExist, ctx)
-}
-
-func (e *errorThrowerImpl) ThrowNoExistOrNoAccess(ctx *context.T, _ rpc.ServerCall) error {
- return verror.New(verror.ErrNoExistOrNoAccess, ctx)
-}
-
-func (e *errorThrowerImpl) ThrowUnknown(ctx *context.T, _ rpc.ServerCall) error {
- return verror.New(verror.ErrUnknown, ctx)
-}
-
-func (e *errorThrowerImpl) ThrowGoError(*context.T, rpc.ServerCall) error {
- return errors.New("GoError!")
-}
-
-var customError = verror.Register(pkgPath+".customError", verror.NoRetry, "{1:}{2:} CustomStandard!{:_}")
-
-func (e *errorThrowerImpl) ThrowCustomStandardError(ctx *context.T, _ rpc.ServerCall) error {
- return verror.New(customError, ctx)
-}
diff --git a/go/src/v.io/x/js.core/test_service/test_serviced/invoke_method_caveat_id_impl.go b/go/src/v.io/x/js.core/test_service/test_serviced/invoke_method_caveat_id_impl.go
deleted file mode 100644
index 3480627..0000000
--- a/go/src/v.io/x/js.core/test_service/test_serviced/invoke_method_caveat_id_impl.go
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "fmt"
-
- "v.io/v23"
- "v.io/v23/context"
- "v.io/v23/rpc"
- "v.io/v23/security"
- "v.io/v23/vom"
- "v.io/x/js.core/test_service"
- vsecurity "v.io/x/ref/lib/security"
-)
-
-type invokeMethWCavIdImpl struct{}
-
-var _ test_service.InvokeMethodWithCaveatedIdentityServerMethods = (*invokeMethWCavIdImpl)(nil)
-
-func NewInvokeMethodWithCaveatedIdentityServer() test_service.InvokeMethodWithCaveatedIdentityServerMethods {
- return &invokeMethWCavIdImpl{}
-}
-
-// Invoke is a method on the InvokeMethodWithCaveatedIdentity service that
-// invokes "AMethod" on the service with the provided name with an identity
-// blessed with a caveat with the provided CaveatDescriptor.
-func (i *invokeMethWCavIdImpl) Invoke(ctx *context.T, call rpc.ServerCall, name string, cavDesc security.CaveatDescriptor, cavParam *vom.RawBytes) error {
- bytes, err := vom.Encode(cavParam)
- if err != nil {
- return err
- }
-
- cav := security.Caveat{
- Id: cavDesc.Id,
- ParamVom: bytes,
- }
- p := v23.GetPrincipal(ctx)
- other, _ := security.RemoteBlessingNames(ctx, call.Security())
- sharedWithOther := p.BlessingStore().ForPeer(other...)
-
- pWithCaveats, err := vsecurity.NewPrincipal()
- if err != nil {
- return err
- }
- // The "child" extension below is necessary for the blessing to be authorized
- // at the JavaScript server (which uses the default authorization policy).
- b, err := p.Bless(pWithCaveats.PublicKey(), sharedWithOther, "child", cav)
- if err != nil {
- return err
- }
- if err := vsecurity.SetDefaultBlessings(pWithCaveats, b); err != nil {
- return err
- }
-
- client := test_service.InvokableTestMethodClient(name)
- ctxWithCaveats, err := v23.WithPrincipal(ctx, pWithCaveats)
- if err != nil {
- return err
- }
-
- str, err := client.AMethod(ctxWithCaveats)
- if err != nil {
- return err
- }
- if str != "aResult" {
- return fmt.Errorf("Got wrong result %q", str)
- }
- return nil
-}
diff --git a/go/src/v.io/x/js.core/test_service/test_serviced/main.go b/go/src/v.io/x/js.core/test_service/test_serviced/main.go
deleted file mode 100644
index 4bd6d21..0000000
--- a/go/src/v.io/x/js.core/test_service/test_serviced/main.go
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Command test_serviced is an implementation of the test_service service.
-package main
-
-import (
- "fmt"
- "log"
-
- "v.io/v23"
- "v.io/x/ref/lib/flags"
- "v.io/x/ref/lib/signals"
- _ "v.io/x/ref/runtime/factories/generic"
- "v.io/x/ref/test"
-)
-
-func main() {
- flags.SetDefaultHostPort("127.0.0.1:0")
- ctx, shutdown := test.V23Init()
- defer shutdown()
-
- ctx, s, err := v23.WithNewDispatchingServer(ctx, "test_service", NewDispatcher())
- if err != nil {
- log.Fatalf("failure creating server: %v", err)
- }
- endpoint := s.Status().Endpoints[0]
- fmt.Printf("Listening at: %v\n", endpoint)
- <-signals.ShutdownOnSignals(ctx)
-}
diff --git a/go/src/v.io/x/js.core/test_service/test_serviced/native_impl.go b/go/src/v.io/x/js.core/test_service/test_serviced/native_impl.go
deleted file mode 100644
index a628aa3..0000000
--- a/go/src/v.io/x/js.core/test_service/test_serviced/native_impl.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "time"
-
- "v.io/v23/context"
- "v.io/v23/rpc"
- "v.io/x/js.core/test_service"
-)
-
-func NewNativeTest() test_service.NativeTestServerMethods {
- return &nativeTest{}
-}
-
-type nativeTest struct{}
-
-func (*nativeTest) PassTime(_ *context.T, _ rpc.ServerCall, t time.Time) (time.Time, error) {
- return t, nil
-}
-
-func (*nativeTest) PassError(_ *context.T, _ rpc.ServerCall, e error) error {
- return e
-}
diff --git a/go/src/v.io/x/js.core/test_service/test_serviced/test_serviced.go b/go/src/v.io/x/js.core/test_service/test_serviced/test_serviced.go
deleted file mode 100644
index 4377378..0000000
--- a/go/src/v.io/x/js.core/test_service/test_serviced/test_serviced.go
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package main
-
-import (
- "fmt"
- "strings"
-
- "v.io/v23/context"
- "v.io/v23/rpc"
- "v.io/v23/security"
- "v.io/x/js.core/test_service"
- _ "v.io/x/ref/runtime/factories/generic"
-)
-
-// openAuthorizer allows RPCs from all clients.
-type openAuthorizer struct{}
-
-func (openAuthorizer) Authorize(*context.T, security.Call) error {
- return nil
-}
-
-type testServiceDispatcher struct {
- cache interface{}
- errorThrower interface{}
- cancelCollector interface{}
- native interface{}
- caveatedInvoker interface{}
-}
-
-func NewDispatcher() rpc.Dispatcher {
- disp := &testServiceDispatcher{
- cache: test_service.CacheServer(NewCached()),
- errorThrower: test_service.ErrorThrowerServer(NewErrorThrower()),
- cancelCollector: test_service.CancelCollectorServer(NewCancelCollector()),
- native: test_service.NativeTestServer(NewNativeTest()),
- caveatedInvoker: test_service.InvokeMethodWithCaveatedIdentityServer(NewInvokeMethodWithCaveatedIdentityServer()),
- }
- return disp
-}
-
-func (sd *testServiceDispatcher) Lookup(_ *context.T, suffix string) (interface{}, security.Authorizer, error) {
- authorizer := openAuthorizer{}
-
- if strings.HasPrefix(suffix, "cache") {
- return rpc.ReflectInvokerOrDie(sd.cache), authorizer, nil
- }
-
- if strings.HasPrefix(suffix, "errorThrower") {
- return rpc.ReflectInvokerOrDie(sd.errorThrower), authorizer, nil
- }
-
- if strings.HasPrefix(suffix, "serviceToCancel") {
- return rpc.ReflectInvokerOrDie(sd.cancelCollector), authorizer, nil
- }
-
- if strings.HasPrefix(suffix, "native") {
- fmt.Println("got call to native")
- return rpc.ReflectInvokerOrDie(sd.native), authorizer, nil
- }
-
- if strings.HasPrefix(suffix, "caveatedInvoker") {
- return rpc.ReflectInvokerOrDie(sd.caveatedInvoker), authorizer, nil
- }
-
- return rpc.ReflectInvokerOrDie(sd.cache), authorizer, nil
-}
diff --git a/package.json b/package.json
index 3c5968f..d80101f 100644
--- a/package.json
+++ b/package.json
@@ -4,40 +4,27 @@
"version": "0.1.0",
"main": "./src/vanadium",
"dependencies": {
- "is-browser": "^2.0.1",
- "ws": "~0.4.31",
- "xtend": "^4.0.0",
- "eventemitter2": "~0.4.14",
- "lru-cache": "~2.5.0",
- "minimatch": "~2.0.1",
- "es6-shim": "^0.20.2",
+ "domready": "~1.0.8",
+ "es6-promise": "~2.1.1",
+ "es6-shim": "~0.35.0",
+ "eventemitter2": "~1.0.0",
+ "format": "~0.2.2",
"inherits": "~2.0.1",
- "format": "~0.2.1",
- "randombytes": "2.0.1",
- "domready": "~1.0.7",
- "es6-promise": "~2.1.1"
+ "is-browser": "~2.0.1",
+ "lru-cache": "~4.0.1",
+ "minimatch": "~3.0.0",
+ "randombytes": "~2.0.3",
+ "ws": "~1.0.1",
+ "xtend": "~4.0.1"
},
"devDependencies": {
- "node-static": "^0.7.4",
- "browserify": "^8.1.1",
- "child-killer": "~1.0.0",
- "comandante": "0.0.1",
- "debug": "^2.1.1",
- "dependency-check": "^1.1.5",
- "envify": "^3.2.0",
- "ink-docstrap": "~0.4.12",
- "jsdoc": "^3.3.0-alpha9",
- "jshint": "^2.6.0",
- "minimist": "^1.1.0",
- "mkdirp": "^0.5.0",
- "prova": "aghassemi/prova#0.0.4",
- "run-parallel": "^1.0.0",
- "which": "^1.0.5",
- "esprima": "~1.2.2",
- "tap-xunit": "~1.2.1",
- "uglifyify": "~3.0.1",
- "exorcist": "~0.1.6",
- "bower": "1.3.12",
- "grunt-cli": "0.1.13"
+ "bower": "~1.7.7",
+ "debug": "~2.2.0",
+ "dependency-check": "~2.5.1",
+ "ink-docstrap": "~1.1.4",
+ "jsdoc": "~3.4.0",
+ "jshint": "~2.9.1",
+ "tape": "~4.5.1",
+ "tap-xunit": "~1.3.1"
}
}
diff --git a/test/integration/default-blessing-regex.js b/test/integration/default-blessing-regex.js
deleted file mode 100644
index e883fe0..0000000
--- a/test/integration/default-blessing-regex.js
+++ /dev/null
@@ -1,5 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-module.exports = new RegExp('^test:child.*');
diff --git a/test/integration/default-config.js b/test/integration/default-config.js
deleted file mode 100644
index 7fc3bb5..0000000
--- a/test/integration/default-config.js
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var isBrowser = require('is-browser');
-
-// Use 'null' in browser to use nacl plugin.
-var wspr = isBrowser ? null : 'http://' + process.env.WSPR_ADDR;
-
-module.exports = {
- wspr: wspr
-};
diff --git a/test/integration/get-service.js b/test/integration/get-service.js
deleted file mode 100644
index 55a0752..0000000
--- a/test/integration/get-service.js
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var vanadium = require('../../');
-var config = require('./default-config');
-
-module.exports = service;
-
-// DRYs up test code by wrapping the default success case for:
-//
-// vanadium.init() -> runtime.bindTo() -> assertions -> runtime.close()
-//
-// To make a connection to the default integration test wspr instance and
-// bind to a service use:
-//
-// service('test_service/cache', function(err, ctx, cache, end, runtime) {
-// assert.error(err)
-//
-// // your assertions here...
-//
-// // use the `end` function to close the underlying runtime/wspr
-// // connection and end your test run.
-// end(assert)
-// })
-//
-function service(name, callback) {
- vanadium.init(config, function(err, runtime) {
- if (err) {
- return callback(err);
- }
-
- var ctx = runtime.getContext();
- runtime.getClient().bindTo(ctx, name, function(err, service) {
- callback(err, ctx, service, end, runtime);
- });
-
- // hoisted and passed as the last argument to the callback argument.
- function end(assert) {
- if (typeof assert === 'function') {
- return runtime.close(assert);
- } else if (!! assert.end && typeof assert.end === 'function') {
- return runtime.close(function(err) {
- assert.error(err, 'should not error on runtime.close(...)');
- assert.end();
- });
- } else {
- var message = 'end(callback) requires a callback or assert object';
- throw new Error(message);
- }
- }
- });
-}
diff --git a/test/integration/runner.js b/test/integration/runner.js
deleted file mode 100644
index 21558c7..0000000
--- a/test/integration/runner.js
+++ /dev/null
@@ -1,96 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var debug = require('debug')('integration-runner');
-var extend = require('xtend');
-var ServiceRunner = require('../services/run-services');
-var serviceRunner;
-var spawn = require('child_process').spawn;
-
-var argv = require('minimist')(process.argv.slice(2), {
- '--': true,
- default: {services: ''}
-});
-
-process.on('uncaughtException', function(err) {
- console.error('Uncaught exception: ' + err);
- stop(err);
-});
-process.on('SIGINT', stop);
-
-// Spawn test command and stop on exit.
-function runTests() {
- debug('running tests');
- var debugEnv = {
- DEBUG: argv.debug || process.env.DEBUG || '',
- DEBUG_COLORS: true
- };
- var env = extend(process.env, serviceRunner.env, debugEnv);
-
- var command = argv['--'];
- var name = command[0];
- var args = command.slice(1);
- var proc = spawn(name, args, {env: env});
-
- // Pipe the test's stdout and stderr to the parent process.
- proc.stdout.pipe(process.stdout);
- proc.stderr.pipe(process.stderr);
- proc.on('error', function(err) {
- debug('test errored');
- stop(err);
- });
-
- // NOTE: 'exit' is better than 'close' in this context since close can be
- // emitted multiple times (since multiple processes might share the same
- // stdio streams)
- proc.on('exit', function(code, signal) {
- debug('test process exited - code: %s, signal: %s', code, signal);
- stop(null, code);
- });
-}
-
-// Stop all services and exit.
-function stop(err, code) {
- if (err) {
- code = code || 1;
- console.error(err);
- console.error(err.stack);
- } else {
- code = code || 0;
- }
-
- serviceRunner.stop(function(err) {
- if (err) {
- debug('warning: serviceRunner.stop() failed! exiting anyways: %s', code);
- } else {
- debug('runner stopped, exiting: %s', code);
- }
- process.exit(code);
- });
-}
-
-// Starts the "servicerunner" service as well as any services specified in the
-// --services command line flag, then runs tests.
-function startServicesAndRunTests() {
- var services = [];
- if (argv.services && argv.services.length) {
- services = argv.services.split(',');
- }
-
- debug('starting core services and: ' + services.join(', '));
-
- // NOTE(sadovsky): There are all sorts of race conditions and unhandled edge
- // cases in this code.
- serviceRunner = new ServiceRunner(services);
- serviceRunner
- .on('error', stop)
- .start(function(err) {
- if (err) {
- return stop(err);
- }
- runTests();
- });
-}
-
-startServicesAndRunTests();
diff --git a/test/integration/serve.js b/test/integration/serve.js
deleted file mode 100644
index 44c4b85..0000000
--- a/test/integration/serve.js
+++ /dev/null
@@ -1,162 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var vanadium = require('../../');
-var config = require('./default-config');
-var extend = require('xtend');
-var defaults = {
- autoBind: true
-};
-
-module.exports = serve;
-
-// # serve(name, dispatcher, callback)
-//
-// DRYs up test code by wrapping the default success case for:
-//
-// vanadium.init() ->
-// runtime.server(name, dispatcher, ...) ->
-// runtime.bindTo(ctx, name, ...) -> r
-// assertions ->
-// runtime.close()
-//
-// To make a connection to the default integration test wspr instance and
-// bind to a service use:
-//
-// serve('test/service', dispatcher, function(err, res) {
-// res.service.returnBuiltInError(function(err) {
-// assert.error(err)
-//
-// // your assertions here...
-//
-// // `res` has several attributes to make your life easier:
-// //
-// // * runtime: vanadium runtime object
-// // * config: config passed into vanadium.init()
-// // * server: returned from runtime._getServer()
-// // * service: returned from runtime.bindTo(name, ...)
-// // * end: the end function to shut down the connection
-//
-//
-// // use the `res.end` function to close the underlying runtime/wspr
-// // connection and end your test run.
-// res.end(assert);
-// })
-// })
-//
-function serve(name, dispatcher, callback) {
- var options = defaults;
- var serverOption;
- // alternate: serve(options, callback)
- if (typeof name === 'object') {
- options = extend(defaults, name);
- callback = dispatcher;
- name = options.name;
- dispatcher = options.dispatcher;
- serverOption = options.serverOption;
- }
-
- vanadium.init(config, function(err, runtime) {
- // basic response used for failures where we want .close and .end to
- // still work:
- var basicRes = {
- end: end,
- close: close
- };
-
- if (err) {
- return callback(err, basicRes);
- }
-
- runtime.newDispatchingServer(name, dispatcher, serverOption,
- function(err, server) {
-
- if (err) {
- return callback(err, basicRes);
- }
-
- var ctx = runtime.getContext();
-
- waitUntilResolve();
-
- // The server is not gauranteed to be mounted by the time the
- // serve call finishes. We should wait until the name
- // resolves before calling the callback. As a side a benefit,
- // this also speeds up the browser tests, because browspr is
- // quicker than wspr and so it is more likely to return before
- // the server is mounted. The normal backoff for bindTo
- // starts at 100ms, but this code only waits a few
- // milliseconds. TODO(mattr): I have temporarily set this to
- // retry at longer intervals. In practice this previous code
- // (which checked every 10ms) allowed the server up to 0.5s or
- // so to mount through the proxy. In the new RPC system it
- // can take a bit longer. I upped the number of attempts and
- // retry time to compensate. We will eventually optimize this
- // time back down.
- function waitUntilResolve() {
- var ns = runtime.getNamespace();
- var count = 0;
- runResolve();
-
- function runResolve() {
- ns.resolve(ctx, name, function(err, s) {
- if (err || s.length === 0) {
- count++;
- if (count === 20) {
- return callback(
- new Error(
- 'Timed out waiting for resolve in serve.js: ' + err),
- basicRes);
- }
- return setTimeout(runResolve, 100);
- }
- completeServe();
- });
- }
- }
-
- function completeServe() {
- var res = {
- runtime: runtime,
- config: config,
- close: close,
- end: end,
- server: server
- };
-
- if (options.autoBind === false) {
- return callback(err, res, end);
- }
-
- function onBind(err, service) {
- if (err) {
- return callback(err, basicRes);
- }
-
- res.service = service;
- callback(err, res, end);
- }
- var client = runtime.getClient();
- client.bindTo(ctx, name, onBind);
- }
- });
-
- function close(callback) {
- return runtime.close(callback);
- }
-
- // hoisted and passed as the last argument to the callback argument.
- function end(assert, errorMsg) {
- if (!!assert.end && typeof assert.end === 'function') {
- return close(function(err) {
- assert.error(err, 'should not error on runtime.close(...)');
- assert.end(errorMsg);
- });
- } else {
- var message = 'end(callback) requires an assert object';
- throw new Error(message);
- }
- }
- });
-}
diff --git a/test/integration/test-authorizer.js b/test/integration/test-authorizer.js
deleted file mode 100644
index f88ea69..0000000
--- a/test/integration/test-authorizer.js
+++ /dev/null
@@ -1,220 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var vanadium = require('../..');
-var test = require('prova');
-var Deferred = require('../../src/lib/deferred');
-var serve = require('./serve');
-var access = vanadium.security.access;
-var permissionsAuthorizer = vanadium.security.access.permissionsAuthorizer;
-var allowEveryoneAuthorizer = vanadium.security.access.allowEveryoneAuthorizer;
-
-var service = {
- call: function(ctx, serverCall, arg) {
- return Promise.resolve(1);
- }
-};
-
-function createPromiseDispatcher(authorizer, tags) {
- function auth(ctx, call) {
- if (call.method === '__Signature') {
- return null;
- }
- return authorizer(ctx, call);
- }
- var desc = {
- methods: [
- {
- name: 'Call',
- tags: tags
- }
- ]
- };
- service._serviceDescription = desc;
- return function callbackDispatcher(suffix) {
- return {
- service: service,
- authorizer: auth,
- };
- };
-}
-
-
-function testErrorCase(assert, authorizer, tags, isPromise) {
- serve({
- name: 'authorizerTestService',
- autoBind: false,
- dispatcher: isPromise ?
- createPromiseDispatcher(authorizer, tags) :
- createCallbackDispatcher(authorizer, tags)
- }, function(err, res) {
- if (err) {
- return assert.end(err);
- }
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
- client.bindTo(ctx, 'authorizerTestService/auth').then(function(service) {
- service.call(ctx, 'foo').then(function(value) {
- assert.error(new Error('call should not have succeeded. res:' + value));
- res.end(assert);
- }).catch(function(err) {
- assert.ok(err);
- res.end(assert);
- });
- }, function(err) {
- assert.error(err);
- res.end(assert);
- });
- });
-}
-
-test('Test errors are properly returned',
-function(assert) {
- testErrorCase(assert, function (ctx, call) {
- var def = new Deferred();
- function reject() {
- def.reject(new Error('unauthorized'));
- }
- setTimeout(reject, 0);
- return def.promise;
- }, [], true);
-});
-
-function createCallbackDispatcher(authorizer, tags) {
- function auth(ctx, call, cb) {
- if (call.method === '__Signature') {
- cb(null);
- }
- authorizer(ctx, call, cb);
- }
- var desc = {
- methods: [
- {
- name: 'Call',
- tags: tags
- }
- ]
- };
- service._serviceDescription = desc;
- return function callbackDispatcher(suffix) {
- return {
- service: service,
- authorizer: auth,
- };
- };
-}
-
-function testSuccessCase(assert, authorizer, tags, isPromise) {
- serve({
- name: 'authorizerTestService',
- autoBind: false,
- dispatcher: isPromise ?
- createPromiseDispatcher(authorizer, tags) :
- createCallbackDispatcher(authorizer, tags)
- }, function(err, res) {
- if (err) {
- return assert.end(err);
- }
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
- client.bindTo(ctx, 'authorizerTestService/auth').then(function(service) {
- return service.call(ctx, 'foo');
- }).then(function() {
- assert.pass('RPC resolved');
- res.end(assert);
- }).catch(function(err) {
- assert.fail('RPC rejected with error:' + err.toString());
- res.end(assert);
- });
- });
-}
-
-
-test('Test successes are handled', function(assert) {
- testSuccessCase(assert, function (ctx, call, cb) {
- process.nextTick(cb.bind(null, null));
- });
-});
-
-test('Test proper context is passed to authorizer', function(assert) {
- var defaultBlessingRegex = require('./default-blessing-regex');
-
- testSuccessCase(assert, function (ctx, call, cb) {
- if (!defaultBlessingRegex.test(call.remoteBlessingStrings[0])) {
- return cb(new Error('unknown remote blessings ' +
- call.remoteBlessingStrings));
- } else if (!defaultBlessingRegex.test(call.localBlessingStrings[0])) {
- cb(new Error('unknown local blessings ' + call.localBlessingStrings));
- } else if (call.method !== 'call') {
- return cb(new Error('wrong method ' + call.method));
- } else if (call.suffix !== 'auth') {
- return cb(new Error('wrong suffix ' + call.suffix));
- }
- // TODO(bjornick): Fix the endpoint format
- // } else if (call.remoteEndpoint === endpoint ||
- // !call.remoteEndpoint) {
- // return new Error('bad endpoint ' + call.remoteEndpoint);
- // } else if (call.localEndpoint !== endpoint ||
- // !call.localEndpoint) {
- // return new Error('bad endpoint ' + call.localEndpoint);
- // }
-
- cb();
- });
-});
-
-test('Test passing in labels', function(assert) {
- testSuccessCase(assert, function(ctx, call, cb) {
- if (call.methodTags[0] !== 'foo') {
- return cb(new Error('wrong label ' + call.label));
- }
- return cb();
- }, ['foo']);
-});
-
-var perms = {
- foo: {
- in: ['...']
- },
- bar: {}
-};
-var tagPermsAuthorizer = permissionsAuthorizer(perms, access.Tag);
-
-
-test('Test permissionsAuthorizer (public key) - success', function(assert) {
- var tagBar = new access.Tag('Bar');
-
- // Passes because we reuse the same public key, despite the tag not being ok.
- testSuccessCase(assert, tagPermsAuthorizer, [tagBar], true);
-});
-
-test('Test permissionsAuthorizer (tag) - success', function(assert) {
- var tagFoo = new access.Tag('Foo');
-
- function diffPublicKeyPermsAuthorizer(ctx, call) {
- // get rid of public key, just for this example
- call.remoteBlessings.publicKey = '';
- tagPermsAuthorizer(ctx, call);
- }
-
- // Everyone is allowed via the Foo tag.
- testSuccessCase(assert, diffPublicKeyPermsAuthorizer, [tagFoo], true);
-});
-
-test('Test permissionsAuthorizer (tag) - failure', function(assert) {
- var tagBar = new access.Tag('Bar');
-
- function diffPublicKeyPermsAuthorizer(ctx, call) {
- // get rid of public key, just for this example to demonstrate failure
- call.remoteBlessings.publicKey = '';
- tagPermsAuthorizer(ctx, call);
- }
-
- // Nobody is allowed via the Bar tag.
- testErrorCase(assert, diffPublicKeyPermsAuthorizer, [tagBar], true);
-});
-
-test('Test allowEveryoneAuthorizer() - success', function(assert) {
- testSuccessCase(assert, allowEveryoneAuthorizer(), [], true);
-});
diff --git a/test/integration/test-bless.js b/test/integration/test-bless.js
deleted file mode 100644
index 2ce1ba1..0000000
--- a/test/integration/test-bless.js
+++ /dev/null
@@ -1,266 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var vanadium = require('../../');
-var config = require('./default-config');
-var leafDispatcher = require('../../src/rpc/leaf-dispatcher');
-var Blessings = require('../../src/security/blessings');
-var serve = require('./serve');
-var security = vanadium.security;
-
-function validateBlessings(t, blessings) {
- t.ok(blessings instanceof Blessings, 'Blessings have correct type');
- t.ok(blessings.chains.length > 0, 'Non-empty chains');
- t.ok(blessings.publicKey, 'Public key is set');
-}
-
-test('Test bless self without Caveat', function(t) {
- var rt;
- vanadium.init(config, function(err, runtime) {
- if (err) {
- t.end(err);
- }
-
- rt = runtime;
-
- runtime.principal.blessSelf(runtime.getContext(), 'blessedname')
- .then(function(blessings) {
- validateBlessings(t, blessings);
- t.equal(blessings.chains.length, 1, 'Has exactly one chain');
- t.equal(blessings.chains[0].length, 1, 'Chain has exactly one blessing');
- t.equal(blessings.chains[0][0].extension, 'blessedname',
- 'Has correct extension');
- t.equal(blessings.chains[0][0].caveats.length, 0, 'Has no caveats');
- rt.close(t.end);
- }).catch(function(err) {
- t.error(err);
- rt.close(t.end);
- });
- });
-});
-
-test('Test bless self with Caveat', function(t) {
- var rt;
- vanadium.init(config, function(err, runtime) {
- if (err) {
- t.end(err);
- }
-
- rt = runtime;
-
- var cav = security.createExpiryCaveat(new Date());
- runtime.principal.blessSelf(runtime.getContext(), 'blessedname', cav,
- function(err, blessings) {
- t.error(err);
- validateBlessings(t, blessings);
- t.equal(blessings.chains.length, 1, 'Has exactly one chain');
- t.equal(blessings.chains[0].length, 1, 'Chain has exactly one blessing');
- t.equal(blessings.chains[0][0].extension, 'blessedname',
- 'Has correct extension');
- t.equal(blessings.chains[0][0].caveats.length, 1, 'Has one caveat');
- t.deepEqual(blessings.chains[0][0].caveats[0], cav, 'Has correct caveat');
- rt.close(t.end);
- });
- });
-});
-
-test('Test bless without Caveat from server', function(t) {
- var service = {
- method: function(ctx, serverCall, cb) {
- var secCall = serverCall.securityCall;
- var rt = vanadium.runtimeForContext(ctx);
- var remoteKey = secCall.remoteBlessings.publicKey;
- rt.principal.bless(ctx, remoteKey, secCall.localBlessings,
- 'ext', function(err) {
- t.ok(err, 'Expected at least one caveat must be specified error');
- cb(null, null);
- });
- }
- };
-
- serve('testing/blessnocav', leafDispatcher(service),
- function(err, res) {
- if (err) {
- res.end(t, err);
- return;
- }
-
- res.service.method(res.runtime.getContext(), function(err) {
- t.error(err);
- res.end(t);
- });
- });
-});
-
-test('Test bless with Caveat from server', function(t) {
- var service = {
- method: function(ctx, serverCall, cb) {
- var rt = vanadium.runtimeForContext(ctx);
- var secCall = serverCall.securityCall;
- var remoteKey = secCall.remoteBlessings.publicKey;
- var expiryCav = security.createExpiryCaveat(new Date(Date.now() - 1000));
- var constCav = security.createConstCaveat(true);
- rt.principal.bless(ctx, remoteKey, secCall.localBlessings,
- 'ext', expiryCav, constCav, function(err, blessings) {
- t.notOk(err, 'No error expected during bless');
- validateBlessings(t, blessings);
- for (var i = 0; i < blessings.chains.length; i++) {
- var chain = blessings.chains[i];
- t.equal(chain[chain.length - 1].extension, 'ext',
- 'Expected final extension to match');
- t.deepEqual(chain[chain.length - 1].caveats.sort(objectSorter),
- [expiryCav, constCav].sort(objectSorter),
- 'Has correct caveats');
- }
- cb(null, null);
- });
- }
- };
-
- serve('testing/blesscav', leafDispatcher(service),
- function(err, res) {
- if (err) {
- res.end(t, err);
- return;
- }
-
- res.service.method(res.runtime.getContext(), function(err) {
- t.error(err);
- res.end(t);
- });
- });
-});
-
-test('Test bless without Caveat from client (with Granter)', function(t) {
- var expectedBlessing;
-
- var service = {
- method: function(ctx, serverCall) {
- t.ok(serverCall.grantedBlessings, 'Expect to get granted blessing');
- t.deepEqual(serverCall.grantedBlessings, expectedBlessing,
- 'Expect to get blessing that was granted.');
- return 'aResponse';
- }
- };
-
-
- serve('testing/clientblessgranter', leafDispatcher(service),
- function(err, res) {
- if (err) {
- t.end(err);
- return;
- }
-
- var client = res.runtime.getClient();
- var fiveSecondsInFuture = new Date(Date.now() + 5000);
- var granterCalled = false;
- var granterOption = client.callOption({
- granter: function(ctx, call, cb) {
- granterCalled = true;
- res.runtime.principal.bless(res.runtime.getContext(),
- call.remoteBlessings.publicKey,
- call.localBlessings,
- 'ext',
- security.createExpiryCaveat(fiveSecondsInFuture),
- function(err, blessing) {
- expectedBlessing = blessing;
- cb(err, blessing);
- });
- }
- });
-
- res.service.method(res.runtime.getContext(), granterOption, function(err){
- t.ok(granterCalled, 'Granter should be called');
- t.error(err);
- res.runtime.close(t.end);
- });
- });
-});
-
-// Tests add roots by trying to invoke a method with a blessing not in the
-// roots and then adding it to the roots.
-test('Test add roots', function(t) {
- var service = {
- method: function(ctx, serverCall) {
- return 'aResponse';
- }
- };
-
- var authorizer = function(ctx, securityCall) {
- var hasBlessedName = securityCall.remoteBlessingStrings.some(function(str) {
- return str === 'blessedname';
- });
- if (hasBlessedName) {
- return Promise.resolve();
- }
- return Promise.reject(new Error('Expected blessedname in blessings'));
- };
-
- serve('testing/addroots', leafDispatcher(service, authorizer),
- function(err, res) {
- if (err) {
- t.end(err);
- return;
- }
-
- var runtime = res.runtime;
- var ctx = runtime.getContext();
- var blessings;
- var origDefault;
- var origTripDot;
- runtime.principal.blessSelf(ctx, 'blessedname')
- .then(function(selfBlessings) {
- blessings = selfBlessings;
- validateBlessings(t, blessings);
- // Get the original blessings used for '...' and save them for later.
- return runtime.principal.blessingStore.forPeer(ctx, '...');
- }).then(function(oldBlessings) {
- origTripDot = oldBlessings;
- // Replace it with the union of the old and the new self-blessing
- return vanadium.security.unionOfBlessings(ctx, oldBlessings, blessings);
- }).then(function(unionedBlessings) {
- return runtime.principal.blessingStore.set(ctx, unionedBlessings, '...');
- }).then(function() {
- // Get the original default blessings and save them for later.
- return runtime.principal.blessingStore.getDefault(ctx);
- }).then(function(oldDefault) {
- origDefault = oldDefault;
- // Replace it with the union of the old and the new self-blessing
- return vanadium.security.unionOfBlessings(ctx, oldDefault, blessings);
- }).then(function(unionedBlessings) {
- return runtime.principal.blessingStore.setDefault(ctx, unionedBlessings);
- }).catch(function(err) {
- t.error('Failed to configure blessings: ' + err);
- }).then(function() {
- // Attempt to call the method; it should fail.
- return res.service.method(ctx);
- }).then(function() {
- t.error('Method call unexpectedly succeeded without valid roots');
- }).catch(function() {
- return runtime.principal.addToRoots(ctx, blessings);
- }).then(function() {
- // Call the method after addToRoots; it should succeed.
- return res.service.method(ctx);
- }).then(function(result) {
- t.equal(result, 'aResponse', 'Got correct result');
- }).catch(function(err) {
- t.error('either blessSelf or addToRoots errored ' + err);
- }).then(function() {
- // Reset the blessingStore for default blessings.
- return runtime.principal.blessingStore.setDefault(ctx, origDefault);
- }).then(function() {
- // Reset the blessingStore for peer '...'
- return runtime.principal.blessingStore.set(ctx, origTripDot, '...');
- }).catch(function(err) {
- t.error('Unexpected error resetting blessing store');
- }).then(function(){
- res.end(t);
- });
- });
-});
-
-function objectSorter(a, b) {
- return JSON.stringify(a) < JSON.stringify(b);
-}
diff --git a/test/integration/test-blessings-util.js b/test/integration/test-blessings-util.js
deleted file mode 100644
index 48d1a5a..0000000
--- a/test/integration/test-blessings-util.js
+++ /dev/null
@@ -1,75 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var vanadium = require('../../');
-var config = require('./default-config');
-var security = vanadium.security;
-
-function validateUnionedBlessings(t, blessings) {
- t.equal(blessings.chains.length, 2, 'Should have 2 chains');
- t.equal(blessings.chains[0].length, 1, 'First chain has 1 cert');
- t.equal(blessings.chains[1].length, 1, 'Second chain has 1 cert');
- t.equal(blessings.chains[0][0].extension, 'blessedname1',
- 'Get first extension on first chain');
- t.equal(blessings.chains[1][0].extension, 'blessedname2',
- 'Get second extension on second chain');
- t.deepEqual(blessings.chains[0][0].publicKey, blessings.publicKey,
- 'First public key matches blessing key');
- t.deepEqual(blessings.chains[1][0].publicKey, blessings.publicKey,
- 'Second public key matches blessing key');
-}
-
-test('Test union of blessings', function(t) {
- vanadium.init(config, function(err, runtime) {
- if (err) {
- t.end(err);
- }
-
- runtime.principal.blessSelf(runtime.getContext(), 'blessedname1')
- .then(function(blessings1) {
- return runtime.principal.blessSelf(runtime.getContext(), 'blessedname2')
- .then(function(blessings2) {
- return security.unionOfBlessings(
- runtime.getContext(), blessings1, blessings2);
- });
- })
- .then(function(unionedBlessings) {
- validateUnionedBlessings(t, unionedBlessings);
- runtime.close(t.end);
- }).catch(function(err) {
- runtime.close();
- t.end(err);
- });
- });
-});
-
-test('Test union of blessings with differing public keys', function(t) {
- vanadium.init(config, function(err, runtime) {
- if (err) {
- t.end(err);
- }
-
- runtime.principal.blessSelf(runtime.getContext(), 'blessedname1')
- .then(function(blessings1) {
- return runtime.principal.blessSelf(runtime.getContext(), 'blessedname2')
- .then(function(blessings2) {
- // modify the public key so it doesn't match
- blessings2.chains[0][0].publicKey[0] -= 1;
- return security.unionOfBlessings(
- runtime.getContext(), blessings1, blessings2);
- });
- })
- .then(function(unionedBlessings) {
- runtime.close();
- t.end('Should have failed due to public keys not matching');
- }).catch(function(err) {
- t.ok(err instanceof Error, 'Got error');
- t.ok(err.toString().indexOf('cannot create union of blessings ' +
- 'bound to different public keys') !== -1,
- 'Should get message about keys differing');
- runtime.close(t.end);
- });
- });
-});
diff --git a/test/integration/test-blessingstore.js b/test/integration/test-blessingstore.js
deleted file mode 100644
index 2ad5d2f..0000000
--- a/test/integration/test-blessingstore.js
+++ /dev/null
@@ -1,383 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var vanadium = require('../../');
-var Blessings = require('../../src/security/blessings');
-var config = require('./default-config');
-
-function validateBlessings(t, blessings) {
- t.ok(blessings instanceof Blessings, 'Blessings have correct type');
- t.ok(blessings.chains.length > 0, 'Non-empty chains');
- t.ok(blessings.publicKey, 'Public key is set');
-}
-
-test('Test blessing store set (promise case)', function(t) {
- vanadium.init(config, function(err, runtime) {
- if (err) {
- t.end(err);
- }
- var blessSelfResult;
- runtime.principal.blessSelf(runtime.getContext(), 'ext')
- .then(function(blessings) {
- validateBlessings(t, blessings);
- blessSelfResult = blessings;
-
- return runtime.principal.blessingStore.set(runtime.getContext(),
- blessings, 'fake:remote:pattern');
- }).then(function() {
- return runtime.principal.blessingStore.set(runtime.getContext(),
- blessSelfResult, 'fake:remote:pattern');
- }).then(function(firstBlessing) {
- t.deepEqual(firstBlessing, blessSelfResult,
- 'Should get first blessings back');
- validateBlessings(t, firstBlessing);
- runtime.close(t.end);
- }).catch(function(err) {
- t.error(err, 'either blessSelf or blessingStore.set errored');
- runtime.close(t.end);
- });
- });
-});
-
-test('Test blessing store set (callback case)', function(t) {
- vanadium.init(config, function(err, runtime) {
- if (err) {
- t.end(err);
- }
- var blessSelfResult;
- runtime.principal.blessSelf(runtime.getContext(), 'ext',
- function(err, blessings) {
- if (err) {
- t.error(err);
- runtime.close(t.end);
- return;
- }
- validateBlessings(t, blessings);
- blessSelfResult = blessings;
-
- runtime.principal.blessingStore.set(runtime.getContext(),
- blessings, 'fake:remote:pattern',
- function(err) {
- if (err) {
- t.error(err);
- runtime.close(t.end);
- return;
- }
- runtime.principal.blessingStore.set(runtime.getContext(),
- blessSelfResult, 'fake:remote:pattern',
- function(err, firstBlessing) {
- if (err) {
- t.error(err);
- runtime.close(t.end);
- return;
- }
- t.deepEqual(firstBlessing, blessSelfResult,
- 'Should get first blessings back');
- validateBlessings(t, firstBlessing);
- runtime.close(t.end);
- });
- });
- });
- });
-});
-
-test('Test blessing store for peer (promise case)', function(t) {
- vanadium.init(config, function(err, runtime) {
- if (err) {
- t.end(err);
- }
-
- runtime.principal.blessSelf(runtime.getContext(), 'ext')
- .then(function(blessings) {
- validateBlessings(t, blessings);
-
- return runtime.principal.blessingStore.set(runtime.getContext(),
- blessings, 'fake:remote:pattern');
- }).then(function() {
- return runtime.principal.blessingStore.forPeer(runtime.getContext(),
- 'fake:remote:pattern');
- }).then(function(firstBlessing) {
- validateBlessings(t, firstBlessing);
- runtime.close(t.end);
- }).catch(function(err) {
- t.error(err, 'error in one of the async calls');
- runtime.close(t.end);
- });
- });
-});
-
-test('Test blessing store for peer (callback case)', function(t) {
- vanadium.init(config, function(err, runtime) {
- if (err) {
- t.end(err);
- }
-
- runtime.principal.blessSelf(runtime.getContext(), 'ext',
- function(err, blessings) {
- if (err) {
- t.error(err);
- runtime.close(t.end);
- return;
- }
- validateBlessings(t, blessings);
-
- runtime.principal.blessingStore.set(runtime.getContext(),
- blessings, 'fake:remote:pattern',
- function(err) {
- if (err) {
- t.error(err);
- runtime.close(t.end);
- return;
- }
- return runtime.principal.blessingStore.forPeer(runtime.getContext(),
- 'fake:remote:pattern',
- function(err, firstBlessing) {
- validateBlessings(t, firstBlessing);
- runtime.close(t.end);
- });
- });
- });
- });
-});
-
-test('Test blessing store set/get default (promise case)', function(t) {
- vanadium.init(config, function(err, runtime) {
- if (err) {
- t.end(err);
- }
-
- var blessSelfResult;
- var oldDefaultBlessings;
- runtime.principal.blessSelf(runtime.getContext(), 'ext')
- .then(function(blessings) {
- validateBlessings(t, blessings);
- blessSelfResult = blessings;
-
- return runtime.principal.blessingStore.getDefault(runtime.getContext());
- }).then(function(blessings) {
- oldDefaultBlessings = blessings;
- validateBlessings(t, oldDefaultBlessings);
- return runtime.principal.blessingStore.setDefault(
- runtime.getContext(), blessSelfResult);
- }).then(function() {
- return runtime.principal.blessingStore.getDefault(runtime.getContext());
- }).then(function(defaultBlessings) {
- validateBlessings(t, defaultBlessings);
- t.deepEqual(defaultBlessings, blessSelfResult,
- 'Should get default blessings back');
-
- // Restore original default blessings
- return runtime.principal.blessingStore.setDefault(
- runtime.getContext(), oldDefaultBlessings);
- }).then(function() {
- runtime.close(t.end);
- }).catch(function(err) {
- t.error(err, 'error in one of the async calls');
- runtime.close(t.end);
- });
- });
-});
-
-test('Test blessing store set/get default (callback case)', function(t) {
- vanadium.init(config, function(err, runtime) {
- if (err) {
- t.end(err);
- }
-
- var blessSelfResult;
- var oldDefaultBlessings;
- runtime.principal.blessSelf(runtime.getContext(), 'ext',
- function(err, blessings) {
- if (err) {
- t.error(err);
- runtime.close(t.end);
- return;
- }
- validateBlessings(t, blessings);
- blessSelfResult = blessings;
-
- runtime.principal.blessingStore.getDefault(runtime.getContext(),
- function(err, blessings) {
- if (err) {
- t.error(err);
- runtime.close(t.end);
- return;
- }
- oldDefaultBlessings = blessings;
- validateBlessings(t, oldDefaultBlessings);
-
- runtime.principal.blessingStore.setDefault(runtime.getContext(),
- blessSelfResult, function(err) {
- runtime.principal.blessingStore.getDefault(runtime.getContext(),
- function(err, defaultBlessings) {
- if (err) {
- t.error(err);
- runtime.close(t.end);
- return;
- }
- validateBlessings(t, defaultBlessings);
- t.deepEqual(defaultBlessings, blessSelfResult,
- 'Should get default blessings back');
-
- // Restore original default blessings
- runtime.principal.blessingStore.setDefault(runtime.getContext(),
- oldDefaultBlessings, function(err) {
- t.error(err, 'error setting default');
- runtime.close(t.end);
- });
- });
- });
- });
- });
- });
-});
-
-test('Test blessing store get public key (promise case)', function(t) {
- vanadium.init(config, function(err, runtime) {
- if (err) {
- t.end(err);
- }
-
- runtime.principal.blessingStore.getPublicKey(runtime.getContext())
- .then(function(publicKey) {
- t.ok(publicKey instanceof Uint8Array && publicKey.length > 0,
- 'got public key');
- runtime.close(t.end);
- }).catch(function(err) {
- t.error(err, 'error in getPublicKey()');
- runtime.close(t.end);
- });
- });
-});
-
-test('Test blessing store get public key (callback case)', function(t) {
- vanadium.init(config, function(err, runtime) {
- if (err) {
- t.end(err);
- }
-
- runtime.principal.blessingStore.getPublicKey(runtime.getContext(),
- function(err, publicKey) {
- if (err) {
- t.error(err);
- runtime.close(t.end);
- return;
- }
- t.ok(publicKey instanceof Uint8Array && publicKey.length > 0,
- 'got public key');
- runtime.close(t.end);
- });
- });
-});
-
-test('Test peer blessings (promise case)', function(t) {
- vanadium.init(config, function(err, runtime) {
- if (err) {
- t.end(err);
- }
- runtime.principal.blessSelf(runtime.getContext(), 'ext')
- .then(function(blessings) {
- validateBlessings(t, blessings);
-
- return runtime.principal.blessingStore.set(runtime.getContext(),
- blessings, 'fake:remote:pattern');
- }).then(function() {
- return runtime.principal.blessingStore.getPeerBlessings(
- runtime.getContext());
- }).then(function(peerBlessings) {
- t.ok(peerBlessings instanceof Map, 'Peer blessings is a map');
- t.ok(peerBlessings.size > 0, 'Non-empty peer blessings');
- peerBlessings.forEach(function(blessings, pattern) {
- t.ok(typeof pattern === 'string' && pattern !== '',
- 'got string pattern');
- validateBlessings(t, blessings);
- });
- runtime.close(t.end);
- }).catch(function(err) {
- t.error(err, 'error in getPublicKey()');
- runtime.close(t.end);
- });
- });
-});
-
-test('Test peer blessings (callback case)', function(t) {
- vanadium.init(config, function(err, runtime) {
- if (err) {
- t.end(err);
- }
- runtime.principal.blessSelf(runtime.getContext(), 'ext',
- function(err, blessings) {
- if (err) {
- t.error(err);
- runtime.close(t.end);
- return;
- }
- validateBlessings(t, blessings);
-
- runtime.principal.blessingStore.set(runtime.getContext(),
- blessings, 'fake:remote:pattern', function(err){
- if (err) {
- t.error(err);
- runtime.close(t.end);
- return;
- }
- runtime.principal.blessingStore.getPeerBlessings(runtime.getContext(),
- function(err, peerBlessings) {
- if (err) {
- t.error(err);
- runtime.close(t.end);
- return;
- }
- t.ok(peerBlessings instanceof Map, 'Peer blessings is a map');
- t.ok(peerBlessings.size > 0, 'Non-empty peer blessings');
- peerBlessings.forEach(function(blessings, pattern) {
- t.ok(typeof pattern === 'string' && pattern !== '',
- 'got string pattern');
- validateBlessings(t, blessings);
- });
- runtime.close(t.end);
- });
- });
- });
- });
-});
-
-test('Test blessing store get debug string (promise case)', function(t) {
- vanadium.init(config, function(err, runtime) {
- if (err) {
- t.end(err);
- }
-
- runtime.principal.blessingStore.getDebugString(runtime.getContext())
- .then(function(debugString) {
- t.ok(typeof debugString === 'string' && debugString !== '',
- 'got blessing store debug string');
- runtime.close(t.end);
- }).catch(function(err) {
- t.error(err, 'error in getDebugString()');
- runtime.close(t.end);
- });
- });
-});
-
-test('Test blessing store get debug string (callback case)', function(t) {
- vanadium.init(config, function(err, runtime) {
- if (err) {
- t.end(err);
- }
-
- runtime.principal.blessingStore.getDebugString(runtime.getContext(),
- function(err, debugString) {
- if (err) {
- t.error(err);
- runtime.close(t.end);
- return;
- }
- t.ok(typeof debugString === 'string' && debugString !== '',
- 'got blessing store debug string');
- runtime.close(t.end);
- });
- });
-});
diff --git a/test/integration/test-cancellation.js b/test/integration/test-cancellation.js
deleted file mode 100644
index ec9b9c1..0000000
--- a/test/integration/test-cancellation.js
+++ /dev/null
@@ -1,139 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var vanadium = require('../../');
-var service = require('./get-service');
-var serve = require('./serve');
-var leafDispatcher = require('../../src/rpc/leaf-dispatcher');
-var NO_TIMEOUT = require('../../src/rpc/constants').NO_TIMEOUT;
-var CanceledError = vanadium.verror.CanceledError;
-
-var errorId = new CanceledError(null).id;
-
-function run(ctx, err, collector, end, assert, id, runtime) {
- if (err) {
- return assert.end(err);
- }
-
- var timeout = 60 * 60 * 1000;
- ctx = ctx.withTimeout(timeout);
-
- collector.neverReturn(ctx, id).catch(function(err) {
- if (err.id !== errorId) {
- assert.fail(err);
- }
- });
-
- ctx.waitUntilDone().catch(function(err) {
- assert.ok(err instanceof CanceledError);
- });
- var dctx = runtime.getContext().withTimeout(60000);
- collector.waitForStatus(dctx, id, 'running')
- .then(function(serverTimeout) {
- // Ensure that the server got the timeout we set. We allow up to 10s
- // of network delay.
- if (serverTimeout > timeout || serverTimeout < timeout - 10000) {
- assert.fail('serverTimeout and timeout differ by too much. ' +
- 'serverTimeout: ' + serverTimeout +
- ' timeout: ' + timeout);
- }
-
- // Now cancel the call and check that the server call got cancelled.
- ctx.cancel();
- return collector.waitForStatus(dctx, id, 'cancelled');
- }).then(function(timeout) {
- dctx.finish();
- end(assert);
- }).catch(function(err) {
- dctx.cancel();
- assert.error(err);
- end(assert);
- });
-}
-
-function newDispatcher() {
- return leafDispatcher({
- callInfo: {},
- _processWaiters: function(key) {
- var info = this.callInfo[key];
- if (!info || !info.waiters) {
- return;
- }
- var remaining = [];
- for (var i = 0; i < info.waiters.length; i++) {
- var waiter = info.waiters[i];
- if (waiter.status === info.status) {
- waiter.cb(null, info.timeout);
- } else {
- remaining.push(info);
- }
- }
- info.waiters = remaining;
- },
- _onCancel: function(key, err) {
- var info = this.callInfo[key];
- info.status = 'cancelled';
- this._processWaiters(key);
- info.cb(err);
- },
- neverReturn: function(context, serverCall, key, cb) {
- var info = this.callInfo[key];
- if (!info) {
- info = {};
- this.callInfo[key] = info;
- }
- info.status = 'running';
- info.timeout = NO_TIMEOUT;
- var deadline = context.deadline();
- if (deadline !== null) {
- info.timeout = deadline - Date.now();
- }
- info.cb = cb;
- this._processWaiters(key);
-
- var server = this;
- context.waitUntilDone().catch(function(err) {
- server._onCancel(key, err);
- });
- },
- waitForStatus: function(context, serverCall, key, status, cb) {
- var info = this.callInfo[key];
- if (!info) {
- info = {
- status: 'unknown'
- };
- this.callInfo[key] = info;
- }
- if (status === info.status) {
- cb(null, info.timeout);
- return;
- }
- if (!info.waiters) {
- info.waiters = [];
- }
- info.waiters.push({status: status, cb: cb});
- }
- });
-}
-
-test('Test cancellation from JS client to Go server', function(assert) {
- service('test_service/serviceToCancel', function(err, ctx, collector, end,
- runtime) {
- ctx = ctx.withCancel();
- run(ctx, err, collector, end, assert, 1, runtime);
- });
-});
-
-test('Test cancellation from JS client to JS server', function(assert) {
- serve('testing/serviceToCancel', newDispatcher(), function(err, res) {
- if (err) {
- assert.error(err);
- assert.end();
- return;
- }
- var ctx = res.runtime.getContext();
- run(ctx, err, res.service, res.end, assert, 2, res.runtime);
- });
-});
diff --git a/test/integration/test-caveat-validation.js b/test/integration/test-caveat-validation.js
deleted file mode 100644
index bfa1b27..0000000
--- a/test/integration/test-caveat-validation.js
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var vanadium = require('../../');
-var serve = require('./serve');
-var leafDispatcher = require('../../src/rpc/leaf-dispatcher');
-var testService = require('../vdl-out/v.io/x/js.core/test_service');
-var vdl = vanadium.vdl;
-
-// Service to be invoked
-function AServiceDef() {
- this.aMethod = function(ctx, serverCall) {
- return 'aResult';
- };
-}
-AServiceDef.prototype = new testService.InvokableTestMethod();
-var aService = new AServiceDef();
-
-
-test('caveatValidation', function(t) {
- var invokerName = 'test_service/caveatedInvoker';
- var serveName = 'testing/example';
-
- // Expected data to be passed to the caveat validator.
- var expectedCaveatData = new testService.TestCaveatData({
- a: 'a',
- b: {
- val: 9,
- _wrappedType: true,
- _type: {
- name: 'NamedInt32',
- kind: vdl.kind.INT32
- }
- }
- });
-
- // caveatValidator will validate caveats iff nextCaveatValidationResult
- // is true
- var nextCaveatValidationResult = true;
- function caveatValidator(ctx, call, data) {
- t.deepEqual(data, expectedCaveatData, 'validator receives correct data');
- if (!nextCaveatValidationResult) {
- throw new Error('Intentionally failing caveat validation');
- }
- }
-
- // Serve a service providing aMethod().
- var dispatcher = leafDispatcher(aService);
- serve(serveName, dispatcher, function(err, res) {
- if (err) {
- res.end(t, 'error in serve: ' + err);
- return;
- }
-
- // Register the caveat validator.
- res.runtime.caveatRegistry.register(
- testService.ConditionallyValidatingTestCaveat,
- caveatValidator);
-
- // Bind to the go process that will invoke aMethod.
- var client = res.runtime.getClient();
- client.bindTo(res.runtime.getContext(), invokerName, function(err, stub) {
- if (err) {
- res.end(t, 'error in bindTo: ' + err);
- return;
- }
-
- // Tell the go service to invoke aMethod with a caveat that validates.
- stub.invoke(res.runtime.getContext(), serveName,
- testService.ConditionallyValidatingTestCaveat,
- expectedCaveatData,
- function(err) {
- if (err) {
- res.end(t, 'error in invoke: ' + err);
- return;
- }
-
- // Tell the go service to invoke aMethod with a caveat that fails
- // validation.
- nextCaveatValidationResult = false;
- stub.invoke(res.runtime.getContext(), serveName,
- testService.ConditionallyValidatingTestCaveat,
- expectedCaveatData,
- function(err) {
- if (err) {
- // Expected to fail due to validation.
- nextCaveatValidationResult = true; // reset
- res.end(t);
- return;
- }
- nextCaveatValidationResult = true; // reset*/
- res.end(t, 'expected validation error in invoke');
- });
- });
- });
- });
-});
diff --git a/test/integration/test-client-bind-to.js b/test/integration/test-client-bind-to.js
deleted file mode 100644
index 630f422..0000000
--- a/test/integration/test-client-bind-to.js
+++ /dev/null
@@ -1,134 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var isBrowser = require('is-browser');
-var test = require('prova');
-var vanadium = require('../../');
-var config = require('./default-config');
-
-test('Test binding to a Go service named test_service/cache - ' +
- 'client.bindTo(name, callback)', function(assert) {
- var rt;
-
- vanadium.init(config, oninit);
-
- function oninit(err, runtime) {
- assert.error(err);
-
- rt = runtime;
- var client = rt.getClient();
- var ctx = rt.getContext();
- client.bindTo(ctx, 'test_service/cache', onbind);
- }
-
- function onbind(err, service) {
- assert.error(err);
- assert.ok(service);
-
- rt.close(assert.end);
- }
-});
-
-test('Test binding to a Go service named test_service/cache - ' +
- 'var promise = client.bindTo(name)', function(assert) {
- vanadium
- .init(config)
- .then(bindTo)
- .catch(assert.end);
-
- function bindTo(runtime) {
- var ctx = runtime.getContext();
- return runtime.getClient()
- .bindTo(ctx, 'test_service/cache')
- .then(function(service) {
- assert.ok(service);
- runtime.close(assert.end);
- });
- }
-});
-
-test('Test binding to a non-existing name - ' +
- 'client.bindTo(badName, callback)', function(assert) {
- vanadium.init(config, function(err, runtime) {
- assert.error(err);
-
- var client = runtime.getClient();
- var ctx = runtime.getContext().withTimeout(100);
- client.bindTo(ctx, 'does-not/exist', function(err, service) {
- assert.ok(err instanceof Error);
-
- runtime.close(assert.end);
- });
- });
-});
-
-test('Test binding to a non-existing name - ' +
- 'var promise = client.bindTo(badName) ', function(assert) {
- var rt;
-
- vanadium
- .init(config)
- .then(function(runtime) {
- rt = runtime;
- var client = rt.getClient();
- var ctx = runtime.getContext().withTimeout(100);
- return client.bindTo(ctx, 'does-not/exist');
- })
- .then(function(service) {
- assert.fail('should not succeed');
- rt.close(assert.end);
- }, function(err) {
- assert.ok(err instanceof Error);
- rt.close(assert.end);
- })
- .catch(function(err) {
- assert.error(err);
- rt.close(assert.end);
- });
-});
-
-test('Test using the proxy when proxy Url is invalid - ' +
- 'client.bindTo(name, callback)', function(assert) {
- if (isBrowser) {
- return assert.end();
- }
-
- vanadium.init({ wspr: 'http://bad-address.tld' }, onruntime);
-
- function onruntime(err, runtime) {
- assert.notOk(err);
- var client = runtime.getClient();
- client.bindTo(runtime.getContext(), 'test_service/cache', function(err) {
- assert.ok(err instanceof Error);
- runtime.close();
- assert.end();
- });
- }
-});
-
-test('Test binding when wspr Url is invalid - ' +
- 'var promise = client.bindTo(name) ', function(assert) {
- if (isBrowser) {
- return assert.end();
- }
-
- var rt;
- vanadium
- .init({ wspr: 'http://bad-address.tld' })
- .catch(function(err) {
- assert.notOk(err);
- assert.end();
- }).then(function(runtime) {
- rt = runtime;
- var client = rt.getClient();
- return client.bindTo(runtime.getContext(), 'test_service/cache');
- }).then(function() {
- rt.close();
- assert.end('Bind should fail');
- }).catch(function(err) {
- assert.ok(err instanceof Error);
- rt.close();
- assert.end();
- });
-});
diff --git a/test/integration/test-client-call-opts.js b/test/integration/test-client-call-opts.js
deleted file mode 100644
index 6414cc8..0000000
--- a/test/integration/test-client-call-opts.js
+++ /dev/null
@@ -1,115 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var vanadium = require('../../');
-var config = require('./default-config');
-var verror = vanadium.verror;
-
-function end(t, rt, err) {
- t.error(err);
- rt.close(t.end);
-}
-
-test('Test passing valid options to client.callOption()', function(t) {
- vanadium.init(config, function(err, rt) {
- if (err) {
- return t.end(err);
- }
-
- var client = rt.getClient();
-
- var opts = client.callOption({ });
- t.ok(opts, 'with no options should succeed');
-
- opts = client.callOption({
- allowedServersPolicy: ['foo']
- });
- t.ok(opts, 'with allowedOptions should succeed');
-
- end(t, rt);
- });
-});
-
-test('Test passing invalid options to client.callOption()', function(t) {
- vanadium.init(config, function(err, rt) {
- if (err) {
- return t.end(err);
- }
-
- var client = rt.getClient();
-
- t.throws(function() {
- client.callOption({
- invalid: 'key'
- });
- },
- verror.BadArgError,
- ' with one invalid option should throw BadArgError');
-
- t.throws(function() {
- client.callOption({
- allowedServersPolicy: ['foo'],
- 'invalid': 'key'
- });
- },
- verror.BadArgError,
- 'with one valid and one invalid option should throw BadArgError');
-
- end(t, rt);
- });
-});
-
-test('Test passing allowedServersPolicy that matches server blessings',
- function(t) {
- vanadium.init(config, function(err, rt) {
- if (err) {
- return t.end(err);
- }
-
- var ctx = rt.getContext();
- var client = rt.getClient();
-
- client.bindTo(ctx, 'test_service/cache', function(err, cache) {
- if (err) {
- return end(t, rt, err);
- }
-
- var callOpt = client.callOption({
- allowedServersPolicy: ['test']
- });
-
- cache.set(ctx, 'foo', 'bar', callOpt, function(err) {
- end(t, rt, err);
- });
- });
- });
-});
-
-test('Test passing allowedServersPolicy that does not match server blessings',
- function(t) {
- vanadium.init(config, function(err, rt) {
- if (err) {
- return t.end(err);
- }
-
- var ctx = rt.getContext();
- var client = rt.getClient();
-
- client.bindTo(ctx, 'test_service/cache', function(err, cache) {
- if (err) {
- return end(t, rt, err);
- }
-
- var callOpt = client.callOption({
- allowedServersPolicy: ['bad/blessings']
- });
-
- cache.set(ctx, 'foo', 'bar', callOpt, function(err) {
- t.ok(err, 'should error');
- end(t, rt);
- });
- });
- });
-});
diff --git a/test/integration/test-dispatcher.js b/test/integration/test-dispatcher.js
deleted file mode 100644
index 3aecb05..0000000
--- a/test/integration/test-dispatcher.js
+++ /dev/null
@@ -1,294 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var serve = require('./serve');
-var Promise = require('../../src/lib/promise');
-
-test('Test sync dispatcher the echos suffixes - ' +
- 'dispatcher/echo/<suffix>', function(assert) {
- serve({
- name: 'dispatcherServiceName',
- dispatcher: callbackDispatcher,
- autoBind: false
- }, function(err, res) {
- if (err) {
- return assert.end(err);
- }
-
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
- client.bindTo(ctx, 'dispatcherServiceName/echo/bar',
- function(err, service) {
- if (err) {
- assert.error(err);
- res.end(assert);
- return;
- }
-
- service.echo(ctx, function(err, result) {
- assert.error(err);
-
- assert.equal(result, 'bar');
- res.end(assert);
- });
- });
- });
-});
-
-test('Test sync dispatcher that counts length of suffix - ' +
- 'dispatcherServiceName/count/<suffix> - one suffix', function(assert) {
- serve({
- name: 'dispatcherServiceName',
- dispatcher: promiseDispatcher,
- autoBind: false
- }, function(err, res) {
- if (err) {
- return assert.end(err);
- }
-
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
- client.bindTo(ctx, 'dispatcherServiceName/count/bar',
- function(err, service) {
- if (err) {
- return assert.end(err);
- }
-
- service.count(ctx, function(err, result) {
- assert.error(err);
-
- assert.equal(result, 3);
- res.end(assert);
- });
- });
- });
-});
-
-test('Test sync dispatcher that counts length of suffix - ' +
- 'dispatcherServiceName/count/<suffix> - two different suffixes',
- function(assert) {
- serve({
- name: 'dispatcherServiceName',
- dispatcher: promiseDispatcher,
- autoBind: false
- }, function(err, res) {
- if (err) {
- return assert.end(err);
- }
-
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
- var promises = [
- client.bindTo(ctx, 'dispatcherServiceName/count/bar')
- .then(function(client) {
- return client.count(ctx);
- }),
- client.bindTo(ctx, 'dispatcherServiceName/count/longer')
- .then(function(client) {
- return client.count(ctx);
- })
- ];
-
- Promise.all(promises).then(function(results) {
- assert.equal(results[0], 3);
- assert.equal(results[1], 6);
- res.end(assert);
- })
- .catch(function(err) {
- assert.error(err);
- res.end(assert);
- });
- });
-});
-
-test('Test unknown suffix should return error - ' +
- 'dispatcherServiceName/unknown', function(assert) {
- serve({
- name: 'dispatcherServiceName',
- dispatcher: callbackDispatcher,
- autoBind: false
- }, function(err, res) {
- if (err) {
- return assert.end(err);
- }
-
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
- client.bindTo(ctx, 'dispatcherServiceName/unknown',
- function(err, service) {
- assert.ok(err, 'should fail');
- res.end(assert);
- });
- });
-});
-
-test('Test async dispatcher using promises - ' +
- 'dispatcher/promise ' +
- '- success case', function(assert) {
- serve({
- name: 'dispatcherServiceName',
- dispatcher: promiseDispatcher,
- autoBind: false
- }, function(err, res) {
- if (err) {
- return assert.end(err);
- }
-
- var ctx = res.runtime.getContext();
- var name = 'dispatcherServiceName/promise/whatever';
- var client = res.runtime.getClient();
- client.bindTo(ctx, name, function(err, service) {
- if (err) {
- return assert.end(err);
- }
-
- service.echo(ctx, function(err, result) {
- assert.error(err);
- assert.equal(result, 'promise/whatever');
- res.end(assert);
- });
- });
- });
-});
-
-test('Test async dispatcher using promises - ' +
- 'dispatcherServiceName/promise/fail ' +
- '- failure case', function(assert) {
- serve({
- name: 'dispatcherServiceName',
- dispatcher: promiseDispatcher,
- autoBind: false
- }, function(err, res) {
- if (err) {
- return assert.end(err);
- }
-
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
- client.bindTo(ctx, 'dispatcherServiceName/promise/fail',
- function(err, service) {
- assert.ok(err, 'should fail');
- res.end(assert);
- });
- });
-});
-
-test('Test async dispatcher using callbacks - ' +
- 'dispatcherServiceName/callback ' +
- '- success case', function(assert) {
- serve({
- name: 'dispatcherServiceName',
- dispatcher: callbackDispatcher,
- autoBind: false
- }, function(err, res) {
- if (err) {
- return assert.end(err);
- }
-
- var ctx = res.runtime.getContext();
-
- var name = 'dispatcherServiceName/callback/whatever';
- var client = res.runtime.getClient();
- client.bindTo(ctx, name, function(err, service) {
- if (err) {
- return assert.end(err);
- }
-
- service.echo(ctx, function(err, result) {
- assert.error(err);
- assert.equal(result, 'callback/whatever');
- res.end(assert);
- });
- });
- });
-});
-
-test('Test async dispatcher using callbacks - '+
- 'dispatcherServiceName/callback/fail ' +
- '- failure case', function(assert) {
- serve({
- name: 'dispatcherServiceName',
- dispatcher: callbackDispatcher,
- autoBind: false
- }, function(err, res) {
- if (err) {
- return assert.end(err);
- }
-
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
- client.bindTo(ctx, 'dispatcherServiceName/callback/fail',
- function(err, service) {
- assert.ok(err, 'should fail');
- res.end(assert);
- });
- });
-});
-
-function Counter(string) {
- this.string = string;
-}
-
-Counter.prototype.count = function(ctx, serverCall) {
- return this.string.length;
-};
-
-function Echoer(string) {
- this.string = string;
-}
-
-Echoer.prototype.echo = function(ctx, serverCall) {
- return this.string;
-};
-
-function promiseDispatcher(suffix) {
- // dispatcher/echo/:string
- if (suffix.indexOf('echo/') === 0) {
- return {
- service: new Echoer(suffix.substr(5))
- };
- // dispatcher/count/:string
- } else if (suffix.indexOf('count/') === 0) {
- return {
- service: new Counter(suffix.substr(6))
- };
- // dispatcher/promise/fail
- } else if (suffix.indexOf('promise/fail') === 0) {
- return Promise.reject(new Error('bad'));
- // dispatcher/promise/:string
- } else if (suffix.indexOf('promise') === 0) {
- return Promise.resolve({
- service: new Echoer(suffix)
- });
- }
-
- throw new Error('unknown suffix');
-}
-
-function callbackDispatcher(suffix, cb) {
- // dispatcher/echo/:string
- if (suffix.indexOf('echo/') === 0) {
- cb(null, {
- service: new Echoer(suffix.substr(5))
- });
- return;
- // dispatcher/count/:string
- } else if (suffix.indexOf('count/') === 0) {
- cb(null, {
- service: new Counter(suffix.substr(6))
- });
- return;
- // dispatcher/callback/fail
- } else if (suffix.indexOf('callback/fail') === 0) {
- cb(new Error('errorback'));
- return;
- // dispatcher/callback/:string
- } else if (suffix.indexOf('callback') === 0) {
- cb(null, { service: new Echoer(suffix)});
- return;
- }
-
- throw new Error('unknown suffix');
-}
diff --git a/test/integration/test-extension-event-proxy.js b/test/integration/test-extension-event-proxy.js
deleted file mode 100644
index e240e8d..0000000
--- a/test/integration/test-extension-event-proxy.js
+++ /dev/null
@@ -1,98 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-
-test('Test event proxy connects to extension', function(assert) {
- // Don't test this in node because there is no extension to talk to.
- if (!require('is-browser')) {
- return assert.end();
- }
-
- var timeout = 500;
- var ExtensionEventProxy = require('../../src/browser/event-proxy').ctor;
- var extensionEventProxy = new ExtensionEventProxy(timeout);
-
- var finished = false;
-
- extensionEventProxy.once('error', function(err) {
- if (!finished) {
- finished = true;
- assert.fail(err);
- extensionEventProxy.destroy();
- assert.end();
- }
- });
-
- extensionEventProxy.once('connected', function() {
- if (!finished) {
- finished = true;
- extensionEventProxy.destroy();
- assert.end();
- }
- });
-});
-
-// TODO(nlacasse): This test is potentially racey. It's possible that the
-// event proxy might connect to the extension before the 0ms timeout fires
-// (although I have not seen it happen).
-test('Test event proxy fires error when timeout occurs before connection.',
- function(assert) {
- // Don't test this in node because there is no extension to talk to.
- if (!require('is-browser')) {
- return assert.end();
- }
-
- var timeout = 0;
- var ExtensionEventProxy = require('../../src/browser/event-proxy').ctor;
- var extensionEventProxy = new ExtensionEventProxy(timeout);
-
- var finished = false;
-
- extensionEventProxy.once('error', function(err) {
- if (!finished) {
- finished = true;
- assert.ok((/timeout/i).test(err.message));
- extensionEventProxy.destroy();
- assert.end();
- }
- });
-
- extensionEventProxy.once('connected', function() {
- if (!finished) {
- finished = true;
- assert.fail('Expected the event proxy to timeout, but it did not.');
- extensionEventProxy.destroy();
- assert.end();
- }
- });
-});
-
-test('Test event proxy rejects unknown message types', function(assert) {
- // Don't test this in node because there is no extension to talk to.
- if (!require('is-browser')) {
- return assert.end();
- }
-
- var timeout = 500;
- var ExtensionEventProxy = require('../../src/browser/event-proxy').ctor;
- var extensionEventProxy = new ExtensionEventProxy(timeout);
-
- var finished = false;
-
- var bogusType = 'foobar';
-
- extensionEventProxy.once('connected', function() {
- extensionEventProxy.once('error', function(err) {
- if (!finished) {
- finished = true;
- assert.ok((/unknown type/i).test(err.message));
- extensionEventProxy.destroy();
- assert.end();
- }
- });
-
- extensionEventProxy.send(bogusType, {});
- });
-});
diff --git a/test/integration/test-js-client-server.js b/test/integration/test-js-client-server.js
deleted file mode 100644
index 7866b17..0000000
--- a/test/integration/test-js-client-server.js
+++ /dev/null
@@ -1,1092 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var vanadium = require('../../');
-var serve = require('./serve');
-var leafDispatcher = require('../../src/rpc/leaf-dispatcher');
-var Deferred = require('../../src/lib/deferred');
-
-var builtins = require('../../src/vdl/builtins');
-var stringify = require('../../src/vdl/stringify');
-var TypeUtil = require('../../src/vdl/type-util');
-var typeServiceVdl =
- require('../vdl-out/javascript-test/services/type-service');
-var typedStreamingServiceVdl =
- require('../vdl-out/javascript-test/services/typed-streaming-service');
-
-var vdl = vanadium.vdl;
-
-// TODO(bprosnitz) Combine CacheService and CacheServicePromises so there
-// isn't as much duplicated code.
-
-var CacheService = {
- cacheMap: {},
- set: function(context, serverCall, key, value, cb) {
- this.cacheMap[key] = value;
-
- process.nextTick(function() {
- cb(null, undefined);
- });
- },
- get: function(context, serverCall, key, cb) {
- var val = this.cacheMap[key];
- if (val === undefined) {
- var message = 'unknown key ' + JSON.stringify(key);
- var err = new Error(message);
-
- process.nextTick(function() {
- cb(err);
- });
- } else {
- process.nextTick(function() {
- cb(undefined, val);
- });
- }
- } ,
- // TODO(bprosnitz) Also test streaming with no return arg.
- multiGet: function(context, serverCall, $stream, cb) {
- var numReceived = 0;
- $stream.on('end', function close() {
- cb(null, numReceived);
- });
- $stream.on('error', function error(e) {
- cb(e);
- });
- var self = this;
- $stream.on('data', function(key) {
- numReceived++;
- if (key !== null) {
- var val = self.cacheMap[key];
- if (val === undefined) {
- cb(new Error('unknown key'));
- }
- $stream.write(val);
- }
- });
- $stream.read();
- },
- doNothingStream: function(ctx, serverCall, $stream, cb) {
- cb(null, undefined);
- },
- nonAsyncFunction: function(ctx, serverCall, cb) {
- cb(null, 'RESULT');
- }
-};
-
-var CacheServicePromises = {
- cacheMap: {},
- set: function(context, serverCall, key, value) {
- this.cacheMap[key] = value;
- },
- get: function(context, serverCall, key) {
- var def = new Deferred();
- var val = this.cacheMap[key];
- process.nextTick(function() {
- if (val === undefined) {
- // Since we're rejecting the promise before we've returned it
- // we'll register a catch handler now to avoid an unhandled rejection
- // warning.
- def.promise.catch(function() {});
- def.reject('unknown key');
- } else {
- def.resolve(val);
- }
- });
- return def.promise;
- } ,
- multiGet: function(context, serverCall, $stream) {
- var numReceived = 0;
- var def = new Deferred();
- $stream.on('end', function() {
- def.resolve(numReceived);
- });
-
- $stream.on('error', function(e) {
- def.reject(e);
- });
- var self = this;
- $stream.on('data', function(key) {
- numReceived++;
- if (key !== null) {
- var val = self.cacheMap[key];
- if (val === undefined) {
- def.reject('unknown key');
- }
- $stream.write(val);
- }
- });
- $stream.read();
- return def.promise;
- },
- doNothingStream: function(ctx, serverCall, $stream) {
- },
- nonAsyncFunction: function(ctx, serverCall) {
- return 'RESULT';
- }
-};
-
-runCache({
- testName: 'without VDL (JSValue) using callbacks',
- definition: CacheService,
- name: 'foo.Cache'
-});
-
-runCache({
- testName: 'without VDL (JSValue) using promises',
- definition: CacheServicePromises,
- name: 'foo.Cache'
-});
-
-// options: testName, definition, name
-function runCache(options) {
- var namePrefix = 'Test JS client/server rpc ' + options.testName + ' - ';
-
- test(namePrefix + 'cache.set(key, string) -> cache.get(key)',
- function(t) {
- setup(options, function(err, ctx, cache, end) {
- t.error(err, 'should not error on setup');
-
- cache.set(ctx, 'foo', 'bar', function(err, res) {
- t.error(err, 'should not error on set(...)');
- t.notOk(res, 'should be null');
-
- cache.get(ctx, 'foo', function(err, res) {
- t.error(err, 'should not error on get(...)');
- t.equal(res, 'bar');
- end(t);
- });
- });
- });
- });
-
- test(namePrefix + 'cache.set(key, object, callback)', function(t) {
- setup(options, function(err, ctx, cache, end) {
- t.error(err, 'should not error on setup');
-
- // Expect a map as the JSValue.
- var expected = new Map([['a', 'foo'], ['b', 2]]);
-
- cache.set(ctx, 'myObject', expected, function(err, res) {
- t.error(err, 'should not error on set(...)');
- t.equal(res, null, 'should be null');
-
- cache.get(ctx, 'myObject', function(err, res) {
- t.error(err, 'should not error on get(...)');
- t.deepEqual(res, expected, 'should match object');
- end(t);
- });
- });
- });
- });
-
- test(namePrefix + 'cache.get("bad-key", callback) - failure',
- function(t) {
- setup(options, function(err, ctx, cache, end) {
- t.error(err, 'should not error on setup');
-
- cache.get(ctx, 'bad-key', function(err, res) {
- t.ok(err, 'should err on get(...)');
- // TODO(bjornick): Use the constant generated by the vdl generator.
- t.equal(err.id, 'v.io/v23/verror.Unknown');
- end(t);
- });
- });
- });
-
- test(namePrefix + 'cache.badMethod() - failure', function(t) {
- setup(options, function(err, ctx, cache, end) {
- t.error(err, 'should not error on setup');
-
- t.throws(function() {
- cache.badMethod();
- });
-
- end(t);
- });
- });
-
- test(namePrefix + 'cache.multiGet()', function(t) {
- // `cache.multiGet()` returns an object that has a "stream" attribute.
- // The way the streaming interface is implmented for cache.multiGet()
- // is that you use stream.write(key) to get the value of a key. The value
- // is emitted on the stream's data event. In this test there are a few
- // steps to set this up:
- //
- // 1. Prime the cache by setting a bunch of key/values
- // 2. Add a listener or create a stream reader to receive the values
- // 3. Assert the values are correct
- // 4. End the stream.
- setup(options, function(err, ctx, cache, end){
- // 1. Prime the cache by setting a bunch of key/values
-
- // Build a map of items
- var items = {};
- var numItems = 3;
-
- for (var i = 0; i < numItems; ++i) {
- items[i] = {
- key: i,
- value: 'value: ' + i
- };
- }
-
- // Add them to the cache
- var jobs = Object.keys(items).map(function(key) {
- return cache.set(ctx, key, JSON.stringify(items[key]));
- });
-
- Promise
- .all(jobs)
- .then(function() {
- // 2. Add a listener or create a stream reader to receive the values
- var promise = cache.multiGet(ctx);
- var stream = promise.stream;
- var writes = 0;
- var reads = 0;
-
- // Error handling boilerplate
- promise.then(function(numReceived) {
- t.equal(numReceived, numItems, 'received correct number of items');
- t.equal(reads, numItems, 'had correct number of reads');
- t.equal(writes, numItems, 'has correct number of writes');
- end(t);
- }).catch(error);
-
- stream.on('error', error);
-
- // 3. Assert the values are correct
- // stream "data" event emits cached values
- stream.on('data', function(value) {
- var string = value.toString();
- var json = JSON.parse(string);
- var actual = json.value;
- var expected = items[json.key].value;
-
- t.equal(actual, expected);
-
- reads++;
- });
-
- Object.keys(items).forEach(function(key) {
- stream.write(key);
-
- writes++;
- });
-
- // 4. End the stream.
- stream.end();
- });
-
- function error(err) {
- t.error(err, 'should not error');
- end(t);
- }
- });
- });
-
- function setup(options, cb) {
- var dispatcher = leafDispatcher(options.definition);
- serve('testing/cache', dispatcher, function(err, res) {
- cb(err, res.runtime.getContext(), res.service, res.end);
- });
- }
-}
-
-function TypeService() {}
-TypeService.prototype = new typeServiceVdl.TypeService();
-
-TypeService.prototype.isTyped = function(context, serverCall, any) {
- // We expect to receive the internally typed value of the any.
- // However, clients who send JSValue will not produce a typed value here.
- return TypeUtil.isTyped(any);
-};
-TypeService.prototype.isString = function(context, serverCall, str) {
- // We expect to receive a native string, if the client sent us one.
- return (typeof str === 'string');
-};
-TypeService.prototype.isStruct = function(context, serverCall, struct) {
- // A struct should always be typed.
- if (TypeUtil.isTyped(struct)) {
- return;
- }
- // If it was untyped (a JSValue object), then the code is incorrect.
- throw new Error('did not receive a typed struct' + stringify(struct));
-};
-TypeService.prototype.swap = function(context, serverCall, a, b) {
- return [b, a];
-};
-
-runTypeService({
- testName: 'typed, non-async',
- definition: new TypeService(),
- name: 'foo.TypeService'
-});
-
-// options: testName, definition, name
-function runTypeService(options) {
- var namePrefix = 'Test JS client/server rpc ' + options.testName + ' - ';
- // This test ensures that typed values are sent between JS server and client.
- // The server expects an input of the ANY type, which means that it ought to
- // receive a typed value, if we send a typed value.
- // If we send a JSValue, then it will not end up being wrapped.
- test(namePrefix + 'typeService.isTyped(...)', function(t) {
- setup(options, function(err, ctx, typeService, end) {
- t.error(err, 'should not error on setup');
-
- typeService.isTyped(ctx, 'foo', function(err, res) {
- t.error(err, 'should not error on isTyped(...)');
- // Use equal instead of notOk to ensure that res is not wrapped.
- t.equal(res, false, '\'foo\' is an untyped string');
-
-
- var VomStr = vdl.registry.lookupOrCreateConstructor(vdl.types.STRING);
- var typedString = new VomStr('food');
- typeService.isTyped(ctx, typedString, function(err, res) {
- t.error(err, 'should not error on isTyped(...)');
- // Use equal instead of ok to ensure that res is not wrapped.
- t.equal(res, true, 'VomStr(\'food\') is a typed string');
- end(t);
- });
- });
- });
- });
-
- test(namePrefix + 'typeService.isTyped(...) - promise', function(t) {
- setup(options, function(err, ctx, typeService, end) {
- t.error(err, 'should not error on setup');
-
- typeService.isTyped(ctx, 'glue').then(function(res) {
- t.error(err, 'should not error on isTyped(...)');
- // Use equal instead of notOk to ensure that res is not wrapped.
- t.equal(res, false, '\'glue\' is an untyped string');
-
- var VomStr = vdl.registry.lookupOrCreateConstructor(vdl.types.STRING);
- var typedString = new VomStr('glued');
- typeService.isTyped(ctx, typedString, function(err, res) {
- t.error(err, 'should not error on isTyped(...)');
- // Use equal instead of ok to ensure that res is not wrapped.
- t.equal(res, true, 'VomStr(\'glued\') is a typed string');
- end(t);
- });
- }).catch(function error(err) {
- t.error(err, 'should not error');
- end(t);
- });
- });
- });
-
- test(namePrefix + 'typeService.isTyped(undefined) - promise', function(t) {
- setup(options, function(err, ctx, typeService, end) {
- t.error(err, 'should not error on setup');
-
- // Check that you can leave an optional (or any) inArg as undefined.
- // It should not be mistaken for a callback.
- typeService.isTyped(ctx, undefined).then(function(res) {
- t.error(err, 'should not error on isTyped(undefined)');
- t.equal(res, false, 'undefined is treated like JSValue null');
-
- // Lenient: Having both arg and cb as undefined is fine too.
- typeService.isTyped(ctx, undefined, undefined).then(function(res) {
- t.error(err, 'should not error on isTyped(undefined, undefined)');
- t.equal(res, false, 'undefined is treated like JSValue null');
-
- // Having any more undefined's is an error (too many args).
- typeService.isTyped(ctx, undefined, undefined, undefined).then(
- function(res) {
-
- t.fail(err, 'should have errored');
- end(t);
- }).catch(function(err) {
- t.ok(err, 'should error');
- end(t);
- });
- });
- }).catch(function error(err) {
- t.error(err, 'should not error');
- end(t);
- });
- });
- });
-
- // This test ensures that typed values sent between JS server and client are
- // unwrapped when being processed. Further, the client disallows sending the
- // wrong type to the server.
- test(namePrefix + 'typeService.isString(str)', function(t) {
- setup(options, function(err, ctx, typeService, end) {
- t.error(err, 'should not error on setup');
-
- typeService.isString(ctx, 'foo', function(err, res) {
- t.error(err, 'should not error on isString(<a string>)');
- // Use equal instead of ok to ensure that res is not wrapped.
- t.equal(res, true, '\'foo\' is a string');
-
- typeService.isString(ctx, 0, function(err, res) {
- t.ok(err, 'should error on isString(<not a string>)');
- end(t);
- });
- });
- });
- });
-
- // This test ensures that a typed struct has its type on the other side.
- // That would prove that it was not decoded as a JSValue.
- test(namePrefix + 'typeService.isStruct(struct)', function(t) {
- setup(options, function(err, ctx, typeService, end) {
- t.error(err, 'should not error on setup');
-
- typeService.isStruct(ctx, {}, function(err, res) {
- t.error(err, 'should not error on isStruct(...)');
- end(t);
- });
- });
- });
-
- // This test ensures that multiple typed I/O arguments are possible in JS.
- test(namePrefix + 'typeService.swap(a, b)', function(t) {
- setup(options, function(err, ctx, typeService, end) {
- t.error(err, 'should not error on setup');
-
- // Start by swapping JSValue. There are no types attached when returned.
- var a = '33';
- var b = 33;
- typeService.swap(ctx, a, b, function(err, res1, res2) {
- t.error(err, 'should not error on swap(...)');
- t.deepEqual([res1, res2], [b, a], 'correctly swapped the 2 inputs');
-
- // Now, swap a typed value (aa) with a wrapped and typed value (bb).
- var simpleType = {
- name: 'SimpleStruct',
- kind: vdl.kind.STRUCT,
- fields: [
- {
- name: 'Foo',
- type: vdl.types.INT32
- },
- {
- name: 'Bar',
- type: vdl.types.BOOL
- }
- ]
- };
- var SimpleStruct = vdl.registry.lookupOrCreateConstructor(simpleType);
- var aa = new SimpleStruct({
- foo: 10,
- bar: true
- });
- var simpleTypeB = vdl.types.INT32;
- var SimpleInt32 = vdl.registry.lookupOrCreateConstructor(simpleTypeB);
- var bb = new SimpleInt32(-32);
- typeService.swap(ctx, aa, bb, function(err, res1, res2) {
- t.error(err, 'should not error on swap(...)');
- t.deepEqual([res1, res2], [bb, aa], 'correctly swapped the 2 inputs');
-
- // Verify that res2 (the original aa) still has the right type.
- t.ok(TypeUtil.isTyped(res2), 'aa is still typed');
- t.deepEqual(res2._type, simpleType, 'aa has the correct type');
-
- // Verify that res1 (the original bb) still has the right type.
- t.ok(TypeUtil.isTyped(res1), 'bb is still typed');
- t.deepEqual(res1._type, simpleTypeB, 'bb has the correct type');
-
- end(t);
- });
- });
- });
- });
-
- function setup(options, cb) {
- var dispatcher = leafDispatcher(options.definition);
-
- serve('testing/typeService', dispatcher, function(err, res) {
- cb(err, res.runtime.getContext(), res.service, res.end);
- });
- }
-}
-
-var boolListType = typedStreamingServiceVdl.BoolList.prototype._type;
-var numStructType = typedStreamingServiceVdl.NumStruct.prototype._type;
-var typeListType = typedStreamingServiceVdl.TypeList.prototype._type;
-
-// TODO(alexfandrianto): Add a callback version of the typed streaming service.
-// See each test case for what the service method tests.
-function TypedStreamingService() {}
-TypedStreamingService.prototype =
- new typedStreamingServiceVdl.TypedStreamingService();
-
-// inStreamOnly verifies that typed inStreams work properly.
-TypedStreamingService.prototype.inStreamOnly =
- function(ctx, serverCall, numTimes, $stream) {
-
- // Receive stream values numTimes
- var numReceived = 0;
- var def = new Deferred();
- $stream.on('end', function() {
- if (numReceived !== numTimes) {
- var err = new Error('Got ' + numReceived + '. Wanted ' + numTimes);
- def.reject(err);
- }
- def.resolve(numReceived);
- });
-
- $stream.on('error', function(e) {
- def.reject(e);
- });
- $stream.on('data', function(str) {
- if (typeof str !== 'string') {
- def.reject(new Error('Expected a string, but got ' + str));
- }
- numReceived++;
- });
- $stream.read();
- $stream.write('No outstream type; this cannot be sent');
- return def.promise;
-};
-
-// outStreamOnly verifies that typed outStreams work properly.
-TypedStreamingService.prototype.outStreamOnly =
- function(ctx, serverCall, numTimes, $stream, cb) {
-
- // Send stream values numTimes
- var numSent = 0;
- while (numSent < numTimes) {
- $stream.write(numSent); // Despite sending int, we autoconvert to BigInt.
- numSent++;
- }
- return cb(null, numSent);
-};
-
-// bidirBoolListNegationsStream tests that bidirectional streams can send
-// composite types back and forth, as well as modify the data items streamed.
-TypedStreamingService.prototype.bidirBoolListNegationStream =
- function(ctx, serverCall, $stream) {
-
- // Given a list of bool, send the opposite bools back.
- var numReceived = 0;
- var def = new Deferred();
- $stream.on('end', function() {
- def.resolve(numReceived);
- });
-
- $stream.on('error', function(e) {
- def.reject(e);
- });
- $stream.on('data', function(boolList) {
- numReceived++;
- var oppList = boolList.map(function(b) {
- return !b;
- });
- $stream.write(oppList);
- });
- $stream.read();
- return def.promise;
-};
-
-// structValueStream converts a number to a struct based on that number.
-// Ensures that custom-defined types can be sent across the stream.
-TypedStreamingService.prototype.structValueStream =
- function(ctx, serverCall, $stream) {
-
- // Given a number, send a number struct back.
- var numReceived = 0;
- var def = new Deferred();
- $stream.on('end', function() {
- def.resolve(numReceived);
- });
- $stream.on('error', function(e) {
- def.reject(e);
- });
- $stream.on('data', function(num) {
- numReceived++;
- $stream.write({
- 'number': num,
- 'bigInt': vdl.BigInt.fromNativeNumber(num),
- 'string': '' + num
- });
- });
- $stream.read();
- return def.promise;
-};
-
-// anyStream tests that typed values can pass through a bidirectional stream.
-TypedStreamingService.prototype.anyStream =
- function(ctx, serverCall, types, $stream) {
-
- // Given a list of types, listen to a stream of values.
- // Errors if any of the values received did not match their expected type.
- // Stream those values back directly.
- var typesReceived = [];
- var def = new Deferred();
- $stream.on('end', function() {
- def.resolve(typesReceived);
- });
- $stream.on('error', function(e) {
- def.reject(e);
- });
- $stream.on('data', function(val) {
- // Verify that the value has no type if native, or matches, otherwise.
- var expectedType = types[typesReceived.length];
- if (expectedType.equals(vdl.types.JSVALUE) && val._type !== undefined) {
- def.reject(new Error('Native value had a type: ' +
- JSON.stringify(val)));
- }
- if (!expectedType.equals(vdl.types.JSVALUE) &&
- !expectedType.equals(val._type)) {
- def.reject(new Error('Value had wrong type: ' +
- JSON.stringify(val)));
- }
-
- // The value had the corerct type. Write the same value back.
- // Note: Native values lack types, so use the JSValue type instead.
- typesReceived.push(val._type || vdl.types.JSVALUE);
- $stream.write(val);
- });
- $stream.read();
- return def.promise;
-};
-
-runTypedStreamingService({
- testName: 'typed, streaming, non-async',
- definition: new TypedStreamingService(),
- name: 'foo.TypedStreamingService'
-});
-
-// options: testName, definition, name
-function runTypedStreamingService(options) {
- var namePrefix = 'Test JS client/server rpc ' + options.testName + ' - ';
-
- // typedStreamingService.inStreamOnly tests:
- // - correct # of values sent to server
- // - values received by server have correct type
- // - outStream is null
- // - client never gets data, even though server tries to send on outStream
- test(namePrefix + 'typedStreamingService.inStreamOnly(...)',
- function(t) {
-
- setup(options, function(err, ctx, typedStreamingService, end) {
- t.error(err, 'should not error on setup');
-
- // The # of strings we intend to send.
- var strList = ['asdf', ';lkj', 'qwer', 'poiu'];
- var numStrs = strList.length;
-
- // Prepare and run the stream test.
- var testdata = {
- inArg: numStrs,
- inData: strList,
- serviceMethod: typedStreamingService.inStreamOnly,
- writeType: vdl.types.STRING,
- readType: null,
- onResolveFunc: function(numReceived) {
- t.equal(numReceived, numStrs,
- 'service received correct # of strings');
- end(t);
- },
- onDataFunc: function(value, dataIndex) {
- t.fail('received data from the stream: ' + JSON.stringify(value));
- }
- };
- streamTest(t, ctx, testdata, end);
- });
- });
-
- // This test verifies that the stream promise rejects normally.
- // We send 4 items, but we claim to the server that we will send 6.
- // Note: the stream also passes the same reject error to the error stream.
- test(namePrefix + 'typedStreamingService.inStreamOnly(...) - failure',
- function(t) {
-
- setup(options, function(err, ctx, typedStreamingService, end) {
- t.error(err, 'should not error on setup');
-
- // The # of strings we intend to send.
- var strList = ['asdf', ';lkj', 'qwer', 'poiu'];
- var numStrs = strList.length + 2; // mismatch
-
- // The stream will send an error on the error stream just before the
- // Promise rejects.
- var onErrorFunc = function(err) {
- t.ok(err, 'should error');
- t.ok(err.message.indexOf('Got 4. Wanted 6') !== -1,
- 'has correct error message');
- };
-
- // Prepare and run the stream test.
- var testdata = {
- inArg: numStrs,
- inData: strList,
- serviceMethod: typedStreamingService.inStreamOnly,
- writeType: vdl.types.STRING,
- readType: null,
- onResolveFunc: function(numReceived) {
- t.fail('should have errored; did not send correct # of strings');
- end(t);
- },
- onDataFunc: function(value, dataIndex) {
- t.fail('received data from the stream: ' + JSON.stringify(value));
- },
- onErrorFunc: onErrorFunc,
- onRejectFunc: function(err) {
- onErrorFunc(err);
- end(t);
- }
- };
- streamTest(t, ctx, testdata, end);
- });
- });
-
- // This test verifies that the client cannot send a bad type onto the stream.
- // It also verifies that this bad value is not sent to the server.
- // Thus, the promise rejects, and the client gets an error while attempting to
- // write the bad value (write an int instead of a string).
- // Note: the stream also passes the same reject error to the error stream.
- test(namePrefix + 'typedStreamingService.inStreamOnly(...) - failure 2',
- function(t) {
-
- setup(options, function(err, ctx, typedStreamingService, end) {
- t.error(err, 'should not error on setup');
-
- // The # of strings we intend to send.
- var strList = [6];
- var numStrs = strList.length;
-
- // The stream will send an error on the error stream just before the
- // Promise rejects.
- var onErrorFunc = function(err) {
- t.ok(err, 'should error');
- t.ok(err.message.indexOf('Got 0. Wanted 1') !== -1,
- 'has correct error message');
- };
-
- // Prepare and run the stream test.
- var testdata = {
- inArg: numStrs,
- inData: strList,
- serviceMethod: typedStreamingService.inStreamOnly,
- writeType: vdl.types.STRING,
- readType: null,
- onResolveFunc: function(numReceived) {
- t.fail('should have errored; sent an int');
- end(t);
- },
- onDataFunc: function(value, dataIndex) {
- t.fail('received data from the stream: ' + JSON.stringify(value));
- },
- inDataThrowRegexp: /.*cannot convert to string.*/,
- onErrorFunc: onErrorFunc,
- onRejectFunc: function(err) {
- onErrorFunc(err);
- end(t);
- }
- };
- streamTest(t, ctx, testdata, end);
- });
- });
-
- // typedStreamingService.outStreamOnly tests:
- // - correct # of values read and outputted
- // - values received by server have the correct type
- // - inStream is null
- test(namePrefix + 'typedStreamingService.outStreamOnly(...)', function(t) {
-
- setup(options, function(err, ctx, typedStreamingService, end) {
- t.error(err, 'should not error on setup');
-
- // The # of BigInts we want to receive and # received so far.
- var numInts = 3;
- var numOutStream = 0;
-
- // Prepare and run the stream test.
- var testdata = {
- inArg: numInts,
- inData: [],
- serviceMethod: typedStreamingService.outStreamOnly,
- writeType: null,
- readType: vdl.types.INT64,
- onResolveFunc: function(numSent) {
- t.equal(numSent, numInts, 'service knows # of values sent');
- t.equal(numOutStream, numInts, 'service sent correct # of values');
- end(t);
- },
- onDataFunc: function(value, dataIndex) {
- t.ok(value instanceof vdl.BigInt, 'value is a BigInt');
- numOutStream++;
- }
- };
- streamTest(t, ctx, testdata, end);
- });
- });
-
- // typedStreamingService.bidirBoolListNegationStream tests:
- // - custom defined type (simple) can be sent and received properly
- // - the values can be modified and returned (each bool is negated)
- test(namePrefix + 'typedStreamingService.bidirBoolListNegationStream()',
- function(t) {
-
- setup(options, function(err, ctx, typedStreamingService, end){
- t.error(err, 'should not error on setup');
-
- // These are the testcases.
- var boolLists = [
- undefined, // Note: undefined autoconverts to empty list.
- [],
- [true],
- [false, true, true],
- [undefined, false], // Note: undefined autoconverts to false.
- ];
- var expectedLists = [
- [],
- [],
- [false],
- [true, false, false],
- [true, true]
- ];
-
- // Prepare and run the stream test.
- var testdata = {
- inArg: undefined,
- inData: boolLists,
- serviceMethod: typedStreamingService.bidirBoolListNegationStream,
- writeType: boolListType,
- readType: boolListType,
- onResolveFunc: function(numReceived) {
- t.deepEqual(numReceived, boolLists.length,
- 'service sent correct # of values');
- end(t);
- },
- onDataFunc: function(actual, dataIndex) {
- t.ok(Array.isArray(actual), 'value is an array');
- t.deepEqual(actual, expectedLists[dataIndex],
- 'bools were flipped');
- }
- };
- streamTest(t, ctx, testdata, end);
- });
- });
-
- // typedStreamingService.structValueStream tests:
- // - values with a named struct type can be received properly
- test(namePrefix + 'typedStreamingService.structValueStream()', function(t) {
- setup(options, function(err, ctx, typedStreamingService, end){
- t.error(err, 'should not error on setup');
-
- // These are the testcases.
- var numbers = [
- undefined, // Note: undefined autoconverts to 0
- 3,
- -500000
- ];
- var NumStruct = vdl.registry.lookupOrCreateConstructor(numStructType);
- var expectedNumStructs = [
- new NumStruct({
- string: '0'
- }),
- new NumStruct({
- number: 3,
- bigInt: vdl.BigInt.fromNativeNumber(3),
- string: '3'
- }),
- new NumStruct({
- number: -500000,
- bigInt: vdl.BigInt.fromNativeNumber(-500000),
- string: '-500000'
- })
- ];
-
- // Prepare and run the stream test.
- var testdata = {
- inArg: undefined,
- inData: numbers,
- serviceMethod: typedStreamingService.structValueStream,
- writeType: vdl.types.FLOAT64,
- readType: numStructType,
- onResolveFunc: function(numReceived) {
- t.deepEqual(numReceived, numbers.length,
- 'service sent correct # of values');
- end(t);
- },
- onDataFunc: function(actual, dataIndex) {
- t.ok(actual instanceof NumStruct, 'value is a NumStruct');
- t.deepEqual(actual, expectedNumStructs[dataIndex],
- 'number converted to NumStruct');
- }
- };
- streamTest(t, ctx, testdata, end);
- });
- });
-
- // typedStreamingService.anyStream tests:
- // - the any stream succeeds in both directions
- // - complicated types can be sent across the stream in both directions
- // - the types received by the server match the expected types
- // - the types received by the client match the expected types
- test(namePrefix + 'typedStreamingService.anyStream()', function(t) {
- setup(options, function(err, ctx, typedStreamingService, end){
- t.error(err, 'should not error on setup');
-
- // These are the testcases.
- var typesSent = [
- vdl.types.JSVALUE,
- vdl.types.INT32,
- vdl.types.INT64,
- vdl.types.COMPLEX128,
- vdl.types.STRING,
- vdl.types.BOOL,
- numStructType,
- boolListType,
- typeListType
- ];
-
- var NumStruct = vdl.registry.lookupOrCreateConstructor(numStructType);
- var BoolList = vdl.registry.lookupOrCreateConstructor(boolListType);
- var TypeList = vdl.registry.lookupOrCreateConstructor(typeListType);
-
- var sendList = [
- 3.14,
- new builtins.INT32(5),
- new builtins.INT64(-15),
- new builtins.COMPLEX128(new vdl.Complex(5, -5)),
- new builtins.STRING('abc'),
- new builtins.BOOL(true),
- new NumStruct({
- number: -0.5
- }),
- new BoolList([true, true, false, false]),
- new TypeList(typesSent)
- ];
-
- // Prepare and run the stream test.
- var testdata = {
- inArg: typesSent,
- inData: sendList,
- serviceMethod: typedStreamingService.anyStream,
- writeType: vdl.types.ANY,
- readType: vdl.types.ANY,
- onResolveFunc: function(typesReceived) {
- t.deepEqual(typesReceived, typesSent,
- 'service sent back the correct types');
- end(t);
- },
- onDataFunc: function(actual, dataIndex) {
- if (actual._type === undefined) {
- t.ok(typesSent[dataIndex].equals(vdl.types.JSVALUE),
- 'value is native');
- } else {
- t.deepEqual(actual._type, typesSent[dataIndex], 'type matches');
- }
- t.deepEqual(actual, sendList[dataIndex], 'received correct value');
- }
- };
- streamTest(t, ctx, testdata, end);
- });
- });
-
- function setup(options, cb) {
- var dispatcher = leafDispatcher(options.definition);
-
- serve('testing/typeService', dispatcher, function(err, res) {
- cb(err, res.runtime.getContext(), res.service, res.end);
- });
- }
-}
-
-/*
- * Performs a stream test that assumes <= 1 input arg to the service method.
- * testdata contains inArg, inData, serviceMethod, writeType, readType,
- * onResolveFunc, onDataFunc
- * Note: onResolveFunc and onDataFunc should end the test.
- * Optional testdata fields: inDataThrowRegexp, onErrorFunc, and onRejectFunc;
- * these are most useful for error test cases.
- */
-function streamTest(t, ctx, testdata, end) {
- // The Error function is optional; successful test cases never need it.
- function error(err) {
- t.error(err, 'should not error');
- end(t);
- }
-
- // Determine the correct onRejectFunc and onErrorFunc handlers.
- var onRejectFunc = testdata.onRejectFunc || error;
- var onErrorFunc = testdata.onErrorFunc || error;
-
- // 1. Create a stream reader/writer to receive the values
- var promise = testdata.serviceMethod(ctx, testdata.inArg);
- var stream = promise.stream;
- t.deepEqual(stream.writeType, testdata.writeType, 'inStream matches type');
- t.deepEqual(stream.readType, testdata.readType, 'outStream matches type');
-
- // 2. Handle RPC
- promise.then(testdata.onResolveFunc).catch(onRejectFunc);
-
- // 3. Setup listeners for the stream. Data should be NumStructs
- stream.on('error', onErrorFunc);
-
- var dataIndex = 0;
- stream.on('data', function(actual) {
- testdata.onDataFunc(actual, dataIndex);
- dataIndex++;
- });
-
- // 4. Send data through the stream.
- for (var i = 0; i < testdata.inData.length; i++) {
- if (testdata.inDataThrowRegexp) {
- t.throws(stream.write.bind(stream, testdata.inData[i]),
- testdata.inDataThrowRegexp, 'stream write throws on bad input');
- } else {
- stream.write(testdata.inData[i]);
- }
- }
-
- // 5. End the stream.
- stream.end();
-}
-
-test('Test server stream exception handling', function(assert) {
- var exception;
-
- if (typeof window === 'undefined') {
- process.on('uncaughtException', function setexception(err) {
- exception = err;
- process.removeListener('uncaughtException', setexception);
- });
- } else {
- window.onerror = function(message, url, line, column, err) {
- exception = err;
- // Put it back to the default
- window.onerror = null;
- };
- }
-
- var service = {
- get: function get(context, serverCall, $stream, cb) {
- $stream.on('end', cb.bind(null, null, {}));
- $stream.on('error', cb);
- $stream.on('data', function ondata(buffer) {
- throw new Error('Woah!');
- });
- }
- };
-
- setup(service, function ready(err, context, remote, end) {
- assert.error(err, 'should not error on setup');
-
- var stream = remote.get(context, function(err) {
- assert.error(err);
- assert.ok(exception, 'stream exceptions should be raised');
- end(assert);
- }).stream;
-
- stream.write('foo');
- stream.end();
- });
-
- function setup(service, cb) {
- var dispatcher = leafDispatcher(service);
- var name = 'test/server-stream-exception';
-
- serve(name, dispatcher, function(err, res) {
- cb(err, res.runtime.getContext(), res.service, res.end);
- });
- }
-});
diff --git a/test/integration/test-nacl-plugin-crash.js b/test/integration/test-nacl-plugin-crash.js
deleted file mode 100644
index 8e19eb1..0000000
--- a/test/integration/test-nacl-plugin-crash.js
+++ /dev/null
@@ -1,74 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-
-var leafDispatcher = require('../../src/rpc/leaf-dispatcher');
-var serve = require('./serve');
-
-// Test serving and making an RPC call.
-// name is the name of the service to serve and cb is called after completion.
-function validateCommunication(t, name, cb) {
- var response = 5;
-
- var dispatcher = leafDispatcher({
- anRpc: function(context, serverCall, cb) {
- cb(null, response);
- }
- });
-
- serve(name, dispatcher, function(err, res) {
- if (err) {
- return cb(err);
- }
-
- res.service.anRpc(res.runtime.getContext(), function(err, result) {
- t.error(err, 'Err expected to be null');
- t.equal(result, response, 'Expected different response from anRpc()');
- cb(null, res.close, res.runtime);
- });
- });
-}
-
-test('Test recovery from nacl plugin crash', function(t) {
- if (!require('is-browser')) {
- return t.end();
- }
-
- var errors = require('../../src/verror/index');
- var eventProxy = require('../../src/browser/event-proxy');
-
- // validate comunication first, partially because this initializes the
- // nacl plugin.
- validateCommunication(t, 'test/name1', function(err, close1, runtime) {
- if (err) {
- return t.end(err);
- }
-
- // Handle the crash.
- runtime.once('crash', function(err) {
- t.ok(err instanceof errors.ExtensionCrashError,
- 'Receive ExtensionCrashError object.');
-
- // Perform another communication validation.
- validateCommunication(t, 'test/name2', function(err, close2) {
- if (err) {
- t.error(err);
- return close1(function() {
- t.ok(err, 'runtime.close should error because nacl crashed.');
- t.end();
- });
- }
-
- close1(function(err1) {
- t.ok(err1, 'First runtime.close should error because nacl crashed.');
- close2(t.end);
- });
- });
- });
-
- // Send a message triggering a nacl plug-in crash.
- eventProxy.send('intentionallyPanic');
- });
-});
diff --git a/test/integration/test-namespace.js b/test/integration/test-namespace.js
deleted file mode 100644
index 2cab811..0000000
--- a/test/integration/test-namespace.js
+++ /dev/null
@@ -1,895 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var Promise = require('../../src/lib/promise');
-
-var config = require('./default-config');
-var Promise = require('../../src/lib/promise');
-var random = require('../../src/lib/random');
-var timeouts = require('./timeouts');
-var vanadium = require('../../');
-var verror = vanadium.verror;
-var access = vanadium.security.access;
-var reserved = vanadium.rpc.reserved;
-
-var namespaceRoot = process.env.V23_NAMESPACE;
-var PREFIX = 'namespace-testing/';
-var MINUTE = 60 * 1000; // a minute
-
-test('Test globbing children - glob(' + PREFIX + '*)', function(assert) {
- var runtime;
-
- init(config).then(function glob(rt) {
- runtime = rt;
- var namespace = rt.getNamespace();
- var ctx = runtime.getContext();
- var rpc = namespace.glob(ctx, PREFIX + '*');
- rpc.catch(end);
- return readAllMountPoints(rpc.stream);
- }).then(function validate(actual) {
- var expected = [{
- name: PREFIX + 'cottage',
- isLeaf: false
- }, {
- name: PREFIX + 'house',
- isLeaf: false
- }];
- assertResults(actual, expected, assert);
- end();
- }).catch(end);
-
- function end(err) {
- assert.error(err);
- if (runtime) {
- runtime.close(assert.end);
- } else {
- assert.end();
- }
- }
-});
-
-test('Test glob().stream - exception handling', function(assert) {
- vanadium.init(function onruntime(err, runtime) {
- if (err) {
- return end(err);
- }
-
- var namespace = runtime.getNamespace();
- var context = runtime.getContext();
- var promise = namespace.glob(context, '*');
- var stream = promise.stream;
- var exception;
-
- promise.catch(function(err) {
- assert.error(err, 'should not catch expceptions in stream');
- });
-
- if (typeof window === 'undefined') {
- process.on('uncaughtException', function setexception(err) {
- exception = err;
- process.removeListener('uncaughtException', setexception);
- });
- } else {
- window.onerror = function(message, url, line, column, err) {
- exception = err;
- // Put it back to the default
- window.onerror = null;
- };
- }
-
- // NOTE: Using assert.throws(fn) here is not possible since the fix is to
- // use process.nextTick(...) wich will have the raised exception bypass the
- // try/catch stack around where assert.throws(...) calls the passed in fn.
- stream.once('data', function onentry(entry) {
- throw new Error('Woah!');
- });
-
- stream.on('end', end);
-
- function end(err) {
- if (err) {
- assert.error(err, 'should not error');
- }
-
- assert.ok(exception, 'glob-stream exceptions should be raised');
-
- if (runtime) {
- runtime.close(assert.end);
- } else {
- assert.end();
- }
- }
- });
-});
-
-test('Test globbing nested levels - glob(' + PREFIX + 'cottage/*/*/*)',
- function(assert) {
- var runtime;
-
- init(config).then(function glob(rt) {
- runtime = rt;
- var namespace = rt.getNamespace();
- var ctx = runtime.getContext();
- var rpc = namespace.glob(ctx, PREFIX + 'cottage/*/*/*');
- rpc.catch(end);
- return readAllMountPoints(rpc.stream);
- }).then(function validate(actual) {
- var expected = [{
- name: PREFIX + 'cottage/lawn/back/sprinkler',
- isLeaf: true
- }, {
- name: PREFIX + 'cottage/lawn/front/sprinkler',
- isLeaf: true
- }];
- assertResults(actual, expected, assert);
- end();
- }).catch(end);
-
- function end(err) {
- assert.error(err);
- if (runtime) {
- runtime.close(assert.end);
- } else {
- assert.end();
- }
- }
- });
-
-test('Test globbing non-existing name - glob(' + PREFIX + 'does/not/exist)',
- function(assert) {
- var runtime;
-
- init(config).then(function glob(rt) {
- runtime = rt;
- var namespace = rt.getNamespace();
- var ctx = runtime.getContext();
- var rpc = namespace.glob(ctx, PREFIX + 'does/not/exist');
- rpc.catch(end);
- return readAllMountPoints(rpc.stream);
- }).then(function validate(actual) {
- var expected = [];
- assert.deepEqual(actual.sort(), expected.sort());
- end();
- }).catch(end);
-
- function end(err) {
- assert.error(err);
- if (runtime) {
- runtime.close(assert.end);
- } else {
- assert.end();
- }
- }
- });
-
-test('Test glob\'s promise is resolved when glob finishes.' +
- '- var promise = glob(' + PREFIX + '*)',
- function(assert) {
- var runtime;
-
- init(config).then(function glob(rt) {
- runtime = rt;
- var namespace = rt.getNamespace();
- var ctx = runtime.getContext();
- return namespace.glob(ctx, PREFIX + '*');
- }).then(function(finalResult) {
- assert.notOk(finalResult, 'there is no final result for glob');
- assert.pass('Promise resolved when glob finished.');
- end();
- }).catch(end);
-
- function end(err) {
- assert.error(err);
- if (runtime) {
- runtime.close(assert.end);
- } else {
- assert.end();
- }
- }
- });
-
-test('Test glob\'s callback is called when glob finishes.' +
- '- glob(' + PREFIX + '*, cb)',
- function(assert) {
- var runtime;
-
- init(config).then(function glob(rt) {
- runtime = rt;
- var namespace = rt.getNamespace();
- var ctx = runtime.getContext();
- namespace.glob(ctx, PREFIX + '*', function(err, finalResult) {
- assert.error(err);
-
- assert.notOk(finalResult, 'there is no final result for glob');
- assert.pass('Promise resolved when glob finished.');
- end();
- });
- }).catch(end);
-
- function end(err) {
- assert.error(err);
- if (runtime) {
- runtime.close(assert.end);
- } else {
- assert.end();
- }
- }
- });
-
-test('Test globbing non-existing rooted name - ' +
- 'glob(/RootedBadName.Google.tld:1234/*)',
- function(assert) {
-
- // increase timeout for this test as it retries bad-url until timeout.
- assert.timeout(timeouts.long);
-
- var runtime;
- vanadium.init(config).then(function glob(rt) {
- runtime = rt;
- var namespace = rt.getNamespace();
- // Note: Glob will always timeout after 30s
- // see v.io/x/ref/runtime/internal/naming/namespace/parallelstartcall.go
- // This means we'll get a timeout error on the glob stream before
- // timeouts.long expires.
- var rpc = namespace.glob(rt.getContext(),
- '/RootedBadName.Google.tld:1234/*');
- rpc.catch(function(err) {
- // Ignore the timeout error.
- });
-
- // We expect no actual result items but one stream error result item
- rpc.stream.on('data', function(item) {
- assert.notOk(item, 'Should not get any actual results');
- });
-
- var numErrorItems = 0;
- rpc.stream.on('error', function(errItem) {
- if (numErrorItems > 0) {
- end('expected only one error item');
- }
- numErrorItems++;
- assert.ok(errItem, 'Should get one error result item');
- assert.ok(errItem.error instanceof verror.TimeoutError ||
- errItem.error instanceof verror.NoServersError,
- 'error item should have error field of type TimeoutError or ' +
- 'NoServersError');
- assert.equal(errItem.name, '/RootedBadName.Google.tld:1234',
- 'error item should have a name');
- });
-
- rpc.stream.on('end', function() {
- assert.equal(numErrorItems, 1,
- 'must end with 1 GlobError, got: ' + numErrorItems);
- end();
- });
- }).catch(end);
-
- function end(err) {
- assert.error(err);
- if (runtime) {
- runtime.close(assert.end);
- } else {
- assert.end();
- }
- }
- });
-
-test('Test mounting and unmounting - ' +
- 'mount(' + PREFIX + 'new/name), unmount(' + PREFIX + 'new/name)',
- function(assert) {
- var runtime;
- var namespace;
- var expectedServerAddress;
- var initialName = PREFIX + 'first/name';
- var secondaryName = PREFIX + 'new/name';
-
- var ctx;
- vanadium.init(config).then(function createServer(rt) {
- runtime = rt;
- namespace = rt.getNamespace();
- ctx = rt.getContext();
- return rt.newServer(initialName, {});
- })
- .then(function() {
- return waitForPublish(initialName, runtime);
- })
- .then(function resolve() {
- return namespace.resolve(ctx, initialName);
- }).then(function mount(endpoints) {
- expectedServerAddress = endpoints[0];
- return namespace.mount(ctx, secondaryName, expectedServerAddress,
- MINUTE);
- }).then(function() {
- return waitForPublish(initialName, runtime);
- }).then(function resolve() {
- return namespace.resolve(ctx, secondaryName);
- }).then(function validate(resolveResult) {
- assert.equals(resolveResult.length, 1);
- assert.equals(resolveResult[0], expectedServerAddress);
- }).then(function unmount() {
- return namespace.unmount(ctx, secondaryName);
- }).then(function() {
- return waitForUnpublish(secondaryName, runtime);
- }).then(function resolve() {
- namespace.resolve(ctx, secondaryName, function cb(err) {
- assert.ok(err, 'no resolving after unmount()');
- end();
- });
- }).catch(end);
-
- function end(err) {
- assert.error(err);
- if (runtime) {
- runtime.close(assert.end);
- } else {
- assert.end();
- }
- }
- });
-
-test('Test resolving to mounttable - ' +
- 'resolveToMountTable(' + PREFIX + 'cottage)',
- function(assert) {
- var runtime;
-
- var ctx;
- init(config).then(function resolveToMountTable(rt) {
- runtime = rt;
- ctx = runtime.getContext();
- var namespace = rt.getNamespace();
- return namespace.resolveToMounttable(ctx, PREFIX + 'cottage');
- }).then(function validate(mounttableNames) {
- assert.equals(mounttableNames.length, 1);
- var mounttableName = mounttableNames[0];
- assert.ok(mounttableName.indexOf(namespaceRoot) === 0);
- end();
- }).catch(end);
-
- function end(err) {
- assert.error(err);
- if (runtime) {
- runtime.close(assert.end);
- } else {
- assert.end();
- }
- }
- });
-
-test('Test flushing cache entry - ' +
- 'flushCacheEntry(' + PREFIX + 'house/alarm)',
- function(assert) {
- var runtime;
- var namespace;
- var name = PREFIX + 'house/alarm';
-
- init(config).then(function flushCacheEntry(rt) {
- runtime = rt;
- namespace = rt.getNamespace();
- return namespace.flushCacheEntry(name);
- }).then(function validate() {
- // We don't check the return result of flushCachEntry since there is no
- // guarantee that it was in the cache to be flushed in the first place.
- // Even if we do a resolve() before this step to cache it, it may still
- // get evicted by the time we call flushCacheEntry for different reasons
- // such as cache being full, service remounting itself, parent mount-point
- // expiring.
- assert.pass('cache flushed');
- end();
- }).catch(end);
-
- function end(err) {
- assert.error(err);
- if (runtime) {
- runtime.close(assert.end);
- } else {
- assert.end();
- }
- }
- });
-
-test('Test disabling cache - disableCache(true)', function(assert) {
- var runtime;
- var namespace;
- var name = PREFIX + 'house/alarm';
-
- var ctx;
- init(config).then(function disableCache(rt) {
- runtime = rt;
- ctx = rt.getContext();
- namespace = rt.getNamespace();
- return namespace.disableCache(true);
- }).then(function resolveButItShouldNotGetCached(rt) {
- return namespace.resolve(ctx, name);
- }).then(function tryFlushCacheEntry() {
- return namespace.flushCacheEntry(name);
- }).then(function validate(flushed) {
- assert.notOk(flushed, 'no cache to be flushed');
- end();
- }).catch(end);
-
- function end(err) {
- assert.error(err);
- if (runtime) {
- runtime.close(assert.end);
- } else {
- assert.end();
- }
- }
-});
-
-test('Test setting roots to valid endpoints - ' +
- 'setRoots(valid)',
- function(assert) {
- var runtime;
- var namespace;
- var ctx;
-
- init(config).then(function setRoots(rt) {
- runtime = rt;
- namespace = rt.getNamespace();
- ctx = rt.getContext();
- // Set the roots to a valid root, we expect normal glob results.
- return namespace.setRoots(namespaceRoot);
- }).then(function glob() {
- var rpc = namespace.glob(ctx, PREFIX + '*');
- rpc.catch(end);
- return readAllMountPoints(rpc.stream);
- }).then(function validate(actual) {
- var expected = [{
- name: PREFIX + 'cottage',
- isLeaf: false
- }, {
- name: PREFIX + 'house',
- isLeaf: false
- }];
- assertResults(actual, expected, assert);
- end();
- }).catch(end);
-
- function end(err) {
- assert.error(err);
- if (runtime) {
- runtime.close(assert.end);
- } else {
- assert.end();
- }
- }
- });
-
-test('Test setting roots to invalid endpoint - ' +
- 'setRoots(invalid)',
- function(assert) {
-
- // increase timeout for this test as it retries bad-url until timeout.
- assert.timeout(timeouts.max);
-
- var runtime;
- var namespace;
- var ctx;
- vanadium.init(config).then(function setRoots(rt) {
- runtime = rt;
- namespace = rt.getNamespace();
- ctx = rt.getContext();
- // Set the roots to a invalid roots, then we don't expect resolution.
- return namespace.setRoots(['/bad-root-1.tld:80', '/bad-root-2.tld:1234']);
- }).then(function bind() {
- // Since setRoots changes runtimes Namespace roots, binding to any name
- // should now fail
- var client = runtime.getClient();
- ctx = ctx.withTimeout(timeouts.short);
- return client.bindTo(ctx, PREFIX + 'house/kitchen/lights')
- .then(function() {
- assert.fail('Should not have been able to bind with invalid roots');
- }, function(err) {
- assert.ok(err);
- assert.ok(err instanceof Error);
- ctx.finish();
- end();
- });
- }).catch(end);
-
- function end(err) {
- assert.error(err);
- if (runtime) {
- runtime.close(assert.end);
- } else {
- assert.end();
- }
- }
- });
-
-test('Test getting roots - roots()', function(assert) {
- var runtime;
-
- init(config).then(function roots(rt) {
- runtime = rt;
- var namespace = rt.getNamespace();
- return namespace.roots();
- }).then(function validate(roots) {
- assert.equals(roots.length, 1);
- assert.ok(roots.indexOf(namespaceRoot === 0));
- end();
- }).catch(end);
-
- function end(err) {
- assert.error(err);
- if (runtime) {
- runtime.close(assert.end);
- } else {
- assert.end();
- }
- }
-});
-
-test('Test setting and getting roots - ' +
- 'setRoots(), roots(cb)',
- function(assert) {
- var runtime;
- var namespace;
-
- vanadium.init(config, onInit);
-
- function onInit(err, rt) {
- assert.error(err);
- runtime = rt;
- namespace = rt.getNamespace();
- namespace.setRoots('/root1:80', '/root2:1234', onSetRoots);
- }
-
- function onSetRoots(err) {
- assert.error(err);
- namespace.roots(onRoots);
- }
-
- function onRoots(err, roots) {
- assert.error(err);
- assert.ok(roots[0].indexOf('root1:80' >= 0));
- assert.ok(roots[1].indexOf('root2:1234' >= 0));
- if (runtime) {
- runtime.close(assert.end);
- }
- }
- });
-
-test('Test getPermissions() on non-existant name', function(assert) {
- vanadium.init(config, function(err, rt) {
- if (err) {
- return assert.end(err);
- }
-
- var ctx = rt.getContext();
- var ns = rt.getNamespace();
- var name = 'non/existant/name';
-
- ns.getPermissions(ctx, name, function(err) {
- assert.ok(err, 'should error');
- rt.close(assert.end);
- });
- });
-});
-
-test('Test setting and getting permissions - ' +
- 'setPermissions(), getPermissions()',
- function(assert) {
- vanadium.init(config, function(err, rt) {
- if (err) {
- return assert.end(err);
- }
-
- var ctx = rt.getContext();
- var ns = rt.getNamespace();
- // Note: we use a random name here so we can run the test multiple times
- // with the same mounttable without getting locked out of a name.
- var name = 'path/to/some/name/' + random.hex();
-
- var perms = new access.Permissions(new Map([
- [access.Admin, new access.AccessList({
- 'in': ['...'],
- 'notIn': ['foo']
- })],
- [access.Read, new access.AccessList({
- 'in': ['bar/baz']
- })],
- [access.Write, new access.AccessList({
- 'notIn': ['biz/qux']
- })]
- ]));
-
- ns.setPermissions(ctx, name, perms, function(err) {
- if (err) {
- return end(err);
- }
-
- ns.getPermissions(ctx, name, function(err, gotPerms, gotVersion) {
- if (err) {
- return end(err);
- }
-
- assert.equal(typeof gotVersion, 'string',
- 'getPermissions returns a string version');
-
- assert.ok(gotPerms, 'getPermissions returns a permissions');
- assert.deepEqual(gotPerms, perms.val,
- 'getPermissions returns the same permissions that we set');
-
- ns.setPermissions(ctx, name, perms, 'wrongVersion', function(err) {
- assert.ok(err, 'setPermissions with a bad version should error');
-
- ns.setPermissions(ctx, name, perms, gotVersion, function(err) {
- assert.error(err,
- 'setPermissions with the correct version should not error');
- end();
- });
- });
- });
- });
-
- function end(err) {
- assert.error(err, 'should not error');
- rt.close(assert.end);
- }
- });
- });
-
-test('Test delete() on non-existant name', function(assert) {
- vanadium.init(config, function(err, rt) {
- if (err) {
- return assert.end(err);
- }
-
- var ctx = rt.getContext();
- var ns = rt.getNamespace();
- var name = 'non/existant/name';
-
- ns.delete(ctx, name, true, function(err) {
- assert.error(err, 'should not error');
- rt.close(assert.end);
- });
- });
-});
-
-test('Test delete() unmounts a name', function(assert) {
-
- vanadium.init(config, function(err, rt) {
- if (err) {
- return assert.end(err);
- }
-
- var ctx = rt.getContext();
- var ns = rt.getNamespace();
- var name = 'name/that/will/be/deleted';
- var ep = '/@6@ws@2.2.2.2:2222@@e8972f90fe028674f78a164f001d07c5@s@@';
-
- ns.mount(ctx, name, ep, MINUTE)
- .then(function onMount(err) {
- if (err) {
- return end(err);
- }
- }).then(function() {
- return waitForPublish(name, rt);
- }).then(function resolveOnce() {
- return ns.resolve(ctx, name);
- }).then(function validateResolvedEp(gotEps) {
- assert.equal(gotEps.length, 1, 'resolves to a single endpoint');
- assert.equal(ep, gotEps[0], 'resolves to the correct endpoint');
- }).then(function deleteName() {
- return ns.delete(ctx, name, false);
- }).then(function resolveTwice() {
- ns.resolve(ctx, name, function(err) {
- assert.ok(err, 'name should be unmounted');
- end();
- });
- }).catch(function(err) {
- assert.error(err);
- end(err);
- });
-
- function end(err) {
- assert.error(err, 'should not error');
- rt.close(assert.end);
- }
- });
-});
-
-test('Test delete() on name with no children', function(assert) {
- vanadium.init(config, function(err, rt) {
- if (err) {
- return assert.end(err);
- }
-
- var ctx = rt.getContext();
- var ns = rt.getNamespace();
- var name = 'path/to/name/with/no/children';
-
- var perms = new access.Permissions(new Map([
- [access.Admin, new access.AccessList({
- 'in': ['...'],
- })]
- ]));
-
- ns.setPermissions(ctx, name, perms, function(err) {
- if (err) {
- return end(err);
- }
-
- ns.delete(ctx, name, false, end);
- });
-
- function end(err) {
- assert.error(err, 'should not error');
- rt.close(assert.end);
- }
- });
-});
-
-test('Test delete() on name with children', function(assert) {
- vanadium.init(config, function(err, rt) {
- if (err) {
- return assert.end(err);
- }
-
- var ctx = rt.getContext();
- var ns = rt.getNamespace();
- var name = 'path/to/name/with/children';
- var childName1 = vanadium.naming.join(name, 'child1');
- var childName2 = vanadium.naming.join(name, 'node/child2');
-
- var perms = new access.Permissions(new Map([
- [access.Admin, new access.AccessList({
- 'in': ['...'],
- })]
- ]));
-
- // Create all three names.
- ns.setPermissions(ctx, name, perms, function(err) {
- if (err) {
- return end(err);
- }
- ns.setPermissions(ctx, childName1, perms, function(err) {
- if (err) {
- return end(err);
- }
- ns.setPermissions(ctx, childName2, perms, function(err) {
- if (err) {
- return end(err);
- }
-
- ns.delete(ctx, name, false, function(err) {
- assert.ok(err, 'should error if we don\'t delete subchildren');
-
- ns.delete(ctx, name, true, function(err) {
- assert.error(err, 'should not error if we delete subchildren');
- end();
- });
- });
- });
- });
- });
-
- function end(err) {
- assert.error(err, 'should not error');
- rt.close(assert.end);
- }
- });
-});
-
-/*
- * Given a glob stream, returns a promise that will resolve to an array
- * of glob results after all the results have been collected from the stream.
- */
-function readAllMountPoints(stream) {
- var mps = [];
- return new Promise(function(resolve, reject) {
- stream.on('data', function(mountPoint) {
- mps.push(mountPoint);
- });
-
- stream.on('end', function(name) {
- resolve(mps);
- });
-
- stream.on('error', function(errItem) {
- // we don't expect any errors other than GlobNotImplementedError
- if (!(errItem.error instanceof reserved.GlobNotImplementedError)) {
- reject(errItem.error);
- }
- });
- });
-}
-
-function assertResults(got, want, assert) {
- var toEqual = [];
- got.forEach(function(e) {
- toEqual.push({
- name: e.name,
- isLeaf: e.isLeaf
- });
- });
- assert.deepEqual(want.sort(mpSorter), toEqual.sort(mpSorter));
-
- function mpSorter(a, b) {
- return a.name.localeCompare(b.name);
- }
-}
-
-var SAMPLE_NAMESPACE = [
- 'house/alarm',
- 'house/living-room/lights',
- 'house/living-room/smoke-detector',
- 'house/kitchen/lights',
- 'cottage/alarm',
- 'cottage/lawn/back/sprinkler',
- 'cottage/lawn/front/sprinkler',
-];
-
-function init(config) {
- var runtime;
- return vanadium.init(config)
- .then(function serveEmptyService(rt) {
- runtime = rt;
- return rt.newServer('', {});
- })
- .then(function publishUnderMultipleNames(server) {
- var addNamesRequests = SAMPLE_NAMESPACE.map(function(name) {
- return server.addName(PREFIX + name);
- });
- return Promise.all(addNamesRequests);
- })
- .then(function waitUntilAllNamesPublished() {
- var resolveRequests = SAMPLE_NAMESPACE.map(function(name) {
- return waitForPublish(PREFIX + name, runtime);
- });
- return Promise.all(resolveRequests);
- })
- .then(function ready() {
- return runtime;
- });
-
-}
-
-function waitForPublish(name, runtime) {
- return wait(name, runtime, false);
-}
-
-function waitForUnpublish(name, runtime) {
- return wait(name, runtime, true);
-}
-
-// Helper function that waits until name is published or unpublished,
-// it checks every 100ms for a total of 50 tries before failing.
-function wait(name, runtime, waitForUnpublish) {
- var WAIT_TIME = 100;
- var MAX_TRIES = 50;
- return new Promise(function(resolve, reject) {
- var ns = runtime.getNamespace();
- var count = 0;
- runResolve();
-
- function runResolve() {
- ns.resolve(runtime.getContext(), name, function(err, s) {
- if (err && err.id !== 'v.io/v23/naming.nameDoesntExist') {
- reject(err);
- return;
- }
- var continueLoop = err;
- if (waitForUnpublish) {
- continueLoop = !continueLoop;
- }
- if (continueLoop) {
- count++;
- if (count === MAX_TRIES) {
- var verb = waitForUnpublish ? 'unpublished' : 'published';
- reject(
- new Error('Timed out waiting for ' + name + ' to be ' + verb)
- );
- return;
- }
- return setTimeout(runResolve, WAIT_TIME);
- }
- resolve();
- });
- }
- });
-}
\ No newline at end of file
diff --git a/test/integration/test-new-server.js b/test/integration/test-new-server.js
deleted file mode 100644
index 70d6a61..0000000
--- a/test/integration/test-new-server.js
+++ /dev/null
@@ -1,261 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var vanadium = require('../../');
-var Promise = require('../../src/lib/promise');
-var Deferred = require('../../src/lib/deferred');
-var config = require('./default-config');
-var timeouts = require('./timeouts');
-var isBrowser = require('is-browser');
-var promiseWhile = require('../../src/lib/async-helper').promiseWhile;
-
-var NAME_PREFIX = 'new-server-testing-چשઑᜰ/';
-
-var service = {
- changeChannel: function(ctx, serverCall) {
- throw new Error('NotImplemented');
- }
-};
-
-var fooService = {
- foo: function(ctx, serverCall) {
- return 'foo result';
- }
-};
-
-var barService = {
- bar: function(ctx, serverCall) {
- return 'bar result';
- }
-};
-
-test('Test creating a JS service named livingroom/tv - ' +
- 'rt.newServer(name, service, callback)', function(assert) {
- vanadium.init(config, function(err, runtime) {
- assert.error(err);
-
- runtime.newServer('livingroom/tv', service, function(err) {
- assert.error(err);
- runtime.close(assert.end);
- });
- });
-});
-
-test('Test creating a JS service named livingroom/tv - ' +
- 'var promise = rt.newServer(name, service)', function(assert) {
- vanadium.init(config, function(err, runtime) {
- assert.error(err);
-
- runtime.newServer('livingroom/tv', service)
- .then(function() {
- runtime.close(assert.end);
- })
- .catch(function(err) {
- assert.error(err);
- runtime.close(assert.end);
- });
- });
-});
-
-test('Test creating a JS service when proxy Url is invalid - '+
- 'rt.newServer(name, service, callback)', function(t) {
- if (isBrowser) {
- return t.end();
- }
-
- vanadium.init({ wspr: 'http://bad-address.tld' }, function(err, runtime) {
- t.notOk(err, 'no error expected on init() since wspr isn\'t ' +
- 'contacted');
- runtime.newServer('should/fail', service, function(err) {
- t.ok(err, 'should get error after attempting to serve with bad proxy');
- runtime.close(t.end);
- });
- });
-});
-
-test('Test creating a JS service when proxy Url is invalid - '+
- 'var promise = runtime.newServer(name, service)', function(t) {
- if (isBrowser) {
- return t.end();
- }
-
- vanadium.init({ wspr: 'http://bad-address.tld' }, function(err, runtime) {
- t.notOk(err, 'no error expected on init() since wspr isn\'t ' +
- 'contacted');
- runtime.newServer('should/fail', service).then(function() {
- t.fail('serve expected to fail but succeeded');
- runtime.close(t.end);
- }).catch(function(err) {
- t.ok(err, 'should get error after attempting to serve with bad proxy');
- runtime.close(t.end);
- });
- });
-});
-
-test('Test creating a JS service under multiple names - ' +
- 'runtime.addName(name), runtime.removeName(name)', function(assert) {
- var ctx;
-
- vanadium.init(config, function(err, runtime) {
- assert.error(err);
-
- var client = runtime.getClient();
- ctx = runtime.getContext();
- var server;
- runtime.newServer('livingroom/tv', service)
- .then(function addSecondName(s) {
- server = s;
- return server.addName('bedroom/tv');
- })
- .then(function bindToSecondName() {
- return client.bindTo(ctx, 'bedroom/tv');
- })
- .then(function verifySecondName(newObject){
- assert.ok(newObject && newObject.changeChannel, 'new name works');
- })
- .then(function removeSecondName() {
- return server.removeName('bedroom/tv');
- })
- .then(function waitForNameToBeRemoved() {
- var numTries = 0;
- function tryBindTo() {
- numTries++;
- if (numTries > 5) {
- return Promise.resolve(false);
- }
- var shortCtx = runtime.getContext().withTimeout(200);
- return runtime.getNamespace().resolve(shortCtx, 'bedroom/tv')
- .then(function() {
- return true;
- }).catch(function(err) {
- return false;
- });
- }
- // Resolve every 100ms until the name is removed, or 5 tries are
- // attempted.
- return promiseWhile(tryBindTo, function() {
- var def = new Deferred();
- setTimeout(function() {
- def.resolve();
- }, 100);
- return def.promise;
- });
- }).then(function bindToRemovedSecondName() {
- var shortCtx = runtime.getContext().withTimeout(100);
- client.bindTo(shortCtx, 'bedroom/tv')
- .then(function verifyRemovedSecondName(a) {
- assert.fail('should not be able to bind to a removed name');
- runtime.close(assert.end);
- }, function verifyRemovedSecondName(err) {
- assert.ok(err instanceof Error, 'should fail');
- runtime.close(assert.end);
- });
- })
- .catch(function(err) {
- assert.error(err);
- runtime.close(assert.end);
- });
- });
-});
-
-test('Test running several JS servers concurrently and under multiple ' +
- 'names', function(assert) {
- var ctx;
-
- var runtime;
- var fooServer;
- var barServer;
- var fooStub;
- var barStub;
- var client;
-
- // big test, give it more time to finish
- assert.timeout(timeouts.long);
-
- return vanadium.init(config)
- .then(function createTwoServers(rt) {
- runtime = rt;
- client = rt.getClient();
- ctx = rt.getContext();
- return Promise.all([
- rt.newServer(NAME_PREFIX + 'foo', fooService ),
- rt.newServer(NAME_PREFIX + 'bar', barService )
- ]);
- })
- .then(function publishFooAndBarUnderAdditionalNames(servers) {
- fooServer = servers[0];
- barServer = servers[1];
- return Promise.all([
- fooServer.addName(NAME_PREFIX + 'foo-fighter'),
- barServer.addName(NAME_PREFIX + 'bar-baz')
- ]);
- })
- .then(function bindToFoo() {
- // BindTo foo or foo-fighter which ever comes back first
- return Promise.race([
- client.bindTo(ctx, NAME_PREFIX + 'foo'),
- client.bindTo(ctx, NAME_PREFIX + 'foo-fighter')
- ]);
- })
- .then(function validateFooStub(foo) {
- fooStub = foo;
- assert.ok(fooStub['foo'], 'foo stub has method foo()');
- return fooStub.foo(ctx).then(function CallToFooRetruned(result) {
- assert.equal(result, 'foo result');
- });
- })
- .then(function stopFoo() {
- return fooServer.stop();
- })
- .then(function validateFooWasStopped() {
- var shortCtx = runtime.getContext().withTimeout(100);
- return fooStub.foo(shortCtx)
- .then(function() {
- assert.fail('should have failed to call foo() after stop');
- }, function(err) {
- assert.ok(err);
- assert.ok(err instanceof Error);
- });
- })
- .then(function bindToBar() {
- // BindTo bar or bar-fighter which ever comes back first
- return Promise.race([
- client.bindTo(ctx, NAME_PREFIX + 'bar'),
- client.bindTo(ctx, NAME_PREFIX + 'bar-fighter')
- ]);
- })
- .then(function validateBarStub(bar) {
- barStub = bar;
- assert.ok(barStub['bar'], 'bar stub has method bar()');
- return barStub.bar(ctx).then(
- function CallToBarRetruned(result) {
- assert.equal(result, 'bar result');
- });
- })
- .then(function stopBar() {
- return barServer.stop();
- })
- .then(function validateBarWasStopped() {
- var shortCtx = runtime.getContext().withTimeout(100);
- return barStub.bar(shortCtx)
- .then(function() {
- assert.fail('should have failed to call bar() after stop');
- }, function(err) {
- assert.ok(err);
- assert.ok(err instanceof Error);
- });
- })
- .then(end)
- .catch(end);
-
- function end(err) {
- assert.error(err);
- if (runtime) {
- runtime.close(assert.end);
- } else {
- assert.end();
- }
- }
-});
diff --git a/test/integration/test-remote-blessings.js b/test/integration/test-remote-blessings.js
deleted file mode 100644
index e179a5a..0000000
--- a/test/integration/test-remote-blessings.js
+++ /dev/null
@@ -1,111 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-
-var config = require('./default-config');
-var defaultBlessingRegex = require('./default-blessing-regex');
-var leafDispatcher = require('../../src/rpc/leaf-dispatcher');
-var serve = require('./serve');
-var vanadium = require('../../');
-
-function assertBlessings(blessings, t) {
- t.ok(Array.isArray(blessings), 'blessings is an array');
- t.ok(blessings.length > 0, 'blessings has at least one blessing');
- t.ok(defaultBlessingRegex.test(blessings[0]),
- 'blessings[0]: ' + blessings[0] +
- ' should match the default blessings regex ' + defaultBlessingRegex);
-}
-
-var serverName = 'foo';
-function newDispatcher() {
- return leafDispatcher({
- bar: function(ctx, serverCall) {}
- });
-}
-
-test('Test remote blessings with no method name ' +
- '- client.remoteBlessings(' + serverName + ', cb)', function(t) {
- serve(serverName, newDispatcher(), function(err, res) {
- if (err) {
- return t.end(err);
- }
-
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
-
- client.remoteBlessings(ctx, serverName, function(err, blessings) {
- if (err) {
- t.error(err);
- res.end(t);
- }
-
- assertBlessings(blessings, t);
-
- res.end(t);
- });
- });
-});
-
-test('Test remote blessings with known method ' +
- '- client.remoteBlessings(' + serverName + ', bar, cb)', function(t) {
- serve(serverName, newDispatcher(), function(err, res) {
- if (err) {
- return t.end(err);
- }
-
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
-
- client.remoteBlessings(ctx, serverName, 'bar', function(err, blessings) {
- if (err) {
- t.error(err);
- res.end(t);
- }
-
- assertBlessings(blessings, t);
-
- res.end(t);
- });
- });
-});
-
-test('Test remote blessings with unknown method ' +
- '- client.remoteBlessings(' + serverName + ', baz, cb)', function(t) {
- serve(serverName, newDispatcher(), function(err, res) {
- if (err) {
- return t.end(err);
- }
-
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
-
- client.remoteBlessings(ctx, serverName, 'baz', function(err, blessings) {
- if (err) {
- t.error(err);
- res.end(t);
- }
-
- assertBlessings(blessings, t);
-
- res.end(t);
- });
- });
-});
-
-test('Test remote blessings with non-existant server ' +
- '- client.remoteBlessings(unknown, cb)', function(t) {
- vanadium.init(config, function(err, rt) {
- if (err) {
- return t.end(err);
- }
- var client = rt.getClient();
- var ctx = rt.getContext();
-
- client.remoteBlessings(ctx, 'unknown', function(err, blessings) {
- t.ok(err, 'should error');
- rt.close(t.end);
- });
- });
-});
diff --git a/test/integration/test-runtime-close.js b/test/integration/test-runtime-close.js
deleted file mode 100644
index b96a2c7..0000000
--- a/test/integration/test-runtime-close.js
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var vanadium = require('../../');
-var config = require('./default-config');
-
-test('Test closing runtime - runtime.close(cb)', function(assert) {
- vanadium.init(config, oninit);
-
- var rt;
- function oninit(err, runtime) {
- rt = runtime;
- var ctx = runtime.getContext();
- assert.error(err);
- var client = runtime.getClient();
- client.bindTo(ctx, 'test_service/cache', onbind);
- }
-
- function onbind(err, service) {
- assert.error(err);
- rt.close(assert.end);
- }
-});
-
-test('Test closing runtime - var promise = runtime.close()', function(assert) {
- vanadium
- .init(config)
- .then(bindTo)
- .then(close)
- .then(end)
- .catch(assert.end);
-
- var rt;
-
- function bindTo(runtime) {
- rt = runtime;
- var client = runtime.getClient();
- var ctx = runtime.getContext();
- return client.bindTo(ctx, 'test_service/cache');
- }
-
- function close(service) {
- return rt.close().then(function() {
- assert.pass('Runtime closed successfully');
- }).catch(function(err) {
- assert.fail(err);
- });
- }
-
- function end() {
- assert.end();
- }
-});
diff --git a/test/integration/test-sending-blessings.js b/test/integration/test-sending-blessings.js
deleted file mode 100644
index b47004a..0000000
--- a/test/integration/test-sending-blessings.js
+++ /dev/null
@@ -1,75 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var vanadium = require('../../');
-var serve = require('./serve');
-var leafDispatcher = require('../../src/rpc/leaf-dispatcher');
-var WireBlessings = vanadium.security.WireBlessings;
-var Blessings = require('../../src/security/blessings');
-var security = vanadium.security;
-var types = vanadium.vdl.types;
-
-var blessingsService = {
- createBlessings: function(ctx, serverCall, publicKey) {
- var principal = vanadium.runtimeForContext(ctx).principal;
- var expiryDate = new Date((new Date()).getTime() + 6000000);
-
- return principal.blessingStore.getDefault(ctx).then(function(defaultBless) {
- return principal.bless(ctx, publicKey, defaultBless, 'friend',
- security.createExpiryCaveat(expiryDate));
- });
- },
- verifyBlessings: function(ctx, serverCall) {
- var secCall = serverCall.securityCall;
- // We can't look for an exact blessing, because node and browser tests
- // have different root blessings. Instead of looking for a particular
- // blessing, we try to find the extension blessing string.
- var hasGeneratedBlessing = secCall.remoteBlessingStrings.some(function(s) {
- return s.indexOf(':friend') !== -1;
- });
- if (!hasGeneratedBlessing) {
- throw new Error('bad blessings ' + secCall.remoteBlessingStrings);
- }
- return;
- },
- _serviceDescription: {
- methods: [{
- name: 'CreateBlessings',
- inArgs: [{
- type: types.STRING
- }],
- outArgs: [{
- type: WireBlessings.prototype._type,
- }]
- }, {
- name: 'VerifyBlessings',
- inArgs: [],
- outArgs: [],
- }]
- }
-};
-
-test('Test blessings are passed as return args', function(assert) {
- serve('testing/blessings', leafDispatcher(blessingsService),
- function(err, res) {
- var principal = res.runtime.principal;
-
- var ctx = res.runtime.getContext();
- principal.blessingStore.getPublicKey(ctx).then(function(key) {
- return res.service.createBlessings(ctx, key).then(function(blessings) {
- assert.ok(blessings instanceof Blessings, 'Is a blessing');
- return principal.blessingStore.set(ctx, blessings, 'test');
- }).then(function() {
- return res.service.verifyBlessings(ctx);
- }).then(function() {
- assert.ok(true, 'blessings succeed');
- res.end(assert);
- });
- }).catch(function(err) {
- assert.error(err);
- res.end(assert);
- });
- });
-});
diff --git a/test/integration/test-server-call.js b/test/integration/test-server-call.js
deleted file mode 100644
index b1a5ae4..0000000
--- a/test/integration/test-server-call.js
+++ /dev/null
@@ -1,187 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var serve = require('./serve');
-
-// Services that handles anything in a/b/* where b is the service name
-var service = {
- getSuffix: function(ctx, serverCall) {
- return serverCall.securityCall.suffix;
- },
- getContext: function(ctx, serverCall) {
- return serverCall;
- },
- getArgs: function(ctx, serverCall, a, b, c, $stream, cb) {
- var results = {
- call: serverCall,
- a: a,
- b: b,
- c: c
- };
-
- cb(null, results);
- }
-};
-
-function dispatcher(suffix, cb) {
- cb(null, {
- service: service
- });
-}
-
-var expectedContext = {
- suffix: 'suf',
- methodTags: []
-};
-
-function contains(actual, expected, assert) {
- for (var key in expected) {
- if (!expected.hasOwnProperty(key)) {
- continue;
- }
- assert.deepEqual(actual[key], expected[key]);
- }
-}
-
-var defaultBlessingRegex = require('./default-blessing-regex');
-
-function blessingStringsMatch(strings, regex, assert) {
- assert.ok(strings.length > 0, 'Context has strings');
-
- for (var i = 0; i < strings.length; i++) {
- assert.ok(regex.test(strings[i]),
- 'string[' + i + '] matches expected name');
- }
-}
-
-function validateEndpoint(ep, assert) {
- assert.ok(typeof ep === 'string',
- 'Endpoint should be string');
- assert.ok(ep !== '', 'endpoint should not be empty');
-}
-
-function validateContext(call, assert) {
- blessingStringsMatch(call.localBlessingStrings, defaultBlessingRegex,
- assert);
- blessingStringsMatch(call.remoteBlessingStrings, defaultBlessingRegex,
- assert);
- validateEndpoint(call.localEndpoint, assert);
- validateEndpoint(call.remoteEndpoint, assert);
-}
-
-test('Test non-empty suffix is available in context', function(assert) {
- serve('a/b', dispatcher, function(err, res, end) {
- assert.error(err, 'should not error on serve(...)');
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
- client.bindTo(ctx, 'a/b/foo', function(err, service) {
- assert.error(err, 'should not error on runtime.bindTo(...)');
-
- service.getSuffix(ctx, function(err, suffix) {
- assert.error(err, 'should not error on getSuffix(...)');
- assert.equal(suffix, 'foo');
- end(assert);
- });
- });
- });
-});
-
-test('Test Unicode suffix is available in context', function(assert) {
- serve('a/b', dispatcher, function(err, res, end) {
- assert.error(err, 'should not error on serve(...)');
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
- client.bindTo(ctx, 'a/b/چשઑᜰ', function(err, service) {
- assert.error(err, 'should not error on runtime.bindTo(...)');
-
- service.getSuffix(ctx, function(err, suffix) {
- assert.error(err, 'should not error on getSuffix(...)');
- assert.equal(suffix, 'چשઑᜰ');
- end(assert);
- });
- });
- });
-});
-
-test('Test empty suffix is available in context - ', function(assert) {
- serve('a/b', dispatcher, function(err, res, end) {
- assert.error(err, 'should not error on serve(...)');
-
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
- client.bindTo(ctx, 'a/b', function(err, service) {
- assert.error(err, 'should not error on runtime.bindTo(...)');
-
- service.getSuffix(ctx, function(err, suffix) {
- assert.error(err, 'should not error on getSuffix(...)');
- assert.equal(suffix, '');
- end(assert);
- });
- });
- });
-});
-
-test('Test nested suffix /parent/suffix ', function(assert) {
- serve('a/b', dispatcher, function(err, res, end) {
- assert.error(err, 'should not error on serve(...)');
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
- client.bindTo(ctx, 'a/b/parent/suf', function(err, service) {
- assert.error(err, 'should not error on runtime.bindTo(...)');
-
- service.getSuffix(ctx, function(err, suffix) {
- assert.error(err, 'should not error on getSuffix(...)');
- assert.equal(suffix, 'parent/suf');
- end(assert);
- });
- });
- });
-});
-
-test('Test context object', function(assert) {
- serve('a/b', dispatcher, function(err, res, end) {
- assert.error(err, 'should not error on serve(...)');
-
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
- client.bindTo(ctx, 'a/b/suf', function(err, service) {
- assert.error(err, 'should not error on runtime.bindTo(...)');
-
- service.getContext(ctx, function(err, call) {
- assert.error(err, 'should not error on getContext(...)');
- contains(call.securityCall, expectedContext, assert);
- validateContext(call.securityCall, assert);
- end(assert);
- });
- });
- });
-});
-
-test('Test context object and injected stream', function(assert) {
- serve('a/b', dispatcher, function(err, res, end) {
- assert.error(err, 'should not error on serve(...)');
-
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
- client.bindTo(ctx, 'a/b/suf', function(err, service) {
- assert.error(err, 'should not error on runtime.bindTo(...)');
-
- service.getArgs(ctx, '-a-','-b-','-c-', function(err, results) {
- assert.error(err, 'service.getArgs(...) should not error');
-
- contains(results, {
- a: '-a-',
- b: '-b-',
- c: '-c-'
- }, assert);
-
- var call = results.call.securityCall;
- contains(call, expectedContext, assert);
- validateContext(call, assert);
- end(assert);
- });
- });
- });
-});
diff --git a/test/integration/test-server-context.js b/test/integration/test-server-context.js
deleted file mode 100644
index 762a4d5..0000000
--- a/test/integration/test-server-context.js
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var serve = require('./serve');
-var leafDispatcher = require('../../src/rpc/leaf-dispatcher');
-var LANG_KEY = require('../../src/runtime/shared-context-keys').LANG_KEY;
-var dispatcher = leafDispatcher({
- test: function(ctx, serverCall) {
- return ctx.value(LANG_KEY);
- }
-}, function auth(ctx, call) {
- if (ctx.value(LANG_KEY) !== 'my-lang') {
- throw new Error('bad lang ' + ctx.value(LANG_KEY));
- }
-});
-test('Test language in context', function(assert) {
- serve('context', dispatcher, function(err, res, end) {
- assert.error(err, 'should not error on serve(...)');
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext().withValue(LANG_KEY, 'my-lang');
- client.bindTo(ctx, 'context').then(function(service) {
- return service.test(ctx);
- }).then(function(lang) {
- assert.equal(lang, 'my-lang');
- res.end(assert);
- }).catch(function(err) {
- assert.error(err);
- res.end(assert);
- });
- });
-});
diff --git a/test/integration/test-server-errors.js b/test/integration/test-server-errors.js
deleted file mode 100644
index 24e363d..0000000
--- a/test/integration/test-server-errors.js
+++ /dev/null
@@ -1,149 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var vanadium = require('../../');
-var Deferred = require('../../src/lib/deferred');
-var serve = require('./serve');
-var leafDispatcher = require('../../src/rpc/leaf-dispatcher');
-var message = 'failure';
-
-testStandardErrors();
-testNonStandardErrors();
-
-function testStandardErrors() {
- var error = new Error(message);
- var errorThrower = {
- throwError: function(ctx, serverCall) {
- throw error;
- },
- returnErrorInCallback: function(ctx, serverCall, cb) {
- cb(error, null);
- },
- returnStringErrorInCallback: function(ctx, serverCall, cb) {
- cb(message, null);
- },
- rejectPromise: function(ctx, serverCall) {
- var def = new Deferred();
- def.promise.catch(function() {});
- def.reject(error);
- return def.promise;
- },
- throwCustomError: function(ctx, serverCall) {
- function CustomError(message) {
- Error.call(this);
- this.name = 'CustomError';
- this.message = message;
- this.stack = (new Error()).stack;
- }
- CustomError.prototype = new Error();
- CustomError.prototype.constructor = CustomError;
-
- throw new CustomError(message);
- }
- };
- var dispatcher = leafDispatcher(errorThrower);
- var methods = Object.keys(errorThrower);
-
- methods.forEach(function(method) {
- test('Test returning errors of type error() - ' +
- method + '(callback)', function(assert) {
-
- serve('js/errorThrower/' + method, dispatcher, function(err, res) {
- if (err) {
- return assert.end(err);
- }
-
- var ctx = res.runtime.getContext();
- res.service[method](ctx, function(err) {
- assert.ok(err, 'should error');
- assert.ok(err instanceof Error, 'should be Error');
- // TODO(jasoncampbell): The JS is missing support for server context
- // that would allow the error.message to be translated properly as it
- // travels through the supporting vanadium services. Currently the
- // message will be converted to "wsprd Root Error " after it goes out
- // over the wire and gets to the client. To resolve this we need to
- // make sure that the context (contains server name and operation)
- // and the params are sent along in error cases. So that the msg
- // string can be convert the template "{1} {2} Error {_}" into
- // something like "my-server my-method Error Error: my-error-message"
- //
- // SEE: v.io/v23/verror
- // assert.equal(err.message, message);
- assert.notEqual(err.stack, error.stack,
- 'the original stack should not be sent over the wire');
- res.end(assert);
- });
- });
- });
- });
-}
-
-function testNonStandardErrors() {
- var nonStandardErrorThrower = {
- throwString: function(ctx, serverCall) {
- throw message;
- },
- rejectPromiseWithString: function(ctx, serverCall) {
- var def = new Deferred();
- def.promise.catch(function() {});
- def.reject(message);
- return def.promise;
- },
- throwNull: function(ctx, serverCall) {
- throw null;
- },
- throwEmpty: function(ctx, serverCall) {
- throw '';
- },
- rejectNothing: function(ctx, serverCall) {
- var def = new Deferred();
- def.promise.catch(function() {});
- def.reject();
- return def.promise;
- },
- rejectNull: function(ctx, serverCall) {
- var def = new Deferred();
- def.promise.catch(function() {});
- def.reject(null);
- return def.promise;
- },
- rejectEmpty: function(ctx, serverCall) {
- var def = new Deferred();
- def.promise.catch(function() {});
- def.reject('');
- return def.promise;
- }
- };
- var dispatcher = leafDispatcher(nonStandardErrorThrower);
-
- Object.keys(nonStandardErrorThrower).forEach(function(method) {
- test('Test returning errors that are not of standard type error() - ' +
- method + '()', function(assert) {
-
- serve('js/thrower/' + method, dispatcher, function(err, res) {
- if (err) {
- return assert.end(err);
- }
-
- var ctx = res.runtime.getContext();
- res.service[method](ctx, function(err) {
- assert.ok(err, 'should error');
- assert.ok(err instanceof Error, 'should be Error');
- // TODO(jasoncampbell): Update once context and param support is
- // available in JS.
- //
- // SEE: test/integration/test-server-error.js:62
- // assert.equal(err.message, 'Unknown exception.');
- // TODO(bprosnitz) Change back to
- // assert.deepEquals(err.idAction, vanadium.errors.IdActions);
- assert.ok(err instanceof vanadium.verror.UnknownError,
- 'error ids match');
- assert.ok(err.stack, 'error has a stack');
- res.end(assert);
- });
- });
- });
- });
-}
diff --git a/test/integration/test-server-glob.js b/test/integration/test-server-glob.js
deleted file mode 100644
index f91bcc9..0000000
--- a/test/integration/test-server-glob.js
+++ /dev/null
@@ -1,317 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var serve = require('./serve');
-var Promise = require('../../src/lib/promise');
-var vanadium = require('../../');
-var naming = vanadium.naming;
-var verror = vanadium.verror;
-
-var ALBUMS = [
- 'public',
- 'public/2014',
- 'public/2014/california',
- 'public/2014/california/los-angeles',
- 'public/2014/california/san-francisco',
- 'public/2014/california/san-francisco/golden-gate',
- 'public/2014/newyork',
- 'public/2014/newyork/nyc',
- 'public/2014/newyork/nyc/empire-state',
- 'public/2015',
- 'private',
- 'private/2013',
- 'private/2013/california',
- 'private/2013/california/wedding',
- 'private/2013/california/wedding/reception'
-];
-
-function Directory() {
- this.children = {};
-}
-
-Directory.prototype._addChild = function(name, node) {
- this.children[name] = node;
-};
-
-Directory.prototype.__globChildren = function(ctx, serverCall, $stream) {
- Object.keys(this.children).forEach(function(child) {
- $stream.write(child);
- });
-};
-
-function createNodes(files) {
- var root = new Directory();
- for (var i = 0; i < files.length; i++) {
- var path = files[i].split('/');
- var currentNode = root;
- for (var j = 0; j < path.length; j++) {
- var component = path[j];
- var node = currentNode.children[component];
- // Add this element if it doesn't exist.
- if (!node) {
- node = new Directory();
- currentNode._addChild(component, node);
- }
- currentNode = node;
- }
- }
- return root;
-}
-
-function createAuthorizer(disallowed) {
- return function(ctx, call) {
- for (var i = 0; i < disallowed.length; i++) {
- if (call.suffix === disallowed[i]) {
- return new Error('disallowed');
- }
- }
- return;
- };
-}
-
-function createDispatcher(root, disallowed) {
- return function(suffix) {
- var auth;
- if (disallowed) {
- auth = createAuthorizer(disallowed);
- }
- if (suffix === '') {
- return {
- service: root,
- authorizer: auth
- };
- }
- var path = suffix.split('/');
- var current = root;
- for (var i = 0; i < path.length; i++) {
- current = current.children[path[i]];
- if (!current) {
- return Promise.reject(new Error('not found'));
- }
- }
- return Promise.resolve({
- service: current,
- authorizer: auth
- });
- };
-}
-
-function runChildrenGlobTest(pattern, expectedResults, disallowed, assert) {
- runGlobTest(pattern, expectedResults,
- createDispatcher(createNodes(ALBUMS), disallowed),
- disallowed,
- assert);
-}
-
-function runGlobTest(pattern, expectedResults, dispatcher, expectedErrors,
- assert) {
- serve({
- name: 'testGlob',
- autoBind: false,
- dispatcher: dispatcher
- }, function(err, res) {
- if (err) {
- return assert.end(err);
- }
-
- var namespace = res.runtime.getNamespace();
- var ctx = res.runtime.getContext();
- var globRPC = namespace.glob(ctx, pattern);
- var stream = globRPC.stream;
- var globResults = [];
- var globErrors = [];
- var hadErrors = false;
- stream.on('data', function(mountPoint) {
- globResults.push(mountPoint.name);
- });
-
- stream.on('error', function(errItem) {
- hadErrors = true;
- assert.ok(errItem.error instanceof Error);
- assert.ok(typeof errItem.name === 'string');
-
- // The tests are setup to error based on name, which is this glob error.
- assert.ok(errItem.error instanceof verror.NoServersError);
- globErrors.push(errItem.name);
- });
-
- stream.on('end', function() {
- globResults.sort();
- expectedResults.sort();
- assert.deepEqual(globResults, expectedResults);
- if (expectedErrors) {
- globErrors.sort();
- expectedErrors.sort();
- assert.deepEqual(globErrors, expectedErrors);
- assert.ok(hadErrors, 'expected to have errors on the stream');
- } else {
- assert.notOk(hadErrors, 'expected not to have errors on the stream');
- }
- res.end(assert);
- });
-
- });
-}
-
-test('Test globbing all descendants of root - GlobChildren - ' +
- 'glob(testGlob/...)', function(assert) {
- var expectedResults = ALBUMS.map(function(s) { return 'testGlob/' + s; });
- // We need to push testGlob twice because we get one entry from the
- // mountable and the next entry from the glob method. This is expected
- // behavior.
- expectedResults.push('testGlob');
- expectedResults.push('testGlob');
- expectedResults.sort();
- runChildrenGlobTest('testGlob/...', expectedResults, null, assert);
-});
-
-test('Test globbing all descendants of a child - GlobChildren - ' +
- ' glob(testGlob/private/...)',
- function(assert) {
- var expectedResults = [
- 'testGlob/private',
- 'testGlob/private/2013',
- 'testGlob/private/2013/california',
- 'testGlob/private/2013/california/wedding',
- 'testGlob/private/2013/california/wedding/reception',
- ];
- runChildrenGlobTest('testGlob/private/...', expectedResults, null, assert);
-});
-
-test('Test globbing children of root - GlobChildren - glob(testGlob/*)',
- function(assert) {
- var expectedResults = [
- 'testGlob/private',
- 'testGlob/public',
- ];
- runChildrenGlobTest('testGlob/*', expectedResults, null, assert);
-});
-
-test('Test globbing pattern testGlob/*/*/california - GlobChildren',
- function(assert) {
- var expectedResults = [
- 'testGlob/private/2013/california',
- 'testGlob/public/2014/california',
- ];
- runChildrenGlobTest('testGlob/*/*/california', expectedResults, null, assert);
-});
-
-test('Test globbing pattern testGlob/*/20*/california/... - GlobChildren',
- function(assert) {
- var expectedResults = [
- 'testGlob/private/2013/california',
- 'testGlob/private/2013/california/wedding',
- 'testGlob/private/2013/california/wedding/reception',
- 'testGlob/public/2014/california',
- 'testGlob/public/2014/california/los-angeles',
- 'testGlob/public/2014/california/san-francisco',
- 'testGlob/public/2014/california/san-francisco/golden-gate',
- ];
- runChildrenGlobTest('testGlob/*/20*/california/...', expectedResults, null,
- assert);
-});
-
-test('Test globbing a partially restricted namespace - GlobChildren -' +
- ' testGlob/private is restricted', function(assert) {
- var expectedResults = [
- 'testGlob',
- 'testGlob',
- 'testGlob/public',
- 'testGlob/public/2014',
- 'testGlob/public/2014/california',
- 'testGlob/public/2014/california/los-angeles',
- 'testGlob/public/2014/california/san-francisco',
- 'testGlob/public/2014/california/san-francisco/golden-gate',
- 'testGlob/public/2014/newyork',
- 'testGlob/public/2014/newyork/nyc',
- 'testGlob/public/2014/newyork/nyc/empire-state',
- 'testGlob/public/2015'
- ];
-
- var restrictedNames = ['private'];
- runChildrenGlobTest('testGlob/...', expectedResults, restrictedNames, assert);
-});
-
-test('Test globbing a fully restricted namespace - GlobChildren -' +
- ' all children of root are restricted', function(assert) {
- var expectedResults = [
- 'testGlob',
- 'testGlob'
- ];
- var restrictedNames = ['private', 'public'];
- runChildrenGlobTest('testGlob/...', expectedResults, restrictedNames, assert);
-});
-
-function FullGlobber() {
-}
-
-FullGlobber.prototype.__glob = function(ctx, serverCall, glob, $stream) {
- var mountEntry = new naming.MountEntry({
- name: naming.join(serverCall.securityCall.suffix, glob),
- });
- $stream.write(new naming.GlobReply({
- entry: mountEntry
- }));
-};
-
-test('Test globbing all descendants of root - FullGlobber - glob(testGlob/...)',
- function(assert) {
- var expectedResults = [
- 'testGlob',
- 'testGlob/...',
- ];
- function dispatcher(suffix) {
- return {
- service: new FullGlobber(),
- };
- }
- runGlobTest('testGlob/...', expectedResults, dispatcher, null, assert);
-});
-
-test('Test globbing all descendants of a child - FullGlobber - ' +
- 'glob(testGlob/bar/...)', function(assert) {
- var expectedResults = [
- 'testGlob/bar/...',
- ];
- function dispatcher(suffix) {
- return {
- service: new FullGlobber(),
- };
- }
- runGlobTest('testGlob/bar/...', expectedResults, dispatcher, null, assert);
-});
-
-
-function ChildGlobber(children) {
- this.children = children;
-}
-
-ChildGlobber.prototype.__globChildren = function(ctx, $stream) {
- for (var i = 0; i < this.children.length; i++) {
- $stream.write(this.children[i]);
- }
-};
-
-test('Test mixing GlobChildren and FullGlobber', function(assert) {
- var expectedResults = [
- 'testGlob/foo/bar/baz',
- ];
-
- function dispatcher(suffix) {
- var service;
- if (suffix === '') {
- service = new ChildGlobber(['foo', 'bar']);
- } else if (suffix === 'foo') {
- service = new FullGlobber();
- } else {
- service = new ChildGlobber([]);
- }
- return {
- service: service,
- };
- }
- runGlobTest('testGlob/foo/bar/baz', expectedResults, dispatcher, null,
- assert);
-});
diff --git a/test/integration/test-server-option.js b/test/integration/test-server-option.js
deleted file mode 100644
index ddcf6c8..0000000
--- a/test/integration/test-server-option.js
+++ /dev/null
@@ -1,165 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var vanadium = require('../../');
-var serve = require('./serve');
-
-function dispatcher(suffix) {
- return {
- service: function(ctx, serverCall) {
- throw new Error('NotImplemented');
- },
- authorizer: function(ctx, call) {
- return null;
- }
- };
-}
-
-test('Test IsLeaf=True Server Option', function(t) {
- var serverOption = vanadium.rpc.serverOption({
- isLeaf: true
- });
- var name = 'testing/serverOption/isLeafTrue';
-
- var servObj = {
- name: name,
- dispatcher: dispatcher,
- serverOption: serverOption
- };
-
- serve(servObj, function(err, res) {
- t.error(err);
-
- var rt = res.runtime;
- var ns = rt.getNamespace();
- var stream = ns.glob(rt.getContext(), name).stream;
- stream.on('data', function(mp) {
- t.error(err);
-
- t.equal(mp.isLeaf, true, 'Glob must indicate server is a leaf');
- t.equal(mp.servesMountTable, false,
- 'Glob must indicate server is not a mounttable');
- res.end(t);
- });
- });
-});
-
-test('Test IsLeaf=False Server Option', function(t) {
- var serverOption = vanadium.rpc.serverOption({
- isLeaf: false
- });
- var name = 'testing/serverOption/isLeafFalse';
-
- var servObj = {
- name: name,
- dispatcher: dispatcher,
- serverOption: serverOption
- };
-
- serve(servObj, function(err, res) {
- t.error(err);
-
- var rt = res.runtime;
- var ns = rt.getNamespace();
- var stream = ns.glob(rt.getContext(), name).stream;
- stream.on('data', function(mp) {
- t.error(err);
-
- t.equal(mp.isLeaf, false, 'Glob must indicate server is not a leaf');
- t.equal(mp.servesMountTable, false,
- 'Glob must indicate server is not a mounttable');
- res.end(t);
- });
- });
-});
-
-//test('Test ServesMountTable=True Server Option', function(t) {
-// var serverOption = vanadium.rpc.serverOption({
-// servesMountTable: true
-// });
-// var name = 'testing/serverOption/ServesMountTableTrue';
-//
-// var servObj = {
-// name: name,
-// dispatcher: dispatcher,
-// serverOption: serverOption
-// };
-//
-// serve(servObj, function(err, res) {
-// t.error(err);
-//
-// var rt = res.runtime;
-// var ns = rt.getNamespace();
-// var stream = ns.glob(rt.getContext(), name).stream;
-// stream.on('data', function(mp) {
-// t.error(err);
-//
-// t.equal(mp.isLeaf, false, 'Glob must indicate server is not a leaf');
-// t.equal(mp.servesMountTable, true,
-// 'Glob must indicate server is a mounttable');
-// res.end(t);
-// });
-// });
-//});
-
-test('Test ServesMountTable=false server option', function(t) {
- var serverOption = vanadium.rpc.serverOption({
- servesMountTable: false
- });
- var name = 'testing/serverOption/ServesMountTableFalse';
-
- var servObj = {
- name: name,
- dispatcher: dispatcher,
- serverOption: serverOption
- };
-
- serve(servObj, function(err, res) {
- t.error(err);
-
- var rt = res.runtime;
- var ns = rt.getNamespace();
- var stream = ns.glob(rt.getContext(), name).stream;
- stream.on('data', function(mp) {
- t.error(err);
-
- t.equal(mp.isLeaf, false, 'Glob must indicate server is not a leaf');
- t.equal(mp.servesMountTable, false,
- 'Glob must indicate server is not a mounttable');
- res.end(t);
- });
- });
-});
-
-//test('Test ServesMountTable=ture and IsLeaf=true server option',
-// function(t) {
-// var serverOption = vanadium.rpc.serverOption({
-// servesMountTable: true,
-// isLeaf: true
-// });
-// var name = 'testing/serverOption/Both';
-//
-// var servObj = {
-// name: name,
-// dispatcher: dispatcher,
-// serverOption: serverOption
-// };
-//
-// serve(servObj, function(err, res) {
-// t.error(err);
-//
-// var rt = res.runtime;
-// var ns = rt.getNamespace();
-// var stream = ns.glob(rt.getContext(), name).stream;
-// stream.on('data', function(mp) {
-// t.error(err);
-//
-// t.equal(mp.isLeaf, true, 'Glob must indicate server is a leaf');
-// t.equal(mp.servesMountTable, true,
-// 'Glob must indicate server is a mounttable');
-// res.end(t);
-// });
-// });
-// });
\ No newline at end of file
diff --git a/test/integration/test-server-stop.js b/test/integration/test-server-stop.js
deleted file mode 100644
index 118ffd6..0000000
--- a/test/integration/test-server-stop.js
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var serve = require('./serve');
-var leafDispatcher = require('../../src/rpc/leaf-dispatcher');
-var dispatcher = leafDispatcher({
- foo: function(ctx, serverCall) {
- return 'bar';
- }
-});
-var name = 'my-test/service';
-
-test('Test stopping a JS service - ' +
- 'server.stop(callback)', function(assert) {
- serve(name, dispatcher, function(err, res) {
- assert.error(err);
-
- res.server.stop(function(err) {
- assert.error(err);
-
- var ctx = res.runtime.getContext().withTimeout(100);
- res.service.foo(ctx, function(err, result) {
- assert.ok(err, 'should fail');
- res.end(assert);
- });
- });
- });
-});
-
-
-test('Test stopping a JS service - ' +
- 'var promise = server.stop()', function(assert) {
- serve(name, dispatcher, function(err, res) {
- assert.error(err);
-
- var ctx = res.runtime.getContext().withTimeout(100);
- res.server.stop()
- .then(function() {
- return res.service.foo(ctx);
- })
- .then(function() {
- assert.fail('should not succeed');
- res.end(assert);
- }, function(err) {
- assert.ok(err, 'should fail');
- res.end(assert);
- })
- .catch(function(err) {
- assert.error(err);
- res.end(assert);
- });
- });
-});
-
-test('Test stopping a JS service twice - ' +
- 'server.stop(callback)', function(assert) {
- serve(name, dispatcher, function(err, res) {
- assert.error(err);
-
- res.server.stop(function(err) {
- assert.error(err);
-
- res.server.stop(function(err) {
- assert.error(err);
- res.end(assert);
- });
- });
- });
-});
diff --git a/test/integration/test-service-cache.js b/test/integration/test-service-cache.js
deleted file mode 100644
index de12003..0000000
--- a/test/integration/test-service-cache.js
+++ /dev/null
@@ -1,271 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var vanadium = require('../../');
-var NoExistError = vanadium.verror.NoExistError;
-var config = require('./default-config');
-var service = require('./get-service');
-var Promise = require('../../src/lib/promise');
-
-test('Test set() of Go sample cache service - ' +
- 'cache.set(key, value, callback)', function(assert) {
- service('test_service/cache', function(err, ctx, cache, end) {
- assert.error(err);
- if (err) {
- return end(assert);
- }
-
- cache.set(ctx, 'foo', 'bar', function(err, result) {
- assert.error(err);
- end(assert);
- });
- });
-});
-
-test('Test set() of Go sample cache service - ' +
- 'var promise = cache.set(key, value)', function(assert) {
- service('test_service/cache', function(err, ctx, cache, end) {
- assert.error(err);
- if (err) {
- return end(assert);
- }
-
- cache.set(ctx, 'foo', 'bar')
- .then(function() {
- end(assert);
- }, function(err) {
- assert.err(err);
- end(assert);
- });
- });
-});
-
-test('Test get() of Go sample cache service - ' +
- 'cache.get(key, value, callback)', function(assert) {
- service('test_service/cache', function(err, ctx, cache, end) {
- assert.error(err);
- if (err) {
- return end(assert);
- }
-
- cache.set(ctx, 'baz', 'qux', function(err, result) {
- assert.error(err);
-
- cache.get(ctx, 'baz', function(err, value) {
- assert.error(err);
- assert.equal(value, 'qux');
- end(assert);
- });
- });
- });
-});
-
-test('Test get() of Go sample cache service - ' +
- 'var promise = cache.get(key, value)', function(assert) {
- service('test_service/cache', function(err, ctx, cache, end) {
- assert.error(err);
- if (err) {
- return end(assert);
- }
-
- cache.set(ctx, 'baz', 'qux')
- .then(function() {
- return cache.get(ctx, 'baz');
- })
- .then(function(value) {
- assert.equal(value, 'qux');
- end(assert);
- })
- .catch(function(err) {
- // I dont think this does what I think it does
- assert.error(err);
- end(assert);
- });
- });
-});
-
-test('Test get() with invalid key of Go sample cache service - ' +
- 'cache.get(key, value, callback)', function(assert) {
- service('test_service/cache', function(err, ctx, cache, end) {
- assert.error(err);
- if (err) {
- return end(assert);
- }
-
- cache.get(ctx, 'is not a thing', function(err, value) {
- assert.ok(err instanceof NoExistError, 'should error');
- assert.ok(err.message, 'test_serviced:"cache".Get: ' +
- 'Does not exist: is not a thing');
- end(assert);
- });
- });
-});
-
-test('Test get() with invalid key of Go sample cache service - ' +
- 'var promise = cache.get(key, value) - failure', function(assert) {
- service('test_service/cache', function(err, ctx, cache, end) {
- assert.error(err);
- if (err) {
- return end(assert);
- }
-
- cache
- .get(ctx, 'really not a thing')
- .then(function() {
- assert.fail('should not succeed');
- end(assert);
- })
- .catch(function(err) {
- assert.ok(err instanceof NoExistError, 'should error');
- assert.ok(err.message, 'test_serviced:"cache".Get: ' +
- 'Does not exist: really not a thing');
- end(assert);
- });
- });
-});
-
-test('Test calling a non-existing method of Go sample cache service - ' +
- 'cache.badMethod()', function(assert) {
- service('test_service/cache', function(err, ctx, cache, end) {
- assert.error(err);
- if (err) {
- return end(assert);
- }
-
- assert.throws(function() {
- // The cache stub doesn't have this method.
- cache.notEvenAThing('whatever');
- });
-
- end(assert);
- });
-});
-
-test('Test multiGet() streaming method of Go sample cache service - ' +
- 'var stream = cache.multiGet().stream', function(assert) {
- service('test_service/cache', function(err, ctx, cache, end) {
- assert.error(err);
- if (err) {
- return end(assert);
- }
-
- // `cache.mutliGet()` returns an object that has a "stream" attribute.
- // The way the streaming interface is implmented for cache.mutliGet()
- // is that you use stream.write(key) to get the value of a key. The value
- // is emitted on the stream's data event. In this test there are a few
- // steps to set this up:
- //
- // * Prime the cache by setting a bunch of key/values
- // * Add a listener or create a stream reader to recieve the values
- // * Assert the values are correct
- // * End the stream.
-
- // Build a map of items
- var items = {};
- for (var i = 0; i < 10; ++i) {
- items[i] = {
- key: i,
- value: 'next value: ' + i
- };
- }
-
- // Add them to the cache
- var jobs = Object.keys(items).map(function(key) {
- return cache.set(ctx, key, JSON.stringify(items[key]));
- });
-
- Promise
- .all(jobs)
- .then(function() {
- var promise = cache.multiGet(ctx);
- var stream = promise.stream;
-
- // Error handling boilerplate
- promise.catch(error);
- stream.on('error', error);
-
- // "data" event emits cached values
- stream.on('data', function(value) {
- var string = value.toString();
- var json = JSON.parse(string);
- var actual = json.value;
- var expected = items[json.key].value;
-
- assert.equal(actual, expected);
- });
-
- stream.on('end', function() {
- end(assert);
- });
-
- Object.keys(items).forEach(function(key) {
- stream.write(key);
- });
-
- stream.end();
- });
-
- function error(err) {
- assert.error(err);
- end(assert);
- }
- });
-});
-
-test('Test getting signature of Go sample cache service - ' +
- 'var promise = client.signature(ctx, test_service/cache)', function(assert) {
- vanadium.init(config)
- .then(function(runtime) {
- var ctx = runtime.getContext();
- var client = runtime.getClient();
- client.signature(ctx, 'test_service/cache')
- .then(function(sigs) {
- assert.ok(sigs, 'received something');
- assert.ok(Array.isArray(sigs), 'receives a signature array');
- runtime.close(assert.end);
- }).catch(function(err) {
- assert.error(err);
- runtime.close(assert.end);
- });
- }).catch(assert.end);
-});
-
-test('Test getting signature of Go sample cache service - ' +
- 'client.signature(ctx, test_service/cache, callback)', function(assert) {
- vanadium.init(config, function(err, runtime) {
- if(err) {
- assert.end(err);
- }
-
- var ctx = runtime.getContext();
- var client = runtime.getClient();
- client.signature(ctx, 'test_service/cache', function(err, sigs) {
- assert.error(err);
- assert.ok(sigs, 'received something');
- assert.ok(Array.isArray(sigs), 'receives a signature array');
- runtime.close(assert.end);
- });
- });
-});
-
-test('Test a streaming method timing out - ' +
- 'var promise = cache.multiGet(shortTimeout)', function(assert) {
- service('test_service/cache', function(err, ctx, cache, end) {
- assert.error(err);
- if (err) {
- return end(assert);
- }
-
- var shortCtx = ctx.withTimeout(10); // very short timeout
- var promise = cache.multiGet(shortCtx); // streaming method
- promise.then(function success() {
- assert.fail('Should have timedout and errored but succeeded');
- end(assert);
- }, function error() {
- assert.pass('Steaming method timedout correctly');
- end(assert);
- });
- });
-});
diff --git a/test/integration/test-service-errors.js b/test/integration/test-service-errors.js
deleted file mode 100644
index 1e6f31e..0000000
--- a/test/integration/test-service-errors.js
+++ /dev/null
@@ -1,153 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var vanadium = require('../../');
-var service = require('./get-service');
-var verror = vanadium.verror;
-var VanadiumError = verror.VanadiumError;
-
-test('Test Go service returning Aborted error - ' +
- 'errorThrower.method(callback)', function(assert) {
- service('test_service/errorThrower', function(err, ctx, errorThrower, end) {
- assert.error(err);
-
- errorThrower.throwAborted(ctx, function(err) {
- assert.ok(err, 'should error');
- assert.ok(err.message.indexOf('Aborted') !== -1);
- assert.ok(err instanceof verror.AbortedError, 'should be AbortedError');
- end(assert);
- });
- });
-});
-
-test('Test Go service returning BadArg error - ' +
- 'errorThrower.method(callback)', function(assert) {
- service('test_service/errorThrower', function(err, ctx, errorThrower, end) {
- assert.error(err);
-
- errorThrower.throwBadArg(ctx, function(err) {
- assert.ok(err, 'should error');
- assert.ok(err.message.indexOf('Bad argument') !== -1);
- assert.ok(err instanceof verror.BadArgError, 'should be BadArgError');
- end(assert);
- });
- });
-});
-
-test('Test Go service returning BadProtocol error - ' +
- 'errorThrower.method(callback)', function(assert) {
- service('test_service/errorThrower', function(err, ctx, errorThrower, end) {
- assert.error(err);
-
- errorThrower.throwBadProtocol(ctx, function(err) {
- assert.ok(err, 'should error');
- assert.ok(err.message.indexOf('Bad protocol') !== -1);
- assert.ok(err instanceof verror.BadProtocolError,
- 'should be BadProtocolError');
- end(assert);
- });
- });
-});
-
-test('Test Go service returning Internal error - ' +
- 'errorThrower.method(callback)', function(assert) {
- service('test_service/errorThrower', function(err, ctx, errorThrower, end) {
- assert.error(err);
-
- errorThrower.throwInternal(ctx, function(err) {
- assert.ok(err, 'should error');
- assert.ok(err.message.indexOf('Internal error') !== -1);
- assert.ok(err instanceof verror.InternalError,
- 'should be InternalError');
- end(assert);
- });
- });
-});
-
-test('Test Go service returning NoAccess error - ' +
- 'errorThrower.method(callback)', function(assert) {
- service('test_service/errorThrower', function(err, ctx, errorThrower, end) {
- assert.error(err);
-
- errorThrower.throwNoAccess(ctx, function(err) {
- assert.ok(err, 'should error');
- assert.ok(err.message.indexOf('Access denied') !== -1);
- assert.ok(err instanceof verror.NoAccessError,
- 'should be NoAccessError');
- end(assert);
- });
- });
-});
-
-test('Test Go service returning NoExist error - ' +
- 'errorThrower.method(callback)', function(assert) {
- service('test_service/errorThrower', function(err, ctx, errorThrower, end) {
- assert.error(err);
-
- errorThrower.throwNoExist(ctx, function(err) {
- assert.ok(err, 'should error');
- assert.ok(err.message.indexOf('Does not exist') !== -1);
- assert.ok(err instanceof verror.NoExistError, 'should be NoExistError');
- end(assert);
- });
- });
-});
-
-test('Test Go service returning NoExistOrNoAccess error - ' +
- 'errorThrower.method(callback)', function(assert) {
- service('test_service/errorThrower', function(err, ctx, errorThrower, end) {
- assert.error(err);
-
- errorThrower.throwNoExistOrNoAccess(ctx, function(err) {
- assert.ok(err, 'should error');
- assert.ok(err.message.indexOf('Does not exist or access denied') !== -1);
- assert.ok(err instanceof verror.NoExistOrNoAccessError,
- 'should be NoExistOrNoAccess');
- end(assert);
- });
- });
-});
-
-test('Test Go service returning Unknown error - ' +
- 'errorThrower.method(callback)', function(assert) {
- service('test_service/errorThrower', function(err, ctx, errorThrower, end) {
- assert.error(err);
-
- errorThrower.throwUnknown(ctx, function(err) {
- assert.ok(err, 'should error');
- assert.ok(err.message.indexOf('Error') !== -1);
- assert.ok(err instanceof VanadiumError, 'should be VanadiumError');
- end(assert);
- });
- });
-});
-
-test('Test Go service returning GoError error - ' +
- 'errorThrower.method(callback)', function(assert) {
- service('test_service/errorThrower', function(err, ctx, errorThrower, end) {
- assert.error(err);
-
- errorThrower.throwGoError(ctx, function(err) {
- assert.ok(err, 'should error');
- assert.ok(err.message.indexOf('GoError!') !== -1);
- assert.ok(err instanceof VanadiumError, 'should be VanadiumError');
- end(assert);
- });
- });
-});
-
-test('Test Go service returning CustomStandard error - ' +
- 'errorThrower.method(callback)', function(assert) {
- service('test_service/errorThrower', function(err, ctx, errorThrower, end) {
- assert.error(err);
-
- errorThrower.throwCustomStandardError(ctx, function(err) {
- assert.ok(err, 'should error');
- assert.ok(err.message.indexOf('CustomStandard!') !== -1);
- assert.ok(err instanceof VanadiumError, 'should be VanadiumError');
- end(assert);
- });
- });
-});
diff --git a/test/integration/test-service-native.js b/test/integration/test-service-native.js
deleted file mode 100644
index 242ee53..0000000
--- a/test/integration/test-service-native.js
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var vanadium = require('../../');
-var service = require('./get-service');
-var makeError = vanadium.verror.makeError;
-var actions = vanadium.verror.actions;
-
-var E = makeError('randomPrefix.verror', actions.NO_RETRY,
- '{1} {2}: RandomError: {_}');
-
-test('Test PassTime of Go native service', function(assert) {
- service('test_service/native', function(err, ctx, native, end) {
- assert.error(err);
- if (err) {
- return end(assert);
- }
- var now = new Date();
- native.passTime(ctx, now, function(err, result) {
- assert.error(err);
- assert.ok(result instanceof Date, 'native type is returned');
- var diff = Math.abs(result - now);
- // It might be ok to do an equals on the two date objects but because
- // Numbers are floating point and there is some amount of math to do
- // the conversion, === on these dates might not be true even when the
- // dates are really the same.
- assert.ok(diff < 1);
- end(assert);
- });
- });
-});
-
-test('Test PassError of Go native service', function(assert) {
- service('test_service/native', function(err, ctx, native, end) {
- assert.error(err);
- if (err) {
- return end(assert);
- }
- var e = new E(null, 'extra string', 4, false);
- var expectedMessage = 'app op: RandomError: extra string 4 false';
- native.passError(ctx, e, function(err, result) {
- // Bluebird adds __stackCleaned__ as part of its processing but it
- // doesn't show up in the vom decoded message, so we can't do a
- // deepEqual.
- assert.equal(e.id, err.id);
- assert.equal(e.retryCode, err.retryCode);
- assert.equal(e.msg, err.msg);
- assert.equal(e.message, err.message);
- assert.equal(e.msg, expectedMessage);
- assert.equal(e.message, expectedMessage);
- // The decoded error has the paramList values wrapped, since the
- // paramList is a list of any. The error passed into the call
- // does not have that wrapping. We add the wrapping to e to make sure
- // the decoded error has the wrapped paramlist.
- // Note: 'extra string', 4, and false are native values. They would
- // normally be converted to JSValue since the paramList is []any. However,
- // they are specifically guessed to be string, number, and bool in order
- // to avoid revealing JSValue to other languages in the common case.
- // https://github.com/veyron/release-issues/issues/1560
- e.paramList = e.paramList.map(function (v) { return { val: v }; });
- assert.deepEqual(e.paramList, err.paramList);
- end(assert);
- });
- });
-});
diff --git a/test/integration/test-vanadium-init.js b/test/integration/test-vanadium-init.js
deleted file mode 100644
index 23c6509..0000000
--- a/test/integration/test-vanadium-init.js
+++ /dev/null
@@ -1,226 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var extend = require('xtend');
-var isBrowser = require('is-browser');
-var parallel = require('run-parallel');
-var test = require('prova');
-
-var config = require('./default-config');
-var vanadium = require('../../');
-
-test('Test vanadium.init({authenticate: true}) gives runtime with account name',
- function(t) {
-
- var c = extend({authenticate: true}, config);
-
- vanadium.init(c, function(err, rt) {
- if (!isBrowser) {
- t.ok(err, 'should error in node');
- return t.end();
- }
-
- if (err) {
- t.error(err);
- return t.end(err);
- }
-
- t.ok(rt, 'runtime exists');
- t.ok(rt.accountName, 'runtime has accountName property');
- t.ok(typeof rt.accountName === 'string', 'rt.accountName is string');
- t.ok(rt.accountName.length > 0, 'rt.accountName has length > 0');
- t.end();
- });
-});
-
-test('Test vanadium.init({authenticate: true}) twice gives two runtimes',
- function(t) {
-
- if (!isBrowser) {
- return t.end();
- }
-
- var c = extend({authenticate: true}, config);
-
- function vanadiumInit(cb) {
- vanadium.init(c, cb);
- }
-
- parallel([vanadiumInit, vanadiumInit], function(err, runtimes) {
- if (err) {
- t.error(err);
- t.end();
- return;
- }
-
- runtimes.forEach(function(rt) {
- t.ok(rt, 'runtime exists');
- t.ok(rt.accountName, 'runtime has accountName property');
- t.ok(typeof rt.accountName === 'string', 'rt.accountName is string');
- t.ok(rt.accountName.length > 0, 'rt.accountName has length > 0');
- });
-
- t.end();
- });
-});
-
-test('Test config logLevel INFO sets the vlog logLevel', function(t) {
- var c = extend({logLevel: vanadium.vlog.levels.INFO }, config);
-
- vanadium.init(c, function(err, rt) {
- if (err) {
- t.error(err);
- return t.end(err);
- }
-
- t.equal(vanadium.vlog.logger.level, vanadium.vlog.levels.INFO);
- rt.close(t.end);
- });
-});
-
-test('Test config logLevel ERROR sets the vlog logLevel', function(t) {
- var c = extend({logLevel: vanadium.vlog.levels.ERROR }, config);
-
- vanadium.init(c, function(err, rt) {
- if (err) {
- t.error(err);
- return t.end(err);
- }
-
- t.equal(vanadium.vlog.logger.level, vanadium.vlog.levels.ERROR);
- rt.close(t.end);
- });
-});
-
-test('Test vanadium.init({authenticate: false}) gives runtime ' +
- 'with unknown name', function(t) {
-
- var c = extend({authenticate: false}, config);
-
- vanadium.init(c, function(err, rt) {
- if (err) {
- t.error(err);
- return t.end(err);
- }
-
- t.ok(rt, 'runtime exists');
- t.equal(rt.accountName, 'unknown', 'rt.accountName is "unknown"');
- rt.close(t.end);
- });
-});
-
-test('Test passing namespaceRoots to vanadium.init() sets the namespaceRoots',
- function(t) {
-
- var roots = ['/some-root.tld:1234', '/other-root.tld:80'];
-
- var c = extend({namespaceRoots: roots}, config);
-
- vanadium.init(c, function(err, rt) {
- if (!isBrowser) {
- t.ok(err, 'should error in node');
- return t.end();
- }
-
- if (err) {
- t.error(err, 'should not error');
- return t.end();
- }
-
- rt.getNamespace().roots(function(err, gotRoots) {
- if (err) {
- t.error(err);
- return rt.close(t.end);
- }
-
- t.ok(gotRoots, 'runtime.namespace has roots');
- t.deepEqual(gotRoots.sort(), roots.sort(),
- 'runtime.namespace has the correct roots');
-
- rt.close(t.end);
- });
- });
-});
-
-// Helper that remounts a server at 'from' to a name 'to'.
-function remount(from, to, cb) {
- vanadium.init(config, function(err, rt) {
- if (err) {
- return cb(err);
- }
- var ns = rt.getNamespace();
- var ctx = rt.getContext().withTimeout(5000);
-
- ns.resolve(ctx, from, function(err, servers) {
- if (err) {
- return end(err);
- }
-
- ns.mount(ctx, to, servers[0], 0, false, end);
- });
-
- function end(err) {
- rt.close(function(){
- cb(err);
- });
- }
- });
-}
-
-test('Test passing proxy to vanadium.init() sets the proxy',
- function(t) {
-
- // Remount the proxy under a new name.
- var existingProxyName = 'test/proxy';
- var newProxyName = 'new/name/for/proxy';
-
- remount(existingProxyName, newProxyName, function(err) {
- if (err) {
- return t.end(err);
- }
-
- // Initialize a new runtime with the new proxy name.
- var c = extend({proxy: newProxyName}, config);
-
- vanadium.init(c, function(err, rt) {
- if (!isBrowser) {
- t.ok(err, 'should error in node');
- return t.end();
- }
-
- if (err) {
- t.error(err, 'should not error');
- return t.end();
- }
-
- // Create a new server, and verify that we can call it.
- var serverName = 'pingpong';
- var service = {
- ping: function(ctx, serverCall){
- return 'pong';
- }
- };
- rt.newServer(serverName, service, function(err) {
- if (err) {
- return end(err);
- }
-
- var client = rt.getClient();
- var ctx = rt.getContext().withTimeout(5000);
- client.bindTo(ctx, serverName, function(err, pingpong) {
- if (err) {
- return end(err);
- }
- t.ok(pingpong, 'bindTo returns the correct service');
- end(null);
- });
- });
-
- function end(err) {
- t.error(err);
- rt.close(t.end);
- }
- });
- });
-});
diff --git a/test/integration/test-vtrace.js b/test/integration/test-vtrace.js
deleted file mode 100644
index 6da7720..0000000
--- a/test/integration/test-vtrace.js
+++ /dev/null
@@ -1,97 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var test = require('prova');
-var service = require('./get-service');
-var vanadium = require('../../');
-var serve = require('./serve');
-var leafDispatcher = require('../../src/rpc/leaf-dispatcher');
-var vtrace = vanadium.vtrace;
-
-function findSpan(name, trace) {
- for (var i = 0; i < trace.spans.length; i++) {
- var span = trace.spans[i];
- if (span.name === name) {
- return span;
- }
- }
- return null;
-}
-
-test('Test receiving traces with a JavaScript client', function(assert) {
- service('test_service/cache', function(err, ctx, cache, end, runtime) {
- vtrace.forceCollect(ctx);
- if (err) {
- end(assert, err);
- }
- cache.set(ctx, 'key', 'val').then(function() {
- var span = vtrace.getSpan(ctx);
- var record = vtrace.getStore(ctx).traceRecord(span.trace);
- // We expect to see spans at least from:
- // The js client.
- assert.ok(findSpan('<jsclient>"test_service/cache".set', record));
- // The wspr proxy.
- assert.ok(findSpan('<wspr>"test_service/cache".Set', record));
- // The go server.
- assert.ok(findSpan('"cache".Set', record));
- end(assert);
- });
- });
-});
-
-test('Test using collectRegexp', function(assert) {
- service('test_service/cache', function(err, ctx, cache, end, runtime) {
- if (err) {
- end(assert, err);
- }
- var store = vtrace.getStore(ctx);
- store.setCollectRegexp('\.get$');
-
- var t1 = ctx;
- var t2 = vtrace.withNewTrace(ctx);
-
- cache.set(t1, 'key', 'val').then(function() {
- return cache.get(t2, 'key');
- }).then(function() {
- var records = store.traceRecords();
- assert.equals(records.length, 1);
- assert.ok(findSpan('"cache".Get', records[0]));
- end(assert);
- });
- });
-});
-
-var SpanService = {
- makeSpan: function(context, serverCall) {
- context = vtrace.withNewSpan(context, 'in makeSpan');
- vtrace.getSpan(context).finish();
- }
-};
-
-test('Test receiving traces from a javascript server', function(assert) {
- serve('testing/span', leafDispatcher(SpanService), function(err, res) {
- assert.error(err);
- var serverCtx = res.runtime.getContext();
-
- var clientCtx = vtrace.withNewStore(serverCtx);
- var trace = vtrace.getSpan(clientCtx).trace;
- vtrace.forceCollect(clientCtx);
- res.service.makeSpan(clientCtx).then(function() {
- var record = vtrace.getStore(clientCtx).traceRecord(trace);
- // We expect to see spans at least from:
- // The js client.
- assert.ok(findSpan('<jsclient>"testing/span".makeSpan', record));
- // The wspr proxy.
- assert.ok(findSpan('<wspr>"testing/span".MakeSpan', record));
- // The js server.
- assert.ok(findSpan('<jsserver>"".makeSpan', record));
- // A custom span.
- assert.ok(findSpan('in makeSpan', record));
- res.end(assert);
- }).catch(function(err) {
- assert.error(err);
- res.end(assert);
- });
- });
-});
diff --git a/test/integration/timeouts.js b/test/integration/timeouts.js
deleted file mode 100644
index 1cdcb5c..0000000
--- a/test/integration/timeouts.js
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-module.exports = {
- instant: 100,
- quick: 1 * 1000,
- short: 5 * 1000,
- standard: 10 * 1000,
- long: 60 * 1000,
- longer: 2 * 60 * 1000,
- max: 5 * 60 * 1000
-};
\ No newline at end of file
diff --git a/test/load/test-echo.js b/test/load/test-echo.js
deleted file mode 100644
index 2928052..0000000
--- a/test/load/test-echo.js
+++ /dev/null
@@ -1,103 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var service = require('../integration/get-service');
-var serve = require('../integration/serve');
-var Stress = require('../vdl-out/v.io/x/js.core/stress').Stress;
-var test = require('prova');
-
-test.timeout(60 * 5 * 1000);
-
-var PAYLOAD_SIZE = 1000;
-var DURATION = 1 * 60 * 1000;
-test('load test echo', function(assert) {
- service('/localhost:8141', function(err, ctx, echoer, end, rt) {
- assert.error(err);
- var payload = new Uint8Array(PAYLOAD_SIZE);
- for (var i = 0; i < PAYLOAD_SIZE; i++) {
- payload[i] = i && 0xff;
- }
- var iterations = 0;
- var start = Date.now();
- callEcho();
- function callEcho() {
- iterations++;
- if ((iterations % 500) === 0) {
- assert.ok(true, 'done with ' + iterations);
- }
- if ((Date.now() - start) > DURATION) {
- return finish();
- }
- echoer.echo(ctx, payload).then(callEcho).catch(finish);
- }
-
- function finish(err) {
- assert.error(err);
- var duration = (Date.now() - start) / 1000;
- var data = {
- qps: iterations/duration,
- iterations: iterations,
- };
- data.msecsPerRPC = 1000/data.qps;
- assert.ok(true, JSON.stringify(data));
- end(assert);
- }
- });
-});
-
-function Echoer() {}
-
-Echoer.prototype._serviceDescription = Stress.prototype._serviceDescription;
-
-Echoer.prototype.echo = function(ctx, serverCall, bytes) {
- return Promise.resolve(bytes);
-};
-
-var echoer = new Echoer();
-
-function alwaysAuth(ctx, call) {
- return Promise.resolve();
-}
-
-function dispatcher(suffix) {
- return {
- service: echoer,
- authorizer: alwaysAuth
- };
-}
-
-/*
- * The setup of this test is to have a JS server running under the name load
- * and then ask the Go stressd server to create a go client and run the
- * performance test against our server for DURATION milliseconds and return
- * the results
- */
-test('load test echo server', function(assert) {
- var opts = {
- name: 'load',
- dispatcher: dispatcher,
- autoBind: false,
- };
- serve(opts, function(err, res) {
- assert.error(err);
- if (err) {
- res.end(assert);
- }
- // In order to run a performance test where we have a go client send
- // a bunch of tests to the server, we tell the stressd server to run
- // a peformance test against the server we just started.
- var client = res.runtime.getClient();
- var ctx = res.runtime.getContext();
- client.bindTo(ctx, '/localhost:8141').then(function(stub) {
- ctx = ctx.withTimeout(DURATION * 2);
- return stub.serverEcho(ctx, { seconds: DURATION / 1000 }, 'load');
- }).then(function(result) {
- result.iterations = result.iterations.toNativeNumberApprox();
- assert.ok(true, JSON.stringify(result));
- res.end(assert);
- }).catch(function(err) {
- res.end(assert, err);
- });
- });
-});
diff --git a/test/services/config-sampled.js b/test/services/config-sampled.js
deleted file mode 100644
index 69dde48..0000000
--- a/test/services/config-sampled.js
+++ /dev/null
@@ -1,7 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-module.exports = {
- flags: {}
-};
diff --git a/test/services/config-stressd.js b/test/services/config-stressd.js
deleted file mode 100644
index 7473093..0000000
--- a/test/services/config-stressd.js
+++ /dev/null
@@ -1,9 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-module.exports = {
- flags: {
- 'v23.tcp.address': ':8141'
- }
-};
diff --git a/test/services/run-services.js b/test/services/run-services.js
deleted file mode 100644
index 1b8166a..0000000
--- a/test/services/run-services.js
+++ /dev/null
@@ -1,182 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// TODO(sadovsky): Rename this file service-runner.js.
-
-var debug = require('debug')('run-services');
-var EE = require('events').EventEmitter;
-var extend = require('xtend');
-var inherits = require('util').inherits;
-var mkdirp = require('mkdirp');
-var parallel = require('run-parallel');
-var path = require('path');
-var service = require('./service');
-
-module.exports = Runner;
-
-/**
- * var runner = Runner(names=[])
- *
- * Emits: start, stop, error
- *
- * @param {Array} names of the vanadium services to run.
- * @returns {Runner}
- */
-function Runner(names) {
- if (!(this instanceof Runner)) {
- return new Runner(names);
- }
-
- // TODO(sadovsky): Make these fields private.
- var runner = this;
-
- EE.call(runner);
-
- // Env vars produced by servicerunner job. These are made visible to clients
- // in case they want to pass them to other subprocesses.
- runner.env = {};
-
- runner._names = names;
- runner._services = [];
-
- // Used to make start() and stop() idempotent.
- runner._startCalled = false;
- runner._stopCalled = false;
-}
-
-inherits(Runner, EE);
-
-Runner.prototype.start = function(cb) {
- var runner = this;
- if (runner._startCalled) {
- debug('warning: start called multiple times');
- return;
- }
- runner._startCalled = true;
-
- debug('starting core services...');
- runner._setup(function() {
- debug('core services ready; starting additional services...');
- var services = runner._names.map(runner._add.bind(runner));
- // Note, we don't map over runner._services because that includes
- // servicerunner.
- var jobs = services.map(createStartWorker);
- parallel(jobs, function(err) {
- debug('started all services');
- runner.emit('start');
- cb(err);
- });
- });
-
- return runner;
-};
-
-Runner.prototype._add = function(name) {
- var runner = this;
- var env = extend(process.env, runner.env);
- var s = service(name, env);
- s.on('error', function(err) {
- debug('error detected, stopping all services');
- runner.emit('error', err);
- runner.stop();
- });
- runner._services.push(s);
- return s;
-};
-
-// Creates a temporary directory for output, generates a principal, starts core
-// services (mount table, proxyd, wsprd), writes various vars to runner.env,
-// then calls cb.
-Runner.prototype._setup = function(cb) {
- var runner = this;
-
- mkdirp(path.resolve('tmp/log'), createCredentials);
-
- function createCredentials(err) {
- if (err) {
- return runner.emit('error', err);
- }
- runner.env.V23_CREDENTIALS = path.resolve('tmp/test-credentials');
- service('principal')
- .exec('create -with-passphrase=false -overwrite ' +
- runner.env.V23_CREDENTIALS + ' test',
- function(err, stdout, stderr) {
- if (err) {
- return runner.emit('error', err);
- }
- stdout.on('close', startCoreServices);
- });
- }
-
- function startCoreServices() {
- runner
- ._add('servicerunner')
- .on('vars', function(vars) {
- runner.env = extend(runner.env, {
- IDENTITYD: vars.TEST_IDENTITYD_NAME + '/google',
- IDENTITYD_BLESSING_URL:
- vars.TEST_IDENTITYD_HTTP_ADDR + '/auth/blessing-root',
- V23_NAMESPACE: vars.MT_NAME,
- PROXY_ADDR: vars.PROXY_NAME,
- WSPR_ADDR: vars.WSPR_ADDR
- });
- console.log('Tests running with environment: ', runner.env);
- })
- .on('ready', function() {
- debug('core services running');
- cb();
- })
- .spawn();
- }
-};
-
-Runner.prototype.stop = function(cb) {
-
- var runner = this;
- if (runner._stopCalled) {
- var errText = 'stop called multiple times';
- debug(errText);
- if (cb) {
- cb(new Error(errText));
- }
- return;
- }
- runner._stopCalled = true;
-
- cb = cb || function() {};
-
- debug('stopping...');
-
- // Remove all error listeners before killing any services so that services
- // don't complain when other services they depend on are shut down.
- runner._services.map(function(s) {
- s.removeAllListeners('error');
- });
-
- var jobs = runner._services.map(createStopWorker);
- parallel(jobs, function(err) {
- debug('stopped');
- runner.emit('stop');
- cb(err);
- });
-};
-
-function createStartWorker(service) {
- return function start(cb) {
- debug('spawning: %s', service.name);
- service.on('ready', function ready() {
- debug('ready: %s', service.name);
- cb();
- });
- service.spawn();
- };
-}
-
-function createStopWorker(service) {
- return function stop(cb) {
- debug('exiting %s', service.name);
- service.on('exit', cb);
- service.kill('SIGTERM');
- };
-}
diff --git a/test/services/service.js b/test/services/service.js
deleted file mode 100644
index d00d1e7..0000000
--- a/test/services/service.js
+++ /dev/null
@@ -1,156 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-var path = require('path');
-var spawn = require('child_process').spawn;
-var inherits = require('util').inherits;
-var EE = require('events').EventEmitter;
-var extend = require('xtend');
-var which = require('which');
-var PassThrough = require('stream').PassThrough;
-var fs = require('fs');
-
-var JIRI_ROOT = process.env.JIRI_ROOT;
-var VANADIUM_BINS = [
- path.join(JIRI_ROOT, 'release/javascript/core/go/bin'),
- path.join(JIRI_ROOT, 'release/javascript/core/nacl/scripts')
-];
-var DEFAULT_FLAGS = {
- v: 3,
- log_dir: path.resolve('tmp/log') // jshint ignore:line
-};
-
-process.env.PATH += ':' + VANADIUM_BINS.join(':');
-
-module.exports = Service;
-
-function Service(name, env) {
- if (!(this instanceof Service)) {
- return new Service(name, env);
- }
-
- var service = this;
-
- EE.call(service);
-
- try {
- service.config = require('./config-' + name);
- } catch (e) {
- service.config = {};
- }
-
- service.name = name;
- service.args = flags(extend(DEFAULT_FLAGS, service.config.flags));
- service.env = env || {};
-}
-
-inherits(Service, EE);
-
-Service.prototype.spawn = function(args) {
- var service = this;
-
- args = args || service.args;
-
- if (!JIRI_ROOT) {
- var err = new Error('Please export $JIRI_ROOT to proceed');
- return service.emit('error', err);
- }
-
- which(service.name, function(err, bin) {
- if (err) {
- return service.emit('error', notfound(service.name));
- }
-
- var errlog = '';
-
- service.process = spawn(bin, args, {env: service.env});
-
- if (service.name !== 'servicerunner') {
- service.emit('ready');
- }
-
- if (service.process.stdout) {
- service.process.stdout.pipe(fs.createWriteStream(
- path.join('tmp', service.name + '.stdout.log')));
-
- if (service.name === 'servicerunner') {
- service.process.stdout.on('data', function(data) {
- service.emit('vars', JSON.parse(data.toString()));
- service.emit('ready');
- });
- }
- }
-
- // Buffer stderr until close so that a meaningful error can be emitted
- // when a non-zero exit code is encountered.
- //
- // NOTE: All vanadium bins log to stderr so this buffer will just grow
- // until that is resolved...
- if (service.process.stderr) {
- var stderr = new PassThrough();
- service.process.stderr.pipe(stderr);
- stderr.pipe(fs.createWriteStream(
- path.join('tmp', service.name + '.stderr.log')));
-
- stderr.on('data', function(data) {
- errlog += data;
- });
- }
-
- service.process.on('close', function(code) {
- if (code === 0) {
- return;
- }
-
- var message = [
- 'non-zero exit code: ' + code,
- 'while running: ' + service.name + ' ' + args.join(' '),
- '\n',
- errlog
- ].join('\n');
-
- service.emit('error', new Error(message));
- });
-
- [ 'exit', 'close' ].forEach(function(name) {
- service.process.on(name, service.emit.bind(service, name));
- });
-
- service.emit('spawn', service.process.stdout, service.process.stderr);
- });
-};
-
-// A quick wrapper for short run execs, useful for non-deamons like the
-// principal command.
-Service.prototype.exec = function(command, cb) {
- var service = this;
- service
- .on('error', cb.bind(service))
- .on('spawn', cb.bind(service, null))
- .spawn(command.split(' '));
-};
-
-Service.prototype.kill = function() {
- var service = this;
-
- if (service.process) {
- service.process.kill.apply(service.process, arguments);
- }
-};
-
-function notfound(name) {
- var message = 'Vanadium binary not found: ' + name + '\n' +
- 'Please run "make clean" and try again.' +
- 'If problem persists, "make go/bin -B" can force building of binaries.';
-
- return new Error(message);
-}
-
-function flags(obj) {
- var args = Object.keys(obj).map(function(key) {
- return ['-', key, '=', obj[key]].join('');
- });
-
- return args;
-}
diff --git a/test/ui/README.md b/test/ui/README.md
deleted file mode 100644
index 12d70c9..0000000
--- a/test/ui/README.md
+++ /dev/null
@@ -1,57 +0,0 @@
-# Vanadium JavaScript UI Test
-
-## About
-
-The UI tests use the maven architecture. This package manager uses
-the build information from pom.xml to compile a WebDriver program.
-
-The UI library in this repository defines VanadiumUITestBase, which
-uses WebDriver to run Chrome and install the Vanadium Extension.
-
-It also defines HTMLReporter, which is used to grab screenshots and
-generate an HTML report of the WebDriver test.
-
-## Usage
-
-The expected use of the library is to subclass VanadiumUITestBase and
-write a JUnit test function. The HTMLReporter should be started at the
-beginning of the test and generated upon test completion.
-
-A distinct pom.xml should be written for the tests, and it should
-include a dependency to this library.
-
-In order to install and use the Vanadium Extension, it is important to
-have the credentials of a Google account. It is not recommended that
-these credentials be visible to the public. Maven properties and
-environment variables can be used to keep them private.
-
-See release.projects.browser and www for example usages.
-
-## Display Port
-
-To run a test, one will generally set the DISPLAY environment variable
-to :0 or run Xvfb at a specific display port. Set this value in the
-test project's pom.xml file.
-
-Note that when running with :0, the test will run with the current
-display. Mouse and key actions performed during this period will interfere with the WebDriver test.
-
-While :0 is good for watching tests as they run, the screenshots taken
-are not guaranteed to be accurate.
-
-## Invoking maven
-
-At least 4 flags are required when running the maven test:
-- chromeDriverBin: Location of the Chrome WebDriver binary
-- htmlReportsRelativePath: Directory to output an HTML report (relative to $WORKSPACE)
-- googleBotUsername: Username for a Google account
-- googleBotPassword: Password for that user
-
-Here is an example invocation:
-WORKSPACE=$WORKSPACE mvn test \
- -f=$LOCATION_OF_POM_XML \
- -Dtest=$UI_TEST_NAME \
- -DchromeDriverBin=$CHROME_WEBDRIVER \
- -DhtmlReportsRelativePath=$HTML_REPORT_RELATIVE_PATH \
- -DgoogleBotUsername=$BOT_USERNAME \
- -DgoogleBotPassword=$BOT_PASSWORD
diff --git a/test/ui/pom.xml b/test/ui/pom.xml
deleted file mode 100644
index f233058..0000000
--- a/test/ui/pom.xml
+++ /dev/null
@@ -1,51 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <name>Vanadium Webdriver</name>
- <groupId>io.v.webdriver</groupId>
- <artifactId>vanadium_webdriver</artifactId>
- <version>0.1</version>
-
- <dependencies>
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.4</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.freemarker</groupId>
- <artifactId>freemarker</artifactId>
- <version>2.3.22</version>
- </dependency>
- <dependency>
- <groupId>org.seleniumhq.selenium</groupId>
- <artifactId>selenium-chrome-driver</artifactId>
- <version>2.45.0</version>
- </dependency>
- <dependency>
- <groupId>org.seleniumhq.selenium</groupId>
- <artifactId>selenium-support</artifactId>
- <version>2.45.0</version>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>3.2</version>
- <configuration>
- <source>1.7</source>
- <target>1.7</target>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
diff --git a/test/ui/src/test/java/io/v/webdriver/RobotHelper.java b/test/ui/src/test/java/io/v/webdriver/RobotHelper.java
deleted file mode 100644
index bca09c4..0000000
--- a/test/ui/src/test/java/io/v/webdriver/RobotHelper.java
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package io.v.webdriver;
-
-import java.awt.AWTException;
-import java.awt.Robot;
-import java.awt.Toolkit;
-import java.awt.datatransfer.Clipboard;
-import java.awt.datatransfer.StringSelection;
-import java.awt.event.KeyEvent;
-
-/**
- * A helper class for Robot related functions.
- * <p>
- * Most of the automation should be done through WebDriver APIs, but some elements (e.g. Chrome's
- * native Sign-in page or the confirmation dialog after an extension is installed) cannot be
- * accessed and controlled by WebDriver. In those cases, we use Robot to send key strokes, mouse
- * clicks, etc.
- *
- * @author jingjin@google.com
- */
-public class RobotHelper {
- /**
- * This is a singleton instance.
- */
- private static RobotHelper instance;
-
- private final Robot robot;
-
- public static RobotHelper sharedInstance() throws AWTException {
- if (instance == null) {
- instance = new RobotHelper();
- }
- return instance;
- }
-
- private RobotHelper() throws AWTException {
- robot = new Robot();
- robot.setAutoDelay(200);
- robot.setAutoWaitForIdle(true);
- }
-
- /**
- * Enters the given text to the focused element.
- *
- * <p>To make the process easier, we copy the given text to system clipboard and paste it into the
- * target element. Otherwise, we have to call "keyPress" and "keyRelease" on each key stroke.
- *
- * @param text the text to enter.
- */
- public void enterText(String text) {
- // Copy text to clipboard.
- Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
- StringSelection stringSelection = new StringSelection(text);
- clipboard.setContents(stringSelection, stringSelection);
-
- // Send Ctrl+V to paste.
- robot.keyPress(KeyEvent.VK_CONTROL);
- robot.keyPress(KeyEvent.VK_V);
- robot.keyRelease(KeyEvent.VK_V);
- robot.keyRelease(KeyEvent.VK_CONTROL);
- }
-
- /**
- * Presses TAB.
- */
- public void tab() {
- robot.keyPress(KeyEvent.VK_TAB);
- robot.keyRelease(KeyEvent.VK_TAB);
- }
-
- /**
- * Presses Enter.
- */
- public void enter() {
- robot.keyPress(KeyEvent.VK_ENTER);
- robot.keyRelease(KeyEvent.VK_ENTER);
- }
-}
diff --git a/test/ui/src/test/java/io/v/webdriver/TestFailureWatcher.java b/test/ui/src/test/java/io/v/webdriver/TestFailureWatcher.java
deleted file mode 100644
index e4f2fa3..0000000
--- a/test/ui/src/test/java/io/v/webdriver/TestFailureWatcher.java
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package io.v.webdriver;
-
-import org.junit.rules.TestWatcher;
-import org.junit.runner.Description;
-import org.openqa.selenium.TakesScreenshot;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.chrome.ChromeDriverService;
-
-import io.v.webdriver.htmlreport.HTMLReportData;
-import io.v.webdriver.htmlreport.HTMLReporter;
-
-/**
- * A class for performing actions when any test case fails.
- *
- * @author jingjin@google.com
- */
-public class TestFailureWatcher extends TestWatcher {
- private VanadiumUITestBase uiTest;
- private WebDriver driver;
- private ChromeDriverService service;
-
- public void setup(VanadiumUITestBase uiTest, WebDriver driver, ChromeDriverService service) {
- this.uiTest = uiTest;
- this.driver = driver;
- this.service = service;
- }
-
- @Override
- protected void failed(Throwable e, Description description) {
- // Grab all the browser logs and print them out.
- uiTest.printConsoleLogs();
-
- // Take a screenshot for the current screen and write the html report.
- HTMLReportData data = uiTest.getCurrentHTMLReportData();
- Util.takeScreenshot((TakesScreenshot)driver, "test-failed.png", "Test Failed", data);
- HTMLReporter reporter = new HTMLReporter(data);
- try {
- reporter.generateReport();
- } catch (Exception e1) {
- System.err.println("Failed to write html report.\n" + Util.getStackTrace(e1));
- }
- }
-
- @Override
- protected void finished(Description description) {
- driver.quit();
- service.stop();
- }
-}
diff --git a/test/ui/src/test/java/io/v/webdriver/Util.java b/test/ui/src/test/java/io/v/webdriver/Util.java
deleted file mode 100644
index 4fb0d25..0000000
--- a/test/ui/src/test/java/io/v/webdriver/Util.java
+++ /dev/null
@@ -1,119 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package io.v.webdriver;
-
-import io.v.webdriver.htmlreport.HTMLReportData;
-
-import org.openqa.selenium.OutputType;
-import org.openqa.selenium.TakesScreenshot;
-import org.openqa.selenium.WebDriver;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.net.SocketException;
-import java.util.Enumeration;
-
-/**
- * Utility functions.
- *
- * @author jingjin@google.com
- */
-public class Util {
-
- /**
- * Sleeps for given milliseconds.
- *
- * <p>This is mainly used for waiting between Robot related operations. For WebDriver, we should
- * use "wait.until".
- *
- * @param ms number of milliseconds to sleep.
- */
- public static void sleep(int ms) {
- try {
- Thread.sleep(ms);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Converts the given exception's stack trace to a string.
- *
- * @param e the exception to convert to string.
- */
- public static String getStackTrace(Exception e) {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
- e.printStackTrace(pw);
- return sw.toString();
- }
-
- /**
- * Replaces illegal character in the given file name.
- *
- * @param filename the original file name.
- */
- public static String getSafeFilename(String filename) {
- return filename.replaceAll("[^a-zA-Z0-9.-]", "_").toLowerCase();
- }
-
- /**
- * Takes a screenshot.
- *
- * <p>It uses the WebDriver to grab the screenshot data, saves it to the given file,
- * and records it in the given htmlReportData.
- *
- * @param TakesScreenshot a driver that can getScreenshotAs, such as a ChromeDriver.
- * @param fileName the file to save the screenshot to.
- * @param caption the caption of the screenshot.
- * @param htmlReportData the data model to add screenshot data to.
- */
- public static void takeScreenshot(TakesScreenshot taker, String fileName,
- String caption, HTMLReportData htmlReportData) {
-
- String fullFileName =
- String.format("%s-%s", getSafeFilename(htmlReportData.getTestName()), fileName);
- Runtime rt = Runtime.getRuntime();
- try {
- byte[] imageData = taker.getScreenshotAs(OutputType.BYTES); // throws WebDriverException
- File imageFile = new File(htmlReportData.getReportDir(), fullFileName);
- FileOutputStream fos = new FileOutputStream(imageFile);
- fos.write(imageData);
- fos.close();
- } catch (Exception e) {
- System.err.printf("Failed to copy screenshot to %s/%s\n", htmlReportData.getReportDir(), fullFileName);
- e.printStackTrace();
- }
-
- htmlReportData.addScreenshotData(fullFileName, caption);
- }
-
- /**
- * Prints the address of each network interface on the machine.
- * Taken from http://stackoverflow.com/questions/9481865/getting-the-ip-address-of-the-current-machine-using-java
- */
- public static void printIPAddresses() {
- try {
- Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
- while(e.hasMoreElements())
- {
- NetworkInterface n = e.nextElement();
- Enumeration<InetAddress> ee = n.getInetAddresses();
- while (ee.hasMoreElements())
- {
- InetAddress i = ee.nextElement();
- System.out.println(i.getHostAddress());
- }
- }
- } catch(SocketException e) {
- System.err.println("Could not print IP addresses");
- e.printStackTrace();
- }
- }
-}
diff --git a/test/ui/src/test/java/io/v/webdriver/VanadiumUITestBase.java b/test/ui/src/test/java/io/v/webdriver/VanadiumUITestBase.java
deleted file mode 100644
index bd3a5dc..0000000
--- a/test/ui/src/test/java/io/v/webdriver/VanadiumUITestBase.java
+++ /dev/null
@@ -1,222 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package io.v.webdriver;
-
-
-import org.junit.Before;
-import org.junit.Rule;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.chrome.ChromeDriver;
-import org.openqa.selenium.chrome.ChromeDriverService;
-import org.openqa.selenium.chrome.ChromeOptions;
-import org.openqa.selenium.logging.LogEntries;
-import org.openqa.selenium.logging.LogEntry;
-import org.openqa.selenium.logging.LogType;
-import org.openqa.selenium.logging.LoggingPreferences;
-import org.openqa.selenium.remote.CapabilityType;
-import org.openqa.selenium.remote.DesiredCapabilities;
-
-import io.v.webdriver.Util;
-import io.v.webdriver.htmlreport.HTMLReportData;
-import io.v.webdriver.commonpages.ChromeSignInPage;
-import io.v.webdriver.commonpages.CaveatTabPage;
-import io.v.webdriver.commonpages.ExtensionInstallationPage;
-import io.v.webdriver.commonpages.ExtensionOptionPage;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Date;
-import java.util.logging.Level;
-
-/**
- * The base class for all Vanadium UI tests.
- *
- * @author jingjin@google.com
- */
-public class VanadiumUITestBase {
- /**
- * System property name for Chrome driver binary. This will be set from the mvn command line.
- */
- private static final String PROPERTY_CHROME_DRIVER_BIN = "chromeDriverBin";
-
- /**
- * System property name for html report path relative to Jenkins workspace dir. This will be set
- * from the mvn command line.
- */
- private static final String PROPERTY_HTML_REPORTS_RELATIVE_PATH = "htmlReportsRelativePath";
-
- /**
- * System property name for the bot username and bot password. These will be set from the mvn command line.
- */
- private static final String PROPERTY_GOOGLE_BOT_USERNAME = "googleBotUsername";
- private static final String PROPERTY_GOOGLE_BOT_PASSWORD = "googleBotPassword";
-
- /**
- * System property name for the path to the Vanadium extension. Optional.
- */
- private static final String PROPERTY_VANADIUM_EXTENSION_PATH = "vanadiumExtensionPath";
- protected boolean hasExtension;
-
- /**
- * The base dir to store html reports
- */
- protected final String htmlReportsDir;
-
- /**
- * A variable to keep track of the current htmlReportData.
- */
- protected HTMLReportData curHTMLReportData;
-
- /**
- * The username and password of the bot account used to sign in to Google/Chrome.
- */
- protected String botUsername;
- protected String botPassword;
-
- /**
- * Vanadium extension installation url.
- */
- private static final String URL_EXTENSION = "https://chrome.google.com/webstore/detail/"
- + "vanadium-extension/jcaelnibllfoobpedofhlaobfcoknpap";
-
- protected ChromeDriverService service;
-
- protected WebDriver driver;
-
- public VanadiumUITestBase() {
- htmlReportsDir = createReportsDir();
- }
-
- /**
- * This "Rule" is used to catch failed test cases so we can act on it.
- */
- @Rule
- public TestFailureWatcher testFailureWatcher = new TestFailureWatcher();
-
- /**
- * Basic WebDriver and other setup tasks. This will be executed before each test case.
- */
- @Before
- public void setup() throws IOException {
- // TODO(alexfandrianto): Used to debug the IP address of the machine. Possibly remove.
- Util.printIPAddresses();
-
- String chromeDriverBin = System.getProperty(PROPERTY_CHROME_DRIVER_BIN);
- botUsername = System.getProperty(PROPERTY_GOOGLE_BOT_USERNAME);
- botPassword = System.getProperty(PROPERTY_GOOGLE_BOT_PASSWORD);
- System.out.println("ChromeDriver binary: " + chromeDriverBin);
- service = new ChromeDriverService.Builder().usingDriverExecutable(new File(chromeDriverBin))
- .usingAnyFreePort().build();
- service.stop();
- service.start();
-
- // Set up the ability to grab the console.log from the browser.
- DesiredCapabilities capabilities = DesiredCapabilities.chrome();
- LoggingPreferences logPrefs = new LoggingPreferences();
- logPrefs.enable(LogType.BROWSER, Level.ALL);
- capabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
-
- // If an extension was chosen, use that.
- String vanadiumExtensionPath = System.getProperty(PROPERTY_VANADIUM_EXTENSION_PATH);
- if (vanadiumExtensionPath != null) {
- ChromeOptions options = new ChromeOptions();
- options.addArguments("load-extension=" + System.getProperty("vanadiumExtensionPath"));
-
- capabilities.setCapability(ChromeOptions.CAPABILITY, options);
- hasExtension = true;
- }
-
- // Create the driver and start using it.
- driver = new ChromeDriver(service, capabilities);
- driver.manage().window().maximize();
-
- testFailureWatcher.setup(this, driver, service);
- }
-
- public HTMLReportData getCurrentHTMLReportData() {
- return curHTMLReportData;
- }
-
- private String createReportsDir() {
- String workspaceRoot = System.getenv("WORKSPACE");
- if (workspaceRoot == null) {
- workspaceRoot = System.getenv("HOME");
- }
- if (workspaceRoot == null) {
- return "";
- }
- String reportsDir = String.format("%s/%s", workspaceRoot,
- System.getProperty(PROPERTY_HTML_REPORTS_RELATIVE_PATH, "htmlReports"));
- File reportsFile = new File(reportsDir);
- if (!reportsFile.exists()) {
- if (reportsFile.mkdirs()) {
- System.out.println(String.format("Reports dir '%s' created", reportsDir));
- } else {
- throw new RuntimeException(String.format("Failed to create reports dir '%s'", reportsDir));
- }
- }
- return reportsDir;
- }
-
- /**
- * Grab all of the log entries from the browser and print them out.
- */
- public void printConsoleLogs() {
- LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
- for (LogEntry entry : logEntries) {
- System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
- }
- }
-
- /**
- * Sign in and install the extension, if necessary.
- * A simple wrapper around signIn and installExtension.
- */
- protected void signInAndInstallExtension(HTMLReportData reportData) throws Exception {
- signIn(reportData);
- if (!this.hasExtension) {
- installExtension(reportData);
- }
- }
-
- /**
- * Sign into Chrome. This is needed to use the extension.
- */
- protected void signIn(HTMLReportData reportData) throws Exception {
- // Sign into Chrome.
- ChromeSignInPage chromeSignInPage = new ChromeSignInPage(driver, reportData);
- chromeSignInPage.go();
- chromeSignInPage.signIn(botUsername, botPassword);
- }
-
- /**
- * UI tests will commonly need to install the extension.
- * The process involves installing the extension and
- * verifying that it was installed successfully.
- */
- protected void installExtension(HTMLReportData reportData) throws Exception {
- // Install Vanadium extension.
- ExtensionInstallationPage extensionInstallationPage =
- new ExtensionInstallationPage(driver, URL_EXTENSION, reportData);
- extensionInstallationPage.go();
- extensionInstallationPage.login(botPassword);
- extensionInstallationPage.install();
-
- hasExtension = true;
-
- // Check Vanadium extension option page.
- Util.sleep(4000);
- ExtensionOptionPage extensionOptionPage = new ExtensionOptionPage(driver, reportData);
- extensionOptionPage.go();
- }
-
- /**
- * UI tests will commonly need to bypass a caveat page.
- */
- protected void handleCaveatTab(HTMLReportData reportData) throws Exception {
- CaveatTabPage caveatTabPage = new CaveatTabPage(driver, reportData);
- caveatTabPage.bless();
- }
-}
diff --git a/test/ui/src/test/java/io/v/webdriver/commonpages/CaveatTabPage.java b/test/ui/src/test/java/io/v/webdriver/commonpages/CaveatTabPage.java
deleted file mode 100644
index e1473ba..0000000
--- a/test/ui/src/test/java/io/v/webdriver/commonpages/CaveatTabPage.java
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package io.v.webdriver.commonpages;
-
-import com.google.common.base.Function;
-
-import org.openqa.selenium.By;
-import org.openqa.selenium.TakesScreenshot;
-import org.openqa.selenium.TimeoutException;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.support.ui.ExpectedConditions;
-import org.openqa.selenium.support.ui.WebDriverWait;
-
-import io.v.webdriver.RobotHelper;
-import io.v.webdriver.Util;
-import io.v.webdriver.htmlreport.HTMLReportData;
-
-import java.awt.AWTException;
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-
-import java.util.Set;
-
-/**
- * Vanadium extension caveat tab page.
- *
- * @author jingjin@google.com
- */
-public class CaveatTabPage extends PageBase {
- public CaveatTabPage(WebDriver driver,
- HTMLReportData htmlReportData) throws UnsupportedEncodingException {
- super(driver, "", htmlReportData);
- }
-
- private static final int WAIT_TIME = 70; // 70s wait time; allow time for an error to appear and to grab a screenshot of it
-
- public void bless() {
- log("Waiting for Caveat Tab...");
- Util.takeScreenshot((TakesScreenshot)driver, "waiting-caveats.png", "Waiting for Caveats", htmlReportData);
- final String mainTabHandle = driver.getWindowHandle();
-
- // Wait until the corresponding tab is there, which means we should get two window handles.
- String selectCaveatsTabHandle = waitForCaveatTab(mainTabHandle);
- driver.switchTo().window(selectCaveatsTabHandle);
-
- log("Accept blessing");
- // We need to click on the "Bless" button in the "select caveats" page.
- WebElement btnBless =
- wait.until(ExpectedConditions.elementToBeClickable(By.id("submit-caveats")));
- Util.takeScreenshot((TakesScreenshot)driver, "select-caveats.png", "Selecting Caveats", htmlReportData);
- btnBless.click();
- driver.switchTo().window(mainTabHandle);
- }
-
- // Attempts to wait until the caveat tab page shows up.
- // Returns the handle to it.
- private String waitForCaveatTab(final String mainTabHandle) throws TimeoutException {
- return new WebDriverWait(driver, WAIT_TIME).until(new Function<WebDriver, String>() {
- @Override
- public String apply(WebDriver input) {
- Set<String> handles = driver.getWindowHandles();
- if (handles.size() != 2) {
- return null;
- }
- for (String handle : handles) {
- if (!handle.equals(mainTabHandle)) {
- return handle;
- }
- }
- return null;
- }
- });
- }
-}
diff --git a/test/ui/src/test/java/io/v/webdriver/commonpages/ChromeSignInPage.java b/test/ui/src/test/java/io/v/webdriver/commonpages/ChromeSignInPage.java
deleted file mode 100644
index 82838ef..0000000
--- a/test/ui/src/test/java/io/v/webdriver/commonpages/ChromeSignInPage.java
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package io.v.webdriver.commonpages;
-
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.TakesScreenshot;
-
-import io.v.webdriver.RobotHelper;
-import io.v.webdriver.Util;
-import io.v.webdriver.htmlreport.HTMLReportData;
-
-import java.awt.AWTException;
-
-/**
- * Chrome's native Sign-In page.
- *
- * @author jingjin@google.com
- */
-public class ChromeSignInPage extends PageBase {
- private static final String URL_CHROME_SIGNIN = "chrome://chrome-signin";
-
- public ChromeSignInPage(WebDriver driver, HTMLReportData htmlReportData) {
- super(driver, URL_CHROME_SIGNIN, htmlReportData);
- }
-
- @Override
- public void go() {
- super.goWithoutTakingScreenshot();
-
- // For this page we need to wait a little bit before entering username/password.
- Util.sleep(2000);
- takeScreenshotUsingPageName();
- }
-
- public void signIn(String username, String password) throws AWTException {
- // Sign in.
- log("Sign in");
- RobotHelper robotHelper = RobotHelper.sharedInstance();
- robotHelper.enterText(username);
- robotHelper.tab();
- robotHelper.enterText(password);
- robotHelper.tab();
- Util.takeScreenshot((TakesScreenshot)driver, "before-chrome-signin.png", "Before Signing In Chrome", htmlReportData);
- robotHelper.enter();
- Util.sleep(2000);
-
- // Dismiss a "Sign-in successful" popup.
- // This popup is not accessible by WebDriver.
- log("Dismiss 'Sign-in successful' prompt");
- robotHelper.enter();
- Util.takeScreenshot((TakesScreenshot)driver, "after-chrome-signin.png", "After Signing In Chrome", htmlReportData);
- }
-}
diff --git a/test/ui/src/test/java/io/v/webdriver/commonpages/ExtensionInstallationPage.java b/test/ui/src/test/java/io/v/webdriver/commonpages/ExtensionInstallationPage.java
deleted file mode 100644
index 1f430a2..0000000
--- a/test/ui/src/test/java/io/v/webdriver/commonpages/ExtensionInstallationPage.java
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package io.v.webdriver.commonpages;
-
-import org.openqa.selenium.By;
-import org.openqa.selenium.TakesScreenshot;
-import org.openqa.selenium.TimeoutException;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.support.ui.ExpectedConditions;
-
-import io.v.webdriver.RobotHelper;
-import io.v.webdriver.Util;
-import io.v.webdriver.htmlreport.HTMLReportData;
-
-import java.awt.AWTException;
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-
-/**
- * Vanadium extension installation page.
- *
- * @author jingjin@google.com
- */
-public class ExtensionInstallationPage extends PageBase {
- private static final String GOOGLE_LOGIN_URL = "https://accounts.google.com/ServiceLogin";
-
- public ExtensionInstallationPage(WebDriver driver, String extentionUrl,
- HTMLReportData htmlReportData) throws UnsupportedEncodingException {
- super(driver, GOOGLE_LOGIN_URL + "?continue=" + URLEncoder.encode(extentionUrl, "UTF-8"),
- htmlReportData);
- }
-
- public void login(String password) throws TimeoutException {
- log("Log in using Google account");
- WebElement btnSignin = wait.until(ExpectedConditions.elementToBeClickable(By.id("signIn")));
- WebElement passwdTextField = driver.findElement(By.id("Passwd"));
- passwdTextField.sendKeys(password);
- Util.takeScreenshot((TakesScreenshot)driver, "google-account-signin.png", "Google Account Sign-In", htmlReportData);
- btnSignin.click();
- }
-
- public void install() throws AWTException, TimeoutException {
- log("Install extension");
- WebElement btnAddToChrome = wait.until(
- ExpectedConditions.elementToBeClickable(By.cssSelector("div[aria-label='Add to Chrome']")));
- Util.takeScreenshot((TakesScreenshot)driver, "before-install-extension.png", "Before Installing Extension",
- htmlReportData);
- btnAddToChrome.click();
- Util.sleep(4000); // This sleep gives the page time to pop up a confirm box.
-
- // Tab+Enter activates the "Add" button in the extension installation popup.
- // This popup is not accessible by WebDriver.
- log("Confirm adding extension to Chrome");
- RobotHelper robotHelper = RobotHelper.sharedInstance();
- robotHelper.tab();
- robotHelper.enter();
- wait.until(ExpectedConditions.elementToBeClickable(
- By.cssSelector("div[aria-label='Added to Chrome']")));
- // It might take some time for the extension to actually be installed.
- Util.sleep(3000);
- Util.takeScreenshot((TakesScreenshot)driver, "after-install-extension.png", "After Installing Extension",
- htmlReportData);
- }
-}
diff --git a/test/ui/src/test/java/io/v/webdriver/commonpages/ExtensionOptionPage.java b/test/ui/src/test/java/io/v/webdriver/commonpages/ExtensionOptionPage.java
deleted file mode 100644
index 30885c6..0000000
--- a/test/ui/src/test/java/io/v/webdriver/commonpages/ExtensionOptionPage.java
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package io.v.webdriver.commonpages;
-
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.support.ui.ExpectedConditions;
-
-import io.v.webdriver.Util;
-import io.v.webdriver.htmlreport.HTMLReportData;
-
-/**
- * Vanadium extension's option page.
- *
- * @author jingjin@google.com
- */
-public class ExtensionOptionPage extends PageBase {
- private static final String URL_OPTIONS =
- "chrome-extension://jcaelnibllfoobpedofhlaobfcoknpap/html/options.html";
-
- public ExtensionOptionPage(WebDriver driver, HTMLReportData htmlReportData) {
- super(driver, URL_OPTIONS, htmlReportData);
- }
-
- @Override
- public void go() {
- super.goWithoutTakingScreenshot();
-
- // For this page we need to do an extra refresh once to make the page appear.
- driver.navigate().refresh();
- Util.sleep(1000);
- takeScreenshotUsingPageName();
-
- // Verify the "Reload plugin" link is present.
- wait.until(ExpectedConditions.presenceOfElementLocated(By.linkText("Reload plugin")));
- }
-}
diff --git a/test/ui/src/test/java/io/v/webdriver/commonpages/OAuthLoginPage.java b/test/ui/src/test/java/io/v/webdriver/commonpages/OAuthLoginPage.java
deleted file mode 100644
index bb2df3c..0000000
--- a/test/ui/src/test/java/io/v/webdriver/commonpages/OAuthLoginPage.java
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package io.v.webdriver.commonpages;
-
-import org.openqa.selenium.By;
-import org.openqa.selenium.TakesScreenshot;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.WebElement;
-import org.openqa.selenium.support.ui.ExpectedConditions;
-
-import io.v.webdriver.Util;
-import io.v.webdriver.htmlreport.HTMLReportData;
-
-/**
- * Google OAuth login page.
- *
- * @author jingjin@google.com
- */
-public class OAuthLoginPage extends PageBase {
- public OAuthLoginPage(WebDriver driver, HTMLReportData htmlReportData) {
- // This page is often triggered by some other page.
- super(driver, "", htmlReportData);
- }
-
- public void login() {
- log("OAuth login");
- Util.takeScreenshot((TakesScreenshot)driver, "oauth-login.png", "OAuth Login", htmlReportData);
- WebElement btnSignInGoogle = wait.until(ExpectedConditions.elementToBeClickable(
- By.xpath("//button[contains(text(), 'Sign in with a Google Account')]")));
- btnSignInGoogle.click();
-
- log("Accept access info");
- Util.takeScreenshot((TakesScreenshot)driver, "accept-access-info.png", "Accepting Access Info", htmlReportData);
- WebElement btnAccept =
- wait.until(ExpectedConditions.elementToBeClickable(By.id("submit_approve_access")));
- btnAccept.click();
- }
-}
diff --git a/test/ui/src/test/java/io/v/webdriver/commonpages/PageBase.java b/test/ui/src/test/java/io/v/webdriver/commonpages/PageBase.java
deleted file mode 100644
index f3f9874..0000000
--- a/test/ui/src/test/java/io/v/webdriver/commonpages/PageBase.java
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package io.v.webdriver.commonpages;
-
-import org.openqa.selenium.TakesScreenshot;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.support.ui.WebDriverWait;
-
-import io.v.webdriver.Util;
-import io.v.webdriver.htmlreport.HTMLReportData;
-
-/**
- * Base page class.
- *
- * @author jingjin@google.com
- */
-public class PageBase {
- /**
- * Default timeout in seconds for WebDriver to wait for a condition.
- */
- public static final int TIMEOUT_SECONDS = 10;
-
- /**
- * Page URL.
- */
- private String url;
-
- /**
- * Informative page name used in logging.
- */
- private final String pageName;
-
- protected final WebDriver driver;
-
- protected final WebDriverWait wait;
-
- protected final HTMLReportData htmlReportData;
-
- public PageBase(WebDriver driver, String url, HTMLReportData htmlReportData) {
- this.driver = driver;
- this.url = url;
- this.htmlReportData = htmlReportData;
- this.pageName = this.getClass().getSimpleName();
-
- wait = new WebDriverWait(driver, TIMEOUT_SECONDS);
- }
-
- public void go() {
- goWithoutTakingScreenshot();
- takeScreenshotUsingPageName();
- }
-
- public void goWithoutTakingScreenshot() {
- log("Go to " + url);
- driver.get(url);
- }
-
- protected void log(String msg) {
- System.out.println(String.format("[%s]: %s", pageName, msg));
- }
-
- /**
- * Takes a screenshot for the current page and names it using pageName.
- */
- protected void takeScreenshotUsingPageName() {
- Util.takeScreenshot((TakesScreenshot)driver, String.format("%s.png", Util.getSafeFilename(pageName)), pageName,
- htmlReportData);
- }
-}
diff --git a/test/ui/src/test/java/io/v/webdriver/htmlreport/HTMLReportData.java b/test/ui/src/test/java/io/v/webdriver/htmlreport/HTMLReportData.java
deleted file mode 100644
index 998258d..0000000
--- a/test/ui/src/test/java/io/v/webdriver/htmlreport/HTMLReportData.java
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package io.v.webdriver.htmlreport;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Data model class for used in HTML report generation.
- *
- * @author jingjin@google.com
- */
-public class HTMLReportData {
- /**
- * A list of screenshots in the report.
- */
- private final List<ScreenshotData> screenshots = new ArrayList<ScreenshotData>();
-
- /**
- * The report's base dir.
- */
- private final String reportDir;
-
- /**
- * The name of the test associated with the data.
- */
- private final String testName;
-
- public HTMLReportData(String testName, String reportDir) {
- this.testName = testName;
- this.reportDir = reportDir;
- }
-
- public String getReportDir() {
- return reportDir;
- }
-
- public String getTestName() {
- return testName;
- }
-
- public void addScreenshotData(String fileName, String caption) {
- screenshots.add(new ScreenshotData(fileName, caption));
- }
-
- public List<ScreenshotData> getScreenshots() {
- return screenshots;
- }
-}
diff --git a/test/ui/src/test/java/io/v/webdriver/htmlreport/HTMLReporter.java b/test/ui/src/test/java/io/v/webdriver/htmlreport/HTMLReporter.java
deleted file mode 100644
index ef249ac..0000000
--- a/test/ui/src/test/java/io/v/webdriver/htmlreport/HTMLReporter.java
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package io.v.webdriver.htmlreport;
-
-import freemarker.template.Configuration;
-import freemarker.template.Template;
-import freemarker.template.TemplateExceptionHandler;
-
-import io.v.webdriver.Util;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.Writer;
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Map;
-
-/**
- * Generate HTML report that has screenshots of all test steps.
- *
- * @author jingjin@google.com
- */
-public class HTMLReporter {
- private final String reportFileName;
- private final HTMLReportData data;
-
- public HTMLReporter(HTMLReportData data) {
- this.reportFileName = String.format("%s.html", Util.getSafeFilename(data.getTestName()));
- this.data = data;
- }
-
- public void generateReport() throws Exception {
- // Setup and load template.
- Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
- cfg.setClassForTemplateLoading(this.getClass(), "");
- cfg.setDefaultEncoding("UTF-8");
- cfg.setLocale(Locale.US);
- cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
-
- // Figure out where the report.ftl file is.
- File f = new File(System.getenv("JIRI_ROOT") + "/release/javascript/core/test/ui/src/test/java/io/v/webdriver/htmlreport");
- String path = f.getAbsolutePath();
- cfg.setDirectoryForTemplateLoading(new File(path));
-
- // This template formats the HTML report.
- Template template = cfg.getTemplate("report.ftl");
-
- // Prepare data.
- Map<String, Object> input = new HashMap<String, Object>();
- input.put("data", data);
-
- // Generate output.
- String reportPath = String.format("%s/%s", data.getReportDir(), reportFileName);
- Writer fileWriter = new FileWriter(new File(reportPath));
- try {
- template.process(input, fileWriter);
- } finally {
- fileWriter.close();
- }
- }
-}
diff --git a/test/ui/src/test/java/io/v/webdriver/htmlreport/ScreenshotData.java b/test/ui/src/test/java/io/v/webdriver/htmlreport/ScreenshotData.java
deleted file mode 100644
index db7c77f..0000000
--- a/test/ui/src/test/java/io/v/webdriver/htmlreport/ScreenshotData.java
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package io.v.webdriver.htmlreport;
-
-/**
- * Data model for a screenshot image.
- *
- * @author jingjin@google.com
- */
-public class ScreenshotData {
- /**
- * The base file name (not including the full path) of the screenshot image file.
- */
- private final String fileName;
-
- /**
- * The caption of the screenshot.
- */
- private final String caption;
-
- public ScreenshotData(String fileName, String caption) {
- this.fileName = fileName;
- this.caption = caption;
- }
-
- public String getFileName() {
- return fileName;
- }
-
- public String getCaption() {
- return caption;
- }
-}
diff --git a/test/ui/src/test/java/io/v/webdriver/htmlreport/report.ftl b/test/ui/src/test/java/io/v/webdriver/htmlreport/report.ftl
deleted file mode 100644
index 166a919..0000000
--- a/test/ui/src/test/java/io/v/webdriver/htmlreport/report.ftl
+++ /dev/null
@@ -1,69 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <title>${data.testName}</title>
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
- <link href="https://cdnjs.cloudflare.com/ajax/libs/fotorama/4.6.3/fotorama.css" rel="stylesheet">
- <script src="https://cdnjs.cloudflare.com/ajax/libs/fotorama/4.6.3/fotorama.js"></script>
- <script>
- // Set "Test Failed" caption to red background.
- $(function() {
- $('.fotorama').on('fotorama:show', function(e, fotorama, extra) {
- $(".fotorama__caption__wrap").each(function(index) {
- if ($(this).text() == "Test Failed") {
- $(this).addClass('failed-test');
- }
- });
- });
- });
- </script>
- <style>
- body {
- font-family: Helvetica, Arial, sans-serif;
- }
-
- h1 {
- font-size: 20px;
- color: #0097A7;
- }
-
- .failed-test {
- background-color: rgba(200, 0, 0, 0.9) !important;
- color: white !important;
- }
-
- .fotorama__caption {
- left: auto !important;
- right: 0px;
- top: 0px;
- }
-
- .fotorama__caption__wrap {
- border: solid 1px #AAA;
- font-weight: bold;
- }
-
- .fotorama__thumb-border {
- border-color: #0097A7 !important;
- }
-
- .fotorama__wrap {
- margin: 0 auto;
- }
- </style>
- </head>
- <body>
- <h1>${data.testName}</h1>
- <div class="fotorama"
- data-width="800px"
- data-ratio="800/600"
- data-nav="thumbs"
- data-keyboard="true"
- data-thumbwidth=60
- data-thumbheight=45>
- <#list data.screenshots as screenshot>
- <img class="failed-test" src="${screenshot.fileName}" data-caption="${screenshot.caption}"/>
- </#list>
- </div>
- </body>
-</html>
\ No newline at end of file
diff --git a/test/unit/test-arg-inspector.js b/test/unit/test-arg-inspector.js
index 9d48ecd..7bfc686 100644
--- a/test/unit/test-arg-inspector.js
+++ b/test/unit/test-arg-inspector.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var ArgInspector = require('../../src/lib/arg-inspector.js');
test('var args = argInspector(fn)', function(t) {
diff --git a/test/unit/test-async-call.js b/test/unit/test-async-call.js
index f17e96b..a3db333 100644
--- a/test/unit/test-async-call.js
+++ b/test/unit/test-async-call.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var Promise = require('../../src/lib/promise');
var asyncCall = require('../../src/lib/async-call');
var InspectableFunction = require('../../src/lib/inspectable-function');
diff --git a/test/unit/test-async-helper.js b/test/unit/test-async-helper.js
index dfbbc44..21766cc 100644
--- a/test/unit/test-async-helper.js
+++ b/test/unit/test-async-helper.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var Promise = require('../../src/lib/promise');
var asyncHelper = require('../../src/lib/async-helper');
diff --git a/test/unit/test-blessings-cache.js b/test/unit/test-blessings-cache.js
index a7b9e0b..2e52a5b 100644
--- a/test/unit/test-blessings-cache.js
+++ b/test/unit/test-blessings-cache.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var BlessingsCache = require('../../src/security/blessings-cache');
var principal =
require('../../src/gen-vdl/v.io/x/ref/services/wspr/internal/principal');
diff --git a/test/unit/test-blessings.js b/test/unit/test-blessings.js
index 30b1f1c..a7a631f 100644
--- a/test/unit/test-blessings.js
+++ b/test/unit/test-blessings.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var Blessings = require('../../src/security/blessings');
var vom = require('./../../src/vom');
var WireBlessings =
diff --git a/test/unit/test-caveat-validator-registry.js b/test/unit/test-caveat-validator-registry.js
index 27f105b..39e81c5 100644
--- a/test/unit/test-caveat-validator-registry.js
+++ b/test/unit/test-caveat-validator-registry.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var CaveatValidatorRegistry =
require('../../src/security/caveat-validator-registry');
var context = require('../../src/context');
diff --git a/test/unit/test-context.js b/test/unit/test-context.js
index 295429e..fb1ea50 100644
--- a/test/unit/test-context.js
+++ b/test/unit/test-context.js
@@ -6,7 +6,7 @@
* @fileoverview Tests for the context library.
*/
-var test = require('prova');
+var test = require('tape');
var context = require('../../src/context');
var verror = require('../../src/gen-vdl/v.io/v23/verror');
diff --git a/test/unit/test-create-caveats.js b/test/unit/test-create-caveats.js
index f9421df..e8e8337 100644
--- a/test/unit/test-create-caveats.js
+++ b/test/unit/test-create-caveats.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var types = require('../../src/vdl/types');
var kind = require('../../src/vdl/kind');
var vdlSecurity = require('../vdl-out/v.io/v23/security');
diff --git a/test/unit/test-create-signature.js b/test/unit/test-create-signature.js
index e2f5247..d981199 100644
--- a/test/unit/test-create-signature.js
+++ b/test/unit/test-create-signature.js
@@ -5,7 +5,7 @@
/**
* @fileoverview Tests of generating signature with multiple descriptions
*/
-var test = require('prova');
+var test = require('tape');
var createSignature = require('../../src/vdl/create-signature');
var vdl = require('../../src/vdl');
var stringify = require('../../src/vdl/stringify');
diff --git a/test/unit/test-deferred.js b/test/unit/test-deferred.js
index ad78ba6..5ae9484 100644
--- a/test/unit/test-deferred.js
+++ b/test/unit/test-deferred.js
@@ -3,7 +3,7 @@
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var Deferred = require('../../src/lib/deferred');
test('var deferred = new Deferred() - success', function(assert) {
diff --git a/test/unit/test-error-catalog.js b/test/unit/test-error-catalog.js
index f4662b3..970ffd3 100644
--- a/test/unit/test-error-catalog.js
+++ b/test/unit/test-error-catalog.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var Catalog = require('../../src/verror/catalog');
test('set and lookup', function(assert) {
diff --git a/test/unit/test-error-format.js b/test/unit/test-error-format.js
index f16d7d7..4fe3952 100644
--- a/test/unit/test-error-format.js
+++ b/test/unit/test-error-format.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var formatError = require('../../src/verror/format');
function expectFormatParams(t, format, expected) {
diff --git a/test/unit/test-error-tostring.js b/test/unit/test-error-tostring.js
index f6d1cb9..a34c539 100644
--- a/test/unit/test-error-tostring.js
+++ b/test/unit/test-error-tostring.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var verror = require('../../src/gen-vdl/v.io/v23/verror');
test('Working toString on BadArgError (a VanadiumError)', function(t) {
diff --git a/test/unit/test-inspectable-function.js b/test/unit/test-inspectable-function.js
index bd26325..b81959f 100644
--- a/test/unit/test-inspectable-function.js
+++ b/test/unit/test-inspectable-function.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var InspectableFunction = require('../../src/lib/inspectable-function');
test('apply()', function(t) {
diff --git a/test/unit/test-invoker-invoke.js b/test/unit/test-invoker-invoke.js
index db3f3c1..a2f5d7e 100644
--- a/test/unit/test-invoker-invoke.js
+++ b/test/unit/test-invoker-invoke.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var verror = require('../../').verror;
var Invoker = require('../../src/invocation/invoker.js');
var Context = require('../../src/context').Context;
diff --git a/test/unit/test-invoker.js b/test/unit/test-invoker.js
index 841250d..dc6333a 100644
--- a/test/unit/test-invoker.js
+++ b/test/unit/test-invoker.js
@@ -9,7 +9,7 @@
* compatible with that expected by the JavaScript signature generator.
*/
-var test = require('prova');
+var test = require('tape');
var Invoker = require('../../src/invocation/invoker.js');
var Context = require('../../src/context').Context;
var vdl = require('../../src/vdl');
diff --git a/test/unit/test-namespace-util.js b/test/unit/test-namespace-util.js
index 441fd1a..75ad9d2 100644
--- a/test/unit/test-namespace-util.js
+++ b/test/unit/test-namespace-util.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var names = require('../../src/naming/util');
var ep = '@6@tcp@127.0.0.1:22@@@@@s@dev.v.io:blessing,v.io:blessing:b2@@';
var rootedEp = '/' + ep;
diff --git a/test/unit/test-permissions-authorizer.js b/test/unit/test-permissions-authorizer.js
index 970d3b1..f4df793 100644
--- a/test/unit/test-permissions-authorizer.js
+++ b/test/unit/test-permissions-authorizer.js
@@ -3,7 +3,7 @@
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var permissionsAuthorizer =
require('../../src/security/access/permissions-authorizer');
var access = require('../../src/gen-vdl/v.io/v23/security/access');
diff --git a/test/unit/test-proxy.js b/test/unit/test-proxy.js
index bc75be3..b347697 100644
--- a/test/unit/test-proxy.js
+++ b/test/unit/test-proxy.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var Proxy = require('../../src/proxy');
test('creating instances', function(assert) {
diff --git a/test/unit/test-random.js b/test/unit/test-random.js
index 5bf71cd..c9ecdc5 100644
--- a/test/unit/test-random.js
+++ b/test/unit/test-random.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var random = require('../../src/lib/random');
diff --git a/test/unit/test-rpc-client.js b/test/unit/test-rpc-client.js
index f205eb0..89dbb96 100644
--- a/test/unit/test-rpc-client.js
+++ b/test/unit/test-rpc-client.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var Client = require('../../src/rpc/client.js');
var context = require('../../src/context');
var createSignature = require('../../src/vdl/create-signature');
diff --git a/test/unit/test-rpc-signature-cache.js b/test/unit/test-rpc-signature-cache.js
index 2289292..6cfa88d 100644
--- a/test/unit/test-rpc-signature-cache.js
+++ b/test/unit/test-rpc-signature-cache.js
@@ -8,7 +8,7 @@
* cache signatures per object name in JavaScript.
* Scope of the cache is per proxy connection.
*/
-var test = require('prova');
+var test = require('tape');
var context = require('../../src/context');
var createMockProxy = require('./mock-proxy');
var Outgoing = require('../../src/proxy/message-type').Outgoing;
diff --git a/test/unit/test-server-router.js b/test/unit/test-server-router.js
index 9bcbd04..c75f56d 100644
--- a/test/unit/test-server-router.js
+++ b/test/unit/test-server-router.js
@@ -6,7 +6,7 @@
* @fileoveriew Tests server_router.js.
*/
-var test = require('prova');
+var test = require('tape');
var Router = require('../../src/rpc/server-router');
var Server = require('../../src/rpc/server');
var Outgoing = require('../../src/proxy/message-type').Outgoing;
diff --git a/test/unit/test-service-reflection.js b/test/unit/test-service-reflection.js
index 746f560..6004288 100644
--- a/test/unit/test-service-reflection.js
+++ b/test/unit/test-service-reflection.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var isPublicMethod = require('../../src/lib/service-reflection').isPublicMethod;
function AConstructor() {
diff --git a/test/unit/test-signature.js b/test/unit/test-signature.js
index 285c2ff..af6aba0 100644
--- a/test/unit/test-signature.js
+++ b/test/unit/test-signature.js
@@ -6,7 +6,7 @@
* @fileoverview Tests of signature generation.
*/
-var test = require('prova');
+var test = require('tape');
var Interface = require('../../src/vdl/interface');
var vdl = require('../../src/vdl');
var stringify = require('../../src/vdl/stringify');
diff --git a/test/unit/test-standard-caveat-validators.js b/test/unit/test-standard-caveat-validators.js
index 41e545e..a811dcf 100644
--- a/test/unit/test-standard-caveat-validators.js
+++ b/test/unit/test-standard-caveat-validators.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var CaveatValidatorRegistry =
require('../../src/security/caveat-validator-registry');
var caveats = require('../../src/security/caveats');
diff --git a/test/unit/test-task-sequence.js b/test/unit/test-task-sequence.js
index b7fac99..4e46b1d 100644
--- a/test/unit/test-task-sequence.js
+++ b/test/unit/test-task-sequence.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var Promise = require('../../src/lib/promise');
var TaskSequence = require('../../src/lib/task-sequence');
var promiseFor = require('../../src/lib/async-helper').promiseFor;
diff --git a/test/unit/test-uniqueid.js b/test/unit/test-uniqueid.js
index 93b8c5c..1ab9692 100644
--- a/test/unit/test-uniqueid.js
+++ b/test/unit/test-uniqueid.js
@@ -6,7 +6,7 @@
* @fileoverview Tests for the uniqueid library.
*/
-var test = require('prova');
+var test = require('tape');
var uniqueid = require('../../src/lib/uniqueid');
var vdl = require('../../src/gen-vdl/v.io/v23/uniqueid');
var typeutil = require('../../src/vdl/type-util');
diff --git a/test/unit/test-verror.js b/test/unit/test-verror.js
index 48176a4..64e334c 100644
--- a/test/unit/test-verror.js
+++ b/test/unit/test-verror.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var verror = require('../../src/gen-vdl/v.io/v23/verror');
var Context = require('../../src/context').Context;
var VanadiumError = require('../../src/verror/vanadium-error');
diff --git a/test/unit/test-vlog.js b/test/unit/test-vlog.js
index d655b7c..9f15c89 100644
--- a/test/unit/test-vlog.js
+++ b/test/unit/test-vlog.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var vlog = require('../../src/lib/vlog').logger;
var Vlog = require('../../src/lib/vlog').Vlog;
var levels = require('../../src/lib/vlog').levels;
diff --git a/test/unit/test-vtrace.js b/test/unit/test-vtrace.js
index 82f9415..45aa644 100644
--- a/test/unit/test-vtrace.js
+++ b/test/unit/test-vtrace.js
@@ -6,7 +6,7 @@
* @fileoverview Tests for the vtrace library.
*/
-var test = require('prova');
+var test = require('tape');
var context = require('../../src/context');
var vtrace = require('../../src/vtrace');
var vdl = require('../../src/gen-vdl/v.io/v23/vtrace');
diff --git a/test/vdl/test-big-int.js b/test/vdl/test-big-int.js
index 689116a..967e484 100644
--- a/test/vdl/test-big-int.js
+++ b/test/vdl/test-big-int.js
@@ -6,7 +6,7 @@
* @fileoverview Tests for BigInt.
*/
-var test = require('prova');
+var test = require('tape');
var BigInt = require('./../../src/vdl/big-int.js');
diff --git a/test/vdl/test-byte-util.js b/test/vdl/test-byte-util.js
index d09522c..52ee13e 100644
--- a/test/vdl/test-byte-util.js
+++ b/test/vdl/test-byte-util.js
@@ -6,7 +6,7 @@
* @fileoverview Tests for byte util.
*/
-var test = require('prova');
+var test = require('tape');
var ByteUtil = require('./../../src/vdl/byte-util.js');
diff --git a/test/vdl/test-canonicalize.js b/test/vdl/test-canonicalize.js
index 31627fc..96696f0 100644
--- a/test/vdl/test-canonicalize.js
+++ b/test/vdl/test-canonicalize.js
@@ -6,7 +6,7 @@
* @fileoverview Tests for canonicalize.js
*/
-var test = require('prova');
+var test = require('tape');
var BigInt = require('./../../src/vdl/big-int.js');
var Complex = require('./../../src/vdl/complex.js');
diff --git a/test/vdl/test-complex.js b/test/vdl/test-complex.js
index 589c737..f13d025 100644
--- a/test/vdl/test-complex.js
+++ b/test/vdl/test-complex.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var Complex = require('./../../src/vdl/complex');
test('toString', function(assert) {
diff --git a/test/vdl/test-create-constructor.js b/test/vdl/test-create-constructor.js
index 3e1cebc..e5af39b 100644
--- a/test/vdl/test-create-constructor.js
+++ b/test/vdl/test-create-constructor.js
@@ -6,7 +6,7 @@
* @fileoverview Tests create-constructor.js
*/
-var test = require('prova');
+var test = require('tape');
var BigInt = require('./../../src/vdl/big-int.js');
var createConstructor = require('./../../src/vdl/create-constructor.js');
diff --git a/test/vdl/test-js-value-convert.js b/test/vdl/test-js-value-convert.js
index 35c5c17..2251968 100644
--- a/test/vdl/test-js-value-convert.js
+++ b/test/vdl/test-js-value-convert.js
@@ -8,7 +8,7 @@
* Tests of the shallow convertTonative are performed in canonicalize.
*/
-var test = require('prova');
+var test = require('tape');
var registry = require('./../../src/vdl/registry.js');
var types = require('./../../src/vdl/types.js');
diff --git a/test/vdl/test-registry.js b/test/vdl/test-registry.js
index cf0c0c5..592af70 100644
--- a/test/vdl/test-registry.js
+++ b/test/vdl/test-registry.js
@@ -6,7 +6,7 @@
* @fileoverview Tests for registry.js
*/
-var test = require('prova');
+var test = require('tape');
var registry = require('./../../src/vdl/registry.js');
var registryMultipleRequire = require('./../../src/vdl/registry.js');
diff --git a/test/vdl/test-stringify.js b/test/vdl/test-stringify.js
index c9df294..3c193d7 100644
--- a/test/vdl/test-stringify.js
+++ b/test/vdl/test-stringify.js
@@ -6,7 +6,7 @@
* @fileoverview Tests for stringify.js
*/
-var test = require('prova');
+var test = require('tape');
var stringify = require('./../../src/vdl/stringify.js');
diff --git a/test/vdl/test-type-compatible.js b/test/vdl/test-type-compatible.js
index ce802ac..74161d6 100644
--- a/test/vdl/test-type-compatible.js
+++ b/test/vdl/test-type-compatible.js
@@ -6,7 +6,7 @@
* @fileoverview Tests for type conversion compatibility.
*/
-var test = require('prova');
+var test = require('tape');
var kind = require('./../../src/vdl/kind.js');
var Type = require('./../../src/vdl/type.js');
diff --git a/test/vdl/test-type-toString.js b/test/vdl/test-type-toString.js
index 1ed6635..86c9045 100644
--- a/test/vdl/test-type-toString.js
+++ b/test/vdl/test-type-toString.js
@@ -6,7 +6,7 @@
* @fileoverview Tests for toString in type.js and types.js
*/
-var test = require('prova');
+var test = require('tape');
var testCases = require('./type-test-cases.js');
var Type = require('./../../src/vdl/type.js');
diff --git a/test/vdl/test-type-util.js b/test/vdl/test-type-util.js
index ab54e2e..b55279f 100644
--- a/test/vdl/test-type-util.js
+++ b/test/vdl/test-type-util.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var typeUtil = require('../../src/vdl/type-util.js');
var vdl = require('../../src/vdl');
diff --git a/test/vdl/test-vdl-base.js b/test/vdl/test-vdl-base.js
index 47a7dea..bc38f60 100644
--- a/test/vdl/test-vdl-base.js
+++ b/test/vdl/test-vdl-base.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var base = require('../vdl-out/v.io/x/ref/lib/vdl/testdata/base');
var context = require('../../src/context');
var SharedContextKeys = require('../../src/runtime/shared-context-keys');
diff --git a/test/vdl/test-vdl-errors.js b/test/vdl/test-vdl-errors.js
index 156520a..30b8274 100644
--- a/test/vdl/test-vdl-errors.js
+++ b/test/vdl/test-vdl-errors.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var verror = require('../../src/gen-vdl/v.io/v23/verror');
var ec = require('../../src/vdl/error-conversion');
var types = require('../../src/vdl/types');
diff --git a/test/vdl/test-vdl-native.js b/test/vdl/test-vdl-native.js
index da9ed7c..3ec6ad4 100644
--- a/test/vdl/test-vdl-native.js
+++ b/test/vdl/test-vdl-native.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var time = require('../vdl-out/javascript-test/time');
test('time constants are Dates', function(assert) {
diff --git a/test/vom/test-binary-reader.js b/test/vom/test-binary-reader.js
index c627b5d..bcb882d 100644
--- a/test/vom/test-binary-reader.js
+++ b/test/vom/test-binary-reader.js
@@ -6,7 +6,7 @@
* @fileoverview Tests for binary reader.
*/
-var test = require('prova');
+var test = require('tape');
var BinaryReader = require('./../../src/vom/binary-reader.js');
var ByteUtil = require('./../../src/vdl/byte-util.js');
diff --git a/test/vom/test-encode-decode.js b/test/vom/test-encode-decode.js
index 29d71b8..2cb8c86 100644
--- a/test/vom/test-encode-decode.js
+++ b/test/vom/test-encode-decode.js
@@ -6,7 +6,7 @@
* @fileoverview Tests of VOM encoding and decoding.
*/
-var test = require('prova');
+var test = require('tape');
var kind = require('./../../src/vdl/kind.js');
var registry = require('./../../src/vdl/registry.js');
diff --git a/test/vom/test-native-type.js b/test/vom/test-native-type.js
index 7167452..3ce1c58 100644
--- a/test/vom/test-native-type.js
+++ b/test/vom/test-native-type.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var ByteMessageWriter = require(
'./../../src/vom/byte-message-writer');
diff --git a/test/vom/test-raw-vom-compatibility.js b/test/vom/test-raw-vom-compatibility.js
index 8620583..bbf2ebc 100644
--- a/test/vom/test-raw-vom-compatibility.js
+++ b/test/vom/test-raw-vom-compatibility.js
@@ -6,7 +6,7 @@
* @fileoverview Tests compatibility with go.
*/
-var test = require('prova');
+var test = require('tape');
var BigInt = require('./../../src/vdl/big-int.js');
var RawVomWriter = require('./../../src/vom/raw-vom-writer');
diff --git a/test/vom/test-raw-vom-recoverability.js b/test/vom/test-raw-vom-recoverability.js
index 02c578d..47950df 100644
--- a/test/vom/test-raw-vom-recoverability.js
+++ b/test/vom/test-raw-vom-recoverability.js
@@ -6,7 +6,7 @@
* @fileoverview Tests recovering written vom data js to js.
*/
-var test = require('prova');
+var test = require('tape');
var BigInt = require('./../../src/vdl/big-int.js');
var RawVomWriter = require('./../../src/vom/raw-vom-writer');
diff --git a/test/vom/test-stream-reader.js b/test/vom/test-stream-reader.js
index 0e43391..d1ee3ee 100644
--- a/test/vom/test-stream-reader.js
+++ b/test/vom/test-stream-reader.js
@@ -6,7 +6,7 @@
* @fileoverview Tests for stream reader.
*/
-var test = require('prova');
+var test = require('tape');
var StreamReader = require('./../../src/vom/stream-reader.js');
var ByteUtil = require('./../../src/vdl/byte-util.js');
diff --git a/test/vom/test-type-encoding.js b/test/vom/test-type-encoding.js
index faf7a30..7b61b4c 100644
--- a/test/vom/test-type-encoding.js
+++ b/test/vom/test-type-encoding.js
@@ -6,7 +6,7 @@
* @fileoverview Tests for TypeEncoder and TypeDecoder.
*/
-var test = require('prova');
+var test = require('tape');
var stringify = require('./../../src/vdl/stringify.js');
var types = require('./../../src/vdl/types.js');
diff --git a/test/vom/test-vdl-arith.js b/test/vom/test-vdl-arith.js
index e8c1385..018b83d 100644
--- a/test/vom/test-vdl-arith.js
+++ b/test/vom/test-vdl-arith.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-var test = require('prova');
+var test = require('tape');
var vom = require('../../src/vom');
var IfaceSigType =
require('../../src/gen-vdl/v.io/v23/vdlroot/signature').Interface;
diff --git a/test/vom/test-vom-compatibility.js b/test/vom/test-vom-compatibility.js
index 6ddee0d..03ece3b 100644
--- a/test/vom/test-vom-compatibility.js
+++ b/test/vom/test-vom-compatibility.js
@@ -6,7 +6,7 @@
* @fileoverview Tests for encoder and decoder compatibility.
*/
-var test = require('prova');
+var test = require('tape');
var testdata80 = require('../vdl-out/v.io/v23/vom/testdata/data80');
var testdata81 = require('../vdl-out/v.io/v23/vom/testdata/data81');