entities listlengths 1 44.6k | max_stars_repo_path stringlengths 6 160 | max_stars_repo_name stringlengths 6 66 | max_stars_count int64 0 47.9k | content stringlengths 18 1.04M | id stringlengths 1 6 | new_content stringlengths 18 1.04M | modified bool 1 class | references stringlengths 32 1.52M |
|---|---|---|---|---|---|---|---|---|
[
{
"context": " (gbif/request-download\n {:user user \n :password password \n ",
"end": 1971,
"score": 0.8760297298431396,
"start": 1967,
"tag": "USERNAME",
"value": "user"
},
{
"context": " {:user user \n :password password \n :email email\n ",
"end": 2009,
"score": 0.9984567165374756,
"start": 2001,
"tag": "PASSWORD",
"value": "password"
}
] | src/gbif2ipt/core.clj | diogok/gbif2ipt | 0 | (ns gbif2ipt.core
(:require [clojure.java.io :as io])
(:require [clj-http.lite.client :as http])
(:require [clojure.data.json :as json])
(:require [clojure.core.async :refer [<! <!! >! >!! chan close! go-loop]])
(:require [taoensso.timbre :as log])
(:require [environ.core :refer [env]])
(:require [dwc-io.gbif :as gbif])
(:gen-class))
(def taxadata (or (env :taxadata-url) "http://taxadata/api/v2"))
(def data-dir (or (env :data-dir) "data"))
(def country (or (env :country) "BR"))
(def user (or (env :gbif-user) ""))
(def email (or (env :gbif-email) ""))
(def password (or (env :gbif-password) ""))
(defn get-json
[& url]
(log/info "Get JSON"(apply str url ))
(try
(:result (json/read-str (:body (http/get (apply str url))) :key-fn keyword))
(catch Exception e
(log/warn (str "Failled get JSON " (apply str url) (.getMessage e))))))
(defn sources->families
[sources families]
(go-loop [src (<! sources)]
(when-not (nil? src)
(log/info "Got source" src)
(doseq [family (get-json taxadata "/" src "/families")]
(>! families family))
(recur (<! sources)))))
(defn wait-and-download
[dfile dkey]
(log/info "Got download key " dkey)
(loop []
(let [r (http/get (gbif/download-url dkey) { :throw-exceptions false :as :stream})]
(log/info (:status r))
(if (not (= 404 (:status r)))
(io/copy (:body r) (io/file data-dir (str dfile ".zip")))
(do
(Thread/sleep 30000)
(recur))))))
(defn families->download
[families done]
(go-loop [family (<! families)]
(if (nil? family)
(>! done true)
(do
(log/info "Got family" family)
(let [taxon (-> (gbif/get-a-taxon family) :results first)]
(wait-and-download
(if (not (nil? country)) (str country "_" family) family)
(gbif/request-download
{:user user
:password password
:email email
:filters (if-not (nil? country)
[[:FAMILY_KEY :equals (:key taxon)]
[:COUNTRY :equals country]]
[[:FAMILY_KEY :equals (:key taxon)]])})))
(recur (<! families))))))
(defn run
[]
(let [sources (chan 1)
families (chan 1)
done (chan 1)]
(sources->families sources families)
(families->download families done)
(doseq [source (get-json (str taxadata "/sources" ))]
(>!! sources source))
(<!! done)))
(defn wait-taxadata
"Wait for Taxadata to be ready"
[]
(let [done (atom false)]
(while (not @done)
(try
(log/info (str "Waiting: " taxadata))
(let [r (http/get (str taxadata "/status") {:throw-exceptions false})]
(if (= "done" (:status (json/read-str (:body r) :key-fn keyword)))
(reset! done true)
(do
(log/info (json/read-str (:body r)))
(Thread/sleep 1000))))
(catch Exception e
(do
(log/warn (.toString e))
(Thread/sleep 1000)))))
(log/info (str "Done: " taxadata))))
(defn -main
[ & args ]
(log/info "Starting...")
(log/info taxadata)
(log/info data-dir)
(log/info country)
(log/info user)
(spit (str data-dir "/.testwrite") "testwrite")
(wait-taxadata)
(log/info "Will start now")
(run))
| 18854 | (ns gbif2ipt.core
(:require [clojure.java.io :as io])
(:require [clj-http.lite.client :as http])
(:require [clojure.data.json :as json])
(:require [clojure.core.async :refer [<! <!! >! >!! chan close! go-loop]])
(:require [taoensso.timbre :as log])
(:require [environ.core :refer [env]])
(:require [dwc-io.gbif :as gbif])
(:gen-class))
(def taxadata (or (env :taxadata-url) "http://taxadata/api/v2"))
(def data-dir (or (env :data-dir) "data"))
(def country (or (env :country) "BR"))
(def user (or (env :gbif-user) ""))
(def email (or (env :gbif-email) ""))
(def password (or (env :gbif-password) ""))
(defn get-json
[& url]
(log/info "Get JSON"(apply str url ))
(try
(:result (json/read-str (:body (http/get (apply str url))) :key-fn keyword))
(catch Exception e
(log/warn (str "Failled get JSON " (apply str url) (.getMessage e))))))
(defn sources->families
[sources families]
(go-loop [src (<! sources)]
(when-not (nil? src)
(log/info "Got source" src)
(doseq [family (get-json taxadata "/" src "/families")]
(>! families family))
(recur (<! sources)))))
(defn wait-and-download
[dfile dkey]
(log/info "Got download key " dkey)
(loop []
(let [r (http/get (gbif/download-url dkey) { :throw-exceptions false :as :stream})]
(log/info (:status r))
(if (not (= 404 (:status r)))
(io/copy (:body r) (io/file data-dir (str dfile ".zip")))
(do
(Thread/sleep 30000)
(recur))))))
(defn families->download
[families done]
(go-loop [family (<! families)]
(if (nil? family)
(>! done true)
(do
(log/info "Got family" family)
(let [taxon (-> (gbif/get-a-taxon family) :results first)]
(wait-and-download
(if (not (nil? country)) (str country "_" family) family)
(gbif/request-download
{:user user
:password <PASSWORD>
:email email
:filters (if-not (nil? country)
[[:FAMILY_KEY :equals (:key taxon)]
[:COUNTRY :equals country]]
[[:FAMILY_KEY :equals (:key taxon)]])})))
(recur (<! families))))))
(defn run
[]
(let [sources (chan 1)
families (chan 1)
done (chan 1)]
(sources->families sources families)
(families->download families done)
(doseq [source (get-json (str taxadata "/sources" ))]
(>!! sources source))
(<!! done)))
(defn wait-taxadata
"Wait for Taxadata to be ready"
[]
(let [done (atom false)]
(while (not @done)
(try
(log/info (str "Waiting: " taxadata))
(let [r (http/get (str taxadata "/status") {:throw-exceptions false})]
(if (= "done" (:status (json/read-str (:body r) :key-fn keyword)))
(reset! done true)
(do
(log/info (json/read-str (:body r)))
(Thread/sleep 1000))))
(catch Exception e
(do
(log/warn (.toString e))
(Thread/sleep 1000)))))
(log/info (str "Done: " taxadata))))
(defn -main
[ & args ]
(log/info "Starting...")
(log/info taxadata)
(log/info data-dir)
(log/info country)
(log/info user)
(spit (str data-dir "/.testwrite") "testwrite")
(wait-taxadata)
(log/info "Will start now")
(run))
| true | (ns gbif2ipt.core
(:require [clojure.java.io :as io])
(:require [clj-http.lite.client :as http])
(:require [clojure.data.json :as json])
(:require [clojure.core.async :refer [<! <!! >! >!! chan close! go-loop]])
(:require [taoensso.timbre :as log])
(:require [environ.core :refer [env]])
(:require [dwc-io.gbif :as gbif])
(:gen-class))
(def taxadata (or (env :taxadata-url) "http://taxadata/api/v2"))
(def data-dir (or (env :data-dir) "data"))
(def country (or (env :country) "BR"))
(def user (or (env :gbif-user) ""))
(def email (or (env :gbif-email) ""))
(def password (or (env :gbif-password) ""))
(defn get-json
[& url]
(log/info "Get JSON"(apply str url ))
(try
(:result (json/read-str (:body (http/get (apply str url))) :key-fn keyword))
(catch Exception e
(log/warn (str "Failled get JSON " (apply str url) (.getMessage e))))))
(defn sources->families
[sources families]
(go-loop [src (<! sources)]
(when-not (nil? src)
(log/info "Got source" src)
(doseq [family (get-json taxadata "/" src "/families")]
(>! families family))
(recur (<! sources)))))
(defn wait-and-download
[dfile dkey]
(log/info "Got download key " dkey)
(loop []
(let [r (http/get (gbif/download-url dkey) { :throw-exceptions false :as :stream})]
(log/info (:status r))
(if (not (= 404 (:status r)))
(io/copy (:body r) (io/file data-dir (str dfile ".zip")))
(do
(Thread/sleep 30000)
(recur))))))
(defn families->download
[families done]
(go-loop [family (<! families)]
(if (nil? family)
(>! done true)
(do
(log/info "Got family" family)
(let [taxon (-> (gbif/get-a-taxon family) :results first)]
(wait-and-download
(if (not (nil? country)) (str country "_" family) family)
(gbif/request-download
{:user user
:password PI:PASSWORD:<PASSWORD>END_PI
:email email
:filters (if-not (nil? country)
[[:FAMILY_KEY :equals (:key taxon)]
[:COUNTRY :equals country]]
[[:FAMILY_KEY :equals (:key taxon)]])})))
(recur (<! families))))))
(defn run
[]
(let [sources (chan 1)
families (chan 1)
done (chan 1)]
(sources->families sources families)
(families->download families done)
(doseq [source (get-json (str taxadata "/sources" ))]
(>!! sources source))
(<!! done)))
(defn wait-taxadata
"Wait for Taxadata to be ready"
[]
(let [done (atom false)]
(while (not @done)
(try
(log/info (str "Waiting: " taxadata))
(let [r (http/get (str taxadata "/status") {:throw-exceptions false})]
(if (= "done" (:status (json/read-str (:body r) :key-fn keyword)))
(reset! done true)
(do
(log/info (json/read-str (:body r)))
(Thread/sleep 1000))))
(catch Exception e
(do
(log/warn (.toString e))
(Thread/sleep 1000)))))
(log/info (str "Done: " taxadata))))
(defn -main
[ & args ]
(log/info "Starting...")
(log/info taxadata)
(log/info data-dir)
(log/info country)
(log/info user)
(spit (str data-dir "/.testwrite") "testwrite")
(wait-taxadata)
(log/info "Will start now")
(run))
|
[
{
"context": "ate-api-key-with-account {:userid userid :username username :password password :config ega-config}))\n ",
"end": 8360,
"score": 0.8910974860191345,
"start": 8352,
"tag": "USERNAME",
"value": "username"
},
{
"context": "count {:userid userid :username username :password password :config ega-config}))\n (do (usage)\n ",
"end": 8379,
"score": 0.9971083998680115,
"start": 8371,
"tag": "PASSWORD",
"value": "password"
}
] | src/clj/rems/standalone.clj | nuwang/rems | 0 | (ns rems.standalone
"Run the REMS app in an embedded http server."
(:require [clojure.string :as str]
[clojure.tools.cli :refer [parse-opts]]
[clojure.tools.logging :as log]
[luminus-migrations.core :as migrations]
[luminus.http-server :as http]
[luminus.repl-server :as repl]
[medley.core :refer [find-first]]
[mount.core :as mount]
[rems.api.services.ega :as ega]
[rems.application.search :as search]
[rems.common.git :as git]
[rems.config :refer [env]]
[rems.db.api-key :as api-key]
[rems.db.applications :as applications]
[rems.db.core :as db]
[rems.db.fix-userid]
[rems.db.roles :as roles]
[rems.db.test-data :as test-data]
[rems.db.users :as users]
[rems.handler :as handler]
[rems.json :as json]
[rems.validate :as validate])
(:import [sun.misc Signal SignalHandler])
(:refer-clojure :exclude [parse-opts])
(:gen-class))
(def cli-options
[["-p" "--port PORT" "Port number"
:parse-fn #(Integer/parseInt %)]])
(defn- jetty-configurator [server]
(let [pool (.getThreadPool server)]
(.setName pool "jetty-handlers")
server))
(mount/defstate
^{:on-reload :noop}
http-server
:start
(http/start (merge {:handler handler/handler
:send-server-version? false
:port (:port env)
:configurator jetty-configurator}
(when-not (:port env)
{:http? false})
(when (:ssl-port env)
{:ssl? true
:ssl-port (:ssl-port env)
:keystore (:ssl-keystore env)
:key-password (:ssl-keystore-password env)})))
:stop
(when http-server (http/stop http-server)))
(mount/defstate
^{:on-reload :noop}
repl-server
:start
(when-let [nrepl-port (env :nrepl-port)]
(repl/start {:port nrepl-port}))
:stop
(when repl-server
(repl/stop repl-server)))
(defn stop-app []
(doseq [component (:stopped (mount/stop))]
(log/info component "stopped")))
(defn- refresh-caches []
(log/info "Refreshing caches")
(applications/refresh-all-applications-cache!)
(search/refresh!)
(log/info "Caches refreshed"))
(defn start-app [& args]
(doseq [component (-> args
(parse-opts cli-options)
mount/start-with-args
:started)]
(log/info component "started"))
(.addShutdownHook (Runtime/getRuntime) (Thread. stop-app))
(validate/validate)
(refresh-caches))
;; The default of the JVM is to exit with code 128+signal. However, we
;; shut down gracefully on SIGINT and SIGTERM due to the exit hooks
;; mount has installed. Thus exit code 0 is the right choice. This
;; also makes REMS standalone work nicely with systemd: by default it
;; uses SIGTERM to stop services and expects a succesful exit.
(defn exit-on-signals! []
(let [exit (proxy [SignalHandler] []
(handle [sig]
(log/info "Shutting down due to signal" (.getName sig))
(System/exit 0)))]
(Signal/handle (Signal. "INT") exit) ;; e.g. ^C from terminal
(Signal/handle (Signal. "TERM") exit) ;; default kill signal of systemd
nil))
(defn -main
"Arguments can be either arguments to mount/start-with-args, or one of
\"run\" -- start the REMS application
\"help\" -- show this help
\"migrate\" -- migrate database
\"rollback\" -- roll back database migration
\"reset\" -- empties database and runs migrations to empty db
\"test-data\" -- insert test data into database
\"demo-data\" -- insert data for demoing purposes into database
\"validate\" -- validate data in db
\"list-users\" -- list users and roles
\"grant-role <role> <user>\" -- grant a role to a user
\"remove-role <role> <user>\" -- remove a role from a user
\"api-key get\" -- list all api keys
\"api-key get <api-key>\" -- get details of api key
\"api-key add <api-key> [<description>]\" -- add api key to db.
<description> is an optional text comment.
If a pre-existing <api-key> is given, update description for it.
\"api-key delete <api-key>\" -- remove api key from db.
\"api-key set-users <api-key> [<uid1> <uid2> ...]\" -- set allowed users for api key
An empty set of users means all users are allowed.
Adds the api key if it doesn't exist.
\"api-key allow <api-key> <method> <regex>\" -- add an entry to the allowed method/path whitelist
The special method `any` means any method.
The regex is a (Java) regular expression that should match the whole path of the request.
Example regex: /api/applications/[0-9]+/?
\"api-key allow-all <api-key>\" -- clears the allowed method/path whitelist.
An empty list means all methods and paths are allowed.
\"ega api-key <userid> <username> <password> <config-id>\" -- generate a new API-Key for the user using EGA login
\"rename-user <old-userid> <new-userid>\" -- change a user's identity from old to new"
[& args]
(exit-on-signals!)
(log/info "REMS" git/+version+)
(let [usage #(do
(println "Usage:")
(println (:doc (meta #'-main))))]
(if (empty? args)
;; start app by default if no CLI command was supplied
(apply start-app args)
(case (first args)
"run"
(apply start-app args)
"help"
(do
(usage)
(System/exit 0))
("migrate" "rollback")
(do
(mount/start #'rems.config/env)
(migrations/migrate args (select-keys env [:database-url])))
"reset"
(do
(println "\n\n*** Are you absolutely sure??? Reset empties the whole database and runs migrations to empty db.***\nType 'YES' to proceed")
(when (= "YES" (read-line))
(do
(println "Running reset")
(mount/start #'rems.config/env)
(migrations/migrate args (select-keys env [:database-url])))))
"test-data"
(do
(mount/start #'rems.config/env
#'rems.db.core/*db*
#'rems.locales/translations)
(log/info "Creating test data")
(test-data/create-test-data!)
(test-data/create-performance-test-data!)
(log/info "Test data created"))
"demo-data"
(do
(mount/start #'rems.config/env
#'rems.db.core/*db*
#'rems.locales/translations)
(test-data/create-demo-data!))
"api-key"
(let [[_ command api-key & command-args] args]
(mount/start #'rems.config/env #'rems.db.core/*db*)
(case command
"get" (do)
"add" (api-key/update-api-key! api-key {:comment (str/join " " command-args)})
"delete" (api-key/delete-api-key! api-key)
"set-users" (api-key/update-api-key! api-key {:users command-args})
"allow" (let [[method path] command-args
entry {:method method :path path}
old (:paths (api-key/get-api-key api-key))]
(api-key/update-api-key! api-key {:paths (conj old entry)}))
"allow-all" (api-key/update-api-key! api-key {:paths nil})
(do (usage)
(System/exit 1)))
(if api-key
(prn (api-key/get-api-key api-key))
(mapv prn (api-key/get-api-keys))))
"ega"
(let [[_ command userid username password config-id & _] args]
(mount/start #'rems.config/env #'rems.db.core/*db*)
(case command
"api-key" (let [ega-config (->> (:entitlement-push env)
(filter (comp #{:ega} :type))
(find-first (comp #{config-id} :id)))]
(assert ega-config (str "Could not find :entitlement-push with :type :ega and :id " (pr-str config-id)))
(ega/generate-api-key-with-account {:userid userid :username username :password password :config ega-config}))
(do (usage)
(System/exit 1))))
"list-users"
(do
(mount/start #'rems.config/env #'rems.db.core/*db*)
(doseq [u (users/get-all-users)]
(-> u
(assoc :roles (roles/get-roles (:userid u)))
json/generate-string
println)))
"grant-role"
(let [[_ role user] args]
(if (not (and role user))
(do (usage)
(System/exit 1))
(do (mount/start #'rems.config/env #'rems.db.core/*db*)
(roles/add-role! user (keyword role)))))
"remove-role"
(let [[_ role user] args]
(if (not (and role user))
(do (usage)
(System/exit 1))
(do (mount/start #'rems.config/env #'rems.db.core/*db*)
(roles/remove-role! user (keyword role)))))
"validate"
(do
(mount/start #'rems.config/env #'rems.db.core/*db*)
(when-not (validate/validate)
(System/exit 2)))
"rename-user"
(let [[_ old-userid new-userid] args]
(if (not (and old-userid new-userid))
(do (usage)
(System/exit 1))
(do (println "\n\n*** Renaming a user's identity can't easily be undone. ***\nType 'YES' to proceed or anything else to run a simulation only.")
(let [simulate? (not= "YES" (read-line))]
(println (if simulate? "Simulating only..." "Renaming..."))
(mount/start #'rems.config/env #'rems.db.core/*db*)
(rems.db.fix-userid/fix-all old-userid new-userid simulate?)
(println "Finished.\n\nConsider rebooting the server process next to refresh all the caches, most importantly the application cache.")))))
(do
(println "Unrecognized argument:" (first args))
(usage)
(System/exit 1))))))
| 26299 | (ns rems.standalone
"Run the REMS app in an embedded http server."
(:require [clojure.string :as str]
[clojure.tools.cli :refer [parse-opts]]
[clojure.tools.logging :as log]
[luminus-migrations.core :as migrations]
[luminus.http-server :as http]
[luminus.repl-server :as repl]
[medley.core :refer [find-first]]
[mount.core :as mount]
[rems.api.services.ega :as ega]
[rems.application.search :as search]
[rems.common.git :as git]
[rems.config :refer [env]]
[rems.db.api-key :as api-key]
[rems.db.applications :as applications]
[rems.db.core :as db]
[rems.db.fix-userid]
[rems.db.roles :as roles]
[rems.db.test-data :as test-data]
[rems.db.users :as users]
[rems.handler :as handler]
[rems.json :as json]
[rems.validate :as validate])
(:import [sun.misc Signal SignalHandler])
(:refer-clojure :exclude [parse-opts])
(:gen-class))
(def cli-options
[["-p" "--port PORT" "Port number"
:parse-fn #(Integer/parseInt %)]])
(defn- jetty-configurator [server]
(let [pool (.getThreadPool server)]
(.setName pool "jetty-handlers")
server))
(mount/defstate
^{:on-reload :noop}
http-server
:start
(http/start (merge {:handler handler/handler
:send-server-version? false
:port (:port env)
:configurator jetty-configurator}
(when-not (:port env)
{:http? false})
(when (:ssl-port env)
{:ssl? true
:ssl-port (:ssl-port env)
:keystore (:ssl-keystore env)
:key-password (:ssl-keystore-password env)})))
:stop
(when http-server (http/stop http-server)))
(mount/defstate
^{:on-reload :noop}
repl-server
:start
(when-let [nrepl-port (env :nrepl-port)]
(repl/start {:port nrepl-port}))
:stop
(when repl-server
(repl/stop repl-server)))
(defn stop-app []
(doseq [component (:stopped (mount/stop))]
(log/info component "stopped")))
(defn- refresh-caches []
(log/info "Refreshing caches")
(applications/refresh-all-applications-cache!)
(search/refresh!)
(log/info "Caches refreshed"))
(defn start-app [& args]
(doseq [component (-> args
(parse-opts cli-options)
mount/start-with-args
:started)]
(log/info component "started"))
(.addShutdownHook (Runtime/getRuntime) (Thread. stop-app))
(validate/validate)
(refresh-caches))
;; The default of the JVM is to exit with code 128+signal. However, we
;; shut down gracefully on SIGINT and SIGTERM due to the exit hooks
;; mount has installed. Thus exit code 0 is the right choice. This
;; also makes REMS standalone work nicely with systemd: by default it
;; uses SIGTERM to stop services and expects a succesful exit.
(defn exit-on-signals! []
(let [exit (proxy [SignalHandler] []
(handle [sig]
(log/info "Shutting down due to signal" (.getName sig))
(System/exit 0)))]
(Signal/handle (Signal. "INT") exit) ;; e.g. ^C from terminal
(Signal/handle (Signal. "TERM") exit) ;; default kill signal of systemd
nil))
(defn -main
"Arguments can be either arguments to mount/start-with-args, or one of
\"run\" -- start the REMS application
\"help\" -- show this help
\"migrate\" -- migrate database
\"rollback\" -- roll back database migration
\"reset\" -- empties database and runs migrations to empty db
\"test-data\" -- insert test data into database
\"demo-data\" -- insert data for demoing purposes into database
\"validate\" -- validate data in db
\"list-users\" -- list users and roles
\"grant-role <role> <user>\" -- grant a role to a user
\"remove-role <role> <user>\" -- remove a role from a user
\"api-key get\" -- list all api keys
\"api-key get <api-key>\" -- get details of api key
\"api-key add <api-key> [<description>]\" -- add api key to db.
<description> is an optional text comment.
If a pre-existing <api-key> is given, update description for it.
\"api-key delete <api-key>\" -- remove api key from db.
\"api-key set-users <api-key> [<uid1> <uid2> ...]\" -- set allowed users for api key
An empty set of users means all users are allowed.
Adds the api key if it doesn't exist.
\"api-key allow <api-key> <method> <regex>\" -- add an entry to the allowed method/path whitelist
The special method `any` means any method.
The regex is a (Java) regular expression that should match the whole path of the request.
Example regex: /api/applications/[0-9]+/?
\"api-key allow-all <api-key>\" -- clears the allowed method/path whitelist.
An empty list means all methods and paths are allowed.
\"ega api-key <userid> <username> <password> <config-id>\" -- generate a new API-Key for the user using EGA login
\"rename-user <old-userid> <new-userid>\" -- change a user's identity from old to new"
[& args]
(exit-on-signals!)
(log/info "REMS" git/+version+)
(let [usage #(do
(println "Usage:")
(println (:doc (meta #'-main))))]
(if (empty? args)
;; start app by default if no CLI command was supplied
(apply start-app args)
(case (first args)
"run"
(apply start-app args)
"help"
(do
(usage)
(System/exit 0))
("migrate" "rollback")
(do
(mount/start #'rems.config/env)
(migrations/migrate args (select-keys env [:database-url])))
"reset"
(do
(println "\n\n*** Are you absolutely sure??? Reset empties the whole database and runs migrations to empty db.***\nType 'YES' to proceed")
(when (= "YES" (read-line))
(do
(println "Running reset")
(mount/start #'rems.config/env)
(migrations/migrate args (select-keys env [:database-url])))))
"test-data"
(do
(mount/start #'rems.config/env
#'rems.db.core/*db*
#'rems.locales/translations)
(log/info "Creating test data")
(test-data/create-test-data!)
(test-data/create-performance-test-data!)
(log/info "Test data created"))
"demo-data"
(do
(mount/start #'rems.config/env
#'rems.db.core/*db*
#'rems.locales/translations)
(test-data/create-demo-data!))
"api-key"
(let [[_ command api-key & command-args] args]
(mount/start #'rems.config/env #'rems.db.core/*db*)
(case command
"get" (do)
"add" (api-key/update-api-key! api-key {:comment (str/join " " command-args)})
"delete" (api-key/delete-api-key! api-key)
"set-users" (api-key/update-api-key! api-key {:users command-args})
"allow" (let [[method path] command-args
entry {:method method :path path}
old (:paths (api-key/get-api-key api-key))]
(api-key/update-api-key! api-key {:paths (conj old entry)}))
"allow-all" (api-key/update-api-key! api-key {:paths nil})
(do (usage)
(System/exit 1)))
(if api-key
(prn (api-key/get-api-key api-key))
(mapv prn (api-key/get-api-keys))))
"ega"
(let [[_ command userid username password config-id & _] args]
(mount/start #'rems.config/env #'rems.db.core/*db*)
(case command
"api-key" (let [ega-config (->> (:entitlement-push env)
(filter (comp #{:ega} :type))
(find-first (comp #{config-id} :id)))]
(assert ega-config (str "Could not find :entitlement-push with :type :ega and :id " (pr-str config-id)))
(ega/generate-api-key-with-account {:userid userid :username username :password <PASSWORD> :config ega-config}))
(do (usage)
(System/exit 1))))
"list-users"
(do
(mount/start #'rems.config/env #'rems.db.core/*db*)
(doseq [u (users/get-all-users)]
(-> u
(assoc :roles (roles/get-roles (:userid u)))
json/generate-string
println)))
"grant-role"
(let [[_ role user] args]
(if (not (and role user))
(do (usage)
(System/exit 1))
(do (mount/start #'rems.config/env #'rems.db.core/*db*)
(roles/add-role! user (keyword role)))))
"remove-role"
(let [[_ role user] args]
(if (not (and role user))
(do (usage)
(System/exit 1))
(do (mount/start #'rems.config/env #'rems.db.core/*db*)
(roles/remove-role! user (keyword role)))))
"validate"
(do
(mount/start #'rems.config/env #'rems.db.core/*db*)
(when-not (validate/validate)
(System/exit 2)))
"rename-user"
(let [[_ old-userid new-userid] args]
(if (not (and old-userid new-userid))
(do (usage)
(System/exit 1))
(do (println "\n\n*** Renaming a user's identity can't easily be undone. ***\nType 'YES' to proceed or anything else to run a simulation only.")
(let [simulate? (not= "YES" (read-line))]
(println (if simulate? "Simulating only..." "Renaming..."))
(mount/start #'rems.config/env #'rems.db.core/*db*)
(rems.db.fix-userid/fix-all old-userid new-userid simulate?)
(println "Finished.\n\nConsider rebooting the server process next to refresh all the caches, most importantly the application cache.")))))
(do
(println "Unrecognized argument:" (first args))
(usage)
(System/exit 1))))))
| true | (ns rems.standalone
"Run the REMS app in an embedded http server."
(:require [clojure.string :as str]
[clojure.tools.cli :refer [parse-opts]]
[clojure.tools.logging :as log]
[luminus-migrations.core :as migrations]
[luminus.http-server :as http]
[luminus.repl-server :as repl]
[medley.core :refer [find-first]]
[mount.core :as mount]
[rems.api.services.ega :as ega]
[rems.application.search :as search]
[rems.common.git :as git]
[rems.config :refer [env]]
[rems.db.api-key :as api-key]
[rems.db.applications :as applications]
[rems.db.core :as db]
[rems.db.fix-userid]
[rems.db.roles :as roles]
[rems.db.test-data :as test-data]
[rems.db.users :as users]
[rems.handler :as handler]
[rems.json :as json]
[rems.validate :as validate])
(:import [sun.misc Signal SignalHandler])
(:refer-clojure :exclude [parse-opts])
(:gen-class))
(def cli-options
[["-p" "--port PORT" "Port number"
:parse-fn #(Integer/parseInt %)]])
(defn- jetty-configurator [server]
(let [pool (.getThreadPool server)]
(.setName pool "jetty-handlers")
server))
(mount/defstate
^{:on-reload :noop}
http-server
:start
(http/start (merge {:handler handler/handler
:send-server-version? false
:port (:port env)
:configurator jetty-configurator}
(when-not (:port env)
{:http? false})
(when (:ssl-port env)
{:ssl? true
:ssl-port (:ssl-port env)
:keystore (:ssl-keystore env)
:key-password (:ssl-keystore-password env)})))
:stop
(when http-server (http/stop http-server)))
(mount/defstate
^{:on-reload :noop}
repl-server
:start
(when-let [nrepl-port (env :nrepl-port)]
(repl/start {:port nrepl-port}))
:stop
(when repl-server
(repl/stop repl-server)))
(defn stop-app []
(doseq [component (:stopped (mount/stop))]
(log/info component "stopped")))
(defn- refresh-caches []
(log/info "Refreshing caches")
(applications/refresh-all-applications-cache!)
(search/refresh!)
(log/info "Caches refreshed"))
(defn start-app [& args]
(doseq [component (-> args
(parse-opts cli-options)
mount/start-with-args
:started)]
(log/info component "started"))
(.addShutdownHook (Runtime/getRuntime) (Thread. stop-app))
(validate/validate)
(refresh-caches))
;; The default of the JVM is to exit with code 128+signal. However, we
;; shut down gracefully on SIGINT and SIGTERM due to the exit hooks
;; mount has installed. Thus exit code 0 is the right choice. This
;; also makes REMS standalone work nicely with systemd: by default it
;; uses SIGTERM to stop services and expects a succesful exit.
(defn exit-on-signals! []
(let [exit (proxy [SignalHandler] []
(handle [sig]
(log/info "Shutting down due to signal" (.getName sig))
(System/exit 0)))]
(Signal/handle (Signal. "INT") exit) ;; e.g. ^C from terminal
(Signal/handle (Signal. "TERM") exit) ;; default kill signal of systemd
nil))
(defn -main
"Arguments can be either arguments to mount/start-with-args, or one of
\"run\" -- start the REMS application
\"help\" -- show this help
\"migrate\" -- migrate database
\"rollback\" -- roll back database migration
\"reset\" -- empties database and runs migrations to empty db
\"test-data\" -- insert test data into database
\"demo-data\" -- insert data for demoing purposes into database
\"validate\" -- validate data in db
\"list-users\" -- list users and roles
\"grant-role <role> <user>\" -- grant a role to a user
\"remove-role <role> <user>\" -- remove a role from a user
\"api-key get\" -- list all api keys
\"api-key get <api-key>\" -- get details of api key
\"api-key add <api-key> [<description>]\" -- add api key to db.
<description> is an optional text comment.
If a pre-existing <api-key> is given, update description for it.
\"api-key delete <api-key>\" -- remove api key from db.
\"api-key set-users <api-key> [<uid1> <uid2> ...]\" -- set allowed users for api key
An empty set of users means all users are allowed.
Adds the api key if it doesn't exist.
\"api-key allow <api-key> <method> <regex>\" -- add an entry to the allowed method/path whitelist
The special method `any` means any method.
The regex is a (Java) regular expression that should match the whole path of the request.
Example regex: /api/applications/[0-9]+/?
\"api-key allow-all <api-key>\" -- clears the allowed method/path whitelist.
An empty list means all methods and paths are allowed.
\"ega api-key <userid> <username> <password> <config-id>\" -- generate a new API-Key for the user using EGA login
\"rename-user <old-userid> <new-userid>\" -- change a user's identity from old to new"
[& args]
(exit-on-signals!)
(log/info "REMS" git/+version+)
(let [usage #(do
(println "Usage:")
(println (:doc (meta #'-main))))]
(if (empty? args)
;; start app by default if no CLI command was supplied
(apply start-app args)
(case (first args)
"run"
(apply start-app args)
"help"
(do
(usage)
(System/exit 0))
("migrate" "rollback")
(do
(mount/start #'rems.config/env)
(migrations/migrate args (select-keys env [:database-url])))
"reset"
(do
(println "\n\n*** Are you absolutely sure??? Reset empties the whole database and runs migrations to empty db.***\nType 'YES' to proceed")
(when (= "YES" (read-line))
(do
(println "Running reset")
(mount/start #'rems.config/env)
(migrations/migrate args (select-keys env [:database-url])))))
"test-data"
(do
(mount/start #'rems.config/env
#'rems.db.core/*db*
#'rems.locales/translations)
(log/info "Creating test data")
(test-data/create-test-data!)
(test-data/create-performance-test-data!)
(log/info "Test data created"))
"demo-data"
(do
(mount/start #'rems.config/env
#'rems.db.core/*db*
#'rems.locales/translations)
(test-data/create-demo-data!))
"api-key"
(let [[_ command api-key & command-args] args]
(mount/start #'rems.config/env #'rems.db.core/*db*)
(case command
"get" (do)
"add" (api-key/update-api-key! api-key {:comment (str/join " " command-args)})
"delete" (api-key/delete-api-key! api-key)
"set-users" (api-key/update-api-key! api-key {:users command-args})
"allow" (let [[method path] command-args
entry {:method method :path path}
old (:paths (api-key/get-api-key api-key))]
(api-key/update-api-key! api-key {:paths (conj old entry)}))
"allow-all" (api-key/update-api-key! api-key {:paths nil})
(do (usage)
(System/exit 1)))
(if api-key
(prn (api-key/get-api-key api-key))
(mapv prn (api-key/get-api-keys))))
"ega"
(let [[_ command userid username password config-id & _] args]
(mount/start #'rems.config/env #'rems.db.core/*db*)
(case command
"api-key" (let [ega-config (->> (:entitlement-push env)
(filter (comp #{:ega} :type))
(find-first (comp #{config-id} :id)))]
(assert ega-config (str "Could not find :entitlement-push with :type :ega and :id " (pr-str config-id)))
(ega/generate-api-key-with-account {:userid userid :username username :password PI:PASSWORD:<PASSWORD>END_PI :config ega-config}))
(do (usage)
(System/exit 1))))
"list-users"
(do
(mount/start #'rems.config/env #'rems.db.core/*db*)
(doseq [u (users/get-all-users)]
(-> u
(assoc :roles (roles/get-roles (:userid u)))
json/generate-string
println)))
"grant-role"
(let [[_ role user] args]
(if (not (and role user))
(do (usage)
(System/exit 1))
(do (mount/start #'rems.config/env #'rems.db.core/*db*)
(roles/add-role! user (keyword role)))))
"remove-role"
(let [[_ role user] args]
(if (not (and role user))
(do (usage)
(System/exit 1))
(do (mount/start #'rems.config/env #'rems.db.core/*db*)
(roles/remove-role! user (keyword role)))))
"validate"
(do
(mount/start #'rems.config/env #'rems.db.core/*db*)
(when-not (validate/validate)
(System/exit 2)))
"rename-user"
(let [[_ old-userid new-userid] args]
(if (not (and old-userid new-userid))
(do (usage)
(System/exit 1))
(do (println "\n\n*** Renaming a user's identity can't easily be undone. ***\nType 'YES' to proceed or anything else to run a simulation only.")
(let [simulate? (not= "YES" (read-line))]
(println (if simulate? "Simulating only..." "Renaming..."))
(mount/start #'rems.config/env #'rems.db.core/*db*)
(rems.db.fix-userid/fix-all old-userid new-userid simulate?)
(println "Finished.\n\nConsider rebooting the server process next to refresh all the caches, most importantly the application cache.")))))
(do
(println "Unrecognized argument:" (first args))
(usage)
(System/exit 1))))))
|
[
{
"context": "st get-pass-char-test\n (is (= \\1 (get-pass-char \"00000155f8105dff7f56ee10fa9b9abd\"))))\n\n(deftest get-password-chars-test\n (is (= [",
"end": 1011,
"score": 0.998943030834198,
"start": 979,
"tag": "PASSWORD",
"value": "00000155f8105dff7f56ee10fa9b9abd"
}
] | test/adventofcode/day_05_test.clj | rxedu/adventofcode-2016 | 0 | (ns adventofcode.day-05-test
(:require [clojure.test :refer [deftest is]]
[adventofcode.day-05 :refer
[get-hash
get-pass-char
get-pass-chars
get-pass-pos
valid-pos?
read-pass-pos
target-hash?]]))
(deftest get-hash-test
(is (= "71c0a2a39d825b4b4ac6a74257fc6eda" (get-hash "adb" 5)))
(is (= "00000155f8105dff7f56ee10fa9b9abd" (get-hash "abc" 3231929))))
(deftest target-hash?-test
(is (false? (target-hash? "71c0a2a39d825b4b4ac6a74257fc6eda")))
(is (true? (target-hash? "00000155f8105dff7f56ee10fa9b9abd")))
(is (true? (target-hash? "00000a39d825b4b4ac6a74257fc6eda"))))
(deftest valid-pos?-test
(is (true? (valid-pos? {:k 4 :v \b} [])))
(is (false? (valid-pos? {:k 10 :v \b} [])))
(is (false? (valid-pos? {:k 3 :v \b} [{:k 3 :v \q}])))
(is (true? (valid-pos? {:k 3 :v \b} [{:k 4 :v \b}]))))
(deftest get-pass-char-test
(is (= \1 (get-pass-char "00000155f8105dff7f56ee10fa9b9abd"))))
(deftest get-password-chars-test
(is (= [\1] (get-pass-chars "abc" 1 3231925))))
(deftest get-password-pos-test
(is (= [{:k 1 :v \5}] (get-pass-pos "abc" 1 3231928))))
(deftest read-pass-pos-test
(is (= [\5 \a] (read-pass-pos [{:k 2 :v \a} {:k 1 :v \5}]))))
| 14569 | (ns adventofcode.day-05-test
(:require [clojure.test :refer [deftest is]]
[adventofcode.day-05 :refer
[get-hash
get-pass-char
get-pass-chars
get-pass-pos
valid-pos?
read-pass-pos
target-hash?]]))
(deftest get-hash-test
(is (= "71c0a2a39d825b4b4ac6a74257fc6eda" (get-hash "adb" 5)))
(is (= "00000155f8105dff7f56ee10fa9b9abd" (get-hash "abc" 3231929))))
(deftest target-hash?-test
(is (false? (target-hash? "71c0a2a39d825b4b4ac6a74257fc6eda")))
(is (true? (target-hash? "00000155f8105dff7f56ee10fa9b9abd")))
(is (true? (target-hash? "00000a39d825b4b4ac6a74257fc6eda"))))
(deftest valid-pos?-test
(is (true? (valid-pos? {:k 4 :v \b} [])))
(is (false? (valid-pos? {:k 10 :v \b} [])))
(is (false? (valid-pos? {:k 3 :v \b} [{:k 3 :v \q}])))
(is (true? (valid-pos? {:k 3 :v \b} [{:k 4 :v \b}]))))
(deftest get-pass-char-test
(is (= \1 (get-pass-char "<PASSWORD>"))))
(deftest get-password-chars-test
(is (= [\1] (get-pass-chars "abc" 1 3231925))))
(deftest get-password-pos-test
(is (= [{:k 1 :v \5}] (get-pass-pos "abc" 1 3231928))))
(deftest read-pass-pos-test
(is (= [\5 \a] (read-pass-pos [{:k 2 :v \a} {:k 1 :v \5}]))))
| true | (ns adventofcode.day-05-test
(:require [clojure.test :refer [deftest is]]
[adventofcode.day-05 :refer
[get-hash
get-pass-char
get-pass-chars
get-pass-pos
valid-pos?
read-pass-pos
target-hash?]]))
(deftest get-hash-test
(is (= "71c0a2a39d825b4b4ac6a74257fc6eda" (get-hash "adb" 5)))
(is (= "00000155f8105dff7f56ee10fa9b9abd" (get-hash "abc" 3231929))))
(deftest target-hash?-test
(is (false? (target-hash? "71c0a2a39d825b4b4ac6a74257fc6eda")))
(is (true? (target-hash? "00000155f8105dff7f56ee10fa9b9abd")))
(is (true? (target-hash? "00000a39d825b4b4ac6a74257fc6eda"))))
(deftest valid-pos?-test
(is (true? (valid-pos? {:k 4 :v \b} [])))
(is (false? (valid-pos? {:k 10 :v \b} [])))
(is (false? (valid-pos? {:k 3 :v \b} [{:k 3 :v \q}])))
(is (true? (valid-pos? {:k 3 :v \b} [{:k 4 :v \b}]))))
(deftest get-pass-char-test
(is (= \1 (get-pass-char "PI:PASSWORD:<PASSWORD>END_PI"))))
(deftest get-password-chars-test
(is (= [\1] (get-pass-chars "abc" 1 3231925))))
(deftest get-password-pos-test
(is (= [{:k 1 :v \5}] (get-pass-pos "abc" 1 3231928))))
(deftest read-pass-pos-test
(is (= [\5 \a] (read-pass-pos [{:k 2 :v \a} {:k 1 :v \5}]))))
|
[
{
"context": "ices-login (fn [] {:status 200, :body {:username \"qa@artstor.org\"}})\n forum/reserve-imata-asset (",
"end": 591,
"score": 0.9999188780784607,
"start": 577,
"tag": "EMAIL",
"value": "qa@artstor.org"
},
{
"context": "sonal-collection \"my_awesome_pic.jpg\" {:username \"qa@artstor.org\" :profile-id 12345})))))\n (testing \"test uploadi",
"end": 1228,
"score": 0.9999158978462219,
"start": 1214,
"tag": "EMAIL",
"value": "qa@artstor.org"
},
{
"context": "sonal-collection \"my_awesome_pic.jpg\" {:username \"qa@artstor.org\" :profile-id 12345}))))))\n\n(deftest test-update-m",
"end": 2131,
"score": 0.9999122023582458,
"start": 2117,
"tag": "EMAIL",
"value": "qa@artstor.org"
},
{
"context": "ices-login (fn [] {:status 200, :body {:username \"qa@artstor.org\"}})\n forum/reserve-imata-asset (",
"end": 2423,
"score": 0.999912440776825,
"start": 2409,
"tag": "EMAIL",
"value": "qa@artstor.org"
},
{
"context": "ction \"my_awesome_pic1.jpg\" 123456789 {:username \"qa@artstor.org\" :profile-id 12345})))))\n (testing \"test updatin",
"end": 3037,
"score": 0.9999149441719055,
"start": 3023,
"tag": "EMAIL",
"value": "qa@artstor.org"
},
{
"context": "ction \"my_awesome_pic1.jpg\" 123456789 {:username \"qa@artstor.org\" :profile-id 12345}))))))\n\n(deftest test-delete-i",
"end": 3776,
"score": 0.9999182820320129,
"start": 3762,
"tag": "EMAIL",
"value": "qa@artstor.org"
},
{
"context": "ices-login (fn [] {:status 200, :body {:username \"qa@artstor.org\"}})\n forum/delete-pc-images-from",
"end": 4158,
"score": 0.9999212622642517,
"start": 4144,
"tag": "EMAIL",
"value": "qa@artstor.org"
},
{
"context": "rom-personal-collection [\"123456789\"] {:username \"qa@artstor.org\" :profile-id 12345})))))\n (testing \"test deletin",
"end": 4358,
"score": 0.9999180436134338,
"start": 4344,
"tag": "EMAIL",
"value": "qa@artstor.org"
},
{
"context": "ices-login (fn [] {:status 200, :body {:username \"qa@artstor.org\"}})\n forum/delete-pc-images-from",
"end": 4702,
"score": 0.9999210834503174,
"start": 4688,
"tag": "EMAIL",
"value": "qa@artstor.org"
},
{
"context": "123456789\", \"123456780\", \"123456781\"] {:username \"qa@artstor.org\" :profile-id 12345})))))\n (testing \"test deletin",
"end": 4928,
"score": 0.9999235272407532,
"start": 4914,
"tag": "EMAIL",
"value": "qa@artstor.org"
},
{
"context": "e - failed login\"\n (with-redefs [env {:secret \"swiss cheese\"}\n forum/validate-owner-before-d",
"end": 5066,
"score": 0.9497038722038269,
"start": 5054,
"tag": "KEY",
"value": "swiss cheese"
},
{
"context": "rom-personal-collection [\"123456789\"] {:username \"qa@artstor.org\" :profile-id 12345}))))))\n\n(deftest test-getting-",
"end": 5410,
"score": 0.9999216198921204,
"start": 5396,
"tag": "EMAIL",
"value": "qa@artstor.org"
},
{
"context": "c-images [\"1234567890\", \"9087654321\"] {:username \"qa@artstor.org\" :profile-id 12345}))))))\n\n(deftest test-deleted-",
"end": 7165,
"score": 0.9999246597290039,
"start": 7151,
"tag": "EMAIL",
"value": "qa@artstor.org"
},
{
"context": "ices-login (fn [] {:status 200, :body {:username \"pc@artstor.org\"}})\n http/put (fn [_ _] {:status",
"end": 9855,
"score": 0.9999220967292786,
"start": 9841,
"tag": "EMAIL",
"value": "pc@artstor.org"
},
{
"context": " :body \"{\\\"assets\\\": [{\\\"fd_68602_s\\\":\\\"Mr Pumpkin\\\", \\\"id\\\": 1234567890, \\\"created_by\\\": 12345, \\\"f",
"end": 10210,
"score": 0.683892548084259,
"start": 10203,
"tag": "NAME",
"value": "Pumpkin"
},
{
"context": "ess true})]\n (let [artstor-user {:username \"qa@artstor.org\" :profile-id 12345}\n pcookies { :testc",
"end": 10645,
"score": 0.9999232292175293,
"start": 10631,
"tag": "EMAIL",
"value": "qa@artstor.org"
},
{
"context": "7890, :metadata [{:field_id \"fd_68602_s\", :value \"Mr Pumpkin\"} {:field_id \"fd_68619_s\", :value \"Pumpkin\"}]}\n ",
"end": 10823,
"score": 0.8831020593643188,
"start": 10813,
"tag": "NAME",
"value": "Mr Pumpkin"
},
{
"context": "ices-login (fn [] {:status 200, :body {:username \"pc@artstor.org\"}})\n http/put (fn [_ _] {:status",
"end": 11234,
"score": 0.999919593334198,
"start": 11220,
"tag": "EMAIL",
"value": "pc@artstor.org"
},
{
"context": "ess true})]\n (let [artstor-user {:username \"qa@artstor.org\" :profile-id 12345}\n pcookies { :testc",
"end": 11898,
"score": 0.9999213218688965,
"start": 11884,
"tag": "EMAIL",
"value": "qa@artstor.org"
},
{
"context": "ices-login (fn [] {:status 200, :body {:username \"pc@artstor.org\"}})\n http/put (fn [_ _] {:status",
"end": 12504,
"score": 0.9999184608459473,
"start": 12490,
"tag": "EMAIL",
"value": "pc@artstor.org"
},
{
"context": "ess true})]\n (let [artstor-user {:username \"qa@artstor.org\" :profile-id 12345}\n pcookies { :testc",
"end": 13294,
"score": 0.999926745891571,
"start": 13280,
"tag": "EMAIL",
"value": "qa@artstor.org"
},
{
"context": "7890, :metadata [{:field_id \"fd_68602_s\", :value \"Mr Pumpkin\"} {:field_id \"fd_68619_s\", :value \"Pumpkin\"}]}]\n ",
"end": 13474,
"score": 0.7374532222747803,
"start": 13464,
"tag": "NAME",
"value": "Mr Pumpkin"
},
{
"context": " :body \"{\\\"assets\\\": [{\\\"fd_68602_s\\\":\\\"Mr Pumpkin\\\", \\\"id\\\": 1234567890, \\\"created_by\\\": 12345, \\\"f",
"end": 14173,
"score": 0.7079238295555115,
"start": 14163,
"tag": "NAME",
"value": "Mr Pumpkin"
},
{
"context": "ess true})]\n (let [artstor-user {:username \"qa@artstor.org\" :profile-id 12345}\n many-ssids-data [",
"end": 14608,
"score": 0.9999272227287292,
"start": 14594,
"tag": "EMAIL",
"value": "qa@artstor.org"
},
{
"context": "7890, :metadata [{:field_id \"fd_68602_s\", :value \"Mr Pumpkin\"} {:field_id \"fd_68619_s\", :value \"Pumpkin\"}]}]\n ",
"end": 14731,
"score": 0.7101012468338013,
"start": 14721,
"tag": "NAME",
"value": "Mr Pumpkin"
}
] | test/artstor_collection_service_os/forum_test.clj | ithaka/artstor-collection-service-os | 0 | (ns artstor-collection-service-os.forum-test
(:require [artstor-collection-service-os.forum :as forum]
[clojure.test :refer :all]
[clojure.test.check.clojure-test :refer [defspec]]
[clj-http.client :as http]
[environ.core :refer [env]]
[clojure.tools.logging :as logger]))
(deftest test-upload-image-to-personal-collection
(testing "test uploading an image to personal collection"
(with-redefs [env {:secret "swiss cheese"}
forum/forum-services-login (fn [] {:status 200, :body {:username "qa@artstor.org"}})
forum/reserve-imata-asset (fn [_ _] {:status 200})
forum/upload-image-to-storage (fn [_ _ _ _] "100")
forum/assign-uploaded-asset-on-imata (fn [_ _ _] {:success true :assets [{:id "123456789"}]})
forum/update-asset-owner-on-imata-initial-upload (fn [_ _ _] {:success true})
forum/massage-assign-result (fn [_ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] true)]
(is (= {:success true :forum-published-status true} (forum/upload-image-to-personal-collection "my_awesome_pic.jpg" {:username "qa@artstor.org" :profile-id 12345})))))
(testing "test uploading an image to personal collection - failed login"
(with-redefs [env {:secret "swiss cheese"}
forum/forum-services-login (fn [] nil)
forum/reserve-imata-asset (fn [_ _] {:status 200})
forum/upload-image-to-storage (fn [_ _ _ _] "100")
forum/assign-uploaded-asset-on-imata (fn [_ _ _] {:success true})
forum/assign-uploaded-asset-on-imata (fn [_ _ _] {:success true :assets [{:id "123456789"}]})
forum/update-asset-owner-on-imata-initial-upload (fn [_ _ _] {:success true})
forum/massage-assign-result (fn [_ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(is (= {:success false} (forum/upload-image-to-personal-collection "my_awesome_pic.jpg" {:username "qa@artstor.org" :profile-id 12345}))))))
(deftest test-update-media-in-personal-collection
(testing "test updating media of an assest in personal collection"
(with-redefs [env {:secret "swiss cheese"}
forum/forum-services-login (fn [] {:status 200, :body {:username "qa@artstor.org"}})
forum/reserve-imata-asset (fn [_ _] {:status 200})
forum/upload-image-to-storage (fn [_ _ _ _] "100")
forum/update-uploaded-asset-on-imata (fn [_ _ _ _] {:success true, :updated_by 12345, :filename "my_awesome_pic1.jpg" :id 123456789})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] true)]
(is (= {:success true :forum-published-status true} (forum/update-media-in-personal-collection "my_awesome_pic1.jpg" 123456789 {:username "qa@artstor.org" :profile-id 12345})))))
(testing "test updating media of an assest in personal collection - failed login"
(with-redefs [env {:secret "swiss cheese"}
forum/forum-services-login (fn [] nil)
forum/reserve-imata-asset (fn [_ _] {:status 200})
forum/upload-image-to-storage (fn [_ _ _ _] "100")
forum/update-uploaded-asset-on-imata (fn [_ _ _ _] {:success true})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(is (= {:success false} (forum/update-media-in-personal-collection "my_awesome_pic1.jpg" 123456789 {:username "qa@artstor.org" :profile-id 12345}))))))
(deftest test-delete-image-from-personal-collection
(testing "test deleting personal collection image - single object"
(with-redefs [env {:secret "swiss cheese"}
forum/validate-owner-before-delete-pc-images (fn [_ _] ["123456789"])
forum/forum-services-login (fn [] {:status 200, :body {:username "qa@artstor.org"}})
forum/delete-pc-images-from-forum (fn [_ _] {:success true})]
(is (= {:success true} (forum/delete-images-from-personal-collection ["123456789"] {:username "qa@artstor.org" :profile-id 12345})))))
(testing "test deleting personal collection image - multiple objects"
(with-redefs [env {:secret "swiss cheese"}
forum/validate-owner-before-delete-pc-images (fn [_ _] ["123456789", "123456780"])
forum/forum-services-login (fn [] {:status 200, :body {:username "qa@artstor.org"}})
forum/delete-pc-images-from-forum (fn [_ _] {:success true})]
(is (= {:success true} (forum/delete-images-from-personal-collection ["123456789", "123456780", "123456781"] {:username "qa@artstor.org" :profile-id 12345})))))
(testing "test deleting personal collection image - failed login"
(with-redefs [env {:secret "swiss cheese"}
forum/validate-owner-before-delete-pc-images (fn [_ _] ["123456789"])
forum/forum-services-login (fn [] nil)
forum/delete-pc-images-from-forum (fn [_ _] {:success true})]
(is (= {:success false} (forum/delete-images-from-personal-collection ["123456789"] {:username "qa@artstor.org" :profile-id 12345}))))))
(deftest test-getting-object-ids-from-ssids
(testing "test getting good object-id from ssid"
(with-redefs [http/post (fn [_ _] {:status 200,
:body {:requestId "22403631-c2b3-4f02-a9c1-184e7a771fab",
:total 1,
:results [{:date nil,
:updatedon "2018-02-09T23:04:06Z",
:yearend nil,
:doi "10.2307/artstor.1234567890",
:collections [37436],
:id "d3385544-6c0c-3cd7-9aa7-527ef07fed24",
:artstorid "SS37436_37436_39075864",}]}})]
(is (= ["SS37436_37436_39075864"] (forum/get-object-ids-from-ssids [1234567890]))))))
(deftest test-validate-owner-before-delete-pc-images
(testing "test getting owner allowed ssids from given ssids"
(with-redefs [logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))
http/post (fn [_ _] {:status 200,
:body {:requestId "22403631-c2b3-4f02-a9c1-184e7a771fab",
:total 1,
:results [{:personalcollectionowner 12345,
:additional_Fields {:ssid "1234567890"}}]}})]
(is (= ["1234567890"] (forum/validate-owner-before-delete-pc-images ["1234567890", "9087654321"] {:username "qa@artstor.org" :profile-id 12345}))))))
(deftest test-deleted-object-ids-from-ssids
(testing "test getting deleted object-id from ssid"
(with-redefs [http/post (fn [_ _] {:status 200,
:body {:requestId "22403631-c2b3-4f02-a9c1-184e7a771fab",
:total 1,
:results [{:date "",
:updatedon "2018-02-09T23:04:06Z",
:yearend nil,
:name "Removed by request",
:doi "10.2307/artstor.1234567890",
:collections [],
:id "d3385544-6c0c-3cd7-9aa7-527ef07fed24",
:artstorid "",}]}})]
(is (= [""] (forum/get-object-ids-from-ssids [1234567890]))))))
(deftest test-deleted-object-ids-from-ssids
(testing "test getting not object-id from ssid"
(with-redefs [http/post (fn [_ _] {:status 200,
:body {:requestId "22403631-c2b3-4f02-a9c1-184e7a771fab",
:total 0,
:results []}})]
(is (= [""] (forum/get-object-ids-from-ssids [1234567890]))))))
(deftest test-magically-massage-pc-metadata
(testing "Converts the UI sensible structure happy path"
(let [one-ssids-data {:ssid 12345678, :metadata [{:field_id "fd_68634_s", :value "Working"} {:field_id "fd_68633_s", :value "Awesome"}]}
massaged-fields (forum/magically-massage-pc-metadata one-ssids-data)]
(is (= {:id 12345678, "fd_68634_s" "Working", "fd_68633_s" "Awesome"} massaged-fields)))))
(deftest test-bad-massage-pc-metadata
(testing "No ssid test conversion"
(let [one-ssids-data { :metadata [{:field_id "fd_68634_s", :value "Working"} {:field_id "fd_68633_s", :value "Awesome"}]}
massaged-fields (forum/magically-massage-pc-metadata one-ssids-data)]
(is (= {:id nil, "fd_68634_s" "Working", "fd_68633_s" "Awesome"} massaged-fields))))
(testing "No metadata test conversion"
(let [one-ssids-data { :ssid 12345678}
massaged-fields (forum/magically-massage-pc-metadata one-ssids-data)]
(is (= {:id 12345678 } massaged-fields)))))
(deftest test-update-image-metadata
(testing "Tests update image metadata happy path"
(with-redefs [forum/forum-services-login (fn [] {:status 200, :body {:username "pc@artstor.org"}})
http/put (fn [_ _] {:status 200,
:headers {"Server" "gunicorn/19.0.0",
"Content-Length" "1534", "Content-Type" "application/json; charset=UTF-8"},
:body "{\"assets\": [{\"fd_68602_s\":\"Mr Pumpkin\", \"id\": 1234567890, \"created_by\": 12345, \"filename\": \"scary_friday_prod_deploy.jpg\",\"fd_68619_s\": \"Pumpkin\", \"project_id\": 3793, \"fd_68607_s\": \"Friday the Prod Deploy\"}], \"success\": true}"})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(let [artstor-user {:username "qa@artstor.org" :profile-id 12345}
pcookies { :testcookie "magicallydelicious"}
one-ssids-data {:ssid 1234567890, :metadata [{:field_id "fd_68602_s", :value "Mr Pumpkin"} {:field_id "fd_68619_s", :value "Pumpkin"}]}
result (forum/update-image-metadata (one-ssids-data :ssid) one-ssids-data artstor-user)]
(is (= {:ssid 1234567890 :success true :status 200} result))))))
(deftest test-bad-update-image-metadata
(testing "Tests update image metadata sad path"
(with-redefs [forum/forum-services-login (fn [] {:status 200, :body {:username "pc@artstor.org"}})
http/put (fn [_ _] {:status 500,
:headers {"Server" "gunicorn/19.0.0",
"Content-Length" "1534", "Content-Type" "application/json; charset=UTF-8"},
:body "<head>\n <title>Internal Server Error</title>\n </head>\n <body>\n <h1>Internal Server Error</h1>\n </body>\n</html>"})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(let [artstor-user {:username "qa@artstor.org" :profile-id 12345}
pcookies { :testcookie "magicallydelicious"}
one-ssids-data {:ssid 9999867318, :metadata [{:field_id "fd_68602_s", :value "Mr Pumpkin"} {:field_id "fd_68619_s", :value "Pumpkin"}]}
result (forum/update-image-metadata (one-ssids-data :ssid) one-ssids-data artstor-user)]
(is (= {:ssid 9999867318 :success false :status 500} result))))))
(deftest test-multiple-update-image-metadata
(testing "Tests update multiple image metadata happy path"
(with-redefs [forum/forum-services-login (fn [] {:status 200, :body {:username "pc@artstor.org"}})
http/put (fn [_ _] {:status 200,
:headers {"Server" "gunicorn/19.0.0",
"Content-Length" "1534", "Content-Type" "application/json; charset=UTF-8"},
:body "{\"assets\": [{\"fd_68602_s\":\"Mr Pumpkin\", \"id\": 1234567890, \"created_by\": 12345, \"filename\": \"scary_friday_prod_deploy.jpg\",\"fd_68619_s\": \"Pumpkin\", \"project_id\": 3793, \"fd_68607_s\": \"Friday the Prod Deploy\"}], \"success\": true}"})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(let [artstor-user {:username "qa@artstor.org" :profile-id 12345}
pcookies { :testcookie "magicallydelicious"}
many-ssids-data [{:ssid 1234567890, :metadata [{:field_id "fd_68602_s", :value "Mr Pumpkin"} {:field_id "fd_68619_s", :value "Pumpkin"}]}]
result (forum/update-multiple-images-metadata many-ssids-data artstor-user)]
(is (result :success))))))
(deftest test-bad-login-multiple-update-image-metadata
(testing "Tests failed login update multiple image metadata"
(with-redefs [forum/forum-services-login (fn [] nil)
http/put (fn [_ _] {:status 200,
:headers {"Server" "gunicorn/19.0.0",
"Content-Length" "1534", "Content-Type" "application/json; charset=UTF-8"},
:body "{\"assets\": [{\"fd_68602_s\":\"Mr Pumpkin\", \"id\": 1234567890, \"created_by\": 12345, \"filename\": \"scary_friday_prod_deploy.jpg\",\"fd_68619_s\": \"Pumpkin\", \"project_id\": 3793, \"fd_68607_s\": \"Friday the Prod Deploy\"}], \"success\": true}"})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(let [artstor-user {:username "qa@artstor.org" :profile-id 12345}
many-ssids-data [{:ssid 1234567890, :metadata [{:field_id "fd_68602_s", :value "Mr Pumpkin"} {:field_id "fd_68619_s", :value "Pumpkin"}]}]
result (forum/update-multiple-images-metadata many-ssids-data artstor-user)]
(is (result :success)))))) | 40064 | (ns artstor-collection-service-os.forum-test
(:require [artstor-collection-service-os.forum :as forum]
[clojure.test :refer :all]
[clojure.test.check.clojure-test :refer [defspec]]
[clj-http.client :as http]
[environ.core :refer [env]]
[clojure.tools.logging :as logger]))
(deftest test-upload-image-to-personal-collection
(testing "test uploading an image to personal collection"
(with-redefs [env {:secret "swiss cheese"}
forum/forum-services-login (fn [] {:status 200, :body {:username "<EMAIL>"}})
forum/reserve-imata-asset (fn [_ _] {:status 200})
forum/upload-image-to-storage (fn [_ _ _ _] "100")
forum/assign-uploaded-asset-on-imata (fn [_ _ _] {:success true :assets [{:id "123456789"}]})
forum/update-asset-owner-on-imata-initial-upload (fn [_ _ _] {:success true})
forum/massage-assign-result (fn [_ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] true)]
(is (= {:success true :forum-published-status true} (forum/upload-image-to-personal-collection "my_awesome_pic.jpg" {:username "<EMAIL>" :profile-id 12345})))))
(testing "test uploading an image to personal collection - failed login"
(with-redefs [env {:secret "swiss cheese"}
forum/forum-services-login (fn [] nil)
forum/reserve-imata-asset (fn [_ _] {:status 200})
forum/upload-image-to-storage (fn [_ _ _ _] "100")
forum/assign-uploaded-asset-on-imata (fn [_ _ _] {:success true})
forum/assign-uploaded-asset-on-imata (fn [_ _ _] {:success true :assets [{:id "123456789"}]})
forum/update-asset-owner-on-imata-initial-upload (fn [_ _ _] {:success true})
forum/massage-assign-result (fn [_ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(is (= {:success false} (forum/upload-image-to-personal-collection "my_awesome_pic.jpg" {:username "<EMAIL>" :profile-id 12345}))))))
(deftest test-update-media-in-personal-collection
(testing "test updating media of an assest in personal collection"
(with-redefs [env {:secret "swiss cheese"}
forum/forum-services-login (fn [] {:status 200, :body {:username "<EMAIL>"}})
forum/reserve-imata-asset (fn [_ _] {:status 200})
forum/upload-image-to-storage (fn [_ _ _ _] "100")
forum/update-uploaded-asset-on-imata (fn [_ _ _ _] {:success true, :updated_by 12345, :filename "my_awesome_pic1.jpg" :id 123456789})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] true)]
(is (= {:success true :forum-published-status true} (forum/update-media-in-personal-collection "my_awesome_pic1.jpg" 123456789 {:username "<EMAIL>" :profile-id 12345})))))
(testing "test updating media of an assest in personal collection - failed login"
(with-redefs [env {:secret "swiss cheese"}
forum/forum-services-login (fn [] nil)
forum/reserve-imata-asset (fn [_ _] {:status 200})
forum/upload-image-to-storage (fn [_ _ _ _] "100")
forum/update-uploaded-asset-on-imata (fn [_ _ _ _] {:success true})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(is (= {:success false} (forum/update-media-in-personal-collection "my_awesome_pic1.jpg" 123456789 {:username "<EMAIL>" :profile-id 12345}))))))
(deftest test-delete-image-from-personal-collection
(testing "test deleting personal collection image - single object"
(with-redefs [env {:secret "swiss cheese"}
forum/validate-owner-before-delete-pc-images (fn [_ _] ["123456789"])
forum/forum-services-login (fn [] {:status 200, :body {:username "<EMAIL>"}})
forum/delete-pc-images-from-forum (fn [_ _] {:success true})]
(is (= {:success true} (forum/delete-images-from-personal-collection ["123456789"] {:username "<EMAIL>" :profile-id 12345})))))
(testing "test deleting personal collection image - multiple objects"
(with-redefs [env {:secret "swiss cheese"}
forum/validate-owner-before-delete-pc-images (fn [_ _] ["123456789", "123456780"])
forum/forum-services-login (fn [] {:status 200, :body {:username "<EMAIL>"}})
forum/delete-pc-images-from-forum (fn [_ _] {:success true})]
(is (= {:success true} (forum/delete-images-from-personal-collection ["123456789", "123456780", "123456781"] {:username "<EMAIL>" :profile-id 12345})))))
(testing "test deleting personal collection image - failed login"
(with-redefs [env {:secret "<KEY>"}
forum/validate-owner-before-delete-pc-images (fn [_ _] ["123456789"])
forum/forum-services-login (fn [] nil)
forum/delete-pc-images-from-forum (fn [_ _] {:success true})]
(is (= {:success false} (forum/delete-images-from-personal-collection ["123456789"] {:username "<EMAIL>" :profile-id 12345}))))))
(deftest test-getting-object-ids-from-ssids
(testing "test getting good object-id from ssid"
(with-redefs [http/post (fn [_ _] {:status 200,
:body {:requestId "22403631-c2b3-4f02-a9c1-184e7a771fab",
:total 1,
:results [{:date nil,
:updatedon "2018-02-09T23:04:06Z",
:yearend nil,
:doi "10.2307/artstor.1234567890",
:collections [37436],
:id "d3385544-6c0c-3cd7-9aa7-527ef07fed24",
:artstorid "SS37436_37436_39075864",}]}})]
(is (= ["SS37436_37436_39075864"] (forum/get-object-ids-from-ssids [1234567890]))))))
(deftest test-validate-owner-before-delete-pc-images
(testing "test getting owner allowed ssids from given ssids"
(with-redefs [logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))
http/post (fn [_ _] {:status 200,
:body {:requestId "22403631-c2b3-4f02-a9c1-184e7a771fab",
:total 1,
:results [{:personalcollectionowner 12345,
:additional_Fields {:ssid "1234567890"}}]}})]
(is (= ["1234567890"] (forum/validate-owner-before-delete-pc-images ["1234567890", "9087654321"] {:username "<EMAIL>" :profile-id 12345}))))))
(deftest test-deleted-object-ids-from-ssids
(testing "test getting deleted object-id from ssid"
(with-redefs [http/post (fn [_ _] {:status 200,
:body {:requestId "22403631-c2b3-4f02-a9c1-184e7a771fab",
:total 1,
:results [{:date "",
:updatedon "2018-02-09T23:04:06Z",
:yearend nil,
:name "Removed by request",
:doi "10.2307/artstor.1234567890",
:collections [],
:id "d3385544-6c0c-3cd7-9aa7-527ef07fed24",
:artstorid "",}]}})]
(is (= [""] (forum/get-object-ids-from-ssids [1234567890]))))))
(deftest test-deleted-object-ids-from-ssids
(testing "test getting not object-id from ssid"
(with-redefs [http/post (fn [_ _] {:status 200,
:body {:requestId "22403631-c2b3-4f02-a9c1-184e7a771fab",
:total 0,
:results []}})]
(is (= [""] (forum/get-object-ids-from-ssids [1234567890]))))))
(deftest test-magically-massage-pc-metadata
(testing "Converts the UI sensible structure happy path"
(let [one-ssids-data {:ssid 12345678, :metadata [{:field_id "fd_68634_s", :value "Working"} {:field_id "fd_68633_s", :value "Awesome"}]}
massaged-fields (forum/magically-massage-pc-metadata one-ssids-data)]
(is (= {:id 12345678, "fd_68634_s" "Working", "fd_68633_s" "Awesome"} massaged-fields)))))
(deftest test-bad-massage-pc-metadata
(testing "No ssid test conversion"
(let [one-ssids-data { :metadata [{:field_id "fd_68634_s", :value "Working"} {:field_id "fd_68633_s", :value "Awesome"}]}
massaged-fields (forum/magically-massage-pc-metadata one-ssids-data)]
(is (= {:id nil, "fd_68634_s" "Working", "fd_68633_s" "Awesome"} massaged-fields))))
(testing "No metadata test conversion"
(let [one-ssids-data { :ssid 12345678}
massaged-fields (forum/magically-massage-pc-metadata one-ssids-data)]
(is (= {:id 12345678 } massaged-fields)))))
(deftest test-update-image-metadata
(testing "Tests update image metadata happy path"
(with-redefs [forum/forum-services-login (fn [] {:status 200, :body {:username "<EMAIL>"}})
http/put (fn [_ _] {:status 200,
:headers {"Server" "gunicorn/19.0.0",
"Content-Length" "1534", "Content-Type" "application/json; charset=UTF-8"},
:body "{\"assets\": [{\"fd_68602_s\":\"Mr <NAME>\", \"id\": 1234567890, \"created_by\": 12345, \"filename\": \"scary_friday_prod_deploy.jpg\",\"fd_68619_s\": \"Pumpkin\", \"project_id\": 3793, \"fd_68607_s\": \"Friday the Prod Deploy\"}], \"success\": true}"})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(let [artstor-user {:username "<EMAIL>" :profile-id 12345}
pcookies { :testcookie "magicallydelicious"}
one-ssids-data {:ssid 1234567890, :metadata [{:field_id "fd_68602_s", :value "<NAME>"} {:field_id "fd_68619_s", :value "Pumpkin"}]}
result (forum/update-image-metadata (one-ssids-data :ssid) one-ssids-data artstor-user)]
(is (= {:ssid 1234567890 :success true :status 200} result))))))
(deftest test-bad-update-image-metadata
(testing "Tests update image metadata sad path"
(with-redefs [forum/forum-services-login (fn [] {:status 200, :body {:username "<EMAIL>"}})
http/put (fn [_ _] {:status 500,
:headers {"Server" "gunicorn/19.0.0",
"Content-Length" "1534", "Content-Type" "application/json; charset=UTF-8"},
:body "<head>\n <title>Internal Server Error</title>\n </head>\n <body>\n <h1>Internal Server Error</h1>\n </body>\n</html>"})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(let [artstor-user {:username "<EMAIL>" :profile-id 12345}
pcookies { :testcookie "magicallydelicious"}
one-ssids-data {:ssid 9999867318, :metadata [{:field_id "fd_68602_s", :value "Mr Pumpkin"} {:field_id "fd_68619_s", :value "Pumpkin"}]}
result (forum/update-image-metadata (one-ssids-data :ssid) one-ssids-data artstor-user)]
(is (= {:ssid 9999867318 :success false :status 500} result))))))
(deftest test-multiple-update-image-metadata
(testing "Tests update multiple image metadata happy path"
(with-redefs [forum/forum-services-login (fn [] {:status 200, :body {:username "<EMAIL>"}})
http/put (fn [_ _] {:status 200,
:headers {"Server" "gunicorn/19.0.0",
"Content-Length" "1534", "Content-Type" "application/json; charset=UTF-8"},
:body "{\"assets\": [{\"fd_68602_s\":\"Mr Pumpkin\", \"id\": 1234567890, \"created_by\": 12345, \"filename\": \"scary_friday_prod_deploy.jpg\",\"fd_68619_s\": \"Pumpkin\", \"project_id\": 3793, \"fd_68607_s\": \"Friday the Prod Deploy\"}], \"success\": true}"})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(let [artstor-user {:username "<EMAIL>" :profile-id 12345}
pcookies { :testcookie "magicallydelicious"}
many-ssids-data [{:ssid 1234567890, :metadata [{:field_id "fd_68602_s", :value "<NAME>"} {:field_id "fd_68619_s", :value "Pumpkin"}]}]
result (forum/update-multiple-images-metadata many-ssids-data artstor-user)]
(is (result :success))))))
(deftest test-bad-login-multiple-update-image-metadata
(testing "Tests failed login update multiple image metadata"
(with-redefs [forum/forum-services-login (fn [] nil)
http/put (fn [_ _] {:status 200,
:headers {"Server" "gunicorn/19.0.0",
"Content-Length" "1534", "Content-Type" "application/json; charset=UTF-8"},
:body "{\"assets\": [{\"fd_68602_s\":\"<NAME>\", \"id\": 1234567890, \"created_by\": 12345, \"filename\": \"scary_friday_prod_deploy.jpg\",\"fd_68619_s\": \"Pumpkin\", \"project_id\": 3793, \"fd_68607_s\": \"Friday the Prod Deploy\"}], \"success\": true}"})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(let [artstor-user {:username "<EMAIL>" :profile-id 12345}
many-ssids-data [{:ssid 1234567890, :metadata [{:field_id "fd_68602_s", :value "<NAME>"} {:field_id "fd_68619_s", :value "Pumpkin"}]}]
result (forum/update-multiple-images-metadata many-ssids-data artstor-user)]
(is (result :success)))))) | true | (ns artstor-collection-service-os.forum-test
(:require [artstor-collection-service-os.forum :as forum]
[clojure.test :refer :all]
[clojure.test.check.clojure-test :refer [defspec]]
[clj-http.client :as http]
[environ.core :refer [env]]
[clojure.tools.logging :as logger]))
(deftest test-upload-image-to-personal-collection
(testing "test uploading an image to personal collection"
(with-redefs [env {:secret "swiss cheese"}
forum/forum-services-login (fn [] {:status 200, :body {:username "PI:EMAIL:<EMAIL>END_PI"}})
forum/reserve-imata-asset (fn [_ _] {:status 200})
forum/upload-image-to-storage (fn [_ _ _ _] "100")
forum/assign-uploaded-asset-on-imata (fn [_ _ _] {:success true :assets [{:id "123456789"}]})
forum/update-asset-owner-on-imata-initial-upload (fn [_ _ _] {:success true})
forum/massage-assign-result (fn [_ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] true)]
(is (= {:success true :forum-published-status true} (forum/upload-image-to-personal-collection "my_awesome_pic.jpg" {:username "PI:EMAIL:<EMAIL>END_PI" :profile-id 12345})))))
(testing "test uploading an image to personal collection - failed login"
(with-redefs [env {:secret "swiss cheese"}
forum/forum-services-login (fn [] nil)
forum/reserve-imata-asset (fn [_ _] {:status 200})
forum/upload-image-to-storage (fn [_ _ _ _] "100")
forum/assign-uploaded-asset-on-imata (fn [_ _ _] {:success true})
forum/assign-uploaded-asset-on-imata (fn [_ _ _] {:success true :assets [{:id "123456789"}]})
forum/update-asset-owner-on-imata-initial-upload (fn [_ _ _] {:success true})
forum/massage-assign-result (fn [_ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(is (= {:success false} (forum/upload-image-to-personal-collection "my_awesome_pic.jpg" {:username "PI:EMAIL:<EMAIL>END_PI" :profile-id 12345}))))))
(deftest test-update-media-in-personal-collection
(testing "test updating media of an assest in personal collection"
(with-redefs [env {:secret "swiss cheese"}
forum/forum-services-login (fn [] {:status 200, :body {:username "PI:EMAIL:<EMAIL>END_PI"}})
forum/reserve-imata-asset (fn [_ _] {:status 200})
forum/upload-image-to-storage (fn [_ _ _ _] "100")
forum/update-uploaded-asset-on-imata (fn [_ _ _ _] {:success true, :updated_by 12345, :filename "my_awesome_pic1.jpg" :id 123456789})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] true)]
(is (= {:success true :forum-published-status true} (forum/update-media-in-personal-collection "my_awesome_pic1.jpg" 123456789 {:username "PI:EMAIL:<EMAIL>END_PI" :profile-id 12345})))))
(testing "test updating media of an assest in personal collection - failed login"
(with-redefs [env {:secret "swiss cheese"}
forum/forum-services-login (fn [] nil)
forum/reserve-imata-asset (fn [_ _] {:status 200})
forum/upload-image-to-storage (fn [_ _ _ _] "100")
forum/update-uploaded-asset-on-imata (fn [_ _ _ _] {:success true})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(is (= {:success false} (forum/update-media-in-personal-collection "my_awesome_pic1.jpg" 123456789 {:username "PI:EMAIL:<EMAIL>END_PI" :profile-id 12345}))))))
(deftest test-delete-image-from-personal-collection
(testing "test deleting personal collection image - single object"
(with-redefs [env {:secret "swiss cheese"}
forum/validate-owner-before-delete-pc-images (fn [_ _] ["123456789"])
forum/forum-services-login (fn [] {:status 200, :body {:username "PI:EMAIL:<EMAIL>END_PI"}})
forum/delete-pc-images-from-forum (fn [_ _] {:success true})]
(is (= {:success true} (forum/delete-images-from-personal-collection ["123456789"] {:username "PI:EMAIL:<EMAIL>END_PI" :profile-id 12345})))))
(testing "test deleting personal collection image - multiple objects"
(with-redefs [env {:secret "swiss cheese"}
forum/validate-owner-before-delete-pc-images (fn [_ _] ["123456789", "123456780"])
forum/forum-services-login (fn [] {:status 200, :body {:username "PI:EMAIL:<EMAIL>END_PI"}})
forum/delete-pc-images-from-forum (fn [_ _] {:success true})]
(is (= {:success true} (forum/delete-images-from-personal-collection ["123456789", "123456780", "123456781"] {:username "PI:EMAIL:<EMAIL>END_PI" :profile-id 12345})))))
(testing "test deleting personal collection image - failed login"
(with-redefs [env {:secret "PI:KEY:<KEY>END_PI"}
forum/validate-owner-before-delete-pc-images (fn [_ _] ["123456789"])
forum/forum-services-login (fn [] nil)
forum/delete-pc-images-from-forum (fn [_ _] {:success true})]
(is (= {:success false} (forum/delete-images-from-personal-collection ["123456789"] {:username "PI:EMAIL:<EMAIL>END_PI" :profile-id 12345}))))))
(deftest test-getting-object-ids-from-ssids
(testing "test getting good object-id from ssid"
(with-redefs [http/post (fn [_ _] {:status 200,
:body {:requestId "22403631-c2b3-4f02-a9c1-184e7a771fab",
:total 1,
:results [{:date nil,
:updatedon "2018-02-09T23:04:06Z",
:yearend nil,
:doi "10.2307/artstor.1234567890",
:collections [37436],
:id "d3385544-6c0c-3cd7-9aa7-527ef07fed24",
:artstorid "SS37436_37436_39075864",}]}})]
(is (= ["SS37436_37436_39075864"] (forum/get-object-ids-from-ssids [1234567890]))))))
(deftest test-validate-owner-before-delete-pc-images
(testing "test getting owner allowed ssids from given ssids"
(with-redefs [logger/log* (fn [_ _ _ message] (println "Test Log Message=" message))
http/post (fn [_ _] {:status 200,
:body {:requestId "22403631-c2b3-4f02-a9c1-184e7a771fab",
:total 1,
:results [{:personalcollectionowner 12345,
:additional_Fields {:ssid "1234567890"}}]}})]
(is (= ["1234567890"] (forum/validate-owner-before-delete-pc-images ["1234567890", "9087654321"] {:username "PI:EMAIL:<EMAIL>END_PI" :profile-id 12345}))))))
(deftest test-deleted-object-ids-from-ssids
(testing "test getting deleted object-id from ssid"
(with-redefs [http/post (fn [_ _] {:status 200,
:body {:requestId "22403631-c2b3-4f02-a9c1-184e7a771fab",
:total 1,
:results [{:date "",
:updatedon "2018-02-09T23:04:06Z",
:yearend nil,
:name "Removed by request",
:doi "10.2307/artstor.1234567890",
:collections [],
:id "d3385544-6c0c-3cd7-9aa7-527ef07fed24",
:artstorid "",}]}})]
(is (= [""] (forum/get-object-ids-from-ssids [1234567890]))))))
(deftest test-deleted-object-ids-from-ssids
(testing "test getting not object-id from ssid"
(with-redefs [http/post (fn [_ _] {:status 200,
:body {:requestId "22403631-c2b3-4f02-a9c1-184e7a771fab",
:total 0,
:results []}})]
(is (= [""] (forum/get-object-ids-from-ssids [1234567890]))))))
(deftest test-magically-massage-pc-metadata
(testing "Converts the UI sensible structure happy path"
(let [one-ssids-data {:ssid 12345678, :metadata [{:field_id "fd_68634_s", :value "Working"} {:field_id "fd_68633_s", :value "Awesome"}]}
massaged-fields (forum/magically-massage-pc-metadata one-ssids-data)]
(is (= {:id 12345678, "fd_68634_s" "Working", "fd_68633_s" "Awesome"} massaged-fields)))))
(deftest test-bad-massage-pc-metadata
(testing "No ssid test conversion"
(let [one-ssids-data { :metadata [{:field_id "fd_68634_s", :value "Working"} {:field_id "fd_68633_s", :value "Awesome"}]}
massaged-fields (forum/magically-massage-pc-metadata one-ssids-data)]
(is (= {:id nil, "fd_68634_s" "Working", "fd_68633_s" "Awesome"} massaged-fields))))
(testing "No metadata test conversion"
(let [one-ssids-data { :ssid 12345678}
massaged-fields (forum/magically-massage-pc-metadata one-ssids-data)]
(is (= {:id 12345678 } massaged-fields)))))
(deftest test-update-image-metadata
(testing "Tests update image metadata happy path"
(with-redefs [forum/forum-services-login (fn [] {:status 200, :body {:username "PI:EMAIL:<EMAIL>END_PI"}})
http/put (fn [_ _] {:status 200,
:headers {"Server" "gunicorn/19.0.0",
"Content-Length" "1534", "Content-Type" "application/json; charset=UTF-8"},
:body "{\"assets\": [{\"fd_68602_s\":\"Mr PI:NAME:<NAME>END_PI\", \"id\": 1234567890, \"created_by\": 12345, \"filename\": \"scary_friday_prod_deploy.jpg\",\"fd_68619_s\": \"Pumpkin\", \"project_id\": 3793, \"fd_68607_s\": \"Friday the Prod Deploy\"}], \"success\": true}"})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(let [artstor-user {:username "PI:EMAIL:<EMAIL>END_PI" :profile-id 12345}
pcookies { :testcookie "magicallydelicious"}
one-ssids-data {:ssid 1234567890, :metadata [{:field_id "fd_68602_s", :value "PI:NAME:<NAME>END_PI"} {:field_id "fd_68619_s", :value "Pumpkin"}]}
result (forum/update-image-metadata (one-ssids-data :ssid) one-ssids-data artstor-user)]
(is (= {:ssid 1234567890 :success true :status 200} result))))))
(deftest test-bad-update-image-metadata
(testing "Tests update image metadata sad path"
(with-redefs [forum/forum-services-login (fn [] {:status 200, :body {:username "PI:EMAIL:<EMAIL>END_PI"}})
http/put (fn [_ _] {:status 500,
:headers {"Server" "gunicorn/19.0.0",
"Content-Length" "1534", "Content-Type" "application/json; charset=UTF-8"},
:body "<head>\n <title>Internal Server Error</title>\n </head>\n <body>\n <h1>Internal Server Error</h1>\n </body>\n</html>"})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(let [artstor-user {:username "PI:EMAIL:<EMAIL>END_PI" :profile-id 12345}
pcookies { :testcookie "magicallydelicious"}
one-ssids-data {:ssid 9999867318, :metadata [{:field_id "fd_68602_s", :value "Mr Pumpkin"} {:field_id "fd_68619_s", :value "Pumpkin"}]}
result (forum/update-image-metadata (one-ssids-data :ssid) one-ssids-data artstor-user)]
(is (= {:ssid 9999867318 :success false :status 500} result))))))
(deftest test-multiple-update-image-metadata
(testing "Tests update multiple image metadata happy path"
(with-redefs [forum/forum-services-login (fn [] {:status 200, :body {:username "PI:EMAIL:<EMAIL>END_PI"}})
http/put (fn [_ _] {:status 200,
:headers {"Server" "gunicorn/19.0.0",
"Content-Length" "1534", "Content-Type" "application/json; charset=UTF-8"},
:body "{\"assets\": [{\"fd_68602_s\":\"Mr Pumpkin\", \"id\": 1234567890, \"created_by\": 12345, \"filename\": \"scary_friday_prod_deploy.jpg\",\"fd_68619_s\": \"Pumpkin\", \"project_id\": 3793, \"fd_68607_s\": \"Friday the Prod Deploy\"}], \"success\": true}"})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(let [artstor-user {:username "PI:EMAIL:<EMAIL>END_PI" :profile-id 12345}
pcookies { :testcookie "magicallydelicious"}
many-ssids-data [{:ssid 1234567890, :metadata [{:field_id "fd_68602_s", :value "PI:NAME:<NAME>END_PI"} {:field_id "fd_68619_s", :value "Pumpkin"}]}]
result (forum/update-multiple-images-metadata many-ssids-data artstor-user)]
(is (result :success))))))
(deftest test-bad-login-multiple-update-image-metadata
(testing "Tests failed login update multiple image metadata"
(with-redefs [forum/forum-services-login (fn [] nil)
http/put (fn [_ _] {:status 200,
:headers {"Server" "gunicorn/19.0.0",
"Content-Length" "1534", "Content-Type" "application/json; charset=UTF-8"},
:body "{\"assets\": [{\"fd_68602_s\":\"PI:NAME:<NAME>END_PI\", \"id\": 1234567890, \"created_by\": 12345, \"filename\": \"scary_friday_prod_deploy.jpg\",\"fd_68619_s\": \"Pumpkin\", \"project_id\": 3793, \"fd_68607_s\": \"Friday the Prod Deploy\"}], \"success\": true}"})
forum/update-asset-owner-on-imata-after-editing (fn [_ _ _] {:success true})
forum/publish-asset-at-forum (fn [_ _] {:success true})]
(let [artstor-user {:username "PI:EMAIL:<EMAIL>END_PI" :profile-id 12345}
many-ssids-data [{:ssid 1234567890, :metadata [{:field_id "fd_68602_s", :value "PI:NAME:<NAME>END_PI"} {:field_id "fd_68619_s", :value "Pumpkin"}]}]
result (forum/update-multiple-images-metadata many-ssids-data artstor-user)]
(is (result :success)))))) |
[
{
"context": "/id :dbpedia.resource/Pablo-Picasso\n :name \"Pablo\"\n :last-name \"Picasso\"}\n #inst \"2018-0",
"end": 1205,
"score": 0.9995944499969482,
"start": 1200,
"tag": "NAME",
"value": "Pablo"
},
{
"context": "o-Picasso\n :name \"Pablo\"\n :last-name \"Picasso\"}\n #inst \"2018-05-18T09:20:27.966-00:00\"]])\n",
"end": 1233,
"score": 0.9997414350509644,
"start": 1226,
"tag": "NAME",
"value": "Picasso"
},
{
"context": ")))\n '{:find [e]\n :where [[e :name \"Pablo\"]]}))\n",
"end": 1389,
"score": 0.9995357990264893,
"start": 1384,
"tag": "NAME",
"value": "Pablo"
}
] | docs/crux_node_only_system.clj | maacl/crux | 0 | (ns crux-node-only-system
(:require [clojure.tools.logging :as log]
[crux.bootstrap.cluster-node :as cluster-node]
[crux.http-server :as srv]
[crux.kafka.embedded :as ek]
[crux.db :as db]
[crux.query :as q]
[integrant.core :as ig]
[crux.kafka :as k]))
(def tx-topic-config
{"retention.ms" (str Long/MAX_VALUE)})
(def config {:crux/cluster-node {:db-dir "dev-storage/data"
:bootstrap-servers "localhost:9092"}})
(defmethod ig/init-key :crux/cluster-node [_ opts]
(cluster-node/start-cluster-node opts))
(defmethod ig/halt-key! :crux/cluster-node [_ ^java.io.Closeable closeable]
(.close closeable))
(declare system)
(defn start-system []
(alter-var-root #'system (fn [_] (ig/init config)))
:started)
(defn stop-system []
(when (and (bound? #'system)
(not (nil? system)))
(alter-var-root #'system (fn [system] (ig/halt! system)))
:stopped))
(comment
(start-system)
(db/submit-tx
(:tx-log (:crux/cluster-node system))
[[:crux.tx/put :dbpedia.resource/Pablo-Picasso
{:crux.db/id :dbpedia.resource/Pablo-Picasso
:name "Pablo"
:last-name "Picasso"}
#inst "2018-05-18T09:20:27.966-00:00"]])
(q/q (q/db (:kv-store (:crux/cluster-node system)))
'{:find [e]
:where [[e :name "Pablo"]]}))
| 19478 | (ns crux-node-only-system
(:require [clojure.tools.logging :as log]
[crux.bootstrap.cluster-node :as cluster-node]
[crux.http-server :as srv]
[crux.kafka.embedded :as ek]
[crux.db :as db]
[crux.query :as q]
[integrant.core :as ig]
[crux.kafka :as k]))
(def tx-topic-config
{"retention.ms" (str Long/MAX_VALUE)})
(def config {:crux/cluster-node {:db-dir "dev-storage/data"
:bootstrap-servers "localhost:9092"}})
(defmethod ig/init-key :crux/cluster-node [_ opts]
(cluster-node/start-cluster-node opts))
(defmethod ig/halt-key! :crux/cluster-node [_ ^java.io.Closeable closeable]
(.close closeable))
(declare system)
(defn start-system []
(alter-var-root #'system (fn [_] (ig/init config)))
:started)
(defn stop-system []
(when (and (bound? #'system)
(not (nil? system)))
(alter-var-root #'system (fn [system] (ig/halt! system)))
:stopped))
(comment
(start-system)
(db/submit-tx
(:tx-log (:crux/cluster-node system))
[[:crux.tx/put :dbpedia.resource/Pablo-Picasso
{:crux.db/id :dbpedia.resource/Pablo-Picasso
:name "<NAME>"
:last-name "<NAME>"}
#inst "2018-05-18T09:20:27.966-00:00"]])
(q/q (q/db (:kv-store (:crux/cluster-node system)))
'{:find [e]
:where [[e :name "<NAME>"]]}))
| true | (ns crux-node-only-system
(:require [clojure.tools.logging :as log]
[crux.bootstrap.cluster-node :as cluster-node]
[crux.http-server :as srv]
[crux.kafka.embedded :as ek]
[crux.db :as db]
[crux.query :as q]
[integrant.core :as ig]
[crux.kafka :as k]))
(def tx-topic-config
{"retention.ms" (str Long/MAX_VALUE)})
(def config {:crux/cluster-node {:db-dir "dev-storage/data"
:bootstrap-servers "localhost:9092"}})
(defmethod ig/init-key :crux/cluster-node [_ opts]
(cluster-node/start-cluster-node opts))
(defmethod ig/halt-key! :crux/cluster-node [_ ^java.io.Closeable closeable]
(.close closeable))
(declare system)
(defn start-system []
(alter-var-root #'system (fn [_] (ig/init config)))
:started)
(defn stop-system []
(when (and (bound? #'system)
(not (nil? system)))
(alter-var-root #'system (fn [system] (ig/halt! system)))
:stopped))
(comment
(start-system)
(db/submit-tx
(:tx-log (:crux/cluster-node system))
[[:crux.tx/put :dbpedia.resource/Pablo-Picasso
{:crux.db/id :dbpedia.resource/Pablo-Picasso
:name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"}
#inst "2018-05-18T09:20:27.966-00:00"]])
(q/q (q/db (:kv-store (:crux/cluster-node system)))
'{:find [e]
:where [[e :name "PI:NAME:<NAME>END_PI"]]}))
|
[
{
"context": " (let [occurrences (read-gbif {\"scientificName\" \"Aphelandra longiflora\"})]\n (:scientificName (first (:results occurre",
"end": 159,
"score": 0.9998374581336975,
"start": 138,
"tag": "NAME",
"value": "Aphelandra longiflora"
},
{
"context": "icName (first (:results occurrences)))\n => \"Aphelandra longiflora (Lindl.) Profice\"))\n\n(fact \"Can read from gbif re",
"end": 249,
"score": 0.9998449683189392,
"start": 228,
"tag": "NAME",
"value": "Aphelandra longiflora"
},
{
"context": " (let [occurrences (read-gbif {\"scientificName\" \"Vicia faba\" :limit 900})]\n (count (:results occurrences))",
"end": 364,
"score": 0.9996824264526367,
"start": 354,
"tag": "NAME",
"value": "Vicia faba"
},
{
"context": " (let [occurrences (read-gbif {\"scientificName\" \"Vicia faba\" :limit 1200})]\n (count (:results occurrences)",
"end": 483,
"score": 0.9996178150177002,
"start": 473,
"tag": "NAME",
"value": "Vicia faba"
}
] | test/dwc_io/gbif_test.clj | biodivdev/dwc | 0 | (ns dwc-io.gbif-test
(:use midje.sweet)
(:use dwc-io.gbif))
(fact "Can read from gbif"
(let [occurrences (read-gbif {"scientificName" "Aphelandra longiflora"})]
(:scientificName (first (:results occurrences)))
=> "Aphelandra longiflora (Lindl.) Profice"))
(fact "Can read from gbif recur"
(let [occurrences (read-gbif {"scientificName" "Vicia faba" :limit 900})]
(count (:results occurrences)) => 900)
(let [occurrences (read-gbif {"scientificName" "Vicia faba" :limit 1200})]
(count (:results occurrences)) => 1200))
| 107902 | (ns dwc-io.gbif-test
(:use midje.sweet)
(:use dwc-io.gbif))
(fact "Can read from gbif"
(let [occurrences (read-gbif {"scientificName" "<NAME>"})]
(:scientificName (first (:results occurrences)))
=> "<NAME> (Lindl.) Profice"))
(fact "Can read from gbif recur"
(let [occurrences (read-gbif {"scientificName" "<NAME>" :limit 900})]
(count (:results occurrences)) => 900)
(let [occurrences (read-gbif {"scientificName" "<NAME>" :limit 1200})]
(count (:results occurrences)) => 1200))
| true | (ns dwc-io.gbif-test
(:use midje.sweet)
(:use dwc-io.gbif))
(fact "Can read from gbif"
(let [occurrences (read-gbif {"scientificName" "PI:NAME:<NAME>END_PI"})]
(:scientificName (first (:results occurrences)))
=> "PI:NAME:<NAME>END_PI (Lindl.) Profice"))
(fact "Can read from gbif recur"
(let [occurrences (read-gbif {"scientificName" "PI:NAME:<NAME>END_PI" :limit 900})]
(count (:results occurrences)) => 900)
(let [occurrences (read-gbif {"scientificName" "PI:NAME:<NAME>END_PI" :limit 1200})]
(count (:results occurrences)) => 1200))
|
[
{
"context": "esting \"with string\"\n (is (= \"edabe5f8fb842df66d677861c8564bf8671be9bd1ab14028ecf75c915255b31c77c",
"end": 11538,
"score": 0.5047776699066162,
"start": 11536,
"tag": "KEY",
"value": "66"
},
{
"context": "string\"\n (is (= \"edabe5f8fb842df66d677861c8564bf8671be9bd1ab14028ecf75c915255b31c77c43cdde5b9452",
"end": 11550,
"score": 0.5090810656547546,
"start": 11549,
"tag": "KEY",
"value": "4"
},
{
"context": "ing\"\n (is (= \"edabe5f8fb842df66d677861c8564bf8671be9bd1ab14028ecf75c915255b31c77c43cdde5b94524\" ((",
"end": 11555,
"score": 0.5152537226676941,
"start": 11552,
"tag": "KEY",
"value": "867"
},
{
"context": "\n (is (= \"edabe5f8fb842df66d677861c8564bf8671be9bd1ab14028ecf75c915255b31c77c43cdde5b94524\" ((hmac",
"end": 11559,
"score": 0.5168366432189941,
"start": 11556,
"tag": "KEY",
"value": "be9"
},
{
"context": " (is (= \"edabe5f8fb842df66d677861c8564bf8671be9bd1ab14028ecf75c915255b31c77c43cdde5b94524\" ((hmac-ripemd320",
"end": 11569,
"score": 0.5326545834541321,
"start": 11561,
"tag": "KEY",
"value": "1ab14028"
},
{
"context": "dabe5f8fb842df66d677861c8564bf8671be9bd1ab14028ecf75c915255b31c77c43cdde5b94524\" ((hmac-ripemd320 \"hel",
"end": 11574,
"score": 0.5431557893753052,
"start": 11572,
"tag": "KEY",
"value": "75"
},
{
"context": "e5f8fb842df66d677861c8564bf8671be9bd1ab14028ecf75c915255b31c77c43cdde5b94524\" ((hmac-ripemd320 \"hello worl",
"end": 11581,
"score": 0.54905104637146,
"start": 11575,
"tag": "KEY",
"value": "915255"
},
{
"context": "42df66d677861c8564bf8671be9bd1ab14028ecf75c915255b31c77c43cdde5b94524\" ((hmac-ripemd320 \"hello world\" ",
"end": 11584,
"score": 0.5244617462158203,
"start": 11582,
"tag": "KEY",
"value": "31"
},
{
"context": "f66d677861c8564bf8671be9bd1ab14028ecf75c915255b31c77c43cdde5b94524\" ((hmac-ripemd320 \"hello world\" \"se",
"end": 11587,
"score": 0.5513657331466675,
"start": 11585,
"tag": "KEY",
"value": "77"
},
{
"context": "d677861c8564bf8671be9bd1ab14028ecf75c915255b31c77c43cdde5b94524\" ((hmac-ripemd320 \"hello world\" \"secr",
"end": 11589,
"score": 0.5330898761749268,
"start": 11588,
"tag": "KEY",
"value": "4"
},
{
"context": "1c8564bf8671be9bd1ab14028ecf75c915255b31c77c43cdde5b94524\" ((hmac-ripemd320 \"hello world\" \"secret\") {",
"end": 11595,
"score": 0.5243023037910461,
"start": 11594,
"tag": "KEY",
"value": "5"
},
{
"context": "8564bf8671be9bd1ab14028ecf75c915255b31c77c43cdde5b94524\" ((hmac-ripemd320 \"hello world\" \"secret\") {} nil)",
"end": 11601,
"score": 0.5489441752433777,
"start": 11596,
"tag": "KEY",
"value": "94524"
}
] | test/parsec/functions/digest_functions_test.clj | ExpediaGroup/parsec | 1 | (ns parsec.functions.digest-functions-test
(:require [clojure.test :refer :all]
[parsec.helpers :refer :all]
[parsec.test-helpers :refer :all]
[parsec.functions :refer :all]
[parsec.functions.stringfunctions :refer :all]
[clj-time.core :as time]))
(deftest adler32-test
(let [adler32 (partial function-transform :adler32)]
(testing "with nil"
(is (nil? ((adler32 nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((adler32 (long 0)) {} nil))))
(testing "with string"
(is (= "1a0b045d" ((adler32 "hello world") {} nil))))))
(deftest crc32-test
(let [crc32 (partial function-transform :crc32)]
(testing "with nil"
(is (nil? ((crc32 nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((crc32 (long 0)) {} nil))))
(testing "with string"
(is (= "0d4a1185" ((crc32 "hello world") {} nil))))))
(deftest md5-test
(let [md5 (partial function-transform :md5)]
(testing "with nil"
(is (nil? ((md5 nil) {} nil)))
(is (nil? ((md5 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((md5 (long 0)) {} nil)))
(is (thrown? Exception ((md5 (int 1)) {} nil)))
(is (thrown? Exception ((md5 1.0) {} nil)))
(is (thrown? Exception ((md5 1/2) {} nil))))
(testing "with string"
(is (= "acbd18db4cc2f85cedef654fccc4a4d8" ((md5 "foo") {} nil))))
(testing "with boolean"
(is (thrown? Exception ((md5 false) {} nil)))
(is (thrown? Exception ((md5 true) {} nil))))
(testing "with date"
(is (thrown? Exception ((md5 (time/today-at-midnight)) {} nil)))
(is (thrown? Exception ((md5 (time/now)) {} nil))))))
(deftest sha256-test
(let [sha256 (partial function-transform :sha256)]
(testing "with nil"
(is (nil? ((sha256 nil) {} nil)))
(is (nil? ((sha256 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((sha256 (long 0)) {} nil)))
(is (thrown? Exception ((sha256 (int 1)) {} nil)))
(is (thrown? Exception ((sha256 1.0) {} nil)))
(is (thrown? Exception ((sha256 1/2) {} nil))))
(testing "with string"
(is (= "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9" ((sha256 "hello world") {} nil))))
(testing "with boolean"
(is (thrown? Exception ((sha256 false) {} nil)))
(is (thrown? Exception ((sha256 true) {} nil))))
(testing "with date"
(is (thrown? Exception ((sha256 (time/today-at-midnight)) {} nil)))
(is (thrown? Exception ((sha256 (time/now)) {} nil))))))
(deftest hmac-sha256-test
(let [hmac-sha256 (partial function-transform :hmac_sha256)]
(testing "with nil"
(is (nil? ((hmac-sha256 nil) {} nil)))
(is (nil? ((hmac-sha256 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-sha256 (long 0)) {} nil)))
(is (thrown? Exception ((hmac-sha256 (int 1)) {} nil)))
(is (thrown? Exception ((hmac-sha256 1.0) {} nil)))
(is (thrown? Exception ((hmac-sha256 1/2) {} nil))))
(testing "with string"
(is (= "734cc62f32841568f45715aeb9f4d7891324e6d948e4c6c60c0621cdac48623a" ((hmac-sha256 "hello world" "secret") {} nil))))
(testing "with boolean"
(is (thrown? Exception ((hmac-sha256 false) {} nil)))
(is (thrown? Exception ((hmac-sha256 true) {} nil))))
(testing "with date"
(is (thrown? Exception ((hmac-sha256 (time/today-at-midnight)) {} nil)))
(is (thrown? Exception ((hmac-sha256 (time/now)) {} nil))))))
(deftest sha384-test
(let [sha384 (partial function-transform :sha384)]
(testing "with nil"
(is (nil? ((sha384 nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((sha384 (long 0)) {} nil))))
(testing "with string"
(is (= "fdbd8e75a67f29f701a4e040385e2e23986303ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c088de1bd" ((sha384 "hello world") {} nil))))))
(deftest hmac-sha384-test
(let [hmac-sha384 (partial function-transform :hmac_sha384)]
(testing "with nil"
(is (nil? ((hmac-sha384 nil) {} nil)))
(is (nil? ((hmac-sha384 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-sha384 (long 0)) {} nil))))
(testing "with string"
(is (= "2da3bb177b92aae98c3ab22727d7f60c905be1baff71fb4b00a6e410923e6558376590c1faf922ff51ec49be77409ac6" ((hmac-sha384 "hello world" "secret") {} nil))))))
(deftest sha512-test
(let [sha512 (partial function-transform :sha512)]
(testing "with nil"
(is (nil? ((sha512 nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((sha512 (long 0)) {} nil))))
(testing "with string"
(is (= "309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f" ((sha512 "hello world") {} nil))))))
(deftest hmac-sha512-test
(let [hmac-sha512 (partial function-transform :hmac_sha512)]
(testing "with nil"
(is (nil? ((hmac-sha512 nil) {} nil)))
(is (nil? ((hmac-sha512 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-sha512 (long 0)) {} nil))))
(testing "with string"
(is (= "6d32239b01dd1750557211629313d95e4f4fcb8ee517e443990ac1afc7562bfd74ffa6118387efd9e168ff86d1da5cef4a55edc63cc4ba289c4c3a8b4f7bdfc2" ((hmac-sha512 "hello world" "secret") {} nil))))))
(deftest tiger-test
(let [tiger (partial function-transform :tiger)]
(testing "with nil"
(is (nil? ((tiger nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((tiger (long 0)) {} nil))))
(testing "with string"
(is (= "4c8fbddae0b6f25832af45e7c62811bb64ec3e43691e9cc3" ((tiger "hello world") {} nil))))))
(deftest hmac-tiger-test
(let [hmac-tiger (partial function-transform :hmac_tiger)]
(testing "with nil"
(is (nil? ((hmac-tiger nil) {} nil)))
(is (nil? ((hmac-tiger :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-tiger (long 0)) {} nil))))
(testing "with string"
(is (= "e4e7d5a746cde566aad3864cc00afd50469d195007aba89c" ((hmac-tiger "hello world" "secret") {} nil))))))
(deftest whirlpool-test
(let [whirlpool (partial function-transform :whirlpool)]
(testing "with nil"
(is (nil? ((whirlpool nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((whirlpool (long 0)) {} nil))))
(testing "with string"
(is (= "8d8309ca6af848095bcabaf9a53b1b6ce7f594c1434fd6e5177e7e5c20e76cd30936d8606e7f36acbef8978fea008e6400a975d51abe6ba4923178c7cf90c802" ((whirlpool "hello world") {} nil))))))
(deftest hmac-whirlpool-test
(let [hmac-whirlpool (partial function-transform :hmac_whirlpool)]
(testing "with nil"
(is (nil? ((hmac-whirlpool nil) {} nil)))
(is (nil? ((hmac-whirlpool :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-whirlpool (long 0)) {} nil))))
(testing "with string"
(is (= "39935d42ec5ec9c778e9e0ad05e53893296d82ca118ddb01021904ba88cb07c6925dbdd2a16beeed811a78f262839cee8015246a688d087431659772948f0ea8" ((hmac-whirlpool "hello world" "secret") {} nil))))))
(deftest siphash-test
(let [siphash (partial function-transform :siphash)]
(testing "with nil"
(is (nil? ((siphash nil) {} nil)))
(is (nil? ((siphash :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((siphash (long 0)) {} nil))))
(testing "with string"
(is (= "4c00f66010eb806c" ((siphash "hello world" "12345678abcdefgh") {} nil))))))
(deftest siphash48-test
(let [siphash48 (partial function-transform :siphash48)]
(testing "with nil"
(is (nil? ((siphash48 nil) {} nil)))
(is (nil? ((siphash48 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((siphash48 (long 0)) {} nil))))
(testing "with string"
(is (= "3392cccde5c3b774" ((siphash48 "hello world" "12345678abcdefgh") {} nil))))))
(deftest gost-test
(let [gost (partial function-transform :gost)]
(testing "with nil"
(is (nil? ((gost nil) {} nil)))
(is (nil? ((gost :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((gost (long 0)) {} nil))))
(testing "with string"
(is (= "c5aa1455afe9f0c440eec3c96ccccb5c8495097572cc0f625278bd0da5ea5e07" ((gost "hello world") {} nil))))))
(deftest hmac-gost-test
(let [hmac-gost (partial function-transform :hmac_gost)]
(testing "with nil"
(is (nil? ((hmac-gost nil) {} nil)))
(is (nil? ((hmac-gost :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-gost (long 0)) {} nil))))
(testing "with string"
(is (= "df89c2a9e8ae6622d38813ee61d8202d6f424d7169a1eb73d0590d4ad6269625" ((hmac-gost "hello world" "secret") {} nil))))))
(deftest ripemd128-test
(let [ripemd128 (partial function-transform :ripemd128)]
(testing "with nil"
(is (nil? ((ripemd128 nil) {} nil)))
(is (nil? ((ripemd128 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((ripemd128 (long 0)) {} nil))))
(testing "with string"
(is (= "c52ac4d06245286b33953957be6c6f81" ((ripemd128 "hello world") {} nil))))))
(deftest hmac-ripemd128-test
(let [hmac-ripemd128 (partial function-transform :hmac_ripemd128)]
(testing "with nil"
(is (nil? ((hmac-ripemd128 nil) {} nil)))
(is (nil? ((hmac-ripemd128 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-ripemd128 (long 0)) {} nil))))
(testing "with string"
(is (= "692ec2f0d7c7d0649dc5de420c251bc7" ((hmac-ripemd128 "hello world" "secret") {} nil))))))
(deftest ripemd256-test
(let [ripemd256 (partial function-transform :ripemd256)]
(testing "with nil"
(is (nil? ((ripemd256 nil) {} nil)))
(is (nil? ((ripemd256 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((ripemd256 (long 0)) {} nil))))
(testing "with string"
(is (= "0d375cf9d9ee95a3bb15f757c81e93bb0ad963edf69dc4d12264031814608e37" ((ripemd256 "hello world") {} nil))))))
(deftest hmac-ripemd256-test
(let [hmac-ripemd256 (partial function-transform :hmac_ripemd256)]
(testing "with nil"
(is (nil? ((hmac-ripemd256 nil) {} nil)))
(is (nil? ((hmac-ripemd256 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-ripemd256 (long 0)) {} nil))))
(testing "with string"
(is (= "77d19c3c9aa57a4f17f82501aa72cdf469fc908499cdd90999b221d34354330a" ((hmac-ripemd256 "hello world" "secret") {} nil))))))
(deftest ripemd320-test
(let [ripemd320 (partial function-transform :ripemd320)]
(testing "with nil"
(is (nil? ((ripemd320 nil) {} nil)))
(is (nil? ((ripemd320 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((ripemd320 (long 0)) {} nil))))
(testing "with string"
(is (= "0e12fe7d075f8e319e07c106917eddb0135e9a10aefb50a8a07ccb0582ff1fa27b95ed5af57fd5c6" ((ripemd320 "hello world") {} nil))))))
(deftest hmac-ripemd320-test
(let [hmac-ripemd320 (partial function-transform :hmac_ripemd320)]
(testing "with nil"
(is (nil? ((hmac-ripemd320 nil) {} nil)))
(is (nil? ((hmac-ripemd320 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-ripemd320 (long 0)) {} nil))))
(testing "with string"
(is (= "edabe5f8fb842df66d677861c8564bf8671be9bd1ab14028ecf75c915255b31c77c43cdde5b94524" ((hmac-ripemd320 "hello world" "secret") {} nil))))))
| 16705 | (ns parsec.functions.digest-functions-test
(:require [clojure.test :refer :all]
[parsec.helpers :refer :all]
[parsec.test-helpers :refer :all]
[parsec.functions :refer :all]
[parsec.functions.stringfunctions :refer :all]
[clj-time.core :as time]))
(deftest adler32-test
(let [adler32 (partial function-transform :adler32)]
(testing "with nil"
(is (nil? ((adler32 nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((adler32 (long 0)) {} nil))))
(testing "with string"
(is (= "1a0b045d" ((adler32 "hello world") {} nil))))))
(deftest crc32-test
(let [crc32 (partial function-transform :crc32)]
(testing "with nil"
(is (nil? ((crc32 nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((crc32 (long 0)) {} nil))))
(testing "with string"
(is (= "0d4a1185" ((crc32 "hello world") {} nil))))))
(deftest md5-test
(let [md5 (partial function-transform :md5)]
(testing "with nil"
(is (nil? ((md5 nil) {} nil)))
(is (nil? ((md5 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((md5 (long 0)) {} nil)))
(is (thrown? Exception ((md5 (int 1)) {} nil)))
(is (thrown? Exception ((md5 1.0) {} nil)))
(is (thrown? Exception ((md5 1/2) {} nil))))
(testing "with string"
(is (= "acbd18db4cc2f85cedef654fccc4a4d8" ((md5 "foo") {} nil))))
(testing "with boolean"
(is (thrown? Exception ((md5 false) {} nil)))
(is (thrown? Exception ((md5 true) {} nil))))
(testing "with date"
(is (thrown? Exception ((md5 (time/today-at-midnight)) {} nil)))
(is (thrown? Exception ((md5 (time/now)) {} nil))))))
(deftest sha256-test
(let [sha256 (partial function-transform :sha256)]
(testing "with nil"
(is (nil? ((sha256 nil) {} nil)))
(is (nil? ((sha256 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((sha256 (long 0)) {} nil)))
(is (thrown? Exception ((sha256 (int 1)) {} nil)))
(is (thrown? Exception ((sha256 1.0) {} nil)))
(is (thrown? Exception ((sha256 1/2) {} nil))))
(testing "with string"
(is (= "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9" ((sha256 "hello world") {} nil))))
(testing "with boolean"
(is (thrown? Exception ((sha256 false) {} nil)))
(is (thrown? Exception ((sha256 true) {} nil))))
(testing "with date"
(is (thrown? Exception ((sha256 (time/today-at-midnight)) {} nil)))
(is (thrown? Exception ((sha256 (time/now)) {} nil))))))
(deftest hmac-sha256-test
(let [hmac-sha256 (partial function-transform :hmac_sha256)]
(testing "with nil"
(is (nil? ((hmac-sha256 nil) {} nil)))
(is (nil? ((hmac-sha256 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-sha256 (long 0)) {} nil)))
(is (thrown? Exception ((hmac-sha256 (int 1)) {} nil)))
(is (thrown? Exception ((hmac-sha256 1.0) {} nil)))
(is (thrown? Exception ((hmac-sha256 1/2) {} nil))))
(testing "with string"
(is (= "734cc62f32841568f45715aeb9f4d7891324e6d948e4c6c60c0621cdac48623a" ((hmac-sha256 "hello world" "secret") {} nil))))
(testing "with boolean"
(is (thrown? Exception ((hmac-sha256 false) {} nil)))
(is (thrown? Exception ((hmac-sha256 true) {} nil))))
(testing "with date"
(is (thrown? Exception ((hmac-sha256 (time/today-at-midnight)) {} nil)))
(is (thrown? Exception ((hmac-sha256 (time/now)) {} nil))))))
(deftest sha384-test
(let [sha384 (partial function-transform :sha384)]
(testing "with nil"
(is (nil? ((sha384 nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((sha384 (long 0)) {} nil))))
(testing "with string"
(is (= "fdbd8e75a67f29f701a4e040385e2e23986303ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c088de1bd" ((sha384 "hello world") {} nil))))))
(deftest hmac-sha384-test
(let [hmac-sha384 (partial function-transform :hmac_sha384)]
(testing "with nil"
(is (nil? ((hmac-sha384 nil) {} nil)))
(is (nil? ((hmac-sha384 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-sha384 (long 0)) {} nil))))
(testing "with string"
(is (= "2da3bb177b92aae98c3ab22727d7f60c905be1baff71fb4b00a6e410923e6558376590c1faf922ff51ec49be77409ac6" ((hmac-sha384 "hello world" "secret") {} nil))))))
(deftest sha512-test
(let [sha512 (partial function-transform :sha512)]
(testing "with nil"
(is (nil? ((sha512 nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((sha512 (long 0)) {} nil))))
(testing "with string"
(is (= "309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f" ((sha512 "hello world") {} nil))))))
(deftest hmac-sha512-test
(let [hmac-sha512 (partial function-transform :hmac_sha512)]
(testing "with nil"
(is (nil? ((hmac-sha512 nil) {} nil)))
(is (nil? ((hmac-sha512 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-sha512 (long 0)) {} nil))))
(testing "with string"
(is (= "6d32239b01dd1750557211629313d95e4f4fcb8ee517e443990ac1afc7562bfd74ffa6118387efd9e168ff86d1da5cef4a55edc63cc4ba289c4c3a8b4f7bdfc2" ((hmac-sha512 "hello world" "secret") {} nil))))))
(deftest tiger-test
(let [tiger (partial function-transform :tiger)]
(testing "with nil"
(is (nil? ((tiger nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((tiger (long 0)) {} nil))))
(testing "with string"
(is (= "4c8fbddae0b6f25832af45e7c62811bb64ec3e43691e9cc3" ((tiger "hello world") {} nil))))))
(deftest hmac-tiger-test
(let [hmac-tiger (partial function-transform :hmac_tiger)]
(testing "with nil"
(is (nil? ((hmac-tiger nil) {} nil)))
(is (nil? ((hmac-tiger :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-tiger (long 0)) {} nil))))
(testing "with string"
(is (= "e4e7d5a746cde566aad3864cc00afd50469d195007aba89c" ((hmac-tiger "hello world" "secret") {} nil))))))
(deftest whirlpool-test
(let [whirlpool (partial function-transform :whirlpool)]
(testing "with nil"
(is (nil? ((whirlpool nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((whirlpool (long 0)) {} nil))))
(testing "with string"
(is (= "8d8309ca6af848095bcabaf9a53b1b6ce7f594c1434fd6e5177e7e5c20e76cd30936d8606e7f36acbef8978fea008e6400a975d51abe6ba4923178c7cf90c802" ((whirlpool "hello world") {} nil))))))
(deftest hmac-whirlpool-test
(let [hmac-whirlpool (partial function-transform :hmac_whirlpool)]
(testing "with nil"
(is (nil? ((hmac-whirlpool nil) {} nil)))
(is (nil? ((hmac-whirlpool :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-whirlpool (long 0)) {} nil))))
(testing "with string"
(is (= "39935d42ec5ec9c778e9e0ad05e53893296d82ca118ddb01021904ba88cb07c6925dbdd2a16beeed811a78f262839cee8015246a688d087431659772948f0ea8" ((hmac-whirlpool "hello world" "secret") {} nil))))))
(deftest siphash-test
(let [siphash (partial function-transform :siphash)]
(testing "with nil"
(is (nil? ((siphash nil) {} nil)))
(is (nil? ((siphash :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((siphash (long 0)) {} nil))))
(testing "with string"
(is (= "4c00f66010eb806c" ((siphash "hello world" "12345678abcdefgh") {} nil))))))
(deftest siphash48-test
(let [siphash48 (partial function-transform :siphash48)]
(testing "with nil"
(is (nil? ((siphash48 nil) {} nil)))
(is (nil? ((siphash48 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((siphash48 (long 0)) {} nil))))
(testing "with string"
(is (= "3392cccde5c3b774" ((siphash48 "hello world" "12345678abcdefgh") {} nil))))))
(deftest gost-test
(let [gost (partial function-transform :gost)]
(testing "with nil"
(is (nil? ((gost nil) {} nil)))
(is (nil? ((gost :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((gost (long 0)) {} nil))))
(testing "with string"
(is (= "c5aa1455afe9f0c440eec3c96ccccb5c8495097572cc0f625278bd0da5ea5e07" ((gost "hello world") {} nil))))))
(deftest hmac-gost-test
(let [hmac-gost (partial function-transform :hmac_gost)]
(testing "with nil"
(is (nil? ((hmac-gost nil) {} nil)))
(is (nil? ((hmac-gost :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-gost (long 0)) {} nil))))
(testing "with string"
(is (= "df89c2a9e8ae6622d38813ee61d8202d6f424d7169a1eb73d0590d4ad6269625" ((hmac-gost "hello world" "secret") {} nil))))))
(deftest ripemd128-test
(let [ripemd128 (partial function-transform :ripemd128)]
(testing "with nil"
(is (nil? ((ripemd128 nil) {} nil)))
(is (nil? ((ripemd128 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((ripemd128 (long 0)) {} nil))))
(testing "with string"
(is (= "c52ac4d06245286b33953957be6c6f81" ((ripemd128 "hello world") {} nil))))))
(deftest hmac-ripemd128-test
(let [hmac-ripemd128 (partial function-transform :hmac_ripemd128)]
(testing "with nil"
(is (nil? ((hmac-ripemd128 nil) {} nil)))
(is (nil? ((hmac-ripemd128 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-ripemd128 (long 0)) {} nil))))
(testing "with string"
(is (= "692ec2f0d7c7d0649dc5de420c251bc7" ((hmac-ripemd128 "hello world" "secret") {} nil))))))
(deftest ripemd256-test
(let [ripemd256 (partial function-transform :ripemd256)]
(testing "with nil"
(is (nil? ((ripemd256 nil) {} nil)))
(is (nil? ((ripemd256 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((ripemd256 (long 0)) {} nil))))
(testing "with string"
(is (= "0d375cf9d9ee95a3bb15f757c81e93bb0ad963edf69dc4d12264031814608e37" ((ripemd256 "hello world") {} nil))))))
(deftest hmac-ripemd256-test
(let [hmac-ripemd256 (partial function-transform :hmac_ripemd256)]
(testing "with nil"
(is (nil? ((hmac-ripemd256 nil) {} nil)))
(is (nil? ((hmac-ripemd256 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-ripemd256 (long 0)) {} nil))))
(testing "with string"
(is (= "77d19c3c9aa57a4f17f82501aa72cdf469fc908499cdd90999b221d34354330a" ((hmac-ripemd256 "hello world" "secret") {} nil))))))
(deftest ripemd320-test
(let [ripemd320 (partial function-transform :ripemd320)]
(testing "with nil"
(is (nil? ((ripemd320 nil) {} nil)))
(is (nil? ((ripemd320 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((ripemd320 (long 0)) {} nil))))
(testing "with string"
(is (= "0e12fe7d075f8e319e07c106917eddb0135e9a10aefb50a8a07ccb0582ff1fa27b95ed5af57fd5c6" ((ripemd320 "hello world") {} nil))))))
(deftest hmac-ripemd320-test
(let [hmac-ripemd320 (partial function-transform :hmac_ripemd320)]
(testing "with nil"
(is (nil? ((hmac-ripemd320 nil) {} nil)))
(is (nil? ((hmac-ripemd320 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-ripemd320 (long 0)) {} nil))))
(testing "with string"
(is (= "edabe5f8fb842df<KEY>d677861c856<KEY>bf<KEY>1<KEY>bd<KEY>ecf<KEY>c<KEY>b<KEY>c<KEY>c<KEY>3cdde<KEY>b<KEY>" ((hmac-ripemd320 "hello world" "secret") {} nil))))))
| true | (ns parsec.functions.digest-functions-test
(:require [clojure.test :refer :all]
[parsec.helpers :refer :all]
[parsec.test-helpers :refer :all]
[parsec.functions :refer :all]
[parsec.functions.stringfunctions :refer :all]
[clj-time.core :as time]))
(deftest adler32-test
(let [adler32 (partial function-transform :adler32)]
(testing "with nil"
(is (nil? ((adler32 nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((adler32 (long 0)) {} nil))))
(testing "with string"
(is (= "1a0b045d" ((adler32 "hello world") {} nil))))))
(deftest crc32-test
(let [crc32 (partial function-transform :crc32)]
(testing "with nil"
(is (nil? ((crc32 nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((crc32 (long 0)) {} nil))))
(testing "with string"
(is (= "0d4a1185" ((crc32 "hello world") {} nil))))))
(deftest md5-test
(let [md5 (partial function-transform :md5)]
(testing "with nil"
(is (nil? ((md5 nil) {} nil)))
(is (nil? ((md5 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((md5 (long 0)) {} nil)))
(is (thrown? Exception ((md5 (int 1)) {} nil)))
(is (thrown? Exception ((md5 1.0) {} nil)))
(is (thrown? Exception ((md5 1/2) {} nil))))
(testing "with string"
(is (= "acbd18db4cc2f85cedef654fccc4a4d8" ((md5 "foo") {} nil))))
(testing "with boolean"
(is (thrown? Exception ((md5 false) {} nil)))
(is (thrown? Exception ((md5 true) {} nil))))
(testing "with date"
(is (thrown? Exception ((md5 (time/today-at-midnight)) {} nil)))
(is (thrown? Exception ((md5 (time/now)) {} nil))))))
(deftest sha256-test
(let [sha256 (partial function-transform :sha256)]
(testing "with nil"
(is (nil? ((sha256 nil) {} nil)))
(is (nil? ((sha256 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((sha256 (long 0)) {} nil)))
(is (thrown? Exception ((sha256 (int 1)) {} nil)))
(is (thrown? Exception ((sha256 1.0) {} nil)))
(is (thrown? Exception ((sha256 1/2) {} nil))))
(testing "with string"
(is (= "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9" ((sha256 "hello world") {} nil))))
(testing "with boolean"
(is (thrown? Exception ((sha256 false) {} nil)))
(is (thrown? Exception ((sha256 true) {} nil))))
(testing "with date"
(is (thrown? Exception ((sha256 (time/today-at-midnight)) {} nil)))
(is (thrown? Exception ((sha256 (time/now)) {} nil))))))
(deftest hmac-sha256-test
(let [hmac-sha256 (partial function-transform :hmac_sha256)]
(testing "with nil"
(is (nil? ((hmac-sha256 nil) {} nil)))
(is (nil? ((hmac-sha256 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-sha256 (long 0)) {} nil)))
(is (thrown? Exception ((hmac-sha256 (int 1)) {} nil)))
(is (thrown? Exception ((hmac-sha256 1.0) {} nil)))
(is (thrown? Exception ((hmac-sha256 1/2) {} nil))))
(testing "with string"
(is (= "734cc62f32841568f45715aeb9f4d7891324e6d948e4c6c60c0621cdac48623a" ((hmac-sha256 "hello world" "secret") {} nil))))
(testing "with boolean"
(is (thrown? Exception ((hmac-sha256 false) {} nil)))
(is (thrown? Exception ((hmac-sha256 true) {} nil))))
(testing "with date"
(is (thrown? Exception ((hmac-sha256 (time/today-at-midnight)) {} nil)))
(is (thrown? Exception ((hmac-sha256 (time/now)) {} nil))))))
(deftest sha384-test
(let [sha384 (partial function-transform :sha384)]
(testing "with nil"
(is (nil? ((sha384 nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((sha384 (long 0)) {} nil))))
(testing "with string"
(is (= "fdbd8e75a67f29f701a4e040385e2e23986303ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c088de1bd" ((sha384 "hello world") {} nil))))))
(deftest hmac-sha384-test
(let [hmac-sha384 (partial function-transform :hmac_sha384)]
(testing "with nil"
(is (nil? ((hmac-sha384 nil) {} nil)))
(is (nil? ((hmac-sha384 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-sha384 (long 0)) {} nil))))
(testing "with string"
(is (= "2da3bb177b92aae98c3ab22727d7f60c905be1baff71fb4b00a6e410923e6558376590c1faf922ff51ec49be77409ac6" ((hmac-sha384 "hello world" "secret") {} nil))))))
(deftest sha512-test
(let [sha512 (partial function-transform :sha512)]
(testing "with nil"
(is (nil? ((sha512 nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((sha512 (long 0)) {} nil))))
(testing "with string"
(is (= "309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f" ((sha512 "hello world") {} nil))))))
(deftest hmac-sha512-test
(let [hmac-sha512 (partial function-transform :hmac_sha512)]
(testing "with nil"
(is (nil? ((hmac-sha512 nil) {} nil)))
(is (nil? ((hmac-sha512 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-sha512 (long 0)) {} nil))))
(testing "with string"
(is (= "6d32239b01dd1750557211629313d95e4f4fcb8ee517e443990ac1afc7562bfd74ffa6118387efd9e168ff86d1da5cef4a55edc63cc4ba289c4c3a8b4f7bdfc2" ((hmac-sha512 "hello world" "secret") {} nil))))))
(deftest tiger-test
(let [tiger (partial function-transform :tiger)]
(testing "with nil"
(is (nil? ((tiger nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((tiger (long 0)) {} nil))))
(testing "with string"
(is (= "4c8fbddae0b6f25832af45e7c62811bb64ec3e43691e9cc3" ((tiger "hello world") {} nil))))))
(deftest hmac-tiger-test
(let [hmac-tiger (partial function-transform :hmac_tiger)]
(testing "with nil"
(is (nil? ((hmac-tiger nil) {} nil)))
(is (nil? ((hmac-tiger :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-tiger (long 0)) {} nil))))
(testing "with string"
(is (= "e4e7d5a746cde566aad3864cc00afd50469d195007aba89c" ((hmac-tiger "hello world" "secret") {} nil))))))
(deftest whirlpool-test
(let [whirlpool (partial function-transform :whirlpool)]
(testing "with nil"
(is (nil? ((whirlpool nil) {} nil))))
(testing "with number"
(is (thrown? Exception ((whirlpool (long 0)) {} nil))))
(testing "with string"
(is (= "8d8309ca6af848095bcabaf9a53b1b6ce7f594c1434fd6e5177e7e5c20e76cd30936d8606e7f36acbef8978fea008e6400a975d51abe6ba4923178c7cf90c802" ((whirlpool "hello world") {} nil))))))
(deftest hmac-whirlpool-test
(let [hmac-whirlpool (partial function-transform :hmac_whirlpool)]
(testing "with nil"
(is (nil? ((hmac-whirlpool nil) {} nil)))
(is (nil? ((hmac-whirlpool :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-whirlpool (long 0)) {} nil))))
(testing "with string"
(is (= "39935d42ec5ec9c778e9e0ad05e53893296d82ca118ddb01021904ba88cb07c6925dbdd2a16beeed811a78f262839cee8015246a688d087431659772948f0ea8" ((hmac-whirlpool "hello world" "secret") {} nil))))))
(deftest siphash-test
(let [siphash (partial function-transform :siphash)]
(testing "with nil"
(is (nil? ((siphash nil) {} nil)))
(is (nil? ((siphash :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((siphash (long 0)) {} nil))))
(testing "with string"
(is (= "4c00f66010eb806c" ((siphash "hello world" "12345678abcdefgh") {} nil))))))
(deftest siphash48-test
(let [siphash48 (partial function-transform :siphash48)]
(testing "with nil"
(is (nil? ((siphash48 nil) {} nil)))
(is (nil? ((siphash48 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((siphash48 (long 0)) {} nil))))
(testing "with string"
(is (= "3392cccde5c3b774" ((siphash48 "hello world" "12345678abcdefgh") {} nil))))))
(deftest gost-test
(let [gost (partial function-transform :gost)]
(testing "with nil"
(is (nil? ((gost nil) {} nil)))
(is (nil? ((gost :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((gost (long 0)) {} nil))))
(testing "with string"
(is (= "c5aa1455afe9f0c440eec3c96ccccb5c8495097572cc0f625278bd0da5ea5e07" ((gost "hello world") {} nil))))))
(deftest hmac-gost-test
(let [hmac-gost (partial function-transform :hmac_gost)]
(testing "with nil"
(is (nil? ((hmac-gost nil) {} nil)))
(is (nil? ((hmac-gost :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-gost (long 0)) {} nil))))
(testing "with string"
(is (= "df89c2a9e8ae6622d38813ee61d8202d6f424d7169a1eb73d0590d4ad6269625" ((hmac-gost "hello world" "secret") {} nil))))))
(deftest ripemd128-test
(let [ripemd128 (partial function-transform :ripemd128)]
(testing "with nil"
(is (nil? ((ripemd128 nil) {} nil)))
(is (nil? ((ripemd128 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((ripemd128 (long 0)) {} nil))))
(testing "with string"
(is (= "c52ac4d06245286b33953957be6c6f81" ((ripemd128 "hello world") {} nil))))))
(deftest hmac-ripemd128-test
(let [hmac-ripemd128 (partial function-transform :hmac_ripemd128)]
(testing "with nil"
(is (nil? ((hmac-ripemd128 nil) {} nil)))
(is (nil? ((hmac-ripemd128 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-ripemd128 (long 0)) {} nil))))
(testing "with string"
(is (= "692ec2f0d7c7d0649dc5de420c251bc7" ((hmac-ripemd128 "hello world" "secret") {} nil))))))
(deftest ripemd256-test
(let [ripemd256 (partial function-transform :ripemd256)]
(testing "with nil"
(is (nil? ((ripemd256 nil) {} nil)))
(is (nil? ((ripemd256 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((ripemd256 (long 0)) {} nil))))
(testing "with string"
(is (= "0d375cf9d9ee95a3bb15f757c81e93bb0ad963edf69dc4d12264031814608e37" ((ripemd256 "hello world") {} nil))))))
(deftest hmac-ripemd256-test
(let [hmac-ripemd256 (partial function-transform :hmac_ripemd256)]
(testing "with nil"
(is (nil? ((hmac-ripemd256 nil) {} nil)))
(is (nil? ((hmac-ripemd256 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-ripemd256 (long 0)) {} nil))))
(testing "with string"
(is (= "77d19c3c9aa57a4f17f82501aa72cdf469fc908499cdd90999b221d34354330a" ((hmac-ripemd256 "hello world" "secret") {} nil))))))
(deftest ripemd320-test
(let [ripemd320 (partial function-transform :ripemd320)]
(testing "with nil"
(is (nil? ((ripemd320 nil) {} nil)))
(is (nil? ((ripemd320 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((ripemd320 (long 0)) {} nil))))
(testing "with string"
(is (= "0e12fe7d075f8e319e07c106917eddb0135e9a10aefb50a8a07ccb0582ff1fa27b95ed5af57fd5c6" ((ripemd320 "hello world") {} nil))))))
(deftest hmac-ripemd320-test
(let [hmac-ripemd320 (partial function-transform :hmac_ripemd320)]
(testing "with nil"
(is (nil? ((hmac-ripemd320 nil) {} nil)))
(is (nil? ((hmac-ripemd320 :col1) {:col1 nil} nil))))
(testing "with number"
(is (thrown? Exception ((hmac-ripemd320 (long 0)) {} nil))))
(testing "with string"
(is (= "edabe5f8fb842dfPI:KEY:<KEY>END_PId677861c856PI:KEY:<KEY>END_PIbfPI:KEY:<KEY>END_PI1PI:KEY:<KEY>END_PIbdPI:KEY:<KEY>END_PIecfPI:KEY:<KEY>END_PIcPI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PIcPI:KEY:<KEY>END_PIcPI:KEY:<KEY>END_PI3cddePI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PI" ((hmac-ripemd320 "hello world" "secret") {} nil))))))
|
[
{
"context": "clj-time.format :as clj-time-format]\n [robert.bruce :refer [try-try-again]]\n [overtone.at-",
"end": 697,
"score": 0.8205450773239136,
"start": 685,
"tag": "USERNAME",
"value": "robert.bruce"
},
{
"context": "EventSource])\n (:gen-class))\n\n(def source-token \"36c35e23-8757-4a9d-aacf-345e9b7eb50d\")\n(def source-",
"end": 962,
"score": 0.5677101612091064,
"start": 961,
"tag": "KEY",
"value": "3"
},
{
"context": "ventSource])\n (:gen-class))\n\n(def source-token \"36c35e23-8757-4a9d-aacf-345e9b7eb50d\")\n(def source-id \"wikipedia\")\n(def agent-name \"wi",
"end": 997,
"score": 0.8016136884689331,
"start": 962,
"tag": "PASSWORD",
"value": "6c35e23-8757-4a9d-aacf-345e9b7eb50d"
}
] | src/event_data_agents/agents/wikipedia/core.clj | CrossRef/event-data-agents | 3 | (ns event-data-agents.agents.wikipedia.core
(:require [event-data-agents.util :as util]
[event-data-common.evidence-log :as evidence-log]
[crossref.util.doi :as cr-doi]
[clojure.tools.logging :as log]
[clojure.java.io :as io]
[clojure.data.json :as json]
[clojure.core.async :refer [alts!! timeout thread buffer chan <!! >!!]]
[clj-http.client :as client]
[config.core :refer [env]]
[clj-time.core :as clj-time]
[throttler.core :refer [throttle-fn]]
[clj-time.coerce :as clj-time-coerce]
[clj-time.format :as clj-time-format]
[robert.bruce :refer [try-try-again]]
[overtone.at-at :as at-at])
(:import [java.net URLEncoder]
[java.util UUID]
[org.apache.commons.codec.digest DigestUtils]
[javax.ws.rs.sse SseEventSource])
(:gen-class))
(def source-token "36c35e23-8757-4a9d-aacf-345e9b7eb50d")
(def source-id "wikipedia")
(def agent-name "wikipedia-agent")
(def stream-url "https://stream.wikimedia.org/v2/stream/recentchange")
(def action-chunk-size
"Number of input actions to batch into events. A value of 100 results in message size of about 150 KB"
100)
(def action-input-buffer 1000000)
(def action-chan (delay (chan action-input-buffer (partition-all action-chunk-size))))
(declare manifest)
(def date-format
(:date-time-no-ms clj-time-format/formatters))
(defn message->action
"Parse an input into a Percolator Action. Note that an Action ID is not supplied."
[data]
(when (= "edit" (:type data))
(let [canonical-url (-> data :meta :uri)
encoded-title (->> data :meta :uri (re-find #"^.*?/wiki/(.*)$") second)
title (:title data)
new-id (-> data :revision :new)
version-url (str (:server_url data) "/w/index.php?title=" encoded-title "&oldid=" new-id)
new-restbase-url (str (:server_url data) "/api/rest_v1/page/html/" encoded-title "/" new-id)
; normalize format
timestamp-str (clj-time-format/unparse date-format (clj-time-coerce/from-string (-> data :meta :dt)))]
{:url canonical-url
:occurred-at timestamp-str
:relation-type-id "references"
:subj {:pid canonical-url
:url version-url
:title title
:work_type_id "entry-encyclopedia"
:api-url new-restbase-url}
:observations [{:type :content-url
:input-url new-restbase-url
; The Wikipedia robots.txt files prohibit access to the API.
; There are separate terms for the RESTBase API, plus we have specific permission.
:ignore-robots true
:sensitive true}]
:extra-events []})))
(def ignore-wikis
"Set of wiki identifiers that we're not interested in."
#{; Commons pages don't have references, so ignore them.
"commonswiki"
; Wikidata uses a specific JSON format, which we can't yet parse.
"wikidatawiki"})
(def watchdog-timeout-ms
10000)
(defn ingest-stream
"Subscribe to the WC Stream, put data in the input-stream-chan.
Blocks until there's a timeout or error."
[]
(let [client (.build (javax.ws.rs.client.ClientBuilder/newBuilder))
target (.target client stream-url)
event-source (.build (javax.ws.rs.sse.SseEventSource/target target))
last-event-timestamp (atom (System/currentTimeMillis))
events-since-last-check (atom 0)
wikis-breakdown (atom {})]
(evidence-log/log! {:i "a0026" :s agent-name :c "wikipedia-api" :f "connect"})
(def consumer (reify java.util.function.Consumer
(accept [this t]
(reset! last-event-timestamp (System/currentTimeMillis))
(let [data (.readData t)]
(when-not (clojure.string/blank? data)
(try
; Read JSON, package into an Action.
(let [parsed (json/read-str (.readData t) :key-fn keyword)
action (message->action parsed)
wiki-identifier (:wiki parsed)]
; Action may return nil if we're not interested in it.
(when (and action (not (ignore-wikis wiki-identifier)))
(swap! wikis-breakdown #(assoc % wiki-identifier (inc (% wiki-identifier 1))))
(swap! events-since-last-check inc)
(>!! @action-chan action)))
(catch Exception e
(do
(log/error "Error reading input" e)
(evidence-log/log! {:i "a003e" :s agent-name :c "ingest" :f "error"})))))))))
(evidence-log/log! {:i "a0028" :s agent-name :c "ingest" :f "start"})
(.register event-source ^java.util.function.Consumer consumer)
(try
(.open event-source)
; Block unless we run into a timeout.
(loop []
(let [num-events @events-since-last-check
now (System/currentTimeMillis)
diff (- now @last-event-timestamp)]
; There may be a little race, but this number is only an indicator.
(reset! events-since-last-check 0)
(log/info "Check timeout. Since last check got" num-events ", most recent" diff "ms ago")
(log/debug "Wiki breakdown: " @wikis-breakdown)
(reset! wikis-breakdown {})
(if (> diff watchdog-timeout-ms)
(do
(log/warn "Timeout reached, closing connection")
(.close event-source))
(do
(Thread/sleep 1000)
(recur)))))
(finally
(log/warn "Interrupted. Closing connection.")
(.close event-source)))))
(defn main-ingest-stream
"Ingest RC Stream, reconnecting on error."
[]
(loop []
(ingest-stream)
(log/error "Ingest stream exit. Will reconnect.")
(recur)))
(defn main-send
"Take chunks of Actions from the action-chan, assemble into Evidence Records,
put them on the input-package-channel."
[]
(loop []
(try
(evidence-log/log! {:i "a0029" :s agent-name :c "process" :f "start"})
; Take chunks of inputs, a few tweets per input bundle.
; Gather then into a Page of actions.
(log/info "Waiting for chunks of actions...")
(let [channel @action-chan
; We don't use any artifacts.
artifact-map {}]
(loop [actions (<!! channel)]
(log/info "Got a chunk of" (count actions) "actions")
(evidence-log/log! {:i "a0030" :s agent-name :c "process" :f "got-chunk" :v (count actions)})
(let [evidence-record (assoc
(util/build-evidence-record manifest artifact-map)
:pages [{:actions actions}])]
(util/send-evidence-record manifest evidence-record)
(log/info "Sent a chunk of" (count actions) "actions"))
(recur (<!! channel))))
(catch Exception ex (do
(log/error "Unhandled exception sending:" (.getMessage ex))
(evidence-log/log! {:i "a003f" :s agent-name :c "process" :f "error"})))
(finally
(log/error "Stopped!")
(Thread/sleep 1000)))
(recur)))
(def manifest
{:agent-name agent-name
:source-id source-id
:license util/cc-0
:source-token source-token
:schedule []
:daemons [main-ingest-stream main-send]})
| 42279 | (ns event-data-agents.agents.wikipedia.core
(:require [event-data-agents.util :as util]
[event-data-common.evidence-log :as evidence-log]
[crossref.util.doi :as cr-doi]
[clojure.tools.logging :as log]
[clojure.java.io :as io]
[clojure.data.json :as json]
[clojure.core.async :refer [alts!! timeout thread buffer chan <!! >!!]]
[clj-http.client :as client]
[config.core :refer [env]]
[clj-time.core :as clj-time]
[throttler.core :refer [throttle-fn]]
[clj-time.coerce :as clj-time-coerce]
[clj-time.format :as clj-time-format]
[robert.bruce :refer [try-try-again]]
[overtone.at-at :as at-at])
(:import [java.net URLEncoder]
[java.util UUID]
[org.apache.commons.codec.digest DigestUtils]
[javax.ws.rs.sse SseEventSource])
(:gen-class))
(def source-token "<KEY> <PASSWORD>")
(def source-id "wikipedia")
(def agent-name "wikipedia-agent")
(def stream-url "https://stream.wikimedia.org/v2/stream/recentchange")
(def action-chunk-size
"Number of input actions to batch into events. A value of 100 results in message size of about 150 KB"
100)
(def action-input-buffer 1000000)
(def action-chan (delay (chan action-input-buffer (partition-all action-chunk-size))))
(declare manifest)
(def date-format
(:date-time-no-ms clj-time-format/formatters))
(defn message->action
"Parse an input into a Percolator Action. Note that an Action ID is not supplied."
[data]
(when (= "edit" (:type data))
(let [canonical-url (-> data :meta :uri)
encoded-title (->> data :meta :uri (re-find #"^.*?/wiki/(.*)$") second)
title (:title data)
new-id (-> data :revision :new)
version-url (str (:server_url data) "/w/index.php?title=" encoded-title "&oldid=" new-id)
new-restbase-url (str (:server_url data) "/api/rest_v1/page/html/" encoded-title "/" new-id)
; normalize format
timestamp-str (clj-time-format/unparse date-format (clj-time-coerce/from-string (-> data :meta :dt)))]
{:url canonical-url
:occurred-at timestamp-str
:relation-type-id "references"
:subj {:pid canonical-url
:url version-url
:title title
:work_type_id "entry-encyclopedia"
:api-url new-restbase-url}
:observations [{:type :content-url
:input-url new-restbase-url
; The Wikipedia robots.txt files prohibit access to the API.
; There are separate terms for the RESTBase API, plus we have specific permission.
:ignore-robots true
:sensitive true}]
:extra-events []})))
(def ignore-wikis
"Set of wiki identifiers that we're not interested in."
#{; Commons pages don't have references, so ignore them.
"commonswiki"
; Wikidata uses a specific JSON format, which we can't yet parse.
"wikidatawiki"})
(def watchdog-timeout-ms
10000)
(defn ingest-stream
"Subscribe to the WC Stream, put data in the input-stream-chan.
Blocks until there's a timeout or error."
[]
(let [client (.build (javax.ws.rs.client.ClientBuilder/newBuilder))
target (.target client stream-url)
event-source (.build (javax.ws.rs.sse.SseEventSource/target target))
last-event-timestamp (atom (System/currentTimeMillis))
events-since-last-check (atom 0)
wikis-breakdown (atom {})]
(evidence-log/log! {:i "a0026" :s agent-name :c "wikipedia-api" :f "connect"})
(def consumer (reify java.util.function.Consumer
(accept [this t]
(reset! last-event-timestamp (System/currentTimeMillis))
(let [data (.readData t)]
(when-not (clojure.string/blank? data)
(try
; Read JSON, package into an Action.
(let [parsed (json/read-str (.readData t) :key-fn keyword)
action (message->action parsed)
wiki-identifier (:wiki parsed)]
; Action may return nil if we're not interested in it.
(when (and action (not (ignore-wikis wiki-identifier)))
(swap! wikis-breakdown #(assoc % wiki-identifier (inc (% wiki-identifier 1))))
(swap! events-since-last-check inc)
(>!! @action-chan action)))
(catch Exception e
(do
(log/error "Error reading input" e)
(evidence-log/log! {:i "a003e" :s agent-name :c "ingest" :f "error"})))))))))
(evidence-log/log! {:i "a0028" :s agent-name :c "ingest" :f "start"})
(.register event-source ^java.util.function.Consumer consumer)
(try
(.open event-source)
; Block unless we run into a timeout.
(loop []
(let [num-events @events-since-last-check
now (System/currentTimeMillis)
diff (- now @last-event-timestamp)]
; There may be a little race, but this number is only an indicator.
(reset! events-since-last-check 0)
(log/info "Check timeout. Since last check got" num-events ", most recent" diff "ms ago")
(log/debug "Wiki breakdown: " @wikis-breakdown)
(reset! wikis-breakdown {})
(if (> diff watchdog-timeout-ms)
(do
(log/warn "Timeout reached, closing connection")
(.close event-source))
(do
(Thread/sleep 1000)
(recur)))))
(finally
(log/warn "Interrupted. Closing connection.")
(.close event-source)))))
(defn main-ingest-stream
"Ingest RC Stream, reconnecting on error."
[]
(loop []
(ingest-stream)
(log/error "Ingest stream exit. Will reconnect.")
(recur)))
(defn main-send
"Take chunks of Actions from the action-chan, assemble into Evidence Records,
put them on the input-package-channel."
[]
(loop []
(try
(evidence-log/log! {:i "a0029" :s agent-name :c "process" :f "start"})
; Take chunks of inputs, a few tweets per input bundle.
; Gather then into a Page of actions.
(log/info "Waiting for chunks of actions...")
(let [channel @action-chan
; We don't use any artifacts.
artifact-map {}]
(loop [actions (<!! channel)]
(log/info "Got a chunk of" (count actions) "actions")
(evidence-log/log! {:i "a0030" :s agent-name :c "process" :f "got-chunk" :v (count actions)})
(let [evidence-record (assoc
(util/build-evidence-record manifest artifact-map)
:pages [{:actions actions}])]
(util/send-evidence-record manifest evidence-record)
(log/info "Sent a chunk of" (count actions) "actions"))
(recur (<!! channel))))
(catch Exception ex (do
(log/error "Unhandled exception sending:" (.getMessage ex))
(evidence-log/log! {:i "a003f" :s agent-name :c "process" :f "error"})))
(finally
(log/error "Stopped!")
(Thread/sleep 1000)))
(recur)))
(def manifest
{:agent-name agent-name
:source-id source-id
:license util/cc-0
:source-token source-token
:schedule []
:daemons [main-ingest-stream main-send]})
| true | (ns event-data-agents.agents.wikipedia.core
(:require [event-data-agents.util :as util]
[event-data-common.evidence-log :as evidence-log]
[crossref.util.doi :as cr-doi]
[clojure.tools.logging :as log]
[clojure.java.io :as io]
[clojure.data.json :as json]
[clojure.core.async :refer [alts!! timeout thread buffer chan <!! >!!]]
[clj-http.client :as client]
[config.core :refer [env]]
[clj-time.core :as clj-time]
[throttler.core :refer [throttle-fn]]
[clj-time.coerce :as clj-time-coerce]
[clj-time.format :as clj-time-format]
[robert.bruce :refer [try-try-again]]
[overtone.at-at :as at-at])
(:import [java.net URLEncoder]
[java.util UUID]
[org.apache.commons.codec.digest DigestUtils]
[javax.ws.rs.sse SseEventSource])
(:gen-class))
(def source-token "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI")
(def source-id "wikipedia")
(def agent-name "wikipedia-agent")
(def stream-url "https://stream.wikimedia.org/v2/stream/recentchange")
(def action-chunk-size
"Number of input actions to batch into events. A value of 100 results in message size of about 150 KB"
100)
(def action-input-buffer 1000000)
(def action-chan (delay (chan action-input-buffer (partition-all action-chunk-size))))
(declare manifest)
(def date-format
(:date-time-no-ms clj-time-format/formatters))
(defn message->action
"Parse an input into a Percolator Action. Note that an Action ID is not supplied."
[data]
(when (= "edit" (:type data))
(let [canonical-url (-> data :meta :uri)
encoded-title (->> data :meta :uri (re-find #"^.*?/wiki/(.*)$") second)
title (:title data)
new-id (-> data :revision :new)
version-url (str (:server_url data) "/w/index.php?title=" encoded-title "&oldid=" new-id)
new-restbase-url (str (:server_url data) "/api/rest_v1/page/html/" encoded-title "/" new-id)
; normalize format
timestamp-str (clj-time-format/unparse date-format (clj-time-coerce/from-string (-> data :meta :dt)))]
{:url canonical-url
:occurred-at timestamp-str
:relation-type-id "references"
:subj {:pid canonical-url
:url version-url
:title title
:work_type_id "entry-encyclopedia"
:api-url new-restbase-url}
:observations [{:type :content-url
:input-url new-restbase-url
; The Wikipedia robots.txt files prohibit access to the API.
; There are separate terms for the RESTBase API, plus we have specific permission.
:ignore-robots true
:sensitive true}]
:extra-events []})))
(def ignore-wikis
"Set of wiki identifiers that we're not interested in."
#{; Commons pages don't have references, so ignore them.
"commonswiki"
; Wikidata uses a specific JSON format, which we can't yet parse.
"wikidatawiki"})
(def watchdog-timeout-ms
10000)
(defn ingest-stream
"Subscribe to the WC Stream, put data in the input-stream-chan.
Blocks until there's a timeout or error."
[]
(let [client (.build (javax.ws.rs.client.ClientBuilder/newBuilder))
target (.target client stream-url)
event-source (.build (javax.ws.rs.sse.SseEventSource/target target))
last-event-timestamp (atom (System/currentTimeMillis))
events-since-last-check (atom 0)
wikis-breakdown (atom {})]
(evidence-log/log! {:i "a0026" :s agent-name :c "wikipedia-api" :f "connect"})
(def consumer (reify java.util.function.Consumer
(accept [this t]
(reset! last-event-timestamp (System/currentTimeMillis))
(let [data (.readData t)]
(when-not (clojure.string/blank? data)
(try
; Read JSON, package into an Action.
(let [parsed (json/read-str (.readData t) :key-fn keyword)
action (message->action parsed)
wiki-identifier (:wiki parsed)]
; Action may return nil if we're not interested in it.
(when (and action (not (ignore-wikis wiki-identifier)))
(swap! wikis-breakdown #(assoc % wiki-identifier (inc (% wiki-identifier 1))))
(swap! events-since-last-check inc)
(>!! @action-chan action)))
(catch Exception e
(do
(log/error "Error reading input" e)
(evidence-log/log! {:i "a003e" :s agent-name :c "ingest" :f "error"})))))))))
(evidence-log/log! {:i "a0028" :s agent-name :c "ingest" :f "start"})
(.register event-source ^java.util.function.Consumer consumer)
(try
(.open event-source)
; Block unless we run into a timeout.
(loop []
(let [num-events @events-since-last-check
now (System/currentTimeMillis)
diff (- now @last-event-timestamp)]
; There may be a little race, but this number is only an indicator.
(reset! events-since-last-check 0)
(log/info "Check timeout. Since last check got" num-events ", most recent" diff "ms ago")
(log/debug "Wiki breakdown: " @wikis-breakdown)
(reset! wikis-breakdown {})
(if (> diff watchdog-timeout-ms)
(do
(log/warn "Timeout reached, closing connection")
(.close event-source))
(do
(Thread/sleep 1000)
(recur)))))
(finally
(log/warn "Interrupted. Closing connection.")
(.close event-source)))))
(defn main-ingest-stream
"Ingest RC Stream, reconnecting on error."
[]
(loop []
(ingest-stream)
(log/error "Ingest stream exit. Will reconnect.")
(recur)))
(defn main-send
"Take chunks of Actions from the action-chan, assemble into Evidence Records,
put them on the input-package-channel."
[]
(loop []
(try
(evidence-log/log! {:i "a0029" :s agent-name :c "process" :f "start"})
; Take chunks of inputs, a few tweets per input bundle.
; Gather then into a Page of actions.
(log/info "Waiting for chunks of actions...")
(let [channel @action-chan
; We don't use any artifacts.
artifact-map {}]
(loop [actions (<!! channel)]
(log/info "Got a chunk of" (count actions) "actions")
(evidence-log/log! {:i "a0030" :s agent-name :c "process" :f "got-chunk" :v (count actions)})
(let [evidence-record (assoc
(util/build-evidence-record manifest artifact-map)
:pages [{:actions actions}])]
(util/send-evidence-record manifest evidence-record)
(log/info "Sent a chunk of" (count actions) "actions"))
(recur (<!! channel))))
(catch Exception ex (do
(log/error "Unhandled exception sending:" (.getMessage ex))
(evidence-log/log! {:i "a003f" :s agent-name :c "process" :f "error"})))
(finally
(log/error "Stopped!")
(Thread/sleep 1000)))
(recur)))
(def manifest
{:agent-name agent-name
:source-id source-id
:license util/cc-0
:source-token source-token
:schedule []
:daemons [main-ingest-stream main-send]})
|
[
{
"context": "; Copyright 2009, 2010, 2011 Howard M. Lewis Ship\n;\n; Licensed under the Apache License, Version 2.",
"end": 49,
"score": 0.9998604655265808,
"start": 29,
"tag": "NAME",
"value": "Howard M. Lewis Ship"
}
] | src/cascade/utils.clj | hlship/cascade | 8 | ; Copyright 2009, 2010, 2011 Howard M. Lewis Ship
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
; implied. See the License for the specific language governing permissions
; and limitations under the License.
(ns cascade.utils
"Utilities needed by cascade")
(defmacro lcond
"A reimplementation of Clojure's cond, with the addition of a special :let
keyword that injects an implicit let into the logic."
[& clauses]
(when clauses
(if (= 1 (count clauses))
(throw (IllegalArgumentException. "lcond requires an even number of forms")))
(let
[tst (first clauses)
expr (second clauses)
rst (next (next clauses))]
(if (= tst :let)
`(let [~@expr] (lcond ~@rst))
`(if ~tst ~expr (lcond ~@rst))))))
| 67805 | ; Copyright 2009, 2010, 2011 <NAME>
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
; implied. See the License for the specific language governing permissions
; and limitations under the License.
(ns cascade.utils
"Utilities needed by cascade")
(defmacro lcond
"A reimplementation of Clojure's cond, with the addition of a special :let
keyword that injects an implicit let into the logic."
[& clauses]
(when clauses
(if (= 1 (count clauses))
(throw (IllegalArgumentException. "lcond requires an even number of forms")))
(let
[tst (first clauses)
expr (second clauses)
rst (next (next clauses))]
(if (= tst :let)
`(let [~@expr] (lcond ~@rst))
`(if ~tst ~expr (lcond ~@rst))))))
| true | ; Copyright 2009, 2010, 2011 PI:NAME:<NAME>END_PI
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
; implied. See the License for the specific language governing permissions
; and limitations under the License.
(ns cascade.utils
"Utilities needed by cascade")
(defmacro lcond
"A reimplementation of Clojure's cond, with the addition of a special :let
keyword that injects an implicit let into the logic."
[& clauses]
(when clauses
(if (= 1 (count clauses))
(throw (IllegalArgumentException. "lcond requires an even number of forms")))
(let
[tst (first clauses)
expr (second clauses)
rst (next (next clauses))]
(if (= tst :let)
`(let [~@expr] (lcond ~@rst))
`(if ~tst ~expr (lcond ~@rst))))))
|
[
{
"context": "arch-string\n (let [doc {:crux.db/id :ivan :name \"Ivan\"}]\n (submit+await-tx [[:crux.tx/put {:crux.db/",
"end": 477,
"score": 0.9980244040489197,
"start": 473,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "await-tx [[:crux.tx/put {:crux.db/id :ivan :name \"Ivan\"}]])\n\n (t/testing \"using Lucene directly\"\n ",
"end": 547,
"score": 0.9969397783279419,
"start": 543,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "rux.lucene/lucene-store @(:!system *api*)) :name \"Ivan\")]\n (let [docs (iterator-seq search-result",
"end": 711,
"score": 0.9955014586448669,
"start": 707,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " (t/is (= 1 (count docs)))\n (t/is (= \"Ivan\" (.get ^Document (ffirst docs) \"_crux_val\"))))))\n",
"end": 825,
"score": 0.9909484386444092,
"start": 821,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " :where '[[(text-search :name \"Ivan\") [[?e]]]\n ",
"end": 1077,
"score": 0.9970017671585083,
"start": 1073,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " :where '[[(text-search \"Wot\" \"Ivan\") [[?e]]]\n ",
"end": 1377,
"score": 0.923383355140686,
"start": 1374,
"tag": "NAME",
"value": "Wot"
},
{
"context": " :where '[[(text-search \"Wot\" \"Ivan\") [[?e]]]\n ",
"end": 1384,
"score": 0.9912140369415283,
"start": 1380,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " :where '[[(text-search :name \"Iv*\") [[?e]]]\n ",
"end": 1620,
"score": 0.9398509860038757,
"start": 1618,
"tag": "NAME",
"value": "Iv"
},
{
"context": "let [q {:find '[?e] :where '[[(text-search :name \"Iv?n\") [[?e]]] [?e :crux.db/id]]}]\n (t/is (= ",
"end": 1928,
"score": 0.9303975701332092,
"start": 1924,
"tag": "NAME",
"value": "Iv?n"
},
{
"context": "await-tx [[:crux.tx/put {:crux.db/id :ivan :name \"Derek\"}]])\n (let [q {:find '[?e] :where '[[(text",
"end": 2261,
"score": 0.9995339512825012,
"start": 2256,
"tag": "NAME",
"value": "Derek"
},
{
"context": "let [q {:find '[?e] :where '[[(text-search :name \"Derek\") [[?e]]] [?e :crux.db/id]]}]\n (t/is (no",
"end": 2331,
"score": 0.9996069669723511,
"start": 2326,
"tag": "NAME",
"value": "Derek"
},
{
"context": "wait-tx [[:crux.tx/put {:crux.db/id :ivan2 :name \"Derek\"}]])\n (submit+await-tx [[:crux.tx/evict :iva",
"end": 2599,
"score": 0.999492883682251,
"start": 2594,
"tag": "NAME",
"value": "Derek"
},
{
"context": " '[[(text-search :name \"Ivan\") [[?e]]]\n [?e :c",
"end": 2833,
"score": 0.9991949200630188,
"start": 2829,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "rux.lucene/lucene-store @(:!system *api*)) :name \"Ivan\")]\n (t/is (empty? (iterator-seq search-res",
"end": 3018,
"score": 0.9680964350700378,
"start": 3014,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "rux.lucene/lucene-store @(:!system *api*)) :name \"Derek\")]\n (t/is (seq (iterator-seq search-result",
"end": 3196,
"score": 0.998163104057312,
"start": 3191,
"tag": "NAME",
"value": "Derek"
},
{
"context": "is (= #{[:ivan \"abar\"]\n [:ivan \"atar\"]}\n (c/q db {:find '[?e ?v]\n ",
"end": 4450,
"score": 0.8394637107849121,
"start": 4446,
"tag": "NAME",
"value": "atar"
},
{
"context": "await-tx [[:crux.tx/put {:crux.db/id :ivan :name \"Ivan\"}]])\n\n (with-open [db (c/open-db *api*)]\n (t/",
"end": 4746,
"score": 0.999583899974823,
"start": 4742,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "testing \"dont specify A\"\n (t/is (= #{[:ivan \"Ivan\" :name]}\n (c/q db {:find '[?e ?v ?a",
"end": 4850,
"score": 0.9996263980865479,
"start": 4846,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " :where '[[(wildcard-text-search \"Ivan\") [[?e ?v ?a]]]\n ",
"end": 4963,
"score": 0.9995889663696289,
"start": 4959,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " :where '[[(text-search :non-field \"Ivan\") [[?e ?v]]]\n [?e",
"end": 5213,
"score": 0.9995704889297485,
"start": 5209,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "await-tx [[:crux.tx/put {:crux.db/id :ivan :name \"Ivan\" :surname \"Ivan\"}]])\n\n (t/testing \"can find mult",
"end": 5349,
"score": 0.999603271484375,
"start": 5345,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "n [db (c/open-db *api*)]\n (t/is (= #{[:ivan \"Ivan\" :name]\n [:ivan \"Ivan\" :surname]}",
"end": 5477,
"score": 0.9995639324188232,
"start": 5473,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "= #{[:ivan \"Ivan\" :name]\n [:ivan \"Ivan\" :surname]}\n (c/q db {:find '[?e ?v",
"end": 5515,
"score": 0.9996469020843506,
"start": 5511,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " :where '[[(wildcard-text-search \"Ivan\") [[?e ?v ?a _]]]\n ",
"end": 5631,
"score": 0.9995774030685425,
"start": 5627,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "-tx [[:crux.tx/put {:crux.db/id :real-ivan :name \"Ivan Bob\"}]])\n (submit+await-tx [[:crux.tx/put {:crux.db/",
"end": 5929,
"score": 0.9992751479148865,
"start": 5921,
"tag": "NAME",
"value": "Ivan Bob"
},
{
"context": "-tx [[:crux.tx/put {:crux.db/id :ivan-dave :name \"Ivan Dave Ivan\"}]])\n\n (let [q {:find '[?v ?score]\n :w",
"end": 6014,
"score": 0.9997989535331726,
"start": 6000,
"tag": "NAME",
"value": "Ivan Dave Ivan"
},
{
"context": "d '[?v ?score]\n :where '[[(text-search \"Ivan\" :name) [[?e ?v ?a ?score]]]\n ",
"end": 6090,
"score": 0.9996379613876343,
"start": 6086,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "wait-tx [[:crux.tx/put {:crux.db/id \"ivan\" :name \"Ivan Bob Bob\"}]])\n\n (let [q {:find '[?e ?v ?s]\n :wh",
"end": 6720,
"score": 0.9997355341911316,
"start": 6708,
"tag": "NAME",
"value": "Ivan Bob Bob"
},
{
"context": "nd '[?e ?v ?s]\n :where '[[(text-search \"Ivan\" :name) [[?e ?v ?a ?s]]]\n [?e ",
"end": 6795,
"score": 0.9996019601821899,
"start": 6791,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "ait-tx [[:crux.tx/put {:crux.db/id \"ivan1\" :name \"Ivan\"}]])\n (submit+await-tx [[:crux.tx/delete \"ivan",
"end": 7018,
"score": 0.9994199275970459,
"start": 7014,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "wait-tx [[:crux.tx/put {:crux.db/id \"ivan\" :name \"Ivan\"}]])\n (let [q {:find '[?e ?v ?s]\n :whe",
"end": 7257,
"score": 0.9986143112182617,
"start": 7253,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "e ?v ?s]\n :where '[[(text-search :name \"Ivan\") [[?e ?v ?s]]]\n [?e :crux.db/",
"end": 7337,
"score": 0.9983850717544556,
"start": 7333,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " (submit+await-tx [[:crux.tx/put {:crux.db/id \"ivan\" :name \"Ivan\"}]])\n (submit+await-tx [[:crux.tx",
"end": 7537,
"score": 0.8219402432441711,
"start": 7533,
"tag": "NAME",
"value": "ivan"
},
{
"context": "wait-tx [[:crux.tx/put {:crux.db/id \"ivan\" :name \"Ivan\"}]])\n (submit+await-tx [[:crux.tx/put {:crux.d",
"end": 7550,
"score": 0.9975177049636841,
"start": 7546,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " (submit+await-tx [[:crux.tx/put {:crux.db/id \"ivan\" :name \"Ivan\"}]])\n\n (t/is (= 2 (l/doc-count)))",
"end": 7610,
"score": 0.784201979637146,
"start": 7606,
"tag": "NAME",
"value": "ivan"
},
{
"context": "wait-tx [[:crux.tx/put {:crux.db/id \"ivan\" :name \"Ivan\"}]])\n\n (t/is (= 2 (l/doc-count)))\n\n (with-o",
"end": 7623,
"score": 0.9978529214859009,
"start": 7619,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "x [[:crux.tx/put {:crux.db/id :real-ivan-2 :name \"Ivan Bob\"}]])\n (with-open [db (c/open-db *api*)]\n (t/i",
"end": 7847,
"score": 0.9973552227020264,
"start": 7839,
"tag": "NAME",
"value": "Ivan Bob"
},
{
"context": " :where '[[(text-search :name \"Ivan\") [[?e ?v]]]\n [?e",
"end": 7986,
"score": 0.9983915090560913,
"start": 7982,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "crux.tx/put {:crux.db/id :real-ivan-2 :myns/name \"Ivan\"}]])\n (with-open [db (c/open-db *api*)]\n (t/i",
"end": 8172,
"score": 0.9979606866836548,
"start": 8168,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " :where '[[(text-search :myns/name \"Ivan\") [[?e ?v]]]\n [?e",
"end": 8316,
"score": 0.998154878616333,
"start": 8312,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "ait-tx [[:crux.tx/put {:crux.db/id \"ivan0\" :name \"Ivan\"}]])\n (submit+await-tx [[:crux.tx/delete \"ivan0\"",
"end": 8498,
"score": 0.9975568056106567,
"start": 8494,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "ait-tx [[:crux.tx/put {:crux.db/id \"ivan1\" :name \"Ivana\"}]])\n\n (let [q {:find '[?e ?v ?s]\n :wh",
"end": 8619,
"score": 0.9988954663276672,
"start": 8614,
"tag": "NAME",
"value": "Ivana"
},
{
"context": "e ?v ?s]\n :where '[[(text-search :name \"Ivan*\") [[?e ?v ?s]]]\n [?e :crux.db",
"end": 8700,
"score": 0.9994443655014038,
"start": 8696,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "await-tx [[:crux.tx/put {:crux.db/id :ivan :name \"Ivan\"}]])\n (with-open [db (c/open-db *api*)]\n (t/i",
"end": 8946,
"score": 0.9994649887084961,
"start": 8942,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "ch :name input) [[?e ?v]]]]}\n \"Ivan\")))\n (t/is (thrown-with-msg? IllegalArgumentEx",
"end": 9163,
"score": 0.9990406036376953,
"start": 9159,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "let [q {:find '[?e] :where '[[(text-search :name \"Ivan\") [[?e]]] [?e :crux.db/id]]}]\n (submit+await-t",
"end": 9591,
"score": 0.9994287490844727,
"start": 9587,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "await-tx [[:crux.tx/put {:crux.db/id :ivan :name \"Ivanka\"}]])\n (with-open [before-db (c/open-db *api*)]",
"end": 9690,
"score": 0.999262809753418,
"start": 9684,
"tag": "NAME",
"value": "Ivanka"
},
{
"context": "await-tx [[:crux.tx/put {:crux.db/id :ivan :name \"Ivan\"}]])\n (t/is (empty? (c/q before-db q))))))\n\n",
"end": 9809,
"score": 0.9993054866790771,
"start": 9805,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "await-tx [[:crux.tx/put {:crux.db/id :ivan :name \"Ivank\"}]])\n\n (t/is (latest-tx))))\n\n(t/deftest test-e",
"end": 10102,
"score": 0.9984309673309326,
"start": 10097,
"tag": "NAME",
"value": "Ivank"
},
{
"context": "-tx node [[:crux.tx/put {:crux.db/id :ivan :name \"Ivan\"}]]))\n\n (try\n (with-open [node (c/sta",
"end": 10541,
"score": 0.997807502746582,
"start": 10537,
"tag": "NAME",
"value": "Ivan"
}
] | crux-lucene/test/crux/lucene_test.clj | AlistairONeill/crux | 0 | (ns crux.lucene-test
(:require [clojure.test :as t]
[crux.api :as c]
[crux.db :as db]
[crux.fixtures :as fix :refer [*api* submit+await-tx]]
[crux.fixtures.lucene :as lf]
[crux.lucene :as l]
[crux.rocksdb :as rocks])
(:import org.apache.lucene.document.Document))
(t/use-fixtures :each lf/with-lucene-module fix/with-node)
(t/deftest test-can-search-string
(let [doc {:crux.db/id :ivan :name "Ivan"}]
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "Ivan"}]])
(t/testing "using Lucene directly"
(with-open [search-results ^crux.api.ICursor (l/search (:crux.lucene/lucene-store @(:!system *api*)) :name "Ivan")]
(let [docs (iterator-seq search-results)]
(t/is (= 1 (count docs)))
(t/is (= "Ivan" (.get ^Document (ffirst docs) "_crux_val"))))))
(t/testing "using in-built function"
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan]} (c/q db {:find '[?e]
:where '[[(text-search :name "Ivan") [[?e]]]
[?e :crux.db/id]]})))
(t/testing "bad spec"
(t/is (thrown-with-msg? clojure.lang.ExceptionInfo #""
(c/q db {:find '[?e]
:where '[[(text-search "Wot" "Ivan") [[?e]]]
[?e :crux.db/id]]}))))
(t/testing "fuzzy"
(t/is (= #{[:ivan]} (c/q db {:find '[?e]
:where '[[(text-search :name "Iv*") [[?e]]]
[?e :crux.db/id]]}))))))
(t/testing "Subsequent tx/doc"
(with-open [before-db (c/open-db *api*)]
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan2 :name "Ivbn"}]])
(let [q {:find '[?e] :where '[[(text-search :name "Iv?n") [[?e]]] [?e :crux.db/id]]}]
(t/is (= #{[:ivan]} (c/q before-db q)))
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan] [:ivan2]} (c/q db q)))))))
(t/testing "Modifying doc"
(with-open [before-db (c/open-db *api*)]
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "Derek"}]])
(let [q {:find '[?e] :where '[[(text-search :name "Derek") [[?e]]] [?e :crux.db/id]]}]
(t/is (not (seq (c/q before-db q))))
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan]} (c/q db q)))))))
(t/testing "Eviction"
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan2 :name "Derek"}]])
(submit+await-tx [[:crux.tx/evict :ivan]])
(with-open [db (c/open-db *api*)]
(t/is (empty? (c/q db {:find '[?e]
:where
'[[(text-search :name "Ivan") [[?e]]]
[?e :crux.db/id]]}))))
(with-open [search-results ^crux.api.ICursor (l/search (:crux.lucene/lucene-store @(:!system *api*)) :name "Ivan")]
(t/is (empty? (iterator-seq search-results))))
(with-open [search-results ^crux.api.ICursor (l/search (:crux.lucene/lucene-store @(:!system *api*)) :name "Derek")]
(t/is (seq (iterator-seq search-results)))))
(t/testing "Scores"
(submit+await-tx [[:crux.tx/put {:crux.db/id "test0" :name "ivon"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "test1" :name "ivan"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "test2" :name "testivantest"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "test3" :name "testing"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "test4" :name "ivanpost"}]])
(with-open [db (c/open-db *api*)]
(t/is (= #{["test1" "ivan" 1.0] ["test4" "ivanpost" 1.0]}
(c/q db {:find '[?e ?v ?score]
:where '[[(text-search :name "ivan*") [[?e ?v ?score]]]
[?e :crux.db/id]]})))))
(t/testing "cardinality many"
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :foo #{"atar" "abar" "nomatch"}}]])
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan "atar"]}
(c/q db {:find '[?e ?v]
:where '[[(text-search :foo "atar") [[?e ?v]]]
[?e :crux.db/id]]}))))
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan "abar"]
[:ivan "atar"]}
(c/q db {:find '[?e ?v]
:where '[[(text-search :foo "a?ar") [[?e ?v]]]
[?e :crux.db/id]]})))))))
(t/deftest test-can-search-string-across-attributes
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "Ivan"}]])
(with-open [db (c/open-db *api*)]
(t/testing "dont specify A"
(t/is (= #{[:ivan "Ivan" :name]}
(c/q db {:find '[?e ?v ?a]
:where '[[(wildcard-text-search "Ivan") [[?e ?v ?a]]]
[?e :crux.db/id]]}))))
(t/testing "no match against a non-existant field"
(t/is (= #{}
(c/q db {:find '[?e ?v]
:where '[[(text-search :non-field "Ivan") [[?e ?v]]]
[?e :crux.db/id]]})))))
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "Ivan" :surname "Ivan"}]])
(t/testing "can find multiple a/vs"
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan "Ivan" :name]
[:ivan "Ivan" :surname]}
(c/q db {:find '[?e ?v ?a]
:where '[[(wildcard-text-search "Ivan") [[?e ?v ?a _]]]
[?e :crux.db/id]]}))))))
;; Leaving to document when score is impacted by accumulated temporal data
#_(t/deftest test-scoring-shouldnt-be-impacted-by-non-matched-past-docs
(submit+await-tx [[:crux.tx/put {:crux.db/id :real-ivan :name "Ivan Bob"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan-dave :name "Ivan Dave Ivan"}]])
(let [q {:find '[?v ?score]
:where '[[(text-search "Ivan" :name) [[?e ?v ?a ?score]]]
[?e :crux.db/id]]}
prior-score (with-open [db (c/open-db *api*)]
(c/q db q))]
(doseq [n (range 10)]
(submit+await-tx [[:crux.tx/put {:crux.db/id (str "id-" n) :name "NO MATCH"}]])
(submit+await-tx [[:crux.tx/delete (str "id-" n)]]))
(with-open [db (c/open-db *api*)]
(t/is (= prior-score (c/q db q))))))
;; Leaving to document when score is impacted by accumulated temporal data
#_(t/deftest test-scoring-shouldnt-be-impacted-by-matched-past-docs
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan" :name "Ivan Bob Bob"}]])
(let [q {:find '[?e ?v ?s]
:where '[[(text-search "Ivan" :name) [[?e ?v ?a ?s]]]
[?e :crux.db/id]]}
prior-score (with-open [db (c/open-db *api*)]
(c/q db q))]
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan1" :name "Ivan"}]])
(submit+await-tx [[:crux.tx/delete "ivan1"]])
(with-open [db (c/open-db *api*)]
(t/is (= prior-score (c/q db q))))))
(t/deftest test-structural-sharing
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan" :name "Ivan"}]])
(let [q {:find '[?e ?v ?s]
:where '[[(text-search :name "Ivan") [[?e ?v ?s]]]
[?e :crux.db/id]]}
prior-score (with-open [db (c/open-db *api*)]
(c/q db q))]
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan" :name "Ivan"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan" :name "Ivan"}]])
(t/is (= 2 (l/doc-count)))
(with-open [db (c/open-db *api*)]
(t/is (= prior-score (c/q db q))))))
(t/deftest test-keyword-ids
(submit+await-tx [[:crux.tx/put {:crux.db/id :real-ivan-2 :name "Ivan Bob"}]])
(with-open [db (c/open-db *api*)]
(t/is (seq (c/q db {:find '[?e ?v]
:where '[[(text-search :name "Ivan") [[?e ?v]]]
[?e :crux.db/id]]})))))
(t/deftest test-namespaced-attributes
(submit+await-tx [[:crux.tx/put {:crux.db/id :real-ivan-2 :myns/name "Ivan"}]])
(with-open [db (c/open-db *api*)]
(t/is (seq (c/q db {:find '[?e ?v]
:where '[[(text-search :myns/name "Ivan") [[?e ?v]]]
[?e :crux.db/id]]})))))
(t/deftest test-past-fuzzy-results-excluded
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan0" :name "Ivan"}]])
(submit+await-tx [[:crux.tx/delete "ivan0"]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan1" :name "Ivana"}]])
(let [q {:find '[?e ?v ?s]
:where '[[(text-search :name "Ivan*") [[?e ?v ?s]]]
[?e :crux.db/id]]}]
(with-open [db (c/open-db *api*)]
(t/is (= ["ivan1"] (map first (c/q db q)))))))
(t/deftest test-use-in-argument
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "Ivan"}]])
(with-open [db (c/open-db *api*)]
(t/is (seq (c/q db '{:find [?v]
:in [input]
:where [[(text-search :name input) [[?e ?v]]]]}
"Ivan")))
(t/is (thrown-with-msg? IllegalArgumentException #"Lucene text search values must be String"
(c/q db '{:find [?v]
:in [input]
:where [[(text-search :name input) [[?e ?v]]]]}
1)))))
(t/deftest test-exclude-future-results
(let [q {:find '[?e] :where '[[(text-search :name "Ivan") [[?e]]] [?e :crux.db/id]]}]
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "Ivanka"}]])
(with-open [before-db (c/open-db *api*)]
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "Ivan"}]])
(t/is (empty? (c/q before-db q))))))
(t/deftest test-ensure-lucene-store-keeps-last-tx
(let [latest-tx (fn [] (l/latest-submitted-tx (:crux.lucene/lucene-store @(:!system *api*))))]
(t/is (not (latest-tx)))
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "Ivank"}]])
(t/is (latest-tx))))
(t/deftest test-ensure-lucene-store-keeps-up
(fix/with-tmp-dir "rocks" [rocks-tmp-dir]
(fix/with-tmp-dir "lucene" [lucene-tmp-dir]
(with-open [node (c/start-node {:crux/index-store {:kv-store {:crux/module `rocks/->kv-store
:db-dir rocks-tmp-dir}}})]
(submit+await-tx node [[:crux.tx/put {:crux.db/id :ivan :name "Ivan"}]]))
(try
(with-open [node (c/start-node {:crux/index-store {:kv-store {:crux/module `rocks/->kv-store
:db-dir rocks-tmp-dir}}
:crux.lucene/lucene-store {:db-dir lucene-tmp-dir}})])
(t/is false "Exception expected")
(catch Exception t
(t/is (= "Lucene store latest tx mismatch" (ex-message (ex-cause t)))))))))
(t/deftest test-id-can-be-key-1274
(t/is (c/tx-committed? *api* (c/await-tx *api* (c/submit-tx *api* [[:crux.tx/put {:crux.db/id 512 :id "1"}]])))))
(comment
(do
(import '[ch.qos.logback.classic Level Logger]
'org.slf4j.LoggerFactory)
(.setLevel ^Logger (LoggerFactory/getLogger "crux.lucene") (Level/valueOf "INFO"))))
| 95772 | (ns crux.lucene-test
(:require [clojure.test :as t]
[crux.api :as c]
[crux.db :as db]
[crux.fixtures :as fix :refer [*api* submit+await-tx]]
[crux.fixtures.lucene :as lf]
[crux.lucene :as l]
[crux.rocksdb :as rocks])
(:import org.apache.lucene.document.Document))
(t/use-fixtures :each lf/with-lucene-module fix/with-node)
(t/deftest test-can-search-string
(let [doc {:crux.db/id :ivan :name "<NAME>"}]
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>"}]])
(t/testing "using Lucene directly"
(with-open [search-results ^crux.api.ICursor (l/search (:crux.lucene/lucene-store @(:!system *api*)) :name "<NAME>")]
(let [docs (iterator-seq search-results)]
(t/is (= 1 (count docs)))
(t/is (= "<NAME>" (.get ^Document (ffirst docs) "_crux_val"))))))
(t/testing "using in-built function"
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan]} (c/q db {:find '[?e]
:where '[[(text-search :name "<NAME>") [[?e]]]
[?e :crux.db/id]]})))
(t/testing "bad spec"
(t/is (thrown-with-msg? clojure.lang.ExceptionInfo #""
(c/q db {:find '[?e]
:where '[[(text-search "<NAME>" "<NAME>") [[?e]]]
[?e :crux.db/id]]}))))
(t/testing "fuzzy"
(t/is (= #{[:ivan]} (c/q db {:find '[?e]
:where '[[(text-search :name "<NAME>*") [[?e]]]
[?e :crux.db/id]]}))))))
(t/testing "Subsequent tx/doc"
(with-open [before-db (c/open-db *api*)]
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan2 :name "Ivbn"}]])
(let [q {:find '[?e] :where '[[(text-search :name "<NAME>") [[?e]]] [?e :crux.db/id]]}]
(t/is (= #{[:ivan]} (c/q before-db q)))
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan] [:ivan2]} (c/q db q)))))))
(t/testing "Modifying doc"
(with-open [before-db (c/open-db *api*)]
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>"}]])
(let [q {:find '[?e] :where '[[(text-search :name "<NAME>") [[?e]]] [?e :crux.db/id]]}]
(t/is (not (seq (c/q before-db q))))
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan]} (c/q db q)))))))
(t/testing "Eviction"
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan2 :name "<NAME>"}]])
(submit+await-tx [[:crux.tx/evict :ivan]])
(with-open [db (c/open-db *api*)]
(t/is (empty? (c/q db {:find '[?e]
:where
'[[(text-search :name "<NAME>") [[?e]]]
[?e :crux.db/id]]}))))
(with-open [search-results ^crux.api.ICursor (l/search (:crux.lucene/lucene-store @(:!system *api*)) :name "<NAME>")]
(t/is (empty? (iterator-seq search-results))))
(with-open [search-results ^crux.api.ICursor (l/search (:crux.lucene/lucene-store @(:!system *api*)) :name "<NAME>")]
(t/is (seq (iterator-seq search-results)))))
(t/testing "Scores"
(submit+await-tx [[:crux.tx/put {:crux.db/id "test0" :name "ivon"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "test1" :name "ivan"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "test2" :name "testivantest"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "test3" :name "testing"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "test4" :name "ivanpost"}]])
(with-open [db (c/open-db *api*)]
(t/is (= #{["test1" "ivan" 1.0] ["test4" "ivanpost" 1.0]}
(c/q db {:find '[?e ?v ?score]
:where '[[(text-search :name "ivan*") [[?e ?v ?score]]]
[?e :crux.db/id]]})))))
(t/testing "cardinality many"
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :foo #{"atar" "abar" "nomatch"}}]])
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan "atar"]}
(c/q db {:find '[?e ?v]
:where '[[(text-search :foo "atar") [[?e ?v]]]
[?e :crux.db/id]]}))))
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan "abar"]
[:ivan "<NAME>"]}
(c/q db {:find '[?e ?v]
:where '[[(text-search :foo "a?ar") [[?e ?v]]]
[?e :crux.db/id]]})))))))
(t/deftest test-can-search-string-across-attributes
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>"}]])
(with-open [db (c/open-db *api*)]
(t/testing "dont specify A"
(t/is (= #{[:ivan "<NAME>" :name]}
(c/q db {:find '[?e ?v ?a]
:where '[[(wildcard-text-search "<NAME>") [[?e ?v ?a]]]
[?e :crux.db/id]]}))))
(t/testing "no match against a non-existant field"
(t/is (= #{}
(c/q db {:find '[?e ?v]
:where '[[(text-search :non-field "<NAME>") [[?e ?v]]]
[?e :crux.db/id]]})))))
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>" :surname "Ivan"}]])
(t/testing "can find multiple a/vs"
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan "<NAME>" :name]
[:ivan "<NAME>" :surname]}
(c/q db {:find '[?e ?v ?a]
:where '[[(wildcard-text-search "<NAME>") [[?e ?v ?a _]]]
[?e :crux.db/id]]}))))))
;; Leaving to document when score is impacted by accumulated temporal data
#_(t/deftest test-scoring-shouldnt-be-impacted-by-non-matched-past-docs
(submit+await-tx [[:crux.tx/put {:crux.db/id :real-ivan :name "<NAME>"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan-dave :name "<NAME>"}]])
(let [q {:find '[?v ?score]
:where '[[(text-search "<NAME>" :name) [[?e ?v ?a ?score]]]
[?e :crux.db/id]]}
prior-score (with-open [db (c/open-db *api*)]
(c/q db q))]
(doseq [n (range 10)]
(submit+await-tx [[:crux.tx/put {:crux.db/id (str "id-" n) :name "NO MATCH"}]])
(submit+await-tx [[:crux.tx/delete (str "id-" n)]]))
(with-open [db (c/open-db *api*)]
(t/is (= prior-score (c/q db q))))))
;; Leaving to document when score is impacted by accumulated temporal data
#_(t/deftest test-scoring-shouldnt-be-impacted-by-matched-past-docs
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan" :name "<NAME>"}]])
(let [q {:find '[?e ?v ?s]
:where '[[(text-search "<NAME>" :name) [[?e ?v ?a ?s]]]
[?e :crux.db/id]]}
prior-score (with-open [db (c/open-db *api*)]
(c/q db q))]
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan1" :name "<NAME>"}]])
(submit+await-tx [[:crux.tx/delete "ivan1"]])
(with-open [db (c/open-db *api*)]
(t/is (= prior-score (c/q db q))))))
(t/deftest test-structural-sharing
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan" :name "<NAME>"}]])
(let [q {:find '[?e ?v ?s]
:where '[[(text-search :name "<NAME>") [[?e ?v ?s]]]
[?e :crux.db/id]]}
prior-score (with-open [db (c/open-db *api*)]
(c/q db q))]
(submit+await-tx [[:crux.tx/put {:crux.db/id "<NAME>" :name "<NAME>"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "<NAME>" :name "<NAME>"}]])
(t/is (= 2 (l/doc-count)))
(with-open [db (c/open-db *api*)]
(t/is (= prior-score (c/q db q))))))
(t/deftest test-keyword-ids
(submit+await-tx [[:crux.tx/put {:crux.db/id :real-ivan-2 :name "<NAME>"}]])
(with-open [db (c/open-db *api*)]
(t/is (seq (c/q db {:find '[?e ?v]
:where '[[(text-search :name "<NAME>") [[?e ?v]]]
[?e :crux.db/id]]})))))
(t/deftest test-namespaced-attributes
(submit+await-tx [[:crux.tx/put {:crux.db/id :real-ivan-2 :myns/name "<NAME>"}]])
(with-open [db (c/open-db *api*)]
(t/is (seq (c/q db {:find '[?e ?v]
:where '[[(text-search :myns/name "<NAME>") [[?e ?v]]]
[?e :crux.db/id]]})))))
(t/deftest test-past-fuzzy-results-excluded
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan0" :name "<NAME>"}]])
(submit+await-tx [[:crux.tx/delete "ivan0"]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan1" :name "<NAME>"}]])
(let [q {:find '[?e ?v ?s]
:where '[[(text-search :name "<NAME>*") [[?e ?v ?s]]]
[?e :crux.db/id]]}]
(with-open [db (c/open-db *api*)]
(t/is (= ["ivan1"] (map first (c/q db q)))))))
(t/deftest test-use-in-argument
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>"}]])
(with-open [db (c/open-db *api*)]
(t/is (seq (c/q db '{:find [?v]
:in [input]
:where [[(text-search :name input) [[?e ?v]]]]}
"<NAME>")))
(t/is (thrown-with-msg? IllegalArgumentException #"Lucene text search values must be String"
(c/q db '{:find [?v]
:in [input]
:where [[(text-search :name input) [[?e ?v]]]]}
1)))))
(t/deftest test-exclude-future-results
(let [q {:find '[?e] :where '[[(text-search :name "<NAME>") [[?e]]] [?e :crux.db/id]]}]
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>"}]])
(with-open [before-db (c/open-db *api*)]
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>"}]])
(t/is (empty? (c/q before-db q))))))
(t/deftest test-ensure-lucene-store-keeps-last-tx
(let [latest-tx (fn [] (l/latest-submitted-tx (:crux.lucene/lucene-store @(:!system *api*))))]
(t/is (not (latest-tx)))
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>"}]])
(t/is (latest-tx))))
(t/deftest test-ensure-lucene-store-keeps-up
(fix/with-tmp-dir "rocks" [rocks-tmp-dir]
(fix/with-tmp-dir "lucene" [lucene-tmp-dir]
(with-open [node (c/start-node {:crux/index-store {:kv-store {:crux/module `rocks/->kv-store
:db-dir rocks-tmp-dir}}})]
(submit+await-tx node [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>"}]]))
(try
(with-open [node (c/start-node {:crux/index-store {:kv-store {:crux/module `rocks/->kv-store
:db-dir rocks-tmp-dir}}
:crux.lucene/lucene-store {:db-dir lucene-tmp-dir}})])
(t/is false "Exception expected")
(catch Exception t
(t/is (= "Lucene store latest tx mismatch" (ex-message (ex-cause t)))))))))
(t/deftest test-id-can-be-key-1274
(t/is (c/tx-committed? *api* (c/await-tx *api* (c/submit-tx *api* [[:crux.tx/put {:crux.db/id 512 :id "1"}]])))))
(comment
(do
(import '[ch.qos.logback.classic Level Logger]
'org.slf4j.LoggerFactory)
(.setLevel ^Logger (LoggerFactory/getLogger "crux.lucene") (Level/valueOf "INFO"))))
| true | (ns crux.lucene-test
(:require [clojure.test :as t]
[crux.api :as c]
[crux.db :as db]
[crux.fixtures :as fix :refer [*api* submit+await-tx]]
[crux.fixtures.lucene :as lf]
[crux.lucene :as l]
[crux.rocksdb :as rocks])
(:import org.apache.lucene.document.Document))
(t/use-fixtures :each lf/with-lucene-module fix/with-node)
(t/deftest test-can-search-string
(let [doc {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"}]
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"}]])
(t/testing "using Lucene directly"
(with-open [search-results ^crux.api.ICursor (l/search (:crux.lucene/lucene-store @(:!system *api*)) :name "PI:NAME:<NAME>END_PI")]
(let [docs (iterator-seq search-results)]
(t/is (= 1 (count docs)))
(t/is (= "PI:NAME:<NAME>END_PI" (.get ^Document (ffirst docs) "_crux_val"))))))
(t/testing "using in-built function"
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan]} (c/q db {:find '[?e]
:where '[[(text-search :name "PI:NAME:<NAME>END_PI") [[?e]]]
[?e :crux.db/id]]})))
(t/testing "bad spec"
(t/is (thrown-with-msg? clojure.lang.ExceptionInfo #""
(c/q db {:find '[?e]
:where '[[(text-search "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") [[?e]]]
[?e :crux.db/id]]}))))
(t/testing "fuzzy"
(t/is (= #{[:ivan]} (c/q db {:find '[?e]
:where '[[(text-search :name "PI:NAME:<NAME>END_PI*") [[?e]]]
[?e :crux.db/id]]}))))))
(t/testing "Subsequent tx/doc"
(with-open [before-db (c/open-db *api*)]
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan2 :name "Ivbn"}]])
(let [q {:find '[?e] :where '[[(text-search :name "PI:NAME:<NAME>END_PI") [[?e]]] [?e :crux.db/id]]}]
(t/is (= #{[:ivan]} (c/q before-db q)))
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan] [:ivan2]} (c/q db q)))))))
(t/testing "Modifying doc"
(with-open [before-db (c/open-db *api*)]
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"}]])
(let [q {:find '[?e] :where '[[(text-search :name "PI:NAME:<NAME>END_PI") [[?e]]] [?e :crux.db/id]]}]
(t/is (not (seq (c/q before-db q))))
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan]} (c/q db q)))))))
(t/testing "Eviction"
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan2 :name "PI:NAME:<NAME>END_PI"}]])
(submit+await-tx [[:crux.tx/evict :ivan]])
(with-open [db (c/open-db *api*)]
(t/is (empty? (c/q db {:find '[?e]
:where
'[[(text-search :name "PI:NAME:<NAME>END_PI") [[?e]]]
[?e :crux.db/id]]}))))
(with-open [search-results ^crux.api.ICursor (l/search (:crux.lucene/lucene-store @(:!system *api*)) :name "PI:NAME:<NAME>END_PI")]
(t/is (empty? (iterator-seq search-results))))
(with-open [search-results ^crux.api.ICursor (l/search (:crux.lucene/lucene-store @(:!system *api*)) :name "PI:NAME:<NAME>END_PI")]
(t/is (seq (iterator-seq search-results)))))
(t/testing "Scores"
(submit+await-tx [[:crux.tx/put {:crux.db/id "test0" :name "ivon"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "test1" :name "ivan"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "test2" :name "testivantest"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "test3" :name "testing"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "test4" :name "ivanpost"}]])
(with-open [db (c/open-db *api*)]
(t/is (= #{["test1" "ivan" 1.0] ["test4" "ivanpost" 1.0]}
(c/q db {:find '[?e ?v ?score]
:where '[[(text-search :name "ivan*") [[?e ?v ?score]]]
[?e :crux.db/id]]})))))
(t/testing "cardinality many"
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :foo #{"atar" "abar" "nomatch"}}]])
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan "atar"]}
(c/q db {:find '[?e ?v]
:where '[[(text-search :foo "atar") [[?e ?v]]]
[?e :crux.db/id]]}))))
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan "abar"]
[:ivan "PI:NAME:<NAME>END_PI"]}
(c/q db {:find '[?e ?v]
:where '[[(text-search :foo "a?ar") [[?e ?v]]]
[?e :crux.db/id]]})))))))
(t/deftest test-can-search-string-across-attributes
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"}]])
(with-open [db (c/open-db *api*)]
(t/testing "dont specify A"
(t/is (= #{[:ivan "PI:NAME:<NAME>END_PI" :name]}
(c/q db {:find '[?e ?v ?a]
:where '[[(wildcard-text-search "PI:NAME:<NAME>END_PI") [[?e ?v ?a]]]
[?e :crux.db/id]]}))))
(t/testing "no match against a non-existant field"
(t/is (= #{}
(c/q db {:find '[?e ?v]
:where '[[(text-search :non-field "PI:NAME:<NAME>END_PI") [[?e ?v]]]
[?e :crux.db/id]]})))))
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :surname "Ivan"}]])
(t/testing "can find multiple a/vs"
(with-open [db (c/open-db *api*)]
(t/is (= #{[:ivan "PI:NAME:<NAME>END_PI" :name]
[:ivan "PI:NAME:<NAME>END_PI" :surname]}
(c/q db {:find '[?e ?v ?a]
:where '[[(wildcard-text-search "PI:NAME:<NAME>END_PI") [[?e ?v ?a _]]]
[?e :crux.db/id]]}))))))
;; Leaving to document when score is impacted by accumulated temporal data
#_(t/deftest test-scoring-shouldnt-be-impacted-by-non-matched-past-docs
(submit+await-tx [[:crux.tx/put {:crux.db/id :real-ivan :name "PI:NAME:<NAME>END_PI"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan-dave :name "PI:NAME:<NAME>END_PI"}]])
(let [q {:find '[?v ?score]
:where '[[(text-search "PI:NAME:<NAME>END_PI" :name) [[?e ?v ?a ?score]]]
[?e :crux.db/id]]}
prior-score (with-open [db (c/open-db *api*)]
(c/q db q))]
(doseq [n (range 10)]
(submit+await-tx [[:crux.tx/put {:crux.db/id (str "id-" n) :name "NO MATCH"}]])
(submit+await-tx [[:crux.tx/delete (str "id-" n)]]))
(with-open [db (c/open-db *api*)]
(t/is (= prior-score (c/q db q))))))
;; Leaving to document when score is impacted by accumulated temporal data
#_(t/deftest test-scoring-shouldnt-be-impacted-by-matched-past-docs
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan" :name "PI:NAME:<NAME>END_PI"}]])
(let [q {:find '[?e ?v ?s]
:where '[[(text-search "PI:NAME:<NAME>END_PI" :name) [[?e ?v ?a ?s]]]
[?e :crux.db/id]]}
prior-score (with-open [db (c/open-db *api*)]
(c/q db q))]
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan1" :name "PI:NAME:<NAME>END_PI"}]])
(submit+await-tx [[:crux.tx/delete "ivan1"]])
(with-open [db (c/open-db *api*)]
(t/is (= prior-score (c/q db q))))))
(t/deftest test-structural-sharing
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan" :name "PI:NAME:<NAME>END_PI"}]])
(let [q {:find '[?e ?v ?s]
:where '[[(text-search :name "PI:NAME:<NAME>END_PI") [[?e ?v ?s]]]
[?e :crux.db/id]]}
prior-score (with-open [db (c/open-db *api*)]
(c/q db q))]
(submit+await-tx [[:crux.tx/put {:crux.db/id "PI:NAME:<NAME>END_PI" :name "PI:NAME:<NAME>END_PI"}]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "PI:NAME:<NAME>END_PI" :name "PI:NAME:<NAME>END_PI"}]])
(t/is (= 2 (l/doc-count)))
(with-open [db (c/open-db *api*)]
(t/is (= prior-score (c/q db q))))))
(t/deftest test-keyword-ids
(submit+await-tx [[:crux.tx/put {:crux.db/id :real-ivan-2 :name "PI:NAME:<NAME>END_PI"}]])
(with-open [db (c/open-db *api*)]
(t/is (seq (c/q db {:find '[?e ?v]
:where '[[(text-search :name "PI:NAME:<NAME>END_PI") [[?e ?v]]]
[?e :crux.db/id]]})))))
(t/deftest test-namespaced-attributes
(submit+await-tx [[:crux.tx/put {:crux.db/id :real-ivan-2 :myns/name "PI:NAME:<NAME>END_PI"}]])
(with-open [db (c/open-db *api*)]
(t/is (seq (c/q db {:find '[?e ?v]
:where '[[(text-search :myns/name "PI:NAME:<NAME>END_PI") [[?e ?v]]]
[?e :crux.db/id]]})))))
(t/deftest test-past-fuzzy-results-excluded
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan0" :name "PI:NAME:<NAME>END_PI"}]])
(submit+await-tx [[:crux.tx/delete "ivan0"]])
(submit+await-tx [[:crux.tx/put {:crux.db/id "ivan1" :name "PI:NAME:<NAME>END_PI"}]])
(let [q {:find '[?e ?v ?s]
:where '[[(text-search :name "PI:NAME:<NAME>END_PI*") [[?e ?v ?s]]]
[?e :crux.db/id]]}]
(with-open [db (c/open-db *api*)]
(t/is (= ["ivan1"] (map first (c/q db q)))))))
(t/deftest test-use-in-argument
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"}]])
(with-open [db (c/open-db *api*)]
(t/is (seq (c/q db '{:find [?v]
:in [input]
:where [[(text-search :name input) [[?e ?v]]]]}
"PI:NAME:<NAME>END_PI")))
(t/is (thrown-with-msg? IllegalArgumentException #"Lucene text search values must be String"
(c/q db '{:find [?v]
:in [input]
:where [[(text-search :name input) [[?e ?v]]]]}
1)))))
(t/deftest test-exclude-future-results
(let [q {:find '[?e] :where '[[(text-search :name "PI:NAME:<NAME>END_PI") [[?e]]] [?e :crux.db/id]]}]
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"}]])
(with-open [before-db (c/open-db *api*)]
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"}]])
(t/is (empty? (c/q before-db q))))))
(t/deftest test-ensure-lucene-store-keeps-last-tx
(let [latest-tx (fn [] (l/latest-submitted-tx (:crux.lucene/lucene-store @(:!system *api*))))]
(t/is (not (latest-tx)))
(submit+await-tx [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"}]])
(t/is (latest-tx))))
(t/deftest test-ensure-lucene-store-keeps-up
(fix/with-tmp-dir "rocks" [rocks-tmp-dir]
(fix/with-tmp-dir "lucene" [lucene-tmp-dir]
(with-open [node (c/start-node {:crux/index-store {:kv-store {:crux/module `rocks/->kv-store
:db-dir rocks-tmp-dir}}})]
(submit+await-tx node [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"}]]))
(try
(with-open [node (c/start-node {:crux/index-store {:kv-store {:crux/module `rocks/->kv-store
:db-dir rocks-tmp-dir}}
:crux.lucene/lucene-store {:db-dir lucene-tmp-dir}})])
(t/is false "Exception expected")
(catch Exception t
(t/is (= "Lucene store latest tx mismatch" (ex-message (ex-cause t)))))))))
(t/deftest test-id-can-be-key-1274
(t/is (c/tx-committed? *api* (c/await-tx *api* (c/submit-tx *api* [[:crux.tx/put {:crux.db/id 512 :id "1"}]])))))
(comment
(do
(import '[ch.qos.logback.classic Level Logger]
'org.slf4j.LoggerFactory)
(.setLevel ^Logger (LoggerFactory/getLogger "crux.lucene") (Level/valueOf "INFO"))))
|
[
{
"context": " :constructor map->Person\n :items [{:name :andy}\n {:name :bob}]})\n => (comp group? d",
"end": 372,
"score": 0.9926989674568176,
"start": 368,
"tag": "NAME",
"value": "andy"
},
{
"context": " item to the group\"\n (-> (defitem people {:name :chris})\n deref\n list-items)\n => [:andy :bob ",
"end": 541,
"score": 0.9542421102523804,
"start": 536,
"tag": "NAME",
"value": "chris"
},
{
"context": "ame :chris})\n deref\n list-items)\n => [:andy :bob :chris]\n ^:hidden\n (remove-item people :ch",
"end": 585,
"score": 0.599680483341217,
"start": 581,
"tag": "NAME",
"value": "andy"
},
{
"context": "item to the group\"\n (-> (add-item people {:name :chris})\n (list-items))\n => [:andy :bob :chris])\n\n",
"end": 1144,
"score": 0.9731929302215576,
"start": 1139,
"tag": "NAME",
"value": "chris"
},
{
"context": "people {:name :chris})\n (list-items))\n => [:andy :bob :chris])\n\n^{:refer hara.group/find-item :add",
"end": 1178,
"score": 0.6574770212173462,
"start": 1174,
"tag": "NAME",
"value": "andy"
},
{
"context": "iven key\"\n (find-item people :andy)\n => {:name :andy})\n\n^{:refer hara.group/remove-item :added \"2.2\"}\n",
"end": 1327,
"score": 0.6873607635498047,
"start": 1323,
"tag": "NAME",
"value": "andy"
},
{
"context": "tems based on the key\"\n (-> (remove-item people :chris)\n (list-items))\n => [:andy :bob])\n\n^{:ref",
"end": 1446,
"score": 0.52128666639328,
"start": 1443,
"tag": "NAME",
"value": "chr"
},
{
"context": "ve-item people :chris)\n (list-items))\n => [:andy :bob])\n\n^{:refer hara.group/append-items :added \"",
"end": 1481,
"score": 0.9753987193107605,
"start": 1477,
"tag": "NAME",
"value": "andy"
},
{
"context": "m people :chris)\n (list-items))\n => [:andy :bob])\n\n^{:refer hara.group/append-items :added \"2.2\"}",
"end": 1486,
"score": 0.9558330774307251,
"start": 1483,
"tag": "NAME",
"value": "bob"
},
{
"context": "to the group\"\n (-> (append-items people [{:name :dave} {:name :erin}])\n (list-items))\n => [:andy ",
"end": 1620,
"score": 0.8487889766693115,
"start": 1616,
"tag": "NAME",
"value": "dave"
},
{
"context": " (-> (append-items people [{:name :dave} {:name :erin}])\n (list-items))\n => [:andy :bob :dave :er",
"end": 1634,
"score": 0.9971282482147217,
"start": 1630,
"tag": "NAME",
"value": "erin"
},
{
"context": ":dave} {:name :erin}])\n (list-items))\n => [:andy :bob :dave :erin]\n ^:hidden\n (-> people\n (",
"end": 1669,
"score": 0.942337155342102,
"start": 1665,
"tag": "NAME",
"value": "andy"
},
{
"context": " {:name :erin}])\n (list-items))\n => [:andy :bob :dave :erin]\n ^:hidden\n (-> people\n (remov",
"end": 1674,
"score": 0.981630265712738,
"start": 1671,
"tag": "NAME",
"value": "bob"
},
{
"context": "me :erin}])\n (list-items))\n => [:andy :bob :dave :erin]\n ^:hidden\n (-> people\n (remove-item",
"end": 1680,
"score": 0.9973777532577515,
"start": 1676,
"tag": "NAME",
"value": "dave"
},
{
"context": "in}])\n (list-items))\n => [:andy :bob :dave :erin]\n ^:hidden\n (-> people\n (remove-item :dave",
"end": 1686,
"score": 0.9975262880325317,
"start": 1682,
"tag": "NAME",
"value": "erin"
},
{
"context": "rin]\n ^:hidden\n (-> people\n (remove-item :dave)\n (remove-item :erin)))\n\n^{:refer hara.group",
"end": 1736,
"score": 0.38609588146209717,
"start": 1733,
"tag": "NAME",
"value": "ave"
},
{
"context": "ingReader.\n \"[{:name :dave} {:name :erin}]\"))\n (list-items))\n => [:and",
"end": 1981,
"score": 0.6939517855644226,
"start": 1977,
"tag": "NAME",
"value": "dave"
},
{
"context": " \"[{:name :dave} {:name :erin}]\"))\n (list-items))\n => [:andy :bob :dave :",
"end": 1995,
"score": 0.5301777720451355,
"start": 1993,
"tag": "NAME",
"value": "in"
},
{
"context": "ave} {:name :erin}]\"))\n (list-items))\n => [:andy :bob :dave :erin]\n ^:hidden\n (-> people\n (",
"end": 2032,
"score": 0.9791659712791443,
"start": 2028,
"tag": "NAME",
"value": "andy"
},
{
"context": ":name :erin}]\"))\n (list-items))\n => [:andy :bob :dave :erin]\n ^:hidden\n (-> people\n (remov",
"end": 2037,
"score": 0.9941551089286804,
"start": 2034,
"tag": "NAME",
"value": "bob"
},
{
"context": " :erin}]\"))\n (list-items))\n => [:andy :bob :dave :erin]\n ^:hidden\n (-> people\n (remove-item",
"end": 2043,
"score": 0.9987810254096985,
"start": 2039,
"tag": "NAME",
"value": "dave"
},
{
"context": "}]\"))\n (list-items))\n => [:andy :bob :dave :erin]\n ^:hidden\n (-> people\n (remove-item :dave",
"end": 2049,
"score": 0.9971804618835449,
"start": 2045,
"tag": "NAME",
"value": "erin"
}
] | test/hara/group_test.clj | ikitommi/hara | 0 | (ns hara.group-test
(:use midje.sweet)
(:require [hara.group :refer :all]))
(defrecord Person [])
(defmethod print-method
Person
[v ^java.io.Writer w]
(.write w (str "#person" (into {} v))))
^{:refer hara.group/defgroup :added "2.2"}
(fact "creates a group of items"
(defgroup people
{:tag :people
:constructor map->Person
:items [{:name :andy}
{:name :bob}]})
=> (comp group? deref))
^{:refer hara.group/defitem :added "2.2"}
(fact "adds an item to the group"
(-> (defitem people {:name :chris})
deref
list-items)
=> [:andy :bob :chris]
^:hidden
(remove-item people :chris))
^{:refer hara.group/group :added "2.2"}
(fact "creates a group from a map"
(group {:tag :hello})
=> #(-> % :tag (= :hello)))
^{:refer hara.group/group? :added "2.2"}
(fact "checks to see if an element is a group"
(group? people)
=> true)
^{:refer hara.group/list-items :added "2.2"}
(fact "returns a list of keys to items in the group"
(list-items people)
=> [:andy :bob])
^{:refer hara.group/add-item :added "2.2"}
(fact "adds an item to the group"
(-> (add-item people {:name :chris})
(list-items))
=> [:andy :bob :chris])
^{:refer hara.group/find-item :added "2.2"}
(fact "finds an item based on the given key"
(find-item people :andy)
=> {:name :andy})
^{:refer hara.group/remove-item :added "2.2"}
(fact "removes items based on the key"
(-> (remove-item people :chris)
(list-items))
=> [:andy :bob])
^{:refer hara.group/append-items :added "2.2"}
(fact "appends a set of data to the group"
(-> (append-items people [{:name :dave} {:name :erin}])
(list-items))
=> [:andy :bob :dave :erin]
^:hidden
(-> people
(remove-item :dave)
(remove-item :erin)))
^{:refer hara.group/install-items :added "2.2"}
(fact "reads a set of data from a resource and loads it into the group"
(-> (install-items people (java.io.StringReader.
"[{:name :dave} {:name :erin}]"))
(list-items))
=> [:andy :bob :dave :erin]
^:hidden
(-> people
(remove-item :dave)
(remove-item :erin)))
| 104951 | (ns hara.group-test
(:use midje.sweet)
(:require [hara.group :refer :all]))
(defrecord Person [])
(defmethod print-method
Person
[v ^java.io.Writer w]
(.write w (str "#person" (into {} v))))
^{:refer hara.group/defgroup :added "2.2"}
(fact "creates a group of items"
(defgroup people
{:tag :people
:constructor map->Person
:items [{:name :<NAME>}
{:name :bob}]})
=> (comp group? deref))
^{:refer hara.group/defitem :added "2.2"}
(fact "adds an item to the group"
(-> (defitem people {:name :<NAME>})
deref
list-items)
=> [:<NAME> :bob :chris]
^:hidden
(remove-item people :chris))
^{:refer hara.group/group :added "2.2"}
(fact "creates a group from a map"
(group {:tag :hello})
=> #(-> % :tag (= :hello)))
^{:refer hara.group/group? :added "2.2"}
(fact "checks to see if an element is a group"
(group? people)
=> true)
^{:refer hara.group/list-items :added "2.2"}
(fact "returns a list of keys to items in the group"
(list-items people)
=> [:andy :bob])
^{:refer hara.group/add-item :added "2.2"}
(fact "adds an item to the group"
(-> (add-item people {:name :<NAME>})
(list-items))
=> [:<NAME> :bob :chris])
^{:refer hara.group/find-item :added "2.2"}
(fact "finds an item based on the given key"
(find-item people :andy)
=> {:name :<NAME>})
^{:refer hara.group/remove-item :added "2.2"}
(fact "removes items based on the key"
(-> (remove-item people :<NAME>is)
(list-items))
=> [:<NAME> :<NAME>])
^{:refer hara.group/append-items :added "2.2"}
(fact "appends a set of data to the group"
(-> (append-items people [{:name :<NAME>} {:name :<NAME>}])
(list-items))
=> [:<NAME> :<NAME> :<NAME> :<NAME>]
^:hidden
(-> people
(remove-item :d<NAME>)
(remove-item :erin)))
^{:refer hara.group/install-items :added "2.2"}
(fact "reads a set of data from a resource and loads it into the group"
(-> (install-items people (java.io.StringReader.
"[{:name :<NAME>} {:name :er<NAME>}]"))
(list-items))
=> [:<NAME> :<NAME> :<NAME> :<NAME>]
^:hidden
(-> people
(remove-item :dave)
(remove-item :erin)))
| true | (ns hara.group-test
(:use midje.sweet)
(:require [hara.group :refer :all]))
(defrecord Person [])
(defmethod print-method
Person
[v ^java.io.Writer w]
(.write w (str "#person" (into {} v))))
^{:refer hara.group/defgroup :added "2.2"}
(fact "creates a group of items"
(defgroup people
{:tag :people
:constructor map->Person
:items [{:name :PI:NAME:<NAME>END_PI}
{:name :bob}]})
=> (comp group? deref))
^{:refer hara.group/defitem :added "2.2"}
(fact "adds an item to the group"
(-> (defitem people {:name :PI:NAME:<NAME>END_PI})
deref
list-items)
=> [:PI:NAME:<NAME>END_PI :bob :chris]
^:hidden
(remove-item people :chris))
^{:refer hara.group/group :added "2.2"}
(fact "creates a group from a map"
(group {:tag :hello})
=> #(-> % :tag (= :hello)))
^{:refer hara.group/group? :added "2.2"}
(fact "checks to see if an element is a group"
(group? people)
=> true)
^{:refer hara.group/list-items :added "2.2"}
(fact "returns a list of keys to items in the group"
(list-items people)
=> [:andy :bob])
^{:refer hara.group/add-item :added "2.2"}
(fact "adds an item to the group"
(-> (add-item people {:name :PI:NAME:<NAME>END_PI})
(list-items))
=> [:PI:NAME:<NAME>END_PI :bob :chris])
^{:refer hara.group/find-item :added "2.2"}
(fact "finds an item based on the given key"
(find-item people :andy)
=> {:name :PI:NAME:<NAME>END_PI})
^{:refer hara.group/remove-item :added "2.2"}
(fact "removes items based on the key"
(-> (remove-item people :PI:NAME:<NAME>END_PIis)
(list-items))
=> [:PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI])
^{:refer hara.group/append-items :added "2.2"}
(fact "appends a set of data to the group"
(-> (append-items people [{:name :PI:NAME:<NAME>END_PI} {:name :PI:NAME:<NAME>END_PI}])
(list-items))
=> [:PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI]
^:hidden
(-> people
(remove-item :dPI:NAME:<NAME>END_PI)
(remove-item :erin)))
^{:refer hara.group/install-items :added "2.2"}
(fact "reads a set of data from a resource and loads it into the group"
(-> (install-items people (java.io.StringReader.
"[{:name :PI:NAME:<NAME>END_PI} {:name :erPI:NAME:<NAME>END_PI}]"))
(list-items))
=> [:PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI]
^:hidden
(-> people
(remove-item :dave)
(remove-item :erin)))
|
[
{
"context": "nt\"\n (spit (io/file src-dir \"ivan.txt\") \"Hey Ivan!\")\n\n (t/is (= cp-2\n ",
"end": 2453,
"score": 0.7187256813049316,
"start": 2450,
"tag": "NAME",
"value": "Hey"
},
{
"context": "\n (spit (io/file src-dir \"ivan.txt\") \"Hey Ivan!\")\n\n (t/is (= cp-2\n (->",
"end": 2458,
"score": 0.8973270654678345,
"start": 2454,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "est-dir \"hello.txt\"))))\n\n (t/is (= \"Hey Ivan!\"\n (slurp (io/file dest-dir \"i",
"end": 3227,
"score": 0.9763036966323853,
"start": 3223,
"tag": "NAME",
"value": "Ivan"
}
] | test/avisi_apps/crux/google_cloud_storage/checkpoint_test.clj | avisi-apps/crux-google-cloud-storage | 1 | (ns avisi-apps.crux.google-cloud-storage.checkpoint-test
(:require [clojure.test :as t]
[avisi-apps.crux.google-cloud-storage.checkpoint :as gcs-check]
[crux.io :as cio]
[crux.tx :as tx]
[crux.checkpoint :as cp]
[crux.system :as sys]
[clojure.java.io :as io])
(:import [com.google.cloud.storage.contrib.nio.testing LocalStorageHelper]
[java.io File]
[java.nio.file Files]
[java.nio.file.attribute FileAttribute]))
(defn with-tmp-dir* [prefix f]
(let [dir (.toFile (Files/createTempDirectory prefix (make-array FileAttribute 0)))]
(try (f dir) (finally (cio/delete-dir dir)))))
(defmacro with-tmp-dir
[prefix [dir-binding] & body]
`(with-tmp-dir*
~prefix
(fn
[~(->
dir-binding
(with-meta {:type File}))]
~@body)))
(t/deftest test-checkpoint-store
(with-open [sys (-> (sys/prep-system {:store {:crux/module `gcs-check/->cp-store
:storage-options (fn [_] (LocalStorageHelper/getOptions))
:bucket "test"}})
(sys/start-system))]
(with-tmp-dir "gcs-cp" [cp-dir]
(let [{:keys [store]} sys
src-dir (doto (io/file cp-dir "src")
(.mkdirs))
cp-1 {::cp/cp-format ::foo-cp-format
:tx {::tx/tx-id 1}}
cp-2 {::cp/cp-format ::foo-cp-format
:tx {::tx/tx-id 2}}]
(t/testing "first checkpoint"
(spit (io/file src-dir "hello.txt") "Hello world")
(t/is (= cp-1
(-> (cp/upload-checkpoint store src-dir cp-1)
(select-keys #{::cp/cp-format :tx}))))
(t/is (empty? (cp/available-checkpoints store {::cp/cp-format ::bar-cp-format})))
(let [dest-dir (io/file cp-dir "dest")
cps (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})]
(t/is (= [cp-1]
(->> (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})
(map #(select-keys % #{::cp/cp-format :tx})))))
(cp/download-checkpoint store (first cps) dest-dir)
(t/is (= "Hello world"
(slurp (io/file dest-dir "hello.txt"))))))
(t/testing "second checkpoint"
(spit (io/file src-dir "ivan.txt") "Hey Ivan!")
(t/is (= cp-2
(-> (cp/upload-checkpoint store src-dir cp-2)
(select-keys #{::cp/cp-format :tx}))))
(t/is (empty? (cp/available-checkpoints store {::cp/cp-format ::bar-cp-format})))
(let [dest-dir (io/file cp-dir "dest-2")
cps (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})]
(t/is (= [cp-2 cp-1]
(->> (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})
(map #(select-keys % #{::cp/cp-format :tx})))))
(cp/download-checkpoint store (first cps) dest-dir)
(t/is (= "Hello world"
(slurp (io/file dest-dir "hello.txt"))))
(t/is (= "Hey Ivan!"
(slurp (io/file dest-dir "ivan.txt"))))))))))
| 102349 | (ns avisi-apps.crux.google-cloud-storage.checkpoint-test
(:require [clojure.test :as t]
[avisi-apps.crux.google-cloud-storage.checkpoint :as gcs-check]
[crux.io :as cio]
[crux.tx :as tx]
[crux.checkpoint :as cp]
[crux.system :as sys]
[clojure.java.io :as io])
(:import [com.google.cloud.storage.contrib.nio.testing LocalStorageHelper]
[java.io File]
[java.nio.file Files]
[java.nio.file.attribute FileAttribute]))
(defn with-tmp-dir* [prefix f]
(let [dir (.toFile (Files/createTempDirectory prefix (make-array FileAttribute 0)))]
(try (f dir) (finally (cio/delete-dir dir)))))
(defmacro with-tmp-dir
[prefix [dir-binding] & body]
`(with-tmp-dir*
~prefix
(fn
[~(->
dir-binding
(with-meta {:type File}))]
~@body)))
(t/deftest test-checkpoint-store
(with-open [sys (-> (sys/prep-system {:store {:crux/module `gcs-check/->cp-store
:storage-options (fn [_] (LocalStorageHelper/getOptions))
:bucket "test"}})
(sys/start-system))]
(with-tmp-dir "gcs-cp" [cp-dir]
(let [{:keys [store]} sys
src-dir (doto (io/file cp-dir "src")
(.mkdirs))
cp-1 {::cp/cp-format ::foo-cp-format
:tx {::tx/tx-id 1}}
cp-2 {::cp/cp-format ::foo-cp-format
:tx {::tx/tx-id 2}}]
(t/testing "first checkpoint"
(spit (io/file src-dir "hello.txt") "Hello world")
(t/is (= cp-1
(-> (cp/upload-checkpoint store src-dir cp-1)
(select-keys #{::cp/cp-format :tx}))))
(t/is (empty? (cp/available-checkpoints store {::cp/cp-format ::bar-cp-format})))
(let [dest-dir (io/file cp-dir "dest")
cps (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})]
(t/is (= [cp-1]
(->> (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})
(map #(select-keys % #{::cp/cp-format :tx})))))
(cp/download-checkpoint store (first cps) dest-dir)
(t/is (= "Hello world"
(slurp (io/file dest-dir "hello.txt"))))))
(t/testing "second checkpoint"
(spit (io/file src-dir "ivan.txt") "<NAME> <NAME>!")
(t/is (= cp-2
(-> (cp/upload-checkpoint store src-dir cp-2)
(select-keys #{::cp/cp-format :tx}))))
(t/is (empty? (cp/available-checkpoints store {::cp/cp-format ::bar-cp-format})))
(let [dest-dir (io/file cp-dir "dest-2")
cps (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})]
(t/is (= [cp-2 cp-1]
(->> (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})
(map #(select-keys % #{::cp/cp-format :tx})))))
(cp/download-checkpoint store (first cps) dest-dir)
(t/is (= "Hello world"
(slurp (io/file dest-dir "hello.txt"))))
(t/is (= "Hey <NAME>!"
(slurp (io/file dest-dir "ivan.txt"))))))))))
| true | (ns avisi-apps.crux.google-cloud-storage.checkpoint-test
(:require [clojure.test :as t]
[avisi-apps.crux.google-cloud-storage.checkpoint :as gcs-check]
[crux.io :as cio]
[crux.tx :as tx]
[crux.checkpoint :as cp]
[crux.system :as sys]
[clojure.java.io :as io])
(:import [com.google.cloud.storage.contrib.nio.testing LocalStorageHelper]
[java.io File]
[java.nio.file Files]
[java.nio.file.attribute FileAttribute]))
(defn with-tmp-dir* [prefix f]
(let [dir (.toFile (Files/createTempDirectory prefix (make-array FileAttribute 0)))]
(try (f dir) (finally (cio/delete-dir dir)))))
(defmacro with-tmp-dir
[prefix [dir-binding] & body]
`(with-tmp-dir*
~prefix
(fn
[~(->
dir-binding
(with-meta {:type File}))]
~@body)))
(t/deftest test-checkpoint-store
(with-open [sys (-> (sys/prep-system {:store {:crux/module `gcs-check/->cp-store
:storage-options (fn [_] (LocalStorageHelper/getOptions))
:bucket "test"}})
(sys/start-system))]
(with-tmp-dir "gcs-cp" [cp-dir]
(let [{:keys [store]} sys
src-dir (doto (io/file cp-dir "src")
(.mkdirs))
cp-1 {::cp/cp-format ::foo-cp-format
:tx {::tx/tx-id 1}}
cp-2 {::cp/cp-format ::foo-cp-format
:tx {::tx/tx-id 2}}]
(t/testing "first checkpoint"
(spit (io/file src-dir "hello.txt") "Hello world")
(t/is (= cp-1
(-> (cp/upload-checkpoint store src-dir cp-1)
(select-keys #{::cp/cp-format :tx}))))
(t/is (empty? (cp/available-checkpoints store {::cp/cp-format ::bar-cp-format})))
(let [dest-dir (io/file cp-dir "dest")
cps (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})]
(t/is (= [cp-1]
(->> (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})
(map #(select-keys % #{::cp/cp-format :tx})))))
(cp/download-checkpoint store (first cps) dest-dir)
(t/is (= "Hello world"
(slurp (io/file dest-dir "hello.txt"))))))
(t/testing "second checkpoint"
(spit (io/file src-dir "ivan.txt") "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI!")
(t/is (= cp-2
(-> (cp/upload-checkpoint store src-dir cp-2)
(select-keys #{::cp/cp-format :tx}))))
(t/is (empty? (cp/available-checkpoints store {::cp/cp-format ::bar-cp-format})))
(let [dest-dir (io/file cp-dir "dest-2")
cps (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})]
(t/is (= [cp-2 cp-1]
(->> (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})
(map #(select-keys % #{::cp/cp-format :tx})))))
(cp/download-checkpoint store (first cps) dest-dir)
(t/is (= "Hello world"
(slurp (io/file dest-dir "hello.txt"))))
(t/is (= "Hey PI:NAME:<NAME>END_PI!"
(slurp (io/file dest-dir "ivan.txt"))))))))))
|
[
{
"context": "License\"\n :year 2021\n :key \"mit\"}\n\n :min-lein-version \"2.7.1\"\n\n :dependencies [",
"end": 271,
"score": 0.9180415868759155,
"start": 268,
"tag": "KEY",
"value": "mit"
}
] | project.clj | narracion/narracion | 0 | (defproject narracion "0.1.0-SNAPSHOT"
:description "FIXME: write this!"
:url "http://example.com/FIXME"
:license {:name "MIT"
:url "https://choosealicense.com/licenses/mit"
:comment "MIT License"
:year 2021
:key "mit"}
:min-lein-version "2.7.1"
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/clojurescript "1.10.773"]
[org.clojure/tools.reader "1.3.3"]
[reagent "1.0.0" ]
[kee-frame "1.1.2"]
[re-frame "1.2.0"]
[io.github.narracion/reagent-hotkeys "0.1.0-SNAPSHOT"]]
:source-paths ["src"]
:aliases {"fig" ["trampoline" "run" "-m" "figwheel.main"]
"fig:build" ["trampoline" "run" "-m" "figwheel.main" "-b" "dev" "-r"]
"fig:min" ["run" "-m" "figwheel.main" "-O" "advanced" "-bo" "dev"]
"fig:test" ["run" "-m" "figwheel.main" "-co" "test.cljs.edn" "-m" "narracion.test-runner"]}
:profiles {:dev {:dependencies [[com.bhauman/figwheel-main "0.2.12"]
[com.bhauman/rebel-readline-cljs "0.1.4"]
[org.clojure/java.classpath "0.3.0"]
[com.google.code.findbugs/jsr305 "3.0.2"]
[args4j "2.33"]
[ring "1.8.1"]
[commons-io "2.6"]
[commons-fileupload "1.4"]
[ring/ring-codec "1.1.2"]
[ns-tracker "0.4.0"]]
:resource-paths ["target"]
;; need to add the compiled assets to the :clean-targets
:clean-targets ^{:protect false} ["target"]}}
:pedantic? :abort)
| 18697 | (defproject narracion "0.1.0-SNAPSHOT"
:description "FIXME: write this!"
:url "http://example.com/FIXME"
:license {:name "MIT"
:url "https://choosealicense.com/licenses/mit"
:comment "MIT License"
:year 2021
:key "<KEY>"}
:min-lein-version "2.7.1"
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/clojurescript "1.10.773"]
[org.clojure/tools.reader "1.3.3"]
[reagent "1.0.0" ]
[kee-frame "1.1.2"]
[re-frame "1.2.0"]
[io.github.narracion/reagent-hotkeys "0.1.0-SNAPSHOT"]]
:source-paths ["src"]
:aliases {"fig" ["trampoline" "run" "-m" "figwheel.main"]
"fig:build" ["trampoline" "run" "-m" "figwheel.main" "-b" "dev" "-r"]
"fig:min" ["run" "-m" "figwheel.main" "-O" "advanced" "-bo" "dev"]
"fig:test" ["run" "-m" "figwheel.main" "-co" "test.cljs.edn" "-m" "narracion.test-runner"]}
:profiles {:dev {:dependencies [[com.bhauman/figwheel-main "0.2.12"]
[com.bhauman/rebel-readline-cljs "0.1.4"]
[org.clojure/java.classpath "0.3.0"]
[com.google.code.findbugs/jsr305 "3.0.2"]
[args4j "2.33"]
[ring "1.8.1"]
[commons-io "2.6"]
[commons-fileupload "1.4"]
[ring/ring-codec "1.1.2"]
[ns-tracker "0.4.0"]]
:resource-paths ["target"]
;; need to add the compiled assets to the :clean-targets
:clean-targets ^{:protect false} ["target"]}}
:pedantic? :abort)
| true | (defproject narracion "0.1.0-SNAPSHOT"
:description "FIXME: write this!"
:url "http://example.com/FIXME"
:license {:name "MIT"
:url "https://choosealicense.com/licenses/mit"
:comment "MIT License"
:year 2021
:key "PI:KEY:<KEY>END_PI"}
:min-lein-version "2.7.1"
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/clojurescript "1.10.773"]
[org.clojure/tools.reader "1.3.3"]
[reagent "1.0.0" ]
[kee-frame "1.1.2"]
[re-frame "1.2.0"]
[io.github.narracion/reagent-hotkeys "0.1.0-SNAPSHOT"]]
:source-paths ["src"]
:aliases {"fig" ["trampoline" "run" "-m" "figwheel.main"]
"fig:build" ["trampoline" "run" "-m" "figwheel.main" "-b" "dev" "-r"]
"fig:min" ["run" "-m" "figwheel.main" "-O" "advanced" "-bo" "dev"]
"fig:test" ["run" "-m" "figwheel.main" "-co" "test.cljs.edn" "-m" "narracion.test-runner"]}
:profiles {:dev {:dependencies [[com.bhauman/figwheel-main "0.2.12"]
[com.bhauman/rebel-readline-cljs "0.1.4"]
[org.clojure/java.classpath "0.3.0"]
[com.google.code.findbugs/jsr305 "3.0.2"]
[args4j "2.33"]
[ring "1.8.1"]
[commons-io "2.6"]
[commons-fileupload "1.4"]
[ring/ring-codec "1.1.2"]
[ns-tracker "0.4.0"]]
:resource-paths ["target"]
;; need to add the compiled assets to the :clean-targets
:clean-targets ^{:protect false} ["target"]}}
:pedantic? :abort)
|
[
{
"context": " {:doc {:description \"descr\" :name \"name\"\n :params {:id {:type \"s",
"end": 3965,
"score": 0.7238467335700989,
"start": 3961,
"tag": "NAME",
"value": "name"
}
] | test/octia/core_test.clj | smallrivers/octia | 1 | (ns octia.core-test
(:require [ring.mock.request :as request]
[octia.endpoint :as endpoint]
[octia.wrapper :as wrapper])
(:use clojure.test
octia.core
midje.sweet))
(unfinished wrapper-called wrapper2-called group-wrapper-called)
(defn group-wrapper
[handler]
(fn [req]
(group-wrapper-called)
(handler req)))
(defn wrapper
[handler]
(fn [req]
(wrapper-called)
(handler req)))
(defn wrapper2
[handler]
(fn [req]
(wrapper2-called)
(handler req)))
(unfinished handle-update handle-get ping handle-get-post)
(def success "success")
(deftest simple-route
(let [r (endpoint :put
"/:id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-update id))]
(fact
(-> (request/request :put "/123") r :body)
=> success
(provided (handle-update "123") => success)
(provided (wrapper-called) => nil))))
(deftest method-route-put
(let [r (PUT "/:id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-update id))]
(fact
(-> (request/request :put "/123") r :body)
=> success
(provided (handle-update "123") => success)
(provided (wrapper-called) => nil))))
(deftest method-route-get
(let [r (GET "/:id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-get id))]
(fact
(-> (request/request :get "/123") r :body)
=> success
(provided (handle-get "123") => success)
(provided (wrapper-called) => nil))))
(deftest wrapper-test
(let [r (GET "/:id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-get id))]
(fact
(-> (request/request :get "/123") r :body)
=> success
(provided (handle-get "123") => success)
(provided (wrapper-called) => anything))))
(defn concat-wrapper
[x]
(fn [handler]
(fn [req]
(handler (update-in req [:params :x] #(concat (or % []) [x]))))))
(deftest wrapper-order-test
(let [r (group "/x" {:wrappers [(concat-wrapper 1) (concat-wrapper 2)]}
(GET "/:id" {:wrappers [(concat-wrapper 3) (concat-wrapper 4)]}
{{:keys [x] :as user} :params}
(apply str x)))]
(fact (-> (request/request :get "/x/abcd") r :body) => "1234")))
(deftest group-test
(let [r (group "" {}
(group "~api/users/"
{:doc "A group for users routes"
:wrappers [group-wrapper]}
(GET ":id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-get id))
(PUT ":id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-update id)))
(group "~api/posts/"
{:doc "A group for posts routes"
:wrappers [group-wrapper]}
(GET ":id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper2]}
{{:keys [id] :as post} :params}
(handle-get-post id)))
(GET "~api/ping"
{:doc {:description "descr" :name "name"}}
{:as request}
(ping)))]
(fact
(-> (request/request :get "~api/users/123") r :body)
=> success
(provided (handle-get "123") => success)
(provided (wrapper-called) => anything)
(provided (group-wrapper-called) => anything))
(fact
(-> (request/request :put "~api/users/123") r :body)
=> success
(provided (handle-update "123") => success)
(provided (wrapper-called) => anything)
(provided (group-wrapper-called) => anything))
(fact
(-> (request/request :get "~api/posts/123") r :body)
=> success
(provided (handle-get-post "123") => success)
(provided (wrapper2-called) => anything)
(provided (group-wrapper-called) => anything))
(fact
(-> (request/request :get "~api/ping") r :body)
=> success
(provided (ping) => success))))
(deftest multi-lvl-groups-test
(let [r (group "~api/" {:wrappers [group-wrapper]}
(group "users/"
{:doc "A group for users routes"
:wrappers [wrapper]}
(GET ":id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper2]}
{{:keys [id]} :params}
(handle-get id))))]
(fact
(-> (request/request :get "~api/users/123") r :body)
=> success
(provided (handle-get "123") => success)
(provided (wrapper-called) => anything)
(provided (wrapper2-called) => anything)
(provided (group-wrapper-called) => anything))))
(deftest re-test
(let [r (GET ["/:id" :id #"[\w]*"]
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-get id))]
(fact
(-> (request/request :get "/") r :body)
=> success
(provided (handle-get "") => success)
(provided (wrapper-called) => nil))))
(unfinished inc-req-count)
(deftest wrapper-factory-test
"Simple wrapper factory which produces wrappers
which use endpoint information (path & method) to collect stats"
(let [stat-wrapper (reify wrapper/WrapperFactory
(build [this endpoint]
(fn [handler]
(fn [req]
(inc-req-count (endpoint/method endpoint) (endpoint/path endpoint))
(handler req)))))
r (GET "/:id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [stat-wrapper]}
{{:keys [id] :as user} :params}
(handle-get id))]
(fact
(-> (request/request :get "/123") r :body)
=> success
(provided (handle-get "123") => success)
(provided (inc-req-count :get "/:id") => anything))))
| 117735 | (ns octia.core-test
(:require [ring.mock.request :as request]
[octia.endpoint :as endpoint]
[octia.wrapper :as wrapper])
(:use clojure.test
octia.core
midje.sweet))
(unfinished wrapper-called wrapper2-called group-wrapper-called)
(defn group-wrapper
[handler]
(fn [req]
(group-wrapper-called)
(handler req)))
(defn wrapper
[handler]
(fn [req]
(wrapper-called)
(handler req)))
(defn wrapper2
[handler]
(fn [req]
(wrapper2-called)
(handler req)))
(unfinished handle-update handle-get ping handle-get-post)
(def success "success")
(deftest simple-route
(let [r (endpoint :put
"/:id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-update id))]
(fact
(-> (request/request :put "/123") r :body)
=> success
(provided (handle-update "123") => success)
(provided (wrapper-called) => nil))))
(deftest method-route-put
(let [r (PUT "/:id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-update id))]
(fact
(-> (request/request :put "/123") r :body)
=> success
(provided (handle-update "123") => success)
(provided (wrapper-called) => nil))))
(deftest method-route-get
(let [r (GET "/:id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-get id))]
(fact
(-> (request/request :get "/123") r :body)
=> success
(provided (handle-get "123") => success)
(provided (wrapper-called) => nil))))
(deftest wrapper-test
(let [r (GET "/:id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-get id))]
(fact
(-> (request/request :get "/123") r :body)
=> success
(provided (handle-get "123") => success)
(provided (wrapper-called) => anything))))
(defn concat-wrapper
[x]
(fn [handler]
(fn [req]
(handler (update-in req [:params :x] #(concat (or % []) [x]))))))
(deftest wrapper-order-test
(let [r (group "/x" {:wrappers [(concat-wrapper 1) (concat-wrapper 2)]}
(GET "/:id" {:wrappers [(concat-wrapper 3) (concat-wrapper 4)]}
{{:keys [x] :as user} :params}
(apply str x)))]
(fact (-> (request/request :get "/x/abcd") r :body) => "1234")))
(deftest group-test
(let [r (group "" {}
(group "~api/users/"
{:doc "A group for users routes"
:wrappers [group-wrapper]}
(GET ":id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-get id))
(PUT ":id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-update id)))
(group "~api/posts/"
{:doc "A group for posts routes"
:wrappers [group-wrapper]}
(GET ":id"
{:doc {:description "descr" :name "<NAME>"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper2]}
{{:keys [id] :as post} :params}
(handle-get-post id)))
(GET "~api/ping"
{:doc {:description "descr" :name "name"}}
{:as request}
(ping)))]
(fact
(-> (request/request :get "~api/users/123") r :body)
=> success
(provided (handle-get "123") => success)
(provided (wrapper-called) => anything)
(provided (group-wrapper-called) => anything))
(fact
(-> (request/request :put "~api/users/123") r :body)
=> success
(provided (handle-update "123") => success)
(provided (wrapper-called) => anything)
(provided (group-wrapper-called) => anything))
(fact
(-> (request/request :get "~api/posts/123") r :body)
=> success
(provided (handle-get-post "123") => success)
(provided (wrapper2-called) => anything)
(provided (group-wrapper-called) => anything))
(fact
(-> (request/request :get "~api/ping") r :body)
=> success
(provided (ping) => success))))
(deftest multi-lvl-groups-test
(let [r (group "~api/" {:wrappers [group-wrapper]}
(group "users/"
{:doc "A group for users routes"
:wrappers [wrapper]}
(GET ":id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper2]}
{{:keys [id]} :params}
(handle-get id))))]
(fact
(-> (request/request :get "~api/users/123") r :body)
=> success
(provided (handle-get "123") => success)
(provided (wrapper-called) => anything)
(provided (wrapper2-called) => anything)
(provided (group-wrapper-called) => anything))))
(deftest re-test
(let [r (GET ["/:id" :id #"[\w]*"]
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-get id))]
(fact
(-> (request/request :get "/") r :body)
=> success
(provided (handle-get "") => success)
(provided (wrapper-called) => nil))))
(unfinished inc-req-count)
(deftest wrapper-factory-test
"Simple wrapper factory which produces wrappers
which use endpoint information (path & method) to collect stats"
(let [stat-wrapper (reify wrapper/WrapperFactory
(build [this endpoint]
(fn [handler]
(fn [req]
(inc-req-count (endpoint/method endpoint) (endpoint/path endpoint))
(handler req)))))
r (GET "/:id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [stat-wrapper]}
{{:keys [id] :as user} :params}
(handle-get id))]
(fact
(-> (request/request :get "/123") r :body)
=> success
(provided (handle-get "123") => success)
(provided (inc-req-count :get "/:id") => anything))))
| true | (ns octia.core-test
(:require [ring.mock.request :as request]
[octia.endpoint :as endpoint]
[octia.wrapper :as wrapper])
(:use clojure.test
octia.core
midje.sweet))
(unfinished wrapper-called wrapper2-called group-wrapper-called)
(defn group-wrapper
[handler]
(fn [req]
(group-wrapper-called)
(handler req)))
(defn wrapper
[handler]
(fn [req]
(wrapper-called)
(handler req)))
(defn wrapper2
[handler]
(fn [req]
(wrapper2-called)
(handler req)))
(unfinished handle-update handle-get ping handle-get-post)
(def success "success")
(deftest simple-route
(let [r (endpoint :put
"/:id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-update id))]
(fact
(-> (request/request :put "/123") r :body)
=> success
(provided (handle-update "123") => success)
(provided (wrapper-called) => nil))))
(deftest method-route-put
(let [r (PUT "/:id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-update id))]
(fact
(-> (request/request :put "/123") r :body)
=> success
(provided (handle-update "123") => success)
(provided (wrapper-called) => nil))))
(deftest method-route-get
(let [r (GET "/:id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-get id))]
(fact
(-> (request/request :get "/123") r :body)
=> success
(provided (handle-get "123") => success)
(provided (wrapper-called) => nil))))
(deftest wrapper-test
(let [r (GET "/:id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-get id))]
(fact
(-> (request/request :get "/123") r :body)
=> success
(provided (handle-get "123") => success)
(provided (wrapper-called) => anything))))
(defn concat-wrapper
[x]
(fn [handler]
(fn [req]
(handler (update-in req [:params :x] #(concat (or % []) [x]))))))
(deftest wrapper-order-test
(let [r (group "/x" {:wrappers [(concat-wrapper 1) (concat-wrapper 2)]}
(GET "/:id" {:wrappers [(concat-wrapper 3) (concat-wrapper 4)]}
{{:keys [x] :as user} :params}
(apply str x)))]
(fact (-> (request/request :get "/x/abcd") r :body) => "1234")))
(deftest group-test
(let [r (group "" {}
(group "~api/users/"
{:doc "A group for users routes"
:wrappers [group-wrapper]}
(GET ":id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-get id))
(PUT ":id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-update id)))
(group "~api/posts/"
{:doc "A group for posts routes"
:wrappers [group-wrapper]}
(GET ":id"
{:doc {:description "descr" :name "PI:NAME:<NAME>END_PI"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper2]}
{{:keys [id] :as post} :params}
(handle-get-post id)))
(GET "~api/ping"
{:doc {:description "descr" :name "name"}}
{:as request}
(ping)))]
(fact
(-> (request/request :get "~api/users/123") r :body)
=> success
(provided (handle-get "123") => success)
(provided (wrapper-called) => anything)
(provided (group-wrapper-called) => anything))
(fact
(-> (request/request :put "~api/users/123") r :body)
=> success
(provided (handle-update "123") => success)
(provided (wrapper-called) => anything)
(provided (group-wrapper-called) => anything))
(fact
(-> (request/request :get "~api/posts/123") r :body)
=> success
(provided (handle-get-post "123") => success)
(provided (wrapper2-called) => anything)
(provided (group-wrapper-called) => anything))
(fact
(-> (request/request :get "~api/ping") r :body)
=> success
(provided (ping) => success))))
(deftest multi-lvl-groups-test
(let [r (group "~api/" {:wrappers [group-wrapper]}
(group "users/"
{:doc "A group for users routes"
:wrappers [wrapper]}
(GET ":id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper2]}
{{:keys [id]} :params}
(handle-get id))))]
(fact
(-> (request/request :get "~api/users/123") r :body)
=> success
(provided (handle-get "123") => success)
(provided (wrapper-called) => anything)
(provided (wrapper2-called) => anything)
(provided (group-wrapper-called) => anything))))
(deftest re-test
(let [r (GET ["/:id" :id #"[\w]*"]
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [wrapper]}
{{:keys [id] :as user} :params}
(handle-get id))]
(fact
(-> (request/request :get "/") r :body)
=> success
(provided (handle-get "") => success)
(provided (wrapper-called) => nil))))
(unfinished inc-req-count)
(deftest wrapper-factory-test
"Simple wrapper factory which produces wrappers
which use endpoint information (path & method) to collect stats"
(let [stat-wrapper (reify wrapper/WrapperFactory
(build [this endpoint]
(fn [handler]
(fn [req]
(inc-req-count (endpoint/method endpoint) (endpoint/path endpoint))
(handler req)))))
r (GET "/:id"
{:doc {:description "descr" :name "name"
:params {:id {:type "string" :description "id"}}}
:wrappers [stat-wrapper]}
{{:keys [id] :as user} :params}
(handle-get id))]
(fact
(-> (request/request :get "/123") r :body)
=> success
(provided (handle-get "123") => success)
(provided (inc-req-count :get "/:id") => anything))))
|
[
{
"context": "\\\"\n :authentication {:username \\\"zcaudate\\\"\n :password \\\"",
"end": 5722,
"score": 0.999442458152771,
"start": 5714,
"tag": "USERNAME",
"value": "zcaudate"
},
{
"context": "\\\"\n :password \\\"hello\\\"}}})\"\n {:added \"1.2\"}\n ([coord {:keys [artifac",
"end": 5777,
"score": 0.9986346960067749,
"start": 5772,
"tag": "PASSWORD",
"value": "hello"
}
] | src/lucid/aether.clj | willcohen/lucidity | 3 | (ns lucid.aether
(:require [hara.namespace.import :as ns]
[lucid.aether
[artifact :as artifact]
[base :as base]
[request :as request]
[result :as result]]
[hara.io.classpath :as classpath])
(:import (org.eclipse.aether.transfer TransferListener)
(org.eclipse.aether.util.repository AuthenticationBuilder)
(org.eclipse.aether.repository RemoteRepository$Builder)))
(ns/import
lucid.aether.base
[aether])
(defn resolve-hierarchy
" shows the dependency hierachy for all packages
(resolve-hierarchy '[midje \"1.6.3\"])
=> '{[midje/midje \"1.6.3\"]
[{[ordered/ordered \"1.2.0\"] []}
{[org.clojure/math.combinatorics \"0.0.7\"] []}
{[org.clojure/core.unify \"0.5.2\"] []}
{[utilize/utilize \"0.2.3\"]
[{[org.clojure/tools.macro \"0.1.1\"] []}
{[joda-time/joda-time \"2.0\"] []}
{[ordered/ordered \"1.0.0\"] []}]}
{[colorize/colorize \"0.1.1\"] []}
{[org.clojure/tools.macro \"0.1.5\"] []}
{[dynapath/dynapath \"0.2.0\"] []}
{[swiss-arrows/swiss-arrows \"1.0.0\"] []}
{[org.clojure/tools.namespace \"0.2.4\"] []}
{[slingshot/slingshot \"0.10.3\"] []}
{[commons-codec/commons-codec \"1.9\"] []}
{[gui-diff/gui-diff \"0.5.0\"]
[{[org.clojars.trptcolin/sjacket \"0.1.3\"]
[{[net.cgrand/regex \"1.1.0\"] []}
{[net.cgrand/parsley \"0.9.1\"]
[{[net.cgrand/regex \"1.1.0\"] []}]}]}
{[ordered/ordered \"1.2.0\"] []}]}
{[clj-time/clj-time \"0.6.0\"]
[{[joda-time/joda-time \"2.2\"] []}]}]}"
{:added "1.1"}
([coords]
(resolve-hierarchy (base/aether) coords))
([{:keys [system session repositories]} coords]
(let [request (request/dependency-request
{:root {:artifact coords}
:repositories repositories})]
(-> (.resolveDependencies system session request)
(result/summary)))))
(defn resolve-dependencies
"resolves maven dependencies for a set of coordinates
(resolve-dependencies '[prismatic/schema \"1.1.3\"])
=> '[[prismatic/schema \"1.1.3\"]]
(resolve-dependencies '[midje \"1.6.3\"])
=> '[[utilize/utilize \"0.2.3\"]
[swiss-arrows/swiss-arrows \"1.0.0\"]
[slingshot/slingshot \"0.10.3\"]
[org.clojure/tools.namespace \"0.2.4\"]
[org.clojure/tools.macro \"0.1.5\"]
[org.clojure/math.combinatorics \"0.0.7\"]
[org.clojure/core.unify \"0.5.2\"]
[org.clojars.trptcolin/sjacket \"0.1.3\"]
[ordered/ordered \"1.2.0\"]
[net.cgrand/regex \"1.1.0\"]
[net.cgrand/parsley \"0.9.1\"]
[midje/midje \"1.6.3\"]
[joda-time/joda-time \"2.2\"]
[gui-diff/gui-diff \"0.5.0\"]
[dynapath/dynapath \"0.2.0\"]
[commons-codec/commons-codec \"1.9\"]
[colorize/colorize \"0.1.1\"]
[clj-time/clj-time \"0.6.0\"]]"
{:added "1.1"}
([coords]
(resolve-dependencies (base/aether) coords))
([aether coords]
(->> (resolve-hierarchy aether coords)
(request/flatten-values)
(sort)
(reverse)
(reduce (fn [out coord]
(if (-> out last first (= (first coord)))
out
(conj out coord)))
[]))))
(defn populate-artifact
"allows coordinate to fill rest of values
(populate-artifact '[midje \"1.6.3\"]
{:artifacts [{:extension \"pom\"
:file \"midje.pom\"}
{:extension \"jar\"
:file \"midje.jar\"}]})
=> {:artifacts [{:extension \"pom\",
:file \"midje.pom\",
:artifact \"midje\",
:group \"midje\",
:version \"1.6.3\"}
{:extension \"jar\",
:file \"midje.jar\",
:artifact \"midje\",
:group \"midje\",
:version \"1.6.3\"}]}"
{:added "1.2"}
[coord opts]
(let [root (-> (classpath/artifact coord)
(select-keys [:artifact :group :version]))]
opts (update-in opts [:artifacts]
(fn [arr] (mapv #(merge % root) arr)))))
(defn install-artifact
"installs artifacts to the given coordinate
(install-artifact
'[im.chit/hara.io.classpath \"2.4.8\"]
{:artifacts [{:file \"hara_io_classpath-2.4.8.jar\"
:extension \"jar\"}
{:file \"hara_io_classpath-2.4.8.pom\"
:extension \"pom\"}]})"
{:added "1.2"}
([coord {:keys [artifacts] :as opts}]
(install-artifact (base/aether) coord opts))
([{:keys [system session]} coord {:keys [artifacts] :as opts}]
(let [opts (populate-artifact coord opts)
request (request/install-request opts)]
(-> (.install system session request)
(result/summary)))))
(defn deploy-artifact
"deploys artifacts to the given coordinate
(deploy-artifact
'[im.chit/hara.io.classpath \"2.4.8\"]
{:artifacts [{:file \"hara_io_classpath-2.4.8.jar\"
:extension \"jar\"}
{:file \"hara_io_classpath-2.4.8.pom\"
:extension \"pom\"}
{:file \"hara_io_classpath-2.4.8.pom.asc\"
:extension \"pom.asc\"}
{:file \"hara_io_classpath-2.4.8.jar.asc\"
:extension \"jar.asc\"}]
:repository {:id \"clojars\"
:url \"https://clojars.org/repo/\"
:authentication {:username \"zcaudate\"
:password \"hello\"}}})"
{:added "1.2"}
([coord {:keys [artifacts repository] :as opts}]
(deploy-artifact (base/aether) coord opts))
([{:keys [system session]} coord {:keys [artifacts repository] :as opts}]
(let [opts (populate-artifact coord opts)
request (request/deploy-request opts)]
(.deploy system session request))))
| 106565 | (ns lucid.aether
(:require [hara.namespace.import :as ns]
[lucid.aether
[artifact :as artifact]
[base :as base]
[request :as request]
[result :as result]]
[hara.io.classpath :as classpath])
(:import (org.eclipse.aether.transfer TransferListener)
(org.eclipse.aether.util.repository AuthenticationBuilder)
(org.eclipse.aether.repository RemoteRepository$Builder)))
(ns/import
lucid.aether.base
[aether])
(defn resolve-hierarchy
" shows the dependency hierachy for all packages
(resolve-hierarchy '[midje \"1.6.3\"])
=> '{[midje/midje \"1.6.3\"]
[{[ordered/ordered \"1.2.0\"] []}
{[org.clojure/math.combinatorics \"0.0.7\"] []}
{[org.clojure/core.unify \"0.5.2\"] []}
{[utilize/utilize \"0.2.3\"]
[{[org.clojure/tools.macro \"0.1.1\"] []}
{[joda-time/joda-time \"2.0\"] []}
{[ordered/ordered \"1.0.0\"] []}]}
{[colorize/colorize \"0.1.1\"] []}
{[org.clojure/tools.macro \"0.1.5\"] []}
{[dynapath/dynapath \"0.2.0\"] []}
{[swiss-arrows/swiss-arrows \"1.0.0\"] []}
{[org.clojure/tools.namespace \"0.2.4\"] []}
{[slingshot/slingshot \"0.10.3\"] []}
{[commons-codec/commons-codec \"1.9\"] []}
{[gui-diff/gui-diff \"0.5.0\"]
[{[org.clojars.trptcolin/sjacket \"0.1.3\"]
[{[net.cgrand/regex \"1.1.0\"] []}
{[net.cgrand/parsley \"0.9.1\"]
[{[net.cgrand/regex \"1.1.0\"] []}]}]}
{[ordered/ordered \"1.2.0\"] []}]}
{[clj-time/clj-time \"0.6.0\"]
[{[joda-time/joda-time \"2.2\"] []}]}]}"
{:added "1.1"}
([coords]
(resolve-hierarchy (base/aether) coords))
([{:keys [system session repositories]} coords]
(let [request (request/dependency-request
{:root {:artifact coords}
:repositories repositories})]
(-> (.resolveDependencies system session request)
(result/summary)))))
(defn resolve-dependencies
"resolves maven dependencies for a set of coordinates
(resolve-dependencies '[prismatic/schema \"1.1.3\"])
=> '[[prismatic/schema \"1.1.3\"]]
(resolve-dependencies '[midje \"1.6.3\"])
=> '[[utilize/utilize \"0.2.3\"]
[swiss-arrows/swiss-arrows \"1.0.0\"]
[slingshot/slingshot \"0.10.3\"]
[org.clojure/tools.namespace \"0.2.4\"]
[org.clojure/tools.macro \"0.1.5\"]
[org.clojure/math.combinatorics \"0.0.7\"]
[org.clojure/core.unify \"0.5.2\"]
[org.clojars.trptcolin/sjacket \"0.1.3\"]
[ordered/ordered \"1.2.0\"]
[net.cgrand/regex \"1.1.0\"]
[net.cgrand/parsley \"0.9.1\"]
[midje/midje \"1.6.3\"]
[joda-time/joda-time \"2.2\"]
[gui-diff/gui-diff \"0.5.0\"]
[dynapath/dynapath \"0.2.0\"]
[commons-codec/commons-codec \"1.9\"]
[colorize/colorize \"0.1.1\"]
[clj-time/clj-time \"0.6.0\"]]"
{:added "1.1"}
([coords]
(resolve-dependencies (base/aether) coords))
([aether coords]
(->> (resolve-hierarchy aether coords)
(request/flatten-values)
(sort)
(reverse)
(reduce (fn [out coord]
(if (-> out last first (= (first coord)))
out
(conj out coord)))
[]))))
(defn populate-artifact
"allows coordinate to fill rest of values
(populate-artifact '[midje \"1.6.3\"]
{:artifacts [{:extension \"pom\"
:file \"midje.pom\"}
{:extension \"jar\"
:file \"midje.jar\"}]})
=> {:artifacts [{:extension \"pom\",
:file \"midje.pom\",
:artifact \"midje\",
:group \"midje\",
:version \"1.6.3\"}
{:extension \"jar\",
:file \"midje.jar\",
:artifact \"midje\",
:group \"midje\",
:version \"1.6.3\"}]}"
{:added "1.2"}
[coord opts]
(let [root (-> (classpath/artifact coord)
(select-keys [:artifact :group :version]))]
opts (update-in opts [:artifacts]
(fn [arr] (mapv #(merge % root) arr)))))
(defn install-artifact
"installs artifacts to the given coordinate
(install-artifact
'[im.chit/hara.io.classpath \"2.4.8\"]
{:artifacts [{:file \"hara_io_classpath-2.4.8.jar\"
:extension \"jar\"}
{:file \"hara_io_classpath-2.4.8.pom\"
:extension \"pom\"}]})"
{:added "1.2"}
([coord {:keys [artifacts] :as opts}]
(install-artifact (base/aether) coord opts))
([{:keys [system session]} coord {:keys [artifacts] :as opts}]
(let [opts (populate-artifact coord opts)
request (request/install-request opts)]
(-> (.install system session request)
(result/summary)))))
(defn deploy-artifact
"deploys artifacts to the given coordinate
(deploy-artifact
'[im.chit/hara.io.classpath \"2.4.8\"]
{:artifacts [{:file \"hara_io_classpath-2.4.8.jar\"
:extension \"jar\"}
{:file \"hara_io_classpath-2.4.8.pom\"
:extension \"pom\"}
{:file \"hara_io_classpath-2.4.8.pom.asc\"
:extension \"pom.asc\"}
{:file \"hara_io_classpath-2.4.8.jar.asc\"
:extension \"jar.asc\"}]
:repository {:id \"clojars\"
:url \"https://clojars.org/repo/\"
:authentication {:username \"zcaudate\"
:password \"<PASSWORD>\"}}})"
{:added "1.2"}
([coord {:keys [artifacts repository] :as opts}]
(deploy-artifact (base/aether) coord opts))
([{:keys [system session]} coord {:keys [artifacts repository] :as opts}]
(let [opts (populate-artifact coord opts)
request (request/deploy-request opts)]
(.deploy system session request))))
| true | (ns lucid.aether
(:require [hara.namespace.import :as ns]
[lucid.aether
[artifact :as artifact]
[base :as base]
[request :as request]
[result :as result]]
[hara.io.classpath :as classpath])
(:import (org.eclipse.aether.transfer TransferListener)
(org.eclipse.aether.util.repository AuthenticationBuilder)
(org.eclipse.aether.repository RemoteRepository$Builder)))
(ns/import
lucid.aether.base
[aether])
(defn resolve-hierarchy
" shows the dependency hierachy for all packages
(resolve-hierarchy '[midje \"1.6.3\"])
=> '{[midje/midje \"1.6.3\"]
[{[ordered/ordered \"1.2.0\"] []}
{[org.clojure/math.combinatorics \"0.0.7\"] []}
{[org.clojure/core.unify \"0.5.2\"] []}
{[utilize/utilize \"0.2.3\"]
[{[org.clojure/tools.macro \"0.1.1\"] []}
{[joda-time/joda-time \"2.0\"] []}
{[ordered/ordered \"1.0.0\"] []}]}
{[colorize/colorize \"0.1.1\"] []}
{[org.clojure/tools.macro \"0.1.5\"] []}
{[dynapath/dynapath \"0.2.0\"] []}
{[swiss-arrows/swiss-arrows \"1.0.0\"] []}
{[org.clojure/tools.namespace \"0.2.4\"] []}
{[slingshot/slingshot \"0.10.3\"] []}
{[commons-codec/commons-codec \"1.9\"] []}
{[gui-diff/gui-diff \"0.5.0\"]
[{[org.clojars.trptcolin/sjacket \"0.1.3\"]
[{[net.cgrand/regex \"1.1.0\"] []}
{[net.cgrand/parsley \"0.9.1\"]
[{[net.cgrand/regex \"1.1.0\"] []}]}]}
{[ordered/ordered \"1.2.0\"] []}]}
{[clj-time/clj-time \"0.6.0\"]
[{[joda-time/joda-time \"2.2\"] []}]}]}"
{:added "1.1"}
([coords]
(resolve-hierarchy (base/aether) coords))
([{:keys [system session repositories]} coords]
(let [request (request/dependency-request
{:root {:artifact coords}
:repositories repositories})]
(-> (.resolveDependencies system session request)
(result/summary)))))
(defn resolve-dependencies
"resolves maven dependencies for a set of coordinates
(resolve-dependencies '[prismatic/schema \"1.1.3\"])
=> '[[prismatic/schema \"1.1.3\"]]
(resolve-dependencies '[midje \"1.6.3\"])
=> '[[utilize/utilize \"0.2.3\"]
[swiss-arrows/swiss-arrows \"1.0.0\"]
[slingshot/slingshot \"0.10.3\"]
[org.clojure/tools.namespace \"0.2.4\"]
[org.clojure/tools.macro \"0.1.5\"]
[org.clojure/math.combinatorics \"0.0.7\"]
[org.clojure/core.unify \"0.5.2\"]
[org.clojars.trptcolin/sjacket \"0.1.3\"]
[ordered/ordered \"1.2.0\"]
[net.cgrand/regex \"1.1.0\"]
[net.cgrand/parsley \"0.9.1\"]
[midje/midje \"1.6.3\"]
[joda-time/joda-time \"2.2\"]
[gui-diff/gui-diff \"0.5.0\"]
[dynapath/dynapath \"0.2.0\"]
[commons-codec/commons-codec \"1.9\"]
[colorize/colorize \"0.1.1\"]
[clj-time/clj-time \"0.6.0\"]]"
{:added "1.1"}
([coords]
(resolve-dependencies (base/aether) coords))
([aether coords]
(->> (resolve-hierarchy aether coords)
(request/flatten-values)
(sort)
(reverse)
(reduce (fn [out coord]
(if (-> out last first (= (first coord)))
out
(conj out coord)))
[]))))
(defn populate-artifact
"allows coordinate to fill rest of values
(populate-artifact '[midje \"1.6.3\"]
{:artifacts [{:extension \"pom\"
:file \"midje.pom\"}
{:extension \"jar\"
:file \"midje.jar\"}]})
=> {:artifacts [{:extension \"pom\",
:file \"midje.pom\",
:artifact \"midje\",
:group \"midje\",
:version \"1.6.3\"}
{:extension \"jar\",
:file \"midje.jar\",
:artifact \"midje\",
:group \"midje\",
:version \"1.6.3\"}]}"
{:added "1.2"}
[coord opts]
(let [root (-> (classpath/artifact coord)
(select-keys [:artifact :group :version]))]
opts (update-in opts [:artifacts]
(fn [arr] (mapv #(merge % root) arr)))))
(defn install-artifact
"installs artifacts to the given coordinate
(install-artifact
'[im.chit/hara.io.classpath \"2.4.8\"]
{:artifacts [{:file \"hara_io_classpath-2.4.8.jar\"
:extension \"jar\"}
{:file \"hara_io_classpath-2.4.8.pom\"
:extension \"pom\"}]})"
{:added "1.2"}
([coord {:keys [artifacts] :as opts}]
(install-artifact (base/aether) coord opts))
([{:keys [system session]} coord {:keys [artifacts] :as opts}]
(let [opts (populate-artifact coord opts)
request (request/install-request opts)]
(-> (.install system session request)
(result/summary)))))
(defn deploy-artifact
"deploys artifacts to the given coordinate
(deploy-artifact
'[im.chit/hara.io.classpath \"2.4.8\"]
{:artifacts [{:file \"hara_io_classpath-2.4.8.jar\"
:extension \"jar\"}
{:file \"hara_io_classpath-2.4.8.pom\"
:extension \"pom\"}
{:file \"hara_io_classpath-2.4.8.pom.asc\"
:extension \"pom.asc\"}
{:file \"hara_io_classpath-2.4.8.jar.asc\"
:extension \"jar.asc\"}]
:repository {:id \"clojars\"
:url \"https://clojars.org/repo/\"
:authentication {:username \"zcaudate\"
:password \"PI:PASSWORD:<PASSWORD>END_PI\"}}})"
{:added "1.2"}
([coord {:keys [artifacts repository] :as opts}]
(deploy-artifact (base/aether) coord opts))
([{:keys [system session]} coord {:keys [artifacts repository] :as opts}]
(let [opts (populate-artifact coord opts)
request (request/deploy-request opts)]
(.deploy system session request))))
|
[
{
"context": "ets\" \"1877\"]\n ])\n\n(def friend-list\n [\n [\"1\" \"Jennifer\" \"AAPL\"]\n [\"2\" \"Jake\" \"GOOG\"]\n [\"3\" \"Mike\" \"A",
"end": 1478,
"score": 0.9997451305389404,
"start": 1470,
"tag": "NAME",
"value": "Jennifer"
},
{
"context": "iend-list\n [\n [\"1\" \"Jennifer\" \"AAPL\"]\n [\"2\" \"Jake\" \"GOOG\"]\n [\"3\" \"Mike\" \"AMZN\"]\n [\"4\" \"Sam\" \"MS",
"end": 1501,
"score": 0.9998029470443726,
"start": 1497,
"tag": "NAME",
"value": "Jake"
},
{
"context": "Jennifer\" \"AAPL\"]\n [\"2\" \"Jake\" \"GOOG\"]\n [\"3\" \"Mike\" \"AMZN\"]\n [\"4\" \"Sam\" \"MSFT\"]\n [\"5\" \"Tim\" \"VTS",
"end": 1524,
"score": 0.9997372627258301,
"start": 1520,
"tag": "NAME",
"value": "Mike"
},
{
"context": "r\" \"AAPL\"]\n [\"2\" \"Jake\" \"GOOG\"]\n [\"3\" \"Mike\" \"AMZN\"]\n [\"4\" \"Sam\" \"MSFT\"]\n [\"5\" \"Tim\" \"VTSMX\"]\n ",
"end": 1531,
"score": 0.6116049289703369,
"start": 1527,
"tag": "NAME",
"value": "AMZN"
},
{
"context": "2\" \"Jake\" \"GOOG\"]\n [\"3\" \"Mike\" \"AMZN\"]\n [\"4\" \"Sam\" \"MSFT\"]\n [\"5\" \"Tim\" \"VTSMX\"]\n [\"6\" \"Julie\" \"",
"end": 1546,
"score": 0.9998641014099121,
"start": 1543,
"tag": "NAME",
"value": "Sam"
},
{
"context": "\"3\" \"Mike\" \"AMZN\"]\n [\"4\" \"Sam\" \"MSFT\"]\n [\"5\" \"Tim\" \"VTSMX\"]\n [\"6\" \"Julie\" \"F\"]\n [\"7\" \"Harry\" \"S",
"end": 1568,
"score": 0.9998722076416016,
"start": 1565,
"tag": "NAME",
"value": "Tim"
},
{
"context": "\"4\" \"Sam\" \"MSFT\"]\n [\"5\" \"Tim\" \"VTSMX\"]\n [\"6\" \"Julie\" \"F\"]\n [\"7\" \"Harry\" \"SYMC\"]\n [\"8\" \"Jolene\" \"X",
"end": 1593,
"score": 0.9997958540916443,
"start": 1588,
"tag": "NAME",
"value": "Julie"
},
{
"context": "[\"5\" \"Tim\" \"VTSMX\"]\n [\"6\" \"Julie\" \"F\"]\n [\"7\" \"Harry\" \"SYMC\"]\n [\"8\" \"Jolene\" \"XOM\"]\n [\"9\" \"William",
"end": 1614,
"score": 0.999841570854187,
"start": 1609,
"tag": "NAME",
"value": "Harry"
},
{
"context": "\"6\" \"Julie\" \"F\"]\n [\"7\" \"Harry\" \"SYMC\"]\n [\"8\" \"Jolene\" \"XOM\"]\n [\"9\" \"William\" \"BLK\"]\n [\"10\" \"Elaina",
"end": 1639,
"score": 0.9997979998588562,
"start": 1633,
"tag": "NAME",
"value": "Jolene"
},
{
"context": " \"Harry\" \"SYMC\"]\n [\"8\" \"Jolene\" \"XOM\"]\n [\"9\" \"William\" \"BLK\"]\n [\"10\" \"Elaina\" \"BLK\"]\n [\"11\" \"Shu\" \"",
"end": 1664,
"score": 0.9997605681419373,
"start": 1657,
"tag": "NAME",
"value": "William"
},
{
"context": "Jolene\" \"XOM\"]\n [\"9\" \"William\" \"BLK\"]\n [\"10\" \"Elaina\" \"BLK\"]\n [\"11\" \"Shu\" \"CSCO\"]\n [\"12\" \"Irene\" \"",
"end": 1689,
"score": 0.9998065829277039,
"start": 1683,
"tag": "NAME",
"value": "Elaina"
},
{
"context": "illiam\" \"BLK\"]\n [\"10\" \"Elaina\" \"BLK\"]\n [\"11\" \"Shu\" \"CSCO\"]\n [\"12\" \"Irene\" \"FDX\"]\n [\"13\" \"Kelly\"",
"end": 1711,
"score": 0.9969117641448975,
"start": 1708,
"tag": "NAME",
"value": "Shu"
},
{
"context": " \"Elaina\" \"BLK\"]\n [\"11\" \"Shu\" \"CSCO\"]\n [\"12\" \"Irene\" \"FDX\"]\n [\"13\" \"Kelly\" \"FB\"]])\n\n(def chart-colo",
"end": 1736,
"score": 0.9997538924217224,
"start": 1731,
"tag": "NAME",
"value": "Irene"
},
{
"context": "\" \"Shu\" \"CSCO\"]\n [\"12\" \"Irene\" \"FDX\"]\n [\"13\" \"Kelly\" \"FB\"]])\n\n(def chart-colors\n [\"#A96186\" \"#A96162",
"end": 1760,
"score": 0.999764084815979,
"start": 1755,
"tag": "NAME",
"value": "Kelly"
},
{
"context": "\n \"authorization\" \"Bearer wj7fmf21w6lvu0l4u7vmdef1tqo0cykn\"}\n ",
"end": 6327,
"score": 0.9307097792625427,
"start": 6321,
"tag": "KEY",
"value": "Bearer"
},
{
"context": " \"authorization\" \"Bearer wj7fmf21w6lvu0l4u7vmdef1tqo0cykn\"}\n :format :json\n ",
"end": 6360,
"score": 0.9544239044189453,
"start": 6328,
"tag": "KEY",
"value": "wj7fmf21w6lvu0l4u7vmdef1tqo0cykn"
},
{
"context": " [:p#title \"Stockpedia\"]\n [:p#menu \"Welcome Johnson! \"\n [:button \"Logout\"]]]\n [body]\n [",
"end": 8868,
"score": 0.9730770587921143,
"start": 8861,
"tag": "NAME",
"value": "Johnson"
}
] | src/pennapps_xvi/core.cljs | kccqzy/pennapps-xvi | 0 | (ns pennapps-xvi.core
(:require
[clojure.core]
[reagent.core :as r]
[ajax.core :refer [GET POST]]))
(defn floor-factor [n f]
(* f (quot n f)))
(defn gen-dummy-stock-data
[len]
(let [rand-range 0.8
rand-range-half (/ rand-range 2)]
(take
len
(iterate (fn [{:strs [open high low close volume date]}]
{"open" close
"high" (* close (+ 1.0 (* (- (rand rand-range) rand-range-half) (- (rand rand-range) rand-range-half))))
"low" (* close (+ 1.0 (* (- (rand rand-range) rand-range-half) (- (rand rand-range) rand-range-half))))
"close" (* close (+ 1.001 (* (- (rand rand-range) rand-range-half) (- (rand rand-range) rand-range-half))))
"volume" (* volume (+ 1.0 (* (- (rand rand-range) rand-range-half) (- (rand rand-range) rand-range-half) (- (rand rand-range) rand-range-half))))
"date" (js/Date. (+ (.getTime date) 86400000))})
{"date" (js/Date. (floor-factor (js/Date.now) 86400000))
"open" 62.40
"high" 63.34
"low" 61.79
"close" 62.88
"volume" 37617413}))))
;; -------------------------
;; Views
(def dummy-portfolio-data
[
["U.S. Stocks" "1123"]
["U.S. Bonds" "2287"]
["Cryptocurrencies" "3419"]
["Energy" "4200"]
["International Stock" "877"]
["Emerging Markets" "1877"]
])
(def friend-list
[
["1" "Jennifer" "AAPL"]
["2" "Jake" "GOOG"]
["3" "Mike" "AMZN"]
["4" "Sam" "MSFT"]
["5" "Tim" "VTSMX"]
["6" "Julie" "F"]
["7" "Harry" "SYMC"]
["8" "Jolene" "XOM"]
["9" "William" "BLK"]
["10" "Elaina" "BLK"]
["11" "Shu" "CSCO"]
["12" "Irene" "FDX"]
["13" "Kelly" "FB"]])
(def chart-colors
["#A96186" "#A96162" "#A98461" "#A9A861" "#86A961" "#589857" "#4E876A" "#4E8786" "#4E6B87" "#4E4E87" "#6A4E87" "#8F5390"])
(defn overview []
(r/create-class
{:component-did-mount
(fn [this]
(set! js/window.d3 js/window.d3v3)
(js/c3.generate (clj->js {"bindto" "#portfolio-composition"
"color" {"pattern"
(clojure.core/shuffle chart-colors)}
"data" {"columns" dummy-portfolio-data
"type" "donut"}}))
)
:reagent-render
(fn [_] [:div
[:h2 "Overview"]
[:h3 "Your Investment Portfolio"]
[:div#portfolio-composition]
[:h3 "Friends\u2019 Picks"]
[:div#stock-picks
(map (fn [[id name pick]]
[:div.stock-pick {:key name}
[:div [:img {:src (str "img/profile/pic-" id ".jpg")}]]
[:div.name name]
[:div.pick pick]])
(take 5 (clojure.core/shuffle friend-list)))]
])}))
(defn investments []
[:h2 "Long-Term Investments"])
(defonce current-search (r/atom "AAPL"))
(defonce current-range (r/atom 60))
(defonce current-data (r/atom (gen-dummy-stock-data 60)))
(defn candlestick [raw-data range]
(let [r (js/Math.floor (* 1000000000 (rand)))
dorender
(fn [this]
(set! js/window.d3 js/window.d3v4)
(let [margin-top 20
margin-right 20
margin-bottom 30
margin-left 50
width (- 520 margin-left margin-right)
height (- 300 margin-top margin-bottom)
x (-> js/techan.scale (.financetime) (.range (clj->js [0 width])))
y (-> js/d3 (.scaleLinear) (.range (clj->js [height 0])))
candlestick (-> js/techan.plot (.candlestick) (.xScale x) (.yScale y))
xAxis (-> js/d3 (.axisBottom) (.scale x))
yAxis (-> js/d3 (.axisLeft) (.scale y))
svg (-> js/d3
(.select (str "div.candlestick.id" r))
(.html "")
(.append "svg")
(.attr "class" "candlestick")
(.attr "width" (+ width margin-left margin-right))
(.attr "height" (+ height margin-top margin-bottom))
(.append "g")
(.attr "transform" (str "translate(" margin-left "," margin-top ")")))
accessor (-> candlestick (.accessor))
data (-> (clj->js (take @range @raw-data)) (.sort (fn [a b] (js/d3.ascending (.d accessor a) (.d accessor b)))))
]
(-> svg (.append "g") (.attr "class" "candlestick"))
(-> svg (.append "g") (.attr "class" "x axis") (.attr "transform" (str "translate(0," height ")")))
(-> svg (.append "g") (.attr "class" "y axis") (.append "text") (.attr "transform" "rotate(-90)") (.attr "y" "6")
(.attr "dy" ".71em") (.style "text-anchor" "end") (.text "Price ($)"))
(.domain x (.map data (.-d (-> candlestick (.accessor)))))
(.domain y (.domain (js/techan.scale.plot.ohlc data (-> candlestick (.accessor)))))
(-> svg (.selectAll "g.candlestick") (.datum data) (.call candlestick))
(-> svg (.selectAll "g.x.axis") (.call xAxis))
(-> svg (.selectAll "g.y.axis") (.call yAxis))
))]
(r/create-class
{:component-did-mount dorender
:component-did-update dorender
:reagent-render
(fn [_]
[:div {:display "none"} (str @raw-data @range)]
[:div.candlestick {:class (str "id" r)}])})))
(defn trading []
[:div
[:h2 "Short-Term Trading"]
[:input {:type "text" :placeholder "Search for a stock symbol..." :class "ticksymbol"
:value @current-search :on-change #(swap! current-search (constantly (-> % .-target .-value)))}]
[:div
[:span "Days to Predict (max 60)"]
[:input {:type "range" :min "1" :max "60" :step "1"
:on-change #(swap! current-range (constantly (js/window.parseInt (-> % .-target .-value) 10)))
}]]
[:button {:on-click #(do
(swap! current-data (constantly (gen-dummy-stock-data 60)))
(POST "https://data.chastiser11.hasura-app.io/v1/query"
{:headers
{
"authorization" "Bearer wj7fmf21w6lvu0l4u7vmdef1tqo0cykn"}
:format :json
:response-format :json
:params
{"type" "select", "args" {"table" "stockTest", "columns" ["*"], "where" { "stocksymbol" @current-search }}}
:handler
(fn [response]
(let [today (js/Date. (floor-factor (js/Date.now) 86400000))
predictions (js->clj (js/window.JSON.parse (get-in response [0 "predictions"])))
predictions-t (apply mapv vector predictions)
transformed (map-indexed (fn [i [o h l c]]
{"open" o
"high" h
"low" l
"close" c
"date" (js/Date. (+ (.getTime today) (* i 86400000)))
}
) (take 60 predictions-t))]
(if-not (empty? transformed)
(swap! current-data (constantly transformed)))))}))} "Load Prediction"]
[candlestick current-data current-range]])
(defn analytics []
[:h2 "Analytics"])
(def tabmap
{"Overview" overview
"Long-Term Investments" investments
"Short-Term Trading" trading
"Analytics" analytics})
(def tabs
(keys tabmap))
(defonce current-tab (r/atom (or (-> js/window.localStorage (.getItem "current-tab")) "Overview")))
(defn body []
[:div {:id "body"}
[:div#sidebar
[:ul
(map (fn [t] [:li {:key t} [:a {:on-click #(do
(-> js/window.localStorage (.setItem "current-tab" t))
(swap! current-tab (fn [_] t)))
:class (if (= @current-tab t) "selected" "")} t]]) tabs)]]
[:div#main-content
[(get tabmap @current-tab "Overview")]]])
(defn home-page []
[:div#container
[:div#header
[:img#logo {:src "img/logo.png" :height 64 :width 65}]
[:p#title "Stockpedia"]
[:p#menu "Welcome Johnson! "
[:button "Logout"]]]
[body]
[:div#footer
[:p [:strong "Copyright (c) 2017 Stock Advisors and Company. All rights reserved."]]
[:p [:strong "Important Disclaimer: "] "Any past performance, projection, forecast or simulation of results is not necessarily indicative of the future or likely performance of any company or investment. The information provided does not take into account your specific investment objectives, financial situation or particular needs. Before you act on any information on this site, you should always seek independent financial, tax, and legal advice or make such independent investigations as you consider necessary or appropriate regarding the suitability of the investment product, taking into account your specific investment objectives, financial situation or particular needs."]]]
)
;; -------------------------
;; Initialize app
(defn mount-root []
(r/render [home-page] (.getElementById js/document "app")))
(defn init! []
(mount-root))
| 8404 | (ns pennapps-xvi.core
(:require
[clojure.core]
[reagent.core :as r]
[ajax.core :refer [GET POST]]))
(defn floor-factor [n f]
(* f (quot n f)))
(defn gen-dummy-stock-data
[len]
(let [rand-range 0.8
rand-range-half (/ rand-range 2)]
(take
len
(iterate (fn [{:strs [open high low close volume date]}]
{"open" close
"high" (* close (+ 1.0 (* (- (rand rand-range) rand-range-half) (- (rand rand-range) rand-range-half))))
"low" (* close (+ 1.0 (* (- (rand rand-range) rand-range-half) (- (rand rand-range) rand-range-half))))
"close" (* close (+ 1.001 (* (- (rand rand-range) rand-range-half) (- (rand rand-range) rand-range-half))))
"volume" (* volume (+ 1.0 (* (- (rand rand-range) rand-range-half) (- (rand rand-range) rand-range-half) (- (rand rand-range) rand-range-half))))
"date" (js/Date. (+ (.getTime date) 86400000))})
{"date" (js/Date. (floor-factor (js/Date.now) 86400000))
"open" 62.40
"high" 63.34
"low" 61.79
"close" 62.88
"volume" 37617413}))))
;; -------------------------
;; Views
(def dummy-portfolio-data
[
["U.S. Stocks" "1123"]
["U.S. Bonds" "2287"]
["Cryptocurrencies" "3419"]
["Energy" "4200"]
["International Stock" "877"]
["Emerging Markets" "1877"]
])
(def friend-list
[
["1" "<NAME>" "AAPL"]
["2" "<NAME>" "GOOG"]
["3" "<NAME>" "<NAME>"]
["4" "<NAME>" "MSFT"]
["5" "<NAME>" "VTSMX"]
["6" "<NAME>" "F"]
["7" "<NAME>" "SYMC"]
["8" "<NAME>" "XOM"]
["9" "<NAME>" "BLK"]
["10" "<NAME>" "BLK"]
["11" "<NAME>" "CSCO"]
["12" "<NAME>" "FDX"]
["13" "<NAME>" "FB"]])
(def chart-colors
["#A96186" "#A96162" "#A98461" "#A9A861" "#86A961" "#589857" "#4E876A" "#4E8786" "#4E6B87" "#4E4E87" "#6A4E87" "#8F5390"])
(defn overview []
(r/create-class
{:component-did-mount
(fn [this]
(set! js/window.d3 js/window.d3v3)
(js/c3.generate (clj->js {"bindto" "#portfolio-composition"
"color" {"pattern"
(clojure.core/shuffle chart-colors)}
"data" {"columns" dummy-portfolio-data
"type" "donut"}}))
)
:reagent-render
(fn [_] [:div
[:h2 "Overview"]
[:h3 "Your Investment Portfolio"]
[:div#portfolio-composition]
[:h3 "Friends\u2019 Picks"]
[:div#stock-picks
(map (fn [[id name pick]]
[:div.stock-pick {:key name}
[:div [:img {:src (str "img/profile/pic-" id ".jpg")}]]
[:div.name name]
[:div.pick pick]])
(take 5 (clojure.core/shuffle friend-list)))]
])}))
(defn investments []
[:h2 "Long-Term Investments"])
(defonce current-search (r/atom "AAPL"))
(defonce current-range (r/atom 60))
(defonce current-data (r/atom (gen-dummy-stock-data 60)))
(defn candlestick [raw-data range]
(let [r (js/Math.floor (* 1000000000 (rand)))
dorender
(fn [this]
(set! js/window.d3 js/window.d3v4)
(let [margin-top 20
margin-right 20
margin-bottom 30
margin-left 50
width (- 520 margin-left margin-right)
height (- 300 margin-top margin-bottom)
x (-> js/techan.scale (.financetime) (.range (clj->js [0 width])))
y (-> js/d3 (.scaleLinear) (.range (clj->js [height 0])))
candlestick (-> js/techan.plot (.candlestick) (.xScale x) (.yScale y))
xAxis (-> js/d3 (.axisBottom) (.scale x))
yAxis (-> js/d3 (.axisLeft) (.scale y))
svg (-> js/d3
(.select (str "div.candlestick.id" r))
(.html "")
(.append "svg")
(.attr "class" "candlestick")
(.attr "width" (+ width margin-left margin-right))
(.attr "height" (+ height margin-top margin-bottom))
(.append "g")
(.attr "transform" (str "translate(" margin-left "," margin-top ")")))
accessor (-> candlestick (.accessor))
data (-> (clj->js (take @range @raw-data)) (.sort (fn [a b] (js/d3.ascending (.d accessor a) (.d accessor b)))))
]
(-> svg (.append "g") (.attr "class" "candlestick"))
(-> svg (.append "g") (.attr "class" "x axis") (.attr "transform" (str "translate(0," height ")")))
(-> svg (.append "g") (.attr "class" "y axis") (.append "text") (.attr "transform" "rotate(-90)") (.attr "y" "6")
(.attr "dy" ".71em") (.style "text-anchor" "end") (.text "Price ($)"))
(.domain x (.map data (.-d (-> candlestick (.accessor)))))
(.domain y (.domain (js/techan.scale.plot.ohlc data (-> candlestick (.accessor)))))
(-> svg (.selectAll "g.candlestick") (.datum data) (.call candlestick))
(-> svg (.selectAll "g.x.axis") (.call xAxis))
(-> svg (.selectAll "g.y.axis") (.call yAxis))
))]
(r/create-class
{:component-did-mount dorender
:component-did-update dorender
:reagent-render
(fn [_]
[:div {:display "none"} (str @raw-data @range)]
[:div.candlestick {:class (str "id" r)}])})))
(defn trading []
[:div
[:h2 "Short-Term Trading"]
[:input {:type "text" :placeholder "Search for a stock symbol..." :class "ticksymbol"
:value @current-search :on-change #(swap! current-search (constantly (-> % .-target .-value)))}]
[:div
[:span "Days to Predict (max 60)"]
[:input {:type "range" :min "1" :max "60" :step "1"
:on-change #(swap! current-range (constantly (js/window.parseInt (-> % .-target .-value) 10)))
}]]
[:button {:on-click #(do
(swap! current-data (constantly (gen-dummy-stock-data 60)))
(POST "https://data.chastiser11.hasura-app.io/v1/query"
{:headers
{
"authorization" "<KEY> <KEY>"}
:format :json
:response-format :json
:params
{"type" "select", "args" {"table" "stockTest", "columns" ["*"], "where" { "stocksymbol" @current-search }}}
:handler
(fn [response]
(let [today (js/Date. (floor-factor (js/Date.now) 86400000))
predictions (js->clj (js/window.JSON.parse (get-in response [0 "predictions"])))
predictions-t (apply mapv vector predictions)
transformed (map-indexed (fn [i [o h l c]]
{"open" o
"high" h
"low" l
"close" c
"date" (js/Date. (+ (.getTime today) (* i 86400000)))
}
) (take 60 predictions-t))]
(if-not (empty? transformed)
(swap! current-data (constantly transformed)))))}))} "Load Prediction"]
[candlestick current-data current-range]])
(defn analytics []
[:h2 "Analytics"])
(def tabmap
{"Overview" overview
"Long-Term Investments" investments
"Short-Term Trading" trading
"Analytics" analytics})
(def tabs
(keys tabmap))
(defonce current-tab (r/atom (or (-> js/window.localStorage (.getItem "current-tab")) "Overview")))
(defn body []
[:div {:id "body"}
[:div#sidebar
[:ul
(map (fn [t] [:li {:key t} [:a {:on-click #(do
(-> js/window.localStorage (.setItem "current-tab" t))
(swap! current-tab (fn [_] t)))
:class (if (= @current-tab t) "selected" "")} t]]) tabs)]]
[:div#main-content
[(get tabmap @current-tab "Overview")]]])
(defn home-page []
[:div#container
[:div#header
[:img#logo {:src "img/logo.png" :height 64 :width 65}]
[:p#title "Stockpedia"]
[:p#menu "Welcome <NAME>! "
[:button "Logout"]]]
[body]
[:div#footer
[:p [:strong "Copyright (c) 2017 Stock Advisors and Company. All rights reserved."]]
[:p [:strong "Important Disclaimer: "] "Any past performance, projection, forecast or simulation of results is not necessarily indicative of the future or likely performance of any company or investment. The information provided does not take into account your specific investment objectives, financial situation or particular needs. Before you act on any information on this site, you should always seek independent financial, tax, and legal advice or make such independent investigations as you consider necessary or appropriate regarding the suitability of the investment product, taking into account your specific investment objectives, financial situation or particular needs."]]]
)
;; -------------------------
;; Initialize app
(defn mount-root []
(r/render [home-page] (.getElementById js/document "app")))
(defn init! []
(mount-root))
| true | (ns pennapps-xvi.core
(:require
[clojure.core]
[reagent.core :as r]
[ajax.core :refer [GET POST]]))
(defn floor-factor [n f]
(* f (quot n f)))
(defn gen-dummy-stock-data
[len]
(let [rand-range 0.8
rand-range-half (/ rand-range 2)]
(take
len
(iterate (fn [{:strs [open high low close volume date]}]
{"open" close
"high" (* close (+ 1.0 (* (- (rand rand-range) rand-range-half) (- (rand rand-range) rand-range-half))))
"low" (* close (+ 1.0 (* (- (rand rand-range) rand-range-half) (- (rand rand-range) rand-range-half))))
"close" (* close (+ 1.001 (* (- (rand rand-range) rand-range-half) (- (rand rand-range) rand-range-half))))
"volume" (* volume (+ 1.0 (* (- (rand rand-range) rand-range-half) (- (rand rand-range) rand-range-half) (- (rand rand-range) rand-range-half))))
"date" (js/Date. (+ (.getTime date) 86400000))})
{"date" (js/Date. (floor-factor (js/Date.now) 86400000))
"open" 62.40
"high" 63.34
"low" 61.79
"close" 62.88
"volume" 37617413}))))
;; -------------------------
;; Views
(def dummy-portfolio-data
[
["U.S. Stocks" "1123"]
["U.S. Bonds" "2287"]
["Cryptocurrencies" "3419"]
["Energy" "4200"]
["International Stock" "877"]
["Emerging Markets" "1877"]
])
(def friend-list
[
["1" "PI:NAME:<NAME>END_PI" "AAPL"]
["2" "PI:NAME:<NAME>END_PI" "GOOG"]
["3" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]
["4" "PI:NAME:<NAME>END_PI" "MSFT"]
["5" "PI:NAME:<NAME>END_PI" "VTSMX"]
["6" "PI:NAME:<NAME>END_PI" "F"]
["7" "PI:NAME:<NAME>END_PI" "SYMC"]
["8" "PI:NAME:<NAME>END_PI" "XOM"]
["9" "PI:NAME:<NAME>END_PI" "BLK"]
["10" "PI:NAME:<NAME>END_PI" "BLK"]
["11" "PI:NAME:<NAME>END_PI" "CSCO"]
["12" "PI:NAME:<NAME>END_PI" "FDX"]
["13" "PI:NAME:<NAME>END_PI" "FB"]])
(def chart-colors
["#A96186" "#A96162" "#A98461" "#A9A861" "#86A961" "#589857" "#4E876A" "#4E8786" "#4E6B87" "#4E4E87" "#6A4E87" "#8F5390"])
(defn overview []
(r/create-class
{:component-did-mount
(fn [this]
(set! js/window.d3 js/window.d3v3)
(js/c3.generate (clj->js {"bindto" "#portfolio-composition"
"color" {"pattern"
(clojure.core/shuffle chart-colors)}
"data" {"columns" dummy-portfolio-data
"type" "donut"}}))
)
:reagent-render
(fn [_] [:div
[:h2 "Overview"]
[:h3 "Your Investment Portfolio"]
[:div#portfolio-composition]
[:h3 "Friends\u2019 Picks"]
[:div#stock-picks
(map (fn [[id name pick]]
[:div.stock-pick {:key name}
[:div [:img {:src (str "img/profile/pic-" id ".jpg")}]]
[:div.name name]
[:div.pick pick]])
(take 5 (clojure.core/shuffle friend-list)))]
])}))
(defn investments []
[:h2 "Long-Term Investments"])
(defonce current-search (r/atom "AAPL"))
(defonce current-range (r/atom 60))
(defonce current-data (r/atom (gen-dummy-stock-data 60)))
(defn candlestick [raw-data range]
(let [r (js/Math.floor (* 1000000000 (rand)))
dorender
(fn [this]
(set! js/window.d3 js/window.d3v4)
(let [margin-top 20
margin-right 20
margin-bottom 30
margin-left 50
width (- 520 margin-left margin-right)
height (- 300 margin-top margin-bottom)
x (-> js/techan.scale (.financetime) (.range (clj->js [0 width])))
y (-> js/d3 (.scaleLinear) (.range (clj->js [height 0])))
candlestick (-> js/techan.plot (.candlestick) (.xScale x) (.yScale y))
xAxis (-> js/d3 (.axisBottom) (.scale x))
yAxis (-> js/d3 (.axisLeft) (.scale y))
svg (-> js/d3
(.select (str "div.candlestick.id" r))
(.html "")
(.append "svg")
(.attr "class" "candlestick")
(.attr "width" (+ width margin-left margin-right))
(.attr "height" (+ height margin-top margin-bottom))
(.append "g")
(.attr "transform" (str "translate(" margin-left "," margin-top ")")))
accessor (-> candlestick (.accessor))
data (-> (clj->js (take @range @raw-data)) (.sort (fn [a b] (js/d3.ascending (.d accessor a) (.d accessor b)))))
]
(-> svg (.append "g") (.attr "class" "candlestick"))
(-> svg (.append "g") (.attr "class" "x axis") (.attr "transform" (str "translate(0," height ")")))
(-> svg (.append "g") (.attr "class" "y axis") (.append "text") (.attr "transform" "rotate(-90)") (.attr "y" "6")
(.attr "dy" ".71em") (.style "text-anchor" "end") (.text "Price ($)"))
(.domain x (.map data (.-d (-> candlestick (.accessor)))))
(.domain y (.domain (js/techan.scale.plot.ohlc data (-> candlestick (.accessor)))))
(-> svg (.selectAll "g.candlestick") (.datum data) (.call candlestick))
(-> svg (.selectAll "g.x.axis") (.call xAxis))
(-> svg (.selectAll "g.y.axis") (.call yAxis))
))]
(r/create-class
{:component-did-mount dorender
:component-did-update dorender
:reagent-render
(fn [_]
[:div {:display "none"} (str @raw-data @range)]
[:div.candlestick {:class (str "id" r)}])})))
(defn trading []
[:div
[:h2 "Short-Term Trading"]
[:input {:type "text" :placeholder "Search for a stock symbol..." :class "ticksymbol"
:value @current-search :on-change #(swap! current-search (constantly (-> % .-target .-value)))}]
[:div
[:span "Days to Predict (max 60)"]
[:input {:type "range" :min "1" :max "60" :step "1"
:on-change #(swap! current-range (constantly (js/window.parseInt (-> % .-target .-value) 10)))
}]]
[:button {:on-click #(do
(swap! current-data (constantly (gen-dummy-stock-data 60)))
(POST "https://data.chastiser11.hasura-app.io/v1/query"
{:headers
{
"authorization" "PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI"}
:format :json
:response-format :json
:params
{"type" "select", "args" {"table" "stockTest", "columns" ["*"], "where" { "stocksymbol" @current-search }}}
:handler
(fn [response]
(let [today (js/Date. (floor-factor (js/Date.now) 86400000))
predictions (js->clj (js/window.JSON.parse (get-in response [0 "predictions"])))
predictions-t (apply mapv vector predictions)
transformed (map-indexed (fn [i [o h l c]]
{"open" o
"high" h
"low" l
"close" c
"date" (js/Date. (+ (.getTime today) (* i 86400000)))
}
) (take 60 predictions-t))]
(if-not (empty? transformed)
(swap! current-data (constantly transformed)))))}))} "Load Prediction"]
[candlestick current-data current-range]])
(defn analytics []
[:h2 "Analytics"])
(def tabmap
{"Overview" overview
"Long-Term Investments" investments
"Short-Term Trading" trading
"Analytics" analytics})
(def tabs
(keys tabmap))
(defonce current-tab (r/atom (or (-> js/window.localStorage (.getItem "current-tab")) "Overview")))
(defn body []
[:div {:id "body"}
[:div#sidebar
[:ul
(map (fn [t] [:li {:key t} [:a {:on-click #(do
(-> js/window.localStorage (.setItem "current-tab" t))
(swap! current-tab (fn [_] t)))
:class (if (= @current-tab t) "selected" "")} t]]) tabs)]]
[:div#main-content
[(get tabmap @current-tab "Overview")]]])
(defn home-page []
[:div#container
[:div#header
[:img#logo {:src "img/logo.png" :height 64 :width 65}]
[:p#title "Stockpedia"]
[:p#menu "Welcome PI:NAME:<NAME>END_PI! "
[:button "Logout"]]]
[body]
[:div#footer
[:p [:strong "Copyright (c) 2017 Stock Advisors and Company. All rights reserved."]]
[:p [:strong "Important Disclaimer: "] "Any past performance, projection, forecast or simulation of results is not necessarily indicative of the future or likely performance of any company or investment. The information provided does not take into account your specific investment objectives, financial situation or particular needs. Before you act on any information on this site, you should always seek independent financial, tax, and legal advice or make such independent investigations as you consider necessary or appropriate regarding the suitability of the investment product, taking into account your specific investment objectives, financial situation or particular needs."]]]
)
;; -------------------------
;; Initialize app
(defn mount-root []
(r/render [home-page] (.getElementById js/document "app")))
(defn init! []
(mount-root))
|
[
{
"context": "tarting lwb in a repl\n\n; Copyright (c) 2014 - 2016 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu",
"end": 95,
"score": 0.9998673796653748,
"start": 81,
"tag": "NAME",
"value": "Burkhardt Renz"
}
] | src/lwb/main.clj | esb-lwb/lwb | 22 | ; lwb Logic WorkBench -- For starting lwb in a repl
; Copyright (c) 2014 - 2016 Burkhardt Renz, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.main
(:require [clojure.string :as str]
[lwb.consts :refer [welcome]]))
;; # Starting lwb in a repl
;; The command is like this one:
;; `rlwrap java -Xms2G -cp ~/bin/lwb.jar clojure.main -i @lwb/main.clj -r`
;; This command opens a repl in namespace `user` and shows the startinfo.
(defn man
"Manual"
[]
(let [info (str/join \newline
[welcome
"Propositional logic:"
"- (load \"lwb/prop\")"
"- (ns lwb.prop)"
"Predicate logic:"
"- (load \"lwb/pred\")"
"- (ns lwb.pred)"
"Linear temporal logic:"
"- (load \"lwb/ltl\")"
"- (ns lwb.ltl)"
"Natural deduction:"
"- (load \"lwb/nd/repl\")"
"- (ns lwb.nd.repl)"])]
(println info)))
(man)
| 97871 | ; lwb Logic WorkBench -- For starting lwb in a repl
; Copyright (c) 2014 - 2016 <NAME>, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.main
(:require [clojure.string :as str]
[lwb.consts :refer [welcome]]))
;; # Starting lwb in a repl
;; The command is like this one:
;; `rlwrap java -Xms2G -cp ~/bin/lwb.jar clojure.main -i @lwb/main.clj -r`
;; This command opens a repl in namespace `user` and shows the startinfo.
(defn man
"Manual"
[]
(let [info (str/join \newline
[welcome
"Propositional logic:"
"- (load \"lwb/prop\")"
"- (ns lwb.prop)"
"Predicate logic:"
"- (load \"lwb/pred\")"
"- (ns lwb.pred)"
"Linear temporal logic:"
"- (load \"lwb/ltl\")"
"- (ns lwb.ltl)"
"Natural deduction:"
"- (load \"lwb/nd/repl\")"
"- (ns lwb.nd.repl)"])]
(println info)))
(man)
| true | ; lwb Logic WorkBench -- For starting lwb in a repl
; Copyright (c) 2014 - 2016 PI:NAME:<NAME>END_PI, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.main
(:require [clojure.string :as str]
[lwb.consts :refer [welcome]]))
;; # Starting lwb in a repl
;; The command is like this one:
;; `rlwrap java -Xms2G -cp ~/bin/lwb.jar clojure.main -i @lwb/main.clj -r`
;; This command opens a repl in namespace `user` and shows the startinfo.
(defn man
"Manual"
[]
(let [info (str/join \newline
[welcome
"Propositional logic:"
"- (load \"lwb/prop\")"
"- (ns lwb.prop)"
"Predicate logic:"
"- (load \"lwb/pred\")"
"- (ns lwb.pred)"
"Linear temporal logic:"
"- (load \"lwb/ltl\")"
"- (ns lwb.ltl)"
"Natural deduction:"
"- (load \"lwb/nd/repl\")"
"- (ns lwb.nd.repl)"])]
(println info)))
(man)
|
[
{
"context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brow",
"end": 25,
"score": 0.9998442530632019,
"start": 15,
"tag": "NAME",
"value": "Adam Jacob"
},
{
"context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>",
"end": 44,
"score": 0.9999335408210754,
"start": 28,
"tag": "EMAIL",
"value": "adam@opscode.com"
},
{
"context": "thor:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>)\n;; Copyright:: Copyright (c) 2",
"end": 76,
"score": 0.9997360110282898,
"start": 59,
"tag": "NAME",
"value": "Christopher Brown"
},
{
"context": "dam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>)\n;; Copyright:: Copyright (c) 2010 Opscode, Inc.",
"end": 93,
"score": 0.9999328255653381,
"start": 79,
"tag": "EMAIL",
"value": "cb@opscode.com"
}
] | config/software/libxslt.clj | racker/omnibus | 2 | ;;
;; Author:: Adam Jacob (<adam@opscode.com>)
;; Author:: Christopher Brown (<cb@opscode.com>)
;; Copyright:: Copyright (c) 2010 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(software "libxslt" :source "libxslt-1.1.26"
:steps [{:env {"LDFLAGS" "-L/opt/opscode/embedded/lib -I/opt/opscode/embedded/include"
"CFLAGS" "-L/opt/opscode/embedded/lib -I/opt/opscode/embedded/include"
"LD_RUN_PATH" "/opt/opscode/embedded/lib"}
:command (cond (is-os? "darwin")
"true"
true
"./autogen.sh")
:args ["--prefix=/opt/opscode/embedded" "--with-libxml-prefix=/opt/opscode/embedded"
"--with-libxml-include-prefix=/opt/opscode/embedded/include"
"--with-libxml-libs-prefix=/opt/opscode/embedded/lib"]}
{:command (if (is-os? "solaris2") "perl" "true")
:args [ "-pi" "-e" "s/^(LIBXSLT_VERSION_SCRIPT = \\$.+)/\\# Woof/g"
(str *omnibus-build-dir* "/libxslt-1.1.26/libxslt/Makefile") ]}
{:command (if (is-os? "solaris2") "perl" "true")
:args [ "-pi" "-e" "s/^(#LIBXSLT_VERSION_SCRIPT.+)/LIBXSLT_VERSION_SCRIPT =/g"
(str *omnibus-build-dir* "/libxslt-1.1.26/libxslt/Makefile") ]}
{:env {"LD_RUN_PATH" "/opt/opscode/embedded/lib"} :command "make" :args ["install"]}])
| 119478 | ;;
;; Author:: <NAME> (<<EMAIL>>)
;; Author:: <NAME> (<<EMAIL>>)
;; Copyright:: Copyright (c) 2010 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(software "libxslt" :source "libxslt-1.1.26"
:steps [{:env {"LDFLAGS" "-L/opt/opscode/embedded/lib -I/opt/opscode/embedded/include"
"CFLAGS" "-L/opt/opscode/embedded/lib -I/opt/opscode/embedded/include"
"LD_RUN_PATH" "/opt/opscode/embedded/lib"}
:command (cond (is-os? "darwin")
"true"
true
"./autogen.sh")
:args ["--prefix=/opt/opscode/embedded" "--with-libxml-prefix=/opt/opscode/embedded"
"--with-libxml-include-prefix=/opt/opscode/embedded/include"
"--with-libxml-libs-prefix=/opt/opscode/embedded/lib"]}
{:command (if (is-os? "solaris2") "perl" "true")
:args [ "-pi" "-e" "s/^(LIBXSLT_VERSION_SCRIPT = \\$.+)/\\# Woof/g"
(str *omnibus-build-dir* "/libxslt-1.1.26/libxslt/Makefile") ]}
{:command (if (is-os? "solaris2") "perl" "true")
:args [ "-pi" "-e" "s/^(#LIBXSLT_VERSION_SCRIPT.+)/LIBXSLT_VERSION_SCRIPT =/g"
(str *omnibus-build-dir* "/libxslt-1.1.26/libxslt/Makefile") ]}
{:env {"LD_RUN_PATH" "/opt/opscode/embedded/lib"} :command "make" :args ["install"]}])
| true | ;;
;; Author:: PI:NAME:<NAME>END_PI (<PI:EMAIL:<EMAIL>END_PI>)
;; Author:: PI:NAME:<NAME>END_PI (<PI:EMAIL:<EMAIL>END_PI>)
;; Copyright:: Copyright (c) 2010 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(software "libxslt" :source "libxslt-1.1.26"
:steps [{:env {"LDFLAGS" "-L/opt/opscode/embedded/lib -I/opt/opscode/embedded/include"
"CFLAGS" "-L/opt/opscode/embedded/lib -I/opt/opscode/embedded/include"
"LD_RUN_PATH" "/opt/opscode/embedded/lib"}
:command (cond (is-os? "darwin")
"true"
true
"./autogen.sh")
:args ["--prefix=/opt/opscode/embedded" "--with-libxml-prefix=/opt/opscode/embedded"
"--with-libxml-include-prefix=/opt/opscode/embedded/include"
"--with-libxml-libs-prefix=/opt/opscode/embedded/lib"]}
{:command (if (is-os? "solaris2") "perl" "true")
:args [ "-pi" "-e" "s/^(LIBXSLT_VERSION_SCRIPT = \\$.+)/\\# Woof/g"
(str *omnibus-build-dir* "/libxslt-1.1.26/libxslt/Makefile") ]}
{:command (if (is-os? "solaris2") "perl" "true")
:args [ "-pi" "-e" "s/^(#LIBXSLT_VERSION_SCRIPT.+)/LIBXSLT_VERSION_SCRIPT =/g"
(str *omnibus-build-dir* "/libxslt-1.1.26/libxslt/Makefile") ]}
{:env {"LD_RUN_PATH" "/opt/opscode/embedded/lib"} :command "make" :args ["install"]}])
|
[
{
"context": "tp-opts client)\n {:form-params {:password password}\n :content-type :json\n :accep",
"end": 2034,
"score": 0.9977976083755493,
"start": 2026,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "tp-opts client)\n {:form-params {:password password}\n :content-type :json\n :accep",
"end": 3502,
"score": 0.9980338215827942,
"start": 3494,
"tag": "PASSWORD",
"value": "password"
}
] | src/vault/authenticate.clj | b-social/vault-clj | 0 | (ns vault.authenticate
"Handles logic relating to the authentication of a Vault client"
(:require
[clojure.string :as str]
[clojure.tools.logging :as log]
[vault.client.api-util :as api-util]
[vault.lease :as lease]))
(defn ^:no-doc api-auth!
"Validate the response from a vault auth call, update auth-ref with additional
tracking state like lease metadata."
[claim auth-ref response]
(let [auth-info (lease/auth-lease (:auth (api-util/clean-body response)))]
(when-not (:client-token auth-info)
(throw (ex-info (str "No client token returned from non-error API response: "
(:status response) " " (:reason-phrase response))
{:body (:body response)})))
(log/info "Successfully authenticated to Vault as %s for policies: %s"
claim (str/join ", " (:policies auth-info)))
(reset! auth-ref auth-info)))
(defmulti authenticate*
"Authenticate the client with vault using the given auth-type and credentials."
(fn dispatch
[_client auth-type _credentials]
auth-type))
(defmethod authenticate* :default
[_ auth-type _]
(throw (ex-info (str "Unsupported auth-type " (pr-str auth-type))
{:auth-type auth-type})))
(defmethod authenticate* :token
[client _ token]
(when-not (string? token)
(throw (IllegalArgumentException. "Token credential must be a string")))
(reset! (:auth client) {:client-token (str/trim token)}))
(defmethod authenticate* :wrap-token
[client _ credentials]
(api-auth!
"wrapped token"
(:auth client)
(api-util/unwrap-secret client credentials)))
(defmethod authenticate* :userpass
[client _ credentials]
(let [{:keys [username password]} credentials]
(api-auth!
(str "user " username)
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) "/v1/auth/userpass/" (:auth-mount-point client) "login/" username)
(merge
(:http-opts client)
{:form-params {:password password}
:content-type :json
:accept :json
:as :json})))))
(defmethod authenticate* :app-id
[client _ credentials]
(let [{:keys [app user]} credentials]
(api-auth!
(str "app-id " app)
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) "/v1/auth/app-id/" (:auth-mount-point client) "login")
(merge
(:http-opts client)
{:form-params {:app_id app, :user_id user}
:content-type :json
:accept :json
:as :json})))))
(defmethod authenticate* :app-role
[client _ credentials]
(let [{:keys [role-id secret-id]} credentials]
(api-auth!
(str "role-id sha256:" (api-util/sha-256 role-id))
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) "/v1/auth/approle/" (:auth-mount-point client) "login")
(merge
(:http-opts client)
{:form-params {:role_id role-id, :secret_id secret-id}
:content-type :json
:accept :json
:as :json})))))
(defmethod authenticate* :ldap
[client _ credentials]
(let [{:keys [username password]} credentials]
(api-auth!
(str "LDAP user " username)
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) "/v1/auth/ldap/" (:auth-mount-point client) "login/" username)
(merge
(:http-opts client)
{:form-params {:password password}
:content-type :json
:accept :json
:as :json})))))
(defmethod authenticate* :k8s
[client _ credentials]
(let [{:keys [api-path jwt role]} credentials
api-path (or api-path (str "/v1/auth/kubernetes/" (:auth-mount-point client) "login"))]
(when-not jwt
(throw (IllegalArgumentException. "Kubernetes auth credentials must include :jwt")))
(when-not role
(throw (IllegalArgumentException. "Kubernetes auth credentials must include :role")))
(api-auth!
(str "Kubernetes auth role=" role)
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) api-path)
(merge
(:http-opts client)
{:form-params {:jwt jwt :role role}
:content-type :json
:accept :json
:as :json})))))
(defmethod authenticate* :aws-iam
[client _ credentials]
(let [{:keys [api-path http-request-method request-url request-body request-headers
role]} credentials
api-path (or api-path (str "/v1/auth/aws/" (:auth-mount-point client) "login"))]
(when-not http-request-method
(throw (IllegalArgumentException. "AWS auth credentials must include :http-request-method")))
(when-not request-url
(throw (IllegalArgumentException. "AWS auth credentials must include :request-url")))
(when-not request-body
(throw (IllegalArgumentException. "AWS auth credentials must include :request-body")))
(when-not request-headers
(throw (IllegalArgumentException. "AWS auth credentials must include :request-headers")))
(when-not role
(throw (IllegalArgumentException. "AWS auth credentials must include :role")))
(api-auth!
(str "AWS auth role=" role)
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) api-path)
(merge
(:http-opts client)
{:form-params {:iam_http_request_method http-request-method
:iam_request_url request-url
:iam_request_body request-body
:iam_request_headers request-headers
:role role}
:content-type :json
:accept :json
:as :json})))))
| 66652 | (ns vault.authenticate
"Handles logic relating to the authentication of a Vault client"
(:require
[clojure.string :as str]
[clojure.tools.logging :as log]
[vault.client.api-util :as api-util]
[vault.lease :as lease]))
(defn ^:no-doc api-auth!
"Validate the response from a vault auth call, update auth-ref with additional
tracking state like lease metadata."
[claim auth-ref response]
(let [auth-info (lease/auth-lease (:auth (api-util/clean-body response)))]
(when-not (:client-token auth-info)
(throw (ex-info (str "No client token returned from non-error API response: "
(:status response) " " (:reason-phrase response))
{:body (:body response)})))
(log/info "Successfully authenticated to Vault as %s for policies: %s"
claim (str/join ", " (:policies auth-info)))
(reset! auth-ref auth-info)))
(defmulti authenticate*
"Authenticate the client with vault using the given auth-type and credentials."
(fn dispatch
[_client auth-type _credentials]
auth-type))
(defmethod authenticate* :default
[_ auth-type _]
(throw (ex-info (str "Unsupported auth-type " (pr-str auth-type))
{:auth-type auth-type})))
(defmethod authenticate* :token
[client _ token]
(when-not (string? token)
(throw (IllegalArgumentException. "Token credential must be a string")))
(reset! (:auth client) {:client-token (str/trim token)}))
(defmethod authenticate* :wrap-token
[client _ credentials]
(api-auth!
"wrapped token"
(:auth client)
(api-util/unwrap-secret client credentials)))
(defmethod authenticate* :userpass
[client _ credentials]
(let [{:keys [username password]} credentials]
(api-auth!
(str "user " username)
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) "/v1/auth/userpass/" (:auth-mount-point client) "login/" username)
(merge
(:http-opts client)
{:form-params {:password <PASSWORD>}
:content-type :json
:accept :json
:as :json})))))
(defmethod authenticate* :app-id
[client _ credentials]
(let [{:keys [app user]} credentials]
(api-auth!
(str "app-id " app)
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) "/v1/auth/app-id/" (:auth-mount-point client) "login")
(merge
(:http-opts client)
{:form-params {:app_id app, :user_id user}
:content-type :json
:accept :json
:as :json})))))
(defmethod authenticate* :app-role
[client _ credentials]
(let [{:keys [role-id secret-id]} credentials]
(api-auth!
(str "role-id sha256:" (api-util/sha-256 role-id))
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) "/v1/auth/approle/" (:auth-mount-point client) "login")
(merge
(:http-opts client)
{:form-params {:role_id role-id, :secret_id secret-id}
:content-type :json
:accept :json
:as :json})))))
(defmethod authenticate* :ldap
[client _ credentials]
(let [{:keys [username password]} credentials]
(api-auth!
(str "LDAP user " username)
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) "/v1/auth/ldap/" (:auth-mount-point client) "login/" username)
(merge
(:http-opts client)
{:form-params {:password <PASSWORD>}
:content-type :json
:accept :json
:as :json})))))
(defmethod authenticate* :k8s
[client _ credentials]
(let [{:keys [api-path jwt role]} credentials
api-path (or api-path (str "/v1/auth/kubernetes/" (:auth-mount-point client) "login"))]
(when-not jwt
(throw (IllegalArgumentException. "Kubernetes auth credentials must include :jwt")))
(when-not role
(throw (IllegalArgumentException. "Kubernetes auth credentials must include :role")))
(api-auth!
(str "Kubernetes auth role=" role)
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) api-path)
(merge
(:http-opts client)
{:form-params {:jwt jwt :role role}
:content-type :json
:accept :json
:as :json})))))
(defmethod authenticate* :aws-iam
[client _ credentials]
(let [{:keys [api-path http-request-method request-url request-body request-headers
role]} credentials
api-path (or api-path (str "/v1/auth/aws/" (:auth-mount-point client) "login"))]
(when-not http-request-method
(throw (IllegalArgumentException. "AWS auth credentials must include :http-request-method")))
(when-not request-url
(throw (IllegalArgumentException. "AWS auth credentials must include :request-url")))
(when-not request-body
(throw (IllegalArgumentException. "AWS auth credentials must include :request-body")))
(when-not request-headers
(throw (IllegalArgumentException. "AWS auth credentials must include :request-headers")))
(when-not role
(throw (IllegalArgumentException. "AWS auth credentials must include :role")))
(api-auth!
(str "AWS auth role=" role)
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) api-path)
(merge
(:http-opts client)
{:form-params {:iam_http_request_method http-request-method
:iam_request_url request-url
:iam_request_body request-body
:iam_request_headers request-headers
:role role}
:content-type :json
:accept :json
:as :json})))))
| true | (ns vault.authenticate
"Handles logic relating to the authentication of a Vault client"
(:require
[clojure.string :as str]
[clojure.tools.logging :as log]
[vault.client.api-util :as api-util]
[vault.lease :as lease]))
(defn ^:no-doc api-auth!
"Validate the response from a vault auth call, update auth-ref with additional
tracking state like lease metadata."
[claim auth-ref response]
(let [auth-info (lease/auth-lease (:auth (api-util/clean-body response)))]
(when-not (:client-token auth-info)
(throw (ex-info (str "No client token returned from non-error API response: "
(:status response) " " (:reason-phrase response))
{:body (:body response)})))
(log/info "Successfully authenticated to Vault as %s for policies: %s"
claim (str/join ", " (:policies auth-info)))
(reset! auth-ref auth-info)))
(defmulti authenticate*
"Authenticate the client with vault using the given auth-type and credentials."
(fn dispatch
[_client auth-type _credentials]
auth-type))
(defmethod authenticate* :default
[_ auth-type _]
(throw (ex-info (str "Unsupported auth-type " (pr-str auth-type))
{:auth-type auth-type})))
(defmethod authenticate* :token
[client _ token]
(when-not (string? token)
(throw (IllegalArgumentException. "Token credential must be a string")))
(reset! (:auth client) {:client-token (str/trim token)}))
(defmethod authenticate* :wrap-token
[client _ credentials]
(api-auth!
"wrapped token"
(:auth client)
(api-util/unwrap-secret client credentials)))
(defmethod authenticate* :userpass
[client _ credentials]
(let [{:keys [username password]} credentials]
(api-auth!
(str "user " username)
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) "/v1/auth/userpass/" (:auth-mount-point client) "login/" username)
(merge
(:http-opts client)
{:form-params {:password PI:PASSWORD:<PASSWORD>END_PI}
:content-type :json
:accept :json
:as :json})))))
(defmethod authenticate* :app-id
[client _ credentials]
(let [{:keys [app user]} credentials]
(api-auth!
(str "app-id " app)
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) "/v1/auth/app-id/" (:auth-mount-point client) "login")
(merge
(:http-opts client)
{:form-params {:app_id app, :user_id user}
:content-type :json
:accept :json
:as :json})))))
(defmethod authenticate* :app-role
[client _ credentials]
(let [{:keys [role-id secret-id]} credentials]
(api-auth!
(str "role-id sha256:" (api-util/sha-256 role-id))
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) "/v1/auth/approle/" (:auth-mount-point client) "login")
(merge
(:http-opts client)
{:form-params {:role_id role-id, :secret_id secret-id}
:content-type :json
:accept :json
:as :json})))))
(defmethod authenticate* :ldap
[client _ credentials]
(let [{:keys [username password]} credentials]
(api-auth!
(str "LDAP user " username)
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) "/v1/auth/ldap/" (:auth-mount-point client) "login/" username)
(merge
(:http-opts client)
{:form-params {:password PI:PASSWORD:<PASSWORD>END_PI}
:content-type :json
:accept :json
:as :json})))))
(defmethod authenticate* :k8s
[client _ credentials]
(let [{:keys [api-path jwt role]} credentials
api-path (or api-path (str "/v1/auth/kubernetes/" (:auth-mount-point client) "login"))]
(when-not jwt
(throw (IllegalArgumentException. "Kubernetes auth credentials must include :jwt")))
(when-not role
(throw (IllegalArgumentException. "Kubernetes auth credentials must include :role")))
(api-auth!
(str "Kubernetes auth role=" role)
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) api-path)
(merge
(:http-opts client)
{:form-params {:jwt jwt :role role}
:content-type :json
:accept :json
:as :json})))))
(defmethod authenticate* :aws-iam
[client _ credentials]
(let [{:keys [api-path http-request-method request-url request-body request-headers
role]} credentials
api-path (or api-path (str "/v1/auth/aws/" (:auth-mount-point client) "login"))]
(when-not http-request-method
(throw (IllegalArgumentException. "AWS auth credentials must include :http-request-method")))
(when-not request-url
(throw (IllegalArgumentException. "AWS auth credentials must include :request-url")))
(when-not request-body
(throw (IllegalArgumentException. "AWS auth credentials must include :request-body")))
(when-not request-headers
(throw (IllegalArgumentException. "AWS auth credentials must include :request-headers")))
(when-not role
(throw (IllegalArgumentException. "AWS auth credentials must include :role")))
(api-auth!
(str "AWS auth role=" role)
(:auth client)
(api-util/do-api-request
:post (str (:api-url client) api-path)
(merge
(:http-opts client)
{:form-params {:iam_http_request_method http-request-method
:iam_request_url request-url
:iam_request_body request-body
:iam_request_headers request-headers
:role role}
:content-type :json
:accept :json
:as :json})))))
|
[
{
"context": " (pt/-header (new-auth {:basic {:username \"foofoo\"\n :passwor",
"end": 654,
"score": 0.9994034767150879,
"start": 648,
"tag": "USERNAME",
"value": "foofoo"
},
{
"context": " :password \"barbar\"}\n :password {:use",
"end": 713,
"score": 0.9994958639144897,
"start": 707,
"tag": "PASSWORD",
"value": "barbar"
},
{
"context": " :password {:username \"foofoo\"\n :pass",
"end": 776,
"score": 0.9988847970962524,
"start": 770,
"tag": "USERNAME",
"value": "foofoo"
},
{
"context": " :password \"barbar\"}}))))\n\n (is (= {\"Authorization\" \"Basic Zm9vZm9v",
"end": 838,
"score": 0.9994790554046631,
"start": 832,
"tag": "PASSWORD",
"value": "barbar"
},
{
"context": " (pt/-header (new-auth {:basic {:username \"foofoo\"\n :passwor",
"end": 1061,
"score": 0.999443531036377,
"start": 1055,
"tag": "USERNAME",
"value": "foofoo"
},
{
"context": " :password \"barbar\"}\n :password {:use",
"end": 1120,
"score": 0.999447226524353,
"start": 1114,
"tag": "PASSWORD",
"value": "barbar"
},
{
"context": " :password {:username \"foofoo\"\n :pass",
"end": 1183,
"score": 0.9990054368972778,
"start": 1177,
"tag": "USERNAME",
"value": "foofoo"
},
{
"context": " :password \"barbar\"}\n :api-token \"XXX",
"end": 1245,
"score": 0.9995074272155762,
"start": 1239,
"tag": "PASSWORD",
"value": "barbar"
}
] | test/kintone_client/authentication_test.cljc | egs33/kintone-client | 5 | (ns kintone-client.authentication-test
(:require #?(:clj [clojure.test :refer :all]
:cljs [cljs.test :refer-macros [deftest is]])
[kintone-client.authentication :refer [new-auth]]
[kintone-client.protocols :as pt]))
(deftest new-auth-test
#?(:cljs
(is (= {} (pt/-header (new-auth)))))
(is (= {} (pt/-header (new-auth nil))))
(is (= {"X-Cybozu-API-Token" "XXXYYYXXX"}
(pt/-header (new-auth {:api-token "XXXYYYXXX"}))))
(is (= {"Authorization" "Basic Zm9vZm9vOmJhcmJhcg=="
"X-Cybozu-Authorization" "Zm9vZm9vOmJhcmJhcg=="}
(pt/-header (new-auth {:basic {:username "foofoo"
:password "barbar"}
:password {:username "foofoo"
:password "barbar"}}))))
(is (= {"Authorization" "Basic Zm9vZm9vOmJhcmJhcg=="
"X-Cybozu-Authorization" "Zm9vZm9vOmJhcmJhcg=="
"X-Cybozu-API-Token" "XXXYYYXXX"}
(pt/-header (new-auth {:basic {:username "foofoo"
:password "barbar"}
:password {:username "foofoo"
:password "barbar"}
:api-token "XXXYYYXXX"})))))
| 18185 | (ns kintone-client.authentication-test
(:require #?(:clj [clojure.test :refer :all]
:cljs [cljs.test :refer-macros [deftest is]])
[kintone-client.authentication :refer [new-auth]]
[kintone-client.protocols :as pt]))
(deftest new-auth-test
#?(:cljs
(is (= {} (pt/-header (new-auth)))))
(is (= {} (pt/-header (new-auth nil))))
(is (= {"X-Cybozu-API-Token" "XXXYYYXXX"}
(pt/-header (new-auth {:api-token "XXXYYYXXX"}))))
(is (= {"Authorization" "Basic Zm9vZm9vOmJhcmJhcg=="
"X-Cybozu-Authorization" "Zm9vZm9vOmJhcmJhcg=="}
(pt/-header (new-auth {:basic {:username "foofoo"
:password "<PASSWORD>"}
:password {:username "foofoo"
:password "<PASSWORD>"}}))))
(is (= {"Authorization" "Basic Zm9vZm9vOmJhcmJhcg=="
"X-Cybozu-Authorization" "Zm9vZm9vOmJhcmJhcg=="
"X-Cybozu-API-Token" "XXXYYYXXX"}
(pt/-header (new-auth {:basic {:username "foofoo"
:password "<PASSWORD>"}
:password {:username "foofoo"
:password "<PASSWORD>"}
:api-token "XXXYYYXXX"})))))
| true | (ns kintone-client.authentication-test
(:require #?(:clj [clojure.test :refer :all]
:cljs [cljs.test :refer-macros [deftest is]])
[kintone-client.authentication :refer [new-auth]]
[kintone-client.protocols :as pt]))
(deftest new-auth-test
#?(:cljs
(is (= {} (pt/-header (new-auth)))))
(is (= {} (pt/-header (new-auth nil))))
(is (= {"X-Cybozu-API-Token" "XXXYYYXXX"}
(pt/-header (new-auth {:api-token "XXXYYYXXX"}))))
(is (= {"Authorization" "Basic Zm9vZm9vOmJhcmJhcg=="
"X-Cybozu-Authorization" "Zm9vZm9vOmJhcmJhcg=="}
(pt/-header (new-auth {:basic {:username "foofoo"
:password "PI:PASSWORD:<PASSWORD>END_PI"}
:password {:username "foofoo"
:password "PI:PASSWORD:<PASSWORD>END_PI"}}))))
(is (= {"Authorization" "Basic Zm9vZm9vOmJhcmJhcg=="
"X-Cybozu-Authorization" "Zm9vZm9vOmJhcmJhcg=="
"X-Cybozu-API-Token" "XXXYYYXXX"}
(pt/-header (new-auth {:basic {:username "foofoo"
:password "PI:PASSWORD:<PASSWORD>END_PI"}
:password {:username "foofoo"
:password "PI:PASSWORD:<PASSWORD>END_PI"}
:api-token "XXXYYYXXX"})))))
|
[
{
"context": ";;; Copyright 2011 Howard M. Lewis Ship\n;;;\n;;; Licensed under the Apache License, Versio",
"end": 39,
"score": 0.9998588562011719,
"start": 19,
"tag": "NAME",
"value": "Howard M. Lewis Ship"
}
] | src/cascade/import.clj | hlship/cascade | 8 | ;;; Copyright 2011 Howard M. Lewis Ship
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");;;
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
;;; implied. See the License for the specific language governing permissions
;;; and limitations under the License.
(ns cascade.import
"Support for importing assets and JavaScript initialization code into the document, during the DOM rendering phase."
(:use
cascade
[cascade dom asset])
(:require
[clojure.string :as s2]
[clj-json.core :as json]))
(def ^{:dynamic true}
*active-imports*
"Stores a per-thread map used to track what's been imported."
nil)
(defn wrap-setup-active-imports [handler]
"Binds the *active-imports* var so that it may be updated by the downstream handlers."
(fn [req]
(binding [*active-imports* {:stylesheets [] :javascript []}]
(handler req))))
(defn add-if-not-present
[list value]
(if (contains? list value)
list
; Dependent on the list being a vector that conj-es at the end
(conj list value)))
(defn import-into-keyed-list
"Updates that map in *active-imports*, adding the value to the list storted under the
given key, if not already present. Returns nil."
[key value]
(set! *active-imports* (update-in *active-imports* [key] add-if-not-present value))
nil)
(defn import-stylesheet
"Imports a stylesheet for a CSS asset. The stylesheet may be specified as an asset. Alternately, a stylesheet factory
function and a path passed to that factory may be provided (which reads nicely). Returns nil."
; TODO: Naming and explicit ordering!
([stylesheet-asset]
(import-into-keyed-list :stylesheets stylesheet-asset))
([factory-fn asset-path]
(import-stylesheet (factory-fn asset-path))))
(defn import-module
"Imports a module by module name. Returns nil"
[module-name]
(import-into-keyed-list :javascript [module-name]))
(defn javascript
"Imports initialization JavaScript that will be executed when the page loads.
module-name
Name of module exposing the initialization function. The module should return a JavaScript object that maps names to functions.
initializer-fn-name
Name of a function exposed by the module that will be invoked.
arguments
Arguments passed to the client-side function. The arguments will be converted to JSON before being streamed to the client. Typically,
a single value (a string, or a JSON Object) is passed."
[module-name initializer-fn-name & arguments]
; TODO: this may change a bit when we implement Ajax partial rendering.
(import-into-keyed-list :javascript [module-name initializer-fn-name arguments]))
(defn javascript-invoke
"Builds a very particular kinds of call to the javascript function:
dependencies
List of RequireJS module dependencies necessary to invoke the function. These are typically dependencies that extend
jQuery.
selector
A CSS selector string passed to the jQuery main function.
function-name
Name of a jQuery function to invoke on the selection.
arguments
Arguments to pass to the jQuery function."
[dependencies selector function-name & arguments]
(apply javascript "cascade/init" "invoke" dependencies selector function-name arguments))
(defn to-element-node
"Converts an asset into a <link> element node."
[asset]
(element-node :link {:rel :stylesheet :type "text/css" :href asset} nil))
(defn add-stylesheet-nodes
[dom-nodes stylesheet-assets]
; TODO: optimize when no assets
(extend-dom dom-nodes [[[:html :head :script] :before]
[[:html :head :link] :before]
[[:html :head] :bottom]] (map to-element-node stylesheet-assets)))
(defn apply-response-transformation
[handler key transform-fn]
(fn [req]
(let [response (handler req)]
(and response
(update-in response [:body] transform-fn (*active-imports* key))))))
(defn wrap-import-stylesheets
"Middleware that expects the rendered body to be a seq of DOM nodes. The DOM nodes are
post-processed to add new <link> elements for any imported stylesheets."
[handler]
(apply-response-transformation handler :stylesheets add-stylesheet-nodes))
(defn add-javascript
"Updates the DOM with new <script> nodes to support imported JavaScript modules and JavaScript initializations."
[dom-nodes javascript]
(if (empty? javascript)
dom-nodes
(let [just-module-names (map first (filter #(= (count %) 1) javascript))
initializations (filter #(> (count %) 1) javascript)]
(->
dom-nodes
(extend-dom
[[[:html :head] :bottom]]
(markup
[:script {:src (classpath-asset "cascade/require-jquery.js")}]
[:script
"require.config({ baseUrl: '"
(build-client-url :classpath "")
"' });\n"
(if-not (empty? just-module-names)
(markup
"require(["
(->>
(map #(str \' % \') just-module-names)
(s2/join ", "))
"]);\n"))
(if-not (empty? initializations)
(markup
"require(['cascade/init'], function(module) {\n"
" module.pageInit("
(json/generate-string initializations) ");\n"
"});\n"))
]))))))
(defn wrap-import-javascript
"Middleware that handles imported JavaScript modules and JavaScript initialization."
[handler]
(apply-response-transformation handler :javascript add-javascript))
(defn wrap-imports
"Wraps a request-to-DOM-nodes handler with support for imports."
[handler]
(->
handler
wrap-import-javascript
wrap-import-stylesheets
wrap-setup-active-imports))
| 77474 | ;;; Copyright 2011 <NAME>
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");;;
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
;;; implied. See the License for the specific language governing permissions
;;; and limitations under the License.
(ns cascade.import
"Support for importing assets and JavaScript initialization code into the document, during the DOM rendering phase."
(:use
cascade
[cascade dom asset])
(:require
[clojure.string :as s2]
[clj-json.core :as json]))
(def ^{:dynamic true}
*active-imports*
"Stores a per-thread map used to track what's been imported."
nil)
(defn wrap-setup-active-imports [handler]
"Binds the *active-imports* var so that it may be updated by the downstream handlers."
(fn [req]
(binding [*active-imports* {:stylesheets [] :javascript []}]
(handler req))))
(defn add-if-not-present
[list value]
(if (contains? list value)
list
; Dependent on the list being a vector that conj-es at the end
(conj list value)))
(defn import-into-keyed-list
"Updates that map in *active-imports*, adding the value to the list storted under the
given key, if not already present. Returns nil."
[key value]
(set! *active-imports* (update-in *active-imports* [key] add-if-not-present value))
nil)
(defn import-stylesheet
"Imports a stylesheet for a CSS asset. The stylesheet may be specified as an asset. Alternately, a stylesheet factory
function and a path passed to that factory may be provided (which reads nicely). Returns nil."
; TODO: Naming and explicit ordering!
([stylesheet-asset]
(import-into-keyed-list :stylesheets stylesheet-asset))
([factory-fn asset-path]
(import-stylesheet (factory-fn asset-path))))
(defn import-module
"Imports a module by module name. Returns nil"
[module-name]
(import-into-keyed-list :javascript [module-name]))
(defn javascript
"Imports initialization JavaScript that will be executed when the page loads.
module-name
Name of module exposing the initialization function. The module should return a JavaScript object that maps names to functions.
initializer-fn-name
Name of a function exposed by the module that will be invoked.
arguments
Arguments passed to the client-side function. The arguments will be converted to JSON before being streamed to the client. Typically,
a single value (a string, or a JSON Object) is passed."
[module-name initializer-fn-name & arguments]
; TODO: this may change a bit when we implement Ajax partial rendering.
(import-into-keyed-list :javascript [module-name initializer-fn-name arguments]))
(defn javascript-invoke
"Builds a very particular kinds of call to the javascript function:
dependencies
List of RequireJS module dependencies necessary to invoke the function. These are typically dependencies that extend
jQuery.
selector
A CSS selector string passed to the jQuery main function.
function-name
Name of a jQuery function to invoke on the selection.
arguments
Arguments to pass to the jQuery function."
[dependencies selector function-name & arguments]
(apply javascript "cascade/init" "invoke" dependencies selector function-name arguments))
(defn to-element-node
"Converts an asset into a <link> element node."
[asset]
(element-node :link {:rel :stylesheet :type "text/css" :href asset} nil))
(defn add-stylesheet-nodes
[dom-nodes stylesheet-assets]
; TODO: optimize when no assets
(extend-dom dom-nodes [[[:html :head :script] :before]
[[:html :head :link] :before]
[[:html :head] :bottom]] (map to-element-node stylesheet-assets)))
(defn apply-response-transformation
[handler key transform-fn]
(fn [req]
(let [response (handler req)]
(and response
(update-in response [:body] transform-fn (*active-imports* key))))))
(defn wrap-import-stylesheets
"Middleware that expects the rendered body to be a seq of DOM nodes. The DOM nodes are
post-processed to add new <link> elements for any imported stylesheets."
[handler]
(apply-response-transformation handler :stylesheets add-stylesheet-nodes))
(defn add-javascript
"Updates the DOM with new <script> nodes to support imported JavaScript modules and JavaScript initializations."
[dom-nodes javascript]
(if (empty? javascript)
dom-nodes
(let [just-module-names (map first (filter #(= (count %) 1) javascript))
initializations (filter #(> (count %) 1) javascript)]
(->
dom-nodes
(extend-dom
[[[:html :head] :bottom]]
(markup
[:script {:src (classpath-asset "cascade/require-jquery.js")}]
[:script
"require.config({ baseUrl: '"
(build-client-url :classpath "")
"' });\n"
(if-not (empty? just-module-names)
(markup
"require(["
(->>
(map #(str \' % \') just-module-names)
(s2/join ", "))
"]);\n"))
(if-not (empty? initializations)
(markup
"require(['cascade/init'], function(module) {\n"
" module.pageInit("
(json/generate-string initializations) ");\n"
"});\n"))
]))))))
(defn wrap-import-javascript
"Middleware that handles imported JavaScript modules and JavaScript initialization."
[handler]
(apply-response-transformation handler :javascript add-javascript))
(defn wrap-imports
"Wraps a request-to-DOM-nodes handler with support for imports."
[handler]
(->
handler
wrap-import-javascript
wrap-import-stylesheets
wrap-setup-active-imports))
| true | ;;; Copyright 2011 PI:NAME:<NAME>END_PI
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");;;
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
;;; implied. See the License for the specific language governing permissions
;;; and limitations under the License.
(ns cascade.import
"Support for importing assets and JavaScript initialization code into the document, during the DOM rendering phase."
(:use
cascade
[cascade dom asset])
(:require
[clojure.string :as s2]
[clj-json.core :as json]))
(def ^{:dynamic true}
*active-imports*
"Stores a per-thread map used to track what's been imported."
nil)
(defn wrap-setup-active-imports [handler]
"Binds the *active-imports* var so that it may be updated by the downstream handlers."
(fn [req]
(binding [*active-imports* {:stylesheets [] :javascript []}]
(handler req))))
(defn add-if-not-present
[list value]
(if (contains? list value)
list
; Dependent on the list being a vector that conj-es at the end
(conj list value)))
(defn import-into-keyed-list
"Updates that map in *active-imports*, adding the value to the list storted under the
given key, if not already present. Returns nil."
[key value]
(set! *active-imports* (update-in *active-imports* [key] add-if-not-present value))
nil)
(defn import-stylesheet
"Imports a stylesheet for a CSS asset. The stylesheet may be specified as an asset. Alternately, a stylesheet factory
function and a path passed to that factory may be provided (which reads nicely). Returns nil."
; TODO: Naming and explicit ordering!
([stylesheet-asset]
(import-into-keyed-list :stylesheets stylesheet-asset))
([factory-fn asset-path]
(import-stylesheet (factory-fn asset-path))))
(defn import-module
"Imports a module by module name. Returns nil"
[module-name]
(import-into-keyed-list :javascript [module-name]))
(defn javascript
"Imports initialization JavaScript that will be executed when the page loads.
module-name
Name of module exposing the initialization function. The module should return a JavaScript object that maps names to functions.
initializer-fn-name
Name of a function exposed by the module that will be invoked.
arguments
Arguments passed to the client-side function. The arguments will be converted to JSON before being streamed to the client. Typically,
a single value (a string, or a JSON Object) is passed."
[module-name initializer-fn-name & arguments]
; TODO: this may change a bit when we implement Ajax partial rendering.
(import-into-keyed-list :javascript [module-name initializer-fn-name arguments]))
(defn javascript-invoke
"Builds a very particular kinds of call to the javascript function:
dependencies
List of RequireJS module dependencies necessary to invoke the function. These are typically dependencies that extend
jQuery.
selector
A CSS selector string passed to the jQuery main function.
function-name
Name of a jQuery function to invoke on the selection.
arguments
Arguments to pass to the jQuery function."
[dependencies selector function-name & arguments]
(apply javascript "cascade/init" "invoke" dependencies selector function-name arguments))
(defn to-element-node
"Converts an asset into a <link> element node."
[asset]
(element-node :link {:rel :stylesheet :type "text/css" :href asset} nil))
(defn add-stylesheet-nodes
[dom-nodes stylesheet-assets]
; TODO: optimize when no assets
(extend-dom dom-nodes [[[:html :head :script] :before]
[[:html :head :link] :before]
[[:html :head] :bottom]] (map to-element-node stylesheet-assets)))
(defn apply-response-transformation
[handler key transform-fn]
(fn [req]
(let [response (handler req)]
(and response
(update-in response [:body] transform-fn (*active-imports* key))))))
(defn wrap-import-stylesheets
"Middleware that expects the rendered body to be a seq of DOM nodes. The DOM nodes are
post-processed to add new <link> elements for any imported stylesheets."
[handler]
(apply-response-transformation handler :stylesheets add-stylesheet-nodes))
(defn add-javascript
"Updates the DOM with new <script> nodes to support imported JavaScript modules and JavaScript initializations."
[dom-nodes javascript]
(if (empty? javascript)
dom-nodes
(let [just-module-names (map first (filter #(= (count %) 1) javascript))
initializations (filter #(> (count %) 1) javascript)]
(->
dom-nodes
(extend-dom
[[[:html :head] :bottom]]
(markup
[:script {:src (classpath-asset "cascade/require-jquery.js")}]
[:script
"require.config({ baseUrl: '"
(build-client-url :classpath "")
"' });\n"
(if-not (empty? just-module-names)
(markup
"require(["
(->>
(map #(str \' % \') just-module-names)
(s2/join ", "))
"]);\n"))
(if-not (empty? initializations)
(markup
"require(['cascade/init'], function(module) {\n"
" module.pageInit("
(json/generate-string initializations) ");\n"
"});\n"))
]))))))
(defn wrap-import-javascript
"Middleware that handles imported JavaScript modules and JavaScript initialization."
[handler]
(apply-response-transformation handler :javascript add-javascript))
(defn wrap-imports
"Wraps a request-to-DOM-nodes handler with support for imports."
[handler]
(->
handler
wrap-import-javascript
wrap-import-stylesheets
wrap-setup-active-imports))
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.9998082518577576,
"start": 96,
"tag": "NAME",
"value": "Ragnar Svensson"
},
{
"context": "-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold License version 1.0 ",
"end": 129,
"score": 0.999816358089447,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
}
] | editor/test/dynamo/integration/override_test.clj | cmarincia/defold | 0 | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 Ragnar Svensson, Christian Murray
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns dynamo.integration.override-test
(:require [clojure.set :as set]
[clojure.test :refer :all]
[dynamo.graph :as g]
[dynamo.integration.override-test-support :as support]
[editor.defold-project :as project]
[editor.resource :as resource]
[editor.util :as util]
[integration.test-util :as test-util]
[internal.graph.types :as gt]
[internal.util]
[schema.core :as s]
[support.test-support :as ts])
(:import [javax.vecmath Vector3d]))
(g/defnode BaseNode
(property base-property g/Str))
(g/defnode MainNode
(inherits BaseNode)
(property a-property g/Str)
(property b-property g/Str)
(property virt-property g/Str
(value (g/fnk [a-property] a-property)))
(property dyn-property g/Str
(dynamic override? (g/fnk [_node-id _basis] (some? (g/override-original _basis _node-id)))))
(input sub-nodes g/NodeID :array :cascade-delete)
(output sub-nodes [g/NodeID] (g/fnk [sub-nodes] sub-nodes))
(output cached-output g/Str :cached (g/fnk [a-property] a-property))
(input cached-values g/Str :array)
(output cached-values [g/Str] :cached (g/fnk [cached-values] cached-values))
(output _properties g/Properties (g/fnk [_declared-properties]
(-> _declared-properties
(update :properties assoc :c-property (-> _declared-properties :properties :a-property))
(update :display-order conj :c-property)))))
(g/defnode SubNode
(property value g/Str))
(defn- override [node-id]
(-> (g/override node-id {})
ts/tx-nodes))
(defn- setup
([world]
(setup world 0))
([world count]
(let [nodes (ts/tx-nodes (g/make-nodes world [main [MainNode :a-property "main" :b-property "main"]
sub SubNode]
(g/connect sub :_node-id main :sub-nodes)))]
(loop [result [nodes]
counter count]
(if (> counter 0)
(recur (conj result (override (first (last result)))) (dec counter))
result)))))
(deftest test-sanity
(ts/with-clean-system
(let [[[main sub]] (setup world)]
(testing "Original graph connections"
(is (= [sub] (g/node-value main :sub-nodes)))))))
(deftest default-behaviour
(ts/with-clean-system
(let [[[main sub] [or-main or-sub]] (setup world 1)]
(testing "Connection is overridden from start"
(is (= [or-sub] (g/node-value or-main :sub-nodes)))
(is (= or-main (g/node-value or-main :_node-id))))
(testing "Using base values"
(doseq [label [:a-property :b-property :virt-property :cached-output]]
(is (= "main" (g/node-value or-main label)))))
(testing "Base node invalidates cache"
(g/transact (g/set-property main :a-property "new main"))
(is (= "new main" (g/node-value or-main :cached-output)))))))
(deftest property-dynamics
(ts/with-clean-system
(let [[[main sub] [or-main or-sub]] (setup world 1)]
(testing "Property dynamics"
(let [f (fn [n]
(let [p (g/node-value n :_declared-properties)]
(get-in p [:properties :dyn-property :override?])))]
(is (false? (f main)))
(is (true? (f or-main))))))))
(deftest delete
(ts/with-clean-system
(let [[[main sub] [or-main or-sub]] (setup world 1)]
(testing "Overrides can be removed"
(g/transact (g/delete-node or-main))
(doseq [nid [or-main or-sub]]
(is (nil? (g/node-by-id nid))))
(is (empty? (g/overrides main)))))
(let [[[main sub] [or-main or-sub]] (setup world 1)]
(testing "Overrides are removed with base"
(g/transact (g/delete-node main))
(doseq [nid [main sub or-main or-sub]]
(is (nil? (g/node-by-id nid))))
(is (empty? (g/overrides main)))))
(let [[[main sub] [or-main or-sub] [or2-main or2-sub]] (setup world 2)]
(testing "Delete hierarchy"
(g/transact (g/delete-node main))
(doseq [nid [main sub or-main or-sub or2-main or2-sub]]
(is (nil? (g/node-by-id nid))))
(is (empty? (g/overrides main)))))
(let [[[main sub] [or-main or-sub]] (setup world 1)
[stray] (ts/tx-nodes (g/make-nodes world
[stray BaseNode]
(g/connect stray :_node-id or-main :sub-nodes)))]
(testing "Delete stray node attached to override :cascade-delete"
(g/transact (g/delete-node main))
(doseq [nid [main sub or-main or-sub stray]]
(is (nil? (g/node-by-id nid))))
(is (empty? (g/overrides main)))))))
(deftest override-property
(ts/with-clean-system
(let [[[main sub] [or-main or-sub]] (setup world 1)]
(testing "Overriding property"
(g/transact (g/set-property or-main :a-property "overridden main"))
(is (= "overridden main" (g/node-value or-main :a-property)))
(is (= "main" (g/node-value main :a-property)))
(doseq [label [:_properties :_declared-properties]
:let [props (-> (g/node-value or-main label) (get :properties))
a-p (:a-property props)
b-p (:b-property props)]]
(is (= "overridden main" (:value a-p)))
(is (= "main" (:original-value a-p)))
(is (= or-main (:node-id a-p)))
(is (= "main" (:value b-p)))
(is (= false (contains? b-p :original-value)))
(is (= or-main (:node-id b-p)))))
(testing "Virtual property"
(is (= "overridden main" (g/node-value or-main :virt-property))))
(testing "Output production"
(is (= "overridden main" (g/node-value or-main :cached-output)))
(is (= "main" (g/node-value main :cached-output))))
(testing "Clearing property"
(g/transact (g/clear-property or-main :a-property))
(is (= "main" (g/node-value or-main :a-property)))
(is (= "main" (g/node-value or-main :virt-property)))
(is (= "main" (g/node-value or-main :cached-output))))
(testing "Update property"
(g/transact (g/update-property or-main :a-property (fn [prop] (str prop "_changed"))))
(is (= "main_changed" (g/node-value or-main :a-property)))))))
(deftest inherited-property
(ts/with-clean-system
(let [prop :base-property
[main or-main] (ts/tx-nodes (g/make-nodes world [main [MainNode prop "inherited"]]
(g/override main {})))]
(is (= "inherited" (g/node-value or-main prop))))))
(deftest new-node-created
(ts/with-clean-system
(let [[main or-main sub] (ts/tx-nodes (g/make-nodes world [main MainNode]
(g/override main {})
(g/make-nodes world [sub SubNode]
(g/connect sub :_node-id main :sub-nodes))))]
(let [sub-nodes (g/node-value or-main :sub-nodes)]
(is (= 1 (count sub-nodes)))
(is (not= [sub] sub-nodes)))
(g/transact (g/disconnect sub :_node-id main :sub-nodes))
(is (empty? (g/node-value or-main :sub-nodes))))))
(deftest new-node-created-cache-invalidation
(ts/with-clean-system
(let [[main or-main] (ts/tx-nodes (g/make-nodes world [main MainNode]
(g/override main {})))
_ (is (= [] (g/node-value or-main :cached-values)))
[sub] (ts/tx-nodes (g/make-nodes world [sub [SubNode :value "sub"]]
(for [[from to] [[:_node-id :sub-nodes]
[:value :cached-values]]]
(g/connect sub from main to))))]
(is (= ["sub"] (g/node-value or-main :cached-values)))
(g/transact (concat
(g/disconnect sub :_node-id main :sub-nodes)
(g/disconnect sub :value main :cached-values)))
(is (= [] (g/node-value or-main :cached-values))))))
(g/defnode DetectCacheInvalidation
(property invalid-cache g/Any)
(input value g/Str :cascade-delete)
(output cached-value g/Str :cached (g/fnk [value invalid-cache]
(swap! invalid-cache inc)
value)))
(deftest inherit-targets []
(testing "missing override"
(ts/with-clean-system
(let [[main cache-node or-main] (ts/tx-nodes (g/make-nodes world [main [SubNode :value "test"]
cache [DetectCacheInvalidation :invalid-cache (atom 0)]]
(g/connect main :value cache :value)
(g/override main {})))]
(is (= cache-node (ffirst (g/targets-of main :value))))
(is (empty? (g/targets-of or-main :value))))))
(testing "existing override"
(ts/with-clean-system
(let [[main cache-node] (ts/tx-nodes (g/make-nodes world [main [SubNode :value "test"]
cache [DetectCacheInvalidation :invalid-cache (atom 0)]]
(g/connect main :value cache :value)))
[or-cache-node or-main] (ts/tx-nodes (g/override cache-node {}))]
(is (= cache-node (ffirst (g/targets-of main :value))))
(is (= or-cache-node (ffirst (g/targets-of or-main :value))))))))
(g/defnode StringInput
(input value g/Str :cascade-delete))
(deftest inherit-sources []
(testing "missing override"
;; After making g/override perform the bulk of its work in the
;; transaction step (after the g/connect has happened/is
;; observable) this test is less relevant.
(ts/with-clean-system
(let [[main cache-node or-main] (ts/tx-nodes (g/make-nodes world [main StringInput
cache [DetectCacheInvalidation :invalid-cache (atom 0)]]
(g/connect cache :cached-value main :value)
(g/override main {:traverse? (constantly false)})))]
(is (= cache-node (ffirst (g/sources-of main :value))))
(is (= cache-node (ffirst (g/sources-of or-main :value)))))))
(testing "existing override"
(ts/with-clean-system
(let [[main cache-node] (ts/tx-nodes (g/make-nodes world [main StringInput
cache [DetectCacheInvalidation :invalid-cache (atom 0)]]
(g/connect cache :cached-value main :value)))
[or-main or-cache-node] (ts/tx-nodes (g/override cache-node {}))]
(is (= cache-node (ffirst (g/sources-of main :value))))
(is (= or-cache-node (ffirst (g/sources-of or-main :value))))))))
(deftest lonely-override-leaves-cache []
(ts/with-clean-system
(let [[main cache-node or-main] (ts/tx-nodes (g/make-nodes world [main [SubNode :value "test"]
cache [DetectCacheInvalidation :invalid-cache (atom 0)]]
(g/connect main :value cache :value)
(g/override main {})))]
(is (= 0 @(g/node-value cache-node :invalid-cache)))
(is (= "test" (g/node-value cache-node :cached-value)))
(is (= 1 @(g/node-value cache-node :invalid-cache)))
(is (= "test" (g/node-value cache-node :cached-value)))
(is (= 1 @(g/node-value cache-node :invalid-cache)))
(g/transact (g/set-property or-main :value "override"))
(is (= 1 @(g/node-value cache-node :invalid-cache))))))
(deftest multi-override
(ts/with-clean-system
(let [[[main sub]
[or-main or-sub]
[or2-main or2-sub]] (setup world 2)]
(testing "basic default behaviour"
(is (= "main" (g/node-value or2-main :a-property))))
(testing "cache-invalidation in multiple overrides"
(g/transact (g/set-property main :a-property "new main"))
(is (= "new main" (g/node-value or2-main :a-property))))
(testing "override one below overrides"
(g/transact (g/set-property or-main :a-property "main2"))
(is (= "main2" (g/node-value or2-main :a-property))))
(testing "top level override"
(g/transact (g/set-property or2-main :a-property "main3"))
(is (= "main3" (g/node-value or2-main :a-property)))))))
(defn- prop-map-value
[node prop-kw]
(-> node (g/node-value :_properties) :properties prop-kw :value))
(defn- prop-map-original-value
[node prop-kw]
(-> node (g/node-value :_properties) :properties prop-kw :original-value))
(deftest multi-override-with-dynamic-properties
(testing "property value is propagated through all override nodes"
(ts/with-clean-system
(let [[[main sub]
[or1-main or1-sub]
[or2-main or2-sub]
[or3-main or3-sub]] (setup world 3)]
(is (every? #(= "main" (prop-map-value % :a-property)) [main or1-main or2-main or3-main]))
(is (every? #(= "main" (prop-map-value % :c-property)) [main or1-main or2-main or3-main]))
(g/set-property! or1-main :a-property "a")
(is (= "main" (prop-map-value main :a-property)))
(is (= "a" (prop-map-value or1-main :a-property)))
(is (= "main" (prop-map-original-value or1-main :a-property)))
(is (= "a" (prop-map-value or2-main :a-property)))
(is (= nil (prop-map-original-value or2-main :a-property)))
(is (= "a" (prop-map-value or3-main :a-property)))
(is (= nil (prop-map-original-value or3-main :a-property)))
(g/set-property! or2-main :a-property "b")
(is (= "main" (prop-map-value main :a-property)))
(is (= "a" (prop-map-value or1-main :a-property)))
(is (= "main" (prop-map-original-value or1-main :a-property)))
(is (= "b" (prop-map-value or2-main :a-property)))
(is (= "a" (prop-map-original-value or2-main :a-property)))
(is (= "b" (prop-map-value or3-main :a-property)))
(is (= nil (prop-map-original-value or3-main :a-property)))
(g/clear-property! or1-main :a-property)
(g/clear-property! or2-main :a-property)
(g/set-property! or1-main :c-property "c")
(is (= "main" (prop-map-value main :c-property)))
(is (= "c" (prop-map-value or1-main :c-property)))
(is (= "main" (prop-map-original-value or1-main :c-property)))
(is (= "c" (prop-map-value or2-main :c-property)))
(is (= nil (prop-map-original-value or2-main :c-property)))
(is (= "c" (prop-map-value or3-main :c-property)))
(is (= nil (prop-map-original-value or3-main :c-property)))
(g/set-property! or2-main :c-property "d")
(is (= "main" (prop-map-value main :c-property)))
(is (= "c" (prop-map-value or1-main :c-property)))
(is (= "main" (prop-map-original-value or1-main :c-property)))
(is (= "d" (prop-map-value or2-main :c-property)))
(is (= "c" (prop-map-original-value or2-main :c-property)))
(is (= "d" (prop-map-value or3-main :c-property)))
(is (= nil (prop-map-original-value or3-main :c-property)))))))
(deftest mark-defective
(ts/with-clean-system
(let [[[main sub]
[or-main or-sub]] (setup world 1)]
(testing "defective base"
(let [error (g/error-fatal "Something went wrong" {:type :some-error})]
(g/transact
(g/mark-defective main error))
(is (g/error? (g/node-value or-main :a-property))))))
(let [[[main sub]
[or-main or-sub]] (setup world 1)]
(testing "defective override, which throws exception"
(let [error (g/error-fatal "Something went wrong" {:type :some-error})]
(is (thrown? Exception (g/transact
(g/mark-defective or-main error)))))))))
(deftest copy-paste
(ts/with-clean-system
(let [[[main sub]
[or-main or-sub]] (setup world 1)]
(g/transact (g/set-property or-main :a-property "override"))
(let [fragment (g/copy [or-main] {:traverse? (constantly true)})
paste-data (g/paste (g/node-id->graph-id or-main) fragment {})
copy-id (first (:root-node-ids paste-data))]
(g/transact (:tx-data paste-data))
(is (= "override" (g/node-value copy-id :a-property)))))))
(g/defnode ExternalNode
(property value g/Keyword))
(g/defnode ResourceNode
(property reference g/Keyword
(value (g/fnk [in-reference] in-reference))
(set (fn [evaluation-context node-id old-value new-value]
(concat
(g/disconnect-sources (:basis evaluation-context) node-id :in-reference)
(let [gid (g/node-id->graph-id node-id)
node-store (g/graph-value gid :node-store)
src-id (get node-store new-value)]
(if src-id
(g/connect src-id :value node-id :in-reference)
[]))))))
(input in-reference g/Keyword))
(deftest connection-property
(ts/with-clean-system
(let [[res a b] (ts/tx-nodes (g/make-nodes world [res ResourceNode
a [ExternalNode :value :node-a]
b [ExternalNode :value :node-b]]
(g/set-graph-value world :node-store {:node-a a :node-b b})))]
(testing "linking through property setter"
(g/transact (g/set-property res :reference :node-a))
(is (= :node-a (g/node-value res :reference)))
(g/transact (g/set-property a :value :node-a2))
(is (= :node-a2 (g/node-value res :reference))))
(let [or-res (first (override res))]
(testing "override inherits the connection"
(is (= :node-a2 (g/node-value or-res :reference))))
(testing "override the actual connection"
(g/transact (g/set-property or-res :reference :node-b))
(is (= :node-b (g/node-value or-res :reference))))
(testing "clearing the property"
(g/transact (g/clear-property or-res :reference))
(is (= :node-a2 (g/node-value or-res :reference))))))))
(g/deftype ^:private IDMap {s/Str s/Int})
(defprotocol Resource
(path [this]))
(defrecord PathResource [path]
Resource
(path [this] path))
(defn properties->overrides [id properties]
{id (->> (:properties properties)
(filter (fn [[k v]] (contains? v :original-value)))
(map (fn [[k v]] [k (:value v)]))
(into {}))})
(g/defnode Node
(property id g/Str)
(input id-prefix g/Str)
(output id g/Str (g/fnk [id-prefix id] (str id-prefix id)))
(output node-ids IDMap (g/fnk [_node-id id] {id _node-id}))
(output node-overrides g/Any (g/fnk [id _properties] (properties->overrides id _properties))))
(g/defnode VisualNode
(inherits Node)
(property value g/Str))
(g/defnode SceneResourceNode
(property resource Resource :unjammable))
(g/defnode NodeTree
(input nodes g/NodeID :array :cascade-delete)
(input node-ids IDMap :array)
(input node-overrides g/Any :array)
(input id-prefix g/Str)
(output id-prefix g/Str (g/fnk [id-prefix] id-prefix))
(output node-ids IDMap :cached (g/fnk [node-ids] (reduce into {} node-ids)))
(output node-overrides g/Any :cached (g/fnk [node-overrides]
(reduce into {} node-overrides))))
(g/defnode Scene
(inherits SceneResourceNode)
(input node-tree g/NodeID :cascade-delete)
(input layouts g/NodeID :array :cascade-delete)
(input id-prefix g/Str)
(output id-prefix g/Str (g/fnk [id-prefix] id-prefix))
(input node-ids IDMap)
(output node-ids IDMap (g/fnk [node-ids] node-ids))
(input node-overrides g/Any)
(output node-overrides g/Any (g/fnk [node-overrides] node-overrides)))
(defn- scene-by-path
([graph path]
(scene-by-path (g/now) graph path))
([basis graph path]
(let [resources (or (g/graph-value basis graph :resources) {})]
(get resources (->PathResource path)))))
(g/defnode Template
(inherits Node)
(property template g/Any
(value (g/fnk [template-resource source-overrides]
{:resource template-resource :overrides source-overrides}))
(set (fn [evaluation-context self old-value new-value]
(let [basis (:basis evaluation-context)
current-scene (g/node-feeding-into basis self :template-resource)]
(concat
(if current-scene
(g/delete-node current-scene)
[])
(let [gid (g/node-id->graph-id self)
path (:path new-value)]
(if-let [scene (scene-by-path basis gid path)]
(let [tmpl-path (g/node-value self :template-path evaluation-context)
properties-by-node-id (comp (or (:overrides new-value) {})
(into {} (map (fn [[k v]] [v (str tmpl-path k)]))
(g/node-value scene :node-ids evaluation-context)))]
(g/override scene {:properties-by-node-id properties-by-node-id}
(fn [evaluation-context id-mapping]
(let [or-scene (id-mapping scene)]
(concat
(for [[from to] [[:node-ids :node-ids]
[:node-overrides :source-overrides]
[:resource :template-resource]]]
(g/connect or-scene from self to))
(g/connect self :template-path or-scene :id-prefix))))))
[])))))))
(input template-resource Resource :cascade-delete)
(input node-ids IDMap)
(input instance g/NodeID)
(input source-overrides g/Any)
(output template-path g/Str (g/fnk [id] (str id "/")))
(output node-overrides g/Any :cached (g/fnk [id _properties source-overrides]
(merge (properties->overrides id _properties) source-overrides)))
(output node-ids IDMap (g/fnk [_node-id id node-ids] (into {id _node-id} node-ids))))
(g/defnode Layout
(property name g/Str)
(property nodes g/Any
(set (fn [evaluation-context self _ new-value]
(let [basis (:basis evaluation-context)
current-tree (g/node-feeding-into basis self :node-tree)]
(concat
(if current-tree
(g/delete-node current-tree)
[])
(let [scene (ffirst (g/targets-of basis self :_node-id))
node-tree (g/node-value scene :node-tree evaluation-context)]
(g/override node-tree {}
(fn [evaluation-context id-mapping]
(let [node-tree-or (id-mapping node-tree)]
(for [[from to] [[:_node-id :node-tree]]]
(g/connect node-tree-or from self to)))))))))))
(input node-tree g/NodeID :cascade-delete)
(input id-prefix g/Str))
(def ^:private node-tree-inputs [[:_node-id :nodes]
[:node-ids :node-ids]
[:node-overrides :node-overrides]])
(def ^:private node-tree-outputs [[:id-prefix :id-prefix]])
(defn- add-node [graph scene node-tree node-type props]
(g/make-nodes graph [n [node-type props]]
(for [[output input] node-tree-inputs]
(g/connect n output node-tree input))
(for [[output input] node-tree-outputs]
(g/connect node-tree output n input))))
(defn- add-layout [graph scene name]
(g/make-nodes graph [n [Layout :name name]]
(g/connect n :_node-id scene :layouts)
(g/connect scene :id-prefix n :id-prefix)
(g/set-property n :nodes {})))
(defn- load-scene [graph path nodes]
(let [resource (->PathResource path)]
(g/make-nodes graph [scene [Scene :resource resource]
node-tree [NodeTree]]
(for [[from to] [[:_node-id :node-tree]
[:node-ids :node-ids]
[:node-overrides :node-overrides]]]
(g/connect node-tree from scene to))
(for [[from to] [[:id-prefix :id-prefix]]]
(g/connect scene from node-tree to))
(g/update-graph-value graph :resources assoc resource scene)
(reduce (fn [tx [node-type props]]
(into tx (add-node graph scene node-tree node-type props)))
[] nodes))))
(defn- make-scene! [graph path nodes]
(when (nil? (g/graph-value graph :resources))
(g/set-graph-value! graph :resources {}))
(ts/tx-nodes (load-scene graph path nodes)))
(defn- has-node? [scene node-id]
(contains? (g/node-value scene :node-ids) node-id))
(defn- node-by-id [scene node-id]
(get (g/node-value scene :node-ids) node-id))
(defn- target [n label]
(ffirst (g/targets-of n label)))
(deftest scene-loading
(ts/with-clean-system
(let [[scene _ node] (make-scene! world "my-scene" [[VisualNode {:id "my-node" :value "initial"}]])
overrides {"my-template/my-node" {:value "new value"}}
[super-scene _ template] (make-scene! world "my-super-scene" [[Template {:id "my-template" :template {:path "my-scene" :overrides overrides}}]])]
(is (= "initial" (g/node-value node :value)))
(let [or-node (get (g/node-value template :node-ids) "my-template/my-node")]
(is (= "new value" (g/node-value or-node :value))))
(is (= overrides (select-keys (g/node-value template :node-overrides) (keys overrides)))))))
(deftest scene-loading-with-override-values
(ts/with-clean-system
(let [scene-overrides {"template/my-node" {:value "scene-override"}}
super-overrides {"super-template/template/my-node" {:value "super-override"}}]
(g/transact (concat
(load-scene world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
(load-scene world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides scene-overrides}}]])
(load-scene world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides super-overrides}}]])))
(doseq [[actual expected] (mapv (fn [[s-path id expected]] [(-> s-path
(->> (scene-by-path world))
(node-by-id id)
(g/node-value :node-overrides))
expected])
[["scene" "template" scene-overrides]
["super-scene" "super-template" super-overrides]])]
(is (= expected (select-keys actual (keys expected))))))))
(deftest hierarchical-ids
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])]
(is (has-node? sub-scene "my-node"))
(is (has-node? scene "template/my-node"))
(is (has-node? super-scene "super-template/template/my-node"))
(let [tmp (node-by-id super-scene "super-template/template")]
(g/transact (g/set-property sub-scene :resource (->PathResource "sub-scene2")))
(is (= "sub-scene2" (get-in (g/node-value tmp :template) [:resource :path])))))))
(deftest delete-middle
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])
middle (node-by-id scene "template")
super-middle (node-by-id super-scene "super-template/template")]
(is (has-node? super-scene "super-template/template"))
(g/transact (g/delete-node middle))
(is (not (has-node? super-scene "super-template/template")))
(is (nil? (g/node-by-id super-middle))))))
(deftest sibling-templates
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]
[Template {:id "template1" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])]
(is (has-node? scene "template/my-node"))
(is (has-node? scene "template1/my-node"))
(is (has-node? super-scene "super-template/template/my-node"))
(is (has-node? super-scene "super-template/template1/my-node")))))
(deftest new-sibling-delete-repeat
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene scene-tree] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])]
(dotimes [i 5]
(let [[new-tmpl] (ts/tx-nodes (add-node world scene scene-tree Template {:id "new-template" :template {:path "sub-scene" :overrides {}}}))]
(is (contains? (g/node-value (node-by-id scene "new-template") :node-overrides) "new-template/my-node"))
(g/transact (g/delete-node new-tmpl)))))))
(deftest change-override
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])
[sub-scene2] (make-scene! world "sub-scene2" [[VisualNode {:id "my-node2" :value ""}]])]
(g/transact (g/transfer-overrides {sub-scene sub-scene2}))
(is (empty? (g/overrides sub-scene)))
(is (has-node? super-scene "super-template/template/my-node2")))))
(deftest new-node-deep-override
(ts/with-clean-system
(let [[sub-scene sub-tree] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])
[super-super-scene] (make-scene! world "super-super-scene" [[Template {:id "super-super-template" :template {:path "super-scene" :overrides {}}}]])]
(g/transact (add-node world sub-scene sub-tree VisualNode {:id "my-node2"}))
(is (has-node? super-super-scene "super-super-template/super-template/template/my-node2")))))
;; Bug occurring in properties in overloads
(deftest scene-paths
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])
template (node-by-id super-scene "super-template/template")
or-scene (ffirst (g/sources-of template :template-resource))]
(is (= "sub-scene" (:path (g/node-value (g/override-original or-scene) :resource)))))))
;; Simulated layout problem
(deftest template-layouts
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[sub-layout] (ts/tx-nodes (add-layout world sub-scene "Portrait"))]
(is (nil? (g/node-value sub-layout :id-prefix)))
(is (not (nil? (g/node-value (first (g/overrides sub-layout)) :id-prefix)))))))
;; User-defined dynamic properties
(g/defnode Script
(property script-properties g/Any)
(output _properties g/Properties :cached (g/fnk [_node-id _declared-properties script-properties]
(-> _declared-properties
(update :properties dissoc :script-properties)
(update :properties merge (into {} (map (fn [[key value]] [key {:value value
:type (type value)
:node-id _node-id}]) script-properties)))
(update :display-order (comp vec (partial remove #{:script-properties})))))))
(g/defnode Component
(property id g/Str)
(property component g/Any
(set (fn [evaluation-context self old-value new-value]
(let [basis (:basis evaluation-context)]
(concat
(if-let [instance (g/node-value self :instance evaluation-context)]
(g/delete-node instance)
[])
(let [gid (g/node-id->graph-id self)
path (:path new-value)]
(if-let [script (get (g/graph-value basis gid :resources) path)]
(g/override script {}
(fn [evaluation-context id-mapping]
(let [or-script (id-mapping script)
script-props (g/node-value script :_properties evaluation-context)
set-prop-data (for [[key value] (:overrides new-value)]
(g/set-property or-script key value))
conn-data (for [[src tgt] [[:_node-id :instance]
[:_properties :script-properties]]]
(g/connect or-script src self tgt))]
(concat set-prop-data conn-data))))
[])))))))
(input instance g/NodeID :cascade-delete)
(input script-properties g/Properties)
(output _properties g/Properties (g/fnk [_declared-properties script-properties]
(-> _declared-properties
(update :properties merge (:properties script-properties))
(update :display-order concat (:display-order script-properties))))))
(deftest custom-properties
(ts/with-clean-system
(let [[script comp] (ts/tx-nodes (g/make-nodes world [script [Script :script-properties {:speed 0}]]
(g/set-graph-value world :resources {"script.script" script}))
(g/make-nodes world [comp [Component :component {:path "script.script" :overrides {:speed 10}}]]))]
(let [p (get-in (g/node-value comp :_properties) [:properties :speed])]
(is (= 10 (:value p)))
(is (= 0 (:original-value p)))
(g/transact (g/set-property (:node-id p) :speed 20))
(let [p' (get-in (g/node-value comp :_properties) [:properties :speed])]
(is (= 20 (:value p')))
(is (= 0 (:original-value p'))))
(g/transact (g/clear-property (:node-id p) :speed))
(let [p' (get-in (g/node-value comp :_properties) [:properties :speed])]
(is (= 0 (:value p')))
(is (not (contains? p' :original-value))))))))
;; Overloaded outputs with different types
(g/deftype XYZ [(s/one s/Num "x") (s/one s/Num "y") (s/one s/Num "z")])
(g/deftype Complex {s/Keyword Vector3d})
(g/defnode TypedOutputNode
(property value XYZ)
(output value Vector3d (g/fnk [value] (let [[x y z] value] (Vector3d. x y z))))
(output complex Complex (g/fnk [value] {:value value})))
(deftest overloaded-outputs-and-types
(ts/with-clean-system
(let [[a b] (ts/tx-nodes (g/make-nodes world [n [TypedOutputNode :value [1 2 3]]]
(g/override n)))]
(g/transact (g/set-property b :value [2 3 4]))
(is (not= (g/node-value b :complex) (g/node-value a :complex))))))
;; Dynamic property production
(g/defnode IDNode
(input super-id g/Str)
(property id g/Str (value (g/fnk [_node-id super-id id] (if super-id (str super-id "/" id) id)))))
(deftest dynamic-id-in-properties
(ts/with-clean-system
(let [[node parent sub] (ts/tx-nodes (g/make-nodes world [node [IDNode :id "child-id"]
parent [IDNode :id "parent-id"]]
(g/override node {}
(fn [evaluation-context id-mapping]
(let [or-node (id-mapping node)]
(g/connect parent :id or-node :super-id))))))]
(is (= (g/node-value sub :id)
(get-in (g/node-value sub :_declared-properties) [:properties :id :value]))))))
;; Reload supported for overrides
(deftest reload-overrides
(ts/with-clean-system
(let [[node or-node] (ts/tx-nodes (g/make-nodes world [node [support/ReloadNode :my-value "reload-test"]]
(g/override node)))]
(g/transact (g/set-property or-node :my-value "new-value"))
(is (= "new-value" (get-in (g/node-value or-node :_properties) [:properties :my-value :value])))
(use 'dynamo.integration.override-test-support :reload)
(is (= "new-value" (get-in (g/node-value or-node :_properties) [:properties :my-value :value]))))))
;; Dependency rules
(defn- outs [nodes output]
(for [n nodes]
[n output]))
(defn- conn? [[src src-label tgt tgt-label]]
(let [basis (g/now)]
(and (g/connected? basis src src-label tgt tgt-label)
(contains? (into #{} (gt/sources basis tgt tgt-label)) [src src-label])
(contains? (into #{} (gt/targets basis src src-label)) [tgt tgt-label]))))
(defn- no-conn? [[src src-label tgt tgt-label]]
(let [basis (g/now)]
(and (not (g/connected? basis src src-label tgt tgt-label))
(not (contains? (into #{} (gt/sources basis tgt tgt-label)) [src src-label]))
(not (contains? (into #{} (gt/targets basis src src-label)) [tgt tgt-label])))))
(defn- deps [tgts]
(ts/graph-dependencies tgts))
(g/defnode TargetNode
(input in-value g/Str)
(output out-value g/Str (g/fnk [in-value] in-value)))
(deftest dep-rules
(ts/with-clean-system
(let [all (setup world 2)
[[main-0 sub-0]
[main-1 sub-1]
[main-2 sub-2]] all
mains (mapv first all)
subs (mapv second all)]
(testing "value fnk"
(is (every? (deps [[main-0 :a-property]]) (outs mains :virt-property))))
(testing "output"
(is (every? (deps [[main-0 :a-property]]) (outs mains :cached-output))))
(testing "connections"
(is (every? conn? (for [[m s] all]
[s :_node-id m :sub-nodes])))
(is (every? no-conn? (for [mi (range 3)
si (range 3)
:when (not= mi si)
:let [m (nth mains mi)
s (nth subs si)]]
[s :_node-id m :sub-nodes]))))))
(ts/with-clean-system
(let [[src tgt src-1] (ts/tx-nodes (g/make-nodes world [src [MainNode :a-property "reload-test"]
tgt TargetNode]
(g/connect src :a-property tgt :in-value)
(g/override src)))]
(testing "regular dep"
(is (every? (deps [[src :a-property]]) [[tgt :out-value]])))
(testing "no override deps"
(is (not-any? (deps [[src-1 :a-property]]) [[tgt :out-value]])))
(testing "connections"
(is (conn? [src :a-property tgt :in-value]))
(is (no-conn? [src-1 :a-property tgt :in-value])))))
(ts/with-clean-system
(let [[src tgt tgt-1] (ts/tx-nodes (g/make-nodes world [src [MainNode :a-property "reload-test"]
tgt TargetNode]
(g/connect src :a-property tgt :in-value)
(g/override tgt)))]
(testing "regular dep"
(is (every? (deps [[src :a-property]]) [[tgt :out-value] [tgt-1 :out-value]])))
(testing "connections"
(is (conn? [src :a-property tgt :in-value]))
(is (conn? [src :a-property tgt-1 :in-value])))))
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]
[Template {:id "template1" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])
[tmpl-scene tmpl1-scene] (g/overrides sub-scene)
[tmpl-tree tmpl1-tree] (mapv #(g/node-value % :node-tree) [tmpl-scene tmpl1-scene])
[tmpl-sub tmpl1-sub] (mapv #(node-by-id scene %) ["template/my-node" "template1/my-node"])]
(is (conn? [tmpl-sub :node-overrides tmpl-tree :node-overrides]))
(is (conn? [tmpl1-sub :node-overrides tmpl1-tree :node-overrides]))
(is (conn? [tmpl-tree :node-overrides tmpl-scene :node-overrides]))
(is (conn? [tmpl1-tree :node-overrides tmpl1-scene :node-overrides])))))
(g/defnode GameObject
(input components g/NodeID :array :cascade-delete))
(g/defnode GameObjectInstance
(input source g/NodeID :cascade-delete))
(g/defnode Collection
(input instances g/NodeID :array :cascade-delete))
(deftest override-created-on-connect
(ts/with-clean-system
(let [[script] (ts/tx-nodes (g/make-nodes world [script Script]))
[go comp or-script] (ts/tx-nodes (g/make-nodes world [go GameObject
comp Component]
(g/override script {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-script (id-mapping script)]
(concat
(g/connect comp :_node-id go :components)
(g/connect or-script :_node-id comp :instance)))))))
[coll inst or-go] (ts/tx-nodes (g/make-nodes world [coll Collection
inst GameObjectInstance]
(g/override go {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-go (id-mapping go)]
(concat
(g/connect inst :_node-id coll :instances)
(g/connect or-go :_node-id inst :source)))))))
[comp-2 or-script-2] (ts/tx-nodes (g/make-nodes world [comp Component]
(g/override script {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-script (id-mapping script)]
(g/connect or-script :_node-id comp :instance))))))
nodes-on-connect (ts/tx-nodes (g/connect comp-2 :_node-id go :components))]
;; 1 override for the component node and one for the script, w.r.t the collection
(is (= 2 (count nodes-on-connect))))))
(deftest cascade-delete-avoided
(ts/with-clean-system
(let [[script] (ts/tx-nodes (g/make-nodes world [script Script]))
[go comp or-script] (ts/tx-nodes (g/make-nodes world [go GameObject
comp Component]
(g/override script {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-script (id-mapping script)]
(concat
(g/connect comp :_node-id go :components)
(g/connect or-script :_node-id comp :instance)))))))
[coll inst or-go] (ts/tx-nodes (g/make-nodes world [coll Collection
inst GameObjectInstance]
(g/override go {:traverse? (constantly false)}
(fn [evaluation-context id-mapping]
(let [or-go (id-mapping go)]
(concat
(g/connect inst :_node-id coll :instances)
(g/connect or-go :_node-id inst :source)))))))]
(is (every? some? (map g/node-by-id [coll inst or-go go comp or-script script])))
(g/transact (g/delete-node coll))
(is (every? nil? (map g/node-by-id [coll inst or-go])))
(is (every? some? (map g/node-by-id [go comp or-script script])))
(g/transact (g/delete-node go))
(is (every? nil? (map g/node-by-id [coll inst or-go go comp or-script])))
(is (every? some? (map g/node-by-id [script])))
(g/transact (g/delete-node script))
(is (every? nil? (map g/node-by-id [coll inst or-go go comp or-script script]))))))
(deftest auto-add-and-delete
(ts/with-clean-system
(let [[script] (ts/tx-nodes (g/make-nodes world [script Script]))
[go] (ts/tx-nodes (g/make-nodes world [go GameObject]))
[[coll0 go-inst0 or-go0]
[coll1 go-inst1 or-go1]] (for [i (range 2)]
(ts/tx-nodes (g/make-nodes world [coll Collection
go-inst GameObjectInstance]
(g/connect go-inst :_node-id coll :instances)
(g/override go {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-go (id-mapping go)]
(g/connect or-go :_node-id go-inst :source)))))))
[comp or-script] (ts/tx-nodes (g/make-nodes world [comp Component]
(g/override script {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-script (id-mapping script)]
(concat
(g/connect or-script :_node-id comp :instance)
(g/connect comp :_node-id go :components)))))))]
(let [all-script-nodes (doall (tree-seq (constantly true) g/overrides script))]
(is (= 4 (count all-script-nodes)))
(g/transact (g/delete-node comp))
(is (= 1 (count (keep g/node-by-id all-script-nodes))))
(is (empty? (mapcat g/overrides all-script-nodes)))))))
(defn- remove-idx [v ix]
(into (subvec v 0 ix) (subvec v (inc ix))))
(defn- all-system-nodes []
(into []
(mapcat #(keys (:nodes (second %))))
(:graphs @g/*the-system*)))
(deftest symmetric-input-output-arcs
(test-util/with-loaded-project "test/resources/override_project"
(let [all-nodes (all-system-nodes)
node-outputs (reduce (fn [result n]
(reduce (fn [result label]
(assoc-in result [n label] (vec (g/labelled-outputs n label))))
result
(g/output-labels (g/node-type* n))))
{}
all-nodes)
node-inputs (reduce (fn [result n]
(reduce (fn [result label]
(assoc-in result [n label] (vec (g/labelled-inputs n label))))
result
(g/input-labels (g/node-type* n))))
{}
all-nodes)]
(testing "outputs and labelled-outputs report the same arcs, and same cardinality of arcs"
(doseq [node all-nodes]
(let [outputs (g/outputs node)
outputs-freqs (frequencies outputs)
merged-outputs (into [] cat (vals (node-outputs node)))
merged-outputs-freqs (frequencies merged-outputs)
freq-diff [:all-merged (not-empty (set/difference (set outputs-freqs) (set merged-outputs-freqs)))
:merged-all (not-empty (set/difference (set merged-outputs-freqs) (set outputs-freqs)))]]
(is (= freq-diff [:all-merged nil :merged-all nil])))))
(testing "inputs and labelled-inputs report the same arcs, and same cardinality of arcs"
(doseq [node all-nodes]
(let [inputs (g/inputs node)
inputs-freqs (frequencies inputs)
merged-inputs (into [] cat (vals (node-inputs node)))
merged-inputs-freqs (frequencies merged-inputs)
freq-diff [:all-merged (not-empty (set/difference (set inputs-freqs) (set merged-inputs-freqs)))
:merged-all (not-empty (set/difference (set merged-inputs-freqs) (set inputs-freqs)))]]
(is (= freq-diff [:all-merged nil :merged-all nil])))))
(testing "For all outputs, there is a corresponding input and vice versa"
(let [inputs (atom node-inputs)] ; we tick off one input arc per output arc
(doseq [node all-nodes]
(loop [outputs (g/outputs node)]
(when (seq outputs)
(let [output (first outputs)
target (nth output 2)
target-label (nth output 3)
input-index (first (util/positions #(= output %) (get-in @inputs [target target-label])))]
(is (some? input-index) (str "missing input for " output " in:\n" (get-in @inputs [target target-label])))
(swap! inputs update-in [target target-label] remove-idx input-index)
(recur (rest outputs))))))
(is (empty? (into [] (comp (map vals) cat cat) (vals @inputs)))))) ; should end up with no input arcs left
(testing "Sanity: all inputs == all outputs"
(let [output-freqs (frequencies (mapcat g/outputs all-nodes))
input-freqs (frequencies (mapcat g/inputs all-nodes))]
(is (= output-freqs input-freqs)))))))
| 30226 | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 <NAME>, <NAME>
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns dynamo.integration.override-test
(:require [clojure.set :as set]
[clojure.test :refer :all]
[dynamo.graph :as g]
[dynamo.integration.override-test-support :as support]
[editor.defold-project :as project]
[editor.resource :as resource]
[editor.util :as util]
[integration.test-util :as test-util]
[internal.graph.types :as gt]
[internal.util]
[schema.core :as s]
[support.test-support :as ts])
(:import [javax.vecmath Vector3d]))
(g/defnode BaseNode
(property base-property g/Str))
(g/defnode MainNode
(inherits BaseNode)
(property a-property g/Str)
(property b-property g/Str)
(property virt-property g/Str
(value (g/fnk [a-property] a-property)))
(property dyn-property g/Str
(dynamic override? (g/fnk [_node-id _basis] (some? (g/override-original _basis _node-id)))))
(input sub-nodes g/NodeID :array :cascade-delete)
(output sub-nodes [g/NodeID] (g/fnk [sub-nodes] sub-nodes))
(output cached-output g/Str :cached (g/fnk [a-property] a-property))
(input cached-values g/Str :array)
(output cached-values [g/Str] :cached (g/fnk [cached-values] cached-values))
(output _properties g/Properties (g/fnk [_declared-properties]
(-> _declared-properties
(update :properties assoc :c-property (-> _declared-properties :properties :a-property))
(update :display-order conj :c-property)))))
(g/defnode SubNode
(property value g/Str))
(defn- override [node-id]
(-> (g/override node-id {})
ts/tx-nodes))
(defn- setup
([world]
(setup world 0))
([world count]
(let [nodes (ts/tx-nodes (g/make-nodes world [main [MainNode :a-property "main" :b-property "main"]
sub SubNode]
(g/connect sub :_node-id main :sub-nodes)))]
(loop [result [nodes]
counter count]
(if (> counter 0)
(recur (conj result (override (first (last result)))) (dec counter))
result)))))
(deftest test-sanity
(ts/with-clean-system
(let [[[main sub]] (setup world)]
(testing "Original graph connections"
(is (= [sub] (g/node-value main :sub-nodes)))))))
(deftest default-behaviour
(ts/with-clean-system
(let [[[main sub] [or-main or-sub]] (setup world 1)]
(testing "Connection is overridden from start"
(is (= [or-sub] (g/node-value or-main :sub-nodes)))
(is (= or-main (g/node-value or-main :_node-id))))
(testing "Using base values"
(doseq [label [:a-property :b-property :virt-property :cached-output]]
(is (= "main" (g/node-value or-main label)))))
(testing "Base node invalidates cache"
(g/transact (g/set-property main :a-property "new main"))
(is (= "new main" (g/node-value or-main :cached-output)))))))
(deftest property-dynamics
(ts/with-clean-system
(let [[[main sub] [or-main or-sub]] (setup world 1)]
(testing "Property dynamics"
(let [f (fn [n]
(let [p (g/node-value n :_declared-properties)]
(get-in p [:properties :dyn-property :override?])))]
(is (false? (f main)))
(is (true? (f or-main))))))))
(deftest delete
(ts/with-clean-system
(let [[[main sub] [or-main or-sub]] (setup world 1)]
(testing "Overrides can be removed"
(g/transact (g/delete-node or-main))
(doseq [nid [or-main or-sub]]
(is (nil? (g/node-by-id nid))))
(is (empty? (g/overrides main)))))
(let [[[main sub] [or-main or-sub]] (setup world 1)]
(testing "Overrides are removed with base"
(g/transact (g/delete-node main))
(doseq [nid [main sub or-main or-sub]]
(is (nil? (g/node-by-id nid))))
(is (empty? (g/overrides main)))))
(let [[[main sub] [or-main or-sub] [or2-main or2-sub]] (setup world 2)]
(testing "Delete hierarchy"
(g/transact (g/delete-node main))
(doseq [nid [main sub or-main or-sub or2-main or2-sub]]
(is (nil? (g/node-by-id nid))))
(is (empty? (g/overrides main)))))
(let [[[main sub] [or-main or-sub]] (setup world 1)
[stray] (ts/tx-nodes (g/make-nodes world
[stray BaseNode]
(g/connect stray :_node-id or-main :sub-nodes)))]
(testing "Delete stray node attached to override :cascade-delete"
(g/transact (g/delete-node main))
(doseq [nid [main sub or-main or-sub stray]]
(is (nil? (g/node-by-id nid))))
(is (empty? (g/overrides main)))))))
(deftest override-property
(ts/with-clean-system
(let [[[main sub] [or-main or-sub]] (setup world 1)]
(testing "Overriding property"
(g/transact (g/set-property or-main :a-property "overridden main"))
(is (= "overridden main" (g/node-value or-main :a-property)))
(is (= "main" (g/node-value main :a-property)))
(doseq [label [:_properties :_declared-properties]
:let [props (-> (g/node-value or-main label) (get :properties))
a-p (:a-property props)
b-p (:b-property props)]]
(is (= "overridden main" (:value a-p)))
(is (= "main" (:original-value a-p)))
(is (= or-main (:node-id a-p)))
(is (= "main" (:value b-p)))
(is (= false (contains? b-p :original-value)))
(is (= or-main (:node-id b-p)))))
(testing "Virtual property"
(is (= "overridden main" (g/node-value or-main :virt-property))))
(testing "Output production"
(is (= "overridden main" (g/node-value or-main :cached-output)))
(is (= "main" (g/node-value main :cached-output))))
(testing "Clearing property"
(g/transact (g/clear-property or-main :a-property))
(is (= "main" (g/node-value or-main :a-property)))
(is (= "main" (g/node-value or-main :virt-property)))
(is (= "main" (g/node-value or-main :cached-output))))
(testing "Update property"
(g/transact (g/update-property or-main :a-property (fn [prop] (str prop "_changed"))))
(is (= "main_changed" (g/node-value or-main :a-property)))))))
(deftest inherited-property
(ts/with-clean-system
(let [prop :base-property
[main or-main] (ts/tx-nodes (g/make-nodes world [main [MainNode prop "inherited"]]
(g/override main {})))]
(is (= "inherited" (g/node-value or-main prop))))))
(deftest new-node-created
(ts/with-clean-system
(let [[main or-main sub] (ts/tx-nodes (g/make-nodes world [main MainNode]
(g/override main {})
(g/make-nodes world [sub SubNode]
(g/connect sub :_node-id main :sub-nodes))))]
(let [sub-nodes (g/node-value or-main :sub-nodes)]
(is (= 1 (count sub-nodes)))
(is (not= [sub] sub-nodes)))
(g/transact (g/disconnect sub :_node-id main :sub-nodes))
(is (empty? (g/node-value or-main :sub-nodes))))))
(deftest new-node-created-cache-invalidation
(ts/with-clean-system
(let [[main or-main] (ts/tx-nodes (g/make-nodes world [main MainNode]
(g/override main {})))
_ (is (= [] (g/node-value or-main :cached-values)))
[sub] (ts/tx-nodes (g/make-nodes world [sub [SubNode :value "sub"]]
(for [[from to] [[:_node-id :sub-nodes]
[:value :cached-values]]]
(g/connect sub from main to))))]
(is (= ["sub"] (g/node-value or-main :cached-values)))
(g/transact (concat
(g/disconnect sub :_node-id main :sub-nodes)
(g/disconnect sub :value main :cached-values)))
(is (= [] (g/node-value or-main :cached-values))))))
(g/defnode DetectCacheInvalidation
(property invalid-cache g/Any)
(input value g/Str :cascade-delete)
(output cached-value g/Str :cached (g/fnk [value invalid-cache]
(swap! invalid-cache inc)
value)))
(deftest inherit-targets []
(testing "missing override"
(ts/with-clean-system
(let [[main cache-node or-main] (ts/tx-nodes (g/make-nodes world [main [SubNode :value "test"]
cache [DetectCacheInvalidation :invalid-cache (atom 0)]]
(g/connect main :value cache :value)
(g/override main {})))]
(is (= cache-node (ffirst (g/targets-of main :value))))
(is (empty? (g/targets-of or-main :value))))))
(testing "existing override"
(ts/with-clean-system
(let [[main cache-node] (ts/tx-nodes (g/make-nodes world [main [SubNode :value "test"]
cache [DetectCacheInvalidation :invalid-cache (atom 0)]]
(g/connect main :value cache :value)))
[or-cache-node or-main] (ts/tx-nodes (g/override cache-node {}))]
(is (= cache-node (ffirst (g/targets-of main :value))))
(is (= or-cache-node (ffirst (g/targets-of or-main :value))))))))
(g/defnode StringInput
(input value g/Str :cascade-delete))
(deftest inherit-sources []
(testing "missing override"
;; After making g/override perform the bulk of its work in the
;; transaction step (after the g/connect has happened/is
;; observable) this test is less relevant.
(ts/with-clean-system
(let [[main cache-node or-main] (ts/tx-nodes (g/make-nodes world [main StringInput
cache [DetectCacheInvalidation :invalid-cache (atom 0)]]
(g/connect cache :cached-value main :value)
(g/override main {:traverse? (constantly false)})))]
(is (= cache-node (ffirst (g/sources-of main :value))))
(is (= cache-node (ffirst (g/sources-of or-main :value)))))))
(testing "existing override"
(ts/with-clean-system
(let [[main cache-node] (ts/tx-nodes (g/make-nodes world [main StringInput
cache [DetectCacheInvalidation :invalid-cache (atom 0)]]
(g/connect cache :cached-value main :value)))
[or-main or-cache-node] (ts/tx-nodes (g/override cache-node {}))]
(is (= cache-node (ffirst (g/sources-of main :value))))
(is (= or-cache-node (ffirst (g/sources-of or-main :value))))))))
(deftest lonely-override-leaves-cache []
(ts/with-clean-system
(let [[main cache-node or-main] (ts/tx-nodes (g/make-nodes world [main [SubNode :value "test"]
cache [DetectCacheInvalidation :invalid-cache (atom 0)]]
(g/connect main :value cache :value)
(g/override main {})))]
(is (= 0 @(g/node-value cache-node :invalid-cache)))
(is (= "test" (g/node-value cache-node :cached-value)))
(is (= 1 @(g/node-value cache-node :invalid-cache)))
(is (= "test" (g/node-value cache-node :cached-value)))
(is (= 1 @(g/node-value cache-node :invalid-cache)))
(g/transact (g/set-property or-main :value "override"))
(is (= 1 @(g/node-value cache-node :invalid-cache))))))
(deftest multi-override
(ts/with-clean-system
(let [[[main sub]
[or-main or-sub]
[or2-main or2-sub]] (setup world 2)]
(testing "basic default behaviour"
(is (= "main" (g/node-value or2-main :a-property))))
(testing "cache-invalidation in multiple overrides"
(g/transact (g/set-property main :a-property "new main"))
(is (= "new main" (g/node-value or2-main :a-property))))
(testing "override one below overrides"
(g/transact (g/set-property or-main :a-property "main2"))
(is (= "main2" (g/node-value or2-main :a-property))))
(testing "top level override"
(g/transact (g/set-property or2-main :a-property "main3"))
(is (= "main3" (g/node-value or2-main :a-property)))))))
(defn- prop-map-value
[node prop-kw]
(-> node (g/node-value :_properties) :properties prop-kw :value))
(defn- prop-map-original-value
[node prop-kw]
(-> node (g/node-value :_properties) :properties prop-kw :original-value))
(deftest multi-override-with-dynamic-properties
(testing "property value is propagated through all override nodes"
(ts/with-clean-system
(let [[[main sub]
[or1-main or1-sub]
[or2-main or2-sub]
[or3-main or3-sub]] (setup world 3)]
(is (every? #(= "main" (prop-map-value % :a-property)) [main or1-main or2-main or3-main]))
(is (every? #(= "main" (prop-map-value % :c-property)) [main or1-main or2-main or3-main]))
(g/set-property! or1-main :a-property "a")
(is (= "main" (prop-map-value main :a-property)))
(is (= "a" (prop-map-value or1-main :a-property)))
(is (= "main" (prop-map-original-value or1-main :a-property)))
(is (= "a" (prop-map-value or2-main :a-property)))
(is (= nil (prop-map-original-value or2-main :a-property)))
(is (= "a" (prop-map-value or3-main :a-property)))
(is (= nil (prop-map-original-value or3-main :a-property)))
(g/set-property! or2-main :a-property "b")
(is (= "main" (prop-map-value main :a-property)))
(is (= "a" (prop-map-value or1-main :a-property)))
(is (= "main" (prop-map-original-value or1-main :a-property)))
(is (= "b" (prop-map-value or2-main :a-property)))
(is (= "a" (prop-map-original-value or2-main :a-property)))
(is (= "b" (prop-map-value or3-main :a-property)))
(is (= nil (prop-map-original-value or3-main :a-property)))
(g/clear-property! or1-main :a-property)
(g/clear-property! or2-main :a-property)
(g/set-property! or1-main :c-property "c")
(is (= "main" (prop-map-value main :c-property)))
(is (= "c" (prop-map-value or1-main :c-property)))
(is (= "main" (prop-map-original-value or1-main :c-property)))
(is (= "c" (prop-map-value or2-main :c-property)))
(is (= nil (prop-map-original-value or2-main :c-property)))
(is (= "c" (prop-map-value or3-main :c-property)))
(is (= nil (prop-map-original-value or3-main :c-property)))
(g/set-property! or2-main :c-property "d")
(is (= "main" (prop-map-value main :c-property)))
(is (= "c" (prop-map-value or1-main :c-property)))
(is (= "main" (prop-map-original-value or1-main :c-property)))
(is (= "d" (prop-map-value or2-main :c-property)))
(is (= "c" (prop-map-original-value or2-main :c-property)))
(is (= "d" (prop-map-value or3-main :c-property)))
(is (= nil (prop-map-original-value or3-main :c-property)))))))
(deftest mark-defective
(ts/with-clean-system
(let [[[main sub]
[or-main or-sub]] (setup world 1)]
(testing "defective base"
(let [error (g/error-fatal "Something went wrong" {:type :some-error})]
(g/transact
(g/mark-defective main error))
(is (g/error? (g/node-value or-main :a-property))))))
(let [[[main sub]
[or-main or-sub]] (setup world 1)]
(testing "defective override, which throws exception"
(let [error (g/error-fatal "Something went wrong" {:type :some-error})]
(is (thrown? Exception (g/transact
(g/mark-defective or-main error)))))))))
(deftest copy-paste
(ts/with-clean-system
(let [[[main sub]
[or-main or-sub]] (setup world 1)]
(g/transact (g/set-property or-main :a-property "override"))
(let [fragment (g/copy [or-main] {:traverse? (constantly true)})
paste-data (g/paste (g/node-id->graph-id or-main) fragment {})
copy-id (first (:root-node-ids paste-data))]
(g/transact (:tx-data paste-data))
(is (= "override" (g/node-value copy-id :a-property)))))))
(g/defnode ExternalNode
(property value g/Keyword))
(g/defnode ResourceNode
(property reference g/Keyword
(value (g/fnk [in-reference] in-reference))
(set (fn [evaluation-context node-id old-value new-value]
(concat
(g/disconnect-sources (:basis evaluation-context) node-id :in-reference)
(let [gid (g/node-id->graph-id node-id)
node-store (g/graph-value gid :node-store)
src-id (get node-store new-value)]
(if src-id
(g/connect src-id :value node-id :in-reference)
[]))))))
(input in-reference g/Keyword))
(deftest connection-property
(ts/with-clean-system
(let [[res a b] (ts/tx-nodes (g/make-nodes world [res ResourceNode
a [ExternalNode :value :node-a]
b [ExternalNode :value :node-b]]
(g/set-graph-value world :node-store {:node-a a :node-b b})))]
(testing "linking through property setter"
(g/transact (g/set-property res :reference :node-a))
(is (= :node-a (g/node-value res :reference)))
(g/transact (g/set-property a :value :node-a2))
(is (= :node-a2 (g/node-value res :reference))))
(let [or-res (first (override res))]
(testing "override inherits the connection"
(is (= :node-a2 (g/node-value or-res :reference))))
(testing "override the actual connection"
(g/transact (g/set-property or-res :reference :node-b))
(is (= :node-b (g/node-value or-res :reference))))
(testing "clearing the property"
(g/transact (g/clear-property or-res :reference))
(is (= :node-a2 (g/node-value or-res :reference))))))))
(g/deftype ^:private IDMap {s/Str s/Int})
(defprotocol Resource
(path [this]))
(defrecord PathResource [path]
Resource
(path [this] path))
(defn properties->overrides [id properties]
{id (->> (:properties properties)
(filter (fn [[k v]] (contains? v :original-value)))
(map (fn [[k v]] [k (:value v)]))
(into {}))})
(g/defnode Node
(property id g/Str)
(input id-prefix g/Str)
(output id g/Str (g/fnk [id-prefix id] (str id-prefix id)))
(output node-ids IDMap (g/fnk [_node-id id] {id _node-id}))
(output node-overrides g/Any (g/fnk [id _properties] (properties->overrides id _properties))))
(g/defnode VisualNode
(inherits Node)
(property value g/Str))
(g/defnode SceneResourceNode
(property resource Resource :unjammable))
(g/defnode NodeTree
(input nodes g/NodeID :array :cascade-delete)
(input node-ids IDMap :array)
(input node-overrides g/Any :array)
(input id-prefix g/Str)
(output id-prefix g/Str (g/fnk [id-prefix] id-prefix))
(output node-ids IDMap :cached (g/fnk [node-ids] (reduce into {} node-ids)))
(output node-overrides g/Any :cached (g/fnk [node-overrides]
(reduce into {} node-overrides))))
(g/defnode Scene
(inherits SceneResourceNode)
(input node-tree g/NodeID :cascade-delete)
(input layouts g/NodeID :array :cascade-delete)
(input id-prefix g/Str)
(output id-prefix g/Str (g/fnk [id-prefix] id-prefix))
(input node-ids IDMap)
(output node-ids IDMap (g/fnk [node-ids] node-ids))
(input node-overrides g/Any)
(output node-overrides g/Any (g/fnk [node-overrides] node-overrides)))
(defn- scene-by-path
([graph path]
(scene-by-path (g/now) graph path))
([basis graph path]
(let [resources (or (g/graph-value basis graph :resources) {})]
(get resources (->PathResource path)))))
(g/defnode Template
(inherits Node)
(property template g/Any
(value (g/fnk [template-resource source-overrides]
{:resource template-resource :overrides source-overrides}))
(set (fn [evaluation-context self old-value new-value]
(let [basis (:basis evaluation-context)
current-scene (g/node-feeding-into basis self :template-resource)]
(concat
(if current-scene
(g/delete-node current-scene)
[])
(let [gid (g/node-id->graph-id self)
path (:path new-value)]
(if-let [scene (scene-by-path basis gid path)]
(let [tmpl-path (g/node-value self :template-path evaluation-context)
properties-by-node-id (comp (or (:overrides new-value) {})
(into {} (map (fn [[k v]] [v (str tmpl-path k)]))
(g/node-value scene :node-ids evaluation-context)))]
(g/override scene {:properties-by-node-id properties-by-node-id}
(fn [evaluation-context id-mapping]
(let [or-scene (id-mapping scene)]
(concat
(for [[from to] [[:node-ids :node-ids]
[:node-overrides :source-overrides]
[:resource :template-resource]]]
(g/connect or-scene from self to))
(g/connect self :template-path or-scene :id-prefix))))))
[])))))))
(input template-resource Resource :cascade-delete)
(input node-ids IDMap)
(input instance g/NodeID)
(input source-overrides g/Any)
(output template-path g/Str (g/fnk [id] (str id "/")))
(output node-overrides g/Any :cached (g/fnk [id _properties source-overrides]
(merge (properties->overrides id _properties) source-overrides)))
(output node-ids IDMap (g/fnk [_node-id id node-ids] (into {id _node-id} node-ids))))
(g/defnode Layout
(property name g/Str)
(property nodes g/Any
(set (fn [evaluation-context self _ new-value]
(let [basis (:basis evaluation-context)
current-tree (g/node-feeding-into basis self :node-tree)]
(concat
(if current-tree
(g/delete-node current-tree)
[])
(let [scene (ffirst (g/targets-of basis self :_node-id))
node-tree (g/node-value scene :node-tree evaluation-context)]
(g/override node-tree {}
(fn [evaluation-context id-mapping]
(let [node-tree-or (id-mapping node-tree)]
(for [[from to] [[:_node-id :node-tree]]]
(g/connect node-tree-or from self to)))))))))))
(input node-tree g/NodeID :cascade-delete)
(input id-prefix g/Str))
(def ^:private node-tree-inputs [[:_node-id :nodes]
[:node-ids :node-ids]
[:node-overrides :node-overrides]])
(def ^:private node-tree-outputs [[:id-prefix :id-prefix]])
(defn- add-node [graph scene node-tree node-type props]
(g/make-nodes graph [n [node-type props]]
(for [[output input] node-tree-inputs]
(g/connect n output node-tree input))
(for [[output input] node-tree-outputs]
(g/connect node-tree output n input))))
(defn- add-layout [graph scene name]
(g/make-nodes graph [n [Layout :name name]]
(g/connect n :_node-id scene :layouts)
(g/connect scene :id-prefix n :id-prefix)
(g/set-property n :nodes {})))
(defn- load-scene [graph path nodes]
(let [resource (->PathResource path)]
(g/make-nodes graph [scene [Scene :resource resource]
node-tree [NodeTree]]
(for [[from to] [[:_node-id :node-tree]
[:node-ids :node-ids]
[:node-overrides :node-overrides]]]
(g/connect node-tree from scene to))
(for [[from to] [[:id-prefix :id-prefix]]]
(g/connect scene from node-tree to))
(g/update-graph-value graph :resources assoc resource scene)
(reduce (fn [tx [node-type props]]
(into tx (add-node graph scene node-tree node-type props)))
[] nodes))))
(defn- make-scene! [graph path nodes]
(when (nil? (g/graph-value graph :resources))
(g/set-graph-value! graph :resources {}))
(ts/tx-nodes (load-scene graph path nodes)))
(defn- has-node? [scene node-id]
(contains? (g/node-value scene :node-ids) node-id))
(defn- node-by-id [scene node-id]
(get (g/node-value scene :node-ids) node-id))
(defn- target [n label]
(ffirst (g/targets-of n label)))
(deftest scene-loading
(ts/with-clean-system
(let [[scene _ node] (make-scene! world "my-scene" [[VisualNode {:id "my-node" :value "initial"}]])
overrides {"my-template/my-node" {:value "new value"}}
[super-scene _ template] (make-scene! world "my-super-scene" [[Template {:id "my-template" :template {:path "my-scene" :overrides overrides}}]])]
(is (= "initial" (g/node-value node :value)))
(let [or-node (get (g/node-value template :node-ids) "my-template/my-node")]
(is (= "new value" (g/node-value or-node :value))))
(is (= overrides (select-keys (g/node-value template :node-overrides) (keys overrides)))))))
(deftest scene-loading-with-override-values
(ts/with-clean-system
(let [scene-overrides {"template/my-node" {:value "scene-override"}}
super-overrides {"super-template/template/my-node" {:value "super-override"}}]
(g/transact (concat
(load-scene world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
(load-scene world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides scene-overrides}}]])
(load-scene world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides super-overrides}}]])))
(doseq [[actual expected] (mapv (fn [[s-path id expected]] [(-> s-path
(->> (scene-by-path world))
(node-by-id id)
(g/node-value :node-overrides))
expected])
[["scene" "template" scene-overrides]
["super-scene" "super-template" super-overrides]])]
(is (= expected (select-keys actual (keys expected))))))))
(deftest hierarchical-ids
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])]
(is (has-node? sub-scene "my-node"))
(is (has-node? scene "template/my-node"))
(is (has-node? super-scene "super-template/template/my-node"))
(let [tmp (node-by-id super-scene "super-template/template")]
(g/transact (g/set-property sub-scene :resource (->PathResource "sub-scene2")))
(is (= "sub-scene2" (get-in (g/node-value tmp :template) [:resource :path])))))))
(deftest delete-middle
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])
middle (node-by-id scene "template")
super-middle (node-by-id super-scene "super-template/template")]
(is (has-node? super-scene "super-template/template"))
(g/transact (g/delete-node middle))
(is (not (has-node? super-scene "super-template/template")))
(is (nil? (g/node-by-id super-middle))))))
(deftest sibling-templates
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]
[Template {:id "template1" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])]
(is (has-node? scene "template/my-node"))
(is (has-node? scene "template1/my-node"))
(is (has-node? super-scene "super-template/template/my-node"))
(is (has-node? super-scene "super-template/template1/my-node")))))
(deftest new-sibling-delete-repeat
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene scene-tree] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])]
(dotimes [i 5]
(let [[new-tmpl] (ts/tx-nodes (add-node world scene scene-tree Template {:id "new-template" :template {:path "sub-scene" :overrides {}}}))]
(is (contains? (g/node-value (node-by-id scene "new-template") :node-overrides) "new-template/my-node"))
(g/transact (g/delete-node new-tmpl)))))))
(deftest change-override
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])
[sub-scene2] (make-scene! world "sub-scene2" [[VisualNode {:id "my-node2" :value ""}]])]
(g/transact (g/transfer-overrides {sub-scene sub-scene2}))
(is (empty? (g/overrides sub-scene)))
(is (has-node? super-scene "super-template/template/my-node2")))))
(deftest new-node-deep-override
(ts/with-clean-system
(let [[sub-scene sub-tree] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])
[super-super-scene] (make-scene! world "super-super-scene" [[Template {:id "super-super-template" :template {:path "super-scene" :overrides {}}}]])]
(g/transact (add-node world sub-scene sub-tree VisualNode {:id "my-node2"}))
(is (has-node? super-super-scene "super-super-template/super-template/template/my-node2")))))
;; Bug occurring in properties in overloads
(deftest scene-paths
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])
template (node-by-id super-scene "super-template/template")
or-scene (ffirst (g/sources-of template :template-resource))]
(is (= "sub-scene" (:path (g/node-value (g/override-original or-scene) :resource)))))))
;; Simulated layout problem
(deftest template-layouts
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[sub-layout] (ts/tx-nodes (add-layout world sub-scene "Portrait"))]
(is (nil? (g/node-value sub-layout :id-prefix)))
(is (not (nil? (g/node-value (first (g/overrides sub-layout)) :id-prefix)))))))
;; User-defined dynamic properties
(g/defnode Script
(property script-properties g/Any)
(output _properties g/Properties :cached (g/fnk [_node-id _declared-properties script-properties]
(-> _declared-properties
(update :properties dissoc :script-properties)
(update :properties merge (into {} (map (fn [[key value]] [key {:value value
:type (type value)
:node-id _node-id}]) script-properties)))
(update :display-order (comp vec (partial remove #{:script-properties})))))))
(g/defnode Component
(property id g/Str)
(property component g/Any
(set (fn [evaluation-context self old-value new-value]
(let [basis (:basis evaluation-context)]
(concat
(if-let [instance (g/node-value self :instance evaluation-context)]
(g/delete-node instance)
[])
(let [gid (g/node-id->graph-id self)
path (:path new-value)]
(if-let [script (get (g/graph-value basis gid :resources) path)]
(g/override script {}
(fn [evaluation-context id-mapping]
(let [or-script (id-mapping script)
script-props (g/node-value script :_properties evaluation-context)
set-prop-data (for [[key value] (:overrides new-value)]
(g/set-property or-script key value))
conn-data (for [[src tgt] [[:_node-id :instance]
[:_properties :script-properties]]]
(g/connect or-script src self tgt))]
(concat set-prop-data conn-data))))
[])))))))
(input instance g/NodeID :cascade-delete)
(input script-properties g/Properties)
(output _properties g/Properties (g/fnk [_declared-properties script-properties]
(-> _declared-properties
(update :properties merge (:properties script-properties))
(update :display-order concat (:display-order script-properties))))))
(deftest custom-properties
(ts/with-clean-system
(let [[script comp] (ts/tx-nodes (g/make-nodes world [script [Script :script-properties {:speed 0}]]
(g/set-graph-value world :resources {"script.script" script}))
(g/make-nodes world [comp [Component :component {:path "script.script" :overrides {:speed 10}}]]))]
(let [p (get-in (g/node-value comp :_properties) [:properties :speed])]
(is (= 10 (:value p)))
(is (= 0 (:original-value p)))
(g/transact (g/set-property (:node-id p) :speed 20))
(let [p' (get-in (g/node-value comp :_properties) [:properties :speed])]
(is (= 20 (:value p')))
(is (= 0 (:original-value p'))))
(g/transact (g/clear-property (:node-id p) :speed))
(let [p' (get-in (g/node-value comp :_properties) [:properties :speed])]
(is (= 0 (:value p')))
(is (not (contains? p' :original-value))))))))
;; Overloaded outputs with different types
(g/deftype XYZ [(s/one s/Num "x") (s/one s/Num "y") (s/one s/Num "z")])
(g/deftype Complex {s/Keyword Vector3d})
(g/defnode TypedOutputNode
(property value XYZ)
(output value Vector3d (g/fnk [value] (let [[x y z] value] (Vector3d. x y z))))
(output complex Complex (g/fnk [value] {:value value})))
(deftest overloaded-outputs-and-types
(ts/with-clean-system
(let [[a b] (ts/tx-nodes (g/make-nodes world [n [TypedOutputNode :value [1 2 3]]]
(g/override n)))]
(g/transact (g/set-property b :value [2 3 4]))
(is (not= (g/node-value b :complex) (g/node-value a :complex))))))
;; Dynamic property production
(g/defnode IDNode
(input super-id g/Str)
(property id g/Str (value (g/fnk [_node-id super-id id] (if super-id (str super-id "/" id) id)))))
(deftest dynamic-id-in-properties
(ts/with-clean-system
(let [[node parent sub] (ts/tx-nodes (g/make-nodes world [node [IDNode :id "child-id"]
parent [IDNode :id "parent-id"]]
(g/override node {}
(fn [evaluation-context id-mapping]
(let [or-node (id-mapping node)]
(g/connect parent :id or-node :super-id))))))]
(is (= (g/node-value sub :id)
(get-in (g/node-value sub :_declared-properties) [:properties :id :value]))))))
;; Reload supported for overrides
(deftest reload-overrides
(ts/with-clean-system
(let [[node or-node] (ts/tx-nodes (g/make-nodes world [node [support/ReloadNode :my-value "reload-test"]]
(g/override node)))]
(g/transact (g/set-property or-node :my-value "new-value"))
(is (= "new-value" (get-in (g/node-value or-node :_properties) [:properties :my-value :value])))
(use 'dynamo.integration.override-test-support :reload)
(is (= "new-value" (get-in (g/node-value or-node :_properties) [:properties :my-value :value]))))))
;; Dependency rules
(defn- outs [nodes output]
(for [n nodes]
[n output]))
(defn- conn? [[src src-label tgt tgt-label]]
(let [basis (g/now)]
(and (g/connected? basis src src-label tgt tgt-label)
(contains? (into #{} (gt/sources basis tgt tgt-label)) [src src-label])
(contains? (into #{} (gt/targets basis src src-label)) [tgt tgt-label]))))
(defn- no-conn? [[src src-label tgt tgt-label]]
(let [basis (g/now)]
(and (not (g/connected? basis src src-label tgt tgt-label))
(not (contains? (into #{} (gt/sources basis tgt tgt-label)) [src src-label]))
(not (contains? (into #{} (gt/targets basis src src-label)) [tgt tgt-label])))))
(defn- deps [tgts]
(ts/graph-dependencies tgts))
(g/defnode TargetNode
(input in-value g/Str)
(output out-value g/Str (g/fnk [in-value] in-value)))
(deftest dep-rules
(ts/with-clean-system
(let [all (setup world 2)
[[main-0 sub-0]
[main-1 sub-1]
[main-2 sub-2]] all
mains (mapv first all)
subs (mapv second all)]
(testing "value fnk"
(is (every? (deps [[main-0 :a-property]]) (outs mains :virt-property))))
(testing "output"
(is (every? (deps [[main-0 :a-property]]) (outs mains :cached-output))))
(testing "connections"
(is (every? conn? (for [[m s] all]
[s :_node-id m :sub-nodes])))
(is (every? no-conn? (for [mi (range 3)
si (range 3)
:when (not= mi si)
:let [m (nth mains mi)
s (nth subs si)]]
[s :_node-id m :sub-nodes]))))))
(ts/with-clean-system
(let [[src tgt src-1] (ts/tx-nodes (g/make-nodes world [src [MainNode :a-property "reload-test"]
tgt TargetNode]
(g/connect src :a-property tgt :in-value)
(g/override src)))]
(testing "regular dep"
(is (every? (deps [[src :a-property]]) [[tgt :out-value]])))
(testing "no override deps"
(is (not-any? (deps [[src-1 :a-property]]) [[tgt :out-value]])))
(testing "connections"
(is (conn? [src :a-property tgt :in-value]))
(is (no-conn? [src-1 :a-property tgt :in-value])))))
(ts/with-clean-system
(let [[src tgt tgt-1] (ts/tx-nodes (g/make-nodes world [src [MainNode :a-property "reload-test"]
tgt TargetNode]
(g/connect src :a-property tgt :in-value)
(g/override tgt)))]
(testing "regular dep"
(is (every? (deps [[src :a-property]]) [[tgt :out-value] [tgt-1 :out-value]])))
(testing "connections"
(is (conn? [src :a-property tgt :in-value]))
(is (conn? [src :a-property tgt-1 :in-value])))))
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]
[Template {:id "template1" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])
[tmpl-scene tmpl1-scene] (g/overrides sub-scene)
[tmpl-tree tmpl1-tree] (mapv #(g/node-value % :node-tree) [tmpl-scene tmpl1-scene])
[tmpl-sub tmpl1-sub] (mapv #(node-by-id scene %) ["template/my-node" "template1/my-node"])]
(is (conn? [tmpl-sub :node-overrides tmpl-tree :node-overrides]))
(is (conn? [tmpl1-sub :node-overrides tmpl1-tree :node-overrides]))
(is (conn? [tmpl-tree :node-overrides tmpl-scene :node-overrides]))
(is (conn? [tmpl1-tree :node-overrides tmpl1-scene :node-overrides])))))
(g/defnode GameObject
(input components g/NodeID :array :cascade-delete))
(g/defnode GameObjectInstance
(input source g/NodeID :cascade-delete))
(g/defnode Collection
(input instances g/NodeID :array :cascade-delete))
(deftest override-created-on-connect
(ts/with-clean-system
(let [[script] (ts/tx-nodes (g/make-nodes world [script Script]))
[go comp or-script] (ts/tx-nodes (g/make-nodes world [go GameObject
comp Component]
(g/override script {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-script (id-mapping script)]
(concat
(g/connect comp :_node-id go :components)
(g/connect or-script :_node-id comp :instance)))))))
[coll inst or-go] (ts/tx-nodes (g/make-nodes world [coll Collection
inst GameObjectInstance]
(g/override go {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-go (id-mapping go)]
(concat
(g/connect inst :_node-id coll :instances)
(g/connect or-go :_node-id inst :source)))))))
[comp-2 or-script-2] (ts/tx-nodes (g/make-nodes world [comp Component]
(g/override script {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-script (id-mapping script)]
(g/connect or-script :_node-id comp :instance))))))
nodes-on-connect (ts/tx-nodes (g/connect comp-2 :_node-id go :components))]
;; 1 override for the component node and one for the script, w.r.t the collection
(is (= 2 (count nodes-on-connect))))))
(deftest cascade-delete-avoided
(ts/with-clean-system
(let [[script] (ts/tx-nodes (g/make-nodes world [script Script]))
[go comp or-script] (ts/tx-nodes (g/make-nodes world [go GameObject
comp Component]
(g/override script {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-script (id-mapping script)]
(concat
(g/connect comp :_node-id go :components)
(g/connect or-script :_node-id comp :instance)))))))
[coll inst or-go] (ts/tx-nodes (g/make-nodes world [coll Collection
inst GameObjectInstance]
(g/override go {:traverse? (constantly false)}
(fn [evaluation-context id-mapping]
(let [or-go (id-mapping go)]
(concat
(g/connect inst :_node-id coll :instances)
(g/connect or-go :_node-id inst :source)))))))]
(is (every? some? (map g/node-by-id [coll inst or-go go comp or-script script])))
(g/transact (g/delete-node coll))
(is (every? nil? (map g/node-by-id [coll inst or-go])))
(is (every? some? (map g/node-by-id [go comp or-script script])))
(g/transact (g/delete-node go))
(is (every? nil? (map g/node-by-id [coll inst or-go go comp or-script])))
(is (every? some? (map g/node-by-id [script])))
(g/transact (g/delete-node script))
(is (every? nil? (map g/node-by-id [coll inst or-go go comp or-script script]))))))
(deftest auto-add-and-delete
(ts/with-clean-system
(let [[script] (ts/tx-nodes (g/make-nodes world [script Script]))
[go] (ts/tx-nodes (g/make-nodes world [go GameObject]))
[[coll0 go-inst0 or-go0]
[coll1 go-inst1 or-go1]] (for [i (range 2)]
(ts/tx-nodes (g/make-nodes world [coll Collection
go-inst GameObjectInstance]
(g/connect go-inst :_node-id coll :instances)
(g/override go {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-go (id-mapping go)]
(g/connect or-go :_node-id go-inst :source)))))))
[comp or-script] (ts/tx-nodes (g/make-nodes world [comp Component]
(g/override script {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-script (id-mapping script)]
(concat
(g/connect or-script :_node-id comp :instance)
(g/connect comp :_node-id go :components)))))))]
(let [all-script-nodes (doall (tree-seq (constantly true) g/overrides script))]
(is (= 4 (count all-script-nodes)))
(g/transact (g/delete-node comp))
(is (= 1 (count (keep g/node-by-id all-script-nodes))))
(is (empty? (mapcat g/overrides all-script-nodes)))))))
(defn- remove-idx [v ix]
(into (subvec v 0 ix) (subvec v (inc ix))))
(defn- all-system-nodes []
(into []
(mapcat #(keys (:nodes (second %))))
(:graphs @g/*the-system*)))
(deftest symmetric-input-output-arcs
(test-util/with-loaded-project "test/resources/override_project"
(let [all-nodes (all-system-nodes)
node-outputs (reduce (fn [result n]
(reduce (fn [result label]
(assoc-in result [n label] (vec (g/labelled-outputs n label))))
result
(g/output-labels (g/node-type* n))))
{}
all-nodes)
node-inputs (reduce (fn [result n]
(reduce (fn [result label]
(assoc-in result [n label] (vec (g/labelled-inputs n label))))
result
(g/input-labels (g/node-type* n))))
{}
all-nodes)]
(testing "outputs and labelled-outputs report the same arcs, and same cardinality of arcs"
(doseq [node all-nodes]
(let [outputs (g/outputs node)
outputs-freqs (frequencies outputs)
merged-outputs (into [] cat (vals (node-outputs node)))
merged-outputs-freqs (frequencies merged-outputs)
freq-diff [:all-merged (not-empty (set/difference (set outputs-freqs) (set merged-outputs-freqs)))
:merged-all (not-empty (set/difference (set merged-outputs-freqs) (set outputs-freqs)))]]
(is (= freq-diff [:all-merged nil :merged-all nil])))))
(testing "inputs and labelled-inputs report the same arcs, and same cardinality of arcs"
(doseq [node all-nodes]
(let [inputs (g/inputs node)
inputs-freqs (frequencies inputs)
merged-inputs (into [] cat (vals (node-inputs node)))
merged-inputs-freqs (frequencies merged-inputs)
freq-diff [:all-merged (not-empty (set/difference (set inputs-freqs) (set merged-inputs-freqs)))
:merged-all (not-empty (set/difference (set merged-inputs-freqs) (set inputs-freqs)))]]
(is (= freq-diff [:all-merged nil :merged-all nil])))))
(testing "For all outputs, there is a corresponding input and vice versa"
(let [inputs (atom node-inputs)] ; we tick off one input arc per output arc
(doseq [node all-nodes]
(loop [outputs (g/outputs node)]
(when (seq outputs)
(let [output (first outputs)
target (nth output 2)
target-label (nth output 3)
input-index (first (util/positions #(= output %) (get-in @inputs [target target-label])))]
(is (some? input-index) (str "missing input for " output " in:\n" (get-in @inputs [target target-label])))
(swap! inputs update-in [target target-label] remove-idx input-index)
(recur (rest outputs))))))
(is (empty? (into [] (comp (map vals) cat cat) (vals @inputs)))))) ; should end up with no input arcs left
(testing "Sanity: all inputs == all outputs"
(let [output-freqs (frequencies (mapcat g/outputs all-nodes))
input-freqs (frequencies (mapcat g/inputs all-nodes))]
(is (= output-freqs input-freqs)))))))
| true | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns dynamo.integration.override-test
(:require [clojure.set :as set]
[clojure.test :refer :all]
[dynamo.graph :as g]
[dynamo.integration.override-test-support :as support]
[editor.defold-project :as project]
[editor.resource :as resource]
[editor.util :as util]
[integration.test-util :as test-util]
[internal.graph.types :as gt]
[internal.util]
[schema.core :as s]
[support.test-support :as ts])
(:import [javax.vecmath Vector3d]))
(g/defnode BaseNode
(property base-property g/Str))
(g/defnode MainNode
(inherits BaseNode)
(property a-property g/Str)
(property b-property g/Str)
(property virt-property g/Str
(value (g/fnk [a-property] a-property)))
(property dyn-property g/Str
(dynamic override? (g/fnk [_node-id _basis] (some? (g/override-original _basis _node-id)))))
(input sub-nodes g/NodeID :array :cascade-delete)
(output sub-nodes [g/NodeID] (g/fnk [sub-nodes] sub-nodes))
(output cached-output g/Str :cached (g/fnk [a-property] a-property))
(input cached-values g/Str :array)
(output cached-values [g/Str] :cached (g/fnk [cached-values] cached-values))
(output _properties g/Properties (g/fnk [_declared-properties]
(-> _declared-properties
(update :properties assoc :c-property (-> _declared-properties :properties :a-property))
(update :display-order conj :c-property)))))
(g/defnode SubNode
(property value g/Str))
(defn- override [node-id]
(-> (g/override node-id {})
ts/tx-nodes))
(defn- setup
([world]
(setup world 0))
([world count]
(let [nodes (ts/tx-nodes (g/make-nodes world [main [MainNode :a-property "main" :b-property "main"]
sub SubNode]
(g/connect sub :_node-id main :sub-nodes)))]
(loop [result [nodes]
counter count]
(if (> counter 0)
(recur (conj result (override (first (last result)))) (dec counter))
result)))))
(deftest test-sanity
(ts/with-clean-system
(let [[[main sub]] (setup world)]
(testing "Original graph connections"
(is (= [sub] (g/node-value main :sub-nodes)))))))
(deftest default-behaviour
(ts/with-clean-system
(let [[[main sub] [or-main or-sub]] (setup world 1)]
(testing "Connection is overridden from start"
(is (= [or-sub] (g/node-value or-main :sub-nodes)))
(is (= or-main (g/node-value or-main :_node-id))))
(testing "Using base values"
(doseq [label [:a-property :b-property :virt-property :cached-output]]
(is (= "main" (g/node-value or-main label)))))
(testing "Base node invalidates cache"
(g/transact (g/set-property main :a-property "new main"))
(is (= "new main" (g/node-value or-main :cached-output)))))))
(deftest property-dynamics
(ts/with-clean-system
(let [[[main sub] [or-main or-sub]] (setup world 1)]
(testing "Property dynamics"
(let [f (fn [n]
(let [p (g/node-value n :_declared-properties)]
(get-in p [:properties :dyn-property :override?])))]
(is (false? (f main)))
(is (true? (f or-main))))))))
(deftest delete
(ts/with-clean-system
(let [[[main sub] [or-main or-sub]] (setup world 1)]
(testing "Overrides can be removed"
(g/transact (g/delete-node or-main))
(doseq [nid [or-main or-sub]]
(is (nil? (g/node-by-id nid))))
(is (empty? (g/overrides main)))))
(let [[[main sub] [or-main or-sub]] (setup world 1)]
(testing "Overrides are removed with base"
(g/transact (g/delete-node main))
(doseq [nid [main sub or-main or-sub]]
(is (nil? (g/node-by-id nid))))
(is (empty? (g/overrides main)))))
(let [[[main sub] [or-main or-sub] [or2-main or2-sub]] (setup world 2)]
(testing "Delete hierarchy"
(g/transact (g/delete-node main))
(doseq [nid [main sub or-main or-sub or2-main or2-sub]]
(is (nil? (g/node-by-id nid))))
(is (empty? (g/overrides main)))))
(let [[[main sub] [or-main or-sub]] (setup world 1)
[stray] (ts/tx-nodes (g/make-nodes world
[stray BaseNode]
(g/connect stray :_node-id or-main :sub-nodes)))]
(testing "Delete stray node attached to override :cascade-delete"
(g/transact (g/delete-node main))
(doseq [nid [main sub or-main or-sub stray]]
(is (nil? (g/node-by-id nid))))
(is (empty? (g/overrides main)))))))
(deftest override-property
(ts/with-clean-system
(let [[[main sub] [or-main or-sub]] (setup world 1)]
(testing "Overriding property"
(g/transact (g/set-property or-main :a-property "overridden main"))
(is (= "overridden main" (g/node-value or-main :a-property)))
(is (= "main" (g/node-value main :a-property)))
(doseq [label [:_properties :_declared-properties]
:let [props (-> (g/node-value or-main label) (get :properties))
a-p (:a-property props)
b-p (:b-property props)]]
(is (= "overridden main" (:value a-p)))
(is (= "main" (:original-value a-p)))
(is (= or-main (:node-id a-p)))
(is (= "main" (:value b-p)))
(is (= false (contains? b-p :original-value)))
(is (= or-main (:node-id b-p)))))
(testing "Virtual property"
(is (= "overridden main" (g/node-value or-main :virt-property))))
(testing "Output production"
(is (= "overridden main" (g/node-value or-main :cached-output)))
(is (= "main" (g/node-value main :cached-output))))
(testing "Clearing property"
(g/transact (g/clear-property or-main :a-property))
(is (= "main" (g/node-value or-main :a-property)))
(is (= "main" (g/node-value or-main :virt-property)))
(is (= "main" (g/node-value or-main :cached-output))))
(testing "Update property"
(g/transact (g/update-property or-main :a-property (fn [prop] (str prop "_changed"))))
(is (= "main_changed" (g/node-value or-main :a-property)))))))
(deftest inherited-property
(ts/with-clean-system
(let [prop :base-property
[main or-main] (ts/tx-nodes (g/make-nodes world [main [MainNode prop "inherited"]]
(g/override main {})))]
(is (= "inherited" (g/node-value or-main prop))))))
(deftest new-node-created
(ts/with-clean-system
(let [[main or-main sub] (ts/tx-nodes (g/make-nodes world [main MainNode]
(g/override main {})
(g/make-nodes world [sub SubNode]
(g/connect sub :_node-id main :sub-nodes))))]
(let [sub-nodes (g/node-value or-main :sub-nodes)]
(is (= 1 (count sub-nodes)))
(is (not= [sub] sub-nodes)))
(g/transact (g/disconnect sub :_node-id main :sub-nodes))
(is (empty? (g/node-value or-main :sub-nodes))))))
(deftest new-node-created-cache-invalidation
(ts/with-clean-system
(let [[main or-main] (ts/tx-nodes (g/make-nodes world [main MainNode]
(g/override main {})))
_ (is (= [] (g/node-value or-main :cached-values)))
[sub] (ts/tx-nodes (g/make-nodes world [sub [SubNode :value "sub"]]
(for [[from to] [[:_node-id :sub-nodes]
[:value :cached-values]]]
(g/connect sub from main to))))]
(is (= ["sub"] (g/node-value or-main :cached-values)))
(g/transact (concat
(g/disconnect sub :_node-id main :sub-nodes)
(g/disconnect sub :value main :cached-values)))
(is (= [] (g/node-value or-main :cached-values))))))
(g/defnode DetectCacheInvalidation
(property invalid-cache g/Any)
(input value g/Str :cascade-delete)
(output cached-value g/Str :cached (g/fnk [value invalid-cache]
(swap! invalid-cache inc)
value)))
(deftest inherit-targets []
(testing "missing override"
(ts/with-clean-system
(let [[main cache-node or-main] (ts/tx-nodes (g/make-nodes world [main [SubNode :value "test"]
cache [DetectCacheInvalidation :invalid-cache (atom 0)]]
(g/connect main :value cache :value)
(g/override main {})))]
(is (= cache-node (ffirst (g/targets-of main :value))))
(is (empty? (g/targets-of or-main :value))))))
(testing "existing override"
(ts/with-clean-system
(let [[main cache-node] (ts/tx-nodes (g/make-nodes world [main [SubNode :value "test"]
cache [DetectCacheInvalidation :invalid-cache (atom 0)]]
(g/connect main :value cache :value)))
[or-cache-node or-main] (ts/tx-nodes (g/override cache-node {}))]
(is (= cache-node (ffirst (g/targets-of main :value))))
(is (= or-cache-node (ffirst (g/targets-of or-main :value))))))))
(g/defnode StringInput
(input value g/Str :cascade-delete))
(deftest inherit-sources []
(testing "missing override"
;; After making g/override perform the bulk of its work in the
;; transaction step (after the g/connect has happened/is
;; observable) this test is less relevant.
(ts/with-clean-system
(let [[main cache-node or-main] (ts/tx-nodes (g/make-nodes world [main StringInput
cache [DetectCacheInvalidation :invalid-cache (atom 0)]]
(g/connect cache :cached-value main :value)
(g/override main {:traverse? (constantly false)})))]
(is (= cache-node (ffirst (g/sources-of main :value))))
(is (= cache-node (ffirst (g/sources-of or-main :value)))))))
(testing "existing override"
(ts/with-clean-system
(let [[main cache-node] (ts/tx-nodes (g/make-nodes world [main StringInput
cache [DetectCacheInvalidation :invalid-cache (atom 0)]]
(g/connect cache :cached-value main :value)))
[or-main or-cache-node] (ts/tx-nodes (g/override cache-node {}))]
(is (= cache-node (ffirst (g/sources-of main :value))))
(is (= or-cache-node (ffirst (g/sources-of or-main :value))))))))
(deftest lonely-override-leaves-cache []
(ts/with-clean-system
(let [[main cache-node or-main] (ts/tx-nodes (g/make-nodes world [main [SubNode :value "test"]
cache [DetectCacheInvalidation :invalid-cache (atom 0)]]
(g/connect main :value cache :value)
(g/override main {})))]
(is (= 0 @(g/node-value cache-node :invalid-cache)))
(is (= "test" (g/node-value cache-node :cached-value)))
(is (= 1 @(g/node-value cache-node :invalid-cache)))
(is (= "test" (g/node-value cache-node :cached-value)))
(is (= 1 @(g/node-value cache-node :invalid-cache)))
(g/transact (g/set-property or-main :value "override"))
(is (= 1 @(g/node-value cache-node :invalid-cache))))))
(deftest multi-override
(ts/with-clean-system
(let [[[main sub]
[or-main or-sub]
[or2-main or2-sub]] (setup world 2)]
(testing "basic default behaviour"
(is (= "main" (g/node-value or2-main :a-property))))
(testing "cache-invalidation in multiple overrides"
(g/transact (g/set-property main :a-property "new main"))
(is (= "new main" (g/node-value or2-main :a-property))))
(testing "override one below overrides"
(g/transact (g/set-property or-main :a-property "main2"))
(is (= "main2" (g/node-value or2-main :a-property))))
(testing "top level override"
(g/transact (g/set-property or2-main :a-property "main3"))
(is (= "main3" (g/node-value or2-main :a-property)))))))
(defn- prop-map-value
[node prop-kw]
(-> node (g/node-value :_properties) :properties prop-kw :value))
(defn- prop-map-original-value
[node prop-kw]
(-> node (g/node-value :_properties) :properties prop-kw :original-value))
(deftest multi-override-with-dynamic-properties
(testing "property value is propagated through all override nodes"
(ts/with-clean-system
(let [[[main sub]
[or1-main or1-sub]
[or2-main or2-sub]
[or3-main or3-sub]] (setup world 3)]
(is (every? #(= "main" (prop-map-value % :a-property)) [main or1-main or2-main or3-main]))
(is (every? #(= "main" (prop-map-value % :c-property)) [main or1-main or2-main or3-main]))
(g/set-property! or1-main :a-property "a")
(is (= "main" (prop-map-value main :a-property)))
(is (= "a" (prop-map-value or1-main :a-property)))
(is (= "main" (prop-map-original-value or1-main :a-property)))
(is (= "a" (prop-map-value or2-main :a-property)))
(is (= nil (prop-map-original-value or2-main :a-property)))
(is (= "a" (prop-map-value or3-main :a-property)))
(is (= nil (prop-map-original-value or3-main :a-property)))
(g/set-property! or2-main :a-property "b")
(is (= "main" (prop-map-value main :a-property)))
(is (= "a" (prop-map-value or1-main :a-property)))
(is (= "main" (prop-map-original-value or1-main :a-property)))
(is (= "b" (prop-map-value or2-main :a-property)))
(is (= "a" (prop-map-original-value or2-main :a-property)))
(is (= "b" (prop-map-value or3-main :a-property)))
(is (= nil (prop-map-original-value or3-main :a-property)))
(g/clear-property! or1-main :a-property)
(g/clear-property! or2-main :a-property)
(g/set-property! or1-main :c-property "c")
(is (= "main" (prop-map-value main :c-property)))
(is (= "c" (prop-map-value or1-main :c-property)))
(is (= "main" (prop-map-original-value or1-main :c-property)))
(is (= "c" (prop-map-value or2-main :c-property)))
(is (= nil (prop-map-original-value or2-main :c-property)))
(is (= "c" (prop-map-value or3-main :c-property)))
(is (= nil (prop-map-original-value or3-main :c-property)))
(g/set-property! or2-main :c-property "d")
(is (= "main" (prop-map-value main :c-property)))
(is (= "c" (prop-map-value or1-main :c-property)))
(is (= "main" (prop-map-original-value or1-main :c-property)))
(is (= "d" (prop-map-value or2-main :c-property)))
(is (= "c" (prop-map-original-value or2-main :c-property)))
(is (= "d" (prop-map-value or3-main :c-property)))
(is (= nil (prop-map-original-value or3-main :c-property)))))))
(deftest mark-defective
(ts/with-clean-system
(let [[[main sub]
[or-main or-sub]] (setup world 1)]
(testing "defective base"
(let [error (g/error-fatal "Something went wrong" {:type :some-error})]
(g/transact
(g/mark-defective main error))
(is (g/error? (g/node-value or-main :a-property))))))
(let [[[main sub]
[or-main or-sub]] (setup world 1)]
(testing "defective override, which throws exception"
(let [error (g/error-fatal "Something went wrong" {:type :some-error})]
(is (thrown? Exception (g/transact
(g/mark-defective or-main error)))))))))
(deftest copy-paste
(ts/with-clean-system
(let [[[main sub]
[or-main or-sub]] (setup world 1)]
(g/transact (g/set-property or-main :a-property "override"))
(let [fragment (g/copy [or-main] {:traverse? (constantly true)})
paste-data (g/paste (g/node-id->graph-id or-main) fragment {})
copy-id (first (:root-node-ids paste-data))]
(g/transact (:tx-data paste-data))
(is (= "override" (g/node-value copy-id :a-property)))))))
(g/defnode ExternalNode
(property value g/Keyword))
(g/defnode ResourceNode
(property reference g/Keyword
(value (g/fnk [in-reference] in-reference))
(set (fn [evaluation-context node-id old-value new-value]
(concat
(g/disconnect-sources (:basis evaluation-context) node-id :in-reference)
(let [gid (g/node-id->graph-id node-id)
node-store (g/graph-value gid :node-store)
src-id (get node-store new-value)]
(if src-id
(g/connect src-id :value node-id :in-reference)
[]))))))
(input in-reference g/Keyword))
(deftest connection-property
(ts/with-clean-system
(let [[res a b] (ts/tx-nodes (g/make-nodes world [res ResourceNode
a [ExternalNode :value :node-a]
b [ExternalNode :value :node-b]]
(g/set-graph-value world :node-store {:node-a a :node-b b})))]
(testing "linking through property setter"
(g/transact (g/set-property res :reference :node-a))
(is (= :node-a (g/node-value res :reference)))
(g/transact (g/set-property a :value :node-a2))
(is (= :node-a2 (g/node-value res :reference))))
(let [or-res (first (override res))]
(testing "override inherits the connection"
(is (= :node-a2 (g/node-value or-res :reference))))
(testing "override the actual connection"
(g/transact (g/set-property or-res :reference :node-b))
(is (= :node-b (g/node-value or-res :reference))))
(testing "clearing the property"
(g/transact (g/clear-property or-res :reference))
(is (= :node-a2 (g/node-value or-res :reference))))))))
(g/deftype ^:private IDMap {s/Str s/Int})
(defprotocol Resource
(path [this]))
(defrecord PathResource [path]
Resource
(path [this] path))
(defn properties->overrides [id properties]
{id (->> (:properties properties)
(filter (fn [[k v]] (contains? v :original-value)))
(map (fn [[k v]] [k (:value v)]))
(into {}))})
(g/defnode Node
(property id g/Str)
(input id-prefix g/Str)
(output id g/Str (g/fnk [id-prefix id] (str id-prefix id)))
(output node-ids IDMap (g/fnk [_node-id id] {id _node-id}))
(output node-overrides g/Any (g/fnk [id _properties] (properties->overrides id _properties))))
(g/defnode VisualNode
(inherits Node)
(property value g/Str))
(g/defnode SceneResourceNode
(property resource Resource :unjammable))
(g/defnode NodeTree
(input nodes g/NodeID :array :cascade-delete)
(input node-ids IDMap :array)
(input node-overrides g/Any :array)
(input id-prefix g/Str)
(output id-prefix g/Str (g/fnk [id-prefix] id-prefix))
(output node-ids IDMap :cached (g/fnk [node-ids] (reduce into {} node-ids)))
(output node-overrides g/Any :cached (g/fnk [node-overrides]
(reduce into {} node-overrides))))
(g/defnode Scene
(inherits SceneResourceNode)
(input node-tree g/NodeID :cascade-delete)
(input layouts g/NodeID :array :cascade-delete)
(input id-prefix g/Str)
(output id-prefix g/Str (g/fnk [id-prefix] id-prefix))
(input node-ids IDMap)
(output node-ids IDMap (g/fnk [node-ids] node-ids))
(input node-overrides g/Any)
(output node-overrides g/Any (g/fnk [node-overrides] node-overrides)))
(defn- scene-by-path
([graph path]
(scene-by-path (g/now) graph path))
([basis graph path]
(let [resources (or (g/graph-value basis graph :resources) {})]
(get resources (->PathResource path)))))
(g/defnode Template
(inherits Node)
(property template g/Any
(value (g/fnk [template-resource source-overrides]
{:resource template-resource :overrides source-overrides}))
(set (fn [evaluation-context self old-value new-value]
(let [basis (:basis evaluation-context)
current-scene (g/node-feeding-into basis self :template-resource)]
(concat
(if current-scene
(g/delete-node current-scene)
[])
(let [gid (g/node-id->graph-id self)
path (:path new-value)]
(if-let [scene (scene-by-path basis gid path)]
(let [tmpl-path (g/node-value self :template-path evaluation-context)
properties-by-node-id (comp (or (:overrides new-value) {})
(into {} (map (fn [[k v]] [v (str tmpl-path k)]))
(g/node-value scene :node-ids evaluation-context)))]
(g/override scene {:properties-by-node-id properties-by-node-id}
(fn [evaluation-context id-mapping]
(let [or-scene (id-mapping scene)]
(concat
(for [[from to] [[:node-ids :node-ids]
[:node-overrides :source-overrides]
[:resource :template-resource]]]
(g/connect or-scene from self to))
(g/connect self :template-path or-scene :id-prefix))))))
[])))))))
(input template-resource Resource :cascade-delete)
(input node-ids IDMap)
(input instance g/NodeID)
(input source-overrides g/Any)
(output template-path g/Str (g/fnk [id] (str id "/")))
(output node-overrides g/Any :cached (g/fnk [id _properties source-overrides]
(merge (properties->overrides id _properties) source-overrides)))
(output node-ids IDMap (g/fnk [_node-id id node-ids] (into {id _node-id} node-ids))))
(g/defnode Layout
(property name g/Str)
(property nodes g/Any
(set (fn [evaluation-context self _ new-value]
(let [basis (:basis evaluation-context)
current-tree (g/node-feeding-into basis self :node-tree)]
(concat
(if current-tree
(g/delete-node current-tree)
[])
(let [scene (ffirst (g/targets-of basis self :_node-id))
node-tree (g/node-value scene :node-tree evaluation-context)]
(g/override node-tree {}
(fn [evaluation-context id-mapping]
(let [node-tree-or (id-mapping node-tree)]
(for [[from to] [[:_node-id :node-tree]]]
(g/connect node-tree-or from self to)))))))))))
(input node-tree g/NodeID :cascade-delete)
(input id-prefix g/Str))
(def ^:private node-tree-inputs [[:_node-id :nodes]
[:node-ids :node-ids]
[:node-overrides :node-overrides]])
(def ^:private node-tree-outputs [[:id-prefix :id-prefix]])
(defn- add-node [graph scene node-tree node-type props]
(g/make-nodes graph [n [node-type props]]
(for [[output input] node-tree-inputs]
(g/connect n output node-tree input))
(for [[output input] node-tree-outputs]
(g/connect node-tree output n input))))
(defn- add-layout [graph scene name]
(g/make-nodes graph [n [Layout :name name]]
(g/connect n :_node-id scene :layouts)
(g/connect scene :id-prefix n :id-prefix)
(g/set-property n :nodes {})))
(defn- load-scene [graph path nodes]
(let [resource (->PathResource path)]
(g/make-nodes graph [scene [Scene :resource resource]
node-tree [NodeTree]]
(for [[from to] [[:_node-id :node-tree]
[:node-ids :node-ids]
[:node-overrides :node-overrides]]]
(g/connect node-tree from scene to))
(for [[from to] [[:id-prefix :id-prefix]]]
(g/connect scene from node-tree to))
(g/update-graph-value graph :resources assoc resource scene)
(reduce (fn [tx [node-type props]]
(into tx (add-node graph scene node-tree node-type props)))
[] nodes))))
(defn- make-scene! [graph path nodes]
(when (nil? (g/graph-value graph :resources))
(g/set-graph-value! graph :resources {}))
(ts/tx-nodes (load-scene graph path nodes)))
(defn- has-node? [scene node-id]
(contains? (g/node-value scene :node-ids) node-id))
(defn- node-by-id [scene node-id]
(get (g/node-value scene :node-ids) node-id))
(defn- target [n label]
(ffirst (g/targets-of n label)))
(deftest scene-loading
(ts/with-clean-system
(let [[scene _ node] (make-scene! world "my-scene" [[VisualNode {:id "my-node" :value "initial"}]])
overrides {"my-template/my-node" {:value "new value"}}
[super-scene _ template] (make-scene! world "my-super-scene" [[Template {:id "my-template" :template {:path "my-scene" :overrides overrides}}]])]
(is (= "initial" (g/node-value node :value)))
(let [or-node (get (g/node-value template :node-ids) "my-template/my-node")]
(is (= "new value" (g/node-value or-node :value))))
(is (= overrides (select-keys (g/node-value template :node-overrides) (keys overrides)))))))
(deftest scene-loading-with-override-values
(ts/with-clean-system
(let [scene-overrides {"template/my-node" {:value "scene-override"}}
super-overrides {"super-template/template/my-node" {:value "super-override"}}]
(g/transact (concat
(load-scene world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
(load-scene world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides scene-overrides}}]])
(load-scene world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides super-overrides}}]])))
(doseq [[actual expected] (mapv (fn [[s-path id expected]] [(-> s-path
(->> (scene-by-path world))
(node-by-id id)
(g/node-value :node-overrides))
expected])
[["scene" "template" scene-overrides]
["super-scene" "super-template" super-overrides]])]
(is (= expected (select-keys actual (keys expected))))))))
(deftest hierarchical-ids
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])]
(is (has-node? sub-scene "my-node"))
(is (has-node? scene "template/my-node"))
(is (has-node? super-scene "super-template/template/my-node"))
(let [tmp (node-by-id super-scene "super-template/template")]
(g/transact (g/set-property sub-scene :resource (->PathResource "sub-scene2")))
(is (= "sub-scene2" (get-in (g/node-value tmp :template) [:resource :path])))))))
(deftest delete-middle
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])
middle (node-by-id scene "template")
super-middle (node-by-id super-scene "super-template/template")]
(is (has-node? super-scene "super-template/template"))
(g/transact (g/delete-node middle))
(is (not (has-node? super-scene "super-template/template")))
(is (nil? (g/node-by-id super-middle))))))
(deftest sibling-templates
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]
[Template {:id "template1" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])]
(is (has-node? scene "template/my-node"))
(is (has-node? scene "template1/my-node"))
(is (has-node? super-scene "super-template/template/my-node"))
(is (has-node? super-scene "super-template/template1/my-node")))))
(deftest new-sibling-delete-repeat
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene scene-tree] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])]
(dotimes [i 5]
(let [[new-tmpl] (ts/tx-nodes (add-node world scene scene-tree Template {:id "new-template" :template {:path "sub-scene" :overrides {}}}))]
(is (contains? (g/node-value (node-by-id scene "new-template") :node-overrides) "new-template/my-node"))
(g/transact (g/delete-node new-tmpl)))))))
(deftest change-override
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])
[sub-scene2] (make-scene! world "sub-scene2" [[VisualNode {:id "my-node2" :value ""}]])]
(g/transact (g/transfer-overrides {sub-scene sub-scene2}))
(is (empty? (g/overrides sub-scene)))
(is (has-node? super-scene "super-template/template/my-node2")))))
(deftest new-node-deep-override
(ts/with-clean-system
(let [[sub-scene sub-tree] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])
[super-super-scene] (make-scene! world "super-super-scene" [[Template {:id "super-super-template" :template {:path "super-scene" :overrides {}}}]])]
(g/transact (add-node world sub-scene sub-tree VisualNode {:id "my-node2"}))
(is (has-node? super-super-scene "super-super-template/super-template/template/my-node2")))))
;; Bug occurring in properties in overloads
(deftest scene-paths
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])
template (node-by-id super-scene "super-template/template")
or-scene (ffirst (g/sources-of template :template-resource))]
(is (= "sub-scene" (:path (g/node-value (g/override-original or-scene) :resource)))))))
;; Simulated layout problem
(deftest template-layouts
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]])
[sub-layout] (ts/tx-nodes (add-layout world sub-scene "Portrait"))]
(is (nil? (g/node-value sub-layout :id-prefix)))
(is (not (nil? (g/node-value (first (g/overrides sub-layout)) :id-prefix)))))))
;; User-defined dynamic properties
(g/defnode Script
(property script-properties g/Any)
(output _properties g/Properties :cached (g/fnk [_node-id _declared-properties script-properties]
(-> _declared-properties
(update :properties dissoc :script-properties)
(update :properties merge (into {} (map (fn [[key value]] [key {:value value
:type (type value)
:node-id _node-id}]) script-properties)))
(update :display-order (comp vec (partial remove #{:script-properties})))))))
(g/defnode Component
(property id g/Str)
(property component g/Any
(set (fn [evaluation-context self old-value new-value]
(let [basis (:basis evaluation-context)]
(concat
(if-let [instance (g/node-value self :instance evaluation-context)]
(g/delete-node instance)
[])
(let [gid (g/node-id->graph-id self)
path (:path new-value)]
(if-let [script (get (g/graph-value basis gid :resources) path)]
(g/override script {}
(fn [evaluation-context id-mapping]
(let [or-script (id-mapping script)
script-props (g/node-value script :_properties evaluation-context)
set-prop-data (for [[key value] (:overrides new-value)]
(g/set-property or-script key value))
conn-data (for [[src tgt] [[:_node-id :instance]
[:_properties :script-properties]]]
(g/connect or-script src self tgt))]
(concat set-prop-data conn-data))))
[])))))))
(input instance g/NodeID :cascade-delete)
(input script-properties g/Properties)
(output _properties g/Properties (g/fnk [_declared-properties script-properties]
(-> _declared-properties
(update :properties merge (:properties script-properties))
(update :display-order concat (:display-order script-properties))))))
(deftest custom-properties
(ts/with-clean-system
(let [[script comp] (ts/tx-nodes (g/make-nodes world [script [Script :script-properties {:speed 0}]]
(g/set-graph-value world :resources {"script.script" script}))
(g/make-nodes world [comp [Component :component {:path "script.script" :overrides {:speed 10}}]]))]
(let [p (get-in (g/node-value comp :_properties) [:properties :speed])]
(is (= 10 (:value p)))
(is (= 0 (:original-value p)))
(g/transact (g/set-property (:node-id p) :speed 20))
(let [p' (get-in (g/node-value comp :_properties) [:properties :speed])]
(is (= 20 (:value p')))
(is (= 0 (:original-value p'))))
(g/transact (g/clear-property (:node-id p) :speed))
(let [p' (get-in (g/node-value comp :_properties) [:properties :speed])]
(is (= 0 (:value p')))
(is (not (contains? p' :original-value))))))))
;; Overloaded outputs with different types
(g/deftype XYZ [(s/one s/Num "x") (s/one s/Num "y") (s/one s/Num "z")])
(g/deftype Complex {s/Keyword Vector3d})
(g/defnode TypedOutputNode
(property value XYZ)
(output value Vector3d (g/fnk [value] (let [[x y z] value] (Vector3d. x y z))))
(output complex Complex (g/fnk [value] {:value value})))
(deftest overloaded-outputs-and-types
(ts/with-clean-system
(let [[a b] (ts/tx-nodes (g/make-nodes world [n [TypedOutputNode :value [1 2 3]]]
(g/override n)))]
(g/transact (g/set-property b :value [2 3 4]))
(is (not= (g/node-value b :complex) (g/node-value a :complex))))))
;; Dynamic property production
(g/defnode IDNode
(input super-id g/Str)
(property id g/Str (value (g/fnk [_node-id super-id id] (if super-id (str super-id "/" id) id)))))
(deftest dynamic-id-in-properties
(ts/with-clean-system
(let [[node parent sub] (ts/tx-nodes (g/make-nodes world [node [IDNode :id "child-id"]
parent [IDNode :id "parent-id"]]
(g/override node {}
(fn [evaluation-context id-mapping]
(let [or-node (id-mapping node)]
(g/connect parent :id or-node :super-id))))))]
(is (= (g/node-value sub :id)
(get-in (g/node-value sub :_declared-properties) [:properties :id :value]))))))
;; Reload supported for overrides
(deftest reload-overrides
(ts/with-clean-system
(let [[node or-node] (ts/tx-nodes (g/make-nodes world [node [support/ReloadNode :my-value "reload-test"]]
(g/override node)))]
(g/transact (g/set-property or-node :my-value "new-value"))
(is (= "new-value" (get-in (g/node-value or-node :_properties) [:properties :my-value :value])))
(use 'dynamo.integration.override-test-support :reload)
(is (= "new-value" (get-in (g/node-value or-node :_properties) [:properties :my-value :value]))))))
;; Dependency rules
(defn- outs [nodes output]
(for [n nodes]
[n output]))
(defn- conn? [[src src-label tgt tgt-label]]
(let [basis (g/now)]
(and (g/connected? basis src src-label tgt tgt-label)
(contains? (into #{} (gt/sources basis tgt tgt-label)) [src src-label])
(contains? (into #{} (gt/targets basis src src-label)) [tgt tgt-label]))))
(defn- no-conn? [[src src-label tgt tgt-label]]
(let [basis (g/now)]
(and (not (g/connected? basis src src-label tgt tgt-label))
(not (contains? (into #{} (gt/sources basis tgt tgt-label)) [src src-label]))
(not (contains? (into #{} (gt/targets basis src src-label)) [tgt tgt-label])))))
(defn- deps [tgts]
(ts/graph-dependencies tgts))
(g/defnode TargetNode
(input in-value g/Str)
(output out-value g/Str (g/fnk [in-value] in-value)))
(deftest dep-rules
(ts/with-clean-system
(let [all (setup world 2)
[[main-0 sub-0]
[main-1 sub-1]
[main-2 sub-2]] all
mains (mapv first all)
subs (mapv second all)]
(testing "value fnk"
(is (every? (deps [[main-0 :a-property]]) (outs mains :virt-property))))
(testing "output"
(is (every? (deps [[main-0 :a-property]]) (outs mains :cached-output))))
(testing "connections"
(is (every? conn? (for [[m s] all]
[s :_node-id m :sub-nodes])))
(is (every? no-conn? (for [mi (range 3)
si (range 3)
:when (not= mi si)
:let [m (nth mains mi)
s (nth subs si)]]
[s :_node-id m :sub-nodes]))))))
(ts/with-clean-system
(let [[src tgt src-1] (ts/tx-nodes (g/make-nodes world [src [MainNode :a-property "reload-test"]
tgt TargetNode]
(g/connect src :a-property tgt :in-value)
(g/override src)))]
(testing "regular dep"
(is (every? (deps [[src :a-property]]) [[tgt :out-value]])))
(testing "no override deps"
(is (not-any? (deps [[src-1 :a-property]]) [[tgt :out-value]])))
(testing "connections"
(is (conn? [src :a-property tgt :in-value]))
(is (no-conn? [src-1 :a-property tgt :in-value])))))
(ts/with-clean-system
(let [[src tgt tgt-1] (ts/tx-nodes (g/make-nodes world [src [MainNode :a-property "reload-test"]
tgt TargetNode]
(g/connect src :a-property tgt :in-value)
(g/override tgt)))]
(testing "regular dep"
(is (every? (deps [[src :a-property]]) [[tgt :out-value] [tgt-1 :out-value]])))
(testing "connections"
(is (conn? [src :a-property tgt :in-value]))
(is (conn? [src :a-property tgt-1 :in-value])))))
(ts/with-clean-system
(let [[sub-scene] (make-scene! world "sub-scene" [[VisualNode {:id "my-node" :value ""}]])
[scene] (make-scene! world "scene" [[Template {:id "template" :template {:path "sub-scene" :overrides {}}}]
[Template {:id "template1" :template {:path "sub-scene" :overrides {}}}]])
[super-scene] (make-scene! world "super-scene" [[Template {:id "super-template" :template {:path "scene" :overrides {}}}]])
[tmpl-scene tmpl1-scene] (g/overrides sub-scene)
[tmpl-tree tmpl1-tree] (mapv #(g/node-value % :node-tree) [tmpl-scene tmpl1-scene])
[tmpl-sub tmpl1-sub] (mapv #(node-by-id scene %) ["template/my-node" "template1/my-node"])]
(is (conn? [tmpl-sub :node-overrides tmpl-tree :node-overrides]))
(is (conn? [tmpl1-sub :node-overrides tmpl1-tree :node-overrides]))
(is (conn? [tmpl-tree :node-overrides tmpl-scene :node-overrides]))
(is (conn? [tmpl1-tree :node-overrides tmpl1-scene :node-overrides])))))
(g/defnode GameObject
(input components g/NodeID :array :cascade-delete))
(g/defnode GameObjectInstance
(input source g/NodeID :cascade-delete))
(g/defnode Collection
(input instances g/NodeID :array :cascade-delete))
(deftest override-created-on-connect
(ts/with-clean-system
(let [[script] (ts/tx-nodes (g/make-nodes world [script Script]))
[go comp or-script] (ts/tx-nodes (g/make-nodes world [go GameObject
comp Component]
(g/override script {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-script (id-mapping script)]
(concat
(g/connect comp :_node-id go :components)
(g/connect or-script :_node-id comp :instance)))))))
[coll inst or-go] (ts/tx-nodes (g/make-nodes world [coll Collection
inst GameObjectInstance]
(g/override go {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-go (id-mapping go)]
(concat
(g/connect inst :_node-id coll :instances)
(g/connect or-go :_node-id inst :source)))))))
[comp-2 or-script-2] (ts/tx-nodes (g/make-nodes world [comp Component]
(g/override script {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-script (id-mapping script)]
(g/connect or-script :_node-id comp :instance))))))
nodes-on-connect (ts/tx-nodes (g/connect comp-2 :_node-id go :components))]
;; 1 override for the component node and one for the script, w.r.t the collection
(is (= 2 (count nodes-on-connect))))))
(deftest cascade-delete-avoided
(ts/with-clean-system
(let [[script] (ts/tx-nodes (g/make-nodes world [script Script]))
[go comp or-script] (ts/tx-nodes (g/make-nodes world [go GameObject
comp Component]
(g/override script {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-script (id-mapping script)]
(concat
(g/connect comp :_node-id go :components)
(g/connect or-script :_node-id comp :instance)))))))
[coll inst or-go] (ts/tx-nodes (g/make-nodes world [coll Collection
inst GameObjectInstance]
(g/override go {:traverse? (constantly false)}
(fn [evaluation-context id-mapping]
(let [or-go (id-mapping go)]
(concat
(g/connect inst :_node-id coll :instances)
(g/connect or-go :_node-id inst :source)))))))]
(is (every? some? (map g/node-by-id [coll inst or-go go comp or-script script])))
(g/transact (g/delete-node coll))
(is (every? nil? (map g/node-by-id [coll inst or-go])))
(is (every? some? (map g/node-by-id [go comp or-script script])))
(g/transact (g/delete-node go))
(is (every? nil? (map g/node-by-id [coll inst or-go go comp or-script])))
(is (every? some? (map g/node-by-id [script])))
(g/transact (g/delete-node script))
(is (every? nil? (map g/node-by-id [coll inst or-go go comp or-script script]))))))
(deftest auto-add-and-delete
(ts/with-clean-system
(let [[script] (ts/tx-nodes (g/make-nodes world [script Script]))
[go] (ts/tx-nodes (g/make-nodes world [go GameObject]))
[[coll0 go-inst0 or-go0]
[coll1 go-inst1 or-go1]] (for [i (range 2)]
(ts/tx-nodes (g/make-nodes world [coll Collection
go-inst GameObjectInstance]
(g/connect go-inst :_node-id coll :instances)
(g/override go {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-go (id-mapping go)]
(g/connect or-go :_node-id go-inst :source)))))))
[comp or-script] (ts/tx-nodes (g/make-nodes world [comp Component]
(g/override script {:traverse? (constantly true)}
(fn [evaluation-context id-mapping]
(let [or-script (id-mapping script)]
(concat
(g/connect or-script :_node-id comp :instance)
(g/connect comp :_node-id go :components)))))))]
(let [all-script-nodes (doall (tree-seq (constantly true) g/overrides script))]
(is (= 4 (count all-script-nodes)))
(g/transact (g/delete-node comp))
(is (= 1 (count (keep g/node-by-id all-script-nodes))))
(is (empty? (mapcat g/overrides all-script-nodes)))))))
(defn- remove-idx [v ix]
(into (subvec v 0 ix) (subvec v (inc ix))))
(defn- all-system-nodes []
(into []
(mapcat #(keys (:nodes (second %))))
(:graphs @g/*the-system*)))
(deftest symmetric-input-output-arcs
(test-util/with-loaded-project "test/resources/override_project"
(let [all-nodes (all-system-nodes)
node-outputs (reduce (fn [result n]
(reduce (fn [result label]
(assoc-in result [n label] (vec (g/labelled-outputs n label))))
result
(g/output-labels (g/node-type* n))))
{}
all-nodes)
node-inputs (reduce (fn [result n]
(reduce (fn [result label]
(assoc-in result [n label] (vec (g/labelled-inputs n label))))
result
(g/input-labels (g/node-type* n))))
{}
all-nodes)]
(testing "outputs and labelled-outputs report the same arcs, and same cardinality of arcs"
(doseq [node all-nodes]
(let [outputs (g/outputs node)
outputs-freqs (frequencies outputs)
merged-outputs (into [] cat (vals (node-outputs node)))
merged-outputs-freqs (frequencies merged-outputs)
freq-diff [:all-merged (not-empty (set/difference (set outputs-freqs) (set merged-outputs-freqs)))
:merged-all (not-empty (set/difference (set merged-outputs-freqs) (set outputs-freqs)))]]
(is (= freq-diff [:all-merged nil :merged-all nil])))))
(testing "inputs and labelled-inputs report the same arcs, and same cardinality of arcs"
(doseq [node all-nodes]
(let [inputs (g/inputs node)
inputs-freqs (frequencies inputs)
merged-inputs (into [] cat (vals (node-inputs node)))
merged-inputs-freqs (frequencies merged-inputs)
freq-diff [:all-merged (not-empty (set/difference (set inputs-freqs) (set merged-inputs-freqs)))
:merged-all (not-empty (set/difference (set merged-inputs-freqs) (set inputs-freqs)))]]
(is (= freq-diff [:all-merged nil :merged-all nil])))))
(testing "For all outputs, there is a corresponding input and vice versa"
(let [inputs (atom node-inputs)] ; we tick off one input arc per output arc
(doseq [node all-nodes]
(loop [outputs (g/outputs node)]
(when (seq outputs)
(let [output (first outputs)
target (nth output 2)
target-label (nth output 3)
input-index (first (util/positions #(= output %) (get-in @inputs [target target-label])))]
(is (some? input-index) (str "missing input for " output " in:\n" (get-in @inputs [target target-label])))
(swap! inputs update-in [target target-label] remove-idx input-index)
(recur (rest outputs))))))
(is (empty? (into [] (comp (map vals) cat cat) (vals @inputs)))))) ; should end up with no input arcs left
(testing "Sanity: all inputs == all outputs"
(let [output-freqs (frequencies (mapcat g/outputs all-nodes))
input-freqs (frequencies (mapcat g/inputs all-nodes))]
(is (= output-freqs input-freqs)))))))
|
[
{
"context": "(testing \"swaps first and last names\"\n (is (= \"Murakami, Haruki\" (normalize \"Haruki Murakami\"))))\n #_(testing \"t",
"end": 392,
"score": 0.986333429813385,
"start": 376,
"tag": "NAME",
"value": "Murakami, Haruki"
},
{
"context": " names\"\n (is (= \"Murakami, Haruki\" (normalize \"Haruki Murakami\"))))\n #_(testing \"trims leading and trailing whi",
"end": 421,
"score": 0.9930718541145325,
"start": 406,
"tag": "NAME",
"value": "Haruki Murakami"
},
{
"context": " #_(testing \"initializes middle name\"\n (is (= \"Thoreau, Henry D.\" (normalize \"Henry David Thoreau\"))))\n ",
"end": 591,
"score": 0.8925837278366089,
"start": 584,
"tag": "NAME",
"value": "Thoreau"
},
{
"context": "ing \"initializes middle name\"\n (is (= \"Thoreau, Henry D.\" (normalize \"Henry David Thoreau\"))))\n #_(testing",
"end": 600,
"score": 0.9628496170043945,
"start": 593,
"tag": "NAME",
"value": "Henry D"
},
{
"context": " name\"\n (is (= \"Thoreau, Henry D.\" (normalize \"Henry David Thoreau\"))))\n #_(testing \"does not initialize one letter",
"end": 634,
"score": 0.9990187287330627,
"start": 615,
"tag": "NAME",
"value": "Henry David Thoreau"
},
{
"context": "ot initialize one letter middle name\"\n (is (= \"Truman, Harry S\" (normalize \"Harry S Truman\"))))\n #_(tes",
"end": 716,
"score": 0.8927218317985535,
"start": 710,
"tag": "NAME",
"value": "Truman"
},
{
"context": "ialize one letter middle name\"\n (is (= \"Truman, Harry S\" (normalize \"Harry S Truman\"))))\n #_(testing \"in",
"end": 725,
"score": 0.993541419506073,
"start": 718,
"tag": "NAME",
"value": "Harry S"
},
{
"context": "le name\"\n (is (= \"Truman, Harry S\" (normalize \"Harry S Truman\"))))\n #_(testing \"initializes each of multiple m",
"end": 753,
"score": 0.9979761838912964,
"start": 739,
"tag": "NAME",
"value": "Harry S Truman"
},
{
"context": "alizes each of multiple middle names\"\n (is (= \"Louis-Dreyfus, Julia S. E.\" (normalize \"Julia Scarlett Elizabet",
"end": 841,
"score": 0.9960978031158447,
"start": 828,
"tag": "NAME",
"value": "Louis-Dreyfus"
},
{
"context": " multiple middle names\"\n (is (= \"Louis-Dreyfus, Julia S. E.\" (normalize \"Julia Scarlett Elizabeth Louis-Dreyfu",
"end": 853,
"score": 0.9773581624031067,
"start": 843,
"tag": "NAME",
"value": "Julia S. E"
},
{
"context": " (is (= \"Louis-Dreyfus, Julia S. E.\" (normalize \"Julia Scarlett Elizabeth Louis-Dreyfus\"))))\n #_(testing \"appends suffixes to end\"\n (",
"end": 906,
"score": 0.9987165927886963,
"start": 868,
"tag": "NAME",
"value": "Julia Scarlett Elizabeth Louis-Dreyfus"
},
{
"context": " #_(testing \"appends suffixes to end\"\n (is (= \"King, Martin L., Jr.\" (normalize \"Martin Luther King, ",
"end": 967,
"score": 0.8095554113388062,
"start": 963,
"tag": "NAME",
"value": "King"
},
{
"context": "esting \"appends suffixes to end\"\n (is (= \"King, Martin L., Jr.\" (normalize \"Martin Luther King, Jr.\"))))\n #",
"end": 977,
"score": 0.7194318771362305,
"start": 969,
"tag": "NAME",
"value": "Martin L"
},
{
"context": "nd\"\n (is (= \"King, Martin L., Jr.\" (normalize \"Martin Luther King, Jr.\"))))\n #_(testing \"throws when name contains",
"end": 1015,
"score": 0.9690427184104919,
"start": 997,
"tag": "NAME",
"value": "Martin Luther King"
},
{
"context": "(is (thrown? IllegalArgumentException (normalize \"Thurston, Howell, III\")))))\n",
"end": 1140,
"score": 0.925417423248291,
"start": 1132,
"tag": "NAME",
"value": "Thurston"
},
{
"context": "wn? IllegalArgumentException (normalize \"Thurston, Howell, III\")))))\n",
"end": 1148,
"score": 0.7996232509613037,
"start": 1142,
"tag": "NAME",
"value": "Howell"
},
{
"context": "galArgumentException (normalize \"Thurston, Howell, III\")))))\n",
"end": 1153,
"score": 0.6198213696479797,
"start": 1150,
"tag": "NAME",
"value": "III"
}
] | clojure/test/name_normalizer/core_test.clj | duianto/name-normalizer | 21 | (ns name-normalizer.core-test
(:require [clojure.test :refer :all]
[name-normalizer.core :refer :all]))
(deftest a-name-normalizer
(testing "returns empty string when passed an empty string"
(is (= "" (normalize ""))))
#_(testing "returns single word name"
(is (= "Plato" (normalize "Plato"))))
#_(testing "swaps first and last names"
(is (= "Murakami, Haruki" (normalize "Haruki Murakami"))))
#_(testing "trims leading and trailing whitespace"
(is (= "Boi, Big" (normalize " Big Boi "))))
#_(testing "initializes middle name"
(is (= "Thoreau, Henry D." (normalize "Henry David Thoreau"))))
#_(testing "does not initialize one letter middle name"
(is (= "Truman, Harry S" (normalize "Harry S Truman"))))
#_(testing "initializes each of multiple middle names"
(is (= "Louis-Dreyfus, Julia S. E." (normalize "Julia Scarlett Elizabeth Louis-Dreyfus"))))
#_(testing "appends suffixes to end"
(is (= "King, Martin L., Jr." (normalize "Martin Luther King, Jr."))))
#_(testing "throws when name contains two commas"
(is (thrown? IllegalArgumentException (normalize "Thurston, Howell, III")))))
| 37305 | (ns name-normalizer.core-test
(:require [clojure.test :refer :all]
[name-normalizer.core :refer :all]))
(deftest a-name-normalizer
(testing "returns empty string when passed an empty string"
(is (= "" (normalize ""))))
#_(testing "returns single word name"
(is (= "Plato" (normalize "Plato"))))
#_(testing "swaps first and last names"
(is (= "<NAME>" (normalize "<NAME>"))))
#_(testing "trims leading and trailing whitespace"
(is (= "Boi, Big" (normalize " Big Boi "))))
#_(testing "initializes middle name"
(is (= "<NAME>, <NAME>." (normalize "<NAME>"))))
#_(testing "does not initialize one letter middle name"
(is (= "<NAME>, <NAME>" (normalize "<NAME>"))))
#_(testing "initializes each of multiple middle names"
(is (= "<NAME>, <NAME>." (normalize "<NAME>"))))
#_(testing "appends suffixes to end"
(is (= "<NAME>, <NAME>., Jr." (normalize "<NAME>, Jr."))))
#_(testing "throws when name contains two commas"
(is (thrown? IllegalArgumentException (normalize "<NAME>, <NAME>, <NAME>")))))
| true | (ns name-normalizer.core-test
(:require [clojure.test :refer :all]
[name-normalizer.core :refer :all]))
(deftest a-name-normalizer
(testing "returns empty string when passed an empty string"
(is (= "" (normalize ""))))
#_(testing "returns single word name"
(is (= "Plato" (normalize "Plato"))))
#_(testing "swaps first and last names"
(is (= "PI:NAME:<NAME>END_PI" (normalize "PI:NAME:<NAME>END_PI"))))
#_(testing "trims leading and trailing whitespace"
(is (= "Boi, Big" (normalize " Big Boi "))))
#_(testing "initializes middle name"
(is (= "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI." (normalize "PI:NAME:<NAME>END_PI"))))
#_(testing "does not initialize one letter middle name"
(is (= "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI" (normalize "PI:NAME:<NAME>END_PI"))))
#_(testing "initializes each of multiple middle names"
(is (= "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI." (normalize "PI:NAME:<NAME>END_PI"))))
#_(testing "appends suffixes to end"
(is (= "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI., Jr." (normalize "PI:NAME:<NAME>END_PI, Jr."))))
#_(testing "throws when name contains two commas"
(is (thrown? IllegalArgumentException (normalize "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI")))))
|
[
{
"context": " \n ] }\n :user {:name \"user\"\n :fields [ [:created_at :timestamp \"NOT",
"end": 2409,
"score": 0.9994183778762817,
"start": 2405,
"tag": "USERNAME",
"value": "user"
},
{
"context": " \"microcms\"\n :password \"microcms\"})\n :schema cms-schema)",
"end": 2999,
"score": 0.9993895292282104,
"start": 2991,
"tag": "PASSWORD",
"value": "microcms"
}
] | src/clj/microcms/model.clj | martinskou/microcms | 1 | (ns microcms.model
(:require [korma.core :refer :all]
[korma.db :refer :all]
[clojure.java.jdbc :as sql]
[clojure.pprint :refer [pprint]]
))
(def cms-schema {
:pages {:name "pages"
:fields [ [:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:modified_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:id "MEDIUMINT NOT NULL AUTO_INCREMENT" :primary :key]
[:fkey_parent :int]
[:idx :int]
[:inherit_type "varchar(100)"] ; (P)arent,(I)index,In(H)erit,(S)tate,(V)ariant,(T)emplate,(C)ontent
[:fkey_inherit_from :int]
[:state "varchar(100)"]
[:variant "varchar(100)"]
[:template "varchar(200)"]
[:url "varchar(200)"]
[:slug "varchar(100)"]
[:caption "varchar(60)"]
[:title "varchar(200)"]
[:subtitle "varchar(200)"]
[:teaser "text"]
[:thumbnail "varchar(200)"]
[:keyword "text"]
[:metatags "text"] ] }
:content {:name "content"
:fields [ [:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:modified_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:id "MEDIUMINT NOT NULL AUTO_INCREMENT" :primary :key]
[:fkey_page_id :int]
[:idx :int]
[:grp "varchar(100)"]
[:caption "varchar(60)"]
[:title "varchar(200)"]
[:subtitle "varchar(200)"]
[:teaser "text"]
[:text "text"]
[:image_1 "varchar(200)"]
[:image_1_alt "varchar(200)"]
[:image_1_link "varchar(200)"]
[:link_1 "varchar(200)"]
[:link_1_text "varchar(200)"]
[:data "text"]
] }
:user {:name "user"
:fields [ [:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:modified_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:id "MEDIUMINT NOT NULL AUTO_INCREMENT" :primary :key]
[:email "varchar(100)"]
[:salt "varchar(100)"]
[:digest "varchar(100)"]
]}
})
(def cms-db-map (assoc (mysql {:db "microcms"
:user "microcms"
:password "microcms"})
:schema cms-schema))
; a db-map is a map with connection and schema information. No reason to keep them seperate.
;(def cms-korma-db cms-db-map)
(defdb cms-korma-db cms-db-map)
;(defentity pages)
;;;
;;; JDBC Functions
;;;
;;; A small "migration" framework.
;;;
(defn db-exists-table?
([table-name] (db-exists-table? table-name cms-db-map))
([table-name db-map] (not (empty? (sql/query db-map (str "SHOW TABLES LIKE '" table-name "'"))))))
(defn db-exists-field?
([table field] (db-exists-field? table field cms-db-map))
([table field db-map] (not (empty? (sql/query db-map (str "SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='microcms' AND TABLE_NAME='" table "' AND COLUMN_NAME='" field "'"))))))
(defn db-create-table
([table] (db-create-table table cms-db-map))
([table db-map]
(sql/db-do-commands db-map
(println "CREATE" (get table :name))
(apply sql/create-table-ddl (cons (get table :name) (get table :fields))))))
(defn db-drop-table
([table-name] (db-drop-table table-name cms-db-map))
([table-name db-map]
(println "DROP" table-name)
(when (db-exists-table? table-name)
(sql/db-do-commands db-map
(sql/drop-table-ddl table-name)))))
(defn db-create-fields [table]
(let [tablename (table :name)
field (last (table :fields))
fieldname (subs (str (first field)) 1)
fieldtype (second field)]
(when (not (db-exists-field? tablename fieldname))
(do
(println "ALTER" tablename fieldname)
(sql/db-do-commands cms-db-map (str "ALTER TABLE `" tablename "` ADD `" fieldname "` " fieldtype ))))))
(defn db-create [drop?]
; create or update definition of all table and fields in schema
(when drop?
(doall (map #(db-drop-table (get-in cms-db-map [:schema % :name])) (keys (cms-db-map :schema)))))
(defn update-table [tablemap]
(if (not (db-exists-table? (tablemap :name)))
(db-create-table tablemap)
(db-create-fields tablemap)))
(doall (map #(update-table (get-in cms-db-map [:schema %])) (keys (cms-db-map :schema)))))
| 111807 | (ns microcms.model
(:require [korma.core :refer :all]
[korma.db :refer :all]
[clojure.java.jdbc :as sql]
[clojure.pprint :refer [pprint]]
))
(def cms-schema {
:pages {:name "pages"
:fields [ [:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:modified_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:id "MEDIUMINT NOT NULL AUTO_INCREMENT" :primary :key]
[:fkey_parent :int]
[:idx :int]
[:inherit_type "varchar(100)"] ; (P)arent,(I)index,In(H)erit,(S)tate,(V)ariant,(T)emplate,(C)ontent
[:fkey_inherit_from :int]
[:state "varchar(100)"]
[:variant "varchar(100)"]
[:template "varchar(200)"]
[:url "varchar(200)"]
[:slug "varchar(100)"]
[:caption "varchar(60)"]
[:title "varchar(200)"]
[:subtitle "varchar(200)"]
[:teaser "text"]
[:thumbnail "varchar(200)"]
[:keyword "text"]
[:metatags "text"] ] }
:content {:name "content"
:fields [ [:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:modified_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:id "MEDIUMINT NOT NULL AUTO_INCREMENT" :primary :key]
[:fkey_page_id :int]
[:idx :int]
[:grp "varchar(100)"]
[:caption "varchar(60)"]
[:title "varchar(200)"]
[:subtitle "varchar(200)"]
[:teaser "text"]
[:text "text"]
[:image_1 "varchar(200)"]
[:image_1_alt "varchar(200)"]
[:image_1_link "varchar(200)"]
[:link_1 "varchar(200)"]
[:link_1_text "varchar(200)"]
[:data "text"]
] }
:user {:name "user"
:fields [ [:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:modified_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:id "MEDIUMINT NOT NULL AUTO_INCREMENT" :primary :key]
[:email "varchar(100)"]
[:salt "varchar(100)"]
[:digest "varchar(100)"]
]}
})
(def cms-db-map (assoc (mysql {:db "microcms"
:user "microcms"
:password "<PASSWORD>"})
:schema cms-schema))
; a db-map is a map with connection and schema information. No reason to keep them seperate.
;(def cms-korma-db cms-db-map)
(defdb cms-korma-db cms-db-map)
;(defentity pages)
;;;
;;; JDBC Functions
;;;
;;; A small "migration" framework.
;;;
(defn db-exists-table?
([table-name] (db-exists-table? table-name cms-db-map))
([table-name db-map] (not (empty? (sql/query db-map (str "SHOW TABLES LIKE '" table-name "'"))))))
(defn db-exists-field?
([table field] (db-exists-field? table field cms-db-map))
([table field db-map] (not (empty? (sql/query db-map (str "SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='microcms' AND TABLE_NAME='" table "' AND COLUMN_NAME='" field "'"))))))
(defn db-create-table
([table] (db-create-table table cms-db-map))
([table db-map]
(sql/db-do-commands db-map
(println "CREATE" (get table :name))
(apply sql/create-table-ddl (cons (get table :name) (get table :fields))))))
(defn db-drop-table
([table-name] (db-drop-table table-name cms-db-map))
([table-name db-map]
(println "DROP" table-name)
(when (db-exists-table? table-name)
(sql/db-do-commands db-map
(sql/drop-table-ddl table-name)))))
(defn db-create-fields [table]
(let [tablename (table :name)
field (last (table :fields))
fieldname (subs (str (first field)) 1)
fieldtype (second field)]
(when (not (db-exists-field? tablename fieldname))
(do
(println "ALTER" tablename fieldname)
(sql/db-do-commands cms-db-map (str "ALTER TABLE `" tablename "` ADD `" fieldname "` " fieldtype ))))))
(defn db-create [drop?]
; create or update definition of all table and fields in schema
(when drop?
(doall (map #(db-drop-table (get-in cms-db-map [:schema % :name])) (keys (cms-db-map :schema)))))
(defn update-table [tablemap]
(if (not (db-exists-table? (tablemap :name)))
(db-create-table tablemap)
(db-create-fields tablemap)))
(doall (map #(update-table (get-in cms-db-map [:schema %])) (keys (cms-db-map :schema)))))
| true | (ns microcms.model
(:require [korma.core :refer :all]
[korma.db :refer :all]
[clojure.java.jdbc :as sql]
[clojure.pprint :refer [pprint]]
))
(def cms-schema {
:pages {:name "pages"
:fields [ [:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:modified_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:id "MEDIUMINT NOT NULL AUTO_INCREMENT" :primary :key]
[:fkey_parent :int]
[:idx :int]
[:inherit_type "varchar(100)"] ; (P)arent,(I)index,In(H)erit,(S)tate,(V)ariant,(T)emplate,(C)ontent
[:fkey_inherit_from :int]
[:state "varchar(100)"]
[:variant "varchar(100)"]
[:template "varchar(200)"]
[:url "varchar(200)"]
[:slug "varchar(100)"]
[:caption "varchar(60)"]
[:title "varchar(200)"]
[:subtitle "varchar(200)"]
[:teaser "text"]
[:thumbnail "varchar(200)"]
[:keyword "text"]
[:metatags "text"] ] }
:content {:name "content"
:fields [ [:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:modified_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:id "MEDIUMINT NOT NULL AUTO_INCREMENT" :primary :key]
[:fkey_page_id :int]
[:idx :int]
[:grp "varchar(100)"]
[:caption "varchar(60)"]
[:title "varchar(200)"]
[:subtitle "varchar(200)"]
[:teaser "text"]
[:text "text"]
[:image_1 "varchar(200)"]
[:image_1_alt "varchar(200)"]
[:image_1_link "varchar(200)"]
[:link_1 "varchar(200)"]
[:link_1_text "varchar(200)"]
[:data "text"]
] }
:user {:name "user"
:fields [ [:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:modified_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]
[:id "MEDIUMINT NOT NULL AUTO_INCREMENT" :primary :key]
[:email "varchar(100)"]
[:salt "varchar(100)"]
[:digest "varchar(100)"]
]}
})
(def cms-db-map (assoc (mysql {:db "microcms"
:user "microcms"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
:schema cms-schema))
; a db-map is a map with connection and schema information. No reason to keep them seperate.
;(def cms-korma-db cms-db-map)
(defdb cms-korma-db cms-db-map)
;(defentity pages)
;;;
;;; JDBC Functions
;;;
;;; A small "migration" framework.
;;;
(defn db-exists-table?
([table-name] (db-exists-table? table-name cms-db-map))
([table-name db-map] (not (empty? (sql/query db-map (str "SHOW TABLES LIKE '" table-name "'"))))))
(defn db-exists-field?
([table field] (db-exists-field? table field cms-db-map))
([table field db-map] (not (empty? (sql/query db-map (str "SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='microcms' AND TABLE_NAME='" table "' AND COLUMN_NAME='" field "'"))))))
(defn db-create-table
([table] (db-create-table table cms-db-map))
([table db-map]
(sql/db-do-commands db-map
(println "CREATE" (get table :name))
(apply sql/create-table-ddl (cons (get table :name) (get table :fields))))))
(defn db-drop-table
([table-name] (db-drop-table table-name cms-db-map))
([table-name db-map]
(println "DROP" table-name)
(when (db-exists-table? table-name)
(sql/db-do-commands db-map
(sql/drop-table-ddl table-name)))))
(defn db-create-fields [table]
(let [tablename (table :name)
field (last (table :fields))
fieldname (subs (str (first field)) 1)
fieldtype (second field)]
(when (not (db-exists-field? tablename fieldname))
(do
(println "ALTER" tablename fieldname)
(sql/db-do-commands cms-db-map (str "ALTER TABLE `" tablename "` ADD `" fieldname "` " fieldtype ))))))
(defn db-create [drop?]
; create or update definition of all table and fields in schema
(when drop?
(doall (map #(db-drop-table (get-in cms-db-map [:schema % :name])) (keys (cms-db-map :schema)))))
(defn update-table [tablemap]
(if (not (db-exists-table? (tablemap :name)))
(db-create-table tablemap)
(db-create-fields tablemap)))
(doall (map #(update-table (get-in cms-db-map [:schema %])) (keys (cms-db-map :schema)))))
|
[
{
"context": " one primary entry for each SOA record.\n\nsortlist 128.3.0.0\n\ndirectory\t/etc/namedb\n\n; type domain\t\tsource ",
"end": 229,
"score": 0.9997792840003967,
"start": 220,
"tag": "IP_ADDRESS",
"value": "128.3.0.0"
},
{
"context": "ckup file\n\ncache .\t\t\t\t\t\t\troot.cache\nprimary 0.0.127.IN-ADDR.ARPA\tlocalhost.rev\n\n; example secondary s",
"end": 349,
"score": 0.999703049659729,
"start": 342,
"tag": "IP_ADDRESS",
"value": "0.0.127"
},
{
"context": "secondary server config:\n; secondary Berkeley.EDU\t128.32.130.11 128.32.133.1\tucbhosts.bak\n; secondary 32.128.IN-A",
"end": 451,
"score": 0.9997411966323853,
"start": 438,
"tag": "IP_ADDRESS",
"value": "128.32.130.11"
},
{
"context": "er config:\n; secondary Berkeley.EDU\t128.32.130.11 128.32.133.1\tucbhosts.bak\n; secondary 32.128.IN-ADDR.ARPA\t128.",
"end": 464,
"score": 0.9997742772102356,
"start": 452,
"tag": "IP_ADDRESS",
"value": "128.32.133.1"
},
{
"context": "8.32.130.11 128.32.133.1\tucbhosts.bak\n; secondary 32.128.IN-ADDR.ARPA\t128.32.130.11 128.32.133.1\tucbhosts.",
"end": 496,
"score": 0.9996321201324463,
"start": 490,
"tag": "IP_ADDRESS",
"value": "32.128"
},
{
"context": "33.1\tucbhosts.bak\n; secondary 32.128.IN-ADDR.ARPA\t128.32.130.11 128.32.133.1\tucbhosts.rev.bak\n\n; example primary ",
"end": 523,
"score": 0.9997187852859497,
"start": 510,
"tag": "IP_ADDRESS",
"value": "128.32.130.11"
},
{
"context": "bak\n; secondary 32.128.IN-ADDR.ARPA\t128.32.130.11 128.32.133.1\tucbhosts.rev.bak\n\n; example primary server config",
"end": 536,
"score": 0.9990890026092529,
"start": 524,
"tag": "IP_ADDRESS",
"value": "128.32.133.1"
},
{
"context": "fig:\n; primary Berkeley.EDU\t\tucbhosts\n; primary 32.128.IN-ADDR.ARPA\tucbhosts.rev\n",
"end": 639,
"score": 0.9996252655982971,
"start": 633,
"tag": "IP_ADDRESS",
"value": "32.128"
}
] | netbsdsrc/etc/namedb/named.boot | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 46 | ; $NetBSD: named.boot,v 1.3 1997/02/15 10:02:32 mikel Exp $
; from @(#)named.boot 8.1 (Berkeley) 6/9/93
; boot file for secondary name server
; Note that there should be one primary entry for each SOA record.
sortlist 128.3.0.0
directory /etc/namedb
; type domain source host/file backup file
cache . root.cache
primary 0.0.127.IN-ADDR.ARPA localhost.rev
; example secondary server config:
; secondary Berkeley.EDU 128.32.130.11 128.32.133.1 ucbhosts.bak
; secondary 32.128.IN-ADDR.ARPA 128.32.130.11 128.32.133.1 ucbhosts.rev.bak
; example primary server config:
; primary Berkeley.EDU ucbhosts
; primary 32.128.IN-ADDR.ARPA ucbhosts.rev
| 23435 | ; $NetBSD: named.boot,v 1.3 1997/02/15 10:02:32 mikel Exp $
; from @(#)named.boot 8.1 (Berkeley) 6/9/93
; boot file for secondary name server
; Note that there should be one primary entry for each SOA record.
sortlist 192.168.127.12
directory /etc/namedb
; type domain source host/file backup file
cache . root.cache
primary 0.0.127.IN-ADDR.ARPA localhost.rev
; example secondary server config:
; secondary Berkeley.EDU 192.168.127.12 172.16.58.3 ucbhosts.bak
; secondary 32.128.IN-ADDR.ARPA 192.168.127.12 172.16.58.3 ucbhosts.rev.bak
; example primary server config:
; primary Berkeley.EDU ucbhosts
; primary 32.128.IN-ADDR.ARPA ucbhosts.rev
| true | ; $NetBSD: named.boot,v 1.3 1997/02/15 10:02:32 mikel Exp $
; from @(#)named.boot 8.1 (Berkeley) 6/9/93
; boot file for secondary name server
; Note that there should be one primary entry for each SOA record.
sortlist PI:IP_ADDRESS:192.168.127.12END_PI
directory /etc/namedb
; type domain source host/file backup file
cache . root.cache
primary 0.0.127.IN-ADDR.ARPA localhost.rev
; example secondary server config:
; secondary Berkeley.EDU PI:IP_ADDRESS:192.168.127.12END_PI PI:IP_ADDRESS:172.16.58.3END_PI ucbhosts.bak
; secondary 32.128.IN-ADDR.ARPA PI:IP_ADDRESS:192.168.127.12END_PI PI:IP_ADDRESS:172.16.58.3END_PI ucbhosts.rev.bak
; example primary server config:
; primary Berkeley.EDU ucbhosts
; primary 32.128.IN-ADDR.ARPA ucbhosts.rev
|
[
{
"context": ";; Copyright © 2015-2019 Esko Luontola\n;; This software is released under the Apache Lic",
"end": 38,
"score": 0.9998798370361328,
"start": 25,
"tag": "NAME",
"value": "Esko Luontola"
}
] | src/territory_bro/gis.clj | JessRoberts/territory_assistant | 0 | ;; Copyright © 2015-2019 Esko Luontola
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.gis
(:require [territory-bro.db :as db]))
(def ^:private query! (db/compile-queries "db/hugsql/gis.sql"))
(defn- format-gis-change [change]
change)
(defn get-gis-changes
([conn]
(get-gis-changes conn {}))
([conn search]
(->> (query! conn :get-gis-changes search)
(map format-gis-change)
(doall))))
| 109447 | ;; Copyright © 2015-2019 <NAME>
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.gis
(:require [territory-bro.db :as db]))
(def ^:private query! (db/compile-queries "db/hugsql/gis.sql"))
(defn- format-gis-change [change]
change)
(defn get-gis-changes
([conn]
(get-gis-changes conn {}))
([conn search]
(->> (query! conn :get-gis-changes search)
(map format-gis-change)
(doall))))
| true | ;; Copyright © 2015-2019 PI:NAME:<NAME>END_PI
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.gis
(:require [territory-bro.db :as db]))
(def ^:private query! (db/compile-queries "db/hugsql/gis.sql"))
(defn- format-gis-change [change]
change)
(defn get-gis-changes
([conn]
(get-gis-changes conn {}))
([conn search]
(->> (query! conn :get-gis-changes search)
(map format-gis-change)
(doall))))
|
[
{
"context": " :corp :click 1)\n (play-from-hand state :corp \"Hunter\" \"HQ\")\n (let [hunter (get-ice state :hq 0)]\n ",
"end": 7162,
"score": 0.8071572780609131,
"start": 7156,
"tag": "NAME",
"value": "Hunter"
},
{
"context": "ner took 6 tags\"))))\n\n(deftest mushin-no-shin\n ;; Mushin No Shin - Add 3 advancements to a card; prevent rez/score",
"end": 32026,
"score": 0.8558354377746582,
"start": 32012,
"tag": "NAME",
"value": "Mushin No Shin"
},
{
"context": "default-runner))\n (play-from-hand state :corp \"Mushin No Shin\")\n (prompt-select :corp (find-card \"Ronin\" (:h",
"end": 32296,
"score": 0.993962824344635,
"start": 32282,
"tag": "NAME",
"value": "Mushin No Shin"
},
{
"context": "in No Shin\")\n (prompt-select :corp (find-card \"Ronin\" (:hand (get-corp))))\n (let [ronin (get-conten",
"end": 32341,
"score": 0.985256016254425,
"start": 32336,
"tag": "NAME",
"value": "Ronin"
},
{
"context": " (is (not (get-in (refresh ronin) [:rezzed])) \"Ronin did not rez\")\n (take-credits state :corp)\n ",
"end": 32599,
"score": 0.5595751404762268,
"start": 32597,
"tag": "NAME",
"value": "in"
},
{
"context": "n now rezzed\")\n (play-from-hand state :corp \"Mushin No Shin\")\n (prompt-select :corp (find-card \"Profitee",
"end": 32841,
"score": 0.9953770637512207,
"start": 32827,
"tag": "NAME",
"value": "Mushin No Shin"
},
{
"context": "-game (default-corp [(qty \"Precognition\" 1) (qty \"Caprice Nisei\" 1) (qty \"Adonis Campaign\" 1)\n ",
"end": 37884,
"score": 0.7590992450714111,
"start": 37881,
"tag": "NAME",
"value": "Cap"
},
{
"context": "fault-corp [(qty \"Precognition\" 1) (qty \"Caprice Nisei\" 1) (qty \"Adonis Campaign\" 1)\n ",
"end": 37893,
"score": 0.691714882850647,
"start": 37890,
"tag": "NAME",
"value": "ise"
},
{
"context": " (qty \"Quandary\" 1) (qty \"Jackson Howard\" 1) (qty \"Global Food Initiative\" 1)])\n ",
"end": 37993,
"score": 0.995486855506897,
"start": 37979,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "ecognition\")\n (prompt-choice :corp (find-card \"Caprice Nisei\" (:deck (get-corp))))\n (prompt-choice :corp (f",
"end": 38212,
"score": 0.9981623888015747,
"start": 38199,
"tag": "NAME",
"value": "Caprice Nisei"
},
{
"context": "get-corp))))\n (prompt-choice :corp (find-card \"Jackson Howard\" (:deck (get-corp))))\n (prompt-choice :corp (f",
"end": 38429,
"score": 0.999730110168457,
"start": 38415,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "get-corp))))\n (prompt-choice :corp (find-card \"Jackson Howard\" (:deck (get-corp))))\n (prompt-choice :corp (f",
"end": 38731,
"score": 0.9996902942657471,
"start": 38717,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "get-corp))))\n (prompt-choice :corp (find-card \"Quandary\" (:deck (get-corp))))\n (prompt-choice :corp (f",
"end": 38799,
"score": 0.9996760487556458,
"start": 38791,
"tag": "NAME",
"value": "Quandary"
},
{
"context": "get-corp))))\n (prompt-choice :corp (find-card \"Caprice Nisei\" (:deck (get-corp)))) ;this is the top card of R&",
"end": 38947,
"score": 0.9997803568840027,
"start": 38934,
"tag": "NAME",
"value": "Caprice Nisei"
},
{
"context": " R&D\n (prompt-choice :corp \"Done\")\n (is (= \"Caprice Nisei\" (:title (first (:deck (get-corp))))))\n (is (=",
"end": 39057,
"score": 0.9997843503952026,
"start": 39044,
"tag": "NAME",
"value": "Caprice Nisei"
},
{
"context": ":title (second (:deck (get-corp))))))\n (is (= \"Quandary\" (:title (second (rest (:deck (get-corp)))))))\n ",
"end": 39185,
"score": 0.9992315173149109,
"start": 39177,
"tag": "NAME",
"value": "Quandary"
},
{
"context": "(second (rest (:deck (get-corp)))))))\n (is (= \"Jackson Howard\" (:title (second (rest (rest (:deck (get-corp))))",
"end": 39259,
"score": 0.9996909499168396,
"start": 39245,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "ner :credit 3)\n (play-from-hand state :runner \"Hades Shard\")\n (card-ability state :runner (get-in @state ",
"end": 50163,
"score": 0.8124083280563354,
"start": 50152,
"tag": "NAME",
"value": "Hades Shard"
},
{
"context": "ner :credit 3)\n (play-from-hand state :runner \"Hades Shard\")\n (card-ability state :runner (get-in @state ",
"end": 51281,
"score": 0.8777291178703308,
"start": 51270,
"tag": "NAME",
"value": "Hades Shard"
},
{
"context": "nvolving Subliminal being reshuffled into R&D with Jackson\n (do-game\n (new-game (default-corp [(qty \"",
"end": 56704,
"score": 0.9717380404472351,
"start": 56700,
"tag": "NAME",
"value": "Jack"
},
{
"context": "efault-corp [(qty \"Subliminal Messaging\" 1) (qty \"Jackson Howard\" 1)])\n (default-runner))\n (play-f",
"end": 56799,
"score": 0.9998210668563843,
"start": 56785,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "inal Messaging\")\n (play-from-hand state :corp \"Jackson Howard\" \"New remote\")\n (take-credits state :corp)\n ",
"end": 56941,
"score": 0.9998685717582703,
"start": 56927,
"tag": "NAME",
"value": "Jackson Howard"
}
] | src/clj/test/cards/operations.clj | erbridge/netrunner | 0 | (ns test.cards.operations
(:require [game.core :as core]
[test.core :refer :all]
[test.utils :refer :all]
[test.macros :refer :all]
[clojure.test :refer :all]))
(deftest twenty-four-seven-news-cycle-breaking-news
;; 24/7 News Cycle - Breaking News interaction
(do-game
(new-game (default-corp [(qty "Breaking News" 2) (qty "24/7 News Cycle" 3)])
(default-runner))
(play-from-hand state :corp "Breaking News" "New remote")
(play-from-hand state :corp "Breaking News" "New remote")
(let [ag1 (get-content state :remote1 0)
ag2 (get-content state :remote2 0)]
(score-agenda state :corp ag1)
(score-agenda state :corp ag2)
(take-credits state :corp)
(is (= 0 (:tag (get-runner)))) ; tags cleared
(take-credits state :runner)
(play-from-hand state :corp "24/7 News Cycle")
(prompt-card :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))) "Forfeited Breaking News")
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner given 2 tags")
(take-credits state :corp 2)
(is (= 2 (:tag (get-runner))) "Tags remained after Corp ended turn"))))
(deftest twenty-four-seven-news-cycle-posted-bounty
;; 24/7 News Cycle and Posted Bounty interaction -- Issue #1043
(do-game
(new-game (default-corp [(qty "Posted Bounty" 2) (qty "24/7 News Cycle" 3)])
(default-runner))
(play-from-hand state :corp "Posted Bounty" "New remote")
(play-from-hand state :corp "Posted Bounty" "New remote")
(let [ag1 (get-content state :remote1 0)
ag2 (get-content state :remote2 0)]
(score-agenda state :corp ag1)
(prompt-choice :corp "No")
(score-agenda state :corp ag2)
(prompt-choice :corp "No")
(play-from-hand state :corp "24/7 News Cycle")
(prompt-card :corp (find-card "Posted Bounty" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))) "Forfeited Posted Bounty")
(prompt-select :corp (find-card "Posted Bounty" (:scored (get-corp))))
(prompt-choice :corp "Yes") ; "Forfeit Posted Bounty to give 1 tag?"
(is (= 1 (:tag (get-runner))) "Runner given 1 tag")
(is (= 1 (:bad-publicity (get-corp))) "Corp has 1 bad publicity")
(is (= 0 (:agenda-point (get-corp))) "Forfeited Posted Bounty to 24/7 News Cycle"))))
(deftest twenty-four-seven-news-cycle-swaps
;; 24/7 News Cycle - Swapped agendas are able to be used. #1555
(do-game
(new-game (default-corp [(qty "24/7 News Cycle" 1) (qty "Chronos Project" 1)
(qty "Philotic Entanglement" 1) (qty "Profiteering" 1)])
(default-runner [(qty "Turntable" 3)]))
(score-agenda state :corp (find-card "Chronos Project" (:hand (get-corp))))
(score-agenda state :corp (find-card "Philotic Entanglement" (:hand (get-corp))))
(take-credits state :corp)
(play-from-hand state :runner "Turntable")
(core/steal state :runner (find-card "Profiteering" (:hand (get-corp))))
(prompt-choice :runner "Yes")
(prompt-select :runner (find-card "Philotic Entanglement" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(take-credits state :runner)
(play-from-hand state :corp "24/7 News Cycle")
(prompt-card :corp (find-card "Chronos Project" (:scored (get-corp))))
(is (= "Chronos Project" (:title (first (:rfg (get-corp))))))
;; shouldn't work on an agenda in the Runner's scored area
(is (= 2 (count (:hand (get-runner)))))
(prompt-select :corp (find-card "Philotic Entanglement" (:scored (get-runner))))
(is (= 2 (count (:hand (get-runner)))))
;; resolve 'when scored' ability on swapped Profiteering
(is (= 8 (:credit (get-corp))))
(prompt-select :corp (find-card "Profiteering" (:scored (get-corp))))
(prompt-choice :corp "3")
(is (= 1 (:agenda-point (get-corp))))
(is (= 3 (:bad-publicity (get-corp))))
(is (= 23 (:credit (get-corp))) "Gained 15 credits")))
(deftest accelerated-diagnostics
;; Accelerated Diagnostics - Interaction with prompt effects, like Shipment from SanSan
(do-game
(new-game (default-corp [(qty "Accelerated Diagnostics" 1) (qty "Cerebral Overwriter" 1) (qty "Shipment from SanSan" 1)
(qty "Hedge Fund" 1) (qty "Back Channels" 1)])
(default-runner))
(starting-hand state :corp ["Accelerated Diagnostics" "Cerebral Overwriter"])
(play-from-hand state :corp "Cerebral Overwriter" "New remote")
(core/gain state :corp :credit 1)
(play-from-hand state :corp "Accelerated Diagnostics")
(let [playarea (get-in @state [:corp :play-area])
hf (find-card "Hedge Fund" playarea)
ss (find-card "Shipment from SanSan" playarea)
bc (find-card "Back Channels" playarea)
co (get-content state :remote1 0)]
(is (= 3 (count playarea)) "3 cards in play area")
(prompt-select :corp ss)
(prompt-choice :corp "2")
(prompt-select :corp co)
(is (= 2 (:advance-counter (refresh co))) "Cerebral Overwriter gained 2 advancements")
(prompt-select :corp hf)
(is (= 9 (:credit (get-corp))) "Corp gained credits from Hedge Fund")
(prompt-select :corp bc)
(prompt-select :corp (refresh co))
(is (= 15 (:credit (get-corp))) "Corp gained 6 credits for Back Channels"))))
(deftest big-brother
;; Big Brother - Give the Runner 2 tags if already tagged
(do-game
(new-game (default-corp [(qty "Big Brother" 1)])
(default-runner))
(play-from-hand state :corp "Big Brother")
(is (= 1 (count (:hand (get-corp)))) "Card not played because Runner has no tags")
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Big Brother")
(is (= 3 (:tag (get-runner))) "Runner gained 2 tags")))
(deftest biotic-labor
;; Biotic Labor - Gain 2 clicks
(do-game
(new-game (default-corp [(qty "Biotic Labor" 1)])
(default-runner))
(play-from-hand state :corp "Biotic Labor")
(is (= 1 (:credit (get-corp))))
(is (= 4 (:click (get-corp))) "Spent 1 click to gain 2 additional clicks")))
(deftest blue-level-clearance
;; Blue Level Clearance - Gain 5 credits and draw 2 cards
(do-game
(new-game (default-corp [(qty "Blue Level Clearance" 3)
(qty "Hedge Fund" 3)
(qty "Sweeps Week" 2)])
(default-runner))
(play-from-hand state :corp "Blue Level Clearance")
(is (= 8 (:credit (get-corp))) "Gained 5 credits")
(is (= 1 (:click (get-corp))))
(is (= 7 (count (:hand (get-corp)))) "Drew 2 cards")))
(deftest casting-call
;; Casting Call - Only do card-init on the Public agendas. Issue #1128
(do-game
(new-game (default-corp [(qty "Casting Call" 2) (qty "Oaktown Renovation" 1)
(qty "Improved Tracers" 1) (qty "Hunter" 1)])
(default-runner))
(core/gain state :corp :click 1)
(play-from-hand state :corp "Hunter" "HQ")
(let [hunter (get-ice state :hq 0)]
(core/rez state :corp hunter)
(is (= 4 (:current-strength (refresh hunter))))
(play-from-hand state :corp "Casting Call")
(prompt-select :corp (find-card "Improved Tracers" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(let [imptrac (get-content state :remote1 0)]
(is (get-in (refresh imptrac) [:rezzed]) "Improved Tracers is faceup")
(is (= 4 (:current-strength (refresh hunter))) "Hunter hasn't gained strength")
(play-from-hand state :corp "Casting Call")
(prompt-select :corp (find-card "Oaktown Renovation" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(let [oak (get-content state :remote2 0)]
(core/advance state :corp {:card (refresh oak)})
(is (= 5 (:credit (get-corp))) "Events on Public agenda work; gained 2 credits from advancing")
(take-credits state :corp)
(run-empty-server state "Server 2")
(prompt-select :runner oak)
(prompt-choice :runner "Steal")
(is (= 2 (:tag (get-runner))) "Runner took 2 tags from accessing agenda with Casting Call hosted on it"))))))
(deftest cerebral-static-chaos-theory
;; Cerebral Static - vs Chaos Theory
(do-game
(new-game (default-corp [(qty "Cerebral Static" 1) (qty "Lag Time" 1)])
(make-deck "Chaos Theory: Wünderkind" [(qty "Sure Gamble" 3)]))
(is (= 5 (:memory (get-runner))) "CT starts with 5 memory")
(play-from-hand state :corp "Cerebral Static")
(is (= 4 (:memory (get-runner))) "Cerebral Static causes CT to have 4 memory")
(play-from-hand state :corp "Lag Time")
(is (= 5 (:memory (get-runner))) "CT 5 memory restored")))
(deftest closed-accounts
;; Closed Accounts - Play if Runner is tagged to make Runner lose all credits
(do-game
(new-game (default-corp [(qty "Closed Accounts" 1)])
(default-runner))
(play-from-hand state :corp "Closed Accounts")
(is (and (= 3 (:click (get-corp)))
(= 5 (:credit (get-runner))))
"Closed Accounts precondition not met; card not played")
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Closed Accounts")
(is (= 0 (:credit (get-runner))) "Runner lost all credits")))
(deftest consulting-visit
;; Consulting Visit - Only show single copies of operations corp can afford as choices. Play chosen operation
(do-game
(new-game (default-corp [(qty "Consulting Visit" 1)
(qty "Beanstalk Royalties" 2)
(qty "Green Level Clearance" 1)
(qty "Breaking News" 1)
(qty "Hedge Fund" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(starting-hand state :corp ["Consulting Visit"])
(play-from-hand state :corp "Consulting Visit")
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-choice :corp (find-card "Beanstalk Royalties" (:deck (get-corp))))
(is (= 6 (:credit (get-corp)))))))
(deftest consulting-visit-mumbad
;; Consulting Visit - Works properly when played with Mumbad City Hall
(do-game
(new-game (default-corp [(qty "Mumbad City Hall" 1)
(qty "Beanstalk Royalties" 1)
(qty "Green Level Clearance" 1)
(qty "Breaking News" 1)
(qty "Hedge Fund" 1)
(qty "Consulting Visit" 1)
(qty "Mumba Temple" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(starting-hand state :corp ["Mumbad City Hall"])
(play-from-hand state :corp "Mumbad City Hall" "New remote")
(let [hall (get-content state :remote1 0)
get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(card-ability state :corp hall 0)
(is (= (list "Consulting Visit" "Mumba Temple" nil) (prompt-names)))
(prompt-choice :corp (find-card "Consulting Visit" (:deck (get-corp))))
(is (= 3 (:credit (get-corp))))
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-choice :corp (find-card "Green Level Clearance" (:deck (get-corp))))
(is (= 5 (:credit (get-corp)))))))
(deftest defective-brainchips
;; Defective Brainchips - Do 1 add'l brain damage the first time Runner takes some each turn
(do-game
(new-game (default-corp [(qty "Defective Brainchips" 1) (qty "Viktor 1.0" 1)])
(default-runner [(qty "Sure Gamble" 2) (qty "Shiv" 2)]))
(play-from-hand state :corp "Defective Brainchips")
(play-from-hand state :corp "Viktor 1.0" "HQ")
(take-credits state :corp)
(run-on state :hq)
(let [vik (get-ice state :hq 0)]
(core/rez state :corp vik)
(card-subroutine state :corp vik 0)
(is (= 2 (count (:discard (get-runner)))) "2 cards lost to brain damage")
(is (= 2 (:brain-damage (get-runner))) "Brainchips dealt 1 additional brain dmg")
(card-subroutine state :corp vik 0)
(is (= 3 (count (:discard (get-runner)))) "2 cards lost to brain damage")
(is (= 3 (:brain-damage (get-runner))) "Brainchips didn't do additional brain dmg"))))
(deftest diversified-portfolio
(do-game
(new-game (default-corp [(qty "Diversified Portfolio" 1)
(qty "Paper Wall" 1)
(qty "PAD Campaign" 3)])
(default-runner))
(core/gain state :corp :click 2)
(play-from-hand state :corp "Paper Wall" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "Diversified Portfolio")
(is (= 7 (:credit (get-corp))) "Ignored remote with ICE but no server contents")))
(deftest enhanced-login-protocol
;; Enhanced Login Protocol - First click run each turn costs an additional click
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Employee Strike" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make the second run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(take-credits state :runner 3)
(is (= 1 (:click (get-runner))) "Runner has 1 click")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 1 (:click (get-runner))) "Runner has 1 click")
(take-credits state :runner)
(take-credits state :corp)
(play-from-hand state :runner "Employee Strike")
(is (= 3 (:click (get-runner))) "Runner has 3 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make a run")))
(deftest enhanced-login-protocol-card-ability
;; Enhanced Login Protocol - Card ability runs don't cost additional clicks
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(take-credits state :runner)
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 2 clicks")
(let [sneakdoor (get-in @state [:runner :rig :program 0])]
(card-ability state :runner sneakdoor 0)
(is (= 3 (:click (get-runner)))
"Runner doesn't spend 1 additional click to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make a run"))))
(deftest enhanced-login-protocol-run-events
;; Enhanced Login Protocol - Run event don't cost additional clicks
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Out of the Ashes" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(play-from-hand state :runner "Out of the Ashes")
(prompt-choice :runner "Archives")
(is (= 3 (:click (get-runner)))
"Runner doesn't spend 1 additional click to run with a run event")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(prompt-choice :runner "No") ; Out of the Ashes prompt
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make a run")))
(deftest enhanced-login-protocol-runner-turn-first-run
;; Enhanced Login Protocol - Works when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
[(qty "Enhanced Login Protocol" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(core/gain state :runner :credit 2)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Enhanced Login Protocol"
(:hand (get-corp))))
(is (find-card "Enhanced Login Protocol" (:current (get-corp)))
"Enhanced Login Protocol is in play")
(is (= 3 (:click (get-runner))) "Runner has 3 clicks")
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")))
(deftest enhanced-login-protocol-runner-turn-second-run
;; Enhanced Login Protocol - Doesn't fire if already run when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
[(qty "Enhanced Login Protocol" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(run-on state :hq)
(run-successful state)
(prompt-choice :runner "OK")
(core/gain state :runner :credit 2)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Enhanced Login Protocol"
(:hand (get-corp))))
(is (find-card "Enhanced Login Protocol" (:current (get-corp)))
"Enhanced Login Protocol is in play")
(is (= 2 (:click (get-runner))) "Runner has 2 clicks")
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make a run")))
(deftest exchange-of-information
;; Exchange of Information - Swapping agendas works correctly
(do-game
(new-game (default-corp [(qty "Exchange of Information" 1)
(qty "Market Research" 1)
(qty "Breaking News" 1)
(qty "Project Beale" 1)
(qty "Explode-a-palooza" 1)])
(default-runner))
(score-agenda state :corp (find-card "Market Research" (:hand (get-corp))))
(score-agenda state :corp (find-card "Breaking News" (:hand (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner gained 2 tags")
(take-credits state :corp)
(is (= 0 (:tag (get-runner))) "Runner lost 2 tags")
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(core/steal state :runner (find-card "Explode-a-palooza" (:hand (get-corp))))
(take-credits state :runner)
(is (= 4 (:agenda-point (get-runner))))
(is (= 3 (:agenda-point (get-corp))))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 3 (:agenda-point (get-runner))))
(is (= 4 (:agenda-point (get-corp))))))
(deftest exchange-of-information-breaking-news
;; Exchange of Information - Swapping a just scored Breaking News keeps the tags
(do-game
(new-game (default-corp [(qty "Exchange of Information" 1)
(qty "Market Research" 1)
(qty "Breaking News" 1)
(qty "Project Beale" 1)
(qty "Explode-a-palooza" 1)])
(default-runner))
(take-credits state :corp)
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(core/steal state :runner (find-card "Explode-a-palooza" (:hand (get-corp))))
(take-credits state :runner)
(score-agenda state :corp (find-card "Breaking News" (:hand (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner gained 2 tags")
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 2 (:tag (get-runner))) "Still has tags after swap and before end of turn")
(take-credits state :corp)
(is (= 3 (:agenda-point (get-runner))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner does not lose tags at end of turn")))
(deftest exchange-of-information-fifteen-minutes
;; Exchange of Information - Swapping a 15 Minutes still keeps the ability. #1783
(do-game
(new-game (default-corp [(qty "Exchange of Information" 2) (qty "15 Minutes" 1)
(qty "Project Beale" 1)])
(default-runner))
(score-agenda state :corp (find-card "15 Minutes" (:hand (get-corp))))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(take-credits state :runner)
(is (= 1 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "15 Minutes" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 1 (:agenda-point (get-runner))))
(is (= 0 (count (:deck (get-corp)))))
;; shuffle back into R&D from runner's scored area
(let [fifm (get-in @state [:runner :scored 0])]
(card-ability state :corp fifm 0))
(is (= 2 (:agenda-point (get-corp))))
(is (= 0 (:agenda-point (get-runner))))
(is (= "15 Minutes" (:title (first (:deck (get-corp))))))
(take-credits state :corp)
(core/steal state :runner (find-card "15 Minutes" (:deck (get-corp))))
(take-credits state :runner)
(is (= 2 (:agenda-point (get-corp))))
(is (= 1 (:agenda-point (get-runner))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "15 Minutes" (:scored (get-runner))))
(prompt-select :corp (find-card "Project Beale" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
;; shuffle back into R&D from corp's scored area
(let [fifm (get-in @state [:corp :scored 0])]
(card-ability state :corp fifm 0))
(is (= "15 Minutes" (:title (first (:deck (get-corp))))))))
(deftest exchange-of-information-mandatory-upgrades
;; Exchange of Information - Swapping a Mandatory Upgrades gives the Corp an additional click per turn. #1687
(do-game
(new-game (default-corp [(qty "Exchange of Information" 2) (qty "Mandatory Upgrades" 1)
(qty "Global Food Initiative" 1)])
(default-runner))
(score-agenda state :corp (find-card "Global Food Initiative" (:hand (get-corp))))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(core/steal state :runner (find-card "Mandatory Upgrades" (:hand (get-corp))))
(take-credits state :runner)
(is (= 3 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 3 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Mandatory Upgrades" (:scored (get-runner))))
(prompt-select :corp (find-card "Global Food Initiative" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 3 (:click (get-corp))))
(is (= 4 (:click-per-turn (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(is (= 4 (:click (get-corp))))
(is (= 4 (:click-per-turn (get-corp))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Global Food Initiative" (:scored (get-runner))))
(prompt-select :corp (find-card "Mandatory Upgrades" (:scored (get-corp))))
(is (= 3 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 2 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(is (= 3 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))))
(deftest election-day
(do-game
(new-game (default-corp [(qty "Election Day" 7)])
(default-runner))
(is (= 6 (count (:hand (get-corp)))) "Corp starts with 5 + 1 cards")
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(play-from-hand state :corp "Election Day")
(is (= 1 (count (:hand (get-corp)))) "Could not play Election Day")
(take-credits state :corp)
(take-credits state :runner)
(is (= 2 (count (:hand (get-corp)))) "Corp has now 1 + 1 cards before Election Day")
(play-from-hand state :corp "Election Day")
(is (= 5 (count (:hand (get-corp)))) "Corp has now 5 cards due to Election Day")))
(deftest hedge-fund
(do-game
(new-game (default-corp) (default-runner))
(is (= 5 (:credit (get-corp))))
(play-from-hand state :corp "Hedge Fund")
(is (= 9 (:credit (get-corp))))))
(deftest housekeeping
;; Housekeeping - Runner must trash a card from Grip on first install of a turn
(do-game
(new-game (default-corp [(qty "Housekeeping" 1)])
(default-runner [(qty "Cache" 2) (qty "Fall Guy" 1) (qty "Mr. Li" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Fall Guy")
(take-credits state :runner)
(play-from-hand state :corp "Housekeeping")
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(prompt-select :runner (find-card "Mr. Li" (:hand (get-runner))))
(is (empty? (:prompt (get-runner))) "Fall Guy prevention didn't trigger")
(is (= 1 (count (:discard (get-runner)))) "Card trashed")
(play-from-hand state :runner "Cache")
(is (empty? (:prompt (get-runner))) "Housekeeping didn't trigger on 2nd install")))
(deftest invasion-of-privacy
;; Invasion of Privacy - Full test
(do-game
(new-game (default-corp [(qty "Invasion of Privacy" 3)])
(default-runner [(qty "Sure Gamble" 2) (qty "Fall Guy" 1) (qty "Cache" 2)]))
(core/gain state :corp :click 3 :credit 6)
;; trash 2 cards
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 5 (count (:hand (get-runner)))))
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" "Sure Gamble" nil) (prompt-names)))
(prompt-choice :corp (find-card "Sure Gamble" (:hand (get-runner))))
(prompt-choice :corp (find-card "Sure Gamble" (:hand (get-runner)))))
(is (= 3 (count (:hand (get-runner)))))
;; able to trash 2 cards but only 1 available target in Runner's hand
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 3 (count (:hand (get-runner)))))
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" nil) (prompt-names)))
(prompt-choice :corp (find-card "Fall Guy" (:hand (get-runner))))
(is (empty? (get-in @state [:corp :prompt])) "No prompt for second card"))
(is (= 2 (count (:hand (get-runner)))))
;; failed trace - take the bad publicity
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 2) ; Runner matches
(is (= 1 (:bad-publicity (get-corp))))))
(deftest lateral-growth
(do-game
(new-game (default-corp [(qty "Lateral Growth" 1) (qty "Breaking News" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(play-from-hand state :corp "Lateral Growth")
(prompt-select :corp (find-card "Breaking News" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(is (= "Breaking News" (:title (get-content state :remote1 0)))
"Breaking News installed by Lateral Growth")
(is (= 7 (:credit (get-corp))))))
(deftest manhunt-every-run
;; Manhunt - only fires once per turn. Unreported issue.
(do-game
(new-game (default-corp [(qty "Manhunt" 1) (qty "Hedge Fund" 3)])
(default-runner))
(play-from-hand state :corp "Manhunt")
(take-credits state :corp)
(run-empty-server state "HQ")
(is (:prompt (get-corp)) "Manhunt trace initiated")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag")
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")
(run-empty-server state "HQ")
(is (empty? (:prompt (get-corp))) "No Manhunt trace on second run")
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")))
(deftest midseason-replacements
;; Midseason Replacements - Trace to give Runner tags after they steal an agenda
(do-game
(new-game (default-corp [(qty "Midseason Replacements" 1) (qty "Breaking News" 1)])
(default-runner))
(play-from-hand state :corp "Midseason Replacements")
(is (= 3 (:click (get-corp))) "Midseason precondition not met; Corp not charged a click")
(play-from-hand state :corp "Breaking News" "New remote")
(take-credits state :corp)
(is (= 7 (:credit (get-corp))))
(let [bn (get-content state :remote1 0)]
(run-empty-server state "Server 1")
(prompt-choice :runner "Steal")
(is (= 1 (:agenda-point (get-runner))) "Stole Breaking News")
(take-credits state :runner)
(play-from-hand state :corp "Midseason Replacements")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 6 (:tag (get-runner))) "Runner took 6 tags"))))
(deftest mushin-no-shin
;; Mushin No Shin - Add 3 advancements to a card; prevent rez/score of that card the rest of the turn
(do-game
(new-game (default-corp [(qty "Mushin No Shin" 2) (qty "Ronin" 1) (qty "Profiteering" 1)])
(default-runner))
(play-from-hand state :corp "Mushin No Shin")
(prompt-select :corp (find-card "Ronin" (:hand (get-corp))))
(let [ronin (get-content state :remote1 0)]
(is (= 3 (:advance-counter (refresh ronin))) "3 advancements placed on Ronin")
(core/rez state :corp (refresh ronin))
(is (not (get-in (refresh ronin) [:rezzed])) "Ronin did not rez")
(take-credits state :corp)
(take-credits state :runner)
(core/rez state :corp (refresh ronin))
(is (get-in (refresh ronin) [:rezzed]) "Ronin now rezzed")
(play-from-hand state :corp "Mushin No Shin")
(prompt-select :corp (find-card "Profiteering" (:hand (get-corp))))
(let [prof (get-content state :remote2 0)]
(core/score state :corp (refresh prof))
(is (empty? (:scored (get-corp))) "Profiteering not scored")
(is (= 0 (:agenda-point (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(core/score state :corp (refresh prof))
(prompt-choice :corp "0")
(is (= 1 (:agenda-point (get-corp))) "Profiteering was able to be scored")))))
(deftest neural-emp
;; Neural EMP - Play if Runner made a run the previous turn to do 1 net damage
(do-game
(new-game (default-corp [(qty "Neural EMP" 1)])
(default-runner))
(play-from-hand state :corp "Neural EMP")
(is (= 3 (:click (get-corp))) "Neural precondition not met; card not played")
(take-credits state :corp)
(run-empty-server state "Archives")
(take-credits state :runner)
(play-from-hand state :corp "Neural EMP")
(is (= 1 (count (:discard (get-runner)))) "Runner took 1 net damage")))
(deftest oversight-ai
;; Oversight AI - Rez a piece of ICE ignoring all costs
(do-game
(new-game (default-corp [(qty "Oversight AI" 1) (qty "Archer" 1)])
(default-runner))
(play-from-hand state :corp "Archer" "R&D")
(let [archer (get-ice state :rd 0)]
(play-from-hand state :corp "Oversight AI")
(prompt-select :corp archer)
(is (get-in (refresh archer) [:rezzed]))
(is (= 4 (:credit (get-corp))) "Archer rezzed at no credit cost")
(is (= "Oversight AI" (:title (first (:hosted (refresh archer)))))
"Archer hosting OAI as a condition"))))
(deftest patch
;; Patch - +2 current strength
(do-game
(new-game (default-corp [(qty "Patch" 1) (qty "Vanilla" 1)])
(default-runner))
(play-from-hand state :corp "Vanilla" "HQ")
(core/rez state :corp (get-ice state :hq 0))
(play-from-hand state :corp "Patch")
(prompt-select :corp (get-ice state :hq 0))
(is (= 2 (:current-strength (get-ice state :hq 0))) "Vanilla at 2 strength")))
(deftest paywall-implementation
;; Paywall Implementation - Gain 1 credit for every successful run
(do-game
(new-game (default-corp [(qty "Paywall Implementation" 1)])
(default-runner))
(play-from-hand state :corp "Paywall Implementation")
(is (= "Paywall Implementation" (:title (first (get-in @state [:corp :current]))))
"Paywall active in Current area")
(take-credits state :corp)
(is (= 7 (:credit (get-corp))))
(run-empty-server state "Archives")
(is (= 8 (:credit (get-corp))) "Gained 1 credit from successful run")
(run-empty-server state "Archives")
(is (= 9 (:credit (get-corp))) "Gained 1 credit from successful run")))
(deftest peak-efficiency
;; Peak Efficiency - Gain 1 credit for each rezzed ICE
(do-game
(new-game (default-corp [(qty "Peak Efficiency" 1) (qty "Paper Wall" 3) (qty "Wraparound" 1)])
(default-runner))
(core/gain state :corp :click 3)
(play-from-hand state :corp "Paper Wall" "HQ")
(play-from-hand state :corp "Paper Wall" "R&D")
(play-from-hand state :corp "Paper Wall" "New remote")
(play-from-hand state :corp "Wraparound" "New remote")
(core/rez state :corp (get-ice state :hq 0))
(core/rez state :corp (get-ice state :rd 0))
(core/rez state :corp (get-ice state :remote1 0))
(play-from-hand state :corp "Peak Efficiency")
(is (= 7 (:credit (get-corp))) "Gained 3 credits for 3 rezzed ICE; unrezzed ICE ignored")))
(deftest power-shutdown
;; Power Shutdown - Trash cards from R&D to force Runner to trash a program or hardware
(do-game
(new-game (default-corp [(qty "Power Shutdown" 3) (qty "Hive" 3)])
(default-runner [(qty "Grimoire" 1) (qty "Cache" 1)]))
(play-from-hand state :corp "Power Shutdown")
(is (empty? (:discard (get-corp))) "Not played, no run last turn")
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(play-from-hand state :runner "Grimoire")
(run-empty-server state :archives)
(take-credits state :runner)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(play-from-hand state :corp "Power Shutdown")
(prompt-choice :corp 2)
(is (= 3 (count (:discard (get-corp)))) "2 cards trashed from R&D")
(is (= 1 (count (:deck (get-corp)))) "1 card remaining in R&D")
(prompt-select :runner (get-in @state [:runner :rig :hardware 0])) ; try targeting Grimoire
(is (empty? (:discard (get-runner))) "Grimoire too expensive to be targeted")
(prompt-select :runner (get-in @state [:runner :rig :program 0]))
(is (= 1 (count (:discard (get-runner)))) "Cache trashed")))
(deftest precognition
;; Precognition - Full test
(do-game
(new-game (default-corp [(qty "Precognition" 1) (qty "Caprice Nisei" 1) (qty "Adonis Campaign" 1)
(qty "Quandary" 1) (qty "Jackson Howard" 1) (qty "Global Food Initiative" 1)])
(default-runner))
(starting-hand state :corp ["Precognition"])
(play-from-hand state :corp "Precognition")
(prompt-choice :corp (find-card "Caprice Nisei" (:deck (get-corp))))
(prompt-choice :corp (find-card "Adonis Campaign" (:deck (get-corp))))
(prompt-choice :corp (find-card "Quandary" (:deck (get-corp))))
(prompt-choice :corp (find-card "Jackson Howard" (:deck (get-corp))))
(prompt-choice :corp (find-card "Global Food Initiative" (:deck (get-corp))))
;; try starting over
(prompt-choice :corp "Start over")
(prompt-choice :corp (find-card "Global Food Initiative" (:deck (get-corp))))
(prompt-choice :corp (find-card "Jackson Howard" (:deck (get-corp))))
(prompt-choice :corp (find-card "Quandary" (:deck (get-corp))))
(prompt-choice :corp (find-card "Adonis Campaign" (:deck (get-corp))))
(prompt-choice :corp (find-card "Caprice Nisei" (:deck (get-corp)))) ;this is the top card of R&D
(prompt-choice :corp "Done")
(is (= "Caprice Nisei" (:title (first (:deck (get-corp))))))
(is (= "Adonis Campaign" (:title (second (:deck (get-corp))))))
(is (= "Quandary" (:title (second (rest (:deck (get-corp)))))))
(is (= "Jackson Howard" (:title (second (rest (rest (:deck (get-corp))))))))
(is (= "Global Food Initiative" (:title (second (rest (rest (rest (:deck (get-corp)))))))))))
(deftest preemptive-action
;; Preemptive Action - Shuffles cards into R&D and removes itself from game
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 3)
(qty "Preemptive Action" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Preemptive Action")
(prompt-select :corp (first (:discard (get-corp))))
(prompt-select :corp (second (:discard (get-corp))))
(prompt-select :corp (last (:discard (get-corp))))
(is (= 0 (count (:discard (get-corp)))))
(is (= 1 (count (:rfg (get-corp)))))))
(deftest psychographics
;; Psychographics - Place advancements up to the number of Runner tags on a card
(do-game
(new-game (default-corp [(qty "Psychographics" 1) (qty "Project Junebug" 1)])
(default-runner))
(core/gain state :runner :tag 4)
(play-from-hand state :corp "Project Junebug" "New remote")
(let [pj (get-content state :remote1 0)]
(play-from-hand state :corp "Psychographics")
(prompt-choice :corp 4)
(prompt-select :corp pj)
(is (= 1 (:credit (get-corp))) "Spent 4 credits")
(is (= 4 (:advance-counter (refresh pj))) "Junebug has 4 advancements"))))
(deftest punitive-counterstrike
;; Punitive Counterstrike - deal meat damage equal to printed agenda points
(do-game
(new-game (default-corp [(qty "Global Food Initiative" 1) (qty "Punitive Counterstrike" 1)])
(default-runner))
(play-from-hand state :corp "Global Food Initiative" "New remote")
(take-credits state :corp)
(run-empty-server state :remote1)
(prompt-choice :runner "Steal")
(is (= 2 (:agenda-point (get-runner))) "Runner scored 2 points")
(take-credits state :runner)
(play-from-hand state :corp "Punitive Counterstrike")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (empty? (:hand (get-runner))) "Runner took 3 meat damage")))
(deftest reuse
;; Reuse - Gain 2 credits for each card trashed from HQ
(do-game
(new-game (default-corp [(qty "Reuse" 2) (qty "Hive" 1) (qty "IQ" 1)
(qty "Ice Wall" 1)])
(default-runner))
(play-from-hand state :corp "Reuse")
(prompt-select :corp (find-card "Ice Wall" (:hand (get-corp))))
(prompt-select :corp (find-card "Hive" (:hand (get-corp))))
(prompt-select :corp (find-card "IQ" (:hand (get-corp))))
(prompt-choice :corp "Done")
(is (= 4 (count (:discard (get-corp)))) "3 cards trashed plus operation played")
(is (= 11 (:credit (get-corp))) "Gained 6 credits")
(is (= 1 (:click (get-corp))) "Spent 2 clicks")))
(deftest salems-hospitality
;; Salem's Hospitality - Full test
(do-game
(new-game (default-corp [(qty "Salem's Hospitality" 3)])
(default-runner [(qty "I've Had Worse" 3) (qty "Faust" 1)
(qty "Levy AR Lab Access" 1)]))
(play-from-hand state :corp "Salem's Hospitality")
(is (= 5 (count (:hand (get-runner)))))
(prompt-choice :corp "I've Had Worse")
(is (= 2 (count (:hand (get-runner)))))
(play-from-hand state :corp "Salem's Hospitality")
(prompt-choice :corp "Plascrete Carapace")
(is (= 2 (count (:hand (get-runner)))))))
(deftest scorched-earth
;; Scorched Earth - burn 'em
(do-game
(new-game (default-corp [(qty "Scorched Earth" 1)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Scorched Earth")
(is (= 1 (count (:hand (get-runner)))) "Runner has 1 card in hand")))
(deftest scorched-earth-no-tag
;; Scorched Earth - not tagged
(do-game
(new-game (default-corp [(qty "Scorched Earth" 1)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(play-from-hand state :corp "Scorched Earth")
(is (= 3 (:click (get-corp))) "Corp not charged a click")
(is (= 5 (count (:hand (get-runner)))) "Runner did not take damage")))
(deftest scorched-earth-flatline
;; Scorched Earth - murderize 'em
(do-game
(new-game (default-corp [(qty "Scorched Earth" 1)])
(default-runner))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Scorched Earth")
(is (= 0 (count (:hand (get-runner)))) "Runner has 0 cards in hand")
(is (= :corp (:winner @state)) "Corp wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline")))
(deftest subcontract-scorched
;; Subcontract - Don't allow second operation until damage prevention completes
(do-game
(new-game (default-corp [(qty "Scorched Earth" 2) (qty "Subcontract" 1)])
(default-runner [(qty "Plascrete Carapace" 1)]))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(play-from-hand state :runner "Plascrete Carapace")
(take-credits state :runner)
(play-from-hand state :corp "Subcontract")
(prompt-select :corp (find-card "Scorched Earth" (:hand (get-corp))))
(is (and (= 1 (count (:prompt (get-corp)))) (= :waiting (-> (get-corp) :prompt first :prompt-type)))
"Corp does not have Subcontract prompt until damage prevention completes")
(prompt-choice :runner "Done")
(is (not-empty (:prompt (get-corp))) "Corp can now play second Subcontract operation")))
(deftest subcontract-terminal
;; Subcontract - interaction with Terminal operations
(do-game
(new-game
(default-corp [(qty "Hard-Hitting News" 2) (qty "Subcontract" 1)])
(default-runner))
(core/gain state :runner :tag 1)
(take-credits state :corp)
(run-empty-server state :archives)
(take-credits state :runner)
(play-from-hand state :corp "Subcontract")
(prompt-select :corp (find-card "Hard-Hitting News" (:hand (get-corp))))
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 5 (:tag (get-runner))) "Runner has 5 tags")
(is (empty? (:prompt (get-corp))) "Corp does not have a second Subcontract selection prompt")))
(deftest service-outage
;; Service Outage - First click run each turn costs a credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Employee Strike" 1)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(is (= 5 (:credit (get-runner))) "Runner has 5 credits")
(run-on state :archives)
(is (= 4 (:credit (get-runner)))
"Runner spends 1 credit to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 4 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make the second run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 6)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 2)
(play-from-hand state :runner "Employee Strike")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")))
(deftest service-outage-card-ability
;; Service Outage - First card ability run each turn costs an additional credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(take-credits state :runner 1)
(is (= 2 (:credit (get-runner))) "Runner has 2 credits")
(let [sneakdoor (get-in @state [:runner :rig :program 0])]
(card-ability state :runner sneakdoor 0)
(is (= 1 (:credit (get-runner)))
"Runner spends 1 additional credit to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 1)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(card-ability state :runner sneakdoor 0)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits"))))
(deftest service-outage-run-events
;; Service Outage - First run event each turn costs an additional credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Out of the Ashes" 2)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(is (= 5 (:credit (get-runner))) "Runner has 5 credits")
(play-from-hand state :runner "Out of the Ashes")
(is (= 3 (:credit (get-runner)))
"Runner spends 1 additional credit to run with a run event")
(prompt-choice :runner "Archives")
(run-successful state)
(run-on state :archives)
(is (= 3 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(prompt-choice :runner "No") ; Out of the Ashes prompt
(core/lose state :runner :credit 4)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(play-from-hand state :runner "Out of the Ashes")
(is (empty? (get-in @state [:runner :prompt]))
"Out of the Ashes was not played")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")))
(deftest service-outage-runner-turn-first-run
;; Service Outage - Works when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News" [(qty "Service Outage" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(core/gain state :runner :credit 3)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Service Outage" (:hand (get-corp))))
(is (find-card "Service Outage" (:current (get-corp)))
"Service Outage is in play")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 0 (:credit (get-runner)))
"Runner spends 1 additional credit to make a run")))
(deftest service-outage-runner-turn-second-run
;; Service Outage - Doesn't fire if already run when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News" [(qty "Service Outage" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(run-on state :hq)
(run-successful state)
(prompt-choice :runner "OK")
(core/gain state :runner :credit 3)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Service Outage" (:hand (get-corp))))
(is (find-card "Service Outage" (:current (get-corp)))
"Service Outage is in play")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 additional credit to make a run")))
(deftest shipment-from-sansan
;; Shipment from SanSan - placing advancements
(do-game
(new-game (default-corp [(qty "Shipment from SanSan" 3) (qty "Ice Wall" 3)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(let [iwall (get-ice state :hq 0)]
(play-from-hand state :corp "Shipment from SanSan")
(prompt-choice :corp "2")
(prompt-select :corp iwall)
(is (= 5 (:credit (get-corp))))
(is (= 2 (:advance-counter (refresh iwall)))))))
(deftest stock-buy-back
;; Stock Buy-Back - Gain 3c for every agenda in Runner's area
(do-game
(new-game (default-corp [(qty "Hostile Takeover" 2) (qty "Stock Buy-Back" 3)])
(default-runner))
(play-from-hand state :corp "Hostile Takeover" "New remote")
(play-from-hand state :corp "Hostile Takeover" "New remote")
(take-credits state :corp)
(run-empty-server state "Server 1")
(prompt-choice :runner "Steal")
(run-empty-server state "Server 2")
(prompt-choice :runner "Steal")
(take-credits state :runner)
(is (= 2 (count (:scored (get-runner)))))
(play-from-hand state :corp "Stock Buy-Back")
(is (= 11 (:credit (get-corp))))))
(deftest sub-boost
;; Sub Boost - Give ice barrier
(do-game
(new-game (default-corp [(qty "Sub Boost" 1) (qty "Quandary" 1)])
(default-runner))
(play-from-hand state :corp "Quandary" "HQ")
(play-from-hand state :corp "Sub Boost")
(let [qu (get-ice state :hq 0)]
(core/rez state :corp qu)
(prompt-select :corp qu)
(is (core/has-subtype? (refresh qu) "Code Gate") "Quandary has code gate")
(is (core/has-subtype? (refresh qu) "Barrier") "Quandary has barrier"))))
(deftest subliminal-messaging
;; Subliminal Messaging - Playing/trashing/milling will all prompt returning to hand
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 3)])
(make-deck "Noise: Hacker Extraordinaire" [(qty "Cache" 3) (qty "Utopia Shard" 1)]))
(play-from-hand state :corp "Subliminal Messaging")
(is (= 6 (:credit (get-corp))))
(is (= 3 (:click (get-corp))) "First Subliminal Messaging gains 1 click")
(play-from-hand state :corp "Subliminal Messaging")
(is (= 7 (:credit (get-corp))))
(is (= 2 (:click (get-corp))) "Second Subliminal Messaging does not gain 1 click")
(trash-from-hand state :corp "Subliminal Messaging")
(is (= 0 (count (:hand (get-corp)))))
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 3 (count (:hand (get-corp)))) "All 3 Subliminals returned to HQ")
(core/move state :corp (find-card "Subliminal Messaging" (:hand (get-corp))) :deck)
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(play-from-hand state :runner "Utopia Shard")
(let [utopia (get-in @state [:runner :rig :resource 0])]
(card-ability state :runner utopia 0))
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 3 (count (:hand (get-corp)))) "All 3 Subliminals returned to HQ")
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(is (empty? (get-in @state [:corp :prompt])) "No prompt here because runner made a run last turn")
(take-credits state :corp)
(is (= 2 (count (:hand (get-corp)))))
(is (= 1 (count (:discard (get-corp)))) "1 Subliminal not returned because runner made a run last turn")))
(deftest subliminal-messaging-archived
;; Subliminal Messaging - Scenario involving Subliminal being added to HQ with Archived Memories
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2) (qty "Archived Memories" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Archived Memories")
(prompt-select :corp (find-card "Subliminal Messaging" (:discard (get-corp))))
(is (= 2 (count (:discard (get-corp)))))
(is (= 1 (count (:hand (get-corp)))))
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "No")
(is (empty? (get-in @state [:corp :prompt])) "Only 1 Subliminal prompt")
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (empty? (get-in @state [:corp :prompt]))
"Only 2 Subliminal prompts - there will be a third if flag not cleared")))
(deftest subliminal-messaging-jackson
;; Subliminal Messaging - Scenario involving Subliminal being reshuffled into R&D with Jackson
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 1) (qty "Jackson Howard" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Jackson Howard" "New remote")
(take-credits state :corp)
(let [jhow (get-content state :remote1 0)]
(core/rez state :corp jhow)
(card-ability state :corp jhow 1)
(prompt-select :corp (find-card "Subliminal Messaging" (:discard (get-corp))))
(prompt-choice :corp "Done")
(is (= 0 (count (:discard (get-corp)))))
(is (= 1 (count (:rfg (get-corp))))))
(take-credits state :runner)
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(is (= 1 (count (:hand (get-corp)))) "Subliminal returned to HQ")
(is (empty? (get-in @state [:corp :prompt]))
"Subliminal prompt cleared - there will be a second prompt if flag not cleared")))
(deftest subliminal-messaging-made-run
;; Subliminal Messaging - Runner made run, ensure game asks again next turn
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(trash-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(is (empty? (get-in @state [:corp :prompt])) "No prompt here because runner made a run last turn")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 2 (count (:hand (get-corp)))) "Both Subliminals returned to HQ")
(is (= 0 (count (:discard (get-corp)))) "No Subliminals in Archives")))
(deftest subliminal-messaging-no
;; Subliminal Messaging - User declines to return to hand, ensure game asks again next turn
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(trash-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "No")
(prompt-choice :corp "No")
(is (= 0 (count (:hand (get-corp)))) "Neither Subliminal returned to HQ")
(is (= 2 (count (:discard (get-corp)))) "Both Subliminals in Archives")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 2 (count (:hand (get-corp)))) "Both Subliminals returned to HQ")
(is (= 0 (count (:discard (get-corp)))) "No Subliminals in Archives")))
(deftest successful-demonstration
;; Successful Demonstration - Play if only Runner made unsuccessful run last turn; gain 7 credits
(do-game
(new-game (default-corp [(qty "Successful Demonstration" 1)])
(default-runner))
(play-from-hand state :corp "Successful Demonstration")
(is (and (= 3 (:click (get-corp)))
(= 5 (:credit (get-runner))))
"Successful Demonstration precondition not met; card not played")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(play-from-hand state :corp "Successful Demonstration")
(is (= 13 (:credit (get-corp))) "Paid 2 to play event; gained 7 credits")))
(deftest wetwork-refit
;; Wetwork Refit - Only works on bioroid ice and adds a subroutine
(do-game
(new-game (default-corp [(qty "Eli 1.0" 1)
(qty "Vanilla" 1)
(qty "Wetwork Refit" 3)])
(default-runner))
(play-from-hand state :corp "Eli 1.0" "R&D")
(play-from-hand state :corp "Vanilla" "HQ")
(let [eli (get-ice state :rd 0)
vanilla (get-ice state :hq 0)]
(play-from-hand state :corp "Wetwork Refit")
(is (not-any? #{"Eli 1.0"} (get-in @state [:runner :prompt :choices]))
"Unrezzed Eli 1.0 is not a choice to host Wetwork Refit")
(prompt-choice :corp "Done")
(take-credits state :corp)
(take-credits state :runner)
(core/rez state :corp (refresh eli))
(core/rez state :corp (refresh vanilla))
(play-from-hand state :corp "Wetwork Refit")
(prompt-select :corp (refresh eli))
(is (= "Wetwork Refit" (:title (first (:hosted (refresh eli)))))
"Wetwork Refit is hosted on Eli 1.0")
(is (= 2 (count (:subroutines (refresh eli))))
"Eli 1.0 has 2 different subroutines")
(is (= "Do 1 brain damage" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has a brain damage subroutine as his first subroutine")
(core/move state :corp (first (:hosted (refresh eli))) :hand)
(is (empty? (:hosted (refresh eli))) "No cards are hosted on Eli 1.0")
(is (= 1 (count (:subroutines (refresh eli))))
"Eli 1.0 has 1 different subroutine")
(is (= "End the run" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has an end the run subroutine as his first subroutine")
(play-from-hand state :corp "Wetwork Refit")
(prompt-select :corp (refresh vanilla))
(is (not= "Wetwork Refit" (:title (first (:hosted (refresh vanilla)))))
"Wetwork Refit is not hosted on Vanilla"))))
| 80995 | (ns test.cards.operations
(:require [game.core :as core]
[test.core :refer :all]
[test.utils :refer :all]
[test.macros :refer :all]
[clojure.test :refer :all]))
(deftest twenty-four-seven-news-cycle-breaking-news
;; 24/7 News Cycle - Breaking News interaction
(do-game
(new-game (default-corp [(qty "Breaking News" 2) (qty "24/7 News Cycle" 3)])
(default-runner))
(play-from-hand state :corp "Breaking News" "New remote")
(play-from-hand state :corp "Breaking News" "New remote")
(let [ag1 (get-content state :remote1 0)
ag2 (get-content state :remote2 0)]
(score-agenda state :corp ag1)
(score-agenda state :corp ag2)
(take-credits state :corp)
(is (= 0 (:tag (get-runner)))) ; tags cleared
(take-credits state :runner)
(play-from-hand state :corp "24/7 News Cycle")
(prompt-card :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))) "Forfeited Breaking News")
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner given 2 tags")
(take-credits state :corp 2)
(is (= 2 (:tag (get-runner))) "Tags remained after Corp ended turn"))))
(deftest twenty-four-seven-news-cycle-posted-bounty
;; 24/7 News Cycle and Posted Bounty interaction -- Issue #1043
(do-game
(new-game (default-corp [(qty "Posted Bounty" 2) (qty "24/7 News Cycle" 3)])
(default-runner))
(play-from-hand state :corp "Posted Bounty" "New remote")
(play-from-hand state :corp "Posted Bounty" "New remote")
(let [ag1 (get-content state :remote1 0)
ag2 (get-content state :remote2 0)]
(score-agenda state :corp ag1)
(prompt-choice :corp "No")
(score-agenda state :corp ag2)
(prompt-choice :corp "No")
(play-from-hand state :corp "24/7 News Cycle")
(prompt-card :corp (find-card "Posted Bounty" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))) "Forfeited Posted Bounty")
(prompt-select :corp (find-card "Posted Bounty" (:scored (get-corp))))
(prompt-choice :corp "Yes") ; "Forfeit Posted Bounty to give 1 tag?"
(is (= 1 (:tag (get-runner))) "Runner given 1 tag")
(is (= 1 (:bad-publicity (get-corp))) "Corp has 1 bad publicity")
(is (= 0 (:agenda-point (get-corp))) "Forfeited Posted Bounty to 24/7 News Cycle"))))
(deftest twenty-four-seven-news-cycle-swaps
;; 24/7 News Cycle - Swapped agendas are able to be used. #1555
(do-game
(new-game (default-corp [(qty "24/7 News Cycle" 1) (qty "Chronos Project" 1)
(qty "Philotic Entanglement" 1) (qty "Profiteering" 1)])
(default-runner [(qty "Turntable" 3)]))
(score-agenda state :corp (find-card "Chronos Project" (:hand (get-corp))))
(score-agenda state :corp (find-card "Philotic Entanglement" (:hand (get-corp))))
(take-credits state :corp)
(play-from-hand state :runner "Turntable")
(core/steal state :runner (find-card "Profiteering" (:hand (get-corp))))
(prompt-choice :runner "Yes")
(prompt-select :runner (find-card "Philotic Entanglement" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(take-credits state :runner)
(play-from-hand state :corp "24/7 News Cycle")
(prompt-card :corp (find-card "Chronos Project" (:scored (get-corp))))
(is (= "Chronos Project" (:title (first (:rfg (get-corp))))))
;; shouldn't work on an agenda in the Runner's scored area
(is (= 2 (count (:hand (get-runner)))))
(prompt-select :corp (find-card "Philotic Entanglement" (:scored (get-runner))))
(is (= 2 (count (:hand (get-runner)))))
;; resolve 'when scored' ability on swapped Profiteering
(is (= 8 (:credit (get-corp))))
(prompt-select :corp (find-card "Profiteering" (:scored (get-corp))))
(prompt-choice :corp "3")
(is (= 1 (:agenda-point (get-corp))))
(is (= 3 (:bad-publicity (get-corp))))
(is (= 23 (:credit (get-corp))) "Gained 15 credits")))
(deftest accelerated-diagnostics
;; Accelerated Diagnostics - Interaction with prompt effects, like Shipment from SanSan
(do-game
(new-game (default-corp [(qty "Accelerated Diagnostics" 1) (qty "Cerebral Overwriter" 1) (qty "Shipment from SanSan" 1)
(qty "Hedge Fund" 1) (qty "Back Channels" 1)])
(default-runner))
(starting-hand state :corp ["Accelerated Diagnostics" "Cerebral Overwriter"])
(play-from-hand state :corp "Cerebral Overwriter" "New remote")
(core/gain state :corp :credit 1)
(play-from-hand state :corp "Accelerated Diagnostics")
(let [playarea (get-in @state [:corp :play-area])
hf (find-card "Hedge Fund" playarea)
ss (find-card "Shipment from SanSan" playarea)
bc (find-card "Back Channels" playarea)
co (get-content state :remote1 0)]
(is (= 3 (count playarea)) "3 cards in play area")
(prompt-select :corp ss)
(prompt-choice :corp "2")
(prompt-select :corp co)
(is (= 2 (:advance-counter (refresh co))) "Cerebral Overwriter gained 2 advancements")
(prompt-select :corp hf)
(is (= 9 (:credit (get-corp))) "Corp gained credits from Hedge Fund")
(prompt-select :corp bc)
(prompt-select :corp (refresh co))
(is (= 15 (:credit (get-corp))) "Corp gained 6 credits for Back Channels"))))
(deftest big-brother
;; Big Brother - Give the Runner 2 tags if already tagged
(do-game
(new-game (default-corp [(qty "Big Brother" 1)])
(default-runner))
(play-from-hand state :corp "Big Brother")
(is (= 1 (count (:hand (get-corp)))) "Card not played because Runner has no tags")
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Big Brother")
(is (= 3 (:tag (get-runner))) "Runner gained 2 tags")))
(deftest biotic-labor
;; Biotic Labor - Gain 2 clicks
(do-game
(new-game (default-corp [(qty "Biotic Labor" 1)])
(default-runner))
(play-from-hand state :corp "Biotic Labor")
(is (= 1 (:credit (get-corp))))
(is (= 4 (:click (get-corp))) "Spent 1 click to gain 2 additional clicks")))
(deftest blue-level-clearance
;; Blue Level Clearance - Gain 5 credits and draw 2 cards
(do-game
(new-game (default-corp [(qty "Blue Level Clearance" 3)
(qty "Hedge Fund" 3)
(qty "Sweeps Week" 2)])
(default-runner))
(play-from-hand state :corp "Blue Level Clearance")
(is (= 8 (:credit (get-corp))) "Gained 5 credits")
(is (= 1 (:click (get-corp))))
(is (= 7 (count (:hand (get-corp)))) "Drew 2 cards")))
(deftest casting-call
;; Casting Call - Only do card-init on the Public agendas. Issue #1128
(do-game
(new-game (default-corp [(qty "Casting Call" 2) (qty "Oaktown Renovation" 1)
(qty "Improved Tracers" 1) (qty "Hunter" 1)])
(default-runner))
(core/gain state :corp :click 1)
(play-from-hand state :corp "<NAME>" "HQ")
(let [hunter (get-ice state :hq 0)]
(core/rez state :corp hunter)
(is (= 4 (:current-strength (refresh hunter))))
(play-from-hand state :corp "Casting Call")
(prompt-select :corp (find-card "Improved Tracers" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(let [imptrac (get-content state :remote1 0)]
(is (get-in (refresh imptrac) [:rezzed]) "Improved Tracers is faceup")
(is (= 4 (:current-strength (refresh hunter))) "Hunter hasn't gained strength")
(play-from-hand state :corp "Casting Call")
(prompt-select :corp (find-card "Oaktown Renovation" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(let [oak (get-content state :remote2 0)]
(core/advance state :corp {:card (refresh oak)})
(is (= 5 (:credit (get-corp))) "Events on Public agenda work; gained 2 credits from advancing")
(take-credits state :corp)
(run-empty-server state "Server 2")
(prompt-select :runner oak)
(prompt-choice :runner "Steal")
(is (= 2 (:tag (get-runner))) "Runner took 2 tags from accessing agenda with Casting Call hosted on it"))))))
(deftest cerebral-static-chaos-theory
;; Cerebral Static - vs Chaos Theory
(do-game
(new-game (default-corp [(qty "Cerebral Static" 1) (qty "Lag Time" 1)])
(make-deck "Chaos Theory: Wünderkind" [(qty "Sure Gamble" 3)]))
(is (= 5 (:memory (get-runner))) "CT starts with 5 memory")
(play-from-hand state :corp "Cerebral Static")
(is (= 4 (:memory (get-runner))) "Cerebral Static causes CT to have 4 memory")
(play-from-hand state :corp "Lag Time")
(is (= 5 (:memory (get-runner))) "CT 5 memory restored")))
(deftest closed-accounts
;; Closed Accounts - Play if Runner is tagged to make Runner lose all credits
(do-game
(new-game (default-corp [(qty "Closed Accounts" 1)])
(default-runner))
(play-from-hand state :corp "Closed Accounts")
(is (and (= 3 (:click (get-corp)))
(= 5 (:credit (get-runner))))
"Closed Accounts precondition not met; card not played")
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Closed Accounts")
(is (= 0 (:credit (get-runner))) "Runner lost all credits")))
(deftest consulting-visit
;; Consulting Visit - Only show single copies of operations corp can afford as choices. Play chosen operation
(do-game
(new-game (default-corp [(qty "Consulting Visit" 1)
(qty "Beanstalk Royalties" 2)
(qty "Green Level Clearance" 1)
(qty "Breaking News" 1)
(qty "Hedge Fund" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(starting-hand state :corp ["Consulting Visit"])
(play-from-hand state :corp "Consulting Visit")
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-choice :corp (find-card "Beanstalk Royalties" (:deck (get-corp))))
(is (= 6 (:credit (get-corp)))))))
(deftest consulting-visit-mumbad
;; Consulting Visit - Works properly when played with Mumbad City Hall
(do-game
(new-game (default-corp [(qty "Mumbad City Hall" 1)
(qty "Beanstalk Royalties" 1)
(qty "Green Level Clearance" 1)
(qty "Breaking News" 1)
(qty "Hedge Fund" 1)
(qty "Consulting Visit" 1)
(qty "Mumba Temple" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(starting-hand state :corp ["Mumbad City Hall"])
(play-from-hand state :corp "Mumbad City Hall" "New remote")
(let [hall (get-content state :remote1 0)
get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(card-ability state :corp hall 0)
(is (= (list "Consulting Visit" "Mumba Temple" nil) (prompt-names)))
(prompt-choice :corp (find-card "Consulting Visit" (:deck (get-corp))))
(is (= 3 (:credit (get-corp))))
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-choice :corp (find-card "Green Level Clearance" (:deck (get-corp))))
(is (= 5 (:credit (get-corp)))))))
(deftest defective-brainchips
;; Defective Brainchips - Do 1 add'l brain damage the first time Runner takes some each turn
(do-game
(new-game (default-corp [(qty "Defective Brainchips" 1) (qty "Viktor 1.0" 1)])
(default-runner [(qty "Sure Gamble" 2) (qty "Shiv" 2)]))
(play-from-hand state :corp "Defective Brainchips")
(play-from-hand state :corp "Viktor 1.0" "HQ")
(take-credits state :corp)
(run-on state :hq)
(let [vik (get-ice state :hq 0)]
(core/rez state :corp vik)
(card-subroutine state :corp vik 0)
(is (= 2 (count (:discard (get-runner)))) "2 cards lost to brain damage")
(is (= 2 (:brain-damage (get-runner))) "Brainchips dealt 1 additional brain dmg")
(card-subroutine state :corp vik 0)
(is (= 3 (count (:discard (get-runner)))) "2 cards lost to brain damage")
(is (= 3 (:brain-damage (get-runner))) "Brainchips didn't do additional brain dmg"))))
(deftest diversified-portfolio
(do-game
(new-game (default-corp [(qty "Diversified Portfolio" 1)
(qty "Paper Wall" 1)
(qty "PAD Campaign" 3)])
(default-runner))
(core/gain state :corp :click 2)
(play-from-hand state :corp "Paper Wall" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "Diversified Portfolio")
(is (= 7 (:credit (get-corp))) "Ignored remote with ICE but no server contents")))
(deftest enhanced-login-protocol
;; Enhanced Login Protocol - First click run each turn costs an additional click
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Employee Strike" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make the second run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(take-credits state :runner 3)
(is (= 1 (:click (get-runner))) "Runner has 1 click")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 1 (:click (get-runner))) "Runner has 1 click")
(take-credits state :runner)
(take-credits state :corp)
(play-from-hand state :runner "Employee Strike")
(is (= 3 (:click (get-runner))) "Runner has 3 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make a run")))
(deftest enhanced-login-protocol-card-ability
;; Enhanced Login Protocol - Card ability runs don't cost additional clicks
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(take-credits state :runner)
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 2 clicks")
(let [sneakdoor (get-in @state [:runner :rig :program 0])]
(card-ability state :runner sneakdoor 0)
(is (= 3 (:click (get-runner)))
"Runner doesn't spend 1 additional click to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make a run"))))
(deftest enhanced-login-protocol-run-events
;; Enhanced Login Protocol - Run event don't cost additional clicks
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Out of the Ashes" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(play-from-hand state :runner "Out of the Ashes")
(prompt-choice :runner "Archives")
(is (= 3 (:click (get-runner)))
"Runner doesn't spend 1 additional click to run with a run event")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(prompt-choice :runner "No") ; Out of the Ashes prompt
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make a run")))
(deftest enhanced-login-protocol-runner-turn-first-run
;; Enhanced Login Protocol - Works when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
[(qty "Enhanced Login Protocol" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(core/gain state :runner :credit 2)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Enhanced Login Protocol"
(:hand (get-corp))))
(is (find-card "Enhanced Login Protocol" (:current (get-corp)))
"Enhanced Login Protocol is in play")
(is (= 3 (:click (get-runner))) "Runner has 3 clicks")
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")))
(deftest enhanced-login-protocol-runner-turn-second-run
;; Enhanced Login Protocol - Doesn't fire if already run when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
[(qty "Enhanced Login Protocol" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(run-on state :hq)
(run-successful state)
(prompt-choice :runner "OK")
(core/gain state :runner :credit 2)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Enhanced Login Protocol"
(:hand (get-corp))))
(is (find-card "Enhanced Login Protocol" (:current (get-corp)))
"Enhanced Login Protocol is in play")
(is (= 2 (:click (get-runner))) "Runner has 2 clicks")
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make a run")))
(deftest exchange-of-information
;; Exchange of Information - Swapping agendas works correctly
(do-game
(new-game (default-corp [(qty "Exchange of Information" 1)
(qty "Market Research" 1)
(qty "Breaking News" 1)
(qty "Project Beale" 1)
(qty "Explode-a-palooza" 1)])
(default-runner))
(score-agenda state :corp (find-card "Market Research" (:hand (get-corp))))
(score-agenda state :corp (find-card "Breaking News" (:hand (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner gained 2 tags")
(take-credits state :corp)
(is (= 0 (:tag (get-runner))) "Runner lost 2 tags")
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(core/steal state :runner (find-card "Explode-a-palooza" (:hand (get-corp))))
(take-credits state :runner)
(is (= 4 (:agenda-point (get-runner))))
(is (= 3 (:agenda-point (get-corp))))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 3 (:agenda-point (get-runner))))
(is (= 4 (:agenda-point (get-corp))))))
(deftest exchange-of-information-breaking-news
;; Exchange of Information - Swapping a just scored Breaking News keeps the tags
(do-game
(new-game (default-corp [(qty "Exchange of Information" 1)
(qty "Market Research" 1)
(qty "Breaking News" 1)
(qty "Project Beale" 1)
(qty "Explode-a-palooza" 1)])
(default-runner))
(take-credits state :corp)
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(core/steal state :runner (find-card "Explode-a-palooza" (:hand (get-corp))))
(take-credits state :runner)
(score-agenda state :corp (find-card "Breaking News" (:hand (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner gained 2 tags")
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 2 (:tag (get-runner))) "Still has tags after swap and before end of turn")
(take-credits state :corp)
(is (= 3 (:agenda-point (get-runner))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner does not lose tags at end of turn")))
(deftest exchange-of-information-fifteen-minutes
;; Exchange of Information - Swapping a 15 Minutes still keeps the ability. #1783
(do-game
(new-game (default-corp [(qty "Exchange of Information" 2) (qty "15 Minutes" 1)
(qty "Project Beale" 1)])
(default-runner))
(score-agenda state :corp (find-card "15 Minutes" (:hand (get-corp))))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(take-credits state :runner)
(is (= 1 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "15 Minutes" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 1 (:agenda-point (get-runner))))
(is (= 0 (count (:deck (get-corp)))))
;; shuffle back into R&D from runner's scored area
(let [fifm (get-in @state [:runner :scored 0])]
(card-ability state :corp fifm 0))
(is (= 2 (:agenda-point (get-corp))))
(is (= 0 (:agenda-point (get-runner))))
(is (= "15 Minutes" (:title (first (:deck (get-corp))))))
(take-credits state :corp)
(core/steal state :runner (find-card "15 Minutes" (:deck (get-corp))))
(take-credits state :runner)
(is (= 2 (:agenda-point (get-corp))))
(is (= 1 (:agenda-point (get-runner))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "15 Minutes" (:scored (get-runner))))
(prompt-select :corp (find-card "Project Beale" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
;; shuffle back into R&D from corp's scored area
(let [fifm (get-in @state [:corp :scored 0])]
(card-ability state :corp fifm 0))
(is (= "15 Minutes" (:title (first (:deck (get-corp))))))))
(deftest exchange-of-information-mandatory-upgrades
;; Exchange of Information - Swapping a Mandatory Upgrades gives the Corp an additional click per turn. #1687
(do-game
(new-game (default-corp [(qty "Exchange of Information" 2) (qty "Mandatory Upgrades" 1)
(qty "Global Food Initiative" 1)])
(default-runner))
(score-agenda state :corp (find-card "Global Food Initiative" (:hand (get-corp))))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(core/steal state :runner (find-card "Mandatory Upgrades" (:hand (get-corp))))
(take-credits state :runner)
(is (= 3 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 3 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Mandatory Upgrades" (:scored (get-runner))))
(prompt-select :corp (find-card "Global Food Initiative" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 3 (:click (get-corp))))
(is (= 4 (:click-per-turn (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(is (= 4 (:click (get-corp))))
(is (= 4 (:click-per-turn (get-corp))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Global Food Initiative" (:scored (get-runner))))
(prompt-select :corp (find-card "Mandatory Upgrades" (:scored (get-corp))))
(is (= 3 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 2 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(is (= 3 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))))
(deftest election-day
(do-game
(new-game (default-corp [(qty "Election Day" 7)])
(default-runner))
(is (= 6 (count (:hand (get-corp)))) "Corp starts with 5 + 1 cards")
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(play-from-hand state :corp "Election Day")
(is (= 1 (count (:hand (get-corp)))) "Could not play Election Day")
(take-credits state :corp)
(take-credits state :runner)
(is (= 2 (count (:hand (get-corp)))) "Corp has now 1 + 1 cards before Election Day")
(play-from-hand state :corp "Election Day")
(is (= 5 (count (:hand (get-corp)))) "Corp has now 5 cards due to Election Day")))
(deftest hedge-fund
(do-game
(new-game (default-corp) (default-runner))
(is (= 5 (:credit (get-corp))))
(play-from-hand state :corp "Hedge Fund")
(is (= 9 (:credit (get-corp))))))
(deftest housekeeping
;; Housekeeping - Runner must trash a card from Grip on first install of a turn
(do-game
(new-game (default-corp [(qty "Housekeeping" 1)])
(default-runner [(qty "Cache" 2) (qty "Fall Guy" 1) (qty "Mr. Li" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Fall Guy")
(take-credits state :runner)
(play-from-hand state :corp "Housekeeping")
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(prompt-select :runner (find-card "Mr. Li" (:hand (get-runner))))
(is (empty? (:prompt (get-runner))) "Fall Guy prevention didn't trigger")
(is (= 1 (count (:discard (get-runner)))) "Card trashed")
(play-from-hand state :runner "Cache")
(is (empty? (:prompt (get-runner))) "Housekeeping didn't trigger on 2nd install")))
(deftest invasion-of-privacy
;; Invasion of Privacy - Full test
(do-game
(new-game (default-corp [(qty "Invasion of Privacy" 3)])
(default-runner [(qty "Sure Gamble" 2) (qty "Fall Guy" 1) (qty "Cache" 2)]))
(core/gain state :corp :click 3 :credit 6)
;; trash 2 cards
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 5 (count (:hand (get-runner)))))
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" "Sure Gamble" nil) (prompt-names)))
(prompt-choice :corp (find-card "Sure Gamble" (:hand (get-runner))))
(prompt-choice :corp (find-card "Sure Gamble" (:hand (get-runner)))))
(is (= 3 (count (:hand (get-runner)))))
;; able to trash 2 cards but only 1 available target in Runner's hand
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 3 (count (:hand (get-runner)))))
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" nil) (prompt-names)))
(prompt-choice :corp (find-card "Fall Guy" (:hand (get-runner))))
(is (empty? (get-in @state [:corp :prompt])) "No prompt for second card"))
(is (= 2 (count (:hand (get-runner)))))
;; failed trace - take the bad publicity
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 2) ; Runner matches
(is (= 1 (:bad-publicity (get-corp))))))
(deftest lateral-growth
(do-game
(new-game (default-corp [(qty "Lateral Growth" 1) (qty "Breaking News" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(play-from-hand state :corp "Lateral Growth")
(prompt-select :corp (find-card "Breaking News" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(is (= "Breaking News" (:title (get-content state :remote1 0)))
"Breaking News installed by Lateral Growth")
(is (= 7 (:credit (get-corp))))))
(deftest manhunt-every-run
;; Manhunt - only fires once per turn. Unreported issue.
(do-game
(new-game (default-corp [(qty "Manhunt" 1) (qty "Hedge Fund" 3)])
(default-runner))
(play-from-hand state :corp "Manhunt")
(take-credits state :corp)
(run-empty-server state "HQ")
(is (:prompt (get-corp)) "Manhunt trace initiated")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag")
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")
(run-empty-server state "HQ")
(is (empty? (:prompt (get-corp))) "No Manhunt trace on second run")
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")))
(deftest midseason-replacements
;; Midseason Replacements - Trace to give Runner tags after they steal an agenda
(do-game
(new-game (default-corp [(qty "Midseason Replacements" 1) (qty "Breaking News" 1)])
(default-runner))
(play-from-hand state :corp "Midseason Replacements")
(is (= 3 (:click (get-corp))) "Midseason precondition not met; Corp not charged a click")
(play-from-hand state :corp "Breaking News" "New remote")
(take-credits state :corp)
(is (= 7 (:credit (get-corp))))
(let [bn (get-content state :remote1 0)]
(run-empty-server state "Server 1")
(prompt-choice :runner "Steal")
(is (= 1 (:agenda-point (get-runner))) "Stole Breaking News")
(take-credits state :runner)
(play-from-hand state :corp "Midseason Replacements")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 6 (:tag (get-runner))) "Runner took 6 tags"))))
(deftest mushin-no-shin
;; <NAME> - Add 3 advancements to a card; prevent rez/score of that card the rest of the turn
(do-game
(new-game (default-corp [(qty "Mushin No Shin" 2) (qty "Ronin" 1) (qty "Profiteering" 1)])
(default-runner))
(play-from-hand state :corp "<NAME>")
(prompt-select :corp (find-card "<NAME>" (:hand (get-corp))))
(let [ronin (get-content state :remote1 0)]
(is (= 3 (:advance-counter (refresh ronin))) "3 advancements placed on Ronin")
(core/rez state :corp (refresh ronin))
(is (not (get-in (refresh ronin) [:rezzed])) "Ron<NAME> did not rez")
(take-credits state :corp)
(take-credits state :runner)
(core/rez state :corp (refresh ronin))
(is (get-in (refresh ronin) [:rezzed]) "Ronin now rezzed")
(play-from-hand state :corp "<NAME>")
(prompt-select :corp (find-card "Profiteering" (:hand (get-corp))))
(let [prof (get-content state :remote2 0)]
(core/score state :corp (refresh prof))
(is (empty? (:scored (get-corp))) "Profiteering not scored")
(is (= 0 (:agenda-point (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(core/score state :corp (refresh prof))
(prompt-choice :corp "0")
(is (= 1 (:agenda-point (get-corp))) "Profiteering was able to be scored")))))
(deftest neural-emp
;; Neural EMP - Play if Runner made a run the previous turn to do 1 net damage
(do-game
(new-game (default-corp [(qty "Neural EMP" 1)])
(default-runner))
(play-from-hand state :corp "Neural EMP")
(is (= 3 (:click (get-corp))) "Neural precondition not met; card not played")
(take-credits state :corp)
(run-empty-server state "Archives")
(take-credits state :runner)
(play-from-hand state :corp "Neural EMP")
(is (= 1 (count (:discard (get-runner)))) "Runner took 1 net damage")))
(deftest oversight-ai
;; Oversight AI - Rez a piece of ICE ignoring all costs
(do-game
(new-game (default-corp [(qty "Oversight AI" 1) (qty "Archer" 1)])
(default-runner))
(play-from-hand state :corp "Archer" "R&D")
(let [archer (get-ice state :rd 0)]
(play-from-hand state :corp "Oversight AI")
(prompt-select :corp archer)
(is (get-in (refresh archer) [:rezzed]))
(is (= 4 (:credit (get-corp))) "Archer rezzed at no credit cost")
(is (= "Oversight AI" (:title (first (:hosted (refresh archer)))))
"Archer hosting OAI as a condition"))))
(deftest patch
;; Patch - +2 current strength
(do-game
(new-game (default-corp [(qty "Patch" 1) (qty "Vanilla" 1)])
(default-runner))
(play-from-hand state :corp "Vanilla" "HQ")
(core/rez state :corp (get-ice state :hq 0))
(play-from-hand state :corp "Patch")
(prompt-select :corp (get-ice state :hq 0))
(is (= 2 (:current-strength (get-ice state :hq 0))) "Vanilla at 2 strength")))
(deftest paywall-implementation
;; Paywall Implementation - Gain 1 credit for every successful run
(do-game
(new-game (default-corp [(qty "Paywall Implementation" 1)])
(default-runner))
(play-from-hand state :corp "Paywall Implementation")
(is (= "Paywall Implementation" (:title (first (get-in @state [:corp :current]))))
"Paywall active in Current area")
(take-credits state :corp)
(is (= 7 (:credit (get-corp))))
(run-empty-server state "Archives")
(is (= 8 (:credit (get-corp))) "Gained 1 credit from successful run")
(run-empty-server state "Archives")
(is (= 9 (:credit (get-corp))) "Gained 1 credit from successful run")))
(deftest peak-efficiency
;; Peak Efficiency - Gain 1 credit for each rezzed ICE
(do-game
(new-game (default-corp [(qty "Peak Efficiency" 1) (qty "Paper Wall" 3) (qty "Wraparound" 1)])
(default-runner))
(core/gain state :corp :click 3)
(play-from-hand state :corp "Paper Wall" "HQ")
(play-from-hand state :corp "Paper Wall" "R&D")
(play-from-hand state :corp "Paper Wall" "New remote")
(play-from-hand state :corp "Wraparound" "New remote")
(core/rez state :corp (get-ice state :hq 0))
(core/rez state :corp (get-ice state :rd 0))
(core/rez state :corp (get-ice state :remote1 0))
(play-from-hand state :corp "Peak Efficiency")
(is (= 7 (:credit (get-corp))) "Gained 3 credits for 3 rezzed ICE; unrezzed ICE ignored")))
(deftest power-shutdown
;; Power Shutdown - Trash cards from R&D to force Runner to trash a program or hardware
(do-game
(new-game (default-corp [(qty "Power Shutdown" 3) (qty "Hive" 3)])
(default-runner [(qty "Grimoire" 1) (qty "Cache" 1)]))
(play-from-hand state :corp "Power Shutdown")
(is (empty? (:discard (get-corp))) "Not played, no run last turn")
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(play-from-hand state :runner "Grimoire")
(run-empty-server state :archives)
(take-credits state :runner)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(play-from-hand state :corp "Power Shutdown")
(prompt-choice :corp 2)
(is (= 3 (count (:discard (get-corp)))) "2 cards trashed from R&D")
(is (= 1 (count (:deck (get-corp)))) "1 card remaining in R&D")
(prompt-select :runner (get-in @state [:runner :rig :hardware 0])) ; try targeting Grimoire
(is (empty? (:discard (get-runner))) "Grimoire too expensive to be targeted")
(prompt-select :runner (get-in @state [:runner :rig :program 0]))
(is (= 1 (count (:discard (get-runner)))) "Cache trashed")))
(deftest precognition
;; Precognition - Full test
(do-game
(new-game (default-corp [(qty "Precognition" 1) (qty "<NAME>rice N<NAME>i" 1) (qty "Adonis Campaign" 1)
(qty "Quandary" 1) (qty "<NAME>" 1) (qty "Global Food Initiative" 1)])
(default-runner))
(starting-hand state :corp ["Precognition"])
(play-from-hand state :corp "Precognition")
(prompt-choice :corp (find-card "<NAME>" (:deck (get-corp))))
(prompt-choice :corp (find-card "Adonis Campaign" (:deck (get-corp))))
(prompt-choice :corp (find-card "Quandary" (:deck (get-corp))))
(prompt-choice :corp (find-card "<NAME>" (:deck (get-corp))))
(prompt-choice :corp (find-card "Global Food Initiative" (:deck (get-corp))))
;; try starting over
(prompt-choice :corp "Start over")
(prompt-choice :corp (find-card "Global Food Initiative" (:deck (get-corp))))
(prompt-choice :corp (find-card "<NAME>" (:deck (get-corp))))
(prompt-choice :corp (find-card "<NAME>" (:deck (get-corp))))
(prompt-choice :corp (find-card "Adonis Campaign" (:deck (get-corp))))
(prompt-choice :corp (find-card "<NAME>" (:deck (get-corp)))) ;this is the top card of R&D
(prompt-choice :corp "Done")
(is (= "<NAME>" (:title (first (:deck (get-corp))))))
(is (= "Adonis Campaign" (:title (second (:deck (get-corp))))))
(is (= "<NAME>" (:title (second (rest (:deck (get-corp)))))))
(is (= "<NAME>" (:title (second (rest (rest (:deck (get-corp))))))))
(is (= "Global Food Initiative" (:title (second (rest (rest (rest (:deck (get-corp)))))))))))
(deftest preemptive-action
;; Preemptive Action - Shuffles cards into R&D and removes itself from game
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 3)
(qty "Preemptive Action" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Preemptive Action")
(prompt-select :corp (first (:discard (get-corp))))
(prompt-select :corp (second (:discard (get-corp))))
(prompt-select :corp (last (:discard (get-corp))))
(is (= 0 (count (:discard (get-corp)))))
(is (= 1 (count (:rfg (get-corp)))))))
(deftest psychographics
;; Psychographics - Place advancements up to the number of Runner tags on a card
(do-game
(new-game (default-corp [(qty "Psychographics" 1) (qty "Project Junebug" 1)])
(default-runner))
(core/gain state :runner :tag 4)
(play-from-hand state :corp "Project Junebug" "New remote")
(let [pj (get-content state :remote1 0)]
(play-from-hand state :corp "Psychographics")
(prompt-choice :corp 4)
(prompt-select :corp pj)
(is (= 1 (:credit (get-corp))) "Spent 4 credits")
(is (= 4 (:advance-counter (refresh pj))) "Junebug has 4 advancements"))))
(deftest punitive-counterstrike
;; Punitive Counterstrike - deal meat damage equal to printed agenda points
(do-game
(new-game (default-corp [(qty "Global Food Initiative" 1) (qty "Punitive Counterstrike" 1)])
(default-runner))
(play-from-hand state :corp "Global Food Initiative" "New remote")
(take-credits state :corp)
(run-empty-server state :remote1)
(prompt-choice :runner "Steal")
(is (= 2 (:agenda-point (get-runner))) "Runner scored 2 points")
(take-credits state :runner)
(play-from-hand state :corp "Punitive Counterstrike")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (empty? (:hand (get-runner))) "Runner took 3 meat damage")))
(deftest reuse
;; Reuse - Gain 2 credits for each card trashed from HQ
(do-game
(new-game (default-corp [(qty "Reuse" 2) (qty "Hive" 1) (qty "IQ" 1)
(qty "Ice Wall" 1)])
(default-runner))
(play-from-hand state :corp "Reuse")
(prompt-select :corp (find-card "Ice Wall" (:hand (get-corp))))
(prompt-select :corp (find-card "Hive" (:hand (get-corp))))
(prompt-select :corp (find-card "IQ" (:hand (get-corp))))
(prompt-choice :corp "Done")
(is (= 4 (count (:discard (get-corp)))) "3 cards trashed plus operation played")
(is (= 11 (:credit (get-corp))) "Gained 6 credits")
(is (= 1 (:click (get-corp))) "Spent 2 clicks")))
(deftest salems-hospitality
;; Salem's Hospitality - Full test
(do-game
(new-game (default-corp [(qty "Salem's Hospitality" 3)])
(default-runner [(qty "I've Had Worse" 3) (qty "Faust" 1)
(qty "Levy AR Lab Access" 1)]))
(play-from-hand state :corp "Salem's Hospitality")
(is (= 5 (count (:hand (get-runner)))))
(prompt-choice :corp "I've Had Worse")
(is (= 2 (count (:hand (get-runner)))))
(play-from-hand state :corp "Salem's Hospitality")
(prompt-choice :corp "Plascrete Carapace")
(is (= 2 (count (:hand (get-runner)))))))
(deftest scorched-earth
;; Scorched Earth - burn 'em
(do-game
(new-game (default-corp [(qty "Scorched Earth" 1)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Scorched Earth")
(is (= 1 (count (:hand (get-runner)))) "Runner has 1 card in hand")))
(deftest scorched-earth-no-tag
;; Scorched Earth - not tagged
(do-game
(new-game (default-corp [(qty "Scorched Earth" 1)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(play-from-hand state :corp "Scorched Earth")
(is (= 3 (:click (get-corp))) "Corp not charged a click")
(is (= 5 (count (:hand (get-runner)))) "Runner did not take damage")))
(deftest scorched-earth-flatline
;; Scorched Earth - murderize 'em
(do-game
(new-game (default-corp [(qty "Scorched Earth" 1)])
(default-runner))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Scorched Earth")
(is (= 0 (count (:hand (get-runner)))) "Runner has 0 cards in hand")
(is (= :corp (:winner @state)) "Corp wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline")))
(deftest subcontract-scorched
;; Subcontract - Don't allow second operation until damage prevention completes
(do-game
(new-game (default-corp [(qty "Scorched Earth" 2) (qty "Subcontract" 1)])
(default-runner [(qty "Plascrete Carapace" 1)]))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(play-from-hand state :runner "Plascrete Carapace")
(take-credits state :runner)
(play-from-hand state :corp "Subcontract")
(prompt-select :corp (find-card "Scorched Earth" (:hand (get-corp))))
(is (and (= 1 (count (:prompt (get-corp)))) (= :waiting (-> (get-corp) :prompt first :prompt-type)))
"Corp does not have Subcontract prompt until damage prevention completes")
(prompt-choice :runner "Done")
(is (not-empty (:prompt (get-corp))) "Corp can now play second Subcontract operation")))
(deftest subcontract-terminal
;; Subcontract - interaction with Terminal operations
(do-game
(new-game
(default-corp [(qty "Hard-Hitting News" 2) (qty "Subcontract" 1)])
(default-runner))
(core/gain state :runner :tag 1)
(take-credits state :corp)
(run-empty-server state :archives)
(take-credits state :runner)
(play-from-hand state :corp "Subcontract")
(prompt-select :corp (find-card "Hard-Hitting News" (:hand (get-corp))))
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 5 (:tag (get-runner))) "Runner has 5 tags")
(is (empty? (:prompt (get-corp))) "Corp does not have a second Subcontract selection prompt")))
(deftest service-outage
;; Service Outage - First click run each turn costs a credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Employee Strike" 1)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(is (= 5 (:credit (get-runner))) "Runner has 5 credits")
(run-on state :archives)
(is (= 4 (:credit (get-runner)))
"Runner spends 1 credit to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 4 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make the second run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 6)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 2)
(play-from-hand state :runner "Employee Strike")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")))
(deftest service-outage-card-ability
;; Service Outage - First card ability run each turn costs an additional credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(take-credits state :runner 1)
(is (= 2 (:credit (get-runner))) "Runner has 2 credits")
(let [sneakdoor (get-in @state [:runner :rig :program 0])]
(card-ability state :runner sneakdoor 0)
(is (= 1 (:credit (get-runner)))
"Runner spends 1 additional credit to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 1)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(card-ability state :runner sneakdoor 0)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits"))))
(deftest service-outage-run-events
;; Service Outage - First run event each turn costs an additional credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Out of the Ashes" 2)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(is (= 5 (:credit (get-runner))) "Runner has 5 credits")
(play-from-hand state :runner "Out of the Ashes")
(is (= 3 (:credit (get-runner)))
"Runner spends 1 additional credit to run with a run event")
(prompt-choice :runner "Archives")
(run-successful state)
(run-on state :archives)
(is (= 3 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(prompt-choice :runner "No") ; Out of the Ashes prompt
(core/lose state :runner :credit 4)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(play-from-hand state :runner "Out of the Ashes")
(is (empty? (get-in @state [:runner :prompt]))
"Out of the Ashes was not played")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")))
(deftest service-outage-runner-turn-first-run
;; Service Outage - Works when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News" [(qty "Service Outage" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(core/gain state :runner :credit 3)
(play-from-hand state :runner "<NAME>")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Service Outage" (:hand (get-corp))))
(is (find-card "Service Outage" (:current (get-corp)))
"Service Outage is in play")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 0 (:credit (get-runner)))
"Runner spends 1 additional credit to make a run")))
(deftest service-outage-runner-turn-second-run
;; Service Outage - Doesn't fire if already run when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News" [(qty "Service Outage" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(run-on state :hq)
(run-successful state)
(prompt-choice :runner "OK")
(core/gain state :runner :credit 3)
(play-from-hand state :runner "<NAME>")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Service Outage" (:hand (get-corp))))
(is (find-card "Service Outage" (:current (get-corp)))
"Service Outage is in play")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 additional credit to make a run")))
(deftest shipment-from-sansan
;; Shipment from SanSan - placing advancements
(do-game
(new-game (default-corp [(qty "Shipment from SanSan" 3) (qty "Ice Wall" 3)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(let [iwall (get-ice state :hq 0)]
(play-from-hand state :corp "Shipment from SanSan")
(prompt-choice :corp "2")
(prompt-select :corp iwall)
(is (= 5 (:credit (get-corp))))
(is (= 2 (:advance-counter (refresh iwall)))))))
(deftest stock-buy-back
;; Stock Buy-Back - Gain 3c for every agenda in Runner's area
(do-game
(new-game (default-corp [(qty "Hostile Takeover" 2) (qty "Stock Buy-Back" 3)])
(default-runner))
(play-from-hand state :corp "Hostile Takeover" "New remote")
(play-from-hand state :corp "Hostile Takeover" "New remote")
(take-credits state :corp)
(run-empty-server state "Server 1")
(prompt-choice :runner "Steal")
(run-empty-server state "Server 2")
(prompt-choice :runner "Steal")
(take-credits state :runner)
(is (= 2 (count (:scored (get-runner)))))
(play-from-hand state :corp "Stock Buy-Back")
(is (= 11 (:credit (get-corp))))))
(deftest sub-boost
;; Sub Boost - Give ice barrier
(do-game
(new-game (default-corp [(qty "Sub Boost" 1) (qty "Quandary" 1)])
(default-runner))
(play-from-hand state :corp "Quandary" "HQ")
(play-from-hand state :corp "Sub Boost")
(let [qu (get-ice state :hq 0)]
(core/rez state :corp qu)
(prompt-select :corp qu)
(is (core/has-subtype? (refresh qu) "Code Gate") "Quandary has code gate")
(is (core/has-subtype? (refresh qu) "Barrier") "Quandary has barrier"))))
(deftest subliminal-messaging
;; Subliminal Messaging - Playing/trashing/milling will all prompt returning to hand
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 3)])
(make-deck "Noise: Hacker Extraordinaire" [(qty "Cache" 3) (qty "Utopia Shard" 1)]))
(play-from-hand state :corp "Subliminal Messaging")
(is (= 6 (:credit (get-corp))))
(is (= 3 (:click (get-corp))) "First Subliminal Messaging gains 1 click")
(play-from-hand state :corp "Subliminal Messaging")
(is (= 7 (:credit (get-corp))))
(is (= 2 (:click (get-corp))) "Second Subliminal Messaging does not gain 1 click")
(trash-from-hand state :corp "Subliminal Messaging")
(is (= 0 (count (:hand (get-corp)))))
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 3 (count (:hand (get-corp)))) "All 3 Subliminals returned to HQ")
(core/move state :corp (find-card "Subliminal Messaging" (:hand (get-corp))) :deck)
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(play-from-hand state :runner "Utopia Shard")
(let [utopia (get-in @state [:runner :rig :resource 0])]
(card-ability state :runner utopia 0))
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 3 (count (:hand (get-corp)))) "All 3 Subliminals returned to HQ")
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(is (empty? (get-in @state [:corp :prompt])) "No prompt here because runner made a run last turn")
(take-credits state :corp)
(is (= 2 (count (:hand (get-corp)))))
(is (= 1 (count (:discard (get-corp)))) "1 Subliminal not returned because runner made a run last turn")))
(deftest subliminal-messaging-archived
;; Subliminal Messaging - Scenario involving Subliminal being added to HQ with Archived Memories
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2) (qty "Archived Memories" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Archived Memories")
(prompt-select :corp (find-card "Subliminal Messaging" (:discard (get-corp))))
(is (= 2 (count (:discard (get-corp)))))
(is (= 1 (count (:hand (get-corp)))))
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "No")
(is (empty? (get-in @state [:corp :prompt])) "Only 1 Subliminal prompt")
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (empty? (get-in @state [:corp :prompt]))
"Only 2 Subliminal prompts - there will be a third if flag not cleared")))
(deftest subliminal-messaging-jackson
;; Subliminal Messaging - Scenario involving Subliminal being reshuffled into R&D with <NAME>son
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 1) (qty "<NAME>" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "<NAME>" "New remote")
(take-credits state :corp)
(let [jhow (get-content state :remote1 0)]
(core/rez state :corp jhow)
(card-ability state :corp jhow 1)
(prompt-select :corp (find-card "Subliminal Messaging" (:discard (get-corp))))
(prompt-choice :corp "Done")
(is (= 0 (count (:discard (get-corp)))))
(is (= 1 (count (:rfg (get-corp))))))
(take-credits state :runner)
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(is (= 1 (count (:hand (get-corp)))) "Subliminal returned to HQ")
(is (empty? (get-in @state [:corp :prompt]))
"Subliminal prompt cleared - there will be a second prompt if flag not cleared")))
(deftest subliminal-messaging-made-run
;; Subliminal Messaging - Runner made run, ensure game asks again next turn
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(trash-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(is (empty? (get-in @state [:corp :prompt])) "No prompt here because runner made a run last turn")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 2 (count (:hand (get-corp)))) "Both Subliminals returned to HQ")
(is (= 0 (count (:discard (get-corp)))) "No Subliminals in Archives")))
(deftest subliminal-messaging-no
;; Subliminal Messaging - User declines to return to hand, ensure game asks again next turn
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(trash-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "No")
(prompt-choice :corp "No")
(is (= 0 (count (:hand (get-corp)))) "Neither Subliminal returned to HQ")
(is (= 2 (count (:discard (get-corp)))) "Both Subliminals in Archives")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 2 (count (:hand (get-corp)))) "Both Subliminals returned to HQ")
(is (= 0 (count (:discard (get-corp)))) "No Subliminals in Archives")))
(deftest successful-demonstration
;; Successful Demonstration - Play if only Runner made unsuccessful run last turn; gain 7 credits
(do-game
(new-game (default-corp [(qty "Successful Demonstration" 1)])
(default-runner))
(play-from-hand state :corp "Successful Demonstration")
(is (and (= 3 (:click (get-corp)))
(= 5 (:credit (get-runner))))
"Successful Demonstration precondition not met; card not played")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(play-from-hand state :corp "Successful Demonstration")
(is (= 13 (:credit (get-corp))) "Paid 2 to play event; gained 7 credits")))
(deftest wetwork-refit
;; Wetwork Refit - Only works on bioroid ice and adds a subroutine
(do-game
(new-game (default-corp [(qty "Eli 1.0" 1)
(qty "Vanilla" 1)
(qty "Wetwork Refit" 3)])
(default-runner))
(play-from-hand state :corp "Eli 1.0" "R&D")
(play-from-hand state :corp "Vanilla" "HQ")
(let [eli (get-ice state :rd 0)
vanilla (get-ice state :hq 0)]
(play-from-hand state :corp "Wetwork Refit")
(is (not-any? #{"Eli 1.0"} (get-in @state [:runner :prompt :choices]))
"Unrezzed Eli 1.0 is not a choice to host Wetwork Refit")
(prompt-choice :corp "Done")
(take-credits state :corp)
(take-credits state :runner)
(core/rez state :corp (refresh eli))
(core/rez state :corp (refresh vanilla))
(play-from-hand state :corp "Wetwork Refit")
(prompt-select :corp (refresh eli))
(is (= "Wetwork Refit" (:title (first (:hosted (refresh eli)))))
"Wetwork Refit is hosted on Eli 1.0")
(is (= 2 (count (:subroutines (refresh eli))))
"Eli 1.0 has 2 different subroutines")
(is (= "Do 1 brain damage" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has a brain damage subroutine as his first subroutine")
(core/move state :corp (first (:hosted (refresh eli))) :hand)
(is (empty? (:hosted (refresh eli))) "No cards are hosted on Eli 1.0")
(is (= 1 (count (:subroutines (refresh eli))))
"Eli 1.0 has 1 different subroutine")
(is (= "End the run" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has an end the run subroutine as his first subroutine")
(play-from-hand state :corp "Wetwork Refit")
(prompt-select :corp (refresh vanilla))
(is (not= "Wetwork Refit" (:title (first (:hosted (refresh vanilla)))))
"Wetwork Refit is not hosted on Vanilla"))))
| true | (ns test.cards.operations
(:require [game.core :as core]
[test.core :refer :all]
[test.utils :refer :all]
[test.macros :refer :all]
[clojure.test :refer :all]))
(deftest twenty-four-seven-news-cycle-breaking-news
;; 24/7 News Cycle - Breaking News interaction
(do-game
(new-game (default-corp [(qty "Breaking News" 2) (qty "24/7 News Cycle" 3)])
(default-runner))
(play-from-hand state :corp "Breaking News" "New remote")
(play-from-hand state :corp "Breaking News" "New remote")
(let [ag1 (get-content state :remote1 0)
ag2 (get-content state :remote2 0)]
(score-agenda state :corp ag1)
(score-agenda state :corp ag2)
(take-credits state :corp)
(is (= 0 (:tag (get-runner)))) ; tags cleared
(take-credits state :runner)
(play-from-hand state :corp "24/7 News Cycle")
(prompt-card :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))) "Forfeited Breaking News")
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner given 2 tags")
(take-credits state :corp 2)
(is (= 2 (:tag (get-runner))) "Tags remained after Corp ended turn"))))
(deftest twenty-four-seven-news-cycle-posted-bounty
;; 24/7 News Cycle and Posted Bounty interaction -- Issue #1043
(do-game
(new-game (default-corp [(qty "Posted Bounty" 2) (qty "24/7 News Cycle" 3)])
(default-runner))
(play-from-hand state :corp "Posted Bounty" "New remote")
(play-from-hand state :corp "Posted Bounty" "New remote")
(let [ag1 (get-content state :remote1 0)
ag2 (get-content state :remote2 0)]
(score-agenda state :corp ag1)
(prompt-choice :corp "No")
(score-agenda state :corp ag2)
(prompt-choice :corp "No")
(play-from-hand state :corp "24/7 News Cycle")
(prompt-card :corp (find-card "Posted Bounty" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))) "Forfeited Posted Bounty")
(prompt-select :corp (find-card "Posted Bounty" (:scored (get-corp))))
(prompt-choice :corp "Yes") ; "Forfeit Posted Bounty to give 1 tag?"
(is (= 1 (:tag (get-runner))) "Runner given 1 tag")
(is (= 1 (:bad-publicity (get-corp))) "Corp has 1 bad publicity")
(is (= 0 (:agenda-point (get-corp))) "Forfeited Posted Bounty to 24/7 News Cycle"))))
(deftest twenty-four-seven-news-cycle-swaps
;; 24/7 News Cycle - Swapped agendas are able to be used. #1555
(do-game
(new-game (default-corp [(qty "24/7 News Cycle" 1) (qty "Chronos Project" 1)
(qty "Philotic Entanglement" 1) (qty "Profiteering" 1)])
(default-runner [(qty "Turntable" 3)]))
(score-agenda state :corp (find-card "Chronos Project" (:hand (get-corp))))
(score-agenda state :corp (find-card "Philotic Entanglement" (:hand (get-corp))))
(take-credits state :corp)
(play-from-hand state :runner "Turntable")
(core/steal state :runner (find-card "Profiteering" (:hand (get-corp))))
(prompt-choice :runner "Yes")
(prompt-select :runner (find-card "Philotic Entanglement" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(take-credits state :runner)
(play-from-hand state :corp "24/7 News Cycle")
(prompt-card :corp (find-card "Chronos Project" (:scored (get-corp))))
(is (= "Chronos Project" (:title (first (:rfg (get-corp))))))
;; shouldn't work on an agenda in the Runner's scored area
(is (= 2 (count (:hand (get-runner)))))
(prompt-select :corp (find-card "Philotic Entanglement" (:scored (get-runner))))
(is (= 2 (count (:hand (get-runner)))))
;; resolve 'when scored' ability on swapped Profiteering
(is (= 8 (:credit (get-corp))))
(prompt-select :corp (find-card "Profiteering" (:scored (get-corp))))
(prompt-choice :corp "3")
(is (= 1 (:agenda-point (get-corp))))
(is (= 3 (:bad-publicity (get-corp))))
(is (= 23 (:credit (get-corp))) "Gained 15 credits")))
(deftest accelerated-diagnostics
;; Accelerated Diagnostics - Interaction with prompt effects, like Shipment from SanSan
(do-game
(new-game (default-corp [(qty "Accelerated Diagnostics" 1) (qty "Cerebral Overwriter" 1) (qty "Shipment from SanSan" 1)
(qty "Hedge Fund" 1) (qty "Back Channels" 1)])
(default-runner))
(starting-hand state :corp ["Accelerated Diagnostics" "Cerebral Overwriter"])
(play-from-hand state :corp "Cerebral Overwriter" "New remote")
(core/gain state :corp :credit 1)
(play-from-hand state :corp "Accelerated Diagnostics")
(let [playarea (get-in @state [:corp :play-area])
hf (find-card "Hedge Fund" playarea)
ss (find-card "Shipment from SanSan" playarea)
bc (find-card "Back Channels" playarea)
co (get-content state :remote1 0)]
(is (= 3 (count playarea)) "3 cards in play area")
(prompt-select :corp ss)
(prompt-choice :corp "2")
(prompt-select :corp co)
(is (= 2 (:advance-counter (refresh co))) "Cerebral Overwriter gained 2 advancements")
(prompt-select :corp hf)
(is (= 9 (:credit (get-corp))) "Corp gained credits from Hedge Fund")
(prompt-select :corp bc)
(prompt-select :corp (refresh co))
(is (= 15 (:credit (get-corp))) "Corp gained 6 credits for Back Channels"))))
(deftest big-brother
;; Big Brother - Give the Runner 2 tags if already tagged
(do-game
(new-game (default-corp [(qty "Big Brother" 1)])
(default-runner))
(play-from-hand state :corp "Big Brother")
(is (= 1 (count (:hand (get-corp)))) "Card not played because Runner has no tags")
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Big Brother")
(is (= 3 (:tag (get-runner))) "Runner gained 2 tags")))
(deftest biotic-labor
;; Biotic Labor - Gain 2 clicks
(do-game
(new-game (default-corp [(qty "Biotic Labor" 1)])
(default-runner))
(play-from-hand state :corp "Biotic Labor")
(is (= 1 (:credit (get-corp))))
(is (= 4 (:click (get-corp))) "Spent 1 click to gain 2 additional clicks")))
(deftest blue-level-clearance
;; Blue Level Clearance - Gain 5 credits and draw 2 cards
(do-game
(new-game (default-corp [(qty "Blue Level Clearance" 3)
(qty "Hedge Fund" 3)
(qty "Sweeps Week" 2)])
(default-runner))
(play-from-hand state :corp "Blue Level Clearance")
(is (= 8 (:credit (get-corp))) "Gained 5 credits")
(is (= 1 (:click (get-corp))))
(is (= 7 (count (:hand (get-corp)))) "Drew 2 cards")))
(deftest casting-call
;; Casting Call - Only do card-init on the Public agendas. Issue #1128
(do-game
(new-game (default-corp [(qty "Casting Call" 2) (qty "Oaktown Renovation" 1)
(qty "Improved Tracers" 1) (qty "Hunter" 1)])
(default-runner))
(core/gain state :corp :click 1)
(play-from-hand state :corp "PI:NAME:<NAME>END_PI" "HQ")
(let [hunter (get-ice state :hq 0)]
(core/rez state :corp hunter)
(is (= 4 (:current-strength (refresh hunter))))
(play-from-hand state :corp "Casting Call")
(prompt-select :corp (find-card "Improved Tracers" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(let [imptrac (get-content state :remote1 0)]
(is (get-in (refresh imptrac) [:rezzed]) "Improved Tracers is faceup")
(is (= 4 (:current-strength (refresh hunter))) "Hunter hasn't gained strength")
(play-from-hand state :corp "Casting Call")
(prompt-select :corp (find-card "Oaktown Renovation" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(let [oak (get-content state :remote2 0)]
(core/advance state :corp {:card (refresh oak)})
(is (= 5 (:credit (get-corp))) "Events on Public agenda work; gained 2 credits from advancing")
(take-credits state :corp)
(run-empty-server state "Server 2")
(prompt-select :runner oak)
(prompt-choice :runner "Steal")
(is (= 2 (:tag (get-runner))) "Runner took 2 tags from accessing agenda with Casting Call hosted on it"))))))
(deftest cerebral-static-chaos-theory
;; Cerebral Static - vs Chaos Theory
(do-game
(new-game (default-corp [(qty "Cerebral Static" 1) (qty "Lag Time" 1)])
(make-deck "Chaos Theory: Wünderkind" [(qty "Sure Gamble" 3)]))
(is (= 5 (:memory (get-runner))) "CT starts with 5 memory")
(play-from-hand state :corp "Cerebral Static")
(is (= 4 (:memory (get-runner))) "Cerebral Static causes CT to have 4 memory")
(play-from-hand state :corp "Lag Time")
(is (= 5 (:memory (get-runner))) "CT 5 memory restored")))
(deftest closed-accounts
;; Closed Accounts - Play if Runner is tagged to make Runner lose all credits
(do-game
(new-game (default-corp [(qty "Closed Accounts" 1)])
(default-runner))
(play-from-hand state :corp "Closed Accounts")
(is (and (= 3 (:click (get-corp)))
(= 5 (:credit (get-runner))))
"Closed Accounts precondition not met; card not played")
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Closed Accounts")
(is (= 0 (:credit (get-runner))) "Runner lost all credits")))
(deftest consulting-visit
;; Consulting Visit - Only show single copies of operations corp can afford as choices. Play chosen operation
(do-game
(new-game (default-corp [(qty "Consulting Visit" 1)
(qty "Beanstalk Royalties" 2)
(qty "Green Level Clearance" 1)
(qty "Breaking News" 1)
(qty "Hedge Fund" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(starting-hand state :corp ["Consulting Visit"])
(play-from-hand state :corp "Consulting Visit")
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-choice :corp (find-card "Beanstalk Royalties" (:deck (get-corp))))
(is (= 6 (:credit (get-corp)))))))
(deftest consulting-visit-mumbad
;; Consulting Visit - Works properly when played with Mumbad City Hall
(do-game
(new-game (default-corp [(qty "Mumbad City Hall" 1)
(qty "Beanstalk Royalties" 1)
(qty "Green Level Clearance" 1)
(qty "Breaking News" 1)
(qty "Hedge Fund" 1)
(qty "Consulting Visit" 1)
(qty "Mumba Temple" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(starting-hand state :corp ["Mumbad City Hall"])
(play-from-hand state :corp "Mumbad City Hall" "New remote")
(let [hall (get-content state :remote1 0)
get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(card-ability state :corp hall 0)
(is (= (list "Consulting Visit" "Mumba Temple" nil) (prompt-names)))
(prompt-choice :corp (find-card "Consulting Visit" (:deck (get-corp))))
(is (= 3 (:credit (get-corp))))
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-choice :corp (find-card "Green Level Clearance" (:deck (get-corp))))
(is (= 5 (:credit (get-corp)))))))
(deftest defective-brainchips
;; Defective Brainchips - Do 1 add'l brain damage the first time Runner takes some each turn
(do-game
(new-game (default-corp [(qty "Defective Brainchips" 1) (qty "Viktor 1.0" 1)])
(default-runner [(qty "Sure Gamble" 2) (qty "Shiv" 2)]))
(play-from-hand state :corp "Defective Brainchips")
(play-from-hand state :corp "Viktor 1.0" "HQ")
(take-credits state :corp)
(run-on state :hq)
(let [vik (get-ice state :hq 0)]
(core/rez state :corp vik)
(card-subroutine state :corp vik 0)
(is (= 2 (count (:discard (get-runner)))) "2 cards lost to brain damage")
(is (= 2 (:brain-damage (get-runner))) "Brainchips dealt 1 additional brain dmg")
(card-subroutine state :corp vik 0)
(is (= 3 (count (:discard (get-runner)))) "2 cards lost to brain damage")
(is (= 3 (:brain-damage (get-runner))) "Brainchips didn't do additional brain dmg"))))
(deftest diversified-portfolio
(do-game
(new-game (default-corp [(qty "Diversified Portfolio" 1)
(qty "Paper Wall" 1)
(qty "PAD Campaign" 3)])
(default-runner))
(core/gain state :corp :click 2)
(play-from-hand state :corp "Paper Wall" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "Diversified Portfolio")
(is (= 7 (:credit (get-corp))) "Ignored remote with ICE but no server contents")))
(deftest enhanced-login-protocol
;; Enhanced Login Protocol - First click run each turn costs an additional click
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Employee Strike" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make the second run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(take-credits state :runner 3)
(is (= 1 (:click (get-runner))) "Runner has 1 click")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 1 (:click (get-runner))) "Runner has 1 click")
(take-credits state :runner)
(take-credits state :corp)
(play-from-hand state :runner "Employee Strike")
(is (= 3 (:click (get-runner))) "Runner has 3 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make a run")))
(deftest enhanced-login-protocol-card-ability
;; Enhanced Login Protocol - Card ability runs don't cost additional clicks
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(take-credits state :runner)
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 2 clicks")
(let [sneakdoor (get-in @state [:runner :rig :program 0])]
(card-ability state :runner sneakdoor 0)
(is (= 3 (:click (get-runner)))
"Runner doesn't spend 1 additional click to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make a run"))))
(deftest enhanced-login-protocol-run-events
;; Enhanced Login Protocol - Run event don't cost additional clicks
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Out of the Ashes" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(play-from-hand state :runner "Out of the Ashes")
(prompt-choice :runner "Archives")
(is (= 3 (:click (get-runner)))
"Runner doesn't spend 1 additional click to run with a run event")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(prompt-choice :runner "No") ; Out of the Ashes prompt
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make a run")))
(deftest enhanced-login-protocol-runner-turn-first-run
;; Enhanced Login Protocol - Works when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
[(qty "Enhanced Login Protocol" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(core/gain state :runner :credit 2)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Enhanced Login Protocol"
(:hand (get-corp))))
(is (find-card "Enhanced Login Protocol" (:current (get-corp)))
"Enhanced Login Protocol is in play")
(is (= 3 (:click (get-runner))) "Runner has 3 clicks")
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")))
(deftest enhanced-login-protocol-runner-turn-second-run
;; Enhanced Login Protocol - Doesn't fire if already run when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
[(qty "Enhanced Login Protocol" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(run-on state :hq)
(run-successful state)
(prompt-choice :runner "OK")
(core/gain state :runner :credit 2)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Enhanced Login Protocol"
(:hand (get-corp))))
(is (find-card "Enhanced Login Protocol" (:current (get-corp)))
"Enhanced Login Protocol is in play")
(is (= 2 (:click (get-runner))) "Runner has 2 clicks")
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make a run")))
(deftest exchange-of-information
;; Exchange of Information - Swapping agendas works correctly
(do-game
(new-game (default-corp [(qty "Exchange of Information" 1)
(qty "Market Research" 1)
(qty "Breaking News" 1)
(qty "Project Beale" 1)
(qty "Explode-a-palooza" 1)])
(default-runner))
(score-agenda state :corp (find-card "Market Research" (:hand (get-corp))))
(score-agenda state :corp (find-card "Breaking News" (:hand (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner gained 2 tags")
(take-credits state :corp)
(is (= 0 (:tag (get-runner))) "Runner lost 2 tags")
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(core/steal state :runner (find-card "Explode-a-palooza" (:hand (get-corp))))
(take-credits state :runner)
(is (= 4 (:agenda-point (get-runner))))
(is (= 3 (:agenda-point (get-corp))))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 3 (:agenda-point (get-runner))))
(is (= 4 (:agenda-point (get-corp))))))
(deftest exchange-of-information-breaking-news
;; Exchange of Information - Swapping a just scored Breaking News keeps the tags
(do-game
(new-game (default-corp [(qty "Exchange of Information" 1)
(qty "Market Research" 1)
(qty "Breaking News" 1)
(qty "Project Beale" 1)
(qty "Explode-a-palooza" 1)])
(default-runner))
(take-credits state :corp)
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(core/steal state :runner (find-card "Explode-a-palooza" (:hand (get-corp))))
(take-credits state :runner)
(score-agenda state :corp (find-card "Breaking News" (:hand (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner gained 2 tags")
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 2 (:tag (get-runner))) "Still has tags after swap and before end of turn")
(take-credits state :corp)
(is (= 3 (:agenda-point (get-runner))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner does not lose tags at end of turn")))
(deftest exchange-of-information-fifteen-minutes
;; Exchange of Information - Swapping a 15 Minutes still keeps the ability. #1783
(do-game
(new-game (default-corp [(qty "Exchange of Information" 2) (qty "15 Minutes" 1)
(qty "Project Beale" 1)])
(default-runner))
(score-agenda state :corp (find-card "15 Minutes" (:hand (get-corp))))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(take-credits state :runner)
(is (= 1 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "15 Minutes" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 1 (:agenda-point (get-runner))))
(is (= 0 (count (:deck (get-corp)))))
;; shuffle back into R&D from runner's scored area
(let [fifm (get-in @state [:runner :scored 0])]
(card-ability state :corp fifm 0))
(is (= 2 (:agenda-point (get-corp))))
(is (= 0 (:agenda-point (get-runner))))
(is (= "15 Minutes" (:title (first (:deck (get-corp))))))
(take-credits state :corp)
(core/steal state :runner (find-card "15 Minutes" (:deck (get-corp))))
(take-credits state :runner)
(is (= 2 (:agenda-point (get-corp))))
(is (= 1 (:agenda-point (get-runner))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "15 Minutes" (:scored (get-runner))))
(prompt-select :corp (find-card "Project Beale" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
;; shuffle back into R&D from corp's scored area
(let [fifm (get-in @state [:corp :scored 0])]
(card-ability state :corp fifm 0))
(is (= "15 Minutes" (:title (first (:deck (get-corp))))))))
(deftest exchange-of-information-mandatory-upgrades
;; Exchange of Information - Swapping a Mandatory Upgrades gives the Corp an additional click per turn. #1687
(do-game
(new-game (default-corp [(qty "Exchange of Information" 2) (qty "Mandatory Upgrades" 1)
(qty "Global Food Initiative" 1)])
(default-runner))
(score-agenda state :corp (find-card "Global Food Initiative" (:hand (get-corp))))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(core/steal state :runner (find-card "Mandatory Upgrades" (:hand (get-corp))))
(take-credits state :runner)
(is (= 3 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 3 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Mandatory Upgrades" (:scored (get-runner))))
(prompt-select :corp (find-card "Global Food Initiative" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 3 (:click (get-corp))))
(is (= 4 (:click-per-turn (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(is (= 4 (:click (get-corp))))
(is (= 4 (:click-per-turn (get-corp))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Global Food Initiative" (:scored (get-runner))))
(prompt-select :corp (find-card "Mandatory Upgrades" (:scored (get-corp))))
(is (= 3 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 2 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(is (= 3 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))))
(deftest election-day
(do-game
(new-game (default-corp [(qty "Election Day" 7)])
(default-runner))
(is (= 6 (count (:hand (get-corp)))) "Corp starts with 5 + 1 cards")
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(play-from-hand state :corp "Election Day")
(is (= 1 (count (:hand (get-corp)))) "Could not play Election Day")
(take-credits state :corp)
(take-credits state :runner)
(is (= 2 (count (:hand (get-corp)))) "Corp has now 1 + 1 cards before Election Day")
(play-from-hand state :corp "Election Day")
(is (= 5 (count (:hand (get-corp)))) "Corp has now 5 cards due to Election Day")))
(deftest hedge-fund
(do-game
(new-game (default-corp) (default-runner))
(is (= 5 (:credit (get-corp))))
(play-from-hand state :corp "Hedge Fund")
(is (= 9 (:credit (get-corp))))))
(deftest housekeeping
;; Housekeeping - Runner must trash a card from Grip on first install of a turn
(do-game
(new-game (default-corp [(qty "Housekeeping" 1)])
(default-runner [(qty "Cache" 2) (qty "Fall Guy" 1) (qty "Mr. Li" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Fall Guy")
(take-credits state :runner)
(play-from-hand state :corp "Housekeeping")
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(prompt-select :runner (find-card "Mr. Li" (:hand (get-runner))))
(is (empty? (:prompt (get-runner))) "Fall Guy prevention didn't trigger")
(is (= 1 (count (:discard (get-runner)))) "Card trashed")
(play-from-hand state :runner "Cache")
(is (empty? (:prompt (get-runner))) "Housekeeping didn't trigger on 2nd install")))
(deftest invasion-of-privacy
;; Invasion of Privacy - Full test
(do-game
(new-game (default-corp [(qty "Invasion of Privacy" 3)])
(default-runner [(qty "Sure Gamble" 2) (qty "Fall Guy" 1) (qty "Cache" 2)]))
(core/gain state :corp :click 3 :credit 6)
;; trash 2 cards
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 5 (count (:hand (get-runner)))))
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" "Sure Gamble" nil) (prompt-names)))
(prompt-choice :corp (find-card "Sure Gamble" (:hand (get-runner))))
(prompt-choice :corp (find-card "Sure Gamble" (:hand (get-runner)))))
(is (= 3 (count (:hand (get-runner)))))
;; able to trash 2 cards but only 1 available target in Runner's hand
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 3 (count (:hand (get-runner)))))
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" nil) (prompt-names)))
(prompt-choice :corp (find-card "Fall Guy" (:hand (get-runner))))
(is (empty? (get-in @state [:corp :prompt])) "No prompt for second card"))
(is (= 2 (count (:hand (get-runner)))))
;; failed trace - take the bad publicity
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 2) ; Runner matches
(is (= 1 (:bad-publicity (get-corp))))))
(deftest lateral-growth
(do-game
(new-game (default-corp [(qty "Lateral Growth" 1) (qty "Breaking News" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(play-from-hand state :corp "Lateral Growth")
(prompt-select :corp (find-card "Breaking News" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(is (= "Breaking News" (:title (get-content state :remote1 0)))
"Breaking News installed by Lateral Growth")
(is (= 7 (:credit (get-corp))))))
(deftest manhunt-every-run
;; Manhunt - only fires once per turn. Unreported issue.
(do-game
(new-game (default-corp [(qty "Manhunt" 1) (qty "Hedge Fund" 3)])
(default-runner))
(play-from-hand state :corp "Manhunt")
(take-credits state :corp)
(run-empty-server state "HQ")
(is (:prompt (get-corp)) "Manhunt trace initiated")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag")
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")
(run-empty-server state "HQ")
(is (empty? (:prompt (get-corp))) "No Manhunt trace on second run")
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")))
(deftest midseason-replacements
;; Midseason Replacements - Trace to give Runner tags after they steal an agenda
(do-game
(new-game (default-corp [(qty "Midseason Replacements" 1) (qty "Breaking News" 1)])
(default-runner))
(play-from-hand state :corp "Midseason Replacements")
(is (= 3 (:click (get-corp))) "Midseason precondition not met; Corp not charged a click")
(play-from-hand state :corp "Breaking News" "New remote")
(take-credits state :corp)
(is (= 7 (:credit (get-corp))))
(let [bn (get-content state :remote1 0)]
(run-empty-server state "Server 1")
(prompt-choice :runner "Steal")
(is (= 1 (:agenda-point (get-runner))) "Stole Breaking News")
(take-credits state :runner)
(play-from-hand state :corp "Midseason Replacements")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 6 (:tag (get-runner))) "Runner took 6 tags"))))
(deftest mushin-no-shin
;; PI:NAME:<NAME>END_PI - Add 3 advancements to a card; prevent rez/score of that card the rest of the turn
(do-game
(new-game (default-corp [(qty "Mushin No Shin" 2) (qty "Ronin" 1) (qty "Profiteering" 1)])
(default-runner))
(play-from-hand state :corp "PI:NAME:<NAME>END_PI")
(prompt-select :corp (find-card "PI:NAME:<NAME>END_PI" (:hand (get-corp))))
(let [ronin (get-content state :remote1 0)]
(is (= 3 (:advance-counter (refresh ronin))) "3 advancements placed on Ronin")
(core/rez state :corp (refresh ronin))
(is (not (get-in (refresh ronin) [:rezzed])) "RonPI:NAME:<NAME>END_PI did not rez")
(take-credits state :corp)
(take-credits state :runner)
(core/rez state :corp (refresh ronin))
(is (get-in (refresh ronin) [:rezzed]) "Ronin now rezzed")
(play-from-hand state :corp "PI:NAME:<NAME>END_PI")
(prompt-select :corp (find-card "Profiteering" (:hand (get-corp))))
(let [prof (get-content state :remote2 0)]
(core/score state :corp (refresh prof))
(is (empty? (:scored (get-corp))) "Profiteering not scored")
(is (= 0 (:agenda-point (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(core/score state :corp (refresh prof))
(prompt-choice :corp "0")
(is (= 1 (:agenda-point (get-corp))) "Profiteering was able to be scored")))))
(deftest neural-emp
;; Neural EMP - Play if Runner made a run the previous turn to do 1 net damage
(do-game
(new-game (default-corp [(qty "Neural EMP" 1)])
(default-runner))
(play-from-hand state :corp "Neural EMP")
(is (= 3 (:click (get-corp))) "Neural precondition not met; card not played")
(take-credits state :corp)
(run-empty-server state "Archives")
(take-credits state :runner)
(play-from-hand state :corp "Neural EMP")
(is (= 1 (count (:discard (get-runner)))) "Runner took 1 net damage")))
(deftest oversight-ai
;; Oversight AI - Rez a piece of ICE ignoring all costs
(do-game
(new-game (default-corp [(qty "Oversight AI" 1) (qty "Archer" 1)])
(default-runner))
(play-from-hand state :corp "Archer" "R&D")
(let [archer (get-ice state :rd 0)]
(play-from-hand state :corp "Oversight AI")
(prompt-select :corp archer)
(is (get-in (refresh archer) [:rezzed]))
(is (= 4 (:credit (get-corp))) "Archer rezzed at no credit cost")
(is (= "Oversight AI" (:title (first (:hosted (refresh archer)))))
"Archer hosting OAI as a condition"))))
(deftest patch
;; Patch - +2 current strength
(do-game
(new-game (default-corp [(qty "Patch" 1) (qty "Vanilla" 1)])
(default-runner))
(play-from-hand state :corp "Vanilla" "HQ")
(core/rez state :corp (get-ice state :hq 0))
(play-from-hand state :corp "Patch")
(prompt-select :corp (get-ice state :hq 0))
(is (= 2 (:current-strength (get-ice state :hq 0))) "Vanilla at 2 strength")))
(deftest paywall-implementation
;; Paywall Implementation - Gain 1 credit for every successful run
(do-game
(new-game (default-corp [(qty "Paywall Implementation" 1)])
(default-runner))
(play-from-hand state :corp "Paywall Implementation")
(is (= "Paywall Implementation" (:title (first (get-in @state [:corp :current]))))
"Paywall active in Current area")
(take-credits state :corp)
(is (= 7 (:credit (get-corp))))
(run-empty-server state "Archives")
(is (= 8 (:credit (get-corp))) "Gained 1 credit from successful run")
(run-empty-server state "Archives")
(is (= 9 (:credit (get-corp))) "Gained 1 credit from successful run")))
(deftest peak-efficiency
;; Peak Efficiency - Gain 1 credit for each rezzed ICE
(do-game
(new-game (default-corp [(qty "Peak Efficiency" 1) (qty "Paper Wall" 3) (qty "Wraparound" 1)])
(default-runner))
(core/gain state :corp :click 3)
(play-from-hand state :corp "Paper Wall" "HQ")
(play-from-hand state :corp "Paper Wall" "R&D")
(play-from-hand state :corp "Paper Wall" "New remote")
(play-from-hand state :corp "Wraparound" "New remote")
(core/rez state :corp (get-ice state :hq 0))
(core/rez state :corp (get-ice state :rd 0))
(core/rez state :corp (get-ice state :remote1 0))
(play-from-hand state :corp "Peak Efficiency")
(is (= 7 (:credit (get-corp))) "Gained 3 credits for 3 rezzed ICE; unrezzed ICE ignored")))
(deftest power-shutdown
;; Power Shutdown - Trash cards from R&D to force Runner to trash a program or hardware
(do-game
(new-game (default-corp [(qty "Power Shutdown" 3) (qty "Hive" 3)])
(default-runner [(qty "Grimoire" 1) (qty "Cache" 1)]))
(play-from-hand state :corp "Power Shutdown")
(is (empty? (:discard (get-corp))) "Not played, no run last turn")
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(play-from-hand state :runner "Grimoire")
(run-empty-server state :archives)
(take-credits state :runner)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(play-from-hand state :corp "Power Shutdown")
(prompt-choice :corp 2)
(is (= 3 (count (:discard (get-corp)))) "2 cards trashed from R&D")
(is (= 1 (count (:deck (get-corp)))) "1 card remaining in R&D")
(prompt-select :runner (get-in @state [:runner :rig :hardware 0])) ; try targeting Grimoire
(is (empty? (:discard (get-runner))) "Grimoire too expensive to be targeted")
(prompt-select :runner (get-in @state [:runner :rig :program 0]))
(is (= 1 (count (:discard (get-runner)))) "Cache trashed")))
(deftest precognition
;; Precognition - Full test
(do-game
(new-game (default-corp [(qty "Precognition" 1) (qty "PI:NAME:<NAME>END_PIrice NPI:NAME:<NAME>END_PIi" 1) (qty "Adonis Campaign" 1)
(qty "Quandary" 1) (qty "PI:NAME:<NAME>END_PI" 1) (qty "Global Food Initiative" 1)])
(default-runner))
(starting-hand state :corp ["Precognition"])
(play-from-hand state :corp "Precognition")
(prompt-choice :corp (find-card "PI:NAME:<NAME>END_PI" (:deck (get-corp))))
(prompt-choice :corp (find-card "Adonis Campaign" (:deck (get-corp))))
(prompt-choice :corp (find-card "Quandary" (:deck (get-corp))))
(prompt-choice :corp (find-card "PI:NAME:<NAME>END_PI" (:deck (get-corp))))
(prompt-choice :corp (find-card "Global Food Initiative" (:deck (get-corp))))
;; try starting over
(prompt-choice :corp "Start over")
(prompt-choice :corp (find-card "Global Food Initiative" (:deck (get-corp))))
(prompt-choice :corp (find-card "PI:NAME:<NAME>END_PI" (:deck (get-corp))))
(prompt-choice :corp (find-card "PI:NAME:<NAME>END_PI" (:deck (get-corp))))
(prompt-choice :corp (find-card "Adonis Campaign" (:deck (get-corp))))
(prompt-choice :corp (find-card "PI:NAME:<NAME>END_PI" (:deck (get-corp)))) ;this is the top card of R&D
(prompt-choice :corp "Done")
(is (= "PI:NAME:<NAME>END_PI" (:title (first (:deck (get-corp))))))
(is (= "Adonis Campaign" (:title (second (:deck (get-corp))))))
(is (= "PI:NAME:<NAME>END_PI" (:title (second (rest (:deck (get-corp)))))))
(is (= "PI:NAME:<NAME>END_PI" (:title (second (rest (rest (:deck (get-corp))))))))
(is (= "Global Food Initiative" (:title (second (rest (rest (rest (:deck (get-corp)))))))))))
(deftest preemptive-action
;; Preemptive Action - Shuffles cards into R&D and removes itself from game
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 3)
(qty "Preemptive Action" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Preemptive Action")
(prompt-select :corp (first (:discard (get-corp))))
(prompt-select :corp (second (:discard (get-corp))))
(prompt-select :corp (last (:discard (get-corp))))
(is (= 0 (count (:discard (get-corp)))))
(is (= 1 (count (:rfg (get-corp)))))))
(deftest psychographics
;; Psychographics - Place advancements up to the number of Runner tags on a card
(do-game
(new-game (default-corp [(qty "Psychographics" 1) (qty "Project Junebug" 1)])
(default-runner))
(core/gain state :runner :tag 4)
(play-from-hand state :corp "Project Junebug" "New remote")
(let [pj (get-content state :remote1 0)]
(play-from-hand state :corp "Psychographics")
(prompt-choice :corp 4)
(prompt-select :corp pj)
(is (= 1 (:credit (get-corp))) "Spent 4 credits")
(is (= 4 (:advance-counter (refresh pj))) "Junebug has 4 advancements"))))
(deftest punitive-counterstrike
;; Punitive Counterstrike - deal meat damage equal to printed agenda points
(do-game
(new-game (default-corp [(qty "Global Food Initiative" 1) (qty "Punitive Counterstrike" 1)])
(default-runner))
(play-from-hand state :corp "Global Food Initiative" "New remote")
(take-credits state :corp)
(run-empty-server state :remote1)
(prompt-choice :runner "Steal")
(is (= 2 (:agenda-point (get-runner))) "Runner scored 2 points")
(take-credits state :runner)
(play-from-hand state :corp "Punitive Counterstrike")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (empty? (:hand (get-runner))) "Runner took 3 meat damage")))
(deftest reuse
;; Reuse - Gain 2 credits for each card trashed from HQ
(do-game
(new-game (default-corp [(qty "Reuse" 2) (qty "Hive" 1) (qty "IQ" 1)
(qty "Ice Wall" 1)])
(default-runner))
(play-from-hand state :corp "Reuse")
(prompt-select :corp (find-card "Ice Wall" (:hand (get-corp))))
(prompt-select :corp (find-card "Hive" (:hand (get-corp))))
(prompt-select :corp (find-card "IQ" (:hand (get-corp))))
(prompt-choice :corp "Done")
(is (= 4 (count (:discard (get-corp)))) "3 cards trashed plus operation played")
(is (= 11 (:credit (get-corp))) "Gained 6 credits")
(is (= 1 (:click (get-corp))) "Spent 2 clicks")))
(deftest salems-hospitality
;; Salem's Hospitality - Full test
(do-game
(new-game (default-corp [(qty "Salem's Hospitality" 3)])
(default-runner [(qty "I've Had Worse" 3) (qty "Faust" 1)
(qty "Levy AR Lab Access" 1)]))
(play-from-hand state :corp "Salem's Hospitality")
(is (= 5 (count (:hand (get-runner)))))
(prompt-choice :corp "I've Had Worse")
(is (= 2 (count (:hand (get-runner)))))
(play-from-hand state :corp "Salem's Hospitality")
(prompt-choice :corp "Plascrete Carapace")
(is (= 2 (count (:hand (get-runner)))))))
(deftest scorched-earth
;; Scorched Earth - burn 'em
(do-game
(new-game (default-corp [(qty "Scorched Earth" 1)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Scorched Earth")
(is (= 1 (count (:hand (get-runner)))) "Runner has 1 card in hand")))
(deftest scorched-earth-no-tag
;; Scorched Earth - not tagged
(do-game
(new-game (default-corp [(qty "Scorched Earth" 1)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(play-from-hand state :corp "Scorched Earth")
(is (= 3 (:click (get-corp))) "Corp not charged a click")
(is (= 5 (count (:hand (get-runner)))) "Runner did not take damage")))
(deftest scorched-earth-flatline
;; Scorched Earth - murderize 'em
(do-game
(new-game (default-corp [(qty "Scorched Earth" 1)])
(default-runner))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Scorched Earth")
(is (= 0 (count (:hand (get-runner)))) "Runner has 0 cards in hand")
(is (= :corp (:winner @state)) "Corp wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline")))
(deftest subcontract-scorched
;; Subcontract - Don't allow second operation until damage prevention completes
(do-game
(new-game (default-corp [(qty "Scorched Earth" 2) (qty "Subcontract" 1)])
(default-runner [(qty "Plascrete Carapace" 1)]))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(play-from-hand state :runner "Plascrete Carapace")
(take-credits state :runner)
(play-from-hand state :corp "Subcontract")
(prompt-select :corp (find-card "Scorched Earth" (:hand (get-corp))))
(is (and (= 1 (count (:prompt (get-corp)))) (= :waiting (-> (get-corp) :prompt first :prompt-type)))
"Corp does not have Subcontract prompt until damage prevention completes")
(prompt-choice :runner "Done")
(is (not-empty (:prompt (get-corp))) "Corp can now play second Subcontract operation")))
(deftest subcontract-terminal
;; Subcontract - interaction with Terminal operations
(do-game
(new-game
(default-corp [(qty "Hard-Hitting News" 2) (qty "Subcontract" 1)])
(default-runner))
(core/gain state :runner :tag 1)
(take-credits state :corp)
(run-empty-server state :archives)
(take-credits state :runner)
(play-from-hand state :corp "Subcontract")
(prompt-select :corp (find-card "Hard-Hitting News" (:hand (get-corp))))
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 5 (:tag (get-runner))) "Runner has 5 tags")
(is (empty? (:prompt (get-corp))) "Corp does not have a second Subcontract selection prompt")))
(deftest service-outage
;; Service Outage - First click run each turn costs a credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Employee Strike" 1)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(is (= 5 (:credit (get-runner))) "Runner has 5 credits")
(run-on state :archives)
(is (= 4 (:credit (get-runner)))
"Runner spends 1 credit to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 4 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make the second run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 6)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 2)
(play-from-hand state :runner "Employee Strike")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")))
(deftest service-outage-card-ability
;; Service Outage - First card ability run each turn costs an additional credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(take-credits state :runner 1)
(is (= 2 (:credit (get-runner))) "Runner has 2 credits")
(let [sneakdoor (get-in @state [:runner :rig :program 0])]
(card-ability state :runner sneakdoor 0)
(is (= 1 (:credit (get-runner)))
"Runner spends 1 additional credit to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 1)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(card-ability state :runner sneakdoor 0)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits"))))
(deftest service-outage-run-events
;; Service Outage - First run event each turn costs an additional credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Out of the Ashes" 2)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(is (= 5 (:credit (get-runner))) "Runner has 5 credits")
(play-from-hand state :runner "Out of the Ashes")
(is (= 3 (:credit (get-runner)))
"Runner spends 1 additional credit to run with a run event")
(prompt-choice :runner "Archives")
(run-successful state)
(run-on state :archives)
(is (= 3 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(prompt-choice :runner "No") ; Out of the Ashes prompt
(core/lose state :runner :credit 4)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(play-from-hand state :runner "Out of the Ashes")
(is (empty? (get-in @state [:runner :prompt]))
"Out of the Ashes was not played")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")))
(deftest service-outage-runner-turn-first-run
;; Service Outage - Works when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News" [(qty "Service Outage" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(core/gain state :runner :credit 3)
(play-from-hand state :runner "PI:NAME:<NAME>END_PI")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Service Outage" (:hand (get-corp))))
(is (find-card "Service Outage" (:current (get-corp)))
"Service Outage is in play")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 0 (:credit (get-runner)))
"Runner spends 1 additional credit to make a run")))
(deftest service-outage-runner-turn-second-run
;; Service Outage - Doesn't fire if already run when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News" [(qty "Service Outage" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(run-on state :hq)
(run-successful state)
(prompt-choice :runner "OK")
(core/gain state :runner :credit 3)
(play-from-hand state :runner "PI:NAME:<NAME>END_PI")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Service Outage" (:hand (get-corp))))
(is (find-card "Service Outage" (:current (get-corp)))
"Service Outage is in play")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 additional credit to make a run")))
(deftest shipment-from-sansan
;; Shipment from SanSan - placing advancements
(do-game
(new-game (default-corp [(qty "Shipment from SanSan" 3) (qty "Ice Wall" 3)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(let [iwall (get-ice state :hq 0)]
(play-from-hand state :corp "Shipment from SanSan")
(prompt-choice :corp "2")
(prompt-select :corp iwall)
(is (= 5 (:credit (get-corp))))
(is (= 2 (:advance-counter (refresh iwall)))))))
(deftest stock-buy-back
;; Stock Buy-Back - Gain 3c for every agenda in Runner's area
(do-game
(new-game (default-corp [(qty "Hostile Takeover" 2) (qty "Stock Buy-Back" 3)])
(default-runner))
(play-from-hand state :corp "Hostile Takeover" "New remote")
(play-from-hand state :corp "Hostile Takeover" "New remote")
(take-credits state :corp)
(run-empty-server state "Server 1")
(prompt-choice :runner "Steal")
(run-empty-server state "Server 2")
(prompt-choice :runner "Steal")
(take-credits state :runner)
(is (= 2 (count (:scored (get-runner)))))
(play-from-hand state :corp "Stock Buy-Back")
(is (= 11 (:credit (get-corp))))))
(deftest sub-boost
;; Sub Boost - Give ice barrier
(do-game
(new-game (default-corp [(qty "Sub Boost" 1) (qty "Quandary" 1)])
(default-runner))
(play-from-hand state :corp "Quandary" "HQ")
(play-from-hand state :corp "Sub Boost")
(let [qu (get-ice state :hq 0)]
(core/rez state :corp qu)
(prompt-select :corp qu)
(is (core/has-subtype? (refresh qu) "Code Gate") "Quandary has code gate")
(is (core/has-subtype? (refresh qu) "Barrier") "Quandary has barrier"))))
(deftest subliminal-messaging
;; Subliminal Messaging - Playing/trashing/milling will all prompt returning to hand
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 3)])
(make-deck "Noise: Hacker Extraordinaire" [(qty "Cache" 3) (qty "Utopia Shard" 1)]))
(play-from-hand state :corp "Subliminal Messaging")
(is (= 6 (:credit (get-corp))))
(is (= 3 (:click (get-corp))) "First Subliminal Messaging gains 1 click")
(play-from-hand state :corp "Subliminal Messaging")
(is (= 7 (:credit (get-corp))))
(is (= 2 (:click (get-corp))) "Second Subliminal Messaging does not gain 1 click")
(trash-from-hand state :corp "Subliminal Messaging")
(is (= 0 (count (:hand (get-corp)))))
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 3 (count (:hand (get-corp)))) "All 3 Subliminals returned to HQ")
(core/move state :corp (find-card "Subliminal Messaging" (:hand (get-corp))) :deck)
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(play-from-hand state :runner "Utopia Shard")
(let [utopia (get-in @state [:runner :rig :resource 0])]
(card-ability state :runner utopia 0))
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 3 (count (:hand (get-corp)))) "All 3 Subliminals returned to HQ")
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(is (empty? (get-in @state [:corp :prompt])) "No prompt here because runner made a run last turn")
(take-credits state :corp)
(is (= 2 (count (:hand (get-corp)))))
(is (= 1 (count (:discard (get-corp)))) "1 Subliminal not returned because runner made a run last turn")))
(deftest subliminal-messaging-archived
;; Subliminal Messaging - Scenario involving Subliminal being added to HQ with Archived Memories
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2) (qty "Archived Memories" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Archived Memories")
(prompt-select :corp (find-card "Subliminal Messaging" (:discard (get-corp))))
(is (= 2 (count (:discard (get-corp)))))
(is (= 1 (count (:hand (get-corp)))))
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "No")
(is (empty? (get-in @state [:corp :prompt])) "Only 1 Subliminal prompt")
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (empty? (get-in @state [:corp :prompt]))
"Only 2 Subliminal prompts - there will be a third if flag not cleared")))
(deftest subliminal-messaging-jackson
;; Subliminal Messaging - Scenario involving Subliminal being reshuffled into R&D with PI:NAME:<NAME>END_PIson
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 1) (qty "PI:NAME:<NAME>END_PI" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "PI:NAME:<NAME>END_PI" "New remote")
(take-credits state :corp)
(let [jhow (get-content state :remote1 0)]
(core/rez state :corp jhow)
(card-ability state :corp jhow 1)
(prompt-select :corp (find-card "Subliminal Messaging" (:discard (get-corp))))
(prompt-choice :corp "Done")
(is (= 0 (count (:discard (get-corp)))))
(is (= 1 (count (:rfg (get-corp))))))
(take-credits state :runner)
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(is (= 1 (count (:hand (get-corp)))) "Subliminal returned to HQ")
(is (empty? (get-in @state [:corp :prompt]))
"Subliminal prompt cleared - there will be a second prompt if flag not cleared")))
(deftest subliminal-messaging-made-run
;; Subliminal Messaging - Runner made run, ensure game asks again next turn
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(trash-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(is (empty? (get-in @state [:corp :prompt])) "No prompt here because runner made a run last turn")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 2 (count (:hand (get-corp)))) "Both Subliminals returned to HQ")
(is (= 0 (count (:discard (get-corp)))) "No Subliminals in Archives")))
(deftest subliminal-messaging-no
;; Subliminal Messaging - User declines to return to hand, ensure game asks again next turn
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(trash-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "No")
(prompt-choice :corp "No")
(is (= 0 (count (:hand (get-corp)))) "Neither Subliminal returned to HQ")
(is (= 2 (count (:discard (get-corp)))) "Both Subliminals in Archives")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 2 (count (:hand (get-corp)))) "Both Subliminals returned to HQ")
(is (= 0 (count (:discard (get-corp)))) "No Subliminals in Archives")))
(deftest successful-demonstration
;; Successful Demonstration - Play if only Runner made unsuccessful run last turn; gain 7 credits
(do-game
(new-game (default-corp [(qty "Successful Demonstration" 1)])
(default-runner))
(play-from-hand state :corp "Successful Demonstration")
(is (and (= 3 (:click (get-corp)))
(= 5 (:credit (get-runner))))
"Successful Demonstration precondition not met; card not played")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(play-from-hand state :corp "Successful Demonstration")
(is (= 13 (:credit (get-corp))) "Paid 2 to play event; gained 7 credits")))
(deftest wetwork-refit
;; Wetwork Refit - Only works on bioroid ice and adds a subroutine
(do-game
(new-game (default-corp [(qty "Eli 1.0" 1)
(qty "Vanilla" 1)
(qty "Wetwork Refit" 3)])
(default-runner))
(play-from-hand state :corp "Eli 1.0" "R&D")
(play-from-hand state :corp "Vanilla" "HQ")
(let [eli (get-ice state :rd 0)
vanilla (get-ice state :hq 0)]
(play-from-hand state :corp "Wetwork Refit")
(is (not-any? #{"Eli 1.0"} (get-in @state [:runner :prompt :choices]))
"Unrezzed Eli 1.0 is not a choice to host Wetwork Refit")
(prompt-choice :corp "Done")
(take-credits state :corp)
(take-credits state :runner)
(core/rez state :corp (refresh eli))
(core/rez state :corp (refresh vanilla))
(play-from-hand state :corp "Wetwork Refit")
(prompt-select :corp (refresh eli))
(is (= "Wetwork Refit" (:title (first (:hosted (refresh eli)))))
"Wetwork Refit is hosted on Eli 1.0")
(is (= 2 (count (:subroutines (refresh eli))))
"Eli 1.0 has 2 different subroutines")
(is (= "Do 1 brain damage" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has a brain damage subroutine as his first subroutine")
(core/move state :corp (first (:hosted (refresh eli))) :hand)
(is (empty? (:hosted (refresh eli))) "No cards are hosted on Eli 1.0")
(is (= 1 (count (:subroutines (refresh eli))))
"Eli 1.0 has 1 different subroutine")
(is (= "End the run" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has an end the run subroutine as his first subroutine")
(play-from-hand state :corp "Wetwork Refit")
(prompt-select :corp (refresh vanilla))
(is (not= "Wetwork Refit" (:title (first (:hosted (refresh vanilla)))))
"Wetwork Refit is not hosted on Vanilla"))))
|
[
{
"context": "tc/from-long millis))))\n\n(def test-record\n {:id \"abc123\" :timestamp 1440511397267 :ts \"2015-08-25T14:03:1",
"end": 340,
"score": 0.8152428269386292,
"start": 334,
"tag": "KEY",
"value": "abc123"
},
{
"context": "\"\n :type \"a-type\"\n :id \"abc123\"\n :source test-record}\n\n\n ;; with",
"end": 5601,
"score": 0.7475571036338806,
"start": 5595,
"tag": "PASSWORD",
"value": "abc123"
},
{
"context": "\"\n :type \"a-type\"\n :id \"abc123\"\n :source test-record}\n\n\n ;; with",
"end": 6132,
"score": 0.7641189098358154,
"start": 6126,
"tag": "PASSWORD",
"value": "abc123"
}
] | qanal/test/qanal/transform_test.clj | samsara/samsara | 146 | (ns qanal.transform-test
(:require [clj-time
[coerce :as tc]
[format :as f]]
[midje.sweet :refer :all]
[qanal.transform :refer :all]))
(defn format-date [base-index millis]
(str base-index (f/unparse (f/formatter "-YYYY-MM-dd") (tc/from-long millis))))
(def test-record
{:id "abc123" :timestamp 1440511397267 :ts "2015-08-25T14:03:17.267Z"
:eventName "test-event" :sourceId "device1"})
(facts "about `timestamp-extractor`: configured as :system"
;;
;; when configured to use :system time it should return the current time
;;
(let [ts ((timestamp-extractor :system nil) {:timestamp 1})]
(<= 0 (- (System/currentTimeMillis) ts) 100)) => true
)
(facts "about `timestamp-extractor`: configured as field extraction in :millis"
;;
;; when configured to use a field it should extract its value is millis
;;
((timestamp-extractor "timestamp" :millis) {:timestamp 1}) => 1
((timestamp-extractor :timestamp :millis) {:timestamp 100}) => 100
((timestamp-extractor :no-field :millis) {:timestamp 100}) => nil
)
(facts "about `timestamp-extractor`: configured as field extraction in :iso-8601 date"
;;
;; when configured to use a field it should extract its value is millis
;;
((timestamp-extractor "timestamp" :iso-8601)
{:timestamp "2015-08-25T14:03:17.267-00:00"}) => 1440511397267
((timestamp-extractor "timestamp" :iso-8601)
{:timestamp "2015-08-25T14:03:17.267Z"}) => 1440511397267
((timestamp-extractor :timestamp :iso-8601)
{:timestamp "2015-08-25"}) => (throws Exception)
((timestamp-extractor :no-field :iso-8601)
{:timestamp "2015-08-25T14:03:17.267-00:00"}) => (throws Exception)
)
(facts "about `timestamp-extractor`: configured as field extraction in custom formatted date"
;;
;; when configured to use a field it should extract its value is millis
;;
((timestamp-extractor "timestamp" "YYYY-MM-dd")
{:timestamp "2015-08-25"}) => 1440460800000
((timestamp-extractor "timestamp" "YYYY/MM/dd")
{:timestamp "2015/08/25"}) => 1440460800000
((timestamp-extractor "timestamp" "YYYY/MM/dd")
{:timestamp "2015-08-25"}) => (throws Exception)
)
(facts "about `topic-transformer`: river format is a no-op"
;;
;; All transformer should eventually converge to the river format
;; if it is a river then it is a no-op
;;
((topic-transformer
{:type :river :topic "test" :partitions :all})
{:index "a-index" :type "a-type" :id "abc123"
:source test-record})
=> {:index "a-index" :type "a-type" :id "abc123"
:source test-record}
)
(facts "about `topic-transformer`: plain format with simple index"
;;
;; All transformer should eventually converge to the river format
;; if the input format is a :plain non decorated record
;; then it needs to be wrapped in the river format
;;
;; with id field
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :simple :index "a-index" :doc-type "a-type"
:id-field "id"}})
test-record)
=> {:index "a-index" :type "a-type" :id "abc123"
:source test-record}
;; without id field
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :simple :index "a-index" :doc-type "a-type"}})
test-record)
=> {:index "a-index" :type "a-type"
:source test-record}
)
(facts "about `topic-transformer`: plain format with :daily index"
;;
;; All transformer should eventually converge to the river format
;; if the input format is a :plain non decorated record
;; then it needs to be wrapped in the river format
;; When using daily indexes then the index name must be built
;; with the given date
;;
;; with id field and system timestamp
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field :system :timestamp-field-format :millis
:id-field "id"}})
test-record)
=> {:index (format-date "a-index" (System/currentTimeMillis))
:type "a-type"
:id "abc123"
:source test-record}
;; with id field and system field timestamp in millis
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field "timestamp" :timestamp-field-format :millis
:id-field "id"}})
test-record)
=> {:index "a-index-2015-08-25"
:type "a-type"
:id "abc123"
:source test-record}
;; with id field and system field timestamp in millis
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field "ts" :timestamp-field-format :iso-8601
:id-field "id"}})
test-record)
=> {:index "a-index-2015-08-25"
:type "a-type"
:id "abc123"
:source test-record}
;; with id field and system field timestamp in millis
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field "ts"
:timestamp-field-format "yyyy-MM-dd'T'HH:mm:ss.SSSZZ"
:id-field "id"}})
test-record)
=> {:index "a-index-2015-08-25"
:type "a-type"
:id "abc123"
:source test-record}
;; with-out id field and system field timestamp in millis
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field "ts"
:timestamp-field-format "yyyy-MM-dd'T'HH:mm:ss.SSSZZ"}})
test-record)
=> {:index "a-index-2015-08-25"
:type "a-type"
:source test-record}
;; with id field which isn't present and system field timestamp in millis
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field "ts"
:timestamp-field-format "yyyy-MM-dd'T'HH:mm:ss.SSSZZ"
:id-field "NOT_PRESENT"}})
test-record)
=> {:index "a-index-2015-08-25"
:type "a-type"
:id nil
:source test-record}
)
| 24727 | (ns qanal.transform-test
(:require [clj-time
[coerce :as tc]
[format :as f]]
[midje.sweet :refer :all]
[qanal.transform :refer :all]))
(defn format-date [base-index millis]
(str base-index (f/unparse (f/formatter "-YYYY-MM-dd") (tc/from-long millis))))
(def test-record
{:id "<KEY>" :timestamp 1440511397267 :ts "2015-08-25T14:03:17.267Z"
:eventName "test-event" :sourceId "device1"})
(facts "about `timestamp-extractor`: configured as :system"
;;
;; when configured to use :system time it should return the current time
;;
(let [ts ((timestamp-extractor :system nil) {:timestamp 1})]
(<= 0 (- (System/currentTimeMillis) ts) 100)) => true
)
(facts "about `timestamp-extractor`: configured as field extraction in :millis"
;;
;; when configured to use a field it should extract its value is millis
;;
((timestamp-extractor "timestamp" :millis) {:timestamp 1}) => 1
((timestamp-extractor :timestamp :millis) {:timestamp 100}) => 100
((timestamp-extractor :no-field :millis) {:timestamp 100}) => nil
)
(facts "about `timestamp-extractor`: configured as field extraction in :iso-8601 date"
;;
;; when configured to use a field it should extract its value is millis
;;
((timestamp-extractor "timestamp" :iso-8601)
{:timestamp "2015-08-25T14:03:17.267-00:00"}) => 1440511397267
((timestamp-extractor "timestamp" :iso-8601)
{:timestamp "2015-08-25T14:03:17.267Z"}) => 1440511397267
((timestamp-extractor :timestamp :iso-8601)
{:timestamp "2015-08-25"}) => (throws Exception)
((timestamp-extractor :no-field :iso-8601)
{:timestamp "2015-08-25T14:03:17.267-00:00"}) => (throws Exception)
)
(facts "about `timestamp-extractor`: configured as field extraction in custom formatted date"
;;
;; when configured to use a field it should extract its value is millis
;;
((timestamp-extractor "timestamp" "YYYY-MM-dd")
{:timestamp "2015-08-25"}) => 1440460800000
((timestamp-extractor "timestamp" "YYYY/MM/dd")
{:timestamp "2015/08/25"}) => 1440460800000
((timestamp-extractor "timestamp" "YYYY/MM/dd")
{:timestamp "2015-08-25"}) => (throws Exception)
)
(facts "about `topic-transformer`: river format is a no-op"
;;
;; All transformer should eventually converge to the river format
;; if it is a river then it is a no-op
;;
((topic-transformer
{:type :river :topic "test" :partitions :all})
{:index "a-index" :type "a-type" :id "abc123"
:source test-record})
=> {:index "a-index" :type "a-type" :id "abc123"
:source test-record}
)
(facts "about `topic-transformer`: plain format with simple index"
;;
;; All transformer should eventually converge to the river format
;; if the input format is a :plain non decorated record
;; then it needs to be wrapped in the river format
;;
;; with id field
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :simple :index "a-index" :doc-type "a-type"
:id-field "id"}})
test-record)
=> {:index "a-index" :type "a-type" :id "abc123"
:source test-record}
;; without id field
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :simple :index "a-index" :doc-type "a-type"}})
test-record)
=> {:index "a-index" :type "a-type"
:source test-record}
)
(facts "about `topic-transformer`: plain format with :daily index"
;;
;; All transformer should eventually converge to the river format
;; if the input format is a :plain non decorated record
;; then it needs to be wrapped in the river format
;; When using daily indexes then the index name must be built
;; with the given date
;;
;; with id field and system timestamp
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field :system :timestamp-field-format :millis
:id-field "id"}})
test-record)
=> {:index (format-date "a-index" (System/currentTimeMillis))
:type "a-type"
:id "abc123"
:source test-record}
;; with id field and system field timestamp in millis
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field "timestamp" :timestamp-field-format :millis
:id-field "id"}})
test-record)
=> {:index "a-index-2015-08-25"
:type "a-type"
:id "abc123"
:source test-record}
;; with id field and system field timestamp in millis
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field "ts" :timestamp-field-format :iso-8601
:id-field "id"}})
test-record)
=> {:index "a-index-2015-08-25"
:type "a-type"
:id "<KEY>"
:source test-record}
;; with id field and system field timestamp in millis
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field "ts"
:timestamp-field-format "yyyy-MM-dd'T'HH:mm:ss.SSSZZ"
:id-field "id"}})
test-record)
=> {:index "a-index-2015-08-25"
:type "a-type"
:id "<KEY>"
:source test-record}
;; with-out id field and system field timestamp in millis
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field "ts"
:timestamp-field-format "yyyy-MM-dd'T'HH:mm:ss.SSSZZ"}})
test-record)
=> {:index "a-index-2015-08-25"
:type "a-type"
:source test-record}
;; with id field which isn't present and system field timestamp in millis
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field "ts"
:timestamp-field-format "yyyy-MM-dd'T'HH:mm:ss.SSSZZ"
:id-field "NOT_PRESENT"}})
test-record)
=> {:index "a-index-2015-08-25"
:type "a-type"
:id nil
:source test-record}
)
| true | (ns qanal.transform-test
(:require [clj-time
[coerce :as tc]
[format :as f]]
[midje.sweet :refer :all]
[qanal.transform :refer :all]))
(defn format-date [base-index millis]
(str base-index (f/unparse (f/formatter "-YYYY-MM-dd") (tc/from-long millis))))
(def test-record
{:id "PI:KEY:<KEY>END_PI" :timestamp 1440511397267 :ts "2015-08-25T14:03:17.267Z"
:eventName "test-event" :sourceId "device1"})
(facts "about `timestamp-extractor`: configured as :system"
;;
;; when configured to use :system time it should return the current time
;;
(let [ts ((timestamp-extractor :system nil) {:timestamp 1})]
(<= 0 (- (System/currentTimeMillis) ts) 100)) => true
)
(facts "about `timestamp-extractor`: configured as field extraction in :millis"
;;
;; when configured to use a field it should extract its value is millis
;;
((timestamp-extractor "timestamp" :millis) {:timestamp 1}) => 1
((timestamp-extractor :timestamp :millis) {:timestamp 100}) => 100
((timestamp-extractor :no-field :millis) {:timestamp 100}) => nil
)
(facts "about `timestamp-extractor`: configured as field extraction in :iso-8601 date"
;;
;; when configured to use a field it should extract its value is millis
;;
((timestamp-extractor "timestamp" :iso-8601)
{:timestamp "2015-08-25T14:03:17.267-00:00"}) => 1440511397267
((timestamp-extractor "timestamp" :iso-8601)
{:timestamp "2015-08-25T14:03:17.267Z"}) => 1440511397267
((timestamp-extractor :timestamp :iso-8601)
{:timestamp "2015-08-25"}) => (throws Exception)
((timestamp-extractor :no-field :iso-8601)
{:timestamp "2015-08-25T14:03:17.267-00:00"}) => (throws Exception)
)
(facts "about `timestamp-extractor`: configured as field extraction in custom formatted date"
;;
;; when configured to use a field it should extract its value is millis
;;
((timestamp-extractor "timestamp" "YYYY-MM-dd")
{:timestamp "2015-08-25"}) => 1440460800000
((timestamp-extractor "timestamp" "YYYY/MM/dd")
{:timestamp "2015/08/25"}) => 1440460800000
((timestamp-extractor "timestamp" "YYYY/MM/dd")
{:timestamp "2015-08-25"}) => (throws Exception)
)
(facts "about `topic-transformer`: river format is a no-op"
;;
;; All transformer should eventually converge to the river format
;; if it is a river then it is a no-op
;;
((topic-transformer
{:type :river :topic "test" :partitions :all})
{:index "a-index" :type "a-type" :id "abc123"
:source test-record})
=> {:index "a-index" :type "a-type" :id "abc123"
:source test-record}
)
(facts "about `topic-transformer`: plain format with simple index"
;;
;; All transformer should eventually converge to the river format
;; if the input format is a :plain non decorated record
;; then it needs to be wrapped in the river format
;;
;; with id field
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :simple :index "a-index" :doc-type "a-type"
:id-field "id"}})
test-record)
=> {:index "a-index" :type "a-type" :id "abc123"
:source test-record}
;; without id field
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :simple :index "a-index" :doc-type "a-type"}})
test-record)
=> {:index "a-index" :type "a-type"
:source test-record}
)
(facts "about `topic-transformer`: plain format with :daily index"
;;
;; All transformer should eventually converge to the river format
;; if the input format is a :plain non decorated record
;; then it needs to be wrapped in the river format
;; When using daily indexes then the index name must be built
;; with the given date
;;
;; with id field and system timestamp
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field :system :timestamp-field-format :millis
:id-field "id"}})
test-record)
=> {:index (format-date "a-index" (System/currentTimeMillis))
:type "a-type"
:id "abc123"
:source test-record}
;; with id field and system field timestamp in millis
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field "timestamp" :timestamp-field-format :millis
:id-field "id"}})
test-record)
=> {:index "a-index-2015-08-25"
:type "a-type"
:id "abc123"
:source test-record}
;; with id field and system field timestamp in millis
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field "ts" :timestamp-field-format :iso-8601
:id-field "id"}})
test-record)
=> {:index "a-index-2015-08-25"
:type "a-type"
:id "PI:PASSWORD:<KEY>END_PI"
:source test-record}
;; with id field and system field timestamp in millis
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field "ts"
:timestamp-field-format "yyyy-MM-dd'T'HH:mm:ss.SSSZZ"
:id-field "id"}})
test-record)
=> {:index "a-index-2015-08-25"
:type "a-type"
:id "PI:PASSWORD:<KEY>END_PI"
:source test-record}
;; with-out id field and system field timestamp in millis
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field "ts"
:timestamp-field-format "yyyy-MM-dd'T'HH:mm:ss.SSSZZ"}})
test-record)
=> {:index "a-index-2015-08-25"
:type "a-type"
:source test-record}
;; with id field which isn't present and system field timestamp in millis
((topic-transformer
{:type :plain :topic "test" :partitions :all
:indexing {:strategy :daily :base-index "a-index" :doc-type "a-type"
:timestamp-field "ts"
:timestamp-field-format "yyyy-MM-dd'T'HH:mm:ss.SSSZZ"
:id-field "NOT_PRESENT"}})
test-record)
=> {:index "a-index-2015-08-25"
:type "a-type"
:id nil
:source test-record}
)
|
[
{
"context": "in\"\n :password \"secretadmin\"}})\n\n(def hashicorp-vault {:protocol \"http\"\n ",
"end": 1173,
"score": 0.9991992712020874,
"start": 1162,
"tag": "PASSWORD",
"value": "secretadmin"
},
{
"context": " :port 8200\n :token \"myroot\"\n :mount \"secret\"\n ",
"end": 1338,
"score": 0.6521111726760864,
"start": 1332,
"tag": "PASSWORD",
"value": "myroot"
},
{
"context": "\"smtp.eu.mailgun.org\", :replyTo \"example\", :from \"admin@example.com\", :user \"postmaster@mg.example.com\"},\n ",
"end": 2921,
"score": 0.9999305605888367,
"start": 2904,
"tag": "EMAIL",
"value": "admin@example.com"
},
{
"context": "lyTo \"example\", :from \"admin@example.com\", :user \"postmaster@mg.example.com\"},\n :tokens {:sso",
"end": 2956,
"score": 0.9999256134033203,
"start": 2931,
"tag": "EMAIL",
"value": "postmaster@mg.example.com"
},
{
"context": "\" idx))\n :users [{:email \"britt@hotmail.com\", :last-name \"Britt\", :group \"Example\", :realm-ro",
"end": 4773,
"score": 0.9999290108680725,
"start": 4756,
"tag": "EMAIL",
"value": "britt@hotmail.com"
},
{
"context": " :users [{:email \"britt@hotmail.com\", :last-name \"Britt\", :group \"Example\", :realm-roles [\"employee\" \"man",
"end": 4793,
"score": 0.9998060464859009,
"start": 4788,
"tag": "NAME",
"value": "Britt"
},
{
"context": "-admin\" \"group-admin\" \"api-consumer\"], :password \"s0w5roursg3i284\", :username \"britt\", :first-name \"James\", :attrib",
"end": 4934,
"score": 0.9994626045227051,
"start": 4919,
"tag": "PASSWORD",
"value": "s0w5roursg3i284"
},
{
"context": "nsumer\"], :password \"s0w5roursg3i284\", :username \"britt\", :first-name \"James\", :attributes {\"org-ref\" [\"E",
"end": 4953,
"score": 0.9995886087417603,
"start": 4948,
"tag": "USERNAME",
"value": "britt"
},
{
"context": "s0w5roursg3i284\", :username \"britt\", :first-name \"James\", :attributes {\"org-ref\" [\"Example\"]}, :in-subgro",
"end": 4974,
"score": 0.9998286962509155,
"start": 4969,
"tag": "NAME",
"value": "James"
},
{
"context": "[\"IT\"]}\n {:email \"charlotte.peters@gmail.com\", :last-name \"Peters\", :group \"Example\", :realm-r",
"end": 5104,
"score": 0.9999306797981262,
"start": 5078,
"tag": "EMAIL",
"value": "charlotte.peters@gmail.com"
},
{
"context": "{:email \"charlotte.peters@gmail.com\", :last-name \"Peters\", :group \"Example\", :realm-roles [\"employee\" \"man",
"end": 5125,
"score": 0.9997382164001465,
"start": 5119,
"tag": "NAME",
"value": "Peters"
},
{
"context": "-admin\" \"group-admin\" \"api-consumer\"], :password \"7o9573867\", :username \"cpeters\", :first-name \"Charlotte\", :",
"end": 5260,
"score": 0.9994344711303711,
"start": 5251,
"tag": "PASSWORD",
"value": "7o9573867"
},
{
"context": "api-consumer\"], :password \"7o9573867\", :username \"cpeters\", :first-name \"Charlotte\", :attributes {\"org-ref\"",
"end": 5281,
"score": 0.999584972858429,
"start": 5274,
"tag": "USERNAME",
"value": "cpeters"
},
{
"context": "rd \"7o9573867\", :username \"cpeters\", :first-name \"Charlotte\", :attributes {\"org-ref\" [\"Example\"]}, :in-subgro",
"end": 5306,
"score": 0.9998425841331482,
"start": 5297,
"tag": "NAME",
"value": "Charlotte"
},
{
"context": "[\"IT\"]}\n {:email \"skylar91@yahoo.com\", :last-name \"Nielsen\", :group \"Example\", :realm-",
"end": 5428,
"score": 0.9999314546585083,
"start": 5410,
"tag": "EMAIL",
"value": "skylar91@yahoo.com"
},
{
"context": " {:email \"skylar91@yahoo.com\", :last-name \"Nielsen\", :group \"Example\", :realm-roles [\"employee\" \"man",
"end": 5450,
"score": 0.9997985363006592,
"start": 5443,
"tag": "NAME",
"value": "Nielsen"
},
{
"context": "-admin\" \"group-admin\" \"api-consumer\"], :password \"02e9nx6y6\", :username \"snielsen\", :first-name \"Skylar\", :at",
"end": 5585,
"score": 0.9994585514068604,
"start": 5576,
"tag": "PASSWORD",
"value": "02e9nx6y6"
},
{
"context": "api-consumer\"], :password \"02e9nx6y6\", :username \"snielsen\", :first-name \"Skylar\", :attributes {\"org-ref\" [\"",
"end": 5607,
"score": 0.9994894862174988,
"start": 5599,
"tag": "USERNAME",
"value": "snielsen"
},
{
"context": "d \"02e9nx6y6\", :username \"snielsen\", :first-name \"Skylar\", :attributes {\"org-ref\" [\"Example\"]}, :in-subgro",
"end": 5629,
"score": 0.9998148083686829,
"start": 5623,
"tag": "NAME",
"value": "Skylar"
},
{
"context": "[\"IT\"]}\n {:email \"brayden441@me.com\", :last-name \"Pratt\", :group \"Example\", :realm-ro",
"end": 5750,
"score": 0.999930202960968,
"start": 5733,
"tag": "EMAIL",
"value": "brayden441@me.com"
},
{
"context": " {:email \"brayden441@me.com\", :last-name \"Pratt\", :group \"Example\", :realm-roles [\"employee\" \"man",
"end": 5770,
"score": 0.999823808670044,
"start": 5765,
"tag": "NAME",
"value": "Pratt"
},
{
"context": "-admin\" \"group-admin\" \"api-consumer\"], :password \"q1435mle0a4sez5u7vp\", :username \"brayden\", :first-name \"Brayden\", :at",
"end": 5915,
"score": 0.9995071887969971,
"start": 5896,
"tag": "PASSWORD",
"value": "q1435mle0a4sez5u7vp"
},
{
"context": "er\"], :password \"q1435mle0a4sez5u7vp\", :username \"brayden\", :first-name \"Brayden\", :attributes {\"org-ref\" [",
"end": 5936,
"score": 0.999547004699707,
"start": 5929,
"tag": "USERNAME",
"value": "brayden"
},
{
"context": "le0a4sez5u7vp\", :username \"brayden\", :first-name \"Brayden\", :attributes {\"org-ref\" [\"Example\"]}, :in-subgro",
"end": 5959,
"score": 0.999841034412384,
"start": 5952,
"tag": "NAME",
"value": "Brayden"
},
{
"context": "[\"IT\"]}\n {:email \"torres@yahoo.com\", :last-name \"Torres\", :group \"Example\", :realm-r",
"end": 6079,
"score": 0.9999279975891113,
"start": 6063,
"tag": "EMAIL",
"value": "torres@yahoo.com"
},
{
"context": " {:email \"torres@yahoo.com\", :last-name \"Torres\", :group \"Example\", :realm-roles [\"employee\" \"man",
"end": 6100,
"score": 0.9997991919517517,
"start": 6094,
"tag": "NAME",
"value": "Torres"
},
{
"context": "-admin\" \"group-admin\" \"api-consumer\"], :password \"nvvx2brthnxt62hmma\", :username \"torres\", :first-name \"Makayla\", :att",
"end": 6244,
"score": 0.9994794130325317,
"start": 6226,
"tag": "PASSWORD",
"value": "nvvx2brthnxt62hmma"
},
{
"context": "mer\"], :password \"nvvx2brthnxt62hmma\", :username \"torres\", :first-name \"Makayla\", :attributes {\"org-ref\" [",
"end": 6264,
"score": 0.9995644688606262,
"start": 6258,
"tag": "USERNAME",
"value": "torres"
},
{
"context": "2brthnxt62hmma\", :username \"torres\", :first-name \"Makayla\", :attributes {\"org-ref\" [\"Example\"]}, :in-subgro",
"end": 6287,
"score": 0.9998385906219482,
"start": 6280,
"tag": "NAME",
"value": "Makayla"
},
{
"context": "[\"IT\"]}\n {:email \"alyssa@hotmail.com\", :last-name \"Cantrell\", :group \"Example\", :realm",
"end": 6409,
"score": 0.9999257922172546,
"start": 6391,
"tag": "EMAIL",
"value": "alyssa@hotmail.com"
},
{
"context": " {:email \"alyssa@hotmail.com\", :last-name \"Cantrell\", :group \"Example\", :realm-roles [\"employee\" \"man",
"end": 6432,
"score": 0.999841034412384,
"start": 6424,
"tag": "NAME",
"value": "Cantrell"
},
{
"context": "-admin\" \"group-admin\" \"api-consumer\"], :password \"0db8ck\", :username \"alyssa529\", :first-name \"Alyssa\", :a",
"end": 6564,
"score": 0.9994959831237793,
"start": 6558,
"tag": "PASSWORD",
"value": "0db8ck"
},
{
"context": "\" \"api-consumer\"], :password \"0db8ck\", :username \"alyssa529\", :first-name \"Alyssa\", :attributes {\"org-ref\" [\"",
"end": 6587,
"score": 0.9996450543403625,
"start": 6578,
"tag": "USERNAME",
"value": "alyssa529"
},
{
"context": "ord \"0db8ck\", :username \"alyssa529\", :first-name \"Alyssa\", :attributes {\"org-ref\" [\"Example\"]}, :in-subgro",
"end": 6609,
"score": 0.9998224377632141,
"start": 6603,
"tag": "NAME",
"value": "Alyssa"
},
{
"context": "[\"IT\"]}\n {:email \"luke@hotmail.com\", :last-name \"Graves\", :group \"Example\", :realm-r",
"end": 6729,
"score": 0.999924898147583,
"start": 6713,
"tag": "EMAIL",
"value": "luke@hotmail.com"
},
{
"context": " {:email \"luke@hotmail.com\", :last-name \"Graves\", :group \"Example\", :realm-roles [\"employee\" \"man",
"end": 6750,
"score": 0.999754786491394,
"start": 6744,
"tag": "NAME",
"value": "Graves"
},
{
"context": "-admin\" \"group-admin\" \"api-consumer\"], :password \"009y77udi1\", :username \"luke222\", :first-name \"Luke\", :attri",
"end": 6886,
"score": 0.9994836449623108,
"start": 6876,
"tag": "PASSWORD",
"value": "009y77udi1"
},
{
"context": "pi-consumer\"], :password \"009y77udi1\", :username \"luke222\", :first-name \"Luke\", :attributes {\"org-ref\" [\"Ex",
"end": 6907,
"score": 0.9996291399002075,
"start": 6900,
"tag": "USERNAME",
"value": "luke222"
},
{
"context": "d \"009y77udi1\", :username \"luke222\", :first-name \"Luke\", :attributes {\"org-ref\" [\"Example\"]}, :in-subgro",
"end": 6927,
"score": 0.9998376965522766,
"start": 6923,
"tag": "NAME",
"value": "Luke"
},
{
"context": "[\"IT\"]}\n {:email \"zachary660@yahoo.com\", :last-name \"Lynn\", :group \"Example\", :realm-rol",
"end": 7051,
"score": 0.9999282956123352,
"start": 7031,
"tag": "EMAIL",
"value": "zachary660@yahoo.com"
},
{
"context": " {:email \"zachary660@yahoo.com\", :last-name \"Lynn\", :group \"Example\", :realm-roles [\"employee\" \"man",
"end": 7070,
"score": 0.9998147487640381,
"start": 7066,
"tag": "NAME",
"value": "Lynn"
},
{
"context": "-admin\" \"group-admin\" \"api-consumer\"], :password \"fq24gfjrpdhaq3z\", :username \"zachary734\", :first-name \"Zachary\", ",
"end": 7211,
"score": 0.9994945526123047,
"start": 7196,
"tag": "PASSWORD",
"value": "fq24gfjrpdhaq3z"
},
{
"context": "nsumer\"], :password \"fq24gfjrpdhaq3z\", :username \"zachary734\", :first-name \"Zachary\", :attributes {\"org-ref\" [",
"end": 7235,
"score": 0.9996606707572937,
"start": 7225,
"tag": "USERNAME",
"value": "zachary734"
},
{
"context": "fjrpdhaq3z\", :username \"zachary734\", :first-name \"Zachary\", :attributes {\"org-ref\" [\"Example\"]}, :in-subgro",
"end": 7258,
"score": 0.9998424649238586,
"start": 7251,
"tag": "NAME",
"value": "Zachary"
},
{
"context": "[\"IT\"]}\n {:email \"landon@me.com\", :last-name \"Odom\", :group \"Example\", :realm-rol",
"end": 7375,
"score": 0.9999287724494934,
"start": 7362,
"tag": "EMAIL",
"value": "landon@me.com"
},
{
"context": " {:email \"landon@me.com\", :last-name \"Odom\", :group \"Example\", :realm-roles [\"employee\" \"man",
"end": 7394,
"score": 0.9997168779373169,
"start": 7390,
"tag": "NAME",
"value": "Odom"
},
{
"context": "-admin\" \"group-admin\" \"api-consumer\"], :password \"6k421x21x8\", :username \"landon\", :first-name \"Landon\", :attr",
"end": 7530,
"score": 0.9994524717330933,
"start": 7520,
"tag": "PASSWORD",
"value": "6k421x21x8"
},
{
"context": "pi-consumer\"], :password \"6k421x21x8\", :username \"landon\", :first-name \"Landon\", :attributes {\"org-ref\" [\"",
"end": 7550,
"score": 0.9995526075363159,
"start": 7544,
"tag": "USERNAME",
"value": "landon"
},
{
"context": "rd \"6k421x21x8\", :username \"landon\", :first-name \"Landon\", :attributes {\"org-ref\" [\"Example\"]}, :in-subgro",
"end": 7572,
"score": 0.9998045563697815,
"start": 7566,
"tag": "NAME",
"value": "Landon"
},
{
"context": "[\"IT\"]}\n {:email \"angel402@gmail.com\", :last-name \"Sloan\", :group \"Example\", :realm-ro",
"end": 7694,
"score": 0.9999298453330994,
"start": 7676,
"tag": "EMAIL",
"value": "angel402@gmail.com"
},
{
"context": " {:email \"angel402@gmail.com\", :last-name \"Sloan\", :group \"Example\", :realm-roles [\"employee\" \"man",
"end": 7714,
"score": 0.9997831583023071,
"start": 7709,
"tag": "NAME",
"value": "Sloan"
},
{
"context": "-admin\" \"group-admin\" \"api-consumer\"], :password \"99t9myhvn\", :username \"angel\", :first-name \"Angel\", :attrib",
"end": 7849,
"score": 0.9994696378707886,
"start": 7840,
"tag": "PASSWORD",
"value": "99t9myhvn"
},
{
"context": "api-consumer\"], :password \"99t9myhvn\", :username \"angel\", :first-name \"Angel\", :attributes {\"org-ref\" [\"E",
"end": 7868,
"score": 0.9994317293167114,
"start": 7863,
"tag": "USERNAME",
"value": "angel"
},
{
"context": "word \"99t9myhvn\", :username \"angel\", :first-name \"Angel\", :attributes {\"org-ref\" [\"Example\"]}, :in-subgro",
"end": 7889,
"score": 0.9998027086257935,
"start": 7884,
"tag": "NAME",
"value": "Angel"
},
{
"context": "[\"IT\"]}\n {:email \"kayden.griffin@gmail.com\", :last-name \"Griffin\", :group \"Example\", :realm-",
"end": 8017,
"score": 0.9999300241470337,
"start": 7993,
"tag": "EMAIL",
"value": "kayden.griffin@gmail.com"
},
{
"context": " {:email \"kayden.griffin@gmail.com\", :last-name \"Griffin\", :group \"Example\", :realm-roles [\"employee\" \"man",
"end": 8039,
"score": 0.9998368620872498,
"start": 8032,
"tag": "NAME",
"value": "Griffin"
},
{
"context": "-admin\" \"group-admin\" \"api-consumer\"], :password \"8zk7whnoic\", :username \"kayden278\", :first-name \"Kayden\", :a",
"end": 8175,
"score": 0.9994964003562927,
"start": 8165,
"tag": "PASSWORD",
"value": "8zk7whnoic"
},
{
"context": "pi-consumer\"], :password \"8zk7whnoic\", :username \"kayden278\", :first-name \"Kayden\", :attributes {\"org-ref\" [\"",
"end": 8198,
"score": 0.9988543391227722,
"start": 8189,
"tag": "USERNAME",
"value": "kayden278"
},
{
"context": "\"8zk7whnoic\", :username \"kayden278\", :first-name \"Kayden\", :attributes {\"org-ref\" [\"Example\"]}, :in-subgro",
"end": 8220,
"score": 0.9998032450675964,
"start": 8214,
"tag": "NAME",
"value": "Kayden"
},
{
"context": "[\"IT\"]}\n {:email \"evan@yahoo.com\", :last-name \"Patrick\", :group \"Example\", :realm-",
"end": 8338,
"score": 0.9999296069145203,
"start": 8324,
"tag": "EMAIL",
"value": "evan@yahoo.com"
},
{
"context": " {:email \"evan@yahoo.com\", :last-name \"Patrick\", :group \"Example\", :realm-roles [\"employee\" \"man",
"end": 8360,
"score": 0.9997454285621643,
"start": 8353,
"tag": "NAME",
"value": "Patrick"
},
{
"context": "-admin\" \"group-admin\" \"api-consumer\"], :password \"vt5n7ni5zfsbe0abx\", :username \"patrick\", :first-name \"Evan\", :attri",
"end": 8503,
"score": 0.9994927048683167,
"start": 8486,
"tag": "PASSWORD",
"value": "vt5n7ni5zfsbe0abx"
},
{
"context": "umer\"], :password \"vt5n7ni5zfsbe0abx\", :username \"patrick\", :first-name \"Evan\", :attributes {\"org-ref\" [\"Ex",
"end": 8524,
"score": 0.9992551803588867,
"start": 8517,
"tag": "USERNAME",
"value": "patrick"
},
{
"context": "7ni5zfsbe0abx\", :username \"patrick\", :first-name \"Evan\", :attributes {\"org-ref\" [\"Example\"]}, :in-subgro",
"end": 8544,
"score": 0.9998136162757874,
"start": 8540,
"tag": "NAME",
"value": "Evan"
},
{
"context": "[\"IT\"]}\n {:email \"fox@gmail.com\", :last-name \"Fox\", :group \"Example\", :realm-role",
"end": 8661,
"score": 0.9999231100082397,
"start": 8648,
"tag": "EMAIL",
"value": "fox@gmail.com"
},
{
"context": " {:email \"fox@gmail.com\", :last-name \"Fox\", :group \"Example\", :realm-roles [\"employee\" \"man",
"end": 8679,
"score": 0.9998148679733276,
"start": 8676,
"tag": "NAME",
"value": "Fox"
},
{
"context": "-admin\" \"group-admin\" \"api-consumer\"], :password \"u8cj0m\", :username \"bentley\", :first-name \"Bentley\", :at",
"end": 8811,
"score": 0.9994550943374634,
"start": 8805,
"tag": "PASSWORD",
"value": "u8cj0m"
},
{
"context": "\" \"api-consumer\"], :password \"u8cj0m\", :username \"bentley\", :first-name \"Bentley\", :attributes {\"org-ref\" [",
"end": 8832,
"score": 0.9994320869445801,
"start": 8825,
"tag": "USERNAME",
"value": "bentley"
},
{
"context": "sword \"u8cj0m\", :username \"bentley\", :first-name \"Bentley\", :attributes {\"org-ref\" [\"Example\"]}, :in-subgro",
"end": 8855,
"score": 0.9997972846031189,
"start": 8848,
"tag": "NAME",
"value": "Bentley"
},
{
"context": "[\"IT\"]}\n {:email \"genesis@yahoo.com\", :last-name \"Lindsey\", :group \"Example\", :realm-",
"end": 8976,
"score": 0.9999224543571472,
"start": 8959,
"tag": "EMAIL",
"value": "genesis@yahoo.com"
},
{
"context": " {:email \"genesis@yahoo.com\", :last-name \"Lindsey\", :group \"Example\", :realm-roles [\"employee\" \"man",
"end": 8998,
"score": 0.9996252655982971,
"start": 8991,
"tag": "NAME",
"value": "Lindsey"
},
{
"context": "-admin\" \"group-admin\" \"api-consumer\"], :password \"7bo1fvm98gahhgwiv\", :username \"glindsey\", :first-name \"Genesis\", :a",
"end": 9141,
"score": 0.9994954466819763,
"start": 9124,
"tag": "PASSWORD",
"value": "7bo1fvm98gahhgwiv"
},
{
"context": "umer\"], :password \"7bo1fvm98gahhgwiv\", :username \"glindsey\", :first-name \"Genesis\", :attributes {\"org-ref\" [",
"end": 9163,
"score": 0.9994528889656067,
"start": 9155,
"tag": "USERNAME",
"value": "glindsey"
},
{
"context": "vm98gahhgwiv\", :username \"glindsey\", :first-name \"Genesis\", :attributes {\"org-ref\" [\"Example\"]}, :in-subgro",
"end": 9186,
"score": 0.9862804412841797,
"start": 9179,
"tag": "NAME",
"value": "Genesis"
},
{
"context": "[\"IT\"]}\n {:email \"xavier765@yahoo.com\", :last-name \"Mccall\", :group \"Example\", :realm-r",
"end": 9309,
"score": 0.999928891658783,
"start": 9290,
"tag": "EMAIL",
"value": "xavier765@yahoo.com"
},
{
"context": " {:email \"xavier765@yahoo.com\", :last-name \"Mccall\", :group \"Example\", :realm-roles [\"employee\" \"man",
"end": 9330,
"score": 0.999802827835083,
"start": 9324,
"tag": "NAME",
"value": "Mccall"
},
{
"context": "-admin\" \"group-admin\" \"api-consumer\"], :password \"s0xha8r7w9w\", :username \"mccall\", :first-name \"Xavier\", :attr",
"end": 9467,
"score": 0.9993797540664673,
"start": 9456,
"tag": "PASSWORD",
"value": "s0xha8r7w9w"
},
{
"context": "i-consumer\"], :password \"s0xha8r7w9w\", :username \"mccall\", :first-name \"Xavier\", :attributes {\"org-ref\" [\"",
"end": 9487,
"score": 0.999631404876709,
"start": 9481,
"tag": "USERNAME",
"value": "mccall"
},
{
"context": "d \"s0xha8r7w9w\", :username \"mccall\", :first-name \"Xavier\", :attributes {\"org-ref\" [\"Example\"]}, :in-subgro",
"end": 9509,
"score": 0.9996089935302734,
"start": 9503,
"tag": "NAME",
"value": "Xavier"
},
{
"context": "\"]}\n {:last-name \"Carter\", :group \"Example\", :realm-roles [\"employee\" \"man",
"end": 9623,
"score": 0.9997179508209229,
"start": 9617,
"tag": "NAME",
"value": "Carter"
},
{
"context": "\"employee\" \"manager\" \"example-admin\"], :password \"secretstuff\", :username \"testaccount\", :first-name \"Bob\", :at",
"end": 9719,
"score": 0.9994012117385864,
"start": 9708,
"tag": "PASSWORD",
"value": "secretstuff"
},
{
"context": "mple-admin\"], :password \"secretstuff\", :username \"testaccount\", :first-name \"Bob\", :attributes {\"org-ref\" [\"Exa",
"end": 9744,
"score": 0.9993562698364258,
"start": 9733,
"tag": "USERNAME",
"value": "testaccount"
},
{
"context": "cretstuff\", :username \"testaccount\", :first-name \"Bob\", :attributes {\"org-ref\" [\"Example\"]}, :in-subgro",
"end": 9763,
"score": 0.9997704029083252,
"start": 9760,
"tag": "NAME",
"value": "Bob"
}
] | test/keycloak/starter_test.clj | borkdude/keycloak-clojure | 0 | (ns keycloak.starter-test
(:require
[clojure.test :as t :refer :all]
[clojure.string :as str]
[clojure.pprint :as pp]
[sci.core :as sci]
[testit.core :refer :all]
[keycloak.starter :as starter]
[keycloak.admin :refer :all]
[keycloak.user :as user]
[keycloak.utils :as utils :refer [auth-server-url]]
[keycloak.deployment :as deployment :refer [keycloak-client client-conf]]
[keycloak.vault.protocol :as vault :refer [Vault write-secret! read-secret]]
[keycloak.vault.hashicorp :as hashicorp-vault]
[keycloak.vault.google :as google-vault]
[keycloak.reconciliation :as reconciliation]
[clojure.pprint :as pp]))
(def infra-context {:environment "automatedtest"
:color "blue"
:base-domain "example.com"
:applications {:name "myapp"
:version "1.4.12"}
:keycloak {:protocol "http"
:host "localhost"
:port "8090"
:login "admin"
:password "secretadmin"}})
(def hashicorp-vault {:protocol "http"
:host "localhost"
:port 8200
:token "myroot"
:mount "secret"
:vendor :hashicorp
;;%1$s is the environment, %2$s is the color, %3$s is the base-domain, %4$s is the client-id (so depends of your realm-config.clj code)
:path "/env/%1$s/keycloak/clients/%4$s"})
(def google-sm-vault {:project-id "adixe-1168"
:vendor :gcp-sm
:secret-id "secret-name-test"
:replication-policy "automatic"})
(def integration-test-conf (deployment/client-conf (utils/auth-server-url infra-context) "master" "admin-cli"))
(def admin-client (deployment/keycloak-client integration-test-conf (get-in infra-context [:keycloak :login]) (get-in infra-context [:keycloak :password])))
(def static-realm-data [{:realm {:name "example2",
:themes
{:defaultLocale "fr",
:emailTheme "keycloak",
:internationalizationEnabled true,
:adminTheme "keycloak",
:supportedLocales #{"en" "fr"},
:loginTheme "keycloak",
:accountTheme "keycloak"},
:login {:resetPasswordAllowed true, :bruteForceProtected true, :rememberMe true},
:smtp {:starttls true, :password "", :port 587, :auth true, :host "smtp.eu.mailgun.org", :replyTo "example", :from "admin@example.com", :user "postmaster@mg.example.com"},
:tokens {:ssoSessionIdleTimeoutRememberMe (int 172800,) :ssoSessionMaxLifespanRememberMe (int 172800)}},
:roles #{"org-admin" "example-admin" "group-admin" "api-consumer" "employee" "manager"},
:clients [{:name "api-client",
:redirect-uris ["https://myapp.staging.example.com/*"],
:base-url "https://myapp.staging.example.com",
:web-origins ["https://myapp.staging.example.com"],
:public? true,
:root-url "https://myapp.staging.example.com"}
{:name "myfrontend",
:redirect-uris ["https://myapp.staging.example.com/*"],
:base-url "https://myapp.staging.example.com",
:web-origins ["https://myapp.staging.example.com"],
:public? true,
:root-url "https://myapp.staging.example.com"}
{:name "mybackend",
:redirect-uris ["http://localhost:3449/*"],
:web-origins ["http://localhost:3449"],
:public? false}],
:generated-users-by-group-and-role 2,
:groups [{:name "test"} {:name "Example", :subgroups [{:name "IT"} {:name "Sales"} {:name "Logistics"}]}],
:username-creator-fn (fn [role group subgroup idx & opts] (str (str group) "-" (subs (str role) 0 3) "-" idx))
:users [{:email "britt@hotmail.com", :last-name "Britt", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "s0w5roursg3i284", :username "britt", :first-name "James", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "charlotte.peters@gmail.com", :last-name "Peters", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "7o9573867", :username "cpeters", :first-name "Charlotte", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "skylar91@yahoo.com", :last-name "Nielsen", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "02e9nx6y6", :username "snielsen", :first-name "Skylar", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "brayden441@me.com", :last-name "Pratt", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "q1435mle0a4sez5u7vp", :username "brayden", :first-name "Brayden", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "torres@yahoo.com", :last-name "Torres", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "nvvx2brthnxt62hmma", :username "torres", :first-name "Makayla", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "alyssa@hotmail.com", :last-name "Cantrell", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "0db8ck", :username "alyssa529", :first-name "Alyssa", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "luke@hotmail.com", :last-name "Graves", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "009y77udi1", :username "luke222", :first-name "Luke", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "zachary660@yahoo.com", :last-name "Lynn", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "fq24gfjrpdhaq3z", :username "zachary734", :first-name "Zachary", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "landon@me.com", :last-name "Odom", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "6k421x21x8", :username "landon", :first-name "Landon", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "angel402@gmail.com", :last-name "Sloan", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "99t9myhvn", :username "angel", :first-name "Angel", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "kayden.griffin@gmail.com", :last-name "Griffin", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "8zk7whnoic", :username "kayden278", :first-name "Kayden", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "evan@yahoo.com", :last-name "Patrick", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "vt5n7ni5zfsbe0abx", :username "patrick", :first-name "Evan", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "fox@gmail.com", :last-name "Fox", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "u8cj0m", :username "bentley", :first-name "Bentley", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "genesis@yahoo.com", :last-name "Lindsey", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "7bo1fvm98gahhgwiv", :username "glindsey", :first-name "Genesis", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "xavier765@yahoo.com", :last-name "Mccall", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "s0xha8r7w9w", :username "mccall", :first-name "Xavier", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:last-name "Carter", :group "Example", :realm-roles ["employee" "manager" "example-admin"], :password "secretstuff", :username "testaccount", :first-name "Bob", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}]}])
(deftest ^:integration vault-test
(testing "Hashicorp vault"
)
(testing "Google secret manager "
;;this test needs the environment variable GOOGLE_APPLICATION_CREDENTIALS defined with value as the path of the JSON file that contains your service account key.
(let [realm-name (str "test-realm-" (rand-int 1000))]
(doseq [realm-data static-realm-data]
(starter/init! admin-client (assoc-in realm-data [:realm :name] realm-name) (assoc infra-context :vault google-sm-vault))
(let [vault (google-vault/->GoogleSecretManager (:project-id google-sm-vault))]
(doseq [{:keys [name public?] :as client} (:clients realm-data)]
(let [secret-value (vault/read-secret vault name)]
;(println "secret-value" secret-value)
(when (not public?)
(fact secret-value => (comp not str/blank?)))))))
(testing "realm deletion"
(delete-realm! admin-client realm-name)
(is (thrown? javax.ws.rs.NotFoundException (get-realm admin-client realm-name)))
))))
(deftest ^:integration starter-reconciliation-test
(testing "Applying a full configuration to an empty realm"
(let [realm-name (str "reconciliation-test-realm" (rand-int 1000))
config (first (clojure.edn/read-string (slurp "resources/config-init-realm.edn")))]
(starter/init! admin-client (assoc-in config [:realm :name] realm-name) infra-context {:dry-run? false :apply-deletions? true})
(println "roles")
(pp/pprint (:roles config))
(testing "Getting a plan should now be empty"
(let [users-plan (reconciliation/users-plan admin-client realm-name (:users config))
groups-plan (reconciliation/groups-plan admin-client realm-name (:groups config))
role-mappings-plan (reconciliation/role-mappings-plan admin-client realm-name (:roles config) (utils/associate-by :username (:users config)))]
(facts (get users-plan :users/additions) => empty?
(get users-plan :users/deletions) => empty?
(get users-plan :users/updates) => empty?
(get groups-plan :groups/additions) => empty?
(get groups-plan :groups/deletions) => empty?
(get role-mappings-plan :realm-role-mappings/additions) => empty?
(get role-mappings-plan :realm-role-mappings/deletions) => empty?)))
(testing "apply again the same configuration"
(starter/init! admin-client (assoc-in config [:realm :name] realm-name) infra-context {:dry-run? true :apply-deletions? true}))
(testing "realm deletion"
(delete-realm! admin-client realm-name)
(is (thrown? javax.ws.rs.NotFoundException (get-realm admin-client realm-name)))))))
(deftest config-test
(let [environment (sci/new-var 'environment "staging")
applications (sci/new-var 'applications [{:name "myapp"
:version "1.2.3"
:clients-uris [{:client-id "api-client"
:public? true
:root "https://api.example.com"
:base "/"
:redirects ["https://api.example.com/*"]
:origins ["https://api.example.com"]}
{:client-id "backend"
:public? false
:root "https://backend.example.com"
:base "/"
:redirects ["https://backend.example.com/*"]
:origins ["https://backend.example.com"]}]}])
color (sci/new-var 'color "red")
config-code (slurp "resources/realm-config-clients.clj")
config-data (sci/eval-string config-code {:bindings {'environment environment
'applications applications
'color color}})]
(fact config-data => [{:realm {:name "example2"},
:clients [{:name "api-client" :redirect-uris ["https://api.example.com/*"], :base-url "/" :web-origins ["https://api.example.com"], :public? true, :root-url "https://api.example.com"}
{:name "backend" :redirect-uris ["https://backend.example.com/*"], :base-url "/" :web-origins ["https://backend.example.com"], :public? false, :root-url "https://backend.example.com"}]}])))
| 82133 | (ns keycloak.starter-test
(:require
[clojure.test :as t :refer :all]
[clojure.string :as str]
[clojure.pprint :as pp]
[sci.core :as sci]
[testit.core :refer :all]
[keycloak.starter :as starter]
[keycloak.admin :refer :all]
[keycloak.user :as user]
[keycloak.utils :as utils :refer [auth-server-url]]
[keycloak.deployment :as deployment :refer [keycloak-client client-conf]]
[keycloak.vault.protocol :as vault :refer [Vault write-secret! read-secret]]
[keycloak.vault.hashicorp :as hashicorp-vault]
[keycloak.vault.google :as google-vault]
[keycloak.reconciliation :as reconciliation]
[clojure.pprint :as pp]))
(def infra-context {:environment "automatedtest"
:color "blue"
:base-domain "example.com"
:applications {:name "myapp"
:version "1.4.12"}
:keycloak {:protocol "http"
:host "localhost"
:port "8090"
:login "admin"
:password "<PASSWORD>"}})
(def hashicorp-vault {:protocol "http"
:host "localhost"
:port 8200
:token "<PASSWORD>"
:mount "secret"
:vendor :hashicorp
;;%1$s is the environment, %2$s is the color, %3$s is the base-domain, %4$s is the client-id (so depends of your realm-config.clj code)
:path "/env/%1$s/keycloak/clients/%4$s"})
(def google-sm-vault {:project-id "adixe-1168"
:vendor :gcp-sm
:secret-id "secret-name-test"
:replication-policy "automatic"})
(def integration-test-conf (deployment/client-conf (utils/auth-server-url infra-context) "master" "admin-cli"))
(def admin-client (deployment/keycloak-client integration-test-conf (get-in infra-context [:keycloak :login]) (get-in infra-context [:keycloak :password])))
(def static-realm-data [{:realm {:name "example2",
:themes
{:defaultLocale "fr",
:emailTheme "keycloak",
:internationalizationEnabled true,
:adminTheme "keycloak",
:supportedLocales #{"en" "fr"},
:loginTheme "keycloak",
:accountTheme "keycloak"},
:login {:resetPasswordAllowed true, :bruteForceProtected true, :rememberMe true},
:smtp {:starttls true, :password "", :port 587, :auth true, :host "smtp.eu.mailgun.org", :replyTo "example", :from "<EMAIL>", :user "<EMAIL>"},
:tokens {:ssoSessionIdleTimeoutRememberMe (int 172800,) :ssoSessionMaxLifespanRememberMe (int 172800)}},
:roles #{"org-admin" "example-admin" "group-admin" "api-consumer" "employee" "manager"},
:clients [{:name "api-client",
:redirect-uris ["https://myapp.staging.example.com/*"],
:base-url "https://myapp.staging.example.com",
:web-origins ["https://myapp.staging.example.com"],
:public? true,
:root-url "https://myapp.staging.example.com"}
{:name "myfrontend",
:redirect-uris ["https://myapp.staging.example.com/*"],
:base-url "https://myapp.staging.example.com",
:web-origins ["https://myapp.staging.example.com"],
:public? true,
:root-url "https://myapp.staging.example.com"}
{:name "mybackend",
:redirect-uris ["http://localhost:3449/*"],
:web-origins ["http://localhost:3449"],
:public? false}],
:generated-users-by-group-and-role 2,
:groups [{:name "test"} {:name "Example", :subgroups [{:name "IT"} {:name "Sales"} {:name "Logistics"}]}],
:username-creator-fn (fn [role group subgroup idx & opts] (str (str group) "-" (subs (str role) 0 3) "-" idx))
:users [{:email "<EMAIL>", :last-name "<NAME>", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "<PASSWORD>", :username "britt", :first-name "<NAME>", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "<EMAIL>", :last-name "<NAME>", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "<PASSWORD>", :username "cpeters", :first-name "<NAME>", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "<EMAIL>", :last-name "<NAME>", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "<PASSWORD>", :username "snielsen", :first-name "<NAME>", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "<EMAIL>", :last-name "<NAME>", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "<PASSWORD>", :username "brayden", :first-name "<NAME>", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "<EMAIL>", :last-name "<NAME>", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "<PASSWORD>", :username "torres", :first-name "<NAME>", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "<EMAIL>", :last-name "<NAME>", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "<PASSWORD>", :username "alyssa529", :first-name "<NAME>", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "<EMAIL>", :last-name "<NAME>", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "<PASSWORD>", :username "luke222", :first-name "<NAME>", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "<EMAIL>", :last-name "<NAME>", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "<PASSWORD>", :username "zachary734", :first-name "<NAME>", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "<EMAIL>", :last-name "<NAME>", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "<PASSWORD>", :username "landon", :first-name "<NAME>", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "<EMAIL>", :last-name "<NAME>", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "<PASSWORD>", :username "angel", :first-name "<NAME>", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "<EMAIL>", :last-name "<NAME>", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "<PASSWORD>", :username "kayden278", :first-name "<NAME>", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "<EMAIL>", :last-name "<NAME>", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "<PASSWORD>", :username "patrick", :first-name "<NAME>", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "<EMAIL>", :last-name "<NAME>", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "<PASSWORD>", :username "bentley", :first-name "<NAME>", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "<EMAIL>", :last-name "<NAME>", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "<PASSWORD>", :username "glindsey", :first-name "<NAME>", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "<EMAIL>", :last-name "<NAME>", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "<PASSWORD>", :username "mccall", :first-name "<NAME>", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:last-name "<NAME>", :group "Example", :realm-roles ["employee" "manager" "example-admin"], :password "<PASSWORD>", :username "testaccount", :first-name "<NAME>", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}]}])
(deftest ^:integration vault-test
(testing "Hashicorp vault"
)
(testing "Google secret manager "
;;this test needs the environment variable GOOGLE_APPLICATION_CREDENTIALS defined with value as the path of the JSON file that contains your service account key.
(let [realm-name (str "test-realm-" (rand-int 1000))]
(doseq [realm-data static-realm-data]
(starter/init! admin-client (assoc-in realm-data [:realm :name] realm-name) (assoc infra-context :vault google-sm-vault))
(let [vault (google-vault/->GoogleSecretManager (:project-id google-sm-vault))]
(doseq [{:keys [name public?] :as client} (:clients realm-data)]
(let [secret-value (vault/read-secret vault name)]
;(println "secret-value" secret-value)
(when (not public?)
(fact secret-value => (comp not str/blank?)))))))
(testing "realm deletion"
(delete-realm! admin-client realm-name)
(is (thrown? javax.ws.rs.NotFoundException (get-realm admin-client realm-name)))
))))
(deftest ^:integration starter-reconciliation-test
(testing "Applying a full configuration to an empty realm"
(let [realm-name (str "reconciliation-test-realm" (rand-int 1000))
config (first (clojure.edn/read-string (slurp "resources/config-init-realm.edn")))]
(starter/init! admin-client (assoc-in config [:realm :name] realm-name) infra-context {:dry-run? false :apply-deletions? true})
(println "roles")
(pp/pprint (:roles config))
(testing "Getting a plan should now be empty"
(let [users-plan (reconciliation/users-plan admin-client realm-name (:users config))
groups-plan (reconciliation/groups-plan admin-client realm-name (:groups config))
role-mappings-plan (reconciliation/role-mappings-plan admin-client realm-name (:roles config) (utils/associate-by :username (:users config)))]
(facts (get users-plan :users/additions) => empty?
(get users-plan :users/deletions) => empty?
(get users-plan :users/updates) => empty?
(get groups-plan :groups/additions) => empty?
(get groups-plan :groups/deletions) => empty?
(get role-mappings-plan :realm-role-mappings/additions) => empty?
(get role-mappings-plan :realm-role-mappings/deletions) => empty?)))
(testing "apply again the same configuration"
(starter/init! admin-client (assoc-in config [:realm :name] realm-name) infra-context {:dry-run? true :apply-deletions? true}))
(testing "realm deletion"
(delete-realm! admin-client realm-name)
(is (thrown? javax.ws.rs.NotFoundException (get-realm admin-client realm-name)))))))
(deftest config-test
(let [environment (sci/new-var 'environment "staging")
applications (sci/new-var 'applications [{:name "myapp"
:version "1.2.3"
:clients-uris [{:client-id "api-client"
:public? true
:root "https://api.example.com"
:base "/"
:redirects ["https://api.example.com/*"]
:origins ["https://api.example.com"]}
{:client-id "backend"
:public? false
:root "https://backend.example.com"
:base "/"
:redirects ["https://backend.example.com/*"]
:origins ["https://backend.example.com"]}]}])
color (sci/new-var 'color "red")
config-code (slurp "resources/realm-config-clients.clj")
config-data (sci/eval-string config-code {:bindings {'environment environment
'applications applications
'color color}})]
(fact config-data => [{:realm {:name "example2"},
:clients [{:name "api-client" :redirect-uris ["https://api.example.com/*"], :base-url "/" :web-origins ["https://api.example.com"], :public? true, :root-url "https://api.example.com"}
{:name "backend" :redirect-uris ["https://backend.example.com/*"], :base-url "/" :web-origins ["https://backend.example.com"], :public? false, :root-url "https://backend.example.com"}]}])))
| true | (ns keycloak.starter-test
(:require
[clojure.test :as t :refer :all]
[clojure.string :as str]
[clojure.pprint :as pp]
[sci.core :as sci]
[testit.core :refer :all]
[keycloak.starter :as starter]
[keycloak.admin :refer :all]
[keycloak.user :as user]
[keycloak.utils :as utils :refer [auth-server-url]]
[keycloak.deployment :as deployment :refer [keycloak-client client-conf]]
[keycloak.vault.protocol :as vault :refer [Vault write-secret! read-secret]]
[keycloak.vault.hashicorp :as hashicorp-vault]
[keycloak.vault.google :as google-vault]
[keycloak.reconciliation :as reconciliation]
[clojure.pprint :as pp]))
(def infra-context {:environment "automatedtest"
:color "blue"
:base-domain "example.com"
:applications {:name "myapp"
:version "1.4.12"}
:keycloak {:protocol "http"
:host "localhost"
:port "8090"
:login "admin"
:password "PI:PASSWORD:<PASSWORD>END_PI"}})
(def hashicorp-vault {:protocol "http"
:host "localhost"
:port 8200
:token "PI:PASSWORD:<PASSWORD>END_PI"
:mount "secret"
:vendor :hashicorp
;;%1$s is the environment, %2$s is the color, %3$s is the base-domain, %4$s is the client-id (so depends of your realm-config.clj code)
:path "/env/%1$s/keycloak/clients/%4$s"})
(def google-sm-vault {:project-id "adixe-1168"
:vendor :gcp-sm
:secret-id "secret-name-test"
:replication-policy "automatic"})
(def integration-test-conf (deployment/client-conf (utils/auth-server-url infra-context) "master" "admin-cli"))
(def admin-client (deployment/keycloak-client integration-test-conf (get-in infra-context [:keycloak :login]) (get-in infra-context [:keycloak :password])))
(def static-realm-data [{:realm {:name "example2",
:themes
{:defaultLocale "fr",
:emailTheme "keycloak",
:internationalizationEnabled true,
:adminTheme "keycloak",
:supportedLocales #{"en" "fr"},
:loginTheme "keycloak",
:accountTheme "keycloak"},
:login {:resetPasswordAllowed true, :bruteForceProtected true, :rememberMe true},
:smtp {:starttls true, :password "", :port 587, :auth true, :host "smtp.eu.mailgun.org", :replyTo "example", :from "PI:EMAIL:<EMAIL>END_PI", :user "PI:EMAIL:<EMAIL>END_PI"},
:tokens {:ssoSessionIdleTimeoutRememberMe (int 172800,) :ssoSessionMaxLifespanRememberMe (int 172800)}},
:roles #{"org-admin" "example-admin" "group-admin" "api-consumer" "employee" "manager"},
:clients [{:name "api-client",
:redirect-uris ["https://myapp.staging.example.com/*"],
:base-url "https://myapp.staging.example.com",
:web-origins ["https://myapp.staging.example.com"],
:public? true,
:root-url "https://myapp.staging.example.com"}
{:name "myfrontend",
:redirect-uris ["https://myapp.staging.example.com/*"],
:base-url "https://myapp.staging.example.com",
:web-origins ["https://myapp.staging.example.com"],
:public? true,
:root-url "https://myapp.staging.example.com"}
{:name "mybackend",
:redirect-uris ["http://localhost:3449/*"],
:web-origins ["http://localhost:3449"],
:public? false}],
:generated-users-by-group-and-role 2,
:groups [{:name "test"} {:name "Example", :subgroups [{:name "IT"} {:name "Sales"} {:name "Logistics"}]}],
:username-creator-fn (fn [role group subgroup idx & opts] (str (str group) "-" (subs (str role) 0 3) "-" idx))
:users [{:email "PI:EMAIL:<EMAIL>END_PI", :last-name "PI:NAME:<NAME>END_PI", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "PI:PASSWORD:<PASSWORD>END_PI", :username "britt", :first-name "PI:NAME:<NAME>END_PI", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "PI:EMAIL:<EMAIL>END_PI", :last-name "PI:NAME:<NAME>END_PI", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "PI:PASSWORD:<PASSWORD>END_PI", :username "cpeters", :first-name "PI:NAME:<NAME>END_PI", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "PI:EMAIL:<EMAIL>END_PI", :last-name "PI:NAME:<NAME>END_PI", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "PI:PASSWORD:<PASSWORD>END_PI", :username "snielsen", :first-name "PI:NAME:<NAME>END_PI", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "PI:EMAIL:<EMAIL>END_PI", :last-name "PI:NAME:<NAME>END_PI", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "PI:PASSWORD:<PASSWORD>END_PI", :username "brayden", :first-name "PI:NAME:<NAME>END_PI", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "PI:EMAIL:<EMAIL>END_PI", :last-name "PI:NAME:<NAME>END_PI", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "PI:PASSWORD:<PASSWORD>END_PI", :username "torres", :first-name "PI:NAME:<NAME>END_PI", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "PI:EMAIL:<EMAIL>END_PI", :last-name "PI:NAME:<NAME>END_PI", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "PI:PASSWORD:<PASSWORD>END_PI", :username "alyssa529", :first-name "PI:NAME:<NAME>END_PI", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "PI:EMAIL:<EMAIL>END_PI", :last-name "PI:NAME:<NAME>END_PI", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "PI:PASSWORD:<PASSWORD>END_PI", :username "luke222", :first-name "PI:NAME:<NAME>END_PI", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "PI:EMAIL:<EMAIL>END_PI", :last-name "PI:NAME:<NAME>END_PI", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "PI:PASSWORD:<PASSWORD>END_PI", :username "zachary734", :first-name "PI:NAME:<NAME>END_PI", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "PI:EMAIL:<EMAIL>END_PI", :last-name "PI:NAME:<NAME>END_PI", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "PI:PASSWORD:<PASSWORD>END_PI", :username "landon", :first-name "PI:NAME:<NAME>END_PI", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "PI:EMAIL:<EMAIL>END_PI", :last-name "PI:NAME:<NAME>END_PI", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "PI:PASSWORD:<PASSWORD>END_PI", :username "angel", :first-name "PI:NAME:<NAME>END_PI", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "PI:EMAIL:<EMAIL>END_PI", :last-name "PI:NAME:<NAME>END_PI", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "PI:PASSWORD:<PASSWORD>END_PI", :username "kayden278", :first-name "PI:NAME:<NAME>END_PI", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "PI:EMAIL:<EMAIL>END_PI", :last-name "PI:NAME:<NAME>END_PI", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "PI:PASSWORD:<PASSWORD>END_PI", :username "patrick", :first-name "PI:NAME:<NAME>END_PI", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "PI:EMAIL:<EMAIL>END_PI", :last-name "PI:NAME:<NAME>END_PI", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "PI:PASSWORD:<PASSWORD>END_PI", :username "bentley", :first-name "PI:NAME:<NAME>END_PI", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "PI:EMAIL:<EMAIL>END_PI", :last-name "PI:NAME:<NAME>END_PI", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "PI:PASSWORD:<PASSWORD>END_PI", :username "glindsey", :first-name "PI:NAME:<NAME>END_PI", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:email "PI:EMAIL:<EMAIL>END_PI", :last-name "PI:NAME:<NAME>END_PI", :group "Example", :realm-roles ["employee" "manager" "example-admin" "org-admin" "group-admin" "api-consumer"], :password "PI:PASSWORD:<PASSWORD>END_PI", :username "mccall", :first-name "PI:NAME:<NAME>END_PI", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}
{:last-name "PI:NAME:<NAME>END_PI", :group "Example", :realm-roles ["employee" "manager" "example-admin"], :password "PI:PASSWORD:<PASSWORD>END_PI", :username "testaccount", :first-name "PI:NAME:<NAME>END_PI", :attributes {"org-ref" ["Example"]}, :in-subgroups ["IT"]}]}])
(deftest ^:integration vault-test
(testing "Hashicorp vault"
)
(testing "Google secret manager "
;;this test needs the environment variable GOOGLE_APPLICATION_CREDENTIALS defined with value as the path of the JSON file that contains your service account key.
(let [realm-name (str "test-realm-" (rand-int 1000))]
(doseq [realm-data static-realm-data]
(starter/init! admin-client (assoc-in realm-data [:realm :name] realm-name) (assoc infra-context :vault google-sm-vault))
(let [vault (google-vault/->GoogleSecretManager (:project-id google-sm-vault))]
(doseq [{:keys [name public?] :as client} (:clients realm-data)]
(let [secret-value (vault/read-secret vault name)]
;(println "secret-value" secret-value)
(when (not public?)
(fact secret-value => (comp not str/blank?)))))))
(testing "realm deletion"
(delete-realm! admin-client realm-name)
(is (thrown? javax.ws.rs.NotFoundException (get-realm admin-client realm-name)))
))))
(deftest ^:integration starter-reconciliation-test
(testing "Applying a full configuration to an empty realm"
(let [realm-name (str "reconciliation-test-realm" (rand-int 1000))
config (first (clojure.edn/read-string (slurp "resources/config-init-realm.edn")))]
(starter/init! admin-client (assoc-in config [:realm :name] realm-name) infra-context {:dry-run? false :apply-deletions? true})
(println "roles")
(pp/pprint (:roles config))
(testing "Getting a plan should now be empty"
(let [users-plan (reconciliation/users-plan admin-client realm-name (:users config))
groups-plan (reconciliation/groups-plan admin-client realm-name (:groups config))
role-mappings-plan (reconciliation/role-mappings-plan admin-client realm-name (:roles config) (utils/associate-by :username (:users config)))]
(facts (get users-plan :users/additions) => empty?
(get users-plan :users/deletions) => empty?
(get users-plan :users/updates) => empty?
(get groups-plan :groups/additions) => empty?
(get groups-plan :groups/deletions) => empty?
(get role-mappings-plan :realm-role-mappings/additions) => empty?
(get role-mappings-plan :realm-role-mappings/deletions) => empty?)))
(testing "apply again the same configuration"
(starter/init! admin-client (assoc-in config [:realm :name] realm-name) infra-context {:dry-run? true :apply-deletions? true}))
(testing "realm deletion"
(delete-realm! admin-client realm-name)
(is (thrown? javax.ws.rs.NotFoundException (get-realm admin-client realm-name)))))))
(deftest config-test
(let [environment (sci/new-var 'environment "staging")
applications (sci/new-var 'applications [{:name "myapp"
:version "1.2.3"
:clients-uris [{:client-id "api-client"
:public? true
:root "https://api.example.com"
:base "/"
:redirects ["https://api.example.com/*"]
:origins ["https://api.example.com"]}
{:client-id "backend"
:public? false
:root "https://backend.example.com"
:base "/"
:redirects ["https://backend.example.com/*"]
:origins ["https://backend.example.com"]}]}])
color (sci/new-var 'color "red")
config-code (slurp "resources/realm-config-clients.clj")
config-data (sci/eval-string config-code {:bindings {'environment environment
'applications applications
'color color}})]
(fact config-data => [{:realm {:name "example2"},
:clients [{:name "api-client" :redirect-uris ["https://api.example.com/*"], :base-url "/" :web-origins ["https://api.example.com"], :public? true, :root-url "https://api.example.com"}
{:name "backend" :redirect-uris ["https://backend.example.com/*"], :base-url "/" :web-origins ["https://backend.example.com"], :public? false, :root-url "https://backend.example.com"}]}])))
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-09-08\"\n :doc \"Tests for zana.ge",
"end": 105,
"score": 0.9998778700828552,
"start": 87,
"tag": "NAME",
"value": "John Alan McDonald"
}
] | src/test/clojure/zana/test/geometry/z1.clj | wahpenayo/zana | 2 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "John Alan McDonald" :date "2016-09-08"
:doc "Tests for zana.geometry.z1." }
zana.test.geometry.z1
(:require
[clojure.test :as test]
[zana.geometry.z1 :as z1]))
;;------------------------------------------------------------------------------
(comment
(test/run-tests 'zana.test.geometry.z1)
)
;;------------------------------------------------------------------------------
;(test/deftest destructuring
; (test/testing
; "destructuring"
; (let [i (z1/interval 0 1)
; [i0 i1] i]
; (test/is (= i0 (z1/lower i)))
; (test/is (= i1 (z1/upper i))))))
;;------------------------------------------------------------------------------ | 10624 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<NAME>" :date "2016-09-08"
:doc "Tests for zana.geometry.z1." }
zana.test.geometry.z1
(:require
[clojure.test :as test]
[zana.geometry.z1 :as z1]))
;;------------------------------------------------------------------------------
(comment
(test/run-tests 'zana.test.geometry.z1)
)
;;------------------------------------------------------------------------------
;(test/deftest destructuring
; (test/testing
; "destructuring"
; (let [i (z1/interval 0 1)
; [i0 i1] i]
; (test/is (= i0 (z1/lower i)))
; (test/is (= i1 (z1/upper i))))))
;;------------------------------------------------------------------------------ | true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-09-08"
:doc "Tests for zana.geometry.z1." }
zana.test.geometry.z1
(:require
[clojure.test :as test]
[zana.geometry.z1 :as z1]))
;;------------------------------------------------------------------------------
(comment
(test/run-tests 'zana.test.geometry.z1)
)
;;------------------------------------------------------------------------------
;(test/deftest destructuring
; (test/testing
; "destructuring"
; (let [i (z1/interval 0 1)
; [i0 i1] i]
; (test/is (= i0 (z1/lower i)))
; (test/is (= i1 (z1/upper i))))))
;;------------------------------------------------------------------------------ |
[
{
"context": "ts manipulating text and strings.\"\n :author \"Sean Dawson\"}\n nanoweave.ast.text\n (:require [schema.core :a",
"end": 93,
"score": 0.9998348951339722,
"start": 82,
"tag": "NAME",
"value": "Sean Dawson"
}
] | src/nanoweave/ast/text.clj | NoxHarmonium/nanoweave | 0 | (ns ^{:doc "Syntax that represents manipulating text and strings."
:author "Sean Dawson"}
nanoweave.ast.text
(:require [schema.core :as s]
[nanoweave.ast.base :refer [Resolvable]]))
(s/defrecord InterpolatedString [body :- [Resolvable]])
(s/defrecord Regex [regex :- [java.util.regex.Pattern]])
| 82541 | (ns ^{:doc "Syntax that represents manipulating text and strings."
:author "<NAME>"}
nanoweave.ast.text
(:require [schema.core :as s]
[nanoweave.ast.base :refer [Resolvable]]))
(s/defrecord InterpolatedString [body :- [Resolvable]])
(s/defrecord Regex [regex :- [java.util.regex.Pattern]])
| true | (ns ^{:doc "Syntax that represents manipulating text and strings."
:author "PI:NAME:<NAME>END_PI"}
nanoweave.ast.text
(:require [schema.core :as s]
[nanoweave.ast.base :refer [Resolvable]]))
(s/defrecord InterpolatedString [body :- [Resolvable]])
(s/defrecord Regex [regex :- [java.util.regex.Pattern]])
|
[
{
"context": "al Day\" :date (t/date \"2020-05-25\")}\n {:name \"Thanksgiving\" :date (t/date \"2020-11-26\")}\n {:name \"Columb",
"end": 1159,
"score": 0.7911236882209778,
"start": 1147,
"tag": "NAME",
"value": "Thanksgiving"
}
] | test/com/piposaude/calenjars/nth_day_of_week_test.clj | piposaude/calenjars | 3 | (ns com.piposaude.calenjars.nth-day-of-week-test
(:require [clojure.test :refer :all]
[tick.alpha.api :as t]
[com.piposaude.calenjars.holidays :as gen]))
(deftest should-generate-holidays-when-holidays-for-year-with-nth-day-of-week-rule
(are [expected year]
(= expected (gen/holidays-for-year year "test-resources/generate/nth-day-of-week.hol"))
[{:name "Memorial Day" :date (t/date "2016-05-30")}
{:name "Thanksgiving" :date (t/date "2016-11-24")}
{:name "Columbus Day" :date (t/date "2016-10-10")}] 2016
[{:name "Memorial Day" :date (t/date "2017-05-29")}
{:name "Thanksgiving" :date (t/date "2017-11-23")}
{:name "Columbus Day" :date (t/date "2017-10-09")}] 2017
[{:name "Memorial Day" :date (t/date "2018-05-28")}
{:name "Thanksgiving" :date (t/date "2018-11-22")}
{:name "Columbus Day" :date (t/date "2018-10-08")}] 2018
[{:name "Memorial Day" :date (t/date "2019-05-27")}
{:name "Thanksgiving" :date (t/date "2019-11-28")}
{:name "Columbus Day" :date (t/date "2019-10-14")}] 2019
[{:name "Memorial Day" :date (t/date "2020-05-25")}
{:name "Thanksgiving" :date (t/date "2020-11-26")}
{:name "Columbus Day" :date (t/date "2020-10-12")}] 2020)
(are [expected year]
(= expected (gen/holidays-for-year year "test-resources/generate/nth-day-of-week-limit-cases.hol"))
[{:name "Inexistent Holiday 1" :date (t/date "2021-05-03")}
{:name "Inexistent Holiday 2" :date (t/date "2021-05-10")}
{:name "Inexistent Holiday 3" :date (t/date "2021-05-17")}
{:name "Inexistent Holiday 4" :date (t/date "2021-05-24")}
{:name "Inexistent Holiday 5" :date (t/date "2021-05-31")}
{:name "Inexistent Holiday -1" :date (t/date "2021-05-31")}
{:name "Inexistent Holiday -2" :date (t/date "2021-05-24")}
{:name "Inexistent Holiday -3" :date (t/date "2021-05-17")}
{:name "Inexistent Holiday -4" :date (t/date "2021-05-10")}
{:name "Inexistent Holiday -5" :date (t/date "2021-05-03")}] 2021
[{:name "Inexistent Holiday 1" :date (t/date "2019-05-06")}
{:name "Inexistent Holiday 2" :date (t/date "2019-05-13")}
{:name "Inexistent Holiday 3" :date (t/date "2019-05-20")}
{:name "Inexistent Holiday 4" :date (t/date "2019-05-27")}
{:name "Inexistent Holiday -1" :date (t/date "2019-05-27")}
{:name "Inexistent Holiday -2" :date (t/date "2019-05-20")}
{:name "Inexistent Holiday -3" :date (t/date "2019-05-13")}
{:name "Inexistent Holiday -4" :date (t/date "2019-05-06")}] 2019))
(deftest should-generate-holidays-when-holidays-for-year-with-nth-day-of-week-rule-and-exception
(are [expected year]
(= expected (gen/holidays-for-year year "test-resources/generate/nth-day-of-week-exception.hol"))
[{:name "Memorial Day" :date (t/date "2016-05-30")}] 2016
[{:name "Memorial Day" :date (t/date "2017-05-29")}] 2017
[{:name "Memorial Day" :date (t/date "2018-05-28")}] 2018
[] 2019
[{:name "Memorial Day" :date (t/date "2020-05-25")}] 2020))
(deftest should-generate-holidays-only-after-specified-yer-when-holidays-for-year-with-nth-day-of-week-rule-and-start-clause
(are [expected year]
(= expected (gen/holidays-for-year year "test-resources/generate/nth-day-of-week-start.hol"))
[] 2016
[] 2017
[{:name "Memorial Day" :date (t/date "2018-05-28")}] 2018
[{:name "Memorial Day" :date (t/date "2019-05-27")}] 2019
[{:name "Memorial Day" :date (t/date "2020-05-25")}] 2020))
(deftest should-generate-holidays-only-after-specified-yer-when-holidays-for-year-with-nth-day-of-week-rule-and-start-clause-and-exception
(are [expected year]
(= expected (gen/holidays-for-year year "test-resources/generate/nth-day-of-week-start-exception.hol"))
[] 2016
[] 2017
[{:name "Memorial Day" :date (t/date "2018-05-28")}] 2018
[{:name "Memorial Day" :date (t/date "2019-05-27")}] 2019
[] 2020))
| 44115 | (ns com.piposaude.calenjars.nth-day-of-week-test
(:require [clojure.test :refer :all]
[tick.alpha.api :as t]
[com.piposaude.calenjars.holidays :as gen]))
(deftest should-generate-holidays-when-holidays-for-year-with-nth-day-of-week-rule
(are [expected year]
(= expected (gen/holidays-for-year year "test-resources/generate/nth-day-of-week.hol"))
[{:name "Memorial Day" :date (t/date "2016-05-30")}
{:name "Thanksgiving" :date (t/date "2016-11-24")}
{:name "Columbus Day" :date (t/date "2016-10-10")}] 2016
[{:name "Memorial Day" :date (t/date "2017-05-29")}
{:name "Thanksgiving" :date (t/date "2017-11-23")}
{:name "Columbus Day" :date (t/date "2017-10-09")}] 2017
[{:name "Memorial Day" :date (t/date "2018-05-28")}
{:name "Thanksgiving" :date (t/date "2018-11-22")}
{:name "Columbus Day" :date (t/date "2018-10-08")}] 2018
[{:name "Memorial Day" :date (t/date "2019-05-27")}
{:name "Thanksgiving" :date (t/date "2019-11-28")}
{:name "Columbus Day" :date (t/date "2019-10-14")}] 2019
[{:name "Memorial Day" :date (t/date "2020-05-25")}
{:name "<NAME>" :date (t/date "2020-11-26")}
{:name "Columbus Day" :date (t/date "2020-10-12")}] 2020)
(are [expected year]
(= expected (gen/holidays-for-year year "test-resources/generate/nth-day-of-week-limit-cases.hol"))
[{:name "Inexistent Holiday 1" :date (t/date "2021-05-03")}
{:name "Inexistent Holiday 2" :date (t/date "2021-05-10")}
{:name "Inexistent Holiday 3" :date (t/date "2021-05-17")}
{:name "Inexistent Holiday 4" :date (t/date "2021-05-24")}
{:name "Inexistent Holiday 5" :date (t/date "2021-05-31")}
{:name "Inexistent Holiday -1" :date (t/date "2021-05-31")}
{:name "Inexistent Holiday -2" :date (t/date "2021-05-24")}
{:name "Inexistent Holiday -3" :date (t/date "2021-05-17")}
{:name "Inexistent Holiday -4" :date (t/date "2021-05-10")}
{:name "Inexistent Holiday -5" :date (t/date "2021-05-03")}] 2021
[{:name "Inexistent Holiday 1" :date (t/date "2019-05-06")}
{:name "Inexistent Holiday 2" :date (t/date "2019-05-13")}
{:name "Inexistent Holiday 3" :date (t/date "2019-05-20")}
{:name "Inexistent Holiday 4" :date (t/date "2019-05-27")}
{:name "Inexistent Holiday -1" :date (t/date "2019-05-27")}
{:name "Inexistent Holiday -2" :date (t/date "2019-05-20")}
{:name "Inexistent Holiday -3" :date (t/date "2019-05-13")}
{:name "Inexistent Holiday -4" :date (t/date "2019-05-06")}] 2019))
(deftest should-generate-holidays-when-holidays-for-year-with-nth-day-of-week-rule-and-exception
(are [expected year]
(= expected (gen/holidays-for-year year "test-resources/generate/nth-day-of-week-exception.hol"))
[{:name "Memorial Day" :date (t/date "2016-05-30")}] 2016
[{:name "Memorial Day" :date (t/date "2017-05-29")}] 2017
[{:name "Memorial Day" :date (t/date "2018-05-28")}] 2018
[] 2019
[{:name "Memorial Day" :date (t/date "2020-05-25")}] 2020))
(deftest should-generate-holidays-only-after-specified-yer-when-holidays-for-year-with-nth-day-of-week-rule-and-start-clause
(are [expected year]
(= expected (gen/holidays-for-year year "test-resources/generate/nth-day-of-week-start.hol"))
[] 2016
[] 2017
[{:name "Memorial Day" :date (t/date "2018-05-28")}] 2018
[{:name "Memorial Day" :date (t/date "2019-05-27")}] 2019
[{:name "Memorial Day" :date (t/date "2020-05-25")}] 2020))
(deftest should-generate-holidays-only-after-specified-yer-when-holidays-for-year-with-nth-day-of-week-rule-and-start-clause-and-exception
(are [expected year]
(= expected (gen/holidays-for-year year "test-resources/generate/nth-day-of-week-start-exception.hol"))
[] 2016
[] 2017
[{:name "Memorial Day" :date (t/date "2018-05-28")}] 2018
[{:name "Memorial Day" :date (t/date "2019-05-27")}] 2019
[] 2020))
| true | (ns com.piposaude.calenjars.nth-day-of-week-test
(:require [clojure.test :refer :all]
[tick.alpha.api :as t]
[com.piposaude.calenjars.holidays :as gen]))
(deftest should-generate-holidays-when-holidays-for-year-with-nth-day-of-week-rule
(are [expected year]
(= expected (gen/holidays-for-year year "test-resources/generate/nth-day-of-week.hol"))
[{:name "Memorial Day" :date (t/date "2016-05-30")}
{:name "Thanksgiving" :date (t/date "2016-11-24")}
{:name "Columbus Day" :date (t/date "2016-10-10")}] 2016
[{:name "Memorial Day" :date (t/date "2017-05-29")}
{:name "Thanksgiving" :date (t/date "2017-11-23")}
{:name "Columbus Day" :date (t/date "2017-10-09")}] 2017
[{:name "Memorial Day" :date (t/date "2018-05-28")}
{:name "Thanksgiving" :date (t/date "2018-11-22")}
{:name "Columbus Day" :date (t/date "2018-10-08")}] 2018
[{:name "Memorial Day" :date (t/date "2019-05-27")}
{:name "Thanksgiving" :date (t/date "2019-11-28")}
{:name "Columbus Day" :date (t/date "2019-10-14")}] 2019
[{:name "Memorial Day" :date (t/date "2020-05-25")}
{:name "PI:NAME:<NAME>END_PI" :date (t/date "2020-11-26")}
{:name "Columbus Day" :date (t/date "2020-10-12")}] 2020)
(are [expected year]
(= expected (gen/holidays-for-year year "test-resources/generate/nth-day-of-week-limit-cases.hol"))
[{:name "Inexistent Holiday 1" :date (t/date "2021-05-03")}
{:name "Inexistent Holiday 2" :date (t/date "2021-05-10")}
{:name "Inexistent Holiday 3" :date (t/date "2021-05-17")}
{:name "Inexistent Holiday 4" :date (t/date "2021-05-24")}
{:name "Inexistent Holiday 5" :date (t/date "2021-05-31")}
{:name "Inexistent Holiday -1" :date (t/date "2021-05-31")}
{:name "Inexistent Holiday -2" :date (t/date "2021-05-24")}
{:name "Inexistent Holiday -3" :date (t/date "2021-05-17")}
{:name "Inexistent Holiday -4" :date (t/date "2021-05-10")}
{:name "Inexistent Holiday -5" :date (t/date "2021-05-03")}] 2021
[{:name "Inexistent Holiday 1" :date (t/date "2019-05-06")}
{:name "Inexistent Holiday 2" :date (t/date "2019-05-13")}
{:name "Inexistent Holiday 3" :date (t/date "2019-05-20")}
{:name "Inexistent Holiday 4" :date (t/date "2019-05-27")}
{:name "Inexistent Holiday -1" :date (t/date "2019-05-27")}
{:name "Inexistent Holiday -2" :date (t/date "2019-05-20")}
{:name "Inexistent Holiday -3" :date (t/date "2019-05-13")}
{:name "Inexistent Holiday -4" :date (t/date "2019-05-06")}] 2019))
(deftest should-generate-holidays-when-holidays-for-year-with-nth-day-of-week-rule-and-exception
(are [expected year]
(= expected (gen/holidays-for-year year "test-resources/generate/nth-day-of-week-exception.hol"))
[{:name "Memorial Day" :date (t/date "2016-05-30")}] 2016
[{:name "Memorial Day" :date (t/date "2017-05-29")}] 2017
[{:name "Memorial Day" :date (t/date "2018-05-28")}] 2018
[] 2019
[{:name "Memorial Day" :date (t/date "2020-05-25")}] 2020))
(deftest should-generate-holidays-only-after-specified-yer-when-holidays-for-year-with-nth-day-of-week-rule-and-start-clause
(are [expected year]
(= expected (gen/holidays-for-year year "test-resources/generate/nth-day-of-week-start.hol"))
[] 2016
[] 2017
[{:name "Memorial Day" :date (t/date "2018-05-28")}] 2018
[{:name "Memorial Day" :date (t/date "2019-05-27")}] 2019
[{:name "Memorial Day" :date (t/date "2020-05-25")}] 2020))
(deftest should-generate-holidays-only-after-specified-yer-when-holidays-for-year-with-nth-day-of-week-rule-and-start-clause-and-exception
(are [expected year]
(= expected (gen/holidays-for-year year "test-resources/generate/nth-day-of-week-start-exception.hol"))
[] 2016
[] 2017
[{:name "Memorial Day" :date (t/date "2018-05-28")}] 2018
[{:name "Memorial Day" :date (t/date "2019-05-27")}] 2019
[] 2020))
|
[
{
"context": "ions and limitations there under.\n\n;;;; Author: Alex Dean (mailto:support@snowplowanalytics.com)\n;;;; Copyr",
"end": 744,
"score": 0.9998502731323242,
"start": 735,
"tag": "NAME",
"value": "Alex Dean"
},
{
"context": "s there under.\n\n;;;; Author: Alex Dean (mailto:support@snowplowanalytics.com)\n;;;; Copyright: Copyright (c) 2012-2018 Snowplow",
"end": 782,
"score": 0.9999279975891113,
"start": 753,
"tag": "EMAIL",
"value": "support@snowplowanalytics.com"
}
] | 2-collectors/clojure-collector/java-servlet/project.clj | whitemike889/snowplow | 0 | ;;;; Copyright (c) 2012-2018 Snowplow Analytics Ltd. All rights reserved.
;;;;
;;;; This program is licensed to you under the Apache License Version 2.0,
;;;; and you may not use this file except in compliance with the Apache License Version 2.0.
;;;; You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
;;;;
;;;; Unless required by applicable law or agreed to in writing,
;;;; software distributed under the Apache License Version 2.0 is distributed on an
;;;; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;;; See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
;;;; Author: Alex Dean (mailto:support@snowplowanalytics.com)
;;;; Copyright: Copyright (c) 2012-2018 Snowplow Analytics Ltd
;;;; License: Apache License Version 2.0
(defproject snowplow/clojure-collector "2.1.2" ;; MUST also bump version in server.xml
:license {:name "Apache Version 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0"}
:description "A SnowPlow event collector written in Clojure. AWS Elastic Beanstalk compatible."
:dependencies [[org.clojure/clojure "1.9.0"]
[ring/ring-core "1.6.3"]
[ring/ring-devel "1.6.3"]
[compojure "1.6.1"]
[metrics-clojure "2.10.0"]
[metrics-clojure-ring "2.10.0"]
[commons-codec/commons-codec "1.11"]]
;; The jetty adapter is only used during development
:profiles {:dev {:dependencies [[ring/ring-jetty-adapter "1.6.3"]]}}
:war-resources-path "war-resources"
:plugins [[lein-ring "0.12.4"]]
:ring {:handler snowplow.clojure-collector.beanstalk/app}) ; .beanstalk -> .core if you don't need Beanstalk support
| 54943 | ;;;; Copyright (c) 2012-2018 Snowplow Analytics Ltd. All rights reserved.
;;;;
;;;; This program is licensed to you under the Apache License Version 2.0,
;;;; and you may not use this file except in compliance with the Apache License Version 2.0.
;;;; You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
;;;;
;;;; Unless required by applicable law or agreed to in writing,
;;;; software distributed under the Apache License Version 2.0 is distributed on an
;;;; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;;; See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
;;;; Author: <NAME> (mailto:<EMAIL>)
;;;; Copyright: Copyright (c) 2012-2018 Snowplow Analytics Ltd
;;;; License: Apache License Version 2.0
(defproject snowplow/clojure-collector "2.1.2" ;; MUST also bump version in server.xml
:license {:name "Apache Version 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0"}
:description "A SnowPlow event collector written in Clojure. AWS Elastic Beanstalk compatible."
:dependencies [[org.clojure/clojure "1.9.0"]
[ring/ring-core "1.6.3"]
[ring/ring-devel "1.6.3"]
[compojure "1.6.1"]
[metrics-clojure "2.10.0"]
[metrics-clojure-ring "2.10.0"]
[commons-codec/commons-codec "1.11"]]
;; The jetty adapter is only used during development
:profiles {:dev {:dependencies [[ring/ring-jetty-adapter "1.6.3"]]}}
:war-resources-path "war-resources"
:plugins [[lein-ring "0.12.4"]]
:ring {:handler snowplow.clojure-collector.beanstalk/app}) ; .beanstalk -> .core if you don't need Beanstalk support
| true | ;;;; Copyright (c) 2012-2018 Snowplow Analytics Ltd. All rights reserved.
;;;;
;;;; This program is licensed to you under the Apache License Version 2.0,
;;;; and you may not use this file except in compliance with the Apache License Version 2.0.
;;;; You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
;;;;
;;;; Unless required by applicable law or agreed to in writing,
;;;; software distributed under the Apache License Version 2.0 is distributed on an
;;;; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;;; See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
;;;; Author: PI:NAME:<NAME>END_PI (mailto:PI:EMAIL:<EMAIL>END_PI)
;;;; Copyright: Copyright (c) 2012-2018 Snowplow Analytics Ltd
;;;; License: Apache License Version 2.0
(defproject snowplow/clojure-collector "2.1.2" ;; MUST also bump version in server.xml
:license {:name "Apache Version 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0"}
:description "A SnowPlow event collector written in Clojure. AWS Elastic Beanstalk compatible."
:dependencies [[org.clojure/clojure "1.9.0"]
[ring/ring-core "1.6.3"]
[ring/ring-devel "1.6.3"]
[compojure "1.6.1"]
[metrics-clojure "2.10.0"]
[metrics-clojure-ring "2.10.0"]
[commons-codec/commons-codec "1.11"]]
;; The jetty adapter is only used during development
:profiles {:dev {:dependencies [[ring/ring-jetty-adapter "1.6.3"]]}}
:war-resources-path "war-resources"
:plugins [[lein-ring "0.12.4"]]
:ring {:handler snowplow.clojure-collector.beanstalk/app}) ; .beanstalk -> .core if you don't need Beanstalk support
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.9998092651367188,
"start": 96,
"tag": "NAME",
"value": "Ragnar Svensson"
},
{
"context": "-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold License version 1.0 ",
"end": 129,
"score": 0.9998301267623901,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
}
] | editor/src/clj/util/profiler.clj | cmarincia/defold | 0 | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 Ragnar Svensson, Christian Murray
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns util.profiler
(:import [com.defold.util Profiler]))
(set! *warn-on-reflection* true)
(defmacro profile
[name user & body]
`(let [s# (Profiler/begin ~name ~user)]
(try
~@body
(finally
(Profiler/end s#)))))
(defn begin-frame []
(Profiler/beginFrame))
(defn dump-json []
(Profiler/dumpJson))
| 116171 | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 <NAME>, <NAME>
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns util.profiler
(:import [com.defold.util Profiler]))
(set! *warn-on-reflection* true)
(defmacro profile
[name user & body]
`(let [s# (Profiler/begin ~name ~user)]
(try
~@body
(finally
(Profiler/end s#)))))
(defn begin-frame []
(Profiler/beginFrame))
(defn dump-json []
(Profiler/dumpJson))
| true | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns util.profiler
(:import [com.defold.util Profiler]))
(set! *warn-on-reflection* true)
(defmacro profile
[name user & body]
`(let [s# (Profiler/begin ~name ~user)]
(try
~@body
(finally
(Profiler/end s#)))))
(defn begin-frame []
(Profiler/beginFrame))
(defn dump-json []
(Profiler/dumpJson))
|
[
{
"context": "= [] (people/get-all* @conn)))\n (is (= [{:name \"yest\"\n :email \"test@test.com\"\n :",
"end": 883,
"score": 0.9972002506256104,
"start": 879,
"tag": "USERNAME",
"value": "yest"
},
{
"context": "n)))\n (is (= [{:name \"yest\"\n :email \"test@test.com\"\n :entity-id #uuid \"92731758-98f9-435",
"end": 918,
"score": 0.9999099969863892,
"start": 905,
"tag": "EMAIL",
"value": "test@test.com"
},
{
"context": "19-06-24\")}]\n (people/add* @conn {:name \"yest\"\n :email \"test@test.",
"end": 1209,
"score": 0.9965126514434814,
"start": 1205,
"tag": "USERNAME",
"value": "yest"
},
{
"context": "name \"yest\"\n :email \"test@test.com\"\n :entity-id #uuid ",
"end": 1262,
"score": 0.9999191164970398,
"start": 1249,
"tag": "EMAIL",
"value": "test@test.com"
},
{
"context": "e/->date-time \"2019-06-24\")})))\n (is (= [{:name \"who\"\n :email \"dat@test.com\"\n :ent",
"end": 1607,
"score": 0.9955676198005676,
"start": 1604,
"tag": "USERNAME",
"value": "who"
},
{
"context": "4\")})))\n (is (= [{:name \"who\"\n :email \"dat@test.com\"\n :entity-id #uuid \"92731758-98f9-4358",
"end": 1640,
"score": 0.9999226331710815,
"start": 1628,
"tag": "EMAIL",
"value": "dat@test.com"
},
{
"context": "00:13:24Z\")}]\n (people/add* @conn {:name \"who\"\n :email \"dat@test.co",
"end": 1895,
"score": 0.9965012669563293,
"start": 1892,
"tag": "USERNAME",
"value": "who"
},
{
"context": "{:name \"who\"\n :email \"dat@test.com\"\n :entity-id #uuid \"",
"end": 1946,
"score": 0.9999227523803711,
"start": 1934,
"tag": "EMAIL",
"value": "dat@test.com"
},
{
"context": "inst \"2018-03-12T00:13:24Z\"})))\n (is (= [{:name \"who\"\n :email \"dat@test.com\"\n :ent",
"end": 2240,
"score": 0.9928638935089111,
"start": 2237,
"tag": "USERNAME",
"value": "who"
},
{
"context": "4Z\"})))\n (is (= [{:name \"who\"\n :email \"dat@test.com\"\n :entity-id #uuid \"92731758-98f9-4358",
"end": 2273,
"score": 0.9999226331710815,
"start": 2261,
"tag": "EMAIL",
"value": "dat@test.com"
},
{
"context": "2T00:13:24Z\")\n :id 2}\n {:name \"yest\"\n :email \"test@test.com\"\n :en",
"end": 2527,
"score": 0.9981102347373962,
"start": 2523,
"tag": "USERNAME",
"value": "yest"
},
{
"context": ":id 2}\n {:name \"yest\"\n :email \"test@test.com\"\n :entity-id #uuid \"92731758-98f9-4358",
"end": 2561,
"score": 0.9999225735664368,
"start": 2548,
"tag": "EMAIL",
"value": "test@test.com"
},
{
"context": " (people/get-all* @conn)))\n (is (= [{:name \"yest\"\n :id 1\n :email \"test@test.co",
"end": 2882,
"score": 0.8720089197158813,
"start": 2878,
"tag": "USERNAME",
"value": "yest"
},
{
"context": "{:name \"yest\"\n :id 1\n :email \"test@test.com\"\n :entity-id #uuid \"92731758-98f9-4358",
"end": 2933,
"score": 0.9999241828918457,
"start": 2920,
"tag": "EMAIL",
"value": "test@test.com"
},
{
"context": "6-24\")}]\n (people/get-all* @conn {:email \"test@test.com\"})))\n (is (= 1\n (people/set-email* @conn",
"end": 3234,
"score": 0.9999245405197144,
"start": 3221,
"tag": "EMAIL",
"value": "test@test.com"
},
{
"context": " 1\n (people/set-email* @conn {:old-email \"test@test.com\"\n :new-email \"t",
"end": 3311,
"score": 0.999923586845398,
"start": 3298,
"tag": "EMAIL",
"value": "test@test.com"
},
{
"context": "m\"\n :new-email \"test2@test.com\"})))\n (is (= 1\n (people/delete* @conn {:",
"end": 3374,
"score": 0.9999198913574219,
"start": 3360,
"tag": "EMAIL",
"value": "test2@test.com"
},
{
"context": " (is (= 1\n (people/delete* @conn {:email \"dat@test.com\"})))\n (is (= {:count 1}\n (people/count-a",
"end": 3443,
"score": 0.9999249577522278,
"start": 3431,
"tag": "EMAIL",
"value": "dat@test.com"
},
{
"context": "array-coercions\n (people/add-user* @conn {:name \"yest\"})\n (people/add-user* @conn {:name \"who\"})\n (le",
"end": 3572,
"score": 0.8631930351257324,
"start": 3568,
"tag": "NAME",
"value": "yest"
},
{
"context": " (is (= 1 (count (people/get-squad* @conn {:name \"test\"}))))\n (is (= [{:name \"test\"\n :pee",
"end": 3796,
"score": 0.5561901330947876,
"start": 3792,
"tag": "NAME",
"value": "test"
},
{
"context": "names* @conn {:name \"test\"})))\n (is (= {:name \"test\"\n :peeps [{:id 1 :name \"yest\"}\n ",
"end": 3949,
"score": 0.5409150719642639,
"start": 3945,
"tag": "NAME",
"value": "test"
},
{
"context": "= {:name \"test\"\n :peeps [{:id 1 :name \"yest\"}\n {:id 2 :name \"who\"}]}\n ",
"end": 3989,
"score": 0.8592954874038696,
"start": 3985,
"tag": "NAME",
"value": "yest"
}
] | test/utility_belt/sql/core_test.clj | nomnom-insights/nomnom.utility-belt.sql | 2 | (ns utility-belt.sql.core-test
(:require
[clj-time.coerce :as coerce]
[clojure.test :refer [deftest is use-fixtures]]
;; -- test helpers
[utility-belt.sql.connection :as connection]
[utility-belt.sql.conv]
[utility-belt.sql.people :as people]
;; -- actual things under test
[utility-belt.time :as time]))
(def conn (atom nil))
(use-fixtures :each (fn [test-fn]
(connection/start! conn)
(try
(people/setup* @conn)
(people/setup-squad* @conn)
(people/setup-users* @conn)
(people/delete-all* @conn)
(test-fn)
(finally
(connection/stop! conn)))))
(deftest crud-operations
(is (= [] (people/get-all* @conn)))
(is (= [{:name "yest"
:email "test@test.com"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo ["a" "b" "c" "92731758-98f9-4358-974b-b15c74c917d9"]}
:confirmed-at (coerce/to-date-time "2019-06-24")}]
(people/add* @conn {:name "yest"
:email "test@test.com"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo [:a :b :c #uuid "92731758-98f9-4358-974b-b15c74c917d9"]}
:confirmed-at (time/->date-time "2019-06-24")})))
(is (= [{:name "who"
:email "dat@test.com"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d0"
:attributes {:bar 1
:foo {:ok "dawg"}}
:confirmed-at (coerce/to-date-time "2018-03-12T00:13:24Z")}]
(people/add* @conn {:name "who"
:email "dat@test.com"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d0"
:attributes {:bar 1
:foo {:ok :dawg}}
:confirmed-at #inst "2018-03-12T00:13:24Z"})))
(is (= [{:name "who"
:email "dat@test.com"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d0"
:attributes {:bar 1
:foo {:ok "dawg"}}
:confirmed-at (coerce/to-date-time "2018-03-12T00:13:24Z")
:id 2}
{:name "yest"
:email "test@test.com"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo ["a" "b" "c" "92731758-98f9-4358-974b-b15c74c917d9"]}
:confirmed-at (coerce/to-date-time "2019-06-24")
:id 1}]
(people/get-all* @conn)))
(is (= [{:name "yest"
:id 1
:email "test@test.com"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo ["a" "b" "c" "92731758-98f9-4358-974b-b15c74c917d9"]}
:confirmed-at (coerce/to-date-time "2019-06-24")}]
(people/get-all* @conn {:email "test@test.com"})))
(is (= 1
(people/set-email* @conn {:old-email "test@test.com"
:new-email "test2@test.com"})))
(is (= 1
(people/delete* @conn {:email "dat@test.com"})))
(is (= {:count 1}
(people/count-all* @conn))))
(deftest array-coercions
(people/add-user* @conn {:name "yest"})
(people/add-user* @conn {:name "who"})
(let [people (people/get-users* @conn)]
(mapv #(people/add-to-squad* @conn {:name "test" :user-id (:id %)}) people)
(is (= 1 (count (people/get-squad* @conn {:name "test"}))))
(is (= [{:name "test"
:peeps ["yest" "who"]}]
(people/get-squad-names* @conn {:name "test"})))
(is (= {:name "test"
:peeps [{:id 1 :name "yest"}
{:id 2 :name "who"}]}
(-> (people/get-squad* @conn {:name "test"})
first)))))
| 28841 | (ns utility-belt.sql.core-test
(:require
[clj-time.coerce :as coerce]
[clojure.test :refer [deftest is use-fixtures]]
;; -- test helpers
[utility-belt.sql.connection :as connection]
[utility-belt.sql.conv]
[utility-belt.sql.people :as people]
;; -- actual things under test
[utility-belt.time :as time]))
(def conn (atom nil))
(use-fixtures :each (fn [test-fn]
(connection/start! conn)
(try
(people/setup* @conn)
(people/setup-squad* @conn)
(people/setup-users* @conn)
(people/delete-all* @conn)
(test-fn)
(finally
(connection/stop! conn)))))
(deftest crud-operations
(is (= [] (people/get-all* @conn)))
(is (= [{:name "yest"
:email "<EMAIL>"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo ["a" "b" "c" "92731758-98f9-4358-974b-b15c74c917d9"]}
:confirmed-at (coerce/to-date-time "2019-06-24")}]
(people/add* @conn {:name "yest"
:email "<EMAIL>"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo [:a :b :c #uuid "92731758-98f9-4358-974b-b15c74c917d9"]}
:confirmed-at (time/->date-time "2019-06-24")})))
(is (= [{:name "who"
:email "<EMAIL>"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d0"
:attributes {:bar 1
:foo {:ok "dawg"}}
:confirmed-at (coerce/to-date-time "2018-03-12T00:13:24Z")}]
(people/add* @conn {:name "who"
:email "<EMAIL>"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d0"
:attributes {:bar 1
:foo {:ok :dawg}}
:confirmed-at #inst "2018-03-12T00:13:24Z"})))
(is (= [{:name "who"
:email "<EMAIL>"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d0"
:attributes {:bar 1
:foo {:ok "dawg"}}
:confirmed-at (coerce/to-date-time "2018-03-12T00:13:24Z")
:id 2}
{:name "yest"
:email "<EMAIL>"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo ["a" "b" "c" "92731758-98f9-4358-974b-b15c74c917d9"]}
:confirmed-at (coerce/to-date-time "2019-06-24")
:id 1}]
(people/get-all* @conn)))
(is (= [{:name "yest"
:id 1
:email "<EMAIL>"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo ["a" "b" "c" "92731758-98f9-4358-974b-b15c74c917d9"]}
:confirmed-at (coerce/to-date-time "2019-06-24")}]
(people/get-all* @conn {:email "<EMAIL>"})))
(is (= 1
(people/set-email* @conn {:old-email "<EMAIL>"
:new-email "<EMAIL>"})))
(is (= 1
(people/delete* @conn {:email "<EMAIL>"})))
(is (= {:count 1}
(people/count-all* @conn))))
(deftest array-coercions
(people/add-user* @conn {:name "<NAME>"})
(people/add-user* @conn {:name "who"})
(let [people (people/get-users* @conn)]
(mapv #(people/add-to-squad* @conn {:name "test" :user-id (:id %)}) people)
(is (= 1 (count (people/get-squad* @conn {:name "<NAME>"}))))
(is (= [{:name "test"
:peeps ["yest" "who"]}]
(people/get-squad-names* @conn {:name "test"})))
(is (= {:name "<NAME>"
:peeps [{:id 1 :name "<NAME>"}
{:id 2 :name "who"}]}
(-> (people/get-squad* @conn {:name "test"})
first)))))
| true | (ns utility-belt.sql.core-test
(:require
[clj-time.coerce :as coerce]
[clojure.test :refer [deftest is use-fixtures]]
;; -- test helpers
[utility-belt.sql.connection :as connection]
[utility-belt.sql.conv]
[utility-belt.sql.people :as people]
;; -- actual things under test
[utility-belt.time :as time]))
(def conn (atom nil))
(use-fixtures :each (fn [test-fn]
(connection/start! conn)
(try
(people/setup* @conn)
(people/setup-squad* @conn)
(people/setup-users* @conn)
(people/delete-all* @conn)
(test-fn)
(finally
(connection/stop! conn)))))
(deftest crud-operations
(is (= [] (people/get-all* @conn)))
(is (= [{:name "yest"
:email "PI:EMAIL:<EMAIL>END_PI"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo ["a" "b" "c" "92731758-98f9-4358-974b-b15c74c917d9"]}
:confirmed-at (coerce/to-date-time "2019-06-24")}]
(people/add* @conn {:name "yest"
:email "PI:EMAIL:<EMAIL>END_PI"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo [:a :b :c #uuid "92731758-98f9-4358-974b-b15c74c917d9"]}
:confirmed-at (time/->date-time "2019-06-24")})))
(is (= [{:name "who"
:email "PI:EMAIL:<EMAIL>END_PI"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d0"
:attributes {:bar 1
:foo {:ok "dawg"}}
:confirmed-at (coerce/to-date-time "2018-03-12T00:13:24Z")}]
(people/add* @conn {:name "who"
:email "PI:EMAIL:<EMAIL>END_PI"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d0"
:attributes {:bar 1
:foo {:ok :dawg}}
:confirmed-at #inst "2018-03-12T00:13:24Z"})))
(is (= [{:name "who"
:email "PI:EMAIL:<EMAIL>END_PI"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d0"
:attributes {:bar 1
:foo {:ok "dawg"}}
:confirmed-at (coerce/to-date-time "2018-03-12T00:13:24Z")
:id 2}
{:name "yest"
:email "PI:EMAIL:<EMAIL>END_PI"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo ["a" "b" "c" "92731758-98f9-4358-974b-b15c74c917d9"]}
:confirmed-at (coerce/to-date-time "2019-06-24")
:id 1}]
(people/get-all* @conn)))
(is (= [{:name "yest"
:id 1
:email "PI:EMAIL:<EMAIL>END_PI"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo ["a" "b" "c" "92731758-98f9-4358-974b-b15c74c917d9"]}
:confirmed-at (coerce/to-date-time "2019-06-24")}]
(people/get-all* @conn {:email "PI:EMAIL:<EMAIL>END_PI"})))
(is (= 1
(people/set-email* @conn {:old-email "PI:EMAIL:<EMAIL>END_PI"
:new-email "PI:EMAIL:<EMAIL>END_PI"})))
(is (= 1
(people/delete* @conn {:email "PI:EMAIL:<EMAIL>END_PI"})))
(is (= {:count 1}
(people/count-all* @conn))))
(deftest array-coercions
(people/add-user* @conn {:name "PI:NAME:<NAME>END_PI"})
(people/add-user* @conn {:name "who"})
(let [people (people/get-users* @conn)]
(mapv #(people/add-to-squad* @conn {:name "test" :user-id (:id %)}) people)
(is (= 1 (count (people/get-squad* @conn {:name "PI:NAME:<NAME>END_PI"}))))
(is (= [{:name "test"
:peeps ["yest" "who"]}]
(people/get-squad-names* @conn {:name "test"})))
(is (= {:name "PI:NAME:<NAME>END_PI"
:peeps [{:id 1 :name "PI:NAME:<NAME>END_PI"}
{:id 2 :name "who"}]}
(-> (people/get-squad* @conn {:name "test"})
first)))))
|
[
{
"context": "rmchair.db :refer [serialize-db]]))\n\n(def DB-KEY \"armchair-data\")\n(def storage (.-localStorage js/window))\n\n(defn",
"end": 147,
"score": 0.998272716999054,
"start": 134,
"tag": "KEY",
"value": "armchair-data"
}
] | src/cljs/armchair/local_storage.cljs | maiwald/armchair | 6 | (ns armchair.local-storage
(:require [re-frame.core :refer [after]]
[armchair.db :refer [serialize-db]]))
(def DB-KEY "armchair-data")
(def storage (.-localStorage js/window))
(defn set-data [value]
(try (.setItem storage DB-KEY value)
(catch js/Error e e)))
(defn get-data []
(.getItem storage DB-KEY))
(def store
(after #(set-data (serialize-db %))))
| 34952 | (ns armchair.local-storage
(:require [re-frame.core :refer [after]]
[armchair.db :refer [serialize-db]]))
(def DB-KEY "<KEY>")
(def storage (.-localStorage js/window))
(defn set-data [value]
(try (.setItem storage DB-KEY value)
(catch js/Error e e)))
(defn get-data []
(.getItem storage DB-KEY))
(def store
(after #(set-data (serialize-db %))))
| true | (ns armchair.local-storage
(:require [re-frame.core :refer [after]]
[armchair.db :refer [serialize-db]]))
(def DB-KEY "PI:KEY:<KEY>END_PI")
(def storage (.-localStorage js/window))
(defn set-data [value]
(try (.setItem storage DB-KEY value)
(catch js/Error e e)))
(defn get-data []
(.getItem storage DB-KEY))
(def store
(after #(set-data (serialize-db %))))
|
[
{
"context": " :trust-password \"truststore-password\"}\n :work-stealing {:o",
"end": 18190,
"score": 0.9993974566459656,
"start": 18171,
"tag": "PASSWORD",
"value": "truststore-password"
}
] | waiter/test/waiter/settings_test.clj | twosigmajab/waiter | 0 | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns waiter.settings-test
(:require [clojure.test :refer :all]
[schema.core :as s]
[waiter.settings :refer :all]
[waiter.util.utils :as utils]))
(deftest test-load-missing-edn-file
(let [exit-called-atom (atom false)]
(with-redefs [utils/exit (fn [status msg]
(is (= 1 status))
(is msg)
(reset! exit-called-atom true))]
(load-settings-file "a-file-that-does-not-exist")
(is @exit-called-atom))))
(deftest test-load-existing-edn-file
(let [test-cases (list
{:name "load-clj-file-foo-clj"
:input "test-files/test-foo.edn"
:expected {
:foo1 "one.${foo2}"
:foo2 2
:foo3 [3]
:foo4 {:key 4}
:common "from-foo"}}
{:name "load-clj-file-bar-bar"
:input "test-files/test-bar.edn"
:expected {:bar1 "one.${system.user.name}"
:bar2 2
:bar3 [3]
:bar4 {:key 4}
:common "from-bar"}})]
(doseq [{:keys [name input expected]} test-cases]
(testing (str "Test " name)
(is (= expected (load-settings-file input)))))))
(deftest test-validate-nested-merge-settings
(testing "Test validating nested merge settings"
(with-redefs [load-settings-file (fn [file-name]
(is (= "some-config.edn" file-name))
{:kv-config {:kind :zk
:zk {:foo "foo"
:bar "bar"}
:encrypt "fie"}
:scheduler-gc-config {:broken-service-min-hosts 10
:broken-service-timeout-mins 300}})]
(let [loaded-settings (load-settings "some-config.edn" "some-git-version")]
(is (= (-> settings-defaults
(assoc :git-version "some-git-version")
(assoc-in [:kv-config :zk :foo] "foo")
(assoc-in [:kv-config :zk :bar] "bar")
(assoc-in [:kv-config :encrypt] "fie")
(assoc-in [:scheduler-gc-config :broken-service-min-hosts] 10)
(assoc-in [:scheduler-gc-config :broken-service-timeout-mins] 300))
loaded-settings))))))
(defn- load-config-file
"Calls load-settings on config-file with a fake git version string"
[config-file]
(load-settings config-file "some-git-version"))
(defn- load-full-settings
"Loads config-full.edn"
[]
(load-config-file "config-full.edn"))
(defn- load-min-settings
"Loads config-minimal.edn"
[]
(load-config-file "config-minimal.edn"))
(defn- load-minimesos-settings
"Loads config-minimesos.edn"
[]
(load-config-file "config-minimesos.edn"))
(defn- load-shell-settings
"Loads config-shell.edn"
[]
(load-config-file "config-shell.edn"))
(defn- load-composite-settings
"Loads config-composite.edn"
[]
(load-config-file "config-composite.edn"))
(deftest test-validate-minimal-settings
(testing "Test validating minimal settings"
(is (nil? (s/check settings-schema (load-min-settings))))))
(deftest test-validate-full-settings
(testing "Test validating full settings"
(is (nil? (s/check settings-schema (load-full-settings))))))
(deftest test-validate-full-settings-without-defaults
(testing "Test validating full settings"
(let [loaded-settings (load-settings-file "config-full.edn")]
(is (nil? (s/check settings-schema (assoc loaded-settings :git-version "some-git-version")))))))
(defn- settings-with-bogus-factory-fn
"Returns a settings map with the given key's :kind
sub-map containing a bogus (non-symbol) :factory-fn"
[k]
(let [$ (load-full-settings)]
(assoc-in $ [k (get-in $ [k :kind]) :factory-fn] "not-a-symbol")))
(deftest test-factory-fn-should-be-symbol
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :cors-config))))
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :entitlement-config))))
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :kv-config))))
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :password-store-config))))
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :scheduler-config))))
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :service-description-builder-config)))))
(defn- settings-with-missing-kind-sub-map
"Returns a settings map with the given key's :kind sub-map removed"
[k]
(let [$ (load-full-settings)]
(update-in $ [k] #(dissoc % (get-in $ [k :kind])))))
(deftest test-kind-sub-map-should-be-present
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :cors-config))))
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :entitlement-config))))
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :kv-config))))
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :password-store-config))))
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :scheduler-config))))
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :service-description-builder-config)))))
(deftest test-empty-hostname-vector
(let [settings (assoc (load-full-settings) :hostname [])]
(is (some? (s/check settings-schema settings)))))
(deftest test-deep-merge-settings
(testing "Deep merging of configuration settings"
(testing "should support partial configuration of :kind implementations"
(let [defaults {:scheduler-config {:kind :marathon
:marathon {:factory-fn 'waiter.scheduler.marathon/marathon-scheduler
:home-path-prefix "/home/"
:http-options {:conn-timeout 10000
:socket-timeout 10000}
:force-kill-after-ms 60000
:framework-id-ttl 900000}}}
configured {:scheduler-config {:kind :marathon
:marathon {:url "http://marathon.example.com:8080"}}}]
(is (= {:scheduler-config {:kind :marathon
:marathon {:factory-fn 'waiter.scheduler.marathon/marathon-scheduler
:home-path-prefix "/home/"
:http-options {:conn-timeout 10000
:socket-timeout 10000}
:force-kill-after-ms 60000
:framework-id-ttl 900000
:url "http://marathon.example.com:8080"}}}
(deep-merge-settings defaults configured)))))
(testing "should support defaulting the fields of the non-default :kind"
(let [defaults {:scheduler-config {:kind :foo
:foo {:bar 1
:baz 2}
:shell {:factory-fn 'waiter.scheduler.shell/shell-scheduler
:health-check-interval-ms 10000
:health-check-timeout-ms 200
:port-grace-period-ms 120000
:port-range [10000 10999]
:work-directory "scheduler"}}}
configured {:scheduler-config {:kind :shell}}]
(is (= {:scheduler-config {:kind :shell
:foo {:bar 1
:baz 2}
:shell {:factory-fn 'waiter.scheduler.shell/shell-scheduler
:health-check-interval-ms 10000
:health-check-timeout-ms 200
:port-grace-period-ms 120000
:port-range [10000 10999]
:work-directory "scheduler"}}}
(deep-merge-settings defaults configured)))))
(testing "should support partial configuration of the non-default :kind"
(let [defaults {:scheduler-config {:kind :foo
:foo {:bar 1
:baz 2}
:shell {:factory-fn 'waiter.scheduler.shell/shell-scheduler
:health-check-interval-ms 10000
:health-check-timeout-ms 200
:port-grace-period-ms 120000
:port-range [10000 10999]
:work-directory "scheduler"}}}
configured {:scheduler-config {:kind :shell
:shell {:health-check-interval-ms 1}}}]
(is (= {:scheduler-config {:kind :shell
:foo {:bar 1
:baz 2}
:shell {:factory-fn 'waiter.scheduler.shell/shell-scheduler
:health-check-interval-ms 1
:health-check-timeout-ms 200
:port-grace-period-ms 120000
:port-range [10000 10999]
:work-directory "scheduler"}}}
(deep-merge-settings defaults configured)))))
(testing "should not merge sub-maps not related to the configured :kind"
(let [defaults {:scheduler-config {:kind :foo
:foo {:bar 1
:baz 2}
:qux {:one "a"
:two "b"}}}
configured {:scheduler-config {:kind :qux
:qux {:two "c"}
:foo {:other 3}}}]
(is (= {:scheduler-config {:kind :qux
:foo {:other 3}
:qux {:one "a"
:two "c"}}}
(deep-merge-settings defaults configured)))))
(testing "should merge sub-sub-maps within the configured :kind"
(let [defaults {:scheduler-config {:kind :foo
:foo {:bar 1
:baz {:x 2
:y 3}}}}
configured {:scheduler-config {:kind :foo
:foo {:bar 1
:baz {:y 4
:z 4}}}}]
(is (= {:scheduler-config {:kind :foo
:foo {:bar 1
:baz {:x 2
:y 4
:z 4}}}}
(deep-merge-settings defaults configured)))))))
(deftest test-validate-minimesos-settings
(testing "Test validating minimesos settings"
(let [graphite-server-port 5555
port 12345
run-as-user "foo"
marathon "bar"
zk-connect-string "qux"]
(with-redefs [env (fn [name _]
(case name
"GRAPHITE_SERVER_PORT" (str graphite-server-port)
"WAITER_PORT" (str port)
"WAITER_AUTH_RUN_AS_USER" run-as-user
"WAITER_MARATHON" marathon
"WAITER_ZOOKEEPER_CONNECT_STRING" zk-connect-string
(throw (ex-info "Unexpected environment variable" {:name name}))))]
(let [settings (load-minimesos-settings)]
(is (nil? (s/check settings-schema settings)))
(is (= graphite-server-port (get-in settings [:metrics-config :codahale-reporters :graphite :port])))
(is (= port (:port settings)))
(is (= run-as-user (get-in settings [:authenticator-config :one-user :run-as-user])))
(is (= marathon (get-in settings [:scheduler-config :marathon :url])))
(is (= zk-connect-string (get-in settings [:zookeeper :connect-string]))))))))
(deftest test-validate-shell-settings
(testing "Test validating shell scheduler settings"
(let [port 12345
run-as-user "foo"
cluster-name "bar"]
(with-redefs [env (fn [name _]
(case name
"WAITER_PORT" (str port)
"WAITER_AUTH_RUN_AS_USER" run-as-user
"WAITER_CLUSTER_NAME" cluster-name
(throw (ex-info "Unexpected environment variable" {:name name}))))]
(let [settings (load-shell-settings)]
(is (nil? (s/check settings-schema settings)))
(is (= port (:port settings)))
(is (= run-as-user (get-in settings [:authenticator-config :one-user :run-as-user])))
(is (= cluster-name (get-in settings [:cluster-config :name]))))))))
(deftest test-validate-composite-settings
(testing "Test validating composite scheduler settings"
(let [graphite-server-port 5555
port 12345
run-as-user "foo"]
(with-redefs [env (fn [name _]
(case name
"GRAPHITE_SERVER_PORT" (str graphite-server-port)
"WAITER_PORT" (str port)
"WAITER_AUTH_RUN_AS_USER" run-as-user
(throw (ex-info "Unexpected environment variable" {:name name}))))]
(let [settings (load-composite-settings)]
(is (nil? (s/check settings-schema settings)))
(is (= graphite-server-port (get-in settings [:metrics-config :codahale-reporters :graphite :port])))
(is (= port (:port settings)))
(is (= run-as-user (get-in settings [:authenticator-config :one-user :run-as-user]))))))))
(deftest test-sanitize-settings
(is (= {:example {:foo {:kind :test
:test {:factory-fn "create-test" :param "value-test"}}}
:example-2 {:kind :not-present}
:kv-config {:kind :zk
:zk {:factory-fn "create-zk-kv-store" :sync-timeout-ms 2000}
:cache {:threshold 1000 :ttl 60}
:encrypt true
:relative-path "tokens"}
:scheduler-config {:cache {:ttl 100}
:kind :marathon
:marathon {:factory-fn "create-marathon-scheduler" :url "http://marathon.example.com:8080"}}
:server-options {:truststore "/path/to/truststore.p12"
:truststore-type "pkcs12"
:trust-password "<hidden>"}
:work-stealing {:offer-help-interval-ms 100
:reserve-timeout-ms 1000}
:zookeeper {:connect-string "<hidden>"
:gc-relative-path "gc-state"
:leader-latch-relative-path "leader-latch"}}
(sanitize-settings {:example {:foo {:kind :test
:test {:factory-fn "create-test" :param "value-test"}
:prod {:factory-fn "create-prod" :param "value-prod"}}}
:example-2 {:kind :not-present
:present {:factory-fn "create-present"}}
:kv-config {:kind :zk
:zk {:factory-fn "create-zk-kv-store" :sync-timeout-ms 2000}
:cache {:threshold 1000 :ttl 60}
:encrypt true
:relative-path "tokens"}
:scheduler-config {:cache {:ttl 100}
:kind :marathon
:marathon {:factory-fn "create-marathon-scheduler" :url "http://marathon.example.com:8080"}
:shell {:factory-fn "create-shell-scheduler" :working-directory "/path/to/some/directory"}}
:server-options {:truststore "/path/to/truststore.p12"
:truststore-type "pkcs12"
:trust-password "truststore-password"}
:work-stealing {:offer-help-interval-ms 100
:reserve-timeout-ms 1000}
:zookeeper {:connect-string "test-connect-string"
:gc-relative-path "gc-state"
:leader-latch-relative-path "leader-latch"}}))))
| 122111 | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns waiter.settings-test
(:require [clojure.test :refer :all]
[schema.core :as s]
[waiter.settings :refer :all]
[waiter.util.utils :as utils]))
(deftest test-load-missing-edn-file
(let [exit-called-atom (atom false)]
(with-redefs [utils/exit (fn [status msg]
(is (= 1 status))
(is msg)
(reset! exit-called-atom true))]
(load-settings-file "a-file-that-does-not-exist")
(is @exit-called-atom))))
(deftest test-load-existing-edn-file
(let [test-cases (list
{:name "load-clj-file-foo-clj"
:input "test-files/test-foo.edn"
:expected {
:foo1 "one.${foo2}"
:foo2 2
:foo3 [3]
:foo4 {:key 4}
:common "from-foo"}}
{:name "load-clj-file-bar-bar"
:input "test-files/test-bar.edn"
:expected {:bar1 "one.${system.user.name}"
:bar2 2
:bar3 [3]
:bar4 {:key 4}
:common "from-bar"}})]
(doseq [{:keys [name input expected]} test-cases]
(testing (str "Test " name)
(is (= expected (load-settings-file input)))))))
(deftest test-validate-nested-merge-settings
(testing "Test validating nested merge settings"
(with-redefs [load-settings-file (fn [file-name]
(is (= "some-config.edn" file-name))
{:kv-config {:kind :zk
:zk {:foo "foo"
:bar "bar"}
:encrypt "fie"}
:scheduler-gc-config {:broken-service-min-hosts 10
:broken-service-timeout-mins 300}})]
(let [loaded-settings (load-settings "some-config.edn" "some-git-version")]
(is (= (-> settings-defaults
(assoc :git-version "some-git-version")
(assoc-in [:kv-config :zk :foo] "foo")
(assoc-in [:kv-config :zk :bar] "bar")
(assoc-in [:kv-config :encrypt] "fie")
(assoc-in [:scheduler-gc-config :broken-service-min-hosts] 10)
(assoc-in [:scheduler-gc-config :broken-service-timeout-mins] 300))
loaded-settings))))))
(defn- load-config-file
"Calls load-settings on config-file with a fake git version string"
[config-file]
(load-settings config-file "some-git-version"))
(defn- load-full-settings
"Loads config-full.edn"
[]
(load-config-file "config-full.edn"))
(defn- load-min-settings
"Loads config-minimal.edn"
[]
(load-config-file "config-minimal.edn"))
(defn- load-minimesos-settings
"Loads config-minimesos.edn"
[]
(load-config-file "config-minimesos.edn"))
(defn- load-shell-settings
"Loads config-shell.edn"
[]
(load-config-file "config-shell.edn"))
(defn- load-composite-settings
"Loads config-composite.edn"
[]
(load-config-file "config-composite.edn"))
(deftest test-validate-minimal-settings
(testing "Test validating minimal settings"
(is (nil? (s/check settings-schema (load-min-settings))))))
(deftest test-validate-full-settings
(testing "Test validating full settings"
(is (nil? (s/check settings-schema (load-full-settings))))))
(deftest test-validate-full-settings-without-defaults
(testing "Test validating full settings"
(let [loaded-settings (load-settings-file "config-full.edn")]
(is (nil? (s/check settings-schema (assoc loaded-settings :git-version "some-git-version")))))))
(defn- settings-with-bogus-factory-fn
"Returns a settings map with the given key's :kind
sub-map containing a bogus (non-symbol) :factory-fn"
[k]
(let [$ (load-full-settings)]
(assoc-in $ [k (get-in $ [k :kind]) :factory-fn] "not-a-symbol")))
(deftest test-factory-fn-should-be-symbol
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :cors-config))))
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :entitlement-config))))
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :kv-config))))
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :password-store-config))))
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :scheduler-config))))
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :service-description-builder-config)))))
(defn- settings-with-missing-kind-sub-map
"Returns a settings map with the given key's :kind sub-map removed"
[k]
(let [$ (load-full-settings)]
(update-in $ [k] #(dissoc % (get-in $ [k :kind])))))
(deftest test-kind-sub-map-should-be-present
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :cors-config))))
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :entitlement-config))))
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :kv-config))))
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :password-store-config))))
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :scheduler-config))))
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :service-description-builder-config)))))
(deftest test-empty-hostname-vector
(let [settings (assoc (load-full-settings) :hostname [])]
(is (some? (s/check settings-schema settings)))))
(deftest test-deep-merge-settings
(testing "Deep merging of configuration settings"
(testing "should support partial configuration of :kind implementations"
(let [defaults {:scheduler-config {:kind :marathon
:marathon {:factory-fn 'waiter.scheduler.marathon/marathon-scheduler
:home-path-prefix "/home/"
:http-options {:conn-timeout 10000
:socket-timeout 10000}
:force-kill-after-ms 60000
:framework-id-ttl 900000}}}
configured {:scheduler-config {:kind :marathon
:marathon {:url "http://marathon.example.com:8080"}}}]
(is (= {:scheduler-config {:kind :marathon
:marathon {:factory-fn 'waiter.scheduler.marathon/marathon-scheduler
:home-path-prefix "/home/"
:http-options {:conn-timeout 10000
:socket-timeout 10000}
:force-kill-after-ms 60000
:framework-id-ttl 900000
:url "http://marathon.example.com:8080"}}}
(deep-merge-settings defaults configured)))))
(testing "should support defaulting the fields of the non-default :kind"
(let [defaults {:scheduler-config {:kind :foo
:foo {:bar 1
:baz 2}
:shell {:factory-fn 'waiter.scheduler.shell/shell-scheduler
:health-check-interval-ms 10000
:health-check-timeout-ms 200
:port-grace-period-ms 120000
:port-range [10000 10999]
:work-directory "scheduler"}}}
configured {:scheduler-config {:kind :shell}}]
(is (= {:scheduler-config {:kind :shell
:foo {:bar 1
:baz 2}
:shell {:factory-fn 'waiter.scheduler.shell/shell-scheduler
:health-check-interval-ms 10000
:health-check-timeout-ms 200
:port-grace-period-ms 120000
:port-range [10000 10999]
:work-directory "scheduler"}}}
(deep-merge-settings defaults configured)))))
(testing "should support partial configuration of the non-default :kind"
(let [defaults {:scheduler-config {:kind :foo
:foo {:bar 1
:baz 2}
:shell {:factory-fn 'waiter.scheduler.shell/shell-scheduler
:health-check-interval-ms 10000
:health-check-timeout-ms 200
:port-grace-period-ms 120000
:port-range [10000 10999]
:work-directory "scheduler"}}}
configured {:scheduler-config {:kind :shell
:shell {:health-check-interval-ms 1}}}]
(is (= {:scheduler-config {:kind :shell
:foo {:bar 1
:baz 2}
:shell {:factory-fn 'waiter.scheduler.shell/shell-scheduler
:health-check-interval-ms 1
:health-check-timeout-ms 200
:port-grace-period-ms 120000
:port-range [10000 10999]
:work-directory "scheduler"}}}
(deep-merge-settings defaults configured)))))
(testing "should not merge sub-maps not related to the configured :kind"
(let [defaults {:scheduler-config {:kind :foo
:foo {:bar 1
:baz 2}
:qux {:one "a"
:two "b"}}}
configured {:scheduler-config {:kind :qux
:qux {:two "c"}
:foo {:other 3}}}]
(is (= {:scheduler-config {:kind :qux
:foo {:other 3}
:qux {:one "a"
:two "c"}}}
(deep-merge-settings defaults configured)))))
(testing "should merge sub-sub-maps within the configured :kind"
(let [defaults {:scheduler-config {:kind :foo
:foo {:bar 1
:baz {:x 2
:y 3}}}}
configured {:scheduler-config {:kind :foo
:foo {:bar 1
:baz {:y 4
:z 4}}}}]
(is (= {:scheduler-config {:kind :foo
:foo {:bar 1
:baz {:x 2
:y 4
:z 4}}}}
(deep-merge-settings defaults configured)))))))
(deftest test-validate-minimesos-settings
(testing "Test validating minimesos settings"
(let [graphite-server-port 5555
port 12345
run-as-user "foo"
marathon "bar"
zk-connect-string "qux"]
(with-redefs [env (fn [name _]
(case name
"GRAPHITE_SERVER_PORT" (str graphite-server-port)
"WAITER_PORT" (str port)
"WAITER_AUTH_RUN_AS_USER" run-as-user
"WAITER_MARATHON" marathon
"WAITER_ZOOKEEPER_CONNECT_STRING" zk-connect-string
(throw (ex-info "Unexpected environment variable" {:name name}))))]
(let [settings (load-minimesos-settings)]
(is (nil? (s/check settings-schema settings)))
(is (= graphite-server-port (get-in settings [:metrics-config :codahale-reporters :graphite :port])))
(is (= port (:port settings)))
(is (= run-as-user (get-in settings [:authenticator-config :one-user :run-as-user])))
(is (= marathon (get-in settings [:scheduler-config :marathon :url])))
(is (= zk-connect-string (get-in settings [:zookeeper :connect-string]))))))))
(deftest test-validate-shell-settings
(testing "Test validating shell scheduler settings"
(let [port 12345
run-as-user "foo"
cluster-name "bar"]
(with-redefs [env (fn [name _]
(case name
"WAITER_PORT" (str port)
"WAITER_AUTH_RUN_AS_USER" run-as-user
"WAITER_CLUSTER_NAME" cluster-name
(throw (ex-info "Unexpected environment variable" {:name name}))))]
(let [settings (load-shell-settings)]
(is (nil? (s/check settings-schema settings)))
(is (= port (:port settings)))
(is (= run-as-user (get-in settings [:authenticator-config :one-user :run-as-user])))
(is (= cluster-name (get-in settings [:cluster-config :name]))))))))
(deftest test-validate-composite-settings
(testing "Test validating composite scheduler settings"
(let [graphite-server-port 5555
port 12345
run-as-user "foo"]
(with-redefs [env (fn [name _]
(case name
"GRAPHITE_SERVER_PORT" (str graphite-server-port)
"WAITER_PORT" (str port)
"WAITER_AUTH_RUN_AS_USER" run-as-user
(throw (ex-info "Unexpected environment variable" {:name name}))))]
(let [settings (load-composite-settings)]
(is (nil? (s/check settings-schema settings)))
(is (= graphite-server-port (get-in settings [:metrics-config :codahale-reporters :graphite :port])))
(is (= port (:port settings)))
(is (= run-as-user (get-in settings [:authenticator-config :one-user :run-as-user]))))))))
(deftest test-sanitize-settings
(is (= {:example {:foo {:kind :test
:test {:factory-fn "create-test" :param "value-test"}}}
:example-2 {:kind :not-present}
:kv-config {:kind :zk
:zk {:factory-fn "create-zk-kv-store" :sync-timeout-ms 2000}
:cache {:threshold 1000 :ttl 60}
:encrypt true
:relative-path "tokens"}
:scheduler-config {:cache {:ttl 100}
:kind :marathon
:marathon {:factory-fn "create-marathon-scheduler" :url "http://marathon.example.com:8080"}}
:server-options {:truststore "/path/to/truststore.p12"
:truststore-type "pkcs12"
:trust-password "<hidden>"}
:work-stealing {:offer-help-interval-ms 100
:reserve-timeout-ms 1000}
:zookeeper {:connect-string "<hidden>"
:gc-relative-path "gc-state"
:leader-latch-relative-path "leader-latch"}}
(sanitize-settings {:example {:foo {:kind :test
:test {:factory-fn "create-test" :param "value-test"}
:prod {:factory-fn "create-prod" :param "value-prod"}}}
:example-2 {:kind :not-present
:present {:factory-fn "create-present"}}
:kv-config {:kind :zk
:zk {:factory-fn "create-zk-kv-store" :sync-timeout-ms 2000}
:cache {:threshold 1000 :ttl 60}
:encrypt true
:relative-path "tokens"}
:scheduler-config {:cache {:ttl 100}
:kind :marathon
:marathon {:factory-fn "create-marathon-scheduler" :url "http://marathon.example.com:8080"}
:shell {:factory-fn "create-shell-scheduler" :working-directory "/path/to/some/directory"}}
:server-options {:truststore "/path/to/truststore.p12"
:truststore-type "pkcs12"
:trust-password "<PASSWORD>"}
:work-stealing {:offer-help-interval-ms 100
:reserve-timeout-ms 1000}
:zookeeper {:connect-string "test-connect-string"
:gc-relative-path "gc-state"
:leader-latch-relative-path "leader-latch"}}))))
| true | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns waiter.settings-test
(:require [clojure.test :refer :all]
[schema.core :as s]
[waiter.settings :refer :all]
[waiter.util.utils :as utils]))
(deftest test-load-missing-edn-file
(let [exit-called-atom (atom false)]
(with-redefs [utils/exit (fn [status msg]
(is (= 1 status))
(is msg)
(reset! exit-called-atom true))]
(load-settings-file "a-file-that-does-not-exist")
(is @exit-called-atom))))
(deftest test-load-existing-edn-file
(let [test-cases (list
{:name "load-clj-file-foo-clj"
:input "test-files/test-foo.edn"
:expected {
:foo1 "one.${foo2}"
:foo2 2
:foo3 [3]
:foo4 {:key 4}
:common "from-foo"}}
{:name "load-clj-file-bar-bar"
:input "test-files/test-bar.edn"
:expected {:bar1 "one.${system.user.name}"
:bar2 2
:bar3 [3]
:bar4 {:key 4}
:common "from-bar"}})]
(doseq [{:keys [name input expected]} test-cases]
(testing (str "Test " name)
(is (= expected (load-settings-file input)))))))
(deftest test-validate-nested-merge-settings
(testing "Test validating nested merge settings"
(with-redefs [load-settings-file (fn [file-name]
(is (= "some-config.edn" file-name))
{:kv-config {:kind :zk
:zk {:foo "foo"
:bar "bar"}
:encrypt "fie"}
:scheduler-gc-config {:broken-service-min-hosts 10
:broken-service-timeout-mins 300}})]
(let [loaded-settings (load-settings "some-config.edn" "some-git-version")]
(is (= (-> settings-defaults
(assoc :git-version "some-git-version")
(assoc-in [:kv-config :zk :foo] "foo")
(assoc-in [:kv-config :zk :bar] "bar")
(assoc-in [:kv-config :encrypt] "fie")
(assoc-in [:scheduler-gc-config :broken-service-min-hosts] 10)
(assoc-in [:scheduler-gc-config :broken-service-timeout-mins] 300))
loaded-settings))))))
(defn- load-config-file
"Calls load-settings on config-file with a fake git version string"
[config-file]
(load-settings config-file "some-git-version"))
(defn- load-full-settings
"Loads config-full.edn"
[]
(load-config-file "config-full.edn"))
(defn- load-min-settings
"Loads config-minimal.edn"
[]
(load-config-file "config-minimal.edn"))
(defn- load-minimesos-settings
"Loads config-minimesos.edn"
[]
(load-config-file "config-minimesos.edn"))
(defn- load-shell-settings
"Loads config-shell.edn"
[]
(load-config-file "config-shell.edn"))
(defn- load-composite-settings
"Loads config-composite.edn"
[]
(load-config-file "config-composite.edn"))
(deftest test-validate-minimal-settings
(testing "Test validating minimal settings"
(is (nil? (s/check settings-schema (load-min-settings))))))
(deftest test-validate-full-settings
(testing "Test validating full settings"
(is (nil? (s/check settings-schema (load-full-settings))))))
(deftest test-validate-full-settings-without-defaults
(testing "Test validating full settings"
(let [loaded-settings (load-settings-file "config-full.edn")]
(is (nil? (s/check settings-schema (assoc loaded-settings :git-version "some-git-version")))))))
(defn- settings-with-bogus-factory-fn
"Returns a settings map with the given key's :kind
sub-map containing a bogus (non-symbol) :factory-fn"
[k]
(let [$ (load-full-settings)]
(assoc-in $ [k (get-in $ [k :kind]) :factory-fn] "not-a-symbol")))
(deftest test-factory-fn-should-be-symbol
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :cors-config))))
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :entitlement-config))))
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :kv-config))))
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :password-store-config))))
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :scheduler-config))))
(is (some? (s/check settings-schema (settings-with-bogus-factory-fn :service-description-builder-config)))))
(defn- settings-with-missing-kind-sub-map
"Returns a settings map with the given key's :kind sub-map removed"
[k]
(let [$ (load-full-settings)]
(update-in $ [k] #(dissoc % (get-in $ [k :kind])))))
(deftest test-kind-sub-map-should-be-present
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :cors-config))))
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :entitlement-config))))
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :kv-config))))
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :password-store-config))))
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :scheduler-config))))
(is (some? (s/check settings-schema (settings-with-missing-kind-sub-map :service-description-builder-config)))))
(deftest test-empty-hostname-vector
(let [settings (assoc (load-full-settings) :hostname [])]
(is (some? (s/check settings-schema settings)))))
(deftest test-deep-merge-settings
(testing "Deep merging of configuration settings"
(testing "should support partial configuration of :kind implementations"
(let [defaults {:scheduler-config {:kind :marathon
:marathon {:factory-fn 'waiter.scheduler.marathon/marathon-scheduler
:home-path-prefix "/home/"
:http-options {:conn-timeout 10000
:socket-timeout 10000}
:force-kill-after-ms 60000
:framework-id-ttl 900000}}}
configured {:scheduler-config {:kind :marathon
:marathon {:url "http://marathon.example.com:8080"}}}]
(is (= {:scheduler-config {:kind :marathon
:marathon {:factory-fn 'waiter.scheduler.marathon/marathon-scheduler
:home-path-prefix "/home/"
:http-options {:conn-timeout 10000
:socket-timeout 10000}
:force-kill-after-ms 60000
:framework-id-ttl 900000
:url "http://marathon.example.com:8080"}}}
(deep-merge-settings defaults configured)))))
(testing "should support defaulting the fields of the non-default :kind"
(let [defaults {:scheduler-config {:kind :foo
:foo {:bar 1
:baz 2}
:shell {:factory-fn 'waiter.scheduler.shell/shell-scheduler
:health-check-interval-ms 10000
:health-check-timeout-ms 200
:port-grace-period-ms 120000
:port-range [10000 10999]
:work-directory "scheduler"}}}
configured {:scheduler-config {:kind :shell}}]
(is (= {:scheduler-config {:kind :shell
:foo {:bar 1
:baz 2}
:shell {:factory-fn 'waiter.scheduler.shell/shell-scheduler
:health-check-interval-ms 10000
:health-check-timeout-ms 200
:port-grace-period-ms 120000
:port-range [10000 10999]
:work-directory "scheduler"}}}
(deep-merge-settings defaults configured)))))
(testing "should support partial configuration of the non-default :kind"
(let [defaults {:scheduler-config {:kind :foo
:foo {:bar 1
:baz 2}
:shell {:factory-fn 'waiter.scheduler.shell/shell-scheduler
:health-check-interval-ms 10000
:health-check-timeout-ms 200
:port-grace-period-ms 120000
:port-range [10000 10999]
:work-directory "scheduler"}}}
configured {:scheduler-config {:kind :shell
:shell {:health-check-interval-ms 1}}}]
(is (= {:scheduler-config {:kind :shell
:foo {:bar 1
:baz 2}
:shell {:factory-fn 'waiter.scheduler.shell/shell-scheduler
:health-check-interval-ms 1
:health-check-timeout-ms 200
:port-grace-period-ms 120000
:port-range [10000 10999]
:work-directory "scheduler"}}}
(deep-merge-settings defaults configured)))))
(testing "should not merge sub-maps not related to the configured :kind"
(let [defaults {:scheduler-config {:kind :foo
:foo {:bar 1
:baz 2}
:qux {:one "a"
:two "b"}}}
configured {:scheduler-config {:kind :qux
:qux {:two "c"}
:foo {:other 3}}}]
(is (= {:scheduler-config {:kind :qux
:foo {:other 3}
:qux {:one "a"
:two "c"}}}
(deep-merge-settings defaults configured)))))
(testing "should merge sub-sub-maps within the configured :kind"
(let [defaults {:scheduler-config {:kind :foo
:foo {:bar 1
:baz {:x 2
:y 3}}}}
configured {:scheduler-config {:kind :foo
:foo {:bar 1
:baz {:y 4
:z 4}}}}]
(is (= {:scheduler-config {:kind :foo
:foo {:bar 1
:baz {:x 2
:y 4
:z 4}}}}
(deep-merge-settings defaults configured)))))))
(deftest test-validate-minimesos-settings
(testing "Test validating minimesos settings"
(let [graphite-server-port 5555
port 12345
run-as-user "foo"
marathon "bar"
zk-connect-string "qux"]
(with-redefs [env (fn [name _]
(case name
"GRAPHITE_SERVER_PORT" (str graphite-server-port)
"WAITER_PORT" (str port)
"WAITER_AUTH_RUN_AS_USER" run-as-user
"WAITER_MARATHON" marathon
"WAITER_ZOOKEEPER_CONNECT_STRING" zk-connect-string
(throw (ex-info "Unexpected environment variable" {:name name}))))]
(let [settings (load-minimesos-settings)]
(is (nil? (s/check settings-schema settings)))
(is (= graphite-server-port (get-in settings [:metrics-config :codahale-reporters :graphite :port])))
(is (= port (:port settings)))
(is (= run-as-user (get-in settings [:authenticator-config :one-user :run-as-user])))
(is (= marathon (get-in settings [:scheduler-config :marathon :url])))
(is (= zk-connect-string (get-in settings [:zookeeper :connect-string]))))))))
(deftest test-validate-shell-settings
(testing "Test validating shell scheduler settings"
(let [port 12345
run-as-user "foo"
cluster-name "bar"]
(with-redefs [env (fn [name _]
(case name
"WAITER_PORT" (str port)
"WAITER_AUTH_RUN_AS_USER" run-as-user
"WAITER_CLUSTER_NAME" cluster-name
(throw (ex-info "Unexpected environment variable" {:name name}))))]
(let [settings (load-shell-settings)]
(is (nil? (s/check settings-schema settings)))
(is (= port (:port settings)))
(is (= run-as-user (get-in settings [:authenticator-config :one-user :run-as-user])))
(is (= cluster-name (get-in settings [:cluster-config :name]))))))))
(deftest test-validate-composite-settings
(testing "Test validating composite scheduler settings"
(let [graphite-server-port 5555
port 12345
run-as-user "foo"]
(with-redefs [env (fn [name _]
(case name
"GRAPHITE_SERVER_PORT" (str graphite-server-port)
"WAITER_PORT" (str port)
"WAITER_AUTH_RUN_AS_USER" run-as-user
(throw (ex-info "Unexpected environment variable" {:name name}))))]
(let [settings (load-composite-settings)]
(is (nil? (s/check settings-schema settings)))
(is (= graphite-server-port (get-in settings [:metrics-config :codahale-reporters :graphite :port])))
(is (= port (:port settings)))
(is (= run-as-user (get-in settings [:authenticator-config :one-user :run-as-user]))))))))
(deftest test-sanitize-settings
(is (= {:example {:foo {:kind :test
:test {:factory-fn "create-test" :param "value-test"}}}
:example-2 {:kind :not-present}
:kv-config {:kind :zk
:zk {:factory-fn "create-zk-kv-store" :sync-timeout-ms 2000}
:cache {:threshold 1000 :ttl 60}
:encrypt true
:relative-path "tokens"}
:scheduler-config {:cache {:ttl 100}
:kind :marathon
:marathon {:factory-fn "create-marathon-scheduler" :url "http://marathon.example.com:8080"}}
:server-options {:truststore "/path/to/truststore.p12"
:truststore-type "pkcs12"
:trust-password "<hidden>"}
:work-stealing {:offer-help-interval-ms 100
:reserve-timeout-ms 1000}
:zookeeper {:connect-string "<hidden>"
:gc-relative-path "gc-state"
:leader-latch-relative-path "leader-latch"}}
(sanitize-settings {:example {:foo {:kind :test
:test {:factory-fn "create-test" :param "value-test"}
:prod {:factory-fn "create-prod" :param "value-prod"}}}
:example-2 {:kind :not-present
:present {:factory-fn "create-present"}}
:kv-config {:kind :zk
:zk {:factory-fn "create-zk-kv-store" :sync-timeout-ms 2000}
:cache {:threshold 1000 :ttl 60}
:encrypt true
:relative-path "tokens"}
:scheduler-config {:cache {:ttl 100}
:kind :marathon
:marathon {:factory-fn "create-marathon-scheduler" :url "http://marathon.example.com:8080"}
:shell {:factory-fn "create-shell-scheduler" :working-directory "/path/to/some/directory"}}
:server-options {:truststore "/path/to/truststore.p12"
:truststore-type "pkcs12"
:trust-password "PI:PASSWORD:<PASSWORD>END_PI"}
:work-stealing {:offer-help-interval-ms 100
:reserve-timeout-ms 1000}
:zookeeper {:connect-string "test-connect-string"
:gc-relative-path "gc-state"
:leader-latch-relative-path "leader-latch"}}))))
|
[
{
"context": " :key-password \"YourSslKeystorePassword\"}\n :archive-ds-ks [:a",
"end": 1676,
"score": 0.9985060691833496,
"start": 1653,
"tag": "PASSWORD",
"value": "YourSslKeystorePassword"
},
{
"context": " :passphrase \"YourJwtPrivateKeyPassphrase\"\n :pubkey",
"end": 2042,
"score": 0.9899870157241821,
"start": 2015,
"tag": "PASSWORD",
"value": "YourJwtPrivateKeyPassphrase"
}
] | deploy-to-aws/other-resources/boa_server_config.clj | mikub/titanoboa-sample-workflows | 16 | (in-ns 'titanoboa.server)
(log/info "Hello, I am core.async server-config and I am being loaded...")
(defonce archival-queue-local (clojure.core.async/chan (clojure.core.async/dropping-buffer 1024)))
(alter-var-root #'server-config
(constantly {:systems-catalogue
{:core {:system-def #'titanoboa.system.local/local-core-system
:worker-def #'titanoboa.system.local/local-worker-system
:worker-count 1
:autostart true}
:archival-system {:system-def #'titanoboa.system.local/archival-system
:autostart true}
:auth-system {:system-def #'titanoboa.system.auth/auth-system
:autostart true}}
:jobs-repo-path "/mnt/efs/titanoboa/repo/"
:steps-repo-path "/mnt/efs/titanoboa/stepsrepo/"
:job-folder-path "/mnt/efs/titanoboa/jobs/"
:enable-cluster false
:jetty {:ssl-port 443
:join? false
:ssl? true
:http? false
:keystore "/mnt/efs/titanoboa/keystore.jks"
:key-password "YourSslKeystorePassword"}
:archive-ds-ks [:archival-system :system :db-pool]
:auth? true
:auth-ds-ks [:auth-system :system :db-pool]
:auth-conf {:privkey "/mnt/efs/titanoboa/auth_privkey.pem"
:passphrase "YourJwtPrivateKeyPassphrase"
:pubkey "/mnt/efs/titanoboa/auth_pubkey.pem"}
:systems-config {:core
{:new-jobs-chan (clojure.core.async/chan (clojure.core.async/dropping-buffer 1024))
:jobs-chan (clojure.core.async/chan (clojure.core.async/dropping-buffer 1024))
:finished-jobs-chan archival-queue-local}
:archival-system (merge {:finished-jobs-chan archival-queue-local}
(edn/read-string (slurp "/mnt/efs/titanoboa/db-config.edn")))
:auth-system (edn/read-string (slurp "/mnt/efs/titanoboa/db-config.edn"))}}))
| 79332 | (in-ns 'titanoboa.server)
(log/info "Hello, I am core.async server-config and I am being loaded...")
(defonce archival-queue-local (clojure.core.async/chan (clojure.core.async/dropping-buffer 1024)))
(alter-var-root #'server-config
(constantly {:systems-catalogue
{:core {:system-def #'titanoboa.system.local/local-core-system
:worker-def #'titanoboa.system.local/local-worker-system
:worker-count 1
:autostart true}
:archival-system {:system-def #'titanoboa.system.local/archival-system
:autostart true}
:auth-system {:system-def #'titanoboa.system.auth/auth-system
:autostart true}}
:jobs-repo-path "/mnt/efs/titanoboa/repo/"
:steps-repo-path "/mnt/efs/titanoboa/stepsrepo/"
:job-folder-path "/mnt/efs/titanoboa/jobs/"
:enable-cluster false
:jetty {:ssl-port 443
:join? false
:ssl? true
:http? false
:keystore "/mnt/efs/titanoboa/keystore.jks"
:key-password "<PASSWORD>"}
:archive-ds-ks [:archival-system :system :db-pool]
:auth? true
:auth-ds-ks [:auth-system :system :db-pool]
:auth-conf {:privkey "/mnt/efs/titanoboa/auth_privkey.pem"
:passphrase "<PASSWORD>"
:pubkey "/mnt/efs/titanoboa/auth_pubkey.pem"}
:systems-config {:core
{:new-jobs-chan (clojure.core.async/chan (clojure.core.async/dropping-buffer 1024))
:jobs-chan (clojure.core.async/chan (clojure.core.async/dropping-buffer 1024))
:finished-jobs-chan archival-queue-local}
:archival-system (merge {:finished-jobs-chan archival-queue-local}
(edn/read-string (slurp "/mnt/efs/titanoboa/db-config.edn")))
:auth-system (edn/read-string (slurp "/mnt/efs/titanoboa/db-config.edn"))}}))
| true | (in-ns 'titanoboa.server)
(log/info "Hello, I am core.async server-config and I am being loaded...")
(defonce archival-queue-local (clojure.core.async/chan (clojure.core.async/dropping-buffer 1024)))
(alter-var-root #'server-config
(constantly {:systems-catalogue
{:core {:system-def #'titanoboa.system.local/local-core-system
:worker-def #'titanoboa.system.local/local-worker-system
:worker-count 1
:autostart true}
:archival-system {:system-def #'titanoboa.system.local/archival-system
:autostart true}
:auth-system {:system-def #'titanoboa.system.auth/auth-system
:autostart true}}
:jobs-repo-path "/mnt/efs/titanoboa/repo/"
:steps-repo-path "/mnt/efs/titanoboa/stepsrepo/"
:job-folder-path "/mnt/efs/titanoboa/jobs/"
:enable-cluster false
:jetty {:ssl-port 443
:join? false
:ssl? true
:http? false
:keystore "/mnt/efs/titanoboa/keystore.jks"
:key-password "PI:PASSWORD:<PASSWORD>END_PI"}
:archive-ds-ks [:archival-system :system :db-pool]
:auth? true
:auth-ds-ks [:auth-system :system :db-pool]
:auth-conf {:privkey "/mnt/efs/titanoboa/auth_privkey.pem"
:passphrase "PI:PASSWORD:<PASSWORD>END_PI"
:pubkey "/mnt/efs/titanoboa/auth_pubkey.pem"}
:systems-config {:core
{:new-jobs-chan (clojure.core.async/chan (clojure.core.async/dropping-buffer 1024))
:jobs-chan (clojure.core.async/chan (clojure.core.async/dropping-buffer 1024))
:finished-jobs-chan archival-queue-local}
:archival-system (merge {:finished-jobs-chan archival-queue-local}
(edn/read-string (slurp "/mnt/efs/titanoboa/db-config.edn")))
:auth-system (edn/read-string (slurp "/mnt/efs/titanoboa/db-config.edn"))}}))
|
[
{
"context": "(= (catalog-edges-map certname)\n {[\"ff0702ba8a7dc69d3fb17f9d151bf9bd265a9ed9\"\n \"57495b553981551c5194a21b9a2655",
"end": 41146,
"score": 0.9388859272003174,
"start": 41106,
"tag": "KEY",
"value": "ff0702ba8a7dc69d3fb17f9d151bf9bd265a9ed9"
},
{
"context": "c69d3fb17f9d151bf9bd265a9ed9\"\n \"57495b553981551c5194a21b9a26554cd93db3d9\"\n ",
"end": 41171,
"score": 0.6419341564178467,
"start": 41168,
"tag": "KEY",
"value": "495"
},
{
"context": "3fb17f9d151bf9bd265a9ed9\"\n \"57495b553981551c5194a21b9a26554cd93db3d9\"\n \"contains\"] nil,\n ",
"end": 41206,
"score": 0.8371005058288574,
"start": 41172,
"tag": "KEY",
"value": "553981551c5194a21b9a26554cd93db3d9"
},
{
"context": " \"contains\"] nil,\n [\"57495b553981551c5194a21b9a26554cd93db3d9\"\n \"e247f822a0f0bbbfff4fe066ce4a0",
"end": 41301,
"score": 0.9686540365219116,
"start": 41261,
"tag": "KEY",
"value": "57495b553981551c5194a21b9a26554cd93db3d9"
},
{
"context": " \"e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1\"\n \"required-by\"] nil,\n ",
"end": 41356,
"score": 0.5417450666427612,
"start": 41354,
"tag": "KEY",
"value": "9c"
},
{
"context": " \"e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1\"\n \"required-by\"] nil,\n ",
"end": 41362,
"score": 0.5506588816642761,
"start": 41357,
"tag": "KEY",
"value": "3cdb1"
},
{
"context": " \"required-by\"] nil,\n [\"ff0702ba8a7dc69d3fb17f9d151bf9bd265a9ed9\"\n \"e247f822a0f0bbbfff4fe066ce4a",
"end": 41462,
"score": 0.9537301063537598,
"start": 41422,
"tag": "KEY",
"value": "ff0702ba8a7dc69d3fb17f9d151bf9bd265a9ed9"
},
{
"context": "9d151bf9bd265a9ed9\"\n \"e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1\"\n \"",
"end": 41496,
"score": 0.5532956719398499,
"start": 41494,
"tag": "KEY",
"value": "f0"
},
{
"context": "5a9ed9\"\n \"e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1\"\n \"contains\"] ",
"end": 41507,
"score": 0.5146877765655518,
"start": 41506,
"tag": "KEY",
"value": "6"
},
{
"context": "d9\"\n \"e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1\"\n \"contains\"] nil})))\n\n ;;",
"end": 41524,
"score": 0.6162171959877014,
"start": 41510,
"tag": "KEY",
"value": "4a077f9c03cdb1"
},
{
"context": "catalog-edges-map certname)\n {[\"ff0702ba8a7dc69d3fb17f9d151bf9bd265a9ed9\"\n \"e247f822a0f0bbbfff4fe066ce",
"end": 42352,
"score": 0.9388605356216431,
"start": 42312,
"tag": "KEY",
"value": "ff0702ba8a7dc69d3fb17f9d151bf9bd265a9ed9"
},
{
"context": " \"e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1\"\n \"contains\"] nil,\n ",
"end": 42410,
"score": 0.5222326517105103,
"start": 42409,
"tag": "KEY",
"value": "c"
},
{
"context": " \"e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1\"\n \"contains\"] nil,\n ",
"end": 42412,
"score": 0.5610729455947876,
"start": 42411,
"tag": "KEY",
"value": "3"
},
{
"context": " \"contains\"] nil,\n [\"57495b553981551c5194a21b9a26554cd93db3d9\"\n ",
"end": 42482,
"score": 0.5381972193717957,
"start": 42481,
"tag": "KEY",
"value": "4"
},
{
"context": " \"contains\"] nil,\n [\"57495b553981551c5194a21b9a26554cd93db3d9\"\n ",
"end": 42492,
"score": 0.7769673466682434,
"start": 42483,
"tag": "KEY",
"value": "5b5539815"
},
{
"context": " \"networking\" {\"eth0\" {\"ipaddresses\" [\"192.168.0.11\"]}}}]\n (add-facts! {:certname certname\n ",
"end": 46150,
"score": 0.99969083070755,
"start": 46138,
"tag": "IP_ADDRESS",
"value": "192.168.0.11"
}
] | test/puppetlabs/puppetdb/scf/storage_test.clj | jbondpdx/puppetdb | 0 | (ns puppetlabs.puppetdb.scf.storage-test
(:require [clojure.java.jdbc :as sql]
[clojure.set :as set]
[puppetlabs.puppetdb.cheshire :as json]
[puppetlabs.puppetdb.reports :as report]
[puppetlabs.puppetdb.scf.hash :as shash]
[puppetlabs.puppetdb.facts :as facts]
[puppetlabs.puppetdb.schema :as pls :refer [defn-validated]]
[puppetlabs.puppetdb.scf.migrate :as migrate]
[clojure.walk :as walk]
[puppetlabs.puppetdb.scf.storage-utils :as sutils]
[puppetlabs.kitchensink.core :as kitchensink]
[puppetlabs.puppetdb.testutils :as tu]
[puppetlabs.puppetdb.testutils.db
:refer [*db* clear-db-for-testing! init-db with-test-db]]
[metrics.histograms :refer [sample histogram]]
[metrics.counters :as counters]
[schema.core :as s]
[puppetlabs.trapperkeeper.testutils.logging :as pllog]
[clojure.string :as str]
[puppetlabs.puppetdb.examples :refer [catalogs]]
[puppetlabs.puppetdb.examples.reports :refer [reports]]
[puppetlabs.puppetdb.testutils.reports :refer :all]
[puppetlabs.puppetdb.testutils.events :refer :all]
[puppetlabs.puppetdb.random :as random]
[puppetlabs.puppetdb.scf.storage :refer :all]
[clojure.test :refer :all]
[clojure.math.combinatorics :refer [combinations subsets]]
[puppetlabs.puppetdb.jdbc :as jdbc
:refer [call-with-query-rows query-to-vec]]
[puppetlabs.puppetdb.time :as time
:refer [ago before? days from-now now to-string to-timestamp]]))
(def reference-time "2014-10-28T20:26:21.727Z")
(def previous-time "2014-10-26T20:26:21.727Z")
(defn-validated expire-node!
"Expire the given host, recording expire-time. If the node is
already expired, no change is made."
[certname :- String expire-time :- pls/Timestamp]
(jdbc/do-prepared
"update certnames set expired = ? where certname=? and expired is null"
[(to-timestamp expire-time) certname]))
;; When only one db is needed.
(defmacro deftest-db [name & body]
`(deftest ~name (with-test-db ~@body)))
(deftest-db ensure-producer-test
(let [prod1 "foo.com"
prod2 "bar.com"]
(ensure-producer prod1)
(testing "doesn't create new row for existing producer"
(is (= 1 (ensure-producer prod1))))
(testing "creates new row for non-existing producer"
(is (= 2 (ensure-producer prod2))))))
(defn-validated factset-map :- {s/Str s/Any}
"Return all facts and their values for a given certname as a map"
[certname :- String]
(or (-> (jdbc/query ["select (stable||volatile) as facts from factsets where certname=?"
certname])
first
:facts
str
json/parse-string)
{}))
(defn stable-facts [certname]
(-> (query-to-vec "select stable from factsets where certname=?" certname)
first
:stable
str
json/parse-string))
(defn volatile-facts [certname]
(-> (query-to-vec "select volatile from factsets where certname=?" certname)
first
:volatile
str
json/parse-string))
(defn count-facts
[]
(-> "select count(*) c from (select jsonb_each(stable||volatile) from factsets) fs"
query-to-vec
first
:c))
(deftest-db large-fact-update
(testing "updating lots of facts"
(let [certname "scale.com"
facts1 (zipmap (take 10000 (repeatedly #(random/random-string 10)))
(take 10000 (repeatedly #(random/random-string 10))))
timestamp1 (-> 2 days ago)
facts2 (zipmap (take 11000 (repeatedly #(random/random-string 10)))
(take 11000 (repeatedly #(random/random-string 10))))
timestamp2 (-> 1 days ago)
producer "bar.com"]
(add-certname! certname)
(add-facts! {:certname certname
:values facts1
:timestamp timestamp1
:environment nil
:producer_timestamp timestamp1
:producer producer})
(testing "10000 facts stored"
(is (= 10000 (count-facts))))
(update-facts! {:certname certname
:values facts2
:timestamp timestamp2
:environment nil
:producer_timestamp timestamp2
:producer producer})
(testing "11000 facts stored"
(is (= 11000 (count-facts)))))))
(deftest-db escaped-string-factnames
(testing "should work with escaped strings"
(let [certname "some_certname"
facts {"\"hello\"" "world"
"foo#~bar" "baz"
"\"foo" "bar"
"foo#~" "bar"
"foo" "bar"}
producer "bar.com"]
(add-certname! certname)
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment nil
:producer_timestamp previous-time
:producer producer})
(is (= facts (factset-map "some_certname"))))))
(comment
(def certname "some_certname")
(def facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"})
(def new-facts {"domain" "mynewdomain.com"
"fqdn" "myhost.mynewdomain.com"
"hostname" "myhost"
"kernel" "Linux"
"uptime_seconds" 3600})
(def producer "bar.com")
(alter-var-root #'*db*
(constantly jdbc/*db*))
)
(defn delete-certname-facts!
[certname]
(jdbc/do-prepared "delete from factsets where certname = ?" [certname]))
(deftest fact-persistence
(with-test-db
(testing "Persisted facts"
(let [certname "some_certname"
facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"}
producer "bar.com"]
(add-certname! certname)
(is (nil?
(jdbc/with-db-transaction []
(timestamp-of-newest-record :factsets "some_certname"))))
(is (empty? (factset-map "some_certname")))
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment nil
:producer_timestamp previous-time
:producer producer})
(testing "should have entries for each fact"
(is (= facts (factset-map "some_certname"))))
(testing "should have entries for each fact"
(is (= facts (factset-map certname)))
(is (jdbc/with-db-transaction []
(timestamp-of-newest-record :factsets "some_certname")))
(is (= facts (factset-map "some_certname"))))
(testing "should add the certname if necessary"
(is (= (query-to-vec "SELECT certname FROM certnames")
[{:certname certname}])))
(testing "should start with no volatile facts"
(is (= facts (stable-facts certname)))
(is (= {} (volatile-facts certname))))
(testing "replacing facts"
;; Ensuring here that new records are inserted, updated
;; facts are updated (not deleted and inserted) and that
;; the necessary deletes happen
(tu/with-wrapped-fn-args [updates jdbc/update!]
(let [new-facts {"domain" "mynewdomain.com"
"fqdn" "myhost.mynewdomain.com"
"hostname" "myhost"
"kernel" "Linux"
"uptime_seconds" 3600}]
(replace-facts! {:certname certname
:values new-facts
:environment "DEV"
:producer_timestamp reference-time
:timestamp reference-time
:producer producer})
(testing "should have only the new facts"
(is (= {"domain" "mynewdomain.com"
"fqdn" "myhost.mynewdomain.com"
"hostname" "myhost"
"kernel" "Linux"
"uptime_seconds" 3600}
(factset-map certname))))
(testing "producer_timestamp should store current time"
(is (= (query-to-vec "SELECT producer_timestamp FROM factsets")
[{:producer_timestamp (to-timestamp reference-time)}])))
(testing "changed facts should now be volatile"
(is (= #{"domain" "fqdn"}
(set (keys (volatile-facts certname))))))
#_(testing "should update existing keys"
(is (= 1 (count @updates)))
(is (some #{{:timestamp (to-timestamp reference-time)
:environment_id 1
:hash "1a4b10a865b8c7b435ec0fe06968fdc62337f57f"
:producer_timestamp (to-timestamp reference-time)
:producer_id 1}}
;; Again we grab the pertinent non-id bits
(map (fn [itm]
(-> (second itm)
(update-in [:hash] sutils/parse-db-hash)))
@updates)))
(is (some (fn [update-call]
(and (= :factsets (first update-call))
(:timestamp (second update-call))))
@updates))))))
(testing "replacing all new facts"
(delete-certname-facts! certname)
(replace-facts! {:certname certname
:values facts
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(is (= facts (factset-map "some_certname"))))
(testing "replacing all facts with new ones"
(delete-certname-facts! certname)
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment nil
:producer_timestamp previous-time
:producer nil})
(replace-facts! {:certname certname
:values {"foo" "bar"}
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(is (= {"foo" "bar"} (factset-map "some_certname"))))
(testing "replace-facts with only additions"
(let [fact-map (factset-map "some_certname")]
(replace-facts! {:certname certname
:values (assoc fact-map "one more" "here")
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(is (= (assoc fact-map "one more" "here")
(factset-map "some_certname")))))
(testing "replace-facts with no change"
(let [fact-map (factset-map "some_certname")]
(replace-facts! {:certname certname
:values fact-map
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(is (= fact-map
(factset-map "some_certname")))))
(testing "stable hash when no facts change"
(let [fact-map (factset-map "some_certname")
{old-hash :hash} (first (query-to-vec (format "SELECT %s AS hash FROM factsets where certname=?" (sutils/sql-hash-as-str "hash")) certname))]
(replace-facts! {:certname certname
:values fact-map
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(let [{new-hash :hash} (first (query-to-vec (format "SELECT %s AS hash FROM factsets where certname=?" (sutils/sql-hash-as-str "hash")) certname))]
(is (= old-hash new-hash)))
(replace-facts! {:certname certname
:values (assoc fact-map "another thing" "goes here")
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(let [{new-hash :hash} (first (query-to-vec (format "SELECT %s AS hash FROM factsets where certname=?" (sutils/sql-hash-as-str "hash")) certname))]
(is (not= old-hash new-hash)))))))))
(deftest fact-path-gc
(letfn [(facts-now [c v]
{:certname c :values v
:environment nil :timestamp (now) :producer_timestamp (now) :producer nil})
(paths-and-types []
(query-to-vec "select path, value_type_id from fact_paths"))
(check-gc [factset-changes
expected-before
expected-after]
(clear-db-for-testing!)
(init-db *db*)
(doseq [cert (set (map first factset-changes))]
(add-certname! cert))
(doseq [[cert factset] factset-changes]
(replace-facts! (facts-now cert factset)))
(let [obs (paths-and-types)]
(is (= (count expected-before) (count obs)))
(is (= expected-before (set obs))))
(delete-unused-fact-paths)
(let [obs (paths-and-types)]
(is (= (count expected-after) (count obs)))
(is (= expected-after (set obs)))))]
(let [type-id {:int (facts/value-type-id 0)
:str (facts/value-type-id "0")
:obj (facts/value-type-id [])}]
(with-test-db
(testing "works when there are no paths"
(check-gc [] #{} #{}))
(testing "doesn't do anything if nothing changes"
(let [before #{{:path "a" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~foo" :value_type_id (type-id :str)}}]
(check-gc [["c-x" {"a" 1}]
["c-y" {"b" {"foo" "two"}}]]
before
before)))
(testing "orphaning of a simple scalar"
(check-gc [["c-x" {"a" 1}]
["c-y" {"b" 2}]
["c-y" {"c" 3}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :int)}
{:path "c" :value_type_id (type-id :int)}}
#{{:path "a" :value_type_id (type-id :int)}
{:path "c" :value_type_id (type-id :int)}}))
(testing "orphaning of a structured fact"
(check-gc [["c-x" {"a" 1}]
["c-y" {"b" {"foo" "bar"}}]
["c-y" {"c" 3}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~foo" :value_type_id (type-id :str)}
{:path "c" :value_type_id (type-id :int)}}
#{{:path "a" :value_type_id (type-id :int)}
{:path "c" :value_type_id (type-id :int)}}))
(testing "orphaning of an array"
(check-gc [["c-x" {"a" 1}]
["c-y" {"b" ["x" "y"]}]
["c-y" {"c" 3}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~0" :value_type_id (type-id :str)}
{:path "b#~1" :value_type_id (type-id :str)}
{:path "c" :value_type_id (type-id :int)}}
#{{:path "a" :value_type_id (type-id :int)}
{:path "c" :value_type_id (type-id :int)}}))
;; In these type change tests, orphaned types linger because
;; the current gc only operates on (removes) paths that have
;; no references at all. It leaves any existing entries for a
;; given path alone.
(testing "structured fact changing to simple"
(check-gc [["c-x" {"b" {"foo" "bar"}}]
["c-x" {"b" 1}]]
#{{:path "b" :value_type_id (type-id :obj)}
{:path "b#~foo" :value_type_id (type-id :str)}
{:path "b" :value_type_id (type-id :int)}}
#{{:path "b" :value_type_id (type-id :obj)}
{:path "b" :value_type_id (type-id :int)}}))
(testing "simple fact changing to structured"
(check-gc [["c-x" {"b" 1}]
["c-x" {"b" {"foo" "bar"}}]]
#{{:path "b" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~foo" :value_type_id (type-id :str)}}
#{{:path "b" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~foo" :value_type_id (type-id :str)}}))
(testing "array changes to scalar"
(check-gc [["c-x" {"b" ["x" "y"]}]
["c-x" {"b" 1}]]
#{{:path "b" :value_type_id (type-id :obj)}
{:path "b#~0" :value_type_id (type-id :str)}
{:path "b#~1" :value_type_id (type-id :str)}
{:path "b" :value_type_id (type-id :int)}}
#{{:path "b" :value_type_id (type-id :obj)}
{:path "b" :value_type_id (type-id :int)}}))
(testing "scalar changes to array"
(check-gc [["c-x" {"b" 1}]
["c-x" {"b" ["x" "y"]}]]
#{{:path "b" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~0" :value_type_id (type-id :str)}
{:path "b#~1" :value_type_id (type-id :str)}}
#{{:path "b" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~0" :value_type_id (type-id :str)}
{:path "b#~1" :value_type_id (type-id :str)}}))
(testing "multiple types for path and all disappear"
(check-gc [["c-w" {"a" 1}]
["c-x" {"a" "two"}]
["c-y" {"a" {"foo" "bar"}}]
["c-z" {"a" [3]}]
["c-w" {}]
["c-x" {}]
["c-y" {}]
["c-z" {}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "a" :value_type_id (type-id :str)}
{:path "a" :value_type_id (type-id :obj)}
{:path "a#~foo" :value_type_id (type-id :str)}
{:path "a#~0" :value_type_id (type-id :int)}}
#{}))
(testing "multiple types for path and all types change"
(let [expected #{{:path "a" :value_type_id (type-id :int)}
{:path "a" :value_type_id (type-id :obj)}
{:path "a#~0" :value_type_id (type-id :int)}
{:path "a#~foo" :value_type_id (type-id :str)}
{:path "a" :value_type_id (type-id :str)}}]
(check-gc [["c-x" {"a" 1}]
["c-y" {"a" [0]}]
["c-x" {"a" {"foo" "bar"}}]
["c-y" {"a" "two"}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "a" :value_type_id (type-id :obj)}
{:path "a#~0" :value_type_id (type-id :int)}
{:path "a#~foo" :value_type_id (type-id :str)}
{:path "a" :value_type_id (type-id :str)}}
;; Q: Why didn't "a" :int stick around?
#{{:path "a" :value_type_id (type-id :int)}
{:path "a" :value_type_id (type-id :obj)}
{:path "a#~foo" :value_type_id (type-id :str)}
{:path "a" :value_type_id (type-id :str)}})))
(testing "everything to nothing"
(check-gc [["c-x" {"a" 1}]
["c-y" {"a" ["x" "y"]}]
["c-z" {"a" {"foo" "bar"}}]
["c-x" {}]
["c-y" {}]
["c-z" {}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "a" :value_type_id (type-id :obj)}
{:path "a#~0" :value_type_id (type-id :str)}
{:path "a#~1" :value_type_id (type-id :str)}
{:path "a#~foo" :value_type_id (type-id :str)}}
#{}))))))
(deftest factset-paths-write-minimization
(letfn [(facts-now [c v]
{:certname c :values v
:environment nil :timestamp (now) :producer_timestamp (now) :producer nil})
(certname-paths-hash [certname]
(-> "select paths_hash from factsets where certname = ?"
(query-to-vec certname)
first
:paths_hash))
(reset-db []
(clear-db-for-testing!)
(init-db *db*))
(set-cert-facts-causes-update [cert factset]
(let [real-realize-paths realize-paths
called? (atom false)]
(with-redefs [realize-paths (fn [& args]
(reset! called? true)
(apply real-realize-paths args))]
(replace-facts! (facts-now cert factset)))
@called?))]
(with-test-db
(testing "with no hash, establishing no facts establishes a hash"
(reset-db)
(add-certname! "foo")
(is (= nil (certname-paths-hash "foo")))
(set-cert-facts-causes-update "foo" {})
(let [hash (certname-paths-hash "foo")]
(is (= 20 (count hash)))
(is (= (class (byte-array 0)) (class hash)))))
(testing "with hash for no paths, establishing no paths causes no update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {})
(is (= false (set-cert-facts-causes-update "foo" {}))))
(testing "with hash for no paths, establishing paths causes update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {})
(is (= true (set-cert-facts-causes-update "foo" {"a" 1}))))
(testing "with paths, replacing with same paths causes no update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {"a" 1})
(is (= false (set-cert-facts-causes-update "foo" {"a" 1}))))
(testing "with paths, changing fact values causes no update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {"a" 1})
(is (= false (set-cert-facts-causes-update "foo" {"a" 2}))))
(testing "with paths, changing paths causes update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {"a" 1})
(is (= true (set-cert-facts-causes-update "foo" {"b" 1}))))
(testing "with paths, adding path causes update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {"a" 1})
(is (= true (set-cert-facts-causes-update "foo" {"a" 1 "b" 1}))))
(testing "with paths, removing path causes update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {"a" 1 "b" 1})
(is (= true (set-cert-facts-causes-update "foo" {"b" 1})))))))
(deftest-db fact-persistance-with-environment
(testing "Persisted facts"
(let [certname "some_certname"
facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"}
producer "bar.com"]
(add-certname! certname)
(is (nil?
(jdbc/with-db-transaction []
(timestamp-of-newest-record :factsets "some_certname"))))
(is (empty? (factset-map "some_certname")))
(is (nil? (environment-id "PROD")))
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment "PROD"
:producer_timestamp previous-time
:producer producer})
(testing "should have entries for each fact"
(is (= facts (factset-map "some_certname")))
(is (= [{:certname "some_certname"
:environment_id (environment-id "PROD")}]
(query-to-vec "SELECT certname, environment_id FROM factsets"))))
(is (nil? (environment-id "DEV")))
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer})
(testing "should have the same entries for each fact"
(is (= facts (factset-map "some_certname")))
(is (= [{:certname "some_certname"
:environment_id (environment-id "DEV")}]
(query-to-vec "SELECT certname, environment_id FROM factsets")))))))
(defn package-seq
"Return all facts and their values for a given certname as a map"
[certname]
(rest
(jdbc/query
["SELECT p.name as package_name, p.version, p.provider
FROM certname_packages cp
inner join packages p on cp.package_id = p.id
inner join certnames c on cp.certname_id = c.id
WHERE c.certname = ?
ORDER BY package_name, version, provider"
certname]
{:as-arrays? true})))
(deftest-db fact-persistance-with-packages
(testing "Existing facts with new packages added"
(let [certname "some_certname"
facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"}
producer "bar.com"]
(add-certname! certname)
(testing "Existing facts with new packages added"
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment "PROD"
:producer_timestamp previous-time
:producer producer})
(is (empty? (package-seq certname)))
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo" "1.2.3" "apt"]
["bar" "2.3.4" "apt"]
["baz" "3.4.5" "apt"]]})
(is (= [["bar" "2.3.4" "apt"]
["baz" "3.4.5" "apt"]
["foo" "1.2.3" "apt"]]
(package-seq certname))))
(testing "Updating existing packages"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo" "1.2.3" "apt"]
["bar" "2.3.4" "apt"]
["not-baz" "3.4.5" "apt"]]})
(is (= [["bar" "2.3.4" "apt"]
["foo" "1.2.3" "apt"]
["not-baz" "3.4.5" "apt"]]
(package-seq certname))))
(testing "Removing packages"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo" "1.2.3" "apt"]]})
(is (= [["foo" "1.2.3" "apt"]]
(package-seq certname))))
(testing "Removing packages"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo-1" "1.2.3" "apt"]
["foo-2" "1.2.3" "apt"]
["foo-3" "1.2.3" "apt"]
["foo-4" "1.2.3" "apt"]]})
(is (= [["foo-1" "1.2.3" "apt"]
["foo-2" "1.2.3" "apt"]
["foo-3" "1.2.3" "apt"]
["foo-4" "1.2.3" "apt"]]
(package-seq certname))))
(testing "Pinpoint GC cleans up packages"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo-1" "1.2.3" "apt"]]})
(is (= [["foo-1" "1.2.3" "apt"]]
(package-seq certname)))
(is (= 1
(-> ["SELECT count(*) as c FROM packages"]
query-to-vec
first
:c))))
(testing "Orphaned packages are deleted"
(let [package-count (fn [] (-> ["SELECT count(*) as c FROM packages"]
query-to-vec
first
:c))]
(is (pos? (package-count)))
(jdbc/do-commands "DELETE FROM certname_packages")
(is (pos? (package-count)))
(delete-unassociated-packages!)
(is (zero? (package-count))))))))
(deftest-db purge-packages-from-node
(testing "Existing facts with new packages added"
(let [certname "some_certname"
facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"}
producer "bar.com"
reload-packages (fn []
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo" "1.2.3" "apt"]
["bar" "2.3.4" "apt"]
["baz" "3.4.5" "apt"]]}))
find-package-hash (fn []
(:package_hash (certname-factset-metadata "some_certname")))]
(add-certname! certname)
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment "PROD"
:producer_timestamp previous-time
:producer producer})
(is (empty? (package-seq certname)))
(reload-packages)
(testing "data was loaded for test"
(is (= 3 (count (package-seq certname)))))
(is (find-package-hash))
(testing "package_inventory key is missing from command"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer})
(is (= []
(package-seq certname)))
(is (nil? (find-package-hash))))
(reload-packages)
(is (= 3 (count (package-seq certname))))
(testing "package_inventory is nil"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory nil})
(is (= 0 (count (package-seq certname))))
(is (nil? (find-package-hash))))
(reload-packages)
(is (= 3 (count (package-seq certname))))
(is (find-package-hash))
(testing "package_inventory is empty"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory []})
(is (= 0 (count (package-seq certname))))
(is (nil? (find-package-hash)))))))
(def catalog (:basic catalogs))
(def certname (:certname catalog))
(def current-time (str (now)))
(deftest-db catalog-persistence
(testing "Persisted catalogs"
(add-certname! certname)
(replace-catalog! (assoc catalog :producer_timestamp current-time))
(testing "should contain proper catalog metadata"
(is (= (query-to-vec ["SELECT certname, api_version, catalog_version, producer_timestamp FROM catalogs"])
[{:certname certname :api_version 1 :catalog_version "123456789" :producer_timestamp (to-timestamp current-time)}])))
(testing "should contain a complete edges list"
(is (= (query-to-vec [(str "SELECT r1.type as stype, r1.title as stitle, r2.type as ttype, r2.title as ttitle, e.type as etype "
"FROM edges e, catalog_resources r1, catalog_resources r2 "
"WHERE e.source=r1.resource AND e.target=r2.resource "
"ORDER BY r1.type, r1.title, r2.type, r2.title, e.type")])
[{:stype "Class" :stitle "foobar" :ttype "File" :ttitle "/etc/foobar" :etype "contains"}
{:stype "Class" :stitle "foobar" :ttype "File" :ttitle "/etc/foobar/baz" :etype "contains"}
{:stype "File" :stitle "/etc/foobar" :ttype "File" :ttitle "/etc/foobar/baz" :etype "required-by"}])))
(testing "should contain a complete resources list"
(is (= (query-to-vec ["SELECT type, title FROM catalog_resources ORDER BY type, title"])
[{:type "Class" :title "foobar"}
{:type "File" :title "/etc/foobar"}
{:type "File" :title "/etc/foobar/baz"}]))
(testing "properly associated with the host"
(is (= (query-to-vec ["SELECT c.certname, cr.type, cr.title
FROM catalog_resources cr, certnames c
WHERE c.id=cr.certname_id
ORDER BY cr.type, cr.title"])
[{:certname certname :type "Class" :title "foobar"}
{:certname certname :type "File" :title "/etc/foobar"}
{:certname certname :type "File" :title "/etc/foobar/baz"}])))
(testing "with all parameters"
(is (= (query-to-vec ["SELECT cr.type, cr.title, rp.name, rp.value FROM catalog_resources cr, resource_params rp WHERE rp.resource=cr.resource ORDER BY cr.type, cr.title, rp.name"])
[{:type "File" :title "/etc/foobar" :name "ensure" :value (sutils/db-serialize "directory")}
{:type "File" :title "/etc/foobar" :name "group" :value (sutils/db-serialize "root")}
{:type "File" :title "/etc/foobar" :name "user" :value (sutils/db-serialize "root")}
{:type "File" :title "/etc/foobar/baz" :name "ensure" :value (sutils/db-serialize "directory")}
{:type "File" :title "/etc/foobar/baz" :name "group" :value (sutils/db-serialize "root")}
{:type "File" :title "/etc/foobar/baz" :name "require" :value (sutils/db-serialize "File[/etc/foobar]")}
{:type "File" :title "/etc/foobar/baz" :name "user" :value (sutils/db-serialize "root")}])))
(testing "with all metadata"
(let [result (query-to-vec ["SELECT cr.type, cr.title, cr.exported, cr.tags, cr.file, cr.line FROM catalog_resources cr ORDER BY cr.type, cr.title"])]
(is (= (map #(assoc % :tags (sort (:tags %))) result)
[{:type "Class" :title "foobar" :tags ["class" "foobar"] :exported false :file nil :line nil}
{:type "File" :title "/etc/foobar" :tags ["class" "file" "foobar"] :exported false :file "/tmp/foo" :line 10}
{:type "File" :title "/etc/foobar/baz" :tags ["class" "file" "foobar"] :exported false :file "/tmp/bar" :line 20}])))))))
(deftest-db catalog-persistence-with-environment
(let [other-certname "notbasic.catalogs.com"]
(testing "Persisted catalogs"
(add-certname! certname)
(add-certname! other-certname)
(is (nil? (environment-id "PROD")))
(replace-catalog! (assoc catalog :environment "PROD"))
(testing "should persist environment if the environment is new"
(let [id (environment-id "PROD")]
(is (number? (environment-id "PROD")))
(is (= [{:certname certname :api_version 1 :catalog_version "123456789" :environment_id id}]
(query-to-vec ["SELECT certname, api_version, catalog_version, environment_id FROM catalogs"])))
(testing "Adding another catalog with the same environment should just use the existing environment"
(replace-catalog! (assoc catalog :environment "PROD" :certname other-certname))
(is (= [{:certname other-certname :api_version 1 :catalog_version "123456789" :environment_id id}]
(query-to-vec ["SELECT certname, api_version, catalog_version, environment_id FROM catalogs where certname=?" other-certname])))))))))
(deftest-db updating-catalog-environment
(testing "should persist environment if the environment is new"
(let [prod-id (ensure-environment "PROD")
dev-id (ensure-environment "DEV")]
(add-certname! certname)
(replace-catalog! (assoc catalog :environment "DEV"))
(is (= [{:certname certname :api_version 1 :catalog_version "123456789" :environment_id dev-id}]
(query-to-vec ["SELECT certname, api_version, catalog_version, environment_id FROM catalogs"])))
(replace-catalog! (assoc catalog :environment "PROD"))
(is (= [{:certname certname :api_version 1 :catalog_version "123456789" :environment_id prod-id}]
(query-to-vec ["SELECT certname, api_version, catalog_version, environment_id FROM catalogs"]))))))
(deftest-db catalog-replacement
(testing "should noop if replaced by themselves"
(add-certname! certname)
(let [hash (replace-catalog! catalog)]
(replace-catalog! catalog (now))
(is (= (query-to-vec ["SELECT certname FROM certnames"])
[{:certname certname}]))
(is (= (query-to-vec [(format "SELECT %s AS hash FROM catalogs" (sutils/sql-hash-as-str "hash"))])
[{:hash hash}])))))
(deftest-db edge-replacement-differential
(testing "should do selective inserts/deletes when edges are modified just slightly"
(add-certname! certname)
(let [original-catalog (:basic catalogs)
original-edges (:edges original-catalog)
modified-edges (conj (disj original-edges {:source {:type "Class" :title "foobar"}
:target {:type "File" :title "/etc/foobar"}
:relationship :contains})
{:source {:type "File" :title "/etc/foobar"}
:target {:type "File" :title "/etc/foobar/baz"}
:relationship :before})
modified-catalog (assoc original-catalog :edges modified-edges)]
;; Add an initial catalog, we don't care to intercept the SQL yet
(replace-catalog! original-catalog (now))
(testing "ensure catalog-edges-map returns a predictable value"
(is (= (catalog-edges-map certname)
{["ff0702ba8a7dc69d3fb17f9d151bf9bd265a9ed9"
"57495b553981551c5194a21b9a26554cd93db3d9"
"contains"] nil,
["57495b553981551c5194a21b9a26554cd93db3d9"
"e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1"
"required-by"] nil,
["ff0702ba8a7dc69d3fb17f9d151bf9bd265a9ed9"
"e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1"
"contains"] nil})))
;; Lets intercept the insert/update/delete level so we can test it later
;; Here we only replace edges, so we can capture those specific SQL
;; operations
(tu/with-wrapped-fn-args [insert-multis jdbc/insert-multi!
deletes jdbc/delete!]
(let [resources (:resources modified-catalog)
refs-to-hash (reduce-kv (fn [i k v]
(assoc i k (shash/resource-identity-hash v)))
{} resources)]
(replace-edges! certname modified-edges refs-to-hash)
(testing "ensure catalog-edges-map returns a predictable value"
(is (= (catalog-edges-map certname)
{["ff0702ba8a7dc69d3fb17f9d151bf9bd265a9ed9"
"e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1"
"contains"] nil,
["57495b553981551c5194a21b9a26554cd93db3d9"
"e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1"
"required-by"] nil
["57495b553981551c5194a21b9a26554cd93db3d9"
"e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1"
"before"] nil})))
(testing "should only delete the 1 edge"
(let [source-hash "ff0702ba8a7dc69d3fb17f9d151bf9bd265a9ed9"
target-hash "57495b553981551c5194a21b9a26554cd93db3d9"]
(is (= [[:edges [(str "certname=?"
" and source=?::bytea"
" and target=?::bytea"
" and type=?")
"basic.catalogs.com"
(sutils/bytea-escape source-hash)
(sutils/bytea-escape target-hash)
"contains"]]]
@deletes))))
(testing "should only insert the 1 edge"
(is (= [[:edges [{:certname "basic.catalogs.com"
:source (sutils/munge-hash-for-storage "57495b553981551c5194a21b9a26554cd93db3d9")
:target (sutils/munge-hash-for-storage "e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1")
:type "before"}]]]
@insert-multis)))
(testing "when reran to check for idempotency"
(reset! insert-multis [])
(reset! deletes [])
(replace-edges! certname modified-edges refs-to-hash)
(testing "should delete no edges"
(is (empty? @deletes)))
(testing "should insert no edges"
(is (empty? @insert-multis)))))))))
(deftest-db catalog-duplicates
(testing "should share structure when duplicate catalogs are detected for the same host"
(add-certname! certname)
(let [hash (replace-catalog! catalog)
prev-dupe-num (counters/value (:duplicate-catalog performance-metrics))
prev-new-num (counters/value (:updated-catalog performance-metrics))]
;; Do an initial replacement with the same catalog
(replace-catalog! catalog (now))
(is (= 1 (- (counters/value (:duplicate-catalog performance-metrics)) prev-dupe-num)))
(is (= 0 (- (counters/value (:updated-catalog performance-metrics)) prev-new-num)))
;; Store a second catalog, with the same content save the version
(replace-catalog! (assoc catalog :version "abc123") (now))
(is (= 2 (- (counters/value (:duplicate-catalog performance-metrics)) prev-dupe-num)))
(is (= 0 (- (counters/value (:updated-catalog performance-metrics)) prev-new-num)))
(is (= (query-to-vec ["SELECT certname FROM certnames"])
[{:certname certname}]))
(is (= (query-to-vec [(format "SELECT certname, %s AS hash FROM catalogs" (sutils/sql-hash-as-str "hash"))])
[{:hash hash
:certname certname}]))
(replace-catalog! (assoc-in catalog [:resources {:type "File" :title "/etc/foobar"} :line] 20) (now))
(is (= 2 (- (counters/value (:duplicate-catalog performance-metrics)) prev-dupe-num)))
(is (= 1 (- (counters/value (:updated-catalog performance-metrics)) prev-new-num))))))
(deftest-db fact-delete-deletes-facts
(add-certname! certname)
;; Add some facts
(let [facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"
"networking" {"eth0" {"ipaddresses" ["192.168.0.11"]}}}]
(add-facts! {:certname certname
:values facts
:timestamp (-> 2 days ago)
:environment "ENV3"
:producer_timestamp (-> 2 days ago)
:producer "bar.com"}))
(is (= 6 (count-facts)))
(is (= 6 (count-facts)))
(delete-certname-facts! certname)
(is (= 0 (count-facts)))
(is (= 0 (count-facts))))
(deftest-db catalog-bad-input
(testing "should noop"
(testing "on bad input"
(is (thrown? clojure.lang.ExceptionInfo (replace-catalog! {})))
;; Nothing should have been persisted for this catalog
(is (= (query-to-vec ["SELECT count(*) as nrows from certnames"])
[{:nrows 0}])))))
(defn foobar->foobar2 [x]
(if (and (string? x) (= x "/etc/foobar"))
"/etc/foobar2"
x))
(defn table-args
"Many of the puppetdb.jdbc functions accept a table name as the first arg, this
function grabs that argument"
[coll]
(map first coll))
(defn remove-edge-changes
"Remove the edge related changes from the `coll` of function call arguments"
[coll]
(remove #(= :edges (first %)) coll))
(defn sort= [& args]
(apply = (map sort args)))
(deftest-db existing-catalog-update
(let [{certname :certname :as catalog} (:basic catalogs)
old-date (-> 2 days ago)
yesterday (-> 1 days ago)]
(testing "inserting new catalog with resources"
(add-certname! certname)
(is (empty? (query-to-vec "SELECT * from catalogs where certname=?" certname)))
(replace-catalog! catalog old-date)
(let [results (query-to-vec "SELECT timestamp from catalogs where certname=?" certname)
{:keys [timestamp]} (first results)]
(is (= 1 (count results)))
(is (= (to-timestamp old-date) (to-timestamp timestamp)))))
(testing "changing a resource title"
(let [[{orig-id :id
orig-tx-id :transaction_uuid
orig-timestamp :timestamp}]
(query-to-vec (str "select id, timestamp, transaction_uuid::text"
" from catalogs where certname=?")
certname)
updated-catalog (walk/prewalk foobar->foobar2 (:basic catalogs))
new-uuid (kitchensink/uuid)
metrics-map performance-metrics]
(is (= #{{:type "Class" :title "foobar"}
{:type "File" :title "/etc/foobar"}
{:type "File" :title "/etc/foobar/baz"}}
(set (query-to-vec "SELECT cr.type, cr.title
FROM catalogs c
INNER JOIN certnames on c.certname=certnames.certname
INNER JOIN catalog_resources cr
ON certnames.id=cr.certname_id
WHERE c.certname=?" certname))))
(tu/with-wrapped-fn-args [inserts jdbc/insert!
insert-multis jdbc/insert-multi!
deletes jdbc/delete!
updates jdbc/update!]
(with-redefs [performance-metrics
(assoc metrics-map
:catalog-volatility (histogram storage-metrics-registry [(str (gensym))]))]
(replace-catalog! (assoc updated-catalog :transaction_uuid new-uuid) yesterday)
;; 2 edge deletes
;; 2 edge inserts
;; 1 params insert
;; 1 params cache insert
;; 1 catalog_resource insert
;; 1 catalog_resource delete
(is (= 8 (apply + (sample (:catalog-volatility performance-metrics))))))
(is (sort= [:resource_params_cache :resource_params :catalog_resources :edges]
(table-args (concat @inserts @insert-multis))))
(is (= [:catalogs]
(table-args @updates)))
(is (= [[:catalog_resources ["certname_id = ? and type = ? and title = ?"
(-> @updates first (nth 2) second)
"File" "/etc/foobar"]]]
(remove-edge-changes @deletes))))
(is (= #{{:type "Class" :title "foobar"}
{:type "File" :title "/etc/foobar2"}
{:type "File" :title "/etc/foobar/baz"}}
(set (query-to-vec "SELECT cr.type, cr.title
FROM catalogs c
INNER JOIN certnames ON certnames.certname = c.certname
INNER JOIN catalog_resources cr ON cr.certname_id = certnames.id
WHERE c.certname=?" certname))))
(let [results (query-to-vec
(str "select id, timestamp, transaction_uuid::text"
" from catalogs where certname=?")
certname)
{new-timestamp :timestamp
new-tx-id :transaction_uuid
new-id :id} (first results)]
(is (= 1 (count results)))
(is (= (to-timestamp yesterday) (to-timestamp new-timestamp)))
(is (= new-tx-id new-uuid))
(is (= orig-id new-id))
(is (not= orig-tx-id new-tx-id))
(is (not= orig-timestamp new-timestamp)))))))
(comment
(existing-catalog-update)
)
(deftest-db add-resource-to-existing-catalog
(let [{certname :certname :as catalog} (:basic catalogs)
old-date (-> 2 days ago)
yesterday (-> 1 days ago)]
(add-certname! certname)
(replace-catalog! catalog old-date)
(is (= 3 (:c (first (query-to-vec "SELECT count(*) AS c FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname)))))
(tu/with-wrapped-fn-args [inserts jdbc/insert!
insert-multis jdbc/insert-multi!
updates jdbc/update!
deletes jdbc/delete!]
(replace-catalog! (assoc-in catalog
[:resources {:type "File" :title "/etc/foobar2"}]
{:type "File"
:title "/etc/foobar2"
:exported false
:file "/tmp/foo2"
:line 20
:tags #{"file" "class" "foobar"}
:parameters {:ensure "directory"
:group "root"
:user "root"}})
old-date)
(is (sort= [:resource_params_cache :resource_params :catalog_resources]
(table-args (concat @inserts @insert-multis))))
(is (= [:catalogs] (table-args @updates)))
(is (empty? @deletes)))
(is (= 4 (:c (first (query-to-vec "SELECT count(*) AS c FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname)))))))
(deftest-db change-line-resource-metadata
(add-certname! certname)
(replace-catalog! catalog)
(testing "changing line number"
(is (= #{{:line nil}
{:line 10}
{:line 20}}
(set (query-to-vec "SELECT line FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname))))
(replace-catalog! (update-in catalog [:resources]
(fn [resources]
(kitchensink/mapvals #(assoc % :line 1000) resources))))
(is (= [{:line 1000}
{:line 1000}
{:line 1000}]
(query-to-vec "SELECT line FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname)))))
(deftest-db change-exported-resource-metadata
(add-certname! certname)
(replace-catalog! catalog)
(testing "changing exported"
(is (= #{{:exported false
:title "foobar"}
{:exported false
:title "/etc/foobar"}
{:exported false
:title "/etc/foobar/baz"}}
(set (query-to-vec "SELECT title, exported FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname))))
(replace-catalog! (update-in catalog [:resources]
(fn [resources]
(-> resources
(assoc-in [{:type "Class" :title "foobar"} :exported] true)
(assoc-in [{:type "File" :title "/etc/foobar/baz"} :exported] true)))))
(is (= #{{:exported true
:title "foobar"}
{:exported false
:title "/etc/foobar"}
{:exported true
:title "/etc/foobar/baz"}}
(set (query-to-vec "SELECT title, exported FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname))))))
(deftest-db change-file-resource-metadata
(add-certname! certname)
(replace-catalog! catalog)
(testing "changing line number"
(is (= #{{:title "foobar"
:file nil}
{:title "/etc/foobar"
:file "/tmp/foo"}
{:title "/etc/foobar/baz"
:file "/tmp/bar"}}
(set (query-to-vec "SELECT title, file FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname))))
(replace-catalog! (update-in catalog [:resources]
(fn [resources]
(kitchensink/mapvals #(assoc % :file "/tmp/foo.pp") resources))))
(is (= #{{:title "foobar"
:file "/tmp/foo.pp"}
{:title "/etc/foobar"
:file "/tmp/foo.pp"}
{:title "/etc/foobar/baz"
:file "/tmp/foo.pp"}}
(set (query-to-vec "SELECT title, file FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname))))))
(defn tags->set
"Converts tags from a pg-array to a set of strings"
[result-set]
(mapv (fn [result]
(update-in result [:tags] #(jdbc/convert-any-sql-array % set)))
result-set))
(deftest-db change-tags-on-resource
(add-certname! certname)
(replace-catalog! catalog)
(is (= #{{:title "foobar"
:tags #{"class" "foobar"}
:line nil}
{:title "/etc/foobar"
:tags #{"file" "class" "foobar"}
:line 10}
{:title "/etc/foobar/baz"
:tags #{"file" "class" "foobar"}
:line 20}}
(call-with-query-rows
[(str "select title, tags, line from catalog_resources"
" inner join certnames c on c.id = certname_id"
" where c.certname = ?")
certname]
#(-> % tags->set set))))
(replace-catalog! (update-in catalog [:resources]
(fn [resources]
(-> resources
(assoc-in [{:type "File" :title "/etc/foobar"} :tags] #{"totally" "different" "tags"})
(assoc-in [{:type "File" :title "/etc/foobar"} :line] 500)))))
(is (= #{{:title "foobar"
:tags #{"class" "foobar"}
:line nil}
{:title "/etc/foobar"
:line 500
:tags #{"totally" "different" "tags"}}
{:title "/etc/foobar/baz"
:line 20
:tags #{"file" "class" "foobar"}}}
(call-with-query-rows
[(str "select title, tags, line from catalog_resources"
" inner join certnames c on c.id = certname_id"
" where c.certname = ?")
certname]
#(-> % tags->set set)))))
(deftest-db removing-resources
(let [{certname :certname :as catalog} (:basic catalogs)
old-date (-> 2 days ago)
yesterday (-> 1 days ago)
catalog-with-extra-resource (assoc-in catalog
[:resources {:type "File" :title "/etc/the-foo"}]
{:type "File"
:title "/etc/the-foo"
:exported false
:file "/tmp/the-foo"
:line 10
:tags #{"file" "class" "the-foo"}
:parameters {:ensure "directory"
:group "root"
:user "root"}})]
(add-certname! certname)
(replace-catalog! catalog-with-extra-resource old-date)
(let [certname-id (:id (first (query-to-vec "SELECT id from certnames where certname=?" certname)))]
(is (= 4 (count (query-to-vec "SELECT * from catalog_resources where certname_id = ?" certname-id))))
(tu/with-wrapped-fn-args [inserts jdbc/insert!
updates jdbc/update!
deletes jdbc/delete!]
(replace-catalog! catalog yesterday)
(is (empty? @inserts))
(is (= [:catalogs] (table-args @updates)))
(is (= [:catalog_resources] (table-args @deletes))))
(let [catalog-results (query-to-vec "SELECT timestamp from catalogs where certname=?" certname)
{:keys [timestamp]} (first catalog-results)
resources (set (query-to-vec "SELECT type, title from catalog_resources where certname_id = ?" certname-id))]
(is (= 1 (count catalog-results)))
(is (= 3 (count resources)))
(is (= (set (keys (:resources catalog)))
resources))
(is (= (to-timestamp yesterday) (to-timestamp timestamp)))))))
(defn foobar-params []
(jdbc/query-with-resultset
["SELECT p.name AS k, p.value AS v
FROM catalog_resources cr, certnames c, resource_params p
WHERE cr.certname_id = c.id AND cr.resource = p.resource AND c.certname=?
AND cr.type=? AND cr.title=?"
(get-in catalogs [:basic :certname]) "File" "/etc/foobar"]
(fn [rs]
(reduce (fn [acc row]
(assoc acc (keyword (:k row))
(json/parse-string (:v row))))
{}
(sql/result-set-seq rs)))))
(defn foobar-params-cache []
(jdbc/query-with-resultset
["SELECT rpc.parameters as params
FROM catalog_resources cr, certnames c, resource_params_cache rpc
WHERE cr.certname_id = c.id AND cr.resource = rpc.resource AND c.certname=?
AND cr.type=? AND cr.title=?"
(get-in catalogs [:basic :certname]) "File" "/etc/foobar"]
#(-> (sql/result-set-seq %)
first
:params
sutils/parse-db-json)))
(defn foobar-param-hash []
(jdbc/query-with-resultset
[(format "SELECT %s AS hash
FROM catalog_resources cr, certnames c
WHERE cr.certname_id = c.id AND c.certname=? AND cr.type=?
AND cr.title=?"
(sutils/sql-hash-as-str "cr.resource"))
(get-in catalogs [:basic :certname]) "File" "/etc/foobar"]
(comp :hash first sql/result-set-seq)))
(deftest-db catalog-resource-parameter-changes
(let [{certname :certname :as catalog} (:basic catalogs)
old-date (-> 2 days ago)
yesterday (-> 1 days ago)]
(add-certname! certname)
(replace-catalog! catalog old-date)
(let [orig-resource-hash (foobar-param-hash)
add-param-catalog (assoc-in catalog [:resources {:type "File" :title "/etc/foobar"} :parameters :uid] "100")]
(is (= (get-in catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params)))
(is (= (get-in catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params-cache)))
(tu/with-wrapped-fn-args [inserts jdbc/insert!
insert-multis jdbc/insert-multi!
updates jdbc/update!
deletes jdbc/delete!]
(replace-catalog! add-param-catalog yesterday)
(is (sort= [:catalogs :catalog_resources]
(table-args @updates)))
(is (empty? (remove-edge-changes @deletes)))
(is (sort= [:resource_params_cache :resource_params :edges]
(->> (concat @inserts @insert-multis)
(remove #(empty? (second %))) ;; remove inserts w/out rows
table-args))))
(is (not= orig-resource-hash (foobar-param-hash)))
(is (= (get-in add-param-catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params)))
(is (= (get-in add-param-catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params-cache)))
(tu/with-wrapped-fn-args [inserts jdbc/insert!
insert-multis jdbc/insert-multi!
updates jdbc/update!
deletes jdbc/delete!]
(replace-catalog! catalog old-date)
(is (empty? (remove #(or (= :edges (first %)) (empty? (second %)))
(concat @inserts @insert-multis))))
(is (empty? (remove #(= :edges (first %)) @deletes)))
(is (= (sort [:catalog_resources :catalogs])
(sort (table-args @updates)))))
(is (= orig-resource-hash (foobar-param-hash)))
(is (= (get-in catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params)))
(is (= (get-in catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params-cache))))))
(deftest-db catalog-referential-integrity-violation
(testing "on input that violates referential integrity"
;; This catalog has an edge that points to a non-existant resource
(let [catalog (:invalid catalogs)]
(is (thrown? clojure.lang.ExceptionInfo (replace-catalog! catalog)))
;; Nothing should have been persisted for this catalog
(is (= (query-to-vec ["SELECT count(*) as nrows from certnames"])
[{:nrows 0}])))))
(deftest-db node-deactivation
(let [certname "foo.example.com"
query-certnames #(query-to-vec ["select certname, deactivated from certnames"])
deactivated? #(instance? java.sql.Timestamp (:deactivated %))]
(add-certname! certname)
(testing "deactivating a node"
(testing "should mark the node as deactivated"
(deactivate-node! certname)
(let [result (first (query-certnames))]
(is (= certname (:certname result)))
(is (deactivated? result))))
(testing "should not change the node if it's already inactive"
(let [original (query-certnames)]
(deactivate-node! certname)
;; Convert any :deactivated values to #t for comparison
;; since we only care about the state.
(letfn [(deactivated->truthy [x]
(assoc x :deactivated (when (:deactivated x) true)))]
(is (= (map deactivated->truthy original)
(map deactivated->truthy (query-certnames))))))))
(testing "activating a node"
(testing "should activate the node if it was inactive"
(activate-node! certname)
(is (= (query-certnames) [{:certname certname :deactivated nil}])))
(testing "should do nothing if the node is already active"
(let [original (query-certnames)]
(activate-node! certname)
(is (= original (query-certnames))))))
(testing "auto-reactivated based on a command"
(let [before-deactivating (to-timestamp (-> 1 days ago))
after-deactivating (to-timestamp (-> 1 days from-now))]
(testing "should activate the node if the command happened after it was deactivated"
(deactivate-node! certname)
(is (= true (maybe-activate-node! certname after-deactivating)))
(is (= (query-certnames) [{:certname certname :deactivated nil}])))
(testing "should not activate the node if the command happened before it was deactivated"
(deactivate-node! certname)
(is (= false (maybe-activate-node! certname before-deactivating)))
(let [result (first (query-certnames))]
(is (= certname (:certname result)))
(is (deactivated? result))))
(testing "should do nothing if the node is already active"
(activate-node! certname)
(is (= false (maybe-activate-node! certname (now))))
(is (= (query-certnames) [{:certname certname :deactivated nil}])))))))
(deftest-db fresh-node-not-expired
(testing "fresh nodes are not expired"
(let [catalog (:empty catalogs)
certname (:certname catalog)]
(add-certname! certname)
(replace-catalog! (assoc catalog :producer_timestamp (now)) (now))
(is (= [] (expire-stale-nodes (-> 3 days .toPeriod))))
(is (= (map :certname (query-to-vec "select certname from certnames"))
[certname])))))
(deftest expire-nodes-with-stale-catalogs-and-facts-or-none
(testing "nodes with only stale facts/catalogs or no facts/catalogs expire"
(let [mutators {:rc #(replace-catalog!
(assoc (:empty catalogs) :certname "node1")
(-> 2 days ago))
:rf #(replace-facts!
{:certname "node1"
:values {"foo" "bar"}
:environment "DEV"
:producer_timestamp (-> 10 days ago)
:timestamp (-> 2 days ago)
:producer "baz.com"})}]
(doseq [ops (subsets (keys mutators))]
(with-test-db
(add-certname! "node1")
(dorun (map #((mutators %)) ops))
(is (= [ops ["node1"]]
[ops (expire-stale-nodes (-> 1 days .toPeriod))])))))))
(deftest-db node-with-only-fresh-report-is-not-expired
(testing "does not expire a node with a recent report and nothing else"
(let [report (-> (:basic reports)
(assoc :environment "ENV2")
(assoc :end_time (now))
(assoc :producer_timestamp (now)))]
(store-example-report! report (now))
(is (= [] (expire-stale-nodes (-> 1 days .toPeriod)))))))
(deftest stale-nodes-expiration-via-reports
(let [report-at #(assoc (:basic reports)
:environment "ENV2"
:end_time %
:producer_timestamp %)
stamp (now)
stale-stamp-1 (-> 2 days ago)
stale-stamp-2 (-> 3 days ago)]
(with-test-db
(testing "doesn't return node with a recent report and nothing else"
(store-example-report! (report-at stamp) stamp)
(is (= [] (expire-stale-nodes (-> 1 days .toPeriod)))))
(testing "doesn't return node with a recent report and a stale report"
(store-example-report! (report-at stale-stamp-1) stale-stamp-1)
(is (= [] (expire-stale-nodes (-> 1 days .toPeriod))))))
(with-test-db
(testing "returns a node with only stale reports"
(store-example-report! (report-at stale-stamp-1) stale-stamp-1)
(store-example-report! (report-at stale-stamp-2) stale-stamp-2)
(is (= ["foo.local"] (expire-stale-nodes (-> 1 days .toPeriod))))))))
(deftest-db stale-nodes-expiration-via-catalogs
(let [repcat (fn [type stamp]
(replace-catalog! (assoc (type catalogs)
:certname "node1"
:producer_timestamp stamp)
stamp))
stamp (now)
stale-stamp (-> 2 days ago)]
(with-test-db
(testing "doesn't return node with a recent catalog and nothing else"
(add-certname! "node1")
(repcat :empty stamp)
(is (= [] (expire-stale-nodes (-> 1 days .toPeriod))))))
(with-test-db
(testing "returns a node with only a stale catalog"
(add-certname! "node1")
(repcat :empty stale-stamp)
(is (= ["node1"] (expire-stale-nodes (-> 1 days .toPeriod))))))))
(deftest-db only-nodes-older-than-max-age-expired
(testing "should only return nodes older than max age, and leave others alone"
(let [catalog (:empty catalogs)]
(add-certname! "node1")
(add-certname! "node2")
(replace-catalog! (assoc catalog
:certname "node1"
:producer_timestamp (-> 2 days ago))
(now))
(replace-catalog! (assoc catalog
:certname "node2"
:producer_timestamp (now))
(now))
(is (= ["node1"] (expire-stale-nodes (-> 1 days .toPeriod)))))))
(deftest-db node-purge
(testing "should purge nodes which were deactivated before the specified date"
(add-certname! "node1")
(add-certname! "node2")
(add-certname! "node3")
(deactivate-node! "node1")
(deactivate-node! "node2" (-> 10 days ago))
(purge-deactivated-and-expired-nodes! (-> 5 days ago))
(is (= (map :certname
(query-to-vec
"select certname from certnames order by certname asc"))
["node1" "node3"]))))
(deftest-db node-purge-cleans-packages
(testing "should purge nodes which were deactivated before the specified date"
(add-certname! "node1")
(add-certname! "node2")
(insert-packages "node1" [["foo" "1.2.3" "apt"] ["bar" "2.3.4" "apt"]])
(insert-packages "node2" [["foo" "1.2.3" "apt"] ["bar" "2.3.4" "apt"]])
(deactivate-node! "node1")
(deactivate-node! "node2" (-> 10 days ago))
(purge-deactivated-and-expired-nodes! (-> 5 days ago))
(is (= 1
(count (query-to-vec
"select certname_id from certname_packages group by certname_id"))))))
(deftest-db delete-certname-cleans-packages
(add-certname! "node1")
(add-certname! "node2")
(insert-packages "node1" [["foo" "1.2.3" "apt"] ["bar" "2.3.4" "apt"]])
(insert-packages "node2" [["foo" "1.2.3" "apt"] ["bar" "2.3.4" "apt"]])
(delete-certname! "node1")
(is (= 1
(count (query-to-vec
"select certname_id from certname_packages group by certname_id")))))
(deftest-db purge-expired-nodes
(testing "should purge nodes which were expired before the specified date"
(add-certname! "node1")
(add-certname! "node2")
(add-certname! "node3")
(expire-node! "node1" (now))
(expire-node! "node2" (-> 10 days ago))
(purge-deactivated-and-expired-nodes! (-> 5 days ago))
(is (= (map :certname
(query-to-vec
"select certname from certnames order by certname asc"))
["node1" "node3"]))))
(deftest-db report-sweep-nullifies-latest-report
(testing "ensure that if the latest report is swept, latest_report_id is updated to nil"
(let [report1 (assoc (:basic reports) :end_time (-> 12 days ago))
report2 (assoc (:basic reports) :certname "bar.local" :end_time (now) :producer_timestamp (now))]
(add-certname! "foo.local")
(add-certname! "bar.local")
(store-example-report! report1 (-> 12 days ago))
(store-example-report! report2 (now))
(let [ids (map :latest_report_id (query-to-vec "select latest_report_id from certnames order by certname"))
_ (delete-reports-older-than! (-> 11 days ago))
ids2 (map :latest_report_id (query-to-vec "select latest_report_id from certnames order by certname"))]
(is (= ids2 [(first ids) nil]))))))
;; Report tests
(defn update-event-timestamps
"Changes each timestamp in the `report`'s resource_events to `new-timestamp`"
[report new-timestamp]
(update-in report [:resource_events]
(fn [events]
(map #(assoc % :timestamp new-timestamp) events))))
(let [timestamp (now)
{:keys [certname] :as report} (:basic reports)
report-hash (-> report
report/report-query->wire-v8
normalize-report
shash/report-identity-hash)]
(deftest-db report-storage
(testing "should store reports"
(store-example-report! report timestamp)
(is (= [{:certname certname}]
(query-to-vec ["SELECT certname FROM reports"])))
(is (= [{:hash report-hash}]
(query-to-vec [(format "SELECT %s AS hash FROM reports" (sutils/sql-hash-as-str "hash"))])))
(testing "foss doesn't store in the resources column"
(is (nil? (:resources (first (query-to-vec ["SELECT resources FROM reports"])))))))
(testing "should store report with long puppet version string"
(store-example-report!
(assoc report
:puppet_version "3.2.1 (Puppet Enterprise 3.0.0-preview0-168-g32c839e)") timestamp)))
(deftest-db report-with-event-timestamp
(let [z-report (update-event-timestamps report "2011-01-01T12:00:01Z")
offset-report (update-event-timestamps report "2011-01-01T12:00:01-0000")]
(is (= (shash/report-identity-hash (normalize-report z-report))
(shash/report-identity-hash (normalize-report offset-report))))))
(deftest-db report-with-null-bytes-in-events
(store-example-report!
(-> report
(assoc-in [:resource_events :data 0 :new_value] "foo\u0000bar")
(assoc-in [:resource_events :data 0 :old_value] "foo\u0000bar"))
timestamp)
(is (= [{:old_value "\"foo\ufffdbar\""
:new_value "\"foo\ufffdbar\""}]
(query-to-vec ["SELECT old_value, new_value from resource_events where old_value ~ 'foo'"]))))
(deftest-db report-storage-with-environment
(is (nil? (environment-id "DEV")))
(store-example-report! (assoc report :environment "DEV") timestamp)
(is (number? (environment-id "DEV")))
(is (= (query-to-vec ["SELECT certname, environment_id FROM reports"])
[{:certname (:certname report)
:environment_id (environment-id "DEV")}])))
(deftest-db report-storage-with-producer
(let [prod-id (ensure-producer "bar.com")]
(store-example-report! (assoc report :producer "bar.com") timestamp)
(is (= (query-to-vec ["SELECT certname, producer_id FROM reports"])
[{:certname (:certname report)
:producer_id prod-id}]))))
(deftest-db report-storage-with-status
(is (nil? (status-id "unchanged")))
(store-example-report! (assoc report :status "unchanged") timestamp)
(is (number? (status-id "unchanged")))
(is (= (query-to-vec ["SELECT certname, status_id FROM reports"])
[{:certname (:certname report)
:status_id (status-id "unchanged")}])))
(deftest-db report-storage-without-resources
(testing "should store reports"
(let [env-id (ensure-environment "DEV")]
(store-example-report! (assoc-in report [:resource_events :data] []) timestamp)
(is (= (query-to-vec ["SELECT certname FROM reports"])
[{:certname (:certname report)}]))
(is (= (query-to-vec ["SELECT COUNT(1) as num_resource_events FROM resource_events"])
[{:num_resource_events 0}])))))
(deftest-db report-storage-with-existing-environment
(testing "should store reports"
(let [env-id (ensure-environment "DEV")]
(store-example-report! (assoc report :environment "DEV") timestamp)
(is (= (query-to-vec ["SELECT certname, environment_id FROM reports"])
[{:certname (:certname report)
:environment_id env-id}])))))
(deftest-db latest-report
(let [node (:certname report)
report-hash (:hash (store-example-report! report timestamp))]
(testing "should flag report as 'latest'"
(is (is-latest-report? node report-hash))
(let [new-report-hash (:hash (store-example-report!
(-> report
(assoc :configuration_version "bar")
(assoc :end_time (now))
(assoc :producer_timestamp (now)))
timestamp))]
(is (is-latest-report? node new-report-hash))
(is (not (is-latest-report? node report-hash)))))
(testing "should not update latest report with older report timestamp"
(let [old-report-hash (:hash (store-example-report!
(-> report
(assoc :configuration_version "bar")
(assoc :end_time (now))
(assoc :producer_timestamp (-> -1 days from-now)))
timestamp))]
(is (not (is-latest-report? node old-report-hash)))))))
(deftest-db report-cleanup
(testing "should delete reports older than the specified age"
(let [report1 (assoc report
:certname "foo"
:end_time (to-string (-> 5 days ago))
:producer_timestamp (to-string (-> 5 days ago)))
report2 (assoc report
:certname "bar"
:end_time (to-string (-> 2 days ago))
:producer_timestamp (to-string (-> 2 days ago)))]
(store-example-report! report1 timestamp)
(store-example-report! report2 timestamp)
(delete-reports-older-than! (-> 3 days ago))
(is (= (query-to-vec ["SELECT certname FROM reports"])
[{:certname "bar"}])))))
(deftest-db resource-events-cleanup
(testing "should delete all events for reports older than the specified age"
(let [report1 (assoc report :end_time (to-string (-> 5 days ago)))
report1-hash (:hash (store-example-report! report1 timestamp))
report2 (assoc report :end_time (to-string (-> 2 days ago)))]
(store-example-report! report2 timestamp)
(delete-reports-older-than! (-> 3 days ago))
(is (= #{}
(set (query-resource-events :latest ["=" "report" report1-hash] {}))))))))
(deftest test-catalog-schemas
(is (= (:basic catalogs) (s/validate catalog-schema (:basic catalogs)))))
(deftest test-resource-metadata-diff
(are [expected left right] (= expected (basic-diff left right))
{}
{:type "foo" :title "bar"}
{:type "foo" :title "bar"}
{:line 20}
{:type "File"
:title "/etc/foobar/baz"
:exported false
:file "/tmp/bar"
:line 10
:tags #{"file" "class" "foobar"}}
{:type "File"
:title "/etc/foobar/baz"
:exported false
:file "/tmp/bar"
:line 20
:tags #{"file" "class" "foobar"}}
{:exported true
:file "/tmp/bar/baz"
:line 30
:tags #{"file" "class" "foobar" "baz"}}
{:type "File"
:title "/etc/foobar/baz"
:exported false
:file "/tmp/bar"
:line 20
:tags #{"file" "class" "foobar"}}
{:type "File"
:title "/etc/foobar/baz"
:exported true
:file "/tmp/bar/baz"
:line 30
:tags #{"file" "class" "foobar" "baz"}}))
(deftest test-diff-resources-metadata
(let [resources-1 {{:type "File" :title "/etc/foobar"}
{:type "File"
:title "/etc/foobar"
:exported false
:file "/tmp/foo"
:line 10
:tags #{"file" "class" "foobar"}}
{:type "File" :title "/etc/foobar/baz"}
{:type "File"
:title "/etc/foobar/baz"
:exported false
:file "/tmp/bar"
:line 20
:tags #{"file" "class" "foobar"}}}
resources-2 {{:type "File" :title "/etc/foobar"}
{:type "File"
:title "/etc/foobar"
:exported false
:file "/tmp/foo"
:line 20
:tags #{"file" "class" "foobar"}}
{:type "File" :title "/etc/foobar/baz"}
{:type "File"
:title "/etc/foobar/baz"
:exported true
:file "/tmp/bar/baz"
:line 30
:tags #{"file" "class" "foobar" "baz"}}}]
(are [expected left right] (= expected (diff-resources-metadata left right))
{}
resources-1
resources-1
{{:type "File" :title "/etc/foobar"}
{:line 30}}
resources-1
(assoc-in resources-1 [{:type "File" :title "/etc/foobar"} :line] 30)
{{:type "File" :title "/etc/foobar"}
{:line 20}
{:type "File" :title "/etc/foobar/baz"}
{:exported true
:file "/tmp/bar/baz"
:line 30
:tags #{"file" "class" "foobar" "baz"}}}
resources-1
resources-2)))
(defn fake-hash
[]
(shash/generic-identity-hash (random/random-string)))
(deftest-db giant-resources-exist
(testing "resources-exist?"
(is (= #{} (resources-exist? (set (take 40000 (repeatedly fake-hash))))))))
(deftest-db test-merge-resource-hash
(let [ref->resource {{:type "File" :title "/tmp/foo"}
{:line 10}
{:type "File" :title "/tmp/bar"}
{:line 20}}
ref->hash {{:type "File" :title "/tmp/foo"}
"foo hash"
{:type "File" :title "/tmp/bar"}
"bar hash"}]
(is (= {{:type "File" :title "/tmp/foo"}
{:line 10 :resource "foo hash"}
{:type "File" :title "/tmp/bar"}
{:line 20 :resource "bar hash"}}
(merge-resource-hash ref->hash ref->resource)))))
(deftest-db test-resources-exist?
(testing "With empty input"
(is (= #{} (resources-exist? #{})))))
(deftest-db setting-fact-expiration-for-certname
(is (= [] (query-to-vec "select * from certname_fact_expiration")))
(add-certname! "foo")
(is (= [] (query-to-vec "select * from certname_fact_expiration")))
(let [stamp-1 (to-timestamp (now))
stamp-2 (to-timestamp (time/plus (now) (time/seconds 1)))
id (-> "select id from certnames where certname = 'foo'"
query-to-vec first :id)]
(set-certname-facts-expiration "foo" true stamp-1)
(is (= [{:certid id :expire true :updated stamp-1}]
(query-to-vec "select * from certname_fact_expiration")))
;; No effect if time is <=
(set-certname-facts-expiration "foo" false stamp-1)
(is (= [{:certid id :expire true :updated stamp-1}]
(query-to-vec "select * from certname_fact_expiration")))
;; Changes for newer time
(set-certname-facts-expiration "foo" false stamp-2)
(is (= [{:certid id :expire false :updated stamp-2}]
(query-to-vec "select * from certname_fact_expiration")))))
(deftest-db adding-catalog-inputs-for-certname
(is (= [] (query-to-vec "select * from catalog_inputs")))
(let [stamp-1 (to-timestamp (now))
stamp-2 (to-timestamp (time/plus (now) (time/seconds 1)))
id (-> "select id from certnames where certname = 'foo'"
query-to-vec first :id)]
(add-certname! "foo")
(replace-catalog! (assoc catalog :producer_timestamp stamp-1 :certname "foo"))
(is (= [] (query-to-vec "select * from catalog_inputs")))
(is (= [{:id 1 :certname "foo" :catalog_inputs_timestamp nil :catalog_inputs_uuid nil}]
(query-to-vec "select certname, id, catalog_inputs_timestamp, catalog_inputs_uuid::text from certnames")))
(replace-catalog-inputs! "foo"
(:catalog_uuid catalog)
[["hiera", "puppetdb::globals::version"]]
stamp-1)
(is (= [{:certname_id 1 :type "hiera" :name "puppetdb::globals::version"}]
(query-to-vec "select * from catalog_inputs")))
(is (= [{:id 1 :certname "foo" :catalog_inputs_timestamp stamp-1 :catalog_inputs_uuid (:catalog_uuid catalog)}]
(query-to-vec "select certname, id, catalog_inputs_timestamp, catalog_inputs_uuid::text from certnames")))
;; Changes for newer time, removes old inputs, supports multiple inputs
(replace-catalog-inputs! "foo"
(:catalog_uuid catalog)
[["hiera", "puppetdb::disable_ssl"]
["hiera", "puppetdb::disable_cleartext"]]
stamp-2)
(is (= [{:certname_id 1 :type "hiera" :name "puppetdb::disable_ssl"}
{:certname_id 1 :type "hiera" :name "puppetdb::disable_cleartext"}]
(query-to-vec "select * from catalog_inputs")))
(is (= [{:id 1 :certname "foo" :catalog_inputs_timestamp stamp-2 :catalog_inputs_uuid (:catalog_uuid catalog)}]
(query-to-vec "select certname, id, catalog_inputs_timestamp, catalog_inputs_uuid::text from certnames")))
;; No effect if time is <=
(replace-catalog-inputs! "foo"
(:catalog_uuid catalog)
[["hiera", "puppetdb::globals::version"]]
stamp-1)
(is (= [{:certname_id 1 :type "hiera" :name "puppetdb::disable_ssl"}
{:certname_id 1 :type "hiera" :name "puppetdb::disable_cleartext"}]
(query-to-vec "select * from catalog_inputs")))
(is (= [{:id 1 :certname "foo" :catalog_inputs_timestamp stamp-2 :catalog_inputs_uuid (:catalog_uuid catalog)}]
(query-to-vec "select certname, id, catalog_inputs_timestamp, catalog_inputs_uuid::text from certnames")))))
| 84826 | (ns puppetlabs.puppetdb.scf.storage-test
(:require [clojure.java.jdbc :as sql]
[clojure.set :as set]
[puppetlabs.puppetdb.cheshire :as json]
[puppetlabs.puppetdb.reports :as report]
[puppetlabs.puppetdb.scf.hash :as shash]
[puppetlabs.puppetdb.facts :as facts]
[puppetlabs.puppetdb.schema :as pls :refer [defn-validated]]
[puppetlabs.puppetdb.scf.migrate :as migrate]
[clojure.walk :as walk]
[puppetlabs.puppetdb.scf.storage-utils :as sutils]
[puppetlabs.kitchensink.core :as kitchensink]
[puppetlabs.puppetdb.testutils :as tu]
[puppetlabs.puppetdb.testutils.db
:refer [*db* clear-db-for-testing! init-db with-test-db]]
[metrics.histograms :refer [sample histogram]]
[metrics.counters :as counters]
[schema.core :as s]
[puppetlabs.trapperkeeper.testutils.logging :as pllog]
[clojure.string :as str]
[puppetlabs.puppetdb.examples :refer [catalogs]]
[puppetlabs.puppetdb.examples.reports :refer [reports]]
[puppetlabs.puppetdb.testutils.reports :refer :all]
[puppetlabs.puppetdb.testutils.events :refer :all]
[puppetlabs.puppetdb.random :as random]
[puppetlabs.puppetdb.scf.storage :refer :all]
[clojure.test :refer :all]
[clojure.math.combinatorics :refer [combinations subsets]]
[puppetlabs.puppetdb.jdbc :as jdbc
:refer [call-with-query-rows query-to-vec]]
[puppetlabs.puppetdb.time :as time
:refer [ago before? days from-now now to-string to-timestamp]]))
(def reference-time "2014-10-28T20:26:21.727Z")
(def previous-time "2014-10-26T20:26:21.727Z")
(defn-validated expire-node!
"Expire the given host, recording expire-time. If the node is
already expired, no change is made."
[certname :- String expire-time :- pls/Timestamp]
(jdbc/do-prepared
"update certnames set expired = ? where certname=? and expired is null"
[(to-timestamp expire-time) certname]))
;; When only one db is needed.
(defmacro deftest-db [name & body]
`(deftest ~name (with-test-db ~@body)))
(deftest-db ensure-producer-test
(let [prod1 "foo.com"
prod2 "bar.com"]
(ensure-producer prod1)
(testing "doesn't create new row for existing producer"
(is (= 1 (ensure-producer prod1))))
(testing "creates new row for non-existing producer"
(is (= 2 (ensure-producer prod2))))))
(defn-validated factset-map :- {s/Str s/Any}
"Return all facts and their values for a given certname as a map"
[certname :- String]
(or (-> (jdbc/query ["select (stable||volatile) as facts from factsets where certname=?"
certname])
first
:facts
str
json/parse-string)
{}))
(defn stable-facts [certname]
(-> (query-to-vec "select stable from factsets where certname=?" certname)
first
:stable
str
json/parse-string))
(defn volatile-facts [certname]
(-> (query-to-vec "select volatile from factsets where certname=?" certname)
first
:volatile
str
json/parse-string))
(defn count-facts
[]
(-> "select count(*) c from (select jsonb_each(stable||volatile) from factsets) fs"
query-to-vec
first
:c))
(deftest-db large-fact-update
(testing "updating lots of facts"
(let [certname "scale.com"
facts1 (zipmap (take 10000 (repeatedly #(random/random-string 10)))
(take 10000 (repeatedly #(random/random-string 10))))
timestamp1 (-> 2 days ago)
facts2 (zipmap (take 11000 (repeatedly #(random/random-string 10)))
(take 11000 (repeatedly #(random/random-string 10))))
timestamp2 (-> 1 days ago)
producer "bar.com"]
(add-certname! certname)
(add-facts! {:certname certname
:values facts1
:timestamp timestamp1
:environment nil
:producer_timestamp timestamp1
:producer producer})
(testing "10000 facts stored"
(is (= 10000 (count-facts))))
(update-facts! {:certname certname
:values facts2
:timestamp timestamp2
:environment nil
:producer_timestamp timestamp2
:producer producer})
(testing "11000 facts stored"
(is (= 11000 (count-facts)))))))
(deftest-db escaped-string-factnames
(testing "should work with escaped strings"
(let [certname "some_certname"
facts {"\"hello\"" "world"
"foo#~bar" "baz"
"\"foo" "bar"
"foo#~" "bar"
"foo" "bar"}
producer "bar.com"]
(add-certname! certname)
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment nil
:producer_timestamp previous-time
:producer producer})
(is (= facts (factset-map "some_certname"))))))
(comment
(def certname "some_certname")
(def facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"})
(def new-facts {"domain" "mynewdomain.com"
"fqdn" "myhost.mynewdomain.com"
"hostname" "myhost"
"kernel" "Linux"
"uptime_seconds" 3600})
(def producer "bar.com")
(alter-var-root #'*db*
(constantly jdbc/*db*))
)
(defn delete-certname-facts!
[certname]
(jdbc/do-prepared "delete from factsets where certname = ?" [certname]))
(deftest fact-persistence
(with-test-db
(testing "Persisted facts"
(let [certname "some_certname"
facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"}
producer "bar.com"]
(add-certname! certname)
(is (nil?
(jdbc/with-db-transaction []
(timestamp-of-newest-record :factsets "some_certname"))))
(is (empty? (factset-map "some_certname")))
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment nil
:producer_timestamp previous-time
:producer producer})
(testing "should have entries for each fact"
(is (= facts (factset-map "some_certname"))))
(testing "should have entries for each fact"
(is (= facts (factset-map certname)))
(is (jdbc/with-db-transaction []
(timestamp-of-newest-record :factsets "some_certname")))
(is (= facts (factset-map "some_certname"))))
(testing "should add the certname if necessary"
(is (= (query-to-vec "SELECT certname FROM certnames")
[{:certname certname}])))
(testing "should start with no volatile facts"
(is (= facts (stable-facts certname)))
(is (= {} (volatile-facts certname))))
(testing "replacing facts"
;; Ensuring here that new records are inserted, updated
;; facts are updated (not deleted and inserted) and that
;; the necessary deletes happen
(tu/with-wrapped-fn-args [updates jdbc/update!]
(let [new-facts {"domain" "mynewdomain.com"
"fqdn" "myhost.mynewdomain.com"
"hostname" "myhost"
"kernel" "Linux"
"uptime_seconds" 3600}]
(replace-facts! {:certname certname
:values new-facts
:environment "DEV"
:producer_timestamp reference-time
:timestamp reference-time
:producer producer})
(testing "should have only the new facts"
(is (= {"domain" "mynewdomain.com"
"fqdn" "myhost.mynewdomain.com"
"hostname" "myhost"
"kernel" "Linux"
"uptime_seconds" 3600}
(factset-map certname))))
(testing "producer_timestamp should store current time"
(is (= (query-to-vec "SELECT producer_timestamp FROM factsets")
[{:producer_timestamp (to-timestamp reference-time)}])))
(testing "changed facts should now be volatile"
(is (= #{"domain" "fqdn"}
(set (keys (volatile-facts certname))))))
#_(testing "should update existing keys"
(is (= 1 (count @updates)))
(is (some #{{:timestamp (to-timestamp reference-time)
:environment_id 1
:hash "1a4b10a865b8c7b435ec0fe06968fdc62337f57f"
:producer_timestamp (to-timestamp reference-time)
:producer_id 1}}
;; Again we grab the pertinent non-id bits
(map (fn [itm]
(-> (second itm)
(update-in [:hash] sutils/parse-db-hash)))
@updates)))
(is (some (fn [update-call]
(and (= :factsets (first update-call))
(:timestamp (second update-call))))
@updates))))))
(testing "replacing all new facts"
(delete-certname-facts! certname)
(replace-facts! {:certname certname
:values facts
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(is (= facts (factset-map "some_certname"))))
(testing "replacing all facts with new ones"
(delete-certname-facts! certname)
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment nil
:producer_timestamp previous-time
:producer nil})
(replace-facts! {:certname certname
:values {"foo" "bar"}
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(is (= {"foo" "bar"} (factset-map "some_certname"))))
(testing "replace-facts with only additions"
(let [fact-map (factset-map "some_certname")]
(replace-facts! {:certname certname
:values (assoc fact-map "one more" "here")
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(is (= (assoc fact-map "one more" "here")
(factset-map "some_certname")))))
(testing "replace-facts with no change"
(let [fact-map (factset-map "some_certname")]
(replace-facts! {:certname certname
:values fact-map
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(is (= fact-map
(factset-map "some_certname")))))
(testing "stable hash when no facts change"
(let [fact-map (factset-map "some_certname")
{old-hash :hash} (first (query-to-vec (format "SELECT %s AS hash FROM factsets where certname=?" (sutils/sql-hash-as-str "hash")) certname))]
(replace-facts! {:certname certname
:values fact-map
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(let [{new-hash :hash} (first (query-to-vec (format "SELECT %s AS hash FROM factsets where certname=?" (sutils/sql-hash-as-str "hash")) certname))]
(is (= old-hash new-hash)))
(replace-facts! {:certname certname
:values (assoc fact-map "another thing" "goes here")
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(let [{new-hash :hash} (first (query-to-vec (format "SELECT %s AS hash FROM factsets where certname=?" (sutils/sql-hash-as-str "hash")) certname))]
(is (not= old-hash new-hash)))))))))
(deftest fact-path-gc
(letfn [(facts-now [c v]
{:certname c :values v
:environment nil :timestamp (now) :producer_timestamp (now) :producer nil})
(paths-and-types []
(query-to-vec "select path, value_type_id from fact_paths"))
(check-gc [factset-changes
expected-before
expected-after]
(clear-db-for-testing!)
(init-db *db*)
(doseq [cert (set (map first factset-changes))]
(add-certname! cert))
(doseq [[cert factset] factset-changes]
(replace-facts! (facts-now cert factset)))
(let [obs (paths-and-types)]
(is (= (count expected-before) (count obs)))
(is (= expected-before (set obs))))
(delete-unused-fact-paths)
(let [obs (paths-and-types)]
(is (= (count expected-after) (count obs)))
(is (= expected-after (set obs)))))]
(let [type-id {:int (facts/value-type-id 0)
:str (facts/value-type-id "0")
:obj (facts/value-type-id [])}]
(with-test-db
(testing "works when there are no paths"
(check-gc [] #{} #{}))
(testing "doesn't do anything if nothing changes"
(let [before #{{:path "a" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~foo" :value_type_id (type-id :str)}}]
(check-gc [["c-x" {"a" 1}]
["c-y" {"b" {"foo" "two"}}]]
before
before)))
(testing "orphaning of a simple scalar"
(check-gc [["c-x" {"a" 1}]
["c-y" {"b" 2}]
["c-y" {"c" 3}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :int)}
{:path "c" :value_type_id (type-id :int)}}
#{{:path "a" :value_type_id (type-id :int)}
{:path "c" :value_type_id (type-id :int)}}))
(testing "orphaning of a structured fact"
(check-gc [["c-x" {"a" 1}]
["c-y" {"b" {"foo" "bar"}}]
["c-y" {"c" 3}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~foo" :value_type_id (type-id :str)}
{:path "c" :value_type_id (type-id :int)}}
#{{:path "a" :value_type_id (type-id :int)}
{:path "c" :value_type_id (type-id :int)}}))
(testing "orphaning of an array"
(check-gc [["c-x" {"a" 1}]
["c-y" {"b" ["x" "y"]}]
["c-y" {"c" 3}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~0" :value_type_id (type-id :str)}
{:path "b#~1" :value_type_id (type-id :str)}
{:path "c" :value_type_id (type-id :int)}}
#{{:path "a" :value_type_id (type-id :int)}
{:path "c" :value_type_id (type-id :int)}}))
;; In these type change tests, orphaned types linger because
;; the current gc only operates on (removes) paths that have
;; no references at all. It leaves any existing entries for a
;; given path alone.
(testing "structured fact changing to simple"
(check-gc [["c-x" {"b" {"foo" "bar"}}]
["c-x" {"b" 1}]]
#{{:path "b" :value_type_id (type-id :obj)}
{:path "b#~foo" :value_type_id (type-id :str)}
{:path "b" :value_type_id (type-id :int)}}
#{{:path "b" :value_type_id (type-id :obj)}
{:path "b" :value_type_id (type-id :int)}}))
(testing "simple fact changing to structured"
(check-gc [["c-x" {"b" 1}]
["c-x" {"b" {"foo" "bar"}}]]
#{{:path "b" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~foo" :value_type_id (type-id :str)}}
#{{:path "b" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~foo" :value_type_id (type-id :str)}}))
(testing "array changes to scalar"
(check-gc [["c-x" {"b" ["x" "y"]}]
["c-x" {"b" 1}]]
#{{:path "b" :value_type_id (type-id :obj)}
{:path "b#~0" :value_type_id (type-id :str)}
{:path "b#~1" :value_type_id (type-id :str)}
{:path "b" :value_type_id (type-id :int)}}
#{{:path "b" :value_type_id (type-id :obj)}
{:path "b" :value_type_id (type-id :int)}}))
(testing "scalar changes to array"
(check-gc [["c-x" {"b" 1}]
["c-x" {"b" ["x" "y"]}]]
#{{:path "b" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~0" :value_type_id (type-id :str)}
{:path "b#~1" :value_type_id (type-id :str)}}
#{{:path "b" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~0" :value_type_id (type-id :str)}
{:path "b#~1" :value_type_id (type-id :str)}}))
(testing "multiple types for path and all disappear"
(check-gc [["c-w" {"a" 1}]
["c-x" {"a" "two"}]
["c-y" {"a" {"foo" "bar"}}]
["c-z" {"a" [3]}]
["c-w" {}]
["c-x" {}]
["c-y" {}]
["c-z" {}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "a" :value_type_id (type-id :str)}
{:path "a" :value_type_id (type-id :obj)}
{:path "a#~foo" :value_type_id (type-id :str)}
{:path "a#~0" :value_type_id (type-id :int)}}
#{}))
(testing "multiple types for path and all types change"
(let [expected #{{:path "a" :value_type_id (type-id :int)}
{:path "a" :value_type_id (type-id :obj)}
{:path "a#~0" :value_type_id (type-id :int)}
{:path "a#~foo" :value_type_id (type-id :str)}
{:path "a" :value_type_id (type-id :str)}}]
(check-gc [["c-x" {"a" 1}]
["c-y" {"a" [0]}]
["c-x" {"a" {"foo" "bar"}}]
["c-y" {"a" "two"}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "a" :value_type_id (type-id :obj)}
{:path "a#~0" :value_type_id (type-id :int)}
{:path "a#~foo" :value_type_id (type-id :str)}
{:path "a" :value_type_id (type-id :str)}}
;; Q: Why didn't "a" :int stick around?
#{{:path "a" :value_type_id (type-id :int)}
{:path "a" :value_type_id (type-id :obj)}
{:path "a#~foo" :value_type_id (type-id :str)}
{:path "a" :value_type_id (type-id :str)}})))
(testing "everything to nothing"
(check-gc [["c-x" {"a" 1}]
["c-y" {"a" ["x" "y"]}]
["c-z" {"a" {"foo" "bar"}}]
["c-x" {}]
["c-y" {}]
["c-z" {}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "a" :value_type_id (type-id :obj)}
{:path "a#~0" :value_type_id (type-id :str)}
{:path "a#~1" :value_type_id (type-id :str)}
{:path "a#~foo" :value_type_id (type-id :str)}}
#{}))))))
(deftest factset-paths-write-minimization
(letfn [(facts-now [c v]
{:certname c :values v
:environment nil :timestamp (now) :producer_timestamp (now) :producer nil})
(certname-paths-hash [certname]
(-> "select paths_hash from factsets where certname = ?"
(query-to-vec certname)
first
:paths_hash))
(reset-db []
(clear-db-for-testing!)
(init-db *db*))
(set-cert-facts-causes-update [cert factset]
(let [real-realize-paths realize-paths
called? (atom false)]
(with-redefs [realize-paths (fn [& args]
(reset! called? true)
(apply real-realize-paths args))]
(replace-facts! (facts-now cert factset)))
@called?))]
(with-test-db
(testing "with no hash, establishing no facts establishes a hash"
(reset-db)
(add-certname! "foo")
(is (= nil (certname-paths-hash "foo")))
(set-cert-facts-causes-update "foo" {})
(let [hash (certname-paths-hash "foo")]
(is (= 20 (count hash)))
(is (= (class (byte-array 0)) (class hash)))))
(testing "with hash for no paths, establishing no paths causes no update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {})
(is (= false (set-cert-facts-causes-update "foo" {}))))
(testing "with hash for no paths, establishing paths causes update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {})
(is (= true (set-cert-facts-causes-update "foo" {"a" 1}))))
(testing "with paths, replacing with same paths causes no update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {"a" 1})
(is (= false (set-cert-facts-causes-update "foo" {"a" 1}))))
(testing "with paths, changing fact values causes no update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {"a" 1})
(is (= false (set-cert-facts-causes-update "foo" {"a" 2}))))
(testing "with paths, changing paths causes update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {"a" 1})
(is (= true (set-cert-facts-causes-update "foo" {"b" 1}))))
(testing "with paths, adding path causes update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {"a" 1})
(is (= true (set-cert-facts-causes-update "foo" {"a" 1 "b" 1}))))
(testing "with paths, removing path causes update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {"a" 1 "b" 1})
(is (= true (set-cert-facts-causes-update "foo" {"b" 1})))))))
(deftest-db fact-persistance-with-environment
(testing "Persisted facts"
(let [certname "some_certname"
facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"}
producer "bar.com"]
(add-certname! certname)
(is (nil?
(jdbc/with-db-transaction []
(timestamp-of-newest-record :factsets "some_certname"))))
(is (empty? (factset-map "some_certname")))
(is (nil? (environment-id "PROD")))
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment "PROD"
:producer_timestamp previous-time
:producer producer})
(testing "should have entries for each fact"
(is (= facts (factset-map "some_certname")))
(is (= [{:certname "some_certname"
:environment_id (environment-id "PROD")}]
(query-to-vec "SELECT certname, environment_id FROM factsets"))))
(is (nil? (environment-id "DEV")))
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer})
(testing "should have the same entries for each fact"
(is (= facts (factset-map "some_certname")))
(is (= [{:certname "some_certname"
:environment_id (environment-id "DEV")}]
(query-to-vec "SELECT certname, environment_id FROM factsets")))))))
(defn package-seq
"Return all facts and their values for a given certname as a map"
[certname]
(rest
(jdbc/query
["SELECT p.name as package_name, p.version, p.provider
FROM certname_packages cp
inner join packages p on cp.package_id = p.id
inner join certnames c on cp.certname_id = c.id
WHERE c.certname = ?
ORDER BY package_name, version, provider"
certname]
{:as-arrays? true})))
(deftest-db fact-persistance-with-packages
(testing "Existing facts with new packages added"
(let [certname "some_certname"
facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"}
producer "bar.com"]
(add-certname! certname)
(testing "Existing facts with new packages added"
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment "PROD"
:producer_timestamp previous-time
:producer producer})
(is (empty? (package-seq certname)))
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo" "1.2.3" "apt"]
["bar" "2.3.4" "apt"]
["baz" "3.4.5" "apt"]]})
(is (= [["bar" "2.3.4" "apt"]
["baz" "3.4.5" "apt"]
["foo" "1.2.3" "apt"]]
(package-seq certname))))
(testing "Updating existing packages"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo" "1.2.3" "apt"]
["bar" "2.3.4" "apt"]
["not-baz" "3.4.5" "apt"]]})
(is (= [["bar" "2.3.4" "apt"]
["foo" "1.2.3" "apt"]
["not-baz" "3.4.5" "apt"]]
(package-seq certname))))
(testing "Removing packages"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo" "1.2.3" "apt"]]})
(is (= [["foo" "1.2.3" "apt"]]
(package-seq certname))))
(testing "Removing packages"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo-1" "1.2.3" "apt"]
["foo-2" "1.2.3" "apt"]
["foo-3" "1.2.3" "apt"]
["foo-4" "1.2.3" "apt"]]})
(is (= [["foo-1" "1.2.3" "apt"]
["foo-2" "1.2.3" "apt"]
["foo-3" "1.2.3" "apt"]
["foo-4" "1.2.3" "apt"]]
(package-seq certname))))
(testing "Pinpoint GC cleans up packages"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo-1" "1.2.3" "apt"]]})
(is (= [["foo-1" "1.2.3" "apt"]]
(package-seq certname)))
(is (= 1
(-> ["SELECT count(*) as c FROM packages"]
query-to-vec
first
:c))))
(testing "Orphaned packages are deleted"
(let [package-count (fn [] (-> ["SELECT count(*) as c FROM packages"]
query-to-vec
first
:c))]
(is (pos? (package-count)))
(jdbc/do-commands "DELETE FROM certname_packages")
(is (pos? (package-count)))
(delete-unassociated-packages!)
(is (zero? (package-count))))))))
(deftest-db purge-packages-from-node
(testing "Existing facts with new packages added"
(let [certname "some_certname"
facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"}
producer "bar.com"
reload-packages (fn []
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo" "1.2.3" "apt"]
["bar" "2.3.4" "apt"]
["baz" "3.4.5" "apt"]]}))
find-package-hash (fn []
(:package_hash (certname-factset-metadata "some_certname")))]
(add-certname! certname)
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment "PROD"
:producer_timestamp previous-time
:producer producer})
(is (empty? (package-seq certname)))
(reload-packages)
(testing "data was loaded for test"
(is (= 3 (count (package-seq certname)))))
(is (find-package-hash))
(testing "package_inventory key is missing from command"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer})
(is (= []
(package-seq certname)))
(is (nil? (find-package-hash))))
(reload-packages)
(is (= 3 (count (package-seq certname))))
(testing "package_inventory is nil"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory nil})
(is (= 0 (count (package-seq certname))))
(is (nil? (find-package-hash))))
(reload-packages)
(is (= 3 (count (package-seq certname))))
(is (find-package-hash))
(testing "package_inventory is empty"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory []})
(is (= 0 (count (package-seq certname))))
(is (nil? (find-package-hash)))))))
(def catalog (:basic catalogs))
(def certname (:certname catalog))
(def current-time (str (now)))
(deftest-db catalog-persistence
(testing "Persisted catalogs"
(add-certname! certname)
(replace-catalog! (assoc catalog :producer_timestamp current-time))
(testing "should contain proper catalog metadata"
(is (= (query-to-vec ["SELECT certname, api_version, catalog_version, producer_timestamp FROM catalogs"])
[{:certname certname :api_version 1 :catalog_version "123456789" :producer_timestamp (to-timestamp current-time)}])))
(testing "should contain a complete edges list"
(is (= (query-to-vec [(str "SELECT r1.type as stype, r1.title as stitle, r2.type as ttype, r2.title as ttitle, e.type as etype "
"FROM edges e, catalog_resources r1, catalog_resources r2 "
"WHERE e.source=r1.resource AND e.target=r2.resource "
"ORDER BY r1.type, r1.title, r2.type, r2.title, e.type")])
[{:stype "Class" :stitle "foobar" :ttype "File" :ttitle "/etc/foobar" :etype "contains"}
{:stype "Class" :stitle "foobar" :ttype "File" :ttitle "/etc/foobar/baz" :etype "contains"}
{:stype "File" :stitle "/etc/foobar" :ttype "File" :ttitle "/etc/foobar/baz" :etype "required-by"}])))
(testing "should contain a complete resources list"
(is (= (query-to-vec ["SELECT type, title FROM catalog_resources ORDER BY type, title"])
[{:type "Class" :title "foobar"}
{:type "File" :title "/etc/foobar"}
{:type "File" :title "/etc/foobar/baz"}]))
(testing "properly associated with the host"
(is (= (query-to-vec ["SELECT c.certname, cr.type, cr.title
FROM catalog_resources cr, certnames c
WHERE c.id=cr.certname_id
ORDER BY cr.type, cr.title"])
[{:certname certname :type "Class" :title "foobar"}
{:certname certname :type "File" :title "/etc/foobar"}
{:certname certname :type "File" :title "/etc/foobar/baz"}])))
(testing "with all parameters"
(is (= (query-to-vec ["SELECT cr.type, cr.title, rp.name, rp.value FROM catalog_resources cr, resource_params rp WHERE rp.resource=cr.resource ORDER BY cr.type, cr.title, rp.name"])
[{:type "File" :title "/etc/foobar" :name "ensure" :value (sutils/db-serialize "directory")}
{:type "File" :title "/etc/foobar" :name "group" :value (sutils/db-serialize "root")}
{:type "File" :title "/etc/foobar" :name "user" :value (sutils/db-serialize "root")}
{:type "File" :title "/etc/foobar/baz" :name "ensure" :value (sutils/db-serialize "directory")}
{:type "File" :title "/etc/foobar/baz" :name "group" :value (sutils/db-serialize "root")}
{:type "File" :title "/etc/foobar/baz" :name "require" :value (sutils/db-serialize "File[/etc/foobar]")}
{:type "File" :title "/etc/foobar/baz" :name "user" :value (sutils/db-serialize "root")}])))
(testing "with all metadata"
(let [result (query-to-vec ["SELECT cr.type, cr.title, cr.exported, cr.tags, cr.file, cr.line FROM catalog_resources cr ORDER BY cr.type, cr.title"])]
(is (= (map #(assoc % :tags (sort (:tags %))) result)
[{:type "Class" :title "foobar" :tags ["class" "foobar"] :exported false :file nil :line nil}
{:type "File" :title "/etc/foobar" :tags ["class" "file" "foobar"] :exported false :file "/tmp/foo" :line 10}
{:type "File" :title "/etc/foobar/baz" :tags ["class" "file" "foobar"] :exported false :file "/tmp/bar" :line 20}])))))))
(deftest-db catalog-persistence-with-environment
(let [other-certname "notbasic.catalogs.com"]
(testing "Persisted catalogs"
(add-certname! certname)
(add-certname! other-certname)
(is (nil? (environment-id "PROD")))
(replace-catalog! (assoc catalog :environment "PROD"))
(testing "should persist environment if the environment is new"
(let [id (environment-id "PROD")]
(is (number? (environment-id "PROD")))
(is (= [{:certname certname :api_version 1 :catalog_version "123456789" :environment_id id}]
(query-to-vec ["SELECT certname, api_version, catalog_version, environment_id FROM catalogs"])))
(testing "Adding another catalog with the same environment should just use the existing environment"
(replace-catalog! (assoc catalog :environment "PROD" :certname other-certname))
(is (= [{:certname other-certname :api_version 1 :catalog_version "123456789" :environment_id id}]
(query-to-vec ["SELECT certname, api_version, catalog_version, environment_id FROM catalogs where certname=?" other-certname])))))))))
(deftest-db updating-catalog-environment
(testing "should persist environment if the environment is new"
(let [prod-id (ensure-environment "PROD")
dev-id (ensure-environment "DEV")]
(add-certname! certname)
(replace-catalog! (assoc catalog :environment "DEV"))
(is (= [{:certname certname :api_version 1 :catalog_version "123456789" :environment_id dev-id}]
(query-to-vec ["SELECT certname, api_version, catalog_version, environment_id FROM catalogs"])))
(replace-catalog! (assoc catalog :environment "PROD"))
(is (= [{:certname certname :api_version 1 :catalog_version "123456789" :environment_id prod-id}]
(query-to-vec ["SELECT certname, api_version, catalog_version, environment_id FROM catalogs"]))))))
(deftest-db catalog-replacement
(testing "should noop if replaced by themselves"
(add-certname! certname)
(let [hash (replace-catalog! catalog)]
(replace-catalog! catalog (now))
(is (= (query-to-vec ["SELECT certname FROM certnames"])
[{:certname certname}]))
(is (= (query-to-vec [(format "SELECT %s AS hash FROM catalogs" (sutils/sql-hash-as-str "hash"))])
[{:hash hash}])))))
(deftest-db edge-replacement-differential
(testing "should do selective inserts/deletes when edges are modified just slightly"
(add-certname! certname)
(let [original-catalog (:basic catalogs)
original-edges (:edges original-catalog)
modified-edges (conj (disj original-edges {:source {:type "Class" :title "foobar"}
:target {:type "File" :title "/etc/foobar"}
:relationship :contains})
{:source {:type "File" :title "/etc/foobar"}
:target {:type "File" :title "/etc/foobar/baz"}
:relationship :before})
modified-catalog (assoc original-catalog :edges modified-edges)]
;; Add an initial catalog, we don't care to intercept the SQL yet
(replace-catalog! original-catalog (now))
(testing "ensure catalog-edges-map returns a predictable value"
(is (= (catalog-edges-map certname)
{["<KEY>"
"57<KEY>b<KEY>"
"contains"] nil,
["<KEY>"
"e247f822a0f0bbbfff4fe066ce4a077f<KEY>0<KEY>"
"required-by"] nil,
["<KEY>"
"e247f822a0<KEY>bbbfff4fe0<KEY>6ce<KEY>"
"contains"] nil})))
;; Lets intercept the insert/update/delete level so we can test it later
;; Here we only replace edges, so we can capture those specific SQL
;; operations
(tu/with-wrapped-fn-args [insert-multis jdbc/insert-multi!
deletes jdbc/delete!]
(let [resources (:resources modified-catalog)
refs-to-hash (reduce-kv (fn [i k v]
(assoc i k (shash/resource-identity-hash v)))
{} resources)]
(replace-edges! certname modified-edges refs-to-hash)
(testing "ensure catalog-edges-map returns a predictable value"
(is (= (catalog-edges-map certname)
{["<KEY>"
"e247f822a0f0bbbfff4fe066ce4a077f9<KEY>0<KEY>cdb1"
"contains"] nil,
["57<KEY>9<KEY>51c5194a21b9a26554cd93db3d9"
"e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1"
"required-by"] nil
["57495b553981551c5194a21b9a26554cd93db3d9"
"e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1"
"before"] nil})))
(testing "should only delete the 1 edge"
(let [source-hash "ff0702ba8a7dc69d3fb17f9d151bf9bd265a9ed9"
target-hash "57495b553981551c5194a21b9a26554cd93db3d9"]
(is (= [[:edges [(str "certname=?"
" and source=?::bytea"
" and target=?::bytea"
" and type=?")
"basic.catalogs.com"
(sutils/bytea-escape source-hash)
(sutils/bytea-escape target-hash)
"contains"]]]
@deletes))))
(testing "should only insert the 1 edge"
(is (= [[:edges [{:certname "basic.catalogs.com"
:source (sutils/munge-hash-for-storage "57495b553981551c5194a21b9a26554cd93db3d9")
:target (sutils/munge-hash-for-storage "e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1")
:type "before"}]]]
@insert-multis)))
(testing "when reran to check for idempotency"
(reset! insert-multis [])
(reset! deletes [])
(replace-edges! certname modified-edges refs-to-hash)
(testing "should delete no edges"
(is (empty? @deletes)))
(testing "should insert no edges"
(is (empty? @insert-multis)))))))))
(deftest-db catalog-duplicates
(testing "should share structure when duplicate catalogs are detected for the same host"
(add-certname! certname)
(let [hash (replace-catalog! catalog)
prev-dupe-num (counters/value (:duplicate-catalog performance-metrics))
prev-new-num (counters/value (:updated-catalog performance-metrics))]
;; Do an initial replacement with the same catalog
(replace-catalog! catalog (now))
(is (= 1 (- (counters/value (:duplicate-catalog performance-metrics)) prev-dupe-num)))
(is (= 0 (- (counters/value (:updated-catalog performance-metrics)) prev-new-num)))
;; Store a second catalog, with the same content save the version
(replace-catalog! (assoc catalog :version "abc123") (now))
(is (= 2 (- (counters/value (:duplicate-catalog performance-metrics)) prev-dupe-num)))
(is (= 0 (- (counters/value (:updated-catalog performance-metrics)) prev-new-num)))
(is (= (query-to-vec ["SELECT certname FROM certnames"])
[{:certname certname}]))
(is (= (query-to-vec [(format "SELECT certname, %s AS hash FROM catalogs" (sutils/sql-hash-as-str "hash"))])
[{:hash hash
:certname certname}]))
(replace-catalog! (assoc-in catalog [:resources {:type "File" :title "/etc/foobar"} :line] 20) (now))
(is (= 2 (- (counters/value (:duplicate-catalog performance-metrics)) prev-dupe-num)))
(is (= 1 (- (counters/value (:updated-catalog performance-metrics)) prev-new-num))))))
(deftest-db fact-delete-deletes-facts
(add-certname! certname)
;; Add some facts
(let [facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"
"networking" {"eth0" {"ipaddresses" ["192.168.0.11"]}}}]
(add-facts! {:certname certname
:values facts
:timestamp (-> 2 days ago)
:environment "ENV3"
:producer_timestamp (-> 2 days ago)
:producer "bar.com"}))
(is (= 6 (count-facts)))
(is (= 6 (count-facts)))
(delete-certname-facts! certname)
(is (= 0 (count-facts)))
(is (= 0 (count-facts))))
(deftest-db catalog-bad-input
(testing "should noop"
(testing "on bad input"
(is (thrown? clojure.lang.ExceptionInfo (replace-catalog! {})))
;; Nothing should have been persisted for this catalog
(is (= (query-to-vec ["SELECT count(*) as nrows from certnames"])
[{:nrows 0}])))))
(defn foobar->foobar2 [x]
(if (and (string? x) (= x "/etc/foobar"))
"/etc/foobar2"
x))
(defn table-args
"Many of the puppetdb.jdbc functions accept a table name as the first arg, this
function grabs that argument"
[coll]
(map first coll))
(defn remove-edge-changes
"Remove the edge related changes from the `coll` of function call arguments"
[coll]
(remove #(= :edges (first %)) coll))
(defn sort= [& args]
(apply = (map sort args)))
(deftest-db existing-catalog-update
(let [{certname :certname :as catalog} (:basic catalogs)
old-date (-> 2 days ago)
yesterday (-> 1 days ago)]
(testing "inserting new catalog with resources"
(add-certname! certname)
(is (empty? (query-to-vec "SELECT * from catalogs where certname=?" certname)))
(replace-catalog! catalog old-date)
(let [results (query-to-vec "SELECT timestamp from catalogs where certname=?" certname)
{:keys [timestamp]} (first results)]
(is (= 1 (count results)))
(is (= (to-timestamp old-date) (to-timestamp timestamp)))))
(testing "changing a resource title"
(let [[{orig-id :id
orig-tx-id :transaction_uuid
orig-timestamp :timestamp}]
(query-to-vec (str "select id, timestamp, transaction_uuid::text"
" from catalogs where certname=?")
certname)
updated-catalog (walk/prewalk foobar->foobar2 (:basic catalogs))
new-uuid (kitchensink/uuid)
metrics-map performance-metrics]
(is (= #{{:type "Class" :title "foobar"}
{:type "File" :title "/etc/foobar"}
{:type "File" :title "/etc/foobar/baz"}}
(set (query-to-vec "SELECT cr.type, cr.title
FROM catalogs c
INNER JOIN certnames on c.certname=certnames.certname
INNER JOIN catalog_resources cr
ON certnames.id=cr.certname_id
WHERE c.certname=?" certname))))
(tu/with-wrapped-fn-args [inserts jdbc/insert!
insert-multis jdbc/insert-multi!
deletes jdbc/delete!
updates jdbc/update!]
(with-redefs [performance-metrics
(assoc metrics-map
:catalog-volatility (histogram storage-metrics-registry [(str (gensym))]))]
(replace-catalog! (assoc updated-catalog :transaction_uuid new-uuid) yesterday)
;; 2 edge deletes
;; 2 edge inserts
;; 1 params insert
;; 1 params cache insert
;; 1 catalog_resource insert
;; 1 catalog_resource delete
(is (= 8 (apply + (sample (:catalog-volatility performance-metrics))))))
(is (sort= [:resource_params_cache :resource_params :catalog_resources :edges]
(table-args (concat @inserts @insert-multis))))
(is (= [:catalogs]
(table-args @updates)))
(is (= [[:catalog_resources ["certname_id = ? and type = ? and title = ?"
(-> @updates first (nth 2) second)
"File" "/etc/foobar"]]]
(remove-edge-changes @deletes))))
(is (= #{{:type "Class" :title "foobar"}
{:type "File" :title "/etc/foobar2"}
{:type "File" :title "/etc/foobar/baz"}}
(set (query-to-vec "SELECT cr.type, cr.title
FROM catalogs c
INNER JOIN certnames ON certnames.certname = c.certname
INNER JOIN catalog_resources cr ON cr.certname_id = certnames.id
WHERE c.certname=?" certname))))
(let [results (query-to-vec
(str "select id, timestamp, transaction_uuid::text"
" from catalogs where certname=?")
certname)
{new-timestamp :timestamp
new-tx-id :transaction_uuid
new-id :id} (first results)]
(is (= 1 (count results)))
(is (= (to-timestamp yesterday) (to-timestamp new-timestamp)))
(is (= new-tx-id new-uuid))
(is (= orig-id new-id))
(is (not= orig-tx-id new-tx-id))
(is (not= orig-timestamp new-timestamp)))))))
(comment
(existing-catalog-update)
)
(deftest-db add-resource-to-existing-catalog
(let [{certname :certname :as catalog} (:basic catalogs)
old-date (-> 2 days ago)
yesterday (-> 1 days ago)]
(add-certname! certname)
(replace-catalog! catalog old-date)
(is (= 3 (:c (first (query-to-vec "SELECT count(*) AS c FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname)))))
(tu/with-wrapped-fn-args [inserts jdbc/insert!
insert-multis jdbc/insert-multi!
updates jdbc/update!
deletes jdbc/delete!]
(replace-catalog! (assoc-in catalog
[:resources {:type "File" :title "/etc/foobar2"}]
{:type "File"
:title "/etc/foobar2"
:exported false
:file "/tmp/foo2"
:line 20
:tags #{"file" "class" "foobar"}
:parameters {:ensure "directory"
:group "root"
:user "root"}})
old-date)
(is (sort= [:resource_params_cache :resource_params :catalog_resources]
(table-args (concat @inserts @insert-multis))))
(is (= [:catalogs] (table-args @updates)))
(is (empty? @deletes)))
(is (= 4 (:c (first (query-to-vec "SELECT count(*) AS c FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname)))))))
(deftest-db change-line-resource-metadata
(add-certname! certname)
(replace-catalog! catalog)
(testing "changing line number"
(is (= #{{:line nil}
{:line 10}
{:line 20}}
(set (query-to-vec "SELECT line FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname))))
(replace-catalog! (update-in catalog [:resources]
(fn [resources]
(kitchensink/mapvals #(assoc % :line 1000) resources))))
(is (= [{:line 1000}
{:line 1000}
{:line 1000}]
(query-to-vec "SELECT line FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname)))))
(deftest-db change-exported-resource-metadata
(add-certname! certname)
(replace-catalog! catalog)
(testing "changing exported"
(is (= #{{:exported false
:title "foobar"}
{:exported false
:title "/etc/foobar"}
{:exported false
:title "/etc/foobar/baz"}}
(set (query-to-vec "SELECT title, exported FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname))))
(replace-catalog! (update-in catalog [:resources]
(fn [resources]
(-> resources
(assoc-in [{:type "Class" :title "foobar"} :exported] true)
(assoc-in [{:type "File" :title "/etc/foobar/baz"} :exported] true)))))
(is (= #{{:exported true
:title "foobar"}
{:exported false
:title "/etc/foobar"}
{:exported true
:title "/etc/foobar/baz"}}
(set (query-to-vec "SELECT title, exported FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname))))))
(deftest-db change-file-resource-metadata
(add-certname! certname)
(replace-catalog! catalog)
(testing "changing line number"
(is (= #{{:title "foobar"
:file nil}
{:title "/etc/foobar"
:file "/tmp/foo"}
{:title "/etc/foobar/baz"
:file "/tmp/bar"}}
(set (query-to-vec "SELECT title, file FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname))))
(replace-catalog! (update-in catalog [:resources]
(fn [resources]
(kitchensink/mapvals #(assoc % :file "/tmp/foo.pp") resources))))
(is (= #{{:title "foobar"
:file "/tmp/foo.pp"}
{:title "/etc/foobar"
:file "/tmp/foo.pp"}
{:title "/etc/foobar/baz"
:file "/tmp/foo.pp"}}
(set (query-to-vec "SELECT title, file FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname))))))
(defn tags->set
"Converts tags from a pg-array to a set of strings"
[result-set]
(mapv (fn [result]
(update-in result [:tags] #(jdbc/convert-any-sql-array % set)))
result-set))
(deftest-db change-tags-on-resource
(add-certname! certname)
(replace-catalog! catalog)
(is (= #{{:title "foobar"
:tags #{"class" "foobar"}
:line nil}
{:title "/etc/foobar"
:tags #{"file" "class" "foobar"}
:line 10}
{:title "/etc/foobar/baz"
:tags #{"file" "class" "foobar"}
:line 20}}
(call-with-query-rows
[(str "select title, tags, line from catalog_resources"
" inner join certnames c on c.id = certname_id"
" where c.certname = ?")
certname]
#(-> % tags->set set))))
(replace-catalog! (update-in catalog [:resources]
(fn [resources]
(-> resources
(assoc-in [{:type "File" :title "/etc/foobar"} :tags] #{"totally" "different" "tags"})
(assoc-in [{:type "File" :title "/etc/foobar"} :line] 500)))))
(is (= #{{:title "foobar"
:tags #{"class" "foobar"}
:line nil}
{:title "/etc/foobar"
:line 500
:tags #{"totally" "different" "tags"}}
{:title "/etc/foobar/baz"
:line 20
:tags #{"file" "class" "foobar"}}}
(call-with-query-rows
[(str "select title, tags, line from catalog_resources"
" inner join certnames c on c.id = certname_id"
" where c.certname = ?")
certname]
#(-> % tags->set set)))))
(deftest-db removing-resources
(let [{certname :certname :as catalog} (:basic catalogs)
old-date (-> 2 days ago)
yesterday (-> 1 days ago)
catalog-with-extra-resource (assoc-in catalog
[:resources {:type "File" :title "/etc/the-foo"}]
{:type "File"
:title "/etc/the-foo"
:exported false
:file "/tmp/the-foo"
:line 10
:tags #{"file" "class" "the-foo"}
:parameters {:ensure "directory"
:group "root"
:user "root"}})]
(add-certname! certname)
(replace-catalog! catalog-with-extra-resource old-date)
(let [certname-id (:id (first (query-to-vec "SELECT id from certnames where certname=?" certname)))]
(is (= 4 (count (query-to-vec "SELECT * from catalog_resources where certname_id = ?" certname-id))))
(tu/with-wrapped-fn-args [inserts jdbc/insert!
updates jdbc/update!
deletes jdbc/delete!]
(replace-catalog! catalog yesterday)
(is (empty? @inserts))
(is (= [:catalogs] (table-args @updates)))
(is (= [:catalog_resources] (table-args @deletes))))
(let [catalog-results (query-to-vec "SELECT timestamp from catalogs where certname=?" certname)
{:keys [timestamp]} (first catalog-results)
resources (set (query-to-vec "SELECT type, title from catalog_resources where certname_id = ?" certname-id))]
(is (= 1 (count catalog-results)))
(is (= 3 (count resources)))
(is (= (set (keys (:resources catalog)))
resources))
(is (= (to-timestamp yesterday) (to-timestamp timestamp)))))))
(defn foobar-params []
(jdbc/query-with-resultset
["SELECT p.name AS k, p.value AS v
FROM catalog_resources cr, certnames c, resource_params p
WHERE cr.certname_id = c.id AND cr.resource = p.resource AND c.certname=?
AND cr.type=? AND cr.title=?"
(get-in catalogs [:basic :certname]) "File" "/etc/foobar"]
(fn [rs]
(reduce (fn [acc row]
(assoc acc (keyword (:k row))
(json/parse-string (:v row))))
{}
(sql/result-set-seq rs)))))
(defn foobar-params-cache []
(jdbc/query-with-resultset
["SELECT rpc.parameters as params
FROM catalog_resources cr, certnames c, resource_params_cache rpc
WHERE cr.certname_id = c.id AND cr.resource = rpc.resource AND c.certname=?
AND cr.type=? AND cr.title=?"
(get-in catalogs [:basic :certname]) "File" "/etc/foobar"]
#(-> (sql/result-set-seq %)
first
:params
sutils/parse-db-json)))
(defn foobar-param-hash []
(jdbc/query-with-resultset
[(format "SELECT %s AS hash
FROM catalog_resources cr, certnames c
WHERE cr.certname_id = c.id AND c.certname=? AND cr.type=?
AND cr.title=?"
(sutils/sql-hash-as-str "cr.resource"))
(get-in catalogs [:basic :certname]) "File" "/etc/foobar"]
(comp :hash first sql/result-set-seq)))
(deftest-db catalog-resource-parameter-changes
(let [{certname :certname :as catalog} (:basic catalogs)
old-date (-> 2 days ago)
yesterday (-> 1 days ago)]
(add-certname! certname)
(replace-catalog! catalog old-date)
(let [orig-resource-hash (foobar-param-hash)
add-param-catalog (assoc-in catalog [:resources {:type "File" :title "/etc/foobar"} :parameters :uid] "100")]
(is (= (get-in catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params)))
(is (= (get-in catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params-cache)))
(tu/with-wrapped-fn-args [inserts jdbc/insert!
insert-multis jdbc/insert-multi!
updates jdbc/update!
deletes jdbc/delete!]
(replace-catalog! add-param-catalog yesterday)
(is (sort= [:catalogs :catalog_resources]
(table-args @updates)))
(is (empty? (remove-edge-changes @deletes)))
(is (sort= [:resource_params_cache :resource_params :edges]
(->> (concat @inserts @insert-multis)
(remove #(empty? (second %))) ;; remove inserts w/out rows
table-args))))
(is (not= orig-resource-hash (foobar-param-hash)))
(is (= (get-in add-param-catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params)))
(is (= (get-in add-param-catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params-cache)))
(tu/with-wrapped-fn-args [inserts jdbc/insert!
insert-multis jdbc/insert-multi!
updates jdbc/update!
deletes jdbc/delete!]
(replace-catalog! catalog old-date)
(is (empty? (remove #(or (= :edges (first %)) (empty? (second %)))
(concat @inserts @insert-multis))))
(is (empty? (remove #(= :edges (first %)) @deletes)))
(is (= (sort [:catalog_resources :catalogs])
(sort (table-args @updates)))))
(is (= orig-resource-hash (foobar-param-hash)))
(is (= (get-in catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params)))
(is (= (get-in catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params-cache))))))
(deftest-db catalog-referential-integrity-violation
(testing "on input that violates referential integrity"
;; This catalog has an edge that points to a non-existant resource
(let [catalog (:invalid catalogs)]
(is (thrown? clojure.lang.ExceptionInfo (replace-catalog! catalog)))
;; Nothing should have been persisted for this catalog
(is (= (query-to-vec ["SELECT count(*) as nrows from certnames"])
[{:nrows 0}])))))
(deftest-db node-deactivation
(let [certname "foo.example.com"
query-certnames #(query-to-vec ["select certname, deactivated from certnames"])
deactivated? #(instance? java.sql.Timestamp (:deactivated %))]
(add-certname! certname)
(testing "deactivating a node"
(testing "should mark the node as deactivated"
(deactivate-node! certname)
(let [result (first (query-certnames))]
(is (= certname (:certname result)))
(is (deactivated? result))))
(testing "should not change the node if it's already inactive"
(let [original (query-certnames)]
(deactivate-node! certname)
;; Convert any :deactivated values to #t for comparison
;; since we only care about the state.
(letfn [(deactivated->truthy [x]
(assoc x :deactivated (when (:deactivated x) true)))]
(is (= (map deactivated->truthy original)
(map deactivated->truthy (query-certnames))))))))
(testing "activating a node"
(testing "should activate the node if it was inactive"
(activate-node! certname)
(is (= (query-certnames) [{:certname certname :deactivated nil}])))
(testing "should do nothing if the node is already active"
(let [original (query-certnames)]
(activate-node! certname)
(is (= original (query-certnames))))))
(testing "auto-reactivated based on a command"
(let [before-deactivating (to-timestamp (-> 1 days ago))
after-deactivating (to-timestamp (-> 1 days from-now))]
(testing "should activate the node if the command happened after it was deactivated"
(deactivate-node! certname)
(is (= true (maybe-activate-node! certname after-deactivating)))
(is (= (query-certnames) [{:certname certname :deactivated nil}])))
(testing "should not activate the node if the command happened before it was deactivated"
(deactivate-node! certname)
(is (= false (maybe-activate-node! certname before-deactivating)))
(let [result (first (query-certnames))]
(is (= certname (:certname result)))
(is (deactivated? result))))
(testing "should do nothing if the node is already active"
(activate-node! certname)
(is (= false (maybe-activate-node! certname (now))))
(is (= (query-certnames) [{:certname certname :deactivated nil}])))))))
(deftest-db fresh-node-not-expired
(testing "fresh nodes are not expired"
(let [catalog (:empty catalogs)
certname (:certname catalog)]
(add-certname! certname)
(replace-catalog! (assoc catalog :producer_timestamp (now)) (now))
(is (= [] (expire-stale-nodes (-> 3 days .toPeriod))))
(is (= (map :certname (query-to-vec "select certname from certnames"))
[certname])))))
(deftest expire-nodes-with-stale-catalogs-and-facts-or-none
(testing "nodes with only stale facts/catalogs or no facts/catalogs expire"
(let [mutators {:rc #(replace-catalog!
(assoc (:empty catalogs) :certname "node1")
(-> 2 days ago))
:rf #(replace-facts!
{:certname "node1"
:values {"foo" "bar"}
:environment "DEV"
:producer_timestamp (-> 10 days ago)
:timestamp (-> 2 days ago)
:producer "baz.com"})}]
(doseq [ops (subsets (keys mutators))]
(with-test-db
(add-certname! "node1")
(dorun (map #((mutators %)) ops))
(is (= [ops ["node1"]]
[ops (expire-stale-nodes (-> 1 days .toPeriod))])))))))
(deftest-db node-with-only-fresh-report-is-not-expired
(testing "does not expire a node with a recent report and nothing else"
(let [report (-> (:basic reports)
(assoc :environment "ENV2")
(assoc :end_time (now))
(assoc :producer_timestamp (now)))]
(store-example-report! report (now))
(is (= [] (expire-stale-nodes (-> 1 days .toPeriod)))))))
(deftest stale-nodes-expiration-via-reports
(let [report-at #(assoc (:basic reports)
:environment "ENV2"
:end_time %
:producer_timestamp %)
stamp (now)
stale-stamp-1 (-> 2 days ago)
stale-stamp-2 (-> 3 days ago)]
(with-test-db
(testing "doesn't return node with a recent report and nothing else"
(store-example-report! (report-at stamp) stamp)
(is (= [] (expire-stale-nodes (-> 1 days .toPeriod)))))
(testing "doesn't return node with a recent report and a stale report"
(store-example-report! (report-at stale-stamp-1) stale-stamp-1)
(is (= [] (expire-stale-nodes (-> 1 days .toPeriod))))))
(with-test-db
(testing "returns a node with only stale reports"
(store-example-report! (report-at stale-stamp-1) stale-stamp-1)
(store-example-report! (report-at stale-stamp-2) stale-stamp-2)
(is (= ["foo.local"] (expire-stale-nodes (-> 1 days .toPeriod))))))))
(deftest-db stale-nodes-expiration-via-catalogs
(let [repcat (fn [type stamp]
(replace-catalog! (assoc (type catalogs)
:certname "node1"
:producer_timestamp stamp)
stamp))
stamp (now)
stale-stamp (-> 2 days ago)]
(with-test-db
(testing "doesn't return node with a recent catalog and nothing else"
(add-certname! "node1")
(repcat :empty stamp)
(is (= [] (expire-stale-nodes (-> 1 days .toPeriod))))))
(with-test-db
(testing "returns a node with only a stale catalog"
(add-certname! "node1")
(repcat :empty stale-stamp)
(is (= ["node1"] (expire-stale-nodes (-> 1 days .toPeriod))))))))
(deftest-db only-nodes-older-than-max-age-expired
(testing "should only return nodes older than max age, and leave others alone"
(let [catalog (:empty catalogs)]
(add-certname! "node1")
(add-certname! "node2")
(replace-catalog! (assoc catalog
:certname "node1"
:producer_timestamp (-> 2 days ago))
(now))
(replace-catalog! (assoc catalog
:certname "node2"
:producer_timestamp (now))
(now))
(is (= ["node1"] (expire-stale-nodes (-> 1 days .toPeriod)))))))
(deftest-db node-purge
(testing "should purge nodes which were deactivated before the specified date"
(add-certname! "node1")
(add-certname! "node2")
(add-certname! "node3")
(deactivate-node! "node1")
(deactivate-node! "node2" (-> 10 days ago))
(purge-deactivated-and-expired-nodes! (-> 5 days ago))
(is (= (map :certname
(query-to-vec
"select certname from certnames order by certname asc"))
["node1" "node3"]))))
(deftest-db node-purge-cleans-packages
(testing "should purge nodes which were deactivated before the specified date"
(add-certname! "node1")
(add-certname! "node2")
(insert-packages "node1" [["foo" "1.2.3" "apt"] ["bar" "2.3.4" "apt"]])
(insert-packages "node2" [["foo" "1.2.3" "apt"] ["bar" "2.3.4" "apt"]])
(deactivate-node! "node1")
(deactivate-node! "node2" (-> 10 days ago))
(purge-deactivated-and-expired-nodes! (-> 5 days ago))
(is (= 1
(count (query-to-vec
"select certname_id from certname_packages group by certname_id"))))))
(deftest-db delete-certname-cleans-packages
(add-certname! "node1")
(add-certname! "node2")
(insert-packages "node1" [["foo" "1.2.3" "apt"] ["bar" "2.3.4" "apt"]])
(insert-packages "node2" [["foo" "1.2.3" "apt"] ["bar" "2.3.4" "apt"]])
(delete-certname! "node1")
(is (= 1
(count (query-to-vec
"select certname_id from certname_packages group by certname_id")))))
(deftest-db purge-expired-nodes
(testing "should purge nodes which were expired before the specified date"
(add-certname! "node1")
(add-certname! "node2")
(add-certname! "node3")
(expire-node! "node1" (now))
(expire-node! "node2" (-> 10 days ago))
(purge-deactivated-and-expired-nodes! (-> 5 days ago))
(is (= (map :certname
(query-to-vec
"select certname from certnames order by certname asc"))
["node1" "node3"]))))
(deftest-db report-sweep-nullifies-latest-report
(testing "ensure that if the latest report is swept, latest_report_id is updated to nil"
(let [report1 (assoc (:basic reports) :end_time (-> 12 days ago))
report2 (assoc (:basic reports) :certname "bar.local" :end_time (now) :producer_timestamp (now))]
(add-certname! "foo.local")
(add-certname! "bar.local")
(store-example-report! report1 (-> 12 days ago))
(store-example-report! report2 (now))
(let [ids (map :latest_report_id (query-to-vec "select latest_report_id from certnames order by certname"))
_ (delete-reports-older-than! (-> 11 days ago))
ids2 (map :latest_report_id (query-to-vec "select latest_report_id from certnames order by certname"))]
(is (= ids2 [(first ids) nil]))))))
;; Report tests
(defn update-event-timestamps
"Changes each timestamp in the `report`'s resource_events to `new-timestamp`"
[report new-timestamp]
(update-in report [:resource_events]
(fn [events]
(map #(assoc % :timestamp new-timestamp) events))))
(let [timestamp (now)
{:keys [certname] :as report} (:basic reports)
report-hash (-> report
report/report-query->wire-v8
normalize-report
shash/report-identity-hash)]
(deftest-db report-storage
(testing "should store reports"
(store-example-report! report timestamp)
(is (= [{:certname certname}]
(query-to-vec ["SELECT certname FROM reports"])))
(is (= [{:hash report-hash}]
(query-to-vec [(format "SELECT %s AS hash FROM reports" (sutils/sql-hash-as-str "hash"))])))
(testing "foss doesn't store in the resources column"
(is (nil? (:resources (first (query-to-vec ["SELECT resources FROM reports"])))))))
(testing "should store report with long puppet version string"
(store-example-report!
(assoc report
:puppet_version "3.2.1 (Puppet Enterprise 3.0.0-preview0-168-g32c839e)") timestamp)))
(deftest-db report-with-event-timestamp
(let [z-report (update-event-timestamps report "2011-01-01T12:00:01Z")
offset-report (update-event-timestamps report "2011-01-01T12:00:01-0000")]
(is (= (shash/report-identity-hash (normalize-report z-report))
(shash/report-identity-hash (normalize-report offset-report))))))
(deftest-db report-with-null-bytes-in-events
(store-example-report!
(-> report
(assoc-in [:resource_events :data 0 :new_value] "foo\u0000bar")
(assoc-in [:resource_events :data 0 :old_value] "foo\u0000bar"))
timestamp)
(is (= [{:old_value "\"foo\ufffdbar\""
:new_value "\"foo\ufffdbar\""}]
(query-to-vec ["SELECT old_value, new_value from resource_events where old_value ~ 'foo'"]))))
(deftest-db report-storage-with-environment
(is (nil? (environment-id "DEV")))
(store-example-report! (assoc report :environment "DEV") timestamp)
(is (number? (environment-id "DEV")))
(is (= (query-to-vec ["SELECT certname, environment_id FROM reports"])
[{:certname (:certname report)
:environment_id (environment-id "DEV")}])))
(deftest-db report-storage-with-producer
(let [prod-id (ensure-producer "bar.com")]
(store-example-report! (assoc report :producer "bar.com") timestamp)
(is (= (query-to-vec ["SELECT certname, producer_id FROM reports"])
[{:certname (:certname report)
:producer_id prod-id}]))))
(deftest-db report-storage-with-status
(is (nil? (status-id "unchanged")))
(store-example-report! (assoc report :status "unchanged") timestamp)
(is (number? (status-id "unchanged")))
(is (= (query-to-vec ["SELECT certname, status_id FROM reports"])
[{:certname (:certname report)
:status_id (status-id "unchanged")}])))
(deftest-db report-storage-without-resources
(testing "should store reports"
(let [env-id (ensure-environment "DEV")]
(store-example-report! (assoc-in report [:resource_events :data] []) timestamp)
(is (= (query-to-vec ["SELECT certname FROM reports"])
[{:certname (:certname report)}]))
(is (= (query-to-vec ["SELECT COUNT(1) as num_resource_events FROM resource_events"])
[{:num_resource_events 0}])))))
(deftest-db report-storage-with-existing-environment
(testing "should store reports"
(let [env-id (ensure-environment "DEV")]
(store-example-report! (assoc report :environment "DEV") timestamp)
(is (= (query-to-vec ["SELECT certname, environment_id FROM reports"])
[{:certname (:certname report)
:environment_id env-id}])))))
(deftest-db latest-report
(let [node (:certname report)
report-hash (:hash (store-example-report! report timestamp))]
(testing "should flag report as 'latest'"
(is (is-latest-report? node report-hash))
(let [new-report-hash (:hash (store-example-report!
(-> report
(assoc :configuration_version "bar")
(assoc :end_time (now))
(assoc :producer_timestamp (now)))
timestamp))]
(is (is-latest-report? node new-report-hash))
(is (not (is-latest-report? node report-hash)))))
(testing "should not update latest report with older report timestamp"
(let [old-report-hash (:hash (store-example-report!
(-> report
(assoc :configuration_version "bar")
(assoc :end_time (now))
(assoc :producer_timestamp (-> -1 days from-now)))
timestamp))]
(is (not (is-latest-report? node old-report-hash)))))))
(deftest-db report-cleanup
(testing "should delete reports older than the specified age"
(let [report1 (assoc report
:certname "foo"
:end_time (to-string (-> 5 days ago))
:producer_timestamp (to-string (-> 5 days ago)))
report2 (assoc report
:certname "bar"
:end_time (to-string (-> 2 days ago))
:producer_timestamp (to-string (-> 2 days ago)))]
(store-example-report! report1 timestamp)
(store-example-report! report2 timestamp)
(delete-reports-older-than! (-> 3 days ago))
(is (= (query-to-vec ["SELECT certname FROM reports"])
[{:certname "bar"}])))))
(deftest-db resource-events-cleanup
(testing "should delete all events for reports older than the specified age"
(let [report1 (assoc report :end_time (to-string (-> 5 days ago)))
report1-hash (:hash (store-example-report! report1 timestamp))
report2 (assoc report :end_time (to-string (-> 2 days ago)))]
(store-example-report! report2 timestamp)
(delete-reports-older-than! (-> 3 days ago))
(is (= #{}
(set (query-resource-events :latest ["=" "report" report1-hash] {}))))))))
(deftest test-catalog-schemas
(is (= (:basic catalogs) (s/validate catalog-schema (:basic catalogs)))))
(deftest test-resource-metadata-diff
(are [expected left right] (= expected (basic-diff left right))
{}
{:type "foo" :title "bar"}
{:type "foo" :title "bar"}
{:line 20}
{:type "File"
:title "/etc/foobar/baz"
:exported false
:file "/tmp/bar"
:line 10
:tags #{"file" "class" "foobar"}}
{:type "File"
:title "/etc/foobar/baz"
:exported false
:file "/tmp/bar"
:line 20
:tags #{"file" "class" "foobar"}}
{:exported true
:file "/tmp/bar/baz"
:line 30
:tags #{"file" "class" "foobar" "baz"}}
{:type "File"
:title "/etc/foobar/baz"
:exported false
:file "/tmp/bar"
:line 20
:tags #{"file" "class" "foobar"}}
{:type "File"
:title "/etc/foobar/baz"
:exported true
:file "/tmp/bar/baz"
:line 30
:tags #{"file" "class" "foobar" "baz"}}))
(deftest test-diff-resources-metadata
(let [resources-1 {{:type "File" :title "/etc/foobar"}
{:type "File"
:title "/etc/foobar"
:exported false
:file "/tmp/foo"
:line 10
:tags #{"file" "class" "foobar"}}
{:type "File" :title "/etc/foobar/baz"}
{:type "File"
:title "/etc/foobar/baz"
:exported false
:file "/tmp/bar"
:line 20
:tags #{"file" "class" "foobar"}}}
resources-2 {{:type "File" :title "/etc/foobar"}
{:type "File"
:title "/etc/foobar"
:exported false
:file "/tmp/foo"
:line 20
:tags #{"file" "class" "foobar"}}
{:type "File" :title "/etc/foobar/baz"}
{:type "File"
:title "/etc/foobar/baz"
:exported true
:file "/tmp/bar/baz"
:line 30
:tags #{"file" "class" "foobar" "baz"}}}]
(are [expected left right] (= expected (diff-resources-metadata left right))
{}
resources-1
resources-1
{{:type "File" :title "/etc/foobar"}
{:line 30}}
resources-1
(assoc-in resources-1 [{:type "File" :title "/etc/foobar"} :line] 30)
{{:type "File" :title "/etc/foobar"}
{:line 20}
{:type "File" :title "/etc/foobar/baz"}
{:exported true
:file "/tmp/bar/baz"
:line 30
:tags #{"file" "class" "foobar" "baz"}}}
resources-1
resources-2)))
(defn fake-hash
[]
(shash/generic-identity-hash (random/random-string)))
(deftest-db giant-resources-exist
(testing "resources-exist?"
(is (= #{} (resources-exist? (set (take 40000 (repeatedly fake-hash))))))))
(deftest-db test-merge-resource-hash
(let [ref->resource {{:type "File" :title "/tmp/foo"}
{:line 10}
{:type "File" :title "/tmp/bar"}
{:line 20}}
ref->hash {{:type "File" :title "/tmp/foo"}
"foo hash"
{:type "File" :title "/tmp/bar"}
"bar hash"}]
(is (= {{:type "File" :title "/tmp/foo"}
{:line 10 :resource "foo hash"}
{:type "File" :title "/tmp/bar"}
{:line 20 :resource "bar hash"}}
(merge-resource-hash ref->hash ref->resource)))))
(deftest-db test-resources-exist?
(testing "With empty input"
(is (= #{} (resources-exist? #{})))))
(deftest-db setting-fact-expiration-for-certname
(is (= [] (query-to-vec "select * from certname_fact_expiration")))
(add-certname! "foo")
(is (= [] (query-to-vec "select * from certname_fact_expiration")))
(let [stamp-1 (to-timestamp (now))
stamp-2 (to-timestamp (time/plus (now) (time/seconds 1)))
id (-> "select id from certnames where certname = 'foo'"
query-to-vec first :id)]
(set-certname-facts-expiration "foo" true stamp-1)
(is (= [{:certid id :expire true :updated stamp-1}]
(query-to-vec "select * from certname_fact_expiration")))
;; No effect if time is <=
(set-certname-facts-expiration "foo" false stamp-1)
(is (= [{:certid id :expire true :updated stamp-1}]
(query-to-vec "select * from certname_fact_expiration")))
;; Changes for newer time
(set-certname-facts-expiration "foo" false stamp-2)
(is (= [{:certid id :expire false :updated stamp-2}]
(query-to-vec "select * from certname_fact_expiration")))))
(deftest-db adding-catalog-inputs-for-certname
(is (= [] (query-to-vec "select * from catalog_inputs")))
(let [stamp-1 (to-timestamp (now))
stamp-2 (to-timestamp (time/plus (now) (time/seconds 1)))
id (-> "select id from certnames where certname = 'foo'"
query-to-vec first :id)]
(add-certname! "foo")
(replace-catalog! (assoc catalog :producer_timestamp stamp-1 :certname "foo"))
(is (= [] (query-to-vec "select * from catalog_inputs")))
(is (= [{:id 1 :certname "foo" :catalog_inputs_timestamp nil :catalog_inputs_uuid nil}]
(query-to-vec "select certname, id, catalog_inputs_timestamp, catalog_inputs_uuid::text from certnames")))
(replace-catalog-inputs! "foo"
(:catalog_uuid catalog)
[["hiera", "puppetdb::globals::version"]]
stamp-1)
(is (= [{:certname_id 1 :type "hiera" :name "puppetdb::globals::version"}]
(query-to-vec "select * from catalog_inputs")))
(is (= [{:id 1 :certname "foo" :catalog_inputs_timestamp stamp-1 :catalog_inputs_uuid (:catalog_uuid catalog)}]
(query-to-vec "select certname, id, catalog_inputs_timestamp, catalog_inputs_uuid::text from certnames")))
;; Changes for newer time, removes old inputs, supports multiple inputs
(replace-catalog-inputs! "foo"
(:catalog_uuid catalog)
[["hiera", "puppetdb::disable_ssl"]
["hiera", "puppetdb::disable_cleartext"]]
stamp-2)
(is (= [{:certname_id 1 :type "hiera" :name "puppetdb::disable_ssl"}
{:certname_id 1 :type "hiera" :name "puppetdb::disable_cleartext"}]
(query-to-vec "select * from catalog_inputs")))
(is (= [{:id 1 :certname "foo" :catalog_inputs_timestamp stamp-2 :catalog_inputs_uuid (:catalog_uuid catalog)}]
(query-to-vec "select certname, id, catalog_inputs_timestamp, catalog_inputs_uuid::text from certnames")))
;; No effect if time is <=
(replace-catalog-inputs! "foo"
(:catalog_uuid catalog)
[["hiera", "puppetdb::globals::version"]]
stamp-1)
(is (= [{:certname_id 1 :type "hiera" :name "puppetdb::disable_ssl"}
{:certname_id 1 :type "hiera" :name "puppetdb::disable_cleartext"}]
(query-to-vec "select * from catalog_inputs")))
(is (= [{:id 1 :certname "foo" :catalog_inputs_timestamp stamp-2 :catalog_inputs_uuid (:catalog_uuid catalog)}]
(query-to-vec "select certname, id, catalog_inputs_timestamp, catalog_inputs_uuid::text from certnames")))))
| true | (ns puppetlabs.puppetdb.scf.storage-test
(:require [clojure.java.jdbc :as sql]
[clojure.set :as set]
[puppetlabs.puppetdb.cheshire :as json]
[puppetlabs.puppetdb.reports :as report]
[puppetlabs.puppetdb.scf.hash :as shash]
[puppetlabs.puppetdb.facts :as facts]
[puppetlabs.puppetdb.schema :as pls :refer [defn-validated]]
[puppetlabs.puppetdb.scf.migrate :as migrate]
[clojure.walk :as walk]
[puppetlabs.puppetdb.scf.storage-utils :as sutils]
[puppetlabs.kitchensink.core :as kitchensink]
[puppetlabs.puppetdb.testutils :as tu]
[puppetlabs.puppetdb.testutils.db
:refer [*db* clear-db-for-testing! init-db with-test-db]]
[metrics.histograms :refer [sample histogram]]
[metrics.counters :as counters]
[schema.core :as s]
[puppetlabs.trapperkeeper.testutils.logging :as pllog]
[clojure.string :as str]
[puppetlabs.puppetdb.examples :refer [catalogs]]
[puppetlabs.puppetdb.examples.reports :refer [reports]]
[puppetlabs.puppetdb.testutils.reports :refer :all]
[puppetlabs.puppetdb.testutils.events :refer :all]
[puppetlabs.puppetdb.random :as random]
[puppetlabs.puppetdb.scf.storage :refer :all]
[clojure.test :refer :all]
[clojure.math.combinatorics :refer [combinations subsets]]
[puppetlabs.puppetdb.jdbc :as jdbc
:refer [call-with-query-rows query-to-vec]]
[puppetlabs.puppetdb.time :as time
:refer [ago before? days from-now now to-string to-timestamp]]))
(def reference-time "2014-10-28T20:26:21.727Z")
(def previous-time "2014-10-26T20:26:21.727Z")
(defn-validated expire-node!
"Expire the given host, recording expire-time. If the node is
already expired, no change is made."
[certname :- String expire-time :- pls/Timestamp]
(jdbc/do-prepared
"update certnames set expired = ? where certname=? and expired is null"
[(to-timestamp expire-time) certname]))
;; When only one db is needed.
(defmacro deftest-db [name & body]
`(deftest ~name (with-test-db ~@body)))
(deftest-db ensure-producer-test
(let [prod1 "foo.com"
prod2 "bar.com"]
(ensure-producer prod1)
(testing "doesn't create new row for existing producer"
(is (= 1 (ensure-producer prod1))))
(testing "creates new row for non-existing producer"
(is (= 2 (ensure-producer prod2))))))
(defn-validated factset-map :- {s/Str s/Any}
"Return all facts and their values for a given certname as a map"
[certname :- String]
(or (-> (jdbc/query ["select (stable||volatile) as facts from factsets where certname=?"
certname])
first
:facts
str
json/parse-string)
{}))
(defn stable-facts [certname]
(-> (query-to-vec "select stable from factsets where certname=?" certname)
first
:stable
str
json/parse-string))
(defn volatile-facts [certname]
(-> (query-to-vec "select volatile from factsets where certname=?" certname)
first
:volatile
str
json/parse-string))
(defn count-facts
[]
(-> "select count(*) c from (select jsonb_each(stable||volatile) from factsets) fs"
query-to-vec
first
:c))
(deftest-db large-fact-update
(testing "updating lots of facts"
(let [certname "scale.com"
facts1 (zipmap (take 10000 (repeatedly #(random/random-string 10)))
(take 10000 (repeatedly #(random/random-string 10))))
timestamp1 (-> 2 days ago)
facts2 (zipmap (take 11000 (repeatedly #(random/random-string 10)))
(take 11000 (repeatedly #(random/random-string 10))))
timestamp2 (-> 1 days ago)
producer "bar.com"]
(add-certname! certname)
(add-facts! {:certname certname
:values facts1
:timestamp timestamp1
:environment nil
:producer_timestamp timestamp1
:producer producer})
(testing "10000 facts stored"
(is (= 10000 (count-facts))))
(update-facts! {:certname certname
:values facts2
:timestamp timestamp2
:environment nil
:producer_timestamp timestamp2
:producer producer})
(testing "11000 facts stored"
(is (= 11000 (count-facts)))))))
(deftest-db escaped-string-factnames
(testing "should work with escaped strings"
(let [certname "some_certname"
facts {"\"hello\"" "world"
"foo#~bar" "baz"
"\"foo" "bar"
"foo#~" "bar"
"foo" "bar"}
producer "bar.com"]
(add-certname! certname)
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment nil
:producer_timestamp previous-time
:producer producer})
(is (= facts (factset-map "some_certname"))))))
(comment
(def certname "some_certname")
(def facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"})
(def new-facts {"domain" "mynewdomain.com"
"fqdn" "myhost.mynewdomain.com"
"hostname" "myhost"
"kernel" "Linux"
"uptime_seconds" 3600})
(def producer "bar.com")
(alter-var-root #'*db*
(constantly jdbc/*db*))
)
(defn delete-certname-facts!
[certname]
(jdbc/do-prepared "delete from factsets where certname = ?" [certname]))
(deftest fact-persistence
(with-test-db
(testing "Persisted facts"
(let [certname "some_certname"
facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"}
producer "bar.com"]
(add-certname! certname)
(is (nil?
(jdbc/with-db-transaction []
(timestamp-of-newest-record :factsets "some_certname"))))
(is (empty? (factset-map "some_certname")))
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment nil
:producer_timestamp previous-time
:producer producer})
(testing "should have entries for each fact"
(is (= facts (factset-map "some_certname"))))
(testing "should have entries for each fact"
(is (= facts (factset-map certname)))
(is (jdbc/with-db-transaction []
(timestamp-of-newest-record :factsets "some_certname")))
(is (= facts (factset-map "some_certname"))))
(testing "should add the certname if necessary"
(is (= (query-to-vec "SELECT certname FROM certnames")
[{:certname certname}])))
(testing "should start with no volatile facts"
(is (= facts (stable-facts certname)))
(is (= {} (volatile-facts certname))))
(testing "replacing facts"
;; Ensuring here that new records are inserted, updated
;; facts are updated (not deleted and inserted) and that
;; the necessary deletes happen
(tu/with-wrapped-fn-args [updates jdbc/update!]
(let [new-facts {"domain" "mynewdomain.com"
"fqdn" "myhost.mynewdomain.com"
"hostname" "myhost"
"kernel" "Linux"
"uptime_seconds" 3600}]
(replace-facts! {:certname certname
:values new-facts
:environment "DEV"
:producer_timestamp reference-time
:timestamp reference-time
:producer producer})
(testing "should have only the new facts"
(is (= {"domain" "mynewdomain.com"
"fqdn" "myhost.mynewdomain.com"
"hostname" "myhost"
"kernel" "Linux"
"uptime_seconds" 3600}
(factset-map certname))))
(testing "producer_timestamp should store current time"
(is (= (query-to-vec "SELECT producer_timestamp FROM factsets")
[{:producer_timestamp (to-timestamp reference-time)}])))
(testing "changed facts should now be volatile"
(is (= #{"domain" "fqdn"}
(set (keys (volatile-facts certname))))))
#_(testing "should update existing keys"
(is (= 1 (count @updates)))
(is (some #{{:timestamp (to-timestamp reference-time)
:environment_id 1
:hash "1a4b10a865b8c7b435ec0fe06968fdc62337f57f"
:producer_timestamp (to-timestamp reference-time)
:producer_id 1}}
;; Again we grab the pertinent non-id bits
(map (fn [itm]
(-> (second itm)
(update-in [:hash] sutils/parse-db-hash)))
@updates)))
(is (some (fn [update-call]
(and (= :factsets (first update-call))
(:timestamp (second update-call))))
@updates))))))
(testing "replacing all new facts"
(delete-certname-facts! certname)
(replace-facts! {:certname certname
:values facts
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(is (= facts (factset-map "some_certname"))))
(testing "replacing all facts with new ones"
(delete-certname-facts! certname)
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment nil
:producer_timestamp previous-time
:producer nil})
(replace-facts! {:certname certname
:values {"foo" "bar"}
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(is (= {"foo" "bar"} (factset-map "some_certname"))))
(testing "replace-facts with only additions"
(let [fact-map (factset-map "some_certname")]
(replace-facts! {:certname certname
:values (assoc fact-map "one more" "here")
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(is (= (assoc fact-map "one more" "here")
(factset-map "some_certname")))))
(testing "replace-facts with no change"
(let [fact-map (factset-map "some_certname")]
(replace-facts! {:certname certname
:values fact-map
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(is (= fact-map
(factset-map "some_certname")))))
(testing "stable hash when no facts change"
(let [fact-map (factset-map "some_certname")
{old-hash :hash} (first (query-to-vec (format "SELECT %s AS hash FROM factsets where certname=?" (sutils/sql-hash-as-str "hash")) certname))]
(replace-facts! {:certname certname
:values fact-map
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(let [{new-hash :hash} (first (query-to-vec (format "SELECT %s AS hash FROM factsets where certname=?" (sutils/sql-hash-as-str "hash")) certname))]
(is (= old-hash new-hash)))
(replace-facts! {:certname certname
:values (assoc fact-map "another thing" "goes here")
:environment "DEV"
:producer_timestamp (now)
:timestamp (now)
:producer producer})
(let [{new-hash :hash} (first (query-to-vec (format "SELECT %s AS hash FROM factsets where certname=?" (sutils/sql-hash-as-str "hash")) certname))]
(is (not= old-hash new-hash)))))))))
(deftest fact-path-gc
(letfn [(facts-now [c v]
{:certname c :values v
:environment nil :timestamp (now) :producer_timestamp (now) :producer nil})
(paths-and-types []
(query-to-vec "select path, value_type_id from fact_paths"))
(check-gc [factset-changes
expected-before
expected-after]
(clear-db-for-testing!)
(init-db *db*)
(doseq [cert (set (map first factset-changes))]
(add-certname! cert))
(doseq [[cert factset] factset-changes]
(replace-facts! (facts-now cert factset)))
(let [obs (paths-and-types)]
(is (= (count expected-before) (count obs)))
(is (= expected-before (set obs))))
(delete-unused-fact-paths)
(let [obs (paths-and-types)]
(is (= (count expected-after) (count obs)))
(is (= expected-after (set obs)))))]
(let [type-id {:int (facts/value-type-id 0)
:str (facts/value-type-id "0")
:obj (facts/value-type-id [])}]
(with-test-db
(testing "works when there are no paths"
(check-gc [] #{} #{}))
(testing "doesn't do anything if nothing changes"
(let [before #{{:path "a" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~foo" :value_type_id (type-id :str)}}]
(check-gc [["c-x" {"a" 1}]
["c-y" {"b" {"foo" "two"}}]]
before
before)))
(testing "orphaning of a simple scalar"
(check-gc [["c-x" {"a" 1}]
["c-y" {"b" 2}]
["c-y" {"c" 3}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :int)}
{:path "c" :value_type_id (type-id :int)}}
#{{:path "a" :value_type_id (type-id :int)}
{:path "c" :value_type_id (type-id :int)}}))
(testing "orphaning of a structured fact"
(check-gc [["c-x" {"a" 1}]
["c-y" {"b" {"foo" "bar"}}]
["c-y" {"c" 3}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~foo" :value_type_id (type-id :str)}
{:path "c" :value_type_id (type-id :int)}}
#{{:path "a" :value_type_id (type-id :int)}
{:path "c" :value_type_id (type-id :int)}}))
(testing "orphaning of an array"
(check-gc [["c-x" {"a" 1}]
["c-y" {"b" ["x" "y"]}]
["c-y" {"c" 3}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~0" :value_type_id (type-id :str)}
{:path "b#~1" :value_type_id (type-id :str)}
{:path "c" :value_type_id (type-id :int)}}
#{{:path "a" :value_type_id (type-id :int)}
{:path "c" :value_type_id (type-id :int)}}))
;; In these type change tests, orphaned types linger because
;; the current gc only operates on (removes) paths that have
;; no references at all. It leaves any existing entries for a
;; given path alone.
(testing "structured fact changing to simple"
(check-gc [["c-x" {"b" {"foo" "bar"}}]
["c-x" {"b" 1}]]
#{{:path "b" :value_type_id (type-id :obj)}
{:path "b#~foo" :value_type_id (type-id :str)}
{:path "b" :value_type_id (type-id :int)}}
#{{:path "b" :value_type_id (type-id :obj)}
{:path "b" :value_type_id (type-id :int)}}))
(testing "simple fact changing to structured"
(check-gc [["c-x" {"b" 1}]
["c-x" {"b" {"foo" "bar"}}]]
#{{:path "b" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~foo" :value_type_id (type-id :str)}}
#{{:path "b" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~foo" :value_type_id (type-id :str)}}))
(testing "array changes to scalar"
(check-gc [["c-x" {"b" ["x" "y"]}]
["c-x" {"b" 1}]]
#{{:path "b" :value_type_id (type-id :obj)}
{:path "b#~0" :value_type_id (type-id :str)}
{:path "b#~1" :value_type_id (type-id :str)}
{:path "b" :value_type_id (type-id :int)}}
#{{:path "b" :value_type_id (type-id :obj)}
{:path "b" :value_type_id (type-id :int)}}))
(testing "scalar changes to array"
(check-gc [["c-x" {"b" 1}]
["c-x" {"b" ["x" "y"]}]]
#{{:path "b" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~0" :value_type_id (type-id :str)}
{:path "b#~1" :value_type_id (type-id :str)}}
#{{:path "b" :value_type_id (type-id :int)}
{:path "b" :value_type_id (type-id :obj)}
{:path "b#~0" :value_type_id (type-id :str)}
{:path "b#~1" :value_type_id (type-id :str)}}))
(testing "multiple types for path and all disappear"
(check-gc [["c-w" {"a" 1}]
["c-x" {"a" "two"}]
["c-y" {"a" {"foo" "bar"}}]
["c-z" {"a" [3]}]
["c-w" {}]
["c-x" {}]
["c-y" {}]
["c-z" {}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "a" :value_type_id (type-id :str)}
{:path "a" :value_type_id (type-id :obj)}
{:path "a#~foo" :value_type_id (type-id :str)}
{:path "a#~0" :value_type_id (type-id :int)}}
#{}))
(testing "multiple types for path and all types change"
(let [expected #{{:path "a" :value_type_id (type-id :int)}
{:path "a" :value_type_id (type-id :obj)}
{:path "a#~0" :value_type_id (type-id :int)}
{:path "a#~foo" :value_type_id (type-id :str)}
{:path "a" :value_type_id (type-id :str)}}]
(check-gc [["c-x" {"a" 1}]
["c-y" {"a" [0]}]
["c-x" {"a" {"foo" "bar"}}]
["c-y" {"a" "two"}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "a" :value_type_id (type-id :obj)}
{:path "a#~0" :value_type_id (type-id :int)}
{:path "a#~foo" :value_type_id (type-id :str)}
{:path "a" :value_type_id (type-id :str)}}
;; Q: Why didn't "a" :int stick around?
#{{:path "a" :value_type_id (type-id :int)}
{:path "a" :value_type_id (type-id :obj)}
{:path "a#~foo" :value_type_id (type-id :str)}
{:path "a" :value_type_id (type-id :str)}})))
(testing "everything to nothing"
(check-gc [["c-x" {"a" 1}]
["c-y" {"a" ["x" "y"]}]
["c-z" {"a" {"foo" "bar"}}]
["c-x" {}]
["c-y" {}]
["c-z" {}]]
#{{:path "a" :value_type_id (type-id :int)}
{:path "a" :value_type_id (type-id :obj)}
{:path "a#~0" :value_type_id (type-id :str)}
{:path "a#~1" :value_type_id (type-id :str)}
{:path "a#~foo" :value_type_id (type-id :str)}}
#{}))))))
(deftest factset-paths-write-minimization
(letfn [(facts-now [c v]
{:certname c :values v
:environment nil :timestamp (now) :producer_timestamp (now) :producer nil})
(certname-paths-hash [certname]
(-> "select paths_hash from factsets where certname = ?"
(query-to-vec certname)
first
:paths_hash))
(reset-db []
(clear-db-for-testing!)
(init-db *db*))
(set-cert-facts-causes-update [cert factset]
(let [real-realize-paths realize-paths
called? (atom false)]
(with-redefs [realize-paths (fn [& args]
(reset! called? true)
(apply real-realize-paths args))]
(replace-facts! (facts-now cert factset)))
@called?))]
(with-test-db
(testing "with no hash, establishing no facts establishes a hash"
(reset-db)
(add-certname! "foo")
(is (= nil (certname-paths-hash "foo")))
(set-cert-facts-causes-update "foo" {})
(let [hash (certname-paths-hash "foo")]
(is (= 20 (count hash)))
(is (= (class (byte-array 0)) (class hash)))))
(testing "with hash for no paths, establishing no paths causes no update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {})
(is (= false (set-cert-facts-causes-update "foo" {}))))
(testing "with hash for no paths, establishing paths causes update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {})
(is (= true (set-cert-facts-causes-update "foo" {"a" 1}))))
(testing "with paths, replacing with same paths causes no update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {"a" 1})
(is (= false (set-cert-facts-causes-update "foo" {"a" 1}))))
(testing "with paths, changing fact values causes no update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {"a" 1})
(is (= false (set-cert-facts-causes-update "foo" {"a" 2}))))
(testing "with paths, changing paths causes update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {"a" 1})
(is (= true (set-cert-facts-causes-update "foo" {"b" 1}))))
(testing "with paths, adding path causes update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {"a" 1})
(is (= true (set-cert-facts-causes-update "foo" {"a" 1 "b" 1}))))
(testing "with paths, removing path causes update"
(reset-db)
(add-certname! "foo")
(set-cert-facts-causes-update "foo" {"a" 1 "b" 1})
(is (= true (set-cert-facts-causes-update "foo" {"b" 1})))))))
(deftest-db fact-persistance-with-environment
(testing "Persisted facts"
(let [certname "some_certname"
facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"}
producer "bar.com"]
(add-certname! certname)
(is (nil?
(jdbc/with-db-transaction []
(timestamp-of-newest-record :factsets "some_certname"))))
(is (empty? (factset-map "some_certname")))
(is (nil? (environment-id "PROD")))
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment "PROD"
:producer_timestamp previous-time
:producer producer})
(testing "should have entries for each fact"
(is (= facts (factset-map "some_certname")))
(is (= [{:certname "some_certname"
:environment_id (environment-id "PROD")}]
(query-to-vec "SELECT certname, environment_id FROM factsets"))))
(is (nil? (environment-id "DEV")))
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer})
(testing "should have the same entries for each fact"
(is (= facts (factset-map "some_certname")))
(is (= [{:certname "some_certname"
:environment_id (environment-id "DEV")}]
(query-to-vec "SELECT certname, environment_id FROM factsets")))))))
(defn package-seq
"Return all facts and their values for a given certname as a map"
[certname]
(rest
(jdbc/query
["SELECT p.name as package_name, p.version, p.provider
FROM certname_packages cp
inner join packages p on cp.package_id = p.id
inner join certnames c on cp.certname_id = c.id
WHERE c.certname = ?
ORDER BY package_name, version, provider"
certname]
{:as-arrays? true})))
(deftest-db fact-persistance-with-packages
(testing "Existing facts with new packages added"
(let [certname "some_certname"
facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"}
producer "bar.com"]
(add-certname! certname)
(testing "Existing facts with new packages added"
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment "PROD"
:producer_timestamp previous-time
:producer producer})
(is (empty? (package-seq certname)))
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo" "1.2.3" "apt"]
["bar" "2.3.4" "apt"]
["baz" "3.4.5" "apt"]]})
(is (= [["bar" "2.3.4" "apt"]
["baz" "3.4.5" "apt"]
["foo" "1.2.3" "apt"]]
(package-seq certname))))
(testing "Updating existing packages"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo" "1.2.3" "apt"]
["bar" "2.3.4" "apt"]
["not-baz" "3.4.5" "apt"]]})
(is (= [["bar" "2.3.4" "apt"]
["foo" "1.2.3" "apt"]
["not-baz" "3.4.5" "apt"]]
(package-seq certname))))
(testing "Removing packages"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo" "1.2.3" "apt"]]})
(is (= [["foo" "1.2.3" "apt"]]
(package-seq certname))))
(testing "Removing packages"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo-1" "1.2.3" "apt"]
["foo-2" "1.2.3" "apt"]
["foo-3" "1.2.3" "apt"]
["foo-4" "1.2.3" "apt"]]})
(is (= [["foo-1" "1.2.3" "apt"]
["foo-2" "1.2.3" "apt"]
["foo-3" "1.2.3" "apt"]
["foo-4" "1.2.3" "apt"]]
(package-seq certname))))
(testing "Pinpoint GC cleans up packages"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo-1" "1.2.3" "apt"]]})
(is (= [["foo-1" "1.2.3" "apt"]]
(package-seq certname)))
(is (= 1
(-> ["SELECT count(*) as c FROM packages"]
query-to-vec
first
:c))))
(testing "Orphaned packages are deleted"
(let [package-count (fn [] (-> ["SELECT count(*) as c FROM packages"]
query-to-vec
first
:c))]
(is (pos? (package-count)))
(jdbc/do-commands "DELETE FROM certname_packages")
(is (pos? (package-count)))
(delete-unassociated-packages!)
(is (zero? (package-count))))))))
(deftest-db purge-packages-from-node
(testing "Existing facts with new packages added"
(let [certname "some_certname"
facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"}
producer "bar.com"
reload-packages (fn []
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory [["foo" "1.2.3" "apt"]
["bar" "2.3.4" "apt"]
["baz" "3.4.5" "apt"]]}))
find-package-hash (fn []
(:package_hash (certname-factset-metadata "some_certname")))]
(add-certname! certname)
(add-facts! {:certname certname
:values facts
:timestamp previous-time
:environment "PROD"
:producer_timestamp previous-time
:producer producer})
(is (empty? (package-seq certname)))
(reload-packages)
(testing "data was loaded for test"
(is (= 3 (count (package-seq certname)))))
(is (find-package-hash))
(testing "package_inventory key is missing from command"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer})
(is (= []
(package-seq certname)))
(is (nil? (find-package-hash))))
(reload-packages)
(is (= 3 (count (package-seq certname))))
(testing "package_inventory is nil"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory nil})
(is (= 0 (count (package-seq certname))))
(is (nil? (find-package-hash))))
(reload-packages)
(is (= 3 (count (package-seq certname))))
(is (find-package-hash))
(testing "package_inventory is empty"
(update-facts!
{:certname certname
:values facts
:timestamp (-> 1 days ago)
:environment "DEV"
:producer_timestamp (-> 1 days ago)
:producer producer
:package_inventory []})
(is (= 0 (count (package-seq certname))))
(is (nil? (find-package-hash)))))))
(def catalog (:basic catalogs))
(def certname (:certname catalog))
(def current-time (str (now)))
(deftest-db catalog-persistence
(testing "Persisted catalogs"
(add-certname! certname)
(replace-catalog! (assoc catalog :producer_timestamp current-time))
(testing "should contain proper catalog metadata"
(is (= (query-to-vec ["SELECT certname, api_version, catalog_version, producer_timestamp FROM catalogs"])
[{:certname certname :api_version 1 :catalog_version "123456789" :producer_timestamp (to-timestamp current-time)}])))
(testing "should contain a complete edges list"
(is (= (query-to-vec [(str "SELECT r1.type as stype, r1.title as stitle, r2.type as ttype, r2.title as ttitle, e.type as etype "
"FROM edges e, catalog_resources r1, catalog_resources r2 "
"WHERE e.source=r1.resource AND e.target=r2.resource "
"ORDER BY r1.type, r1.title, r2.type, r2.title, e.type")])
[{:stype "Class" :stitle "foobar" :ttype "File" :ttitle "/etc/foobar" :etype "contains"}
{:stype "Class" :stitle "foobar" :ttype "File" :ttitle "/etc/foobar/baz" :etype "contains"}
{:stype "File" :stitle "/etc/foobar" :ttype "File" :ttitle "/etc/foobar/baz" :etype "required-by"}])))
(testing "should contain a complete resources list"
(is (= (query-to-vec ["SELECT type, title FROM catalog_resources ORDER BY type, title"])
[{:type "Class" :title "foobar"}
{:type "File" :title "/etc/foobar"}
{:type "File" :title "/etc/foobar/baz"}]))
(testing "properly associated with the host"
(is (= (query-to-vec ["SELECT c.certname, cr.type, cr.title
FROM catalog_resources cr, certnames c
WHERE c.id=cr.certname_id
ORDER BY cr.type, cr.title"])
[{:certname certname :type "Class" :title "foobar"}
{:certname certname :type "File" :title "/etc/foobar"}
{:certname certname :type "File" :title "/etc/foobar/baz"}])))
(testing "with all parameters"
(is (= (query-to-vec ["SELECT cr.type, cr.title, rp.name, rp.value FROM catalog_resources cr, resource_params rp WHERE rp.resource=cr.resource ORDER BY cr.type, cr.title, rp.name"])
[{:type "File" :title "/etc/foobar" :name "ensure" :value (sutils/db-serialize "directory")}
{:type "File" :title "/etc/foobar" :name "group" :value (sutils/db-serialize "root")}
{:type "File" :title "/etc/foobar" :name "user" :value (sutils/db-serialize "root")}
{:type "File" :title "/etc/foobar/baz" :name "ensure" :value (sutils/db-serialize "directory")}
{:type "File" :title "/etc/foobar/baz" :name "group" :value (sutils/db-serialize "root")}
{:type "File" :title "/etc/foobar/baz" :name "require" :value (sutils/db-serialize "File[/etc/foobar]")}
{:type "File" :title "/etc/foobar/baz" :name "user" :value (sutils/db-serialize "root")}])))
(testing "with all metadata"
(let [result (query-to-vec ["SELECT cr.type, cr.title, cr.exported, cr.tags, cr.file, cr.line FROM catalog_resources cr ORDER BY cr.type, cr.title"])]
(is (= (map #(assoc % :tags (sort (:tags %))) result)
[{:type "Class" :title "foobar" :tags ["class" "foobar"] :exported false :file nil :line nil}
{:type "File" :title "/etc/foobar" :tags ["class" "file" "foobar"] :exported false :file "/tmp/foo" :line 10}
{:type "File" :title "/etc/foobar/baz" :tags ["class" "file" "foobar"] :exported false :file "/tmp/bar" :line 20}])))))))
(deftest-db catalog-persistence-with-environment
(let [other-certname "notbasic.catalogs.com"]
(testing "Persisted catalogs"
(add-certname! certname)
(add-certname! other-certname)
(is (nil? (environment-id "PROD")))
(replace-catalog! (assoc catalog :environment "PROD"))
(testing "should persist environment if the environment is new"
(let [id (environment-id "PROD")]
(is (number? (environment-id "PROD")))
(is (= [{:certname certname :api_version 1 :catalog_version "123456789" :environment_id id}]
(query-to-vec ["SELECT certname, api_version, catalog_version, environment_id FROM catalogs"])))
(testing "Adding another catalog with the same environment should just use the existing environment"
(replace-catalog! (assoc catalog :environment "PROD" :certname other-certname))
(is (= [{:certname other-certname :api_version 1 :catalog_version "123456789" :environment_id id}]
(query-to-vec ["SELECT certname, api_version, catalog_version, environment_id FROM catalogs where certname=?" other-certname])))))))))
(deftest-db updating-catalog-environment
(testing "should persist environment if the environment is new"
(let [prod-id (ensure-environment "PROD")
dev-id (ensure-environment "DEV")]
(add-certname! certname)
(replace-catalog! (assoc catalog :environment "DEV"))
(is (= [{:certname certname :api_version 1 :catalog_version "123456789" :environment_id dev-id}]
(query-to-vec ["SELECT certname, api_version, catalog_version, environment_id FROM catalogs"])))
(replace-catalog! (assoc catalog :environment "PROD"))
(is (= [{:certname certname :api_version 1 :catalog_version "123456789" :environment_id prod-id}]
(query-to-vec ["SELECT certname, api_version, catalog_version, environment_id FROM catalogs"]))))))
(deftest-db catalog-replacement
(testing "should noop if replaced by themselves"
(add-certname! certname)
(let [hash (replace-catalog! catalog)]
(replace-catalog! catalog (now))
(is (= (query-to-vec ["SELECT certname FROM certnames"])
[{:certname certname}]))
(is (= (query-to-vec [(format "SELECT %s AS hash FROM catalogs" (sutils/sql-hash-as-str "hash"))])
[{:hash hash}])))))
(deftest-db edge-replacement-differential
(testing "should do selective inserts/deletes when edges are modified just slightly"
(add-certname! certname)
(let [original-catalog (:basic catalogs)
original-edges (:edges original-catalog)
modified-edges (conj (disj original-edges {:source {:type "Class" :title "foobar"}
:target {:type "File" :title "/etc/foobar"}
:relationship :contains})
{:source {:type "File" :title "/etc/foobar"}
:target {:type "File" :title "/etc/foobar/baz"}
:relationship :before})
modified-catalog (assoc original-catalog :edges modified-edges)]
;; Add an initial catalog, we don't care to intercept the SQL yet
(replace-catalog! original-catalog (now))
(testing "ensure catalog-edges-map returns a predictable value"
(is (= (catalog-edges-map certname)
{["PI:KEY:<KEY>END_PI"
"57PI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PI"
"contains"] nil,
["PI:KEY:<KEY>END_PI"
"e247f822a0f0bbbfff4fe066ce4a077fPI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PI"
"required-by"] nil,
["PI:KEY:<KEY>END_PI"
"e247f822a0PI:KEY:<KEY>END_PIbbbfff4fe0PI:KEY:<KEY>END_PI6cePI:KEY:<KEY>END_PI"
"contains"] nil})))
;; Lets intercept the insert/update/delete level so we can test it later
;; Here we only replace edges, so we can capture those specific SQL
;; operations
(tu/with-wrapped-fn-args [insert-multis jdbc/insert-multi!
deletes jdbc/delete!]
(let [resources (:resources modified-catalog)
refs-to-hash (reduce-kv (fn [i k v]
(assoc i k (shash/resource-identity-hash v)))
{} resources)]
(replace-edges! certname modified-edges refs-to-hash)
(testing "ensure catalog-edges-map returns a predictable value"
(is (= (catalog-edges-map certname)
{["PI:KEY:<KEY>END_PI"
"e247f822a0f0bbbfff4fe066ce4a077f9PI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PIcdb1"
"contains"] nil,
["57PI:KEY:<KEY>END_PI9PI:KEY:<KEY>END_PI51c5194a21b9a26554cd93db3d9"
"e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1"
"required-by"] nil
["57495b553981551c5194a21b9a26554cd93db3d9"
"e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1"
"before"] nil})))
(testing "should only delete the 1 edge"
(let [source-hash "ff0702ba8a7dc69d3fb17f9d151bf9bd265a9ed9"
target-hash "57495b553981551c5194a21b9a26554cd93db3d9"]
(is (= [[:edges [(str "certname=?"
" and source=?::bytea"
" and target=?::bytea"
" and type=?")
"basic.catalogs.com"
(sutils/bytea-escape source-hash)
(sutils/bytea-escape target-hash)
"contains"]]]
@deletes))))
(testing "should only insert the 1 edge"
(is (= [[:edges [{:certname "basic.catalogs.com"
:source (sutils/munge-hash-for-storage "57495b553981551c5194a21b9a26554cd93db3d9")
:target (sutils/munge-hash-for-storage "e247f822a0f0bbbfff4fe066ce4a077f9c03cdb1")
:type "before"}]]]
@insert-multis)))
(testing "when reran to check for idempotency"
(reset! insert-multis [])
(reset! deletes [])
(replace-edges! certname modified-edges refs-to-hash)
(testing "should delete no edges"
(is (empty? @deletes)))
(testing "should insert no edges"
(is (empty? @insert-multis)))))))))
(deftest-db catalog-duplicates
(testing "should share structure when duplicate catalogs are detected for the same host"
(add-certname! certname)
(let [hash (replace-catalog! catalog)
prev-dupe-num (counters/value (:duplicate-catalog performance-metrics))
prev-new-num (counters/value (:updated-catalog performance-metrics))]
;; Do an initial replacement with the same catalog
(replace-catalog! catalog (now))
(is (= 1 (- (counters/value (:duplicate-catalog performance-metrics)) prev-dupe-num)))
(is (= 0 (- (counters/value (:updated-catalog performance-metrics)) prev-new-num)))
;; Store a second catalog, with the same content save the version
(replace-catalog! (assoc catalog :version "abc123") (now))
(is (= 2 (- (counters/value (:duplicate-catalog performance-metrics)) prev-dupe-num)))
(is (= 0 (- (counters/value (:updated-catalog performance-metrics)) prev-new-num)))
(is (= (query-to-vec ["SELECT certname FROM certnames"])
[{:certname certname}]))
(is (= (query-to-vec [(format "SELECT certname, %s AS hash FROM catalogs" (sutils/sql-hash-as-str "hash"))])
[{:hash hash
:certname certname}]))
(replace-catalog! (assoc-in catalog [:resources {:type "File" :title "/etc/foobar"} :line] 20) (now))
(is (= 2 (- (counters/value (:duplicate-catalog performance-metrics)) prev-dupe-num)))
(is (= 1 (- (counters/value (:updated-catalog performance-metrics)) prev-new-num))))))
(deftest-db fact-delete-deletes-facts
(add-certname! certname)
;; Add some facts
(let [facts {"domain" "mydomain.com"
"fqdn" "myhost.mydomain.com"
"hostname" "myhost"
"kernel" "Linux"
"operatingsystem" "Debian"
"networking" {"eth0" {"ipaddresses" ["192.168.0.11"]}}}]
(add-facts! {:certname certname
:values facts
:timestamp (-> 2 days ago)
:environment "ENV3"
:producer_timestamp (-> 2 days ago)
:producer "bar.com"}))
(is (= 6 (count-facts)))
(is (= 6 (count-facts)))
(delete-certname-facts! certname)
(is (= 0 (count-facts)))
(is (= 0 (count-facts))))
(deftest-db catalog-bad-input
(testing "should noop"
(testing "on bad input"
(is (thrown? clojure.lang.ExceptionInfo (replace-catalog! {})))
;; Nothing should have been persisted for this catalog
(is (= (query-to-vec ["SELECT count(*) as nrows from certnames"])
[{:nrows 0}])))))
(defn foobar->foobar2 [x]
(if (and (string? x) (= x "/etc/foobar"))
"/etc/foobar2"
x))
(defn table-args
"Many of the puppetdb.jdbc functions accept a table name as the first arg, this
function grabs that argument"
[coll]
(map first coll))
(defn remove-edge-changes
"Remove the edge related changes from the `coll` of function call arguments"
[coll]
(remove #(= :edges (first %)) coll))
(defn sort= [& args]
(apply = (map sort args)))
(deftest-db existing-catalog-update
(let [{certname :certname :as catalog} (:basic catalogs)
old-date (-> 2 days ago)
yesterday (-> 1 days ago)]
(testing "inserting new catalog with resources"
(add-certname! certname)
(is (empty? (query-to-vec "SELECT * from catalogs where certname=?" certname)))
(replace-catalog! catalog old-date)
(let [results (query-to-vec "SELECT timestamp from catalogs where certname=?" certname)
{:keys [timestamp]} (first results)]
(is (= 1 (count results)))
(is (= (to-timestamp old-date) (to-timestamp timestamp)))))
(testing "changing a resource title"
(let [[{orig-id :id
orig-tx-id :transaction_uuid
orig-timestamp :timestamp}]
(query-to-vec (str "select id, timestamp, transaction_uuid::text"
" from catalogs where certname=?")
certname)
updated-catalog (walk/prewalk foobar->foobar2 (:basic catalogs))
new-uuid (kitchensink/uuid)
metrics-map performance-metrics]
(is (= #{{:type "Class" :title "foobar"}
{:type "File" :title "/etc/foobar"}
{:type "File" :title "/etc/foobar/baz"}}
(set (query-to-vec "SELECT cr.type, cr.title
FROM catalogs c
INNER JOIN certnames on c.certname=certnames.certname
INNER JOIN catalog_resources cr
ON certnames.id=cr.certname_id
WHERE c.certname=?" certname))))
(tu/with-wrapped-fn-args [inserts jdbc/insert!
insert-multis jdbc/insert-multi!
deletes jdbc/delete!
updates jdbc/update!]
(with-redefs [performance-metrics
(assoc metrics-map
:catalog-volatility (histogram storage-metrics-registry [(str (gensym))]))]
(replace-catalog! (assoc updated-catalog :transaction_uuid new-uuid) yesterday)
;; 2 edge deletes
;; 2 edge inserts
;; 1 params insert
;; 1 params cache insert
;; 1 catalog_resource insert
;; 1 catalog_resource delete
(is (= 8 (apply + (sample (:catalog-volatility performance-metrics))))))
(is (sort= [:resource_params_cache :resource_params :catalog_resources :edges]
(table-args (concat @inserts @insert-multis))))
(is (= [:catalogs]
(table-args @updates)))
(is (= [[:catalog_resources ["certname_id = ? and type = ? and title = ?"
(-> @updates first (nth 2) second)
"File" "/etc/foobar"]]]
(remove-edge-changes @deletes))))
(is (= #{{:type "Class" :title "foobar"}
{:type "File" :title "/etc/foobar2"}
{:type "File" :title "/etc/foobar/baz"}}
(set (query-to-vec "SELECT cr.type, cr.title
FROM catalogs c
INNER JOIN certnames ON certnames.certname = c.certname
INNER JOIN catalog_resources cr ON cr.certname_id = certnames.id
WHERE c.certname=?" certname))))
(let [results (query-to-vec
(str "select id, timestamp, transaction_uuid::text"
" from catalogs where certname=?")
certname)
{new-timestamp :timestamp
new-tx-id :transaction_uuid
new-id :id} (first results)]
(is (= 1 (count results)))
(is (= (to-timestamp yesterday) (to-timestamp new-timestamp)))
(is (= new-tx-id new-uuid))
(is (= orig-id new-id))
(is (not= orig-tx-id new-tx-id))
(is (not= orig-timestamp new-timestamp)))))))
(comment
(existing-catalog-update)
)
(deftest-db add-resource-to-existing-catalog
(let [{certname :certname :as catalog} (:basic catalogs)
old-date (-> 2 days ago)
yesterday (-> 1 days ago)]
(add-certname! certname)
(replace-catalog! catalog old-date)
(is (= 3 (:c (first (query-to-vec "SELECT count(*) AS c FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname)))))
(tu/with-wrapped-fn-args [inserts jdbc/insert!
insert-multis jdbc/insert-multi!
updates jdbc/update!
deletes jdbc/delete!]
(replace-catalog! (assoc-in catalog
[:resources {:type "File" :title "/etc/foobar2"}]
{:type "File"
:title "/etc/foobar2"
:exported false
:file "/tmp/foo2"
:line 20
:tags #{"file" "class" "foobar"}
:parameters {:ensure "directory"
:group "root"
:user "root"}})
old-date)
(is (sort= [:resource_params_cache :resource_params :catalog_resources]
(table-args (concat @inserts @insert-multis))))
(is (= [:catalogs] (table-args @updates)))
(is (empty? @deletes)))
(is (= 4 (:c (first (query-to-vec "SELECT count(*) AS c FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname)))))))
(deftest-db change-line-resource-metadata
(add-certname! certname)
(replace-catalog! catalog)
(testing "changing line number"
(is (= #{{:line nil}
{:line 10}
{:line 20}}
(set (query-to-vec "SELECT line FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname))))
(replace-catalog! (update-in catalog [:resources]
(fn [resources]
(kitchensink/mapvals #(assoc % :line 1000) resources))))
(is (= [{:line 1000}
{:line 1000}
{:line 1000}]
(query-to-vec "SELECT line FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname)))))
(deftest-db change-exported-resource-metadata
(add-certname! certname)
(replace-catalog! catalog)
(testing "changing exported"
(is (= #{{:exported false
:title "foobar"}
{:exported false
:title "/etc/foobar"}
{:exported false
:title "/etc/foobar/baz"}}
(set (query-to-vec "SELECT title, exported FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname))))
(replace-catalog! (update-in catalog [:resources]
(fn [resources]
(-> resources
(assoc-in [{:type "Class" :title "foobar"} :exported] true)
(assoc-in [{:type "File" :title "/etc/foobar/baz"} :exported] true)))))
(is (= #{{:exported true
:title "foobar"}
{:exported false
:title "/etc/foobar"}
{:exported true
:title "/etc/foobar/baz"}}
(set (query-to-vec "SELECT title, exported FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname))))))
(deftest-db change-file-resource-metadata
(add-certname! certname)
(replace-catalog! catalog)
(testing "changing line number"
(is (= #{{:title "foobar"
:file nil}
{:title "/etc/foobar"
:file "/tmp/foo"}
{:title "/etc/foobar/baz"
:file "/tmp/bar"}}
(set (query-to-vec "SELECT title, file FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname))))
(replace-catalog! (update-in catalog [:resources]
(fn [resources]
(kitchensink/mapvals #(assoc % :file "/tmp/foo.pp") resources))))
(is (= #{{:title "foobar"
:file "/tmp/foo.pp"}
{:title "/etc/foobar"
:file "/tmp/foo.pp"}
{:title "/etc/foobar/baz"
:file "/tmp/foo.pp"}}
(set (query-to-vec "SELECT title, file FROM catalog_resources WHERE certname_id = (select id from certnames where certname = ?)" certname))))))
(defn tags->set
"Converts tags from a pg-array to a set of strings"
[result-set]
(mapv (fn [result]
(update-in result [:tags] #(jdbc/convert-any-sql-array % set)))
result-set))
(deftest-db change-tags-on-resource
(add-certname! certname)
(replace-catalog! catalog)
(is (= #{{:title "foobar"
:tags #{"class" "foobar"}
:line nil}
{:title "/etc/foobar"
:tags #{"file" "class" "foobar"}
:line 10}
{:title "/etc/foobar/baz"
:tags #{"file" "class" "foobar"}
:line 20}}
(call-with-query-rows
[(str "select title, tags, line from catalog_resources"
" inner join certnames c on c.id = certname_id"
" where c.certname = ?")
certname]
#(-> % tags->set set))))
(replace-catalog! (update-in catalog [:resources]
(fn [resources]
(-> resources
(assoc-in [{:type "File" :title "/etc/foobar"} :tags] #{"totally" "different" "tags"})
(assoc-in [{:type "File" :title "/etc/foobar"} :line] 500)))))
(is (= #{{:title "foobar"
:tags #{"class" "foobar"}
:line nil}
{:title "/etc/foobar"
:line 500
:tags #{"totally" "different" "tags"}}
{:title "/etc/foobar/baz"
:line 20
:tags #{"file" "class" "foobar"}}}
(call-with-query-rows
[(str "select title, tags, line from catalog_resources"
" inner join certnames c on c.id = certname_id"
" where c.certname = ?")
certname]
#(-> % tags->set set)))))
(deftest-db removing-resources
(let [{certname :certname :as catalog} (:basic catalogs)
old-date (-> 2 days ago)
yesterday (-> 1 days ago)
catalog-with-extra-resource (assoc-in catalog
[:resources {:type "File" :title "/etc/the-foo"}]
{:type "File"
:title "/etc/the-foo"
:exported false
:file "/tmp/the-foo"
:line 10
:tags #{"file" "class" "the-foo"}
:parameters {:ensure "directory"
:group "root"
:user "root"}})]
(add-certname! certname)
(replace-catalog! catalog-with-extra-resource old-date)
(let [certname-id (:id (first (query-to-vec "SELECT id from certnames where certname=?" certname)))]
(is (= 4 (count (query-to-vec "SELECT * from catalog_resources where certname_id = ?" certname-id))))
(tu/with-wrapped-fn-args [inserts jdbc/insert!
updates jdbc/update!
deletes jdbc/delete!]
(replace-catalog! catalog yesterday)
(is (empty? @inserts))
(is (= [:catalogs] (table-args @updates)))
(is (= [:catalog_resources] (table-args @deletes))))
(let [catalog-results (query-to-vec "SELECT timestamp from catalogs where certname=?" certname)
{:keys [timestamp]} (first catalog-results)
resources (set (query-to-vec "SELECT type, title from catalog_resources where certname_id = ?" certname-id))]
(is (= 1 (count catalog-results)))
(is (= 3 (count resources)))
(is (= (set (keys (:resources catalog)))
resources))
(is (= (to-timestamp yesterday) (to-timestamp timestamp)))))))
(defn foobar-params []
(jdbc/query-with-resultset
["SELECT p.name AS k, p.value AS v
FROM catalog_resources cr, certnames c, resource_params p
WHERE cr.certname_id = c.id AND cr.resource = p.resource AND c.certname=?
AND cr.type=? AND cr.title=?"
(get-in catalogs [:basic :certname]) "File" "/etc/foobar"]
(fn [rs]
(reduce (fn [acc row]
(assoc acc (keyword (:k row))
(json/parse-string (:v row))))
{}
(sql/result-set-seq rs)))))
(defn foobar-params-cache []
(jdbc/query-with-resultset
["SELECT rpc.parameters as params
FROM catalog_resources cr, certnames c, resource_params_cache rpc
WHERE cr.certname_id = c.id AND cr.resource = rpc.resource AND c.certname=?
AND cr.type=? AND cr.title=?"
(get-in catalogs [:basic :certname]) "File" "/etc/foobar"]
#(-> (sql/result-set-seq %)
first
:params
sutils/parse-db-json)))
(defn foobar-param-hash []
(jdbc/query-with-resultset
[(format "SELECT %s AS hash
FROM catalog_resources cr, certnames c
WHERE cr.certname_id = c.id AND c.certname=? AND cr.type=?
AND cr.title=?"
(sutils/sql-hash-as-str "cr.resource"))
(get-in catalogs [:basic :certname]) "File" "/etc/foobar"]
(comp :hash first sql/result-set-seq)))
(deftest-db catalog-resource-parameter-changes
(let [{certname :certname :as catalog} (:basic catalogs)
old-date (-> 2 days ago)
yesterday (-> 1 days ago)]
(add-certname! certname)
(replace-catalog! catalog old-date)
(let [orig-resource-hash (foobar-param-hash)
add-param-catalog (assoc-in catalog [:resources {:type "File" :title "/etc/foobar"} :parameters :uid] "100")]
(is (= (get-in catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params)))
(is (= (get-in catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params-cache)))
(tu/with-wrapped-fn-args [inserts jdbc/insert!
insert-multis jdbc/insert-multi!
updates jdbc/update!
deletes jdbc/delete!]
(replace-catalog! add-param-catalog yesterday)
(is (sort= [:catalogs :catalog_resources]
(table-args @updates)))
(is (empty? (remove-edge-changes @deletes)))
(is (sort= [:resource_params_cache :resource_params :edges]
(->> (concat @inserts @insert-multis)
(remove #(empty? (second %))) ;; remove inserts w/out rows
table-args))))
(is (not= orig-resource-hash (foobar-param-hash)))
(is (= (get-in add-param-catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params)))
(is (= (get-in add-param-catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params-cache)))
(tu/with-wrapped-fn-args [inserts jdbc/insert!
insert-multis jdbc/insert-multi!
updates jdbc/update!
deletes jdbc/delete!]
(replace-catalog! catalog old-date)
(is (empty? (remove #(or (= :edges (first %)) (empty? (second %)))
(concat @inserts @insert-multis))))
(is (empty? (remove #(= :edges (first %)) @deletes)))
(is (= (sort [:catalog_resources :catalogs])
(sort (table-args @updates)))))
(is (= orig-resource-hash (foobar-param-hash)))
(is (= (get-in catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params)))
(is (= (get-in catalog [:resources {:type "File" :title "/etc/foobar"} :parameters])
(foobar-params-cache))))))
(deftest-db catalog-referential-integrity-violation
(testing "on input that violates referential integrity"
;; This catalog has an edge that points to a non-existant resource
(let [catalog (:invalid catalogs)]
(is (thrown? clojure.lang.ExceptionInfo (replace-catalog! catalog)))
;; Nothing should have been persisted for this catalog
(is (= (query-to-vec ["SELECT count(*) as nrows from certnames"])
[{:nrows 0}])))))
(deftest-db node-deactivation
(let [certname "foo.example.com"
query-certnames #(query-to-vec ["select certname, deactivated from certnames"])
deactivated? #(instance? java.sql.Timestamp (:deactivated %))]
(add-certname! certname)
(testing "deactivating a node"
(testing "should mark the node as deactivated"
(deactivate-node! certname)
(let [result (first (query-certnames))]
(is (= certname (:certname result)))
(is (deactivated? result))))
(testing "should not change the node if it's already inactive"
(let [original (query-certnames)]
(deactivate-node! certname)
;; Convert any :deactivated values to #t for comparison
;; since we only care about the state.
(letfn [(deactivated->truthy [x]
(assoc x :deactivated (when (:deactivated x) true)))]
(is (= (map deactivated->truthy original)
(map deactivated->truthy (query-certnames))))))))
(testing "activating a node"
(testing "should activate the node if it was inactive"
(activate-node! certname)
(is (= (query-certnames) [{:certname certname :deactivated nil}])))
(testing "should do nothing if the node is already active"
(let [original (query-certnames)]
(activate-node! certname)
(is (= original (query-certnames))))))
(testing "auto-reactivated based on a command"
(let [before-deactivating (to-timestamp (-> 1 days ago))
after-deactivating (to-timestamp (-> 1 days from-now))]
(testing "should activate the node if the command happened after it was deactivated"
(deactivate-node! certname)
(is (= true (maybe-activate-node! certname after-deactivating)))
(is (= (query-certnames) [{:certname certname :deactivated nil}])))
(testing "should not activate the node if the command happened before it was deactivated"
(deactivate-node! certname)
(is (= false (maybe-activate-node! certname before-deactivating)))
(let [result (first (query-certnames))]
(is (= certname (:certname result)))
(is (deactivated? result))))
(testing "should do nothing if the node is already active"
(activate-node! certname)
(is (= false (maybe-activate-node! certname (now))))
(is (= (query-certnames) [{:certname certname :deactivated nil}])))))))
(deftest-db fresh-node-not-expired
(testing "fresh nodes are not expired"
(let [catalog (:empty catalogs)
certname (:certname catalog)]
(add-certname! certname)
(replace-catalog! (assoc catalog :producer_timestamp (now)) (now))
(is (= [] (expire-stale-nodes (-> 3 days .toPeriod))))
(is (= (map :certname (query-to-vec "select certname from certnames"))
[certname])))))
(deftest expire-nodes-with-stale-catalogs-and-facts-or-none
(testing "nodes with only stale facts/catalogs or no facts/catalogs expire"
(let [mutators {:rc #(replace-catalog!
(assoc (:empty catalogs) :certname "node1")
(-> 2 days ago))
:rf #(replace-facts!
{:certname "node1"
:values {"foo" "bar"}
:environment "DEV"
:producer_timestamp (-> 10 days ago)
:timestamp (-> 2 days ago)
:producer "baz.com"})}]
(doseq [ops (subsets (keys mutators))]
(with-test-db
(add-certname! "node1")
(dorun (map #((mutators %)) ops))
(is (= [ops ["node1"]]
[ops (expire-stale-nodes (-> 1 days .toPeriod))])))))))
(deftest-db node-with-only-fresh-report-is-not-expired
(testing "does not expire a node with a recent report and nothing else"
(let [report (-> (:basic reports)
(assoc :environment "ENV2")
(assoc :end_time (now))
(assoc :producer_timestamp (now)))]
(store-example-report! report (now))
(is (= [] (expire-stale-nodes (-> 1 days .toPeriod)))))))
(deftest stale-nodes-expiration-via-reports
(let [report-at #(assoc (:basic reports)
:environment "ENV2"
:end_time %
:producer_timestamp %)
stamp (now)
stale-stamp-1 (-> 2 days ago)
stale-stamp-2 (-> 3 days ago)]
(with-test-db
(testing "doesn't return node with a recent report and nothing else"
(store-example-report! (report-at stamp) stamp)
(is (= [] (expire-stale-nodes (-> 1 days .toPeriod)))))
(testing "doesn't return node with a recent report and a stale report"
(store-example-report! (report-at stale-stamp-1) stale-stamp-1)
(is (= [] (expire-stale-nodes (-> 1 days .toPeriod))))))
(with-test-db
(testing "returns a node with only stale reports"
(store-example-report! (report-at stale-stamp-1) stale-stamp-1)
(store-example-report! (report-at stale-stamp-2) stale-stamp-2)
(is (= ["foo.local"] (expire-stale-nodes (-> 1 days .toPeriod))))))))
(deftest-db stale-nodes-expiration-via-catalogs
(let [repcat (fn [type stamp]
(replace-catalog! (assoc (type catalogs)
:certname "node1"
:producer_timestamp stamp)
stamp))
stamp (now)
stale-stamp (-> 2 days ago)]
(with-test-db
(testing "doesn't return node with a recent catalog and nothing else"
(add-certname! "node1")
(repcat :empty stamp)
(is (= [] (expire-stale-nodes (-> 1 days .toPeriod))))))
(with-test-db
(testing "returns a node with only a stale catalog"
(add-certname! "node1")
(repcat :empty stale-stamp)
(is (= ["node1"] (expire-stale-nodes (-> 1 days .toPeriod))))))))
(deftest-db only-nodes-older-than-max-age-expired
(testing "should only return nodes older than max age, and leave others alone"
(let [catalog (:empty catalogs)]
(add-certname! "node1")
(add-certname! "node2")
(replace-catalog! (assoc catalog
:certname "node1"
:producer_timestamp (-> 2 days ago))
(now))
(replace-catalog! (assoc catalog
:certname "node2"
:producer_timestamp (now))
(now))
(is (= ["node1"] (expire-stale-nodes (-> 1 days .toPeriod)))))))
(deftest-db node-purge
(testing "should purge nodes which were deactivated before the specified date"
(add-certname! "node1")
(add-certname! "node2")
(add-certname! "node3")
(deactivate-node! "node1")
(deactivate-node! "node2" (-> 10 days ago))
(purge-deactivated-and-expired-nodes! (-> 5 days ago))
(is (= (map :certname
(query-to-vec
"select certname from certnames order by certname asc"))
["node1" "node3"]))))
(deftest-db node-purge-cleans-packages
(testing "should purge nodes which were deactivated before the specified date"
(add-certname! "node1")
(add-certname! "node2")
(insert-packages "node1" [["foo" "1.2.3" "apt"] ["bar" "2.3.4" "apt"]])
(insert-packages "node2" [["foo" "1.2.3" "apt"] ["bar" "2.3.4" "apt"]])
(deactivate-node! "node1")
(deactivate-node! "node2" (-> 10 days ago))
(purge-deactivated-and-expired-nodes! (-> 5 days ago))
(is (= 1
(count (query-to-vec
"select certname_id from certname_packages group by certname_id"))))))
(deftest-db delete-certname-cleans-packages
(add-certname! "node1")
(add-certname! "node2")
(insert-packages "node1" [["foo" "1.2.3" "apt"] ["bar" "2.3.4" "apt"]])
(insert-packages "node2" [["foo" "1.2.3" "apt"] ["bar" "2.3.4" "apt"]])
(delete-certname! "node1")
(is (= 1
(count (query-to-vec
"select certname_id from certname_packages group by certname_id")))))
(deftest-db purge-expired-nodes
(testing "should purge nodes which were expired before the specified date"
(add-certname! "node1")
(add-certname! "node2")
(add-certname! "node3")
(expire-node! "node1" (now))
(expire-node! "node2" (-> 10 days ago))
(purge-deactivated-and-expired-nodes! (-> 5 days ago))
(is (= (map :certname
(query-to-vec
"select certname from certnames order by certname asc"))
["node1" "node3"]))))
(deftest-db report-sweep-nullifies-latest-report
(testing "ensure that if the latest report is swept, latest_report_id is updated to nil"
(let [report1 (assoc (:basic reports) :end_time (-> 12 days ago))
report2 (assoc (:basic reports) :certname "bar.local" :end_time (now) :producer_timestamp (now))]
(add-certname! "foo.local")
(add-certname! "bar.local")
(store-example-report! report1 (-> 12 days ago))
(store-example-report! report2 (now))
(let [ids (map :latest_report_id (query-to-vec "select latest_report_id from certnames order by certname"))
_ (delete-reports-older-than! (-> 11 days ago))
ids2 (map :latest_report_id (query-to-vec "select latest_report_id from certnames order by certname"))]
(is (= ids2 [(first ids) nil]))))))
;; Report tests
(defn update-event-timestamps
"Changes each timestamp in the `report`'s resource_events to `new-timestamp`"
[report new-timestamp]
(update-in report [:resource_events]
(fn [events]
(map #(assoc % :timestamp new-timestamp) events))))
(let [timestamp (now)
{:keys [certname] :as report} (:basic reports)
report-hash (-> report
report/report-query->wire-v8
normalize-report
shash/report-identity-hash)]
(deftest-db report-storage
(testing "should store reports"
(store-example-report! report timestamp)
(is (= [{:certname certname}]
(query-to-vec ["SELECT certname FROM reports"])))
(is (= [{:hash report-hash}]
(query-to-vec [(format "SELECT %s AS hash FROM reports" (sutils/sql-hash-as-str "hash"))])))
(testing "foss doesn't store in the resources column"
(is (nil? (:resources (first (query-to-vec ["SELECT resources FROM reports"])))))))
(testing "should store report with long puppet version string"
(store-example-report!
(assoc report
:puppet_version "3.2.1 (Puppet Enterprise 3.0.0-preview0-168-g32c839e)") timestamp)))
(deftest-db report-with-event-timestamp
(let [z-report (update-event-timestamps report "2011-01-01T12:00:01Z")
offset-report (update-event-timestamps report "2011-01-01T12:00:01-0000")]
(is (= (shash/report-identity-hash (normalize-report z-report))
(shash/report-identity-hash (normalize-report offset-report))))))
(deftest-db report-with-null-bytes-in-events
(store-example-report!
(-> report
(assoc-in [:resource_events :data 0 :new_value] "foo\u0000bar")
(assoc-in [:resource_events :data 0 :old_value] "foo\u0000bar"))
timestamp)
(is (= [{:old_value "\"foo\ufffdbar\""
:new_value "\"foo\ufffdbar\""}]
(query-to-vec ["SELECT old_value, new_value from resource_events where old_value ~ 'foo'"]))))
(deftest-db report-storage-with-environment
(is (nil? (environment-id "DEV")))
(store-example-report! (assoc report :environment "DEV") timestamp)
(is (number? (environment-id "DEV")))
(is (= (query-to-vec ["SELECT certname, environment_id FROM reports"])
[{:certname (:certname report)
:environment_id (environment-id "DEV")}])))
(deftest-db report-storage-with-producer
(let [prod-id (ensure-producer "bar.com")]
(store-example-report! (assoc report :producer "bar.com") timestamp)
(is (= (query-to-vec ["SELECT certname, producer_id FROM reports"])
[{:certname (:certname report)
:producer_id prod-id}]))))
(deftest-db report-storage-with-status
(is (nil? (status-id "unchanged")))
(store-example-report! (assoc report :status "unchanged") timestamp)
(is (number? (status-id "unchanged")))
(is (= (query-to-vec ["SELECT certname, status_id FROM reports"])
[{:certname (:certname report)
:status_id (status-id "unchanged")}])))
(deftest-db report-storage-without-resources
(testing "should store reports"
(let [env-id (ensure-environment "DEV")]
(store-example-report! (assoc-in report [:resource_events :data] []) timestamp)
(is (= (query-to-vec ["SELECT certname FROM reports"])
[{:certname (:certname report)}]))
(is (= (query-to-vec ["SELECT COUNT(1) as num_resource_events FROM resource_events"])
[{:num_resource_events 0}])))))
(deftest-db report-storage-with-existing-environment
(testing "should store reports"
(let [env-id (ensure-environment "DEV")]
(store-example-report! (assoc report :environment "DEV") timestamp)
(is (= (query-to-vec ["SELECT certname, environment_id FROM reports"])
[{:certname (:certname report)
:environment_id env-id}])))))
(deftest-db latest-report
(let [node (:certname report)
report-hash (:hash (store-example-report! report timestamp))]
(testing "should flag report as 'latest'"
(is (is-latest-report? node report-hash))
(let [new-report-hash (:hash (store-example-report!
(-> report
(assoc :configuration_version "bar")
(assoc :end_time (now))
(assoc :producer_timestamp (now)))
timestamp))]
(is (is-latest-report? node new-report-hash))
(is (not (is-latest-report? node report-hash)))))
(testing "should not update latest report with older report timestamp"
(let [old-report-hash (:hash (store-example-report!
(-> report
(assoc :configuration_version "bar")
(assoc :end_time (now))
(assoc :producer_timestamp (-> -1 days from-now)))
timestamp))]
(is (not (is-latest-report? node old-report-hash)))))))
(deftest-db report-cleanup
(testing "should delete reports older than the specified age"
(let [report1 (assoc report
:certname "foo"
:end_time (to-string (-> 5 days ago))
:producer_timestamp (to-string (-> 5 days ago)))
report2 (assoc report
:certname "bar"
:end_time (to-string (-> 2 days ago))
:producer_timestamp (to-string (-> 2 days ago)))]
(store-example-report! report1 timestamp)
(store-example-report! report2 timestamp)
(delete-reports-older-than! (-> 3 days ago))
(is (= (query-to-vec ["SELECT certname FROM reports"])
[{:certname "bar"}])))))
(deftest-db resource-events-cleanup
(testing "should delete all events for reports older than the specified age"
(let [report1 (assoc report :end_time (to-string (-> 5 days ago)))
report1-hash (:hash (store-example-report! report1 timestamp))
report2 (assoc report :end_time (to-string (-> 2 days ago)))]
(store-example-report! report2 timestamp)
(delete-reports-older-than! (-> 3 days ago))
(is (= #{}
(set (query-resource-events :latest ["=" "report" report1-hash] {}))))))))
(deftest test-catalog-schemas
(is (= (:basic catalogs) (s/validate catalog-schema (:basic catalogs)))))
(deftest test-resource-metadata-diff
(are [expected left right] (= expected (basic-diff left right))
{}
{:type "foo" :title "bar"}
{:type "foo" :title "bar"}
{:line 20}
{:type "File"
:title "/etc/foobar/baz"
:exported false
:file "/tmp/bar"
:line 10
:tags #{"file" "class" "foobar"}}
{:type "File"
:title "/etc/foobar/baz"
:exported false
:file "/tmp/bar"
:line 20
:tags #{"file" "class" "foobar"}}
{:exported true
:file "/tmp/bar/baz"
:line 30
:tags #{"file" "class" "foobar" "baz"}}
{:type "File"
:title "/etc/foobar/baz"
:exported false
:file "/tmp/bar"
:line 20
:tags #{"file" "class" "foobar"}}
{:type "File"
:title "/etc/foobar/baz"
:exported true
:file "/tmp/bar/baz"
:line 30
:tags #{"file" "class" "foobar" "baz"}}))
(deftest test-diff-resources-metadata
(let [resources-1 {{:type "File" :title "/etc/foobar"}
{:type "File"
:title "/etc/foobar"
:exported false
:file "/tmp/foo"
:line 10
:tags #{"file" "class" "foobar"}}
{:type "File" :title "/etc/foobar/baz"}
{:type "File"
:title "/etc/foobar/baz"
:exported false
:file "/tmp/bar"
:line 20
:tags #{"file" "class" "foobar"}}}
resources-2 {{:type "File" :title "/etc/foobar"}
{:type "File"
:title "/etc/foobar"
:exported false
:file "/tmp/foo"
:line 20
:tags #{"file" "class" "foobar"}}
{:type "File" :title "/etc/foobar/baz"}
{:type "File"
:title "/etc/foobar/baz"
:exported true
:file "/tmp/bar/baz"
:line 30
:tags #{"file" "class" "foobar" "baz"}}}]
(are [expected left right] (= expected (diff-resources-metadata left right))
{}
resources-1
resources-1
{{:type "File" :title "/etc/foobar"}
{:line 30}}
resources-1
(assoc-in resources-1 [{:type "File" :title "/etc/foobar"} :line] 30)
{{:type "File" :title "/etc/foobar"}
{:line 20}
{:type "File" :title "/etc/foobar/baz"}
{:exported true
:file "/tmp/bar/baz"
:line 30
:tags #{"file" "class" "foobar" "baz"}}}
resources-1
resources-2)))
(defn fake-hash
[]
(shash/generic-identity-hash (random/random-string)))
(deftest-db giant-resources-exist
(testing "resources-exist?"
(is (= #{} (resources-exist? (set (take 40000 (repeatedly fake-hash))))))))
(deftest-db test-merge-resource-hash
(let [ref->resource {{:type "File" :title "/tmp/foo"}
{:line 10}
{:type "File" :title "/tmp/bar"}
{:line 20}}
ref->hash {{:type "File" :title "/tmp/foo"}
"foo hash"
{:type "File" :title "/tmp/bar"}
"bar hash"}]
(is (= {{:type "File" :title "/tmp/foo"}
{:line 10 :resource "foo hash"}
{:type "File" :title "/tmp/bar"}
{:line 20 :resource "bar hash"}}
(merge-resource-hash ref->hash ref->resource)))))
(deftest-db test-resources-exist?
(testing "With empty input"
(is (= #{} (resources-exist? #{})))))
(deftest-db setting-fact-expiration-for-certname
(is (= [] (query-to-vec "select * from certname_fact_expiration")))
(add-certname! "foo")
(is (= [] (query-to-vec "select * from certname_fact_expiration")))
(let [stamp-1 (to-timestamp (now))
stamp-2 (to-timestamp (time/plus (now) (time/seconds 1)))
id (-> "select id from certnames where certname = 'foo'"
query-to-vec first :id)]
(set-certname-facts-expiration "foo" true stamp-1)
(is (= [{:certid id :expire true :updated stamp-1}]
(query-to-vec "select * from certname_fact_expiration")))
;; No effect if time is <=
(set-certname-facts-expiration "foo" false stamp-1)
(is (= [{:certid id :expire true :updated stamp-1}]
(query-to-vec "select * from certname_fact_expiration")))
;; Changes for newer time
(set-certname-facts-expiration "foo" false stamp-2)
(is (= [{:certid id :expire false :updated stamp-2}]
(query-to-vec "select * from certname_fact_expiration")))))
(deftest-db adding-catalog-inputs-for-certname
(is (= [] (query-to-vec "select * from catalog_inputs")))
(let [stamp-1 (to-timestamp (now))
stamp-2 (to-timestamp (time/plus (now) (time/seconds 1)))
id (-> "select id from certnames where certname = 'foo'"
query-to-vec first :id)]
(add-certname! "foo")
(replace-catalog! (assoc catalog :producer_timestamp stamp-1 :certname "foo"))
(is (= [] (query-to-vec "select * from catalog_inputs")))
(is (= [{:id 1 :certname "foo" :catalog_inputs_timestamp nil :catalog_inputs_uuid nil}]
(query-to-vec "select certname, id, catalog_inputs_timestamp, catalog_inputs_uuid::text from certnames")))
(replace-catalog-inputs! "foo"
(:catalog_uuid catalog)
[["hiera", "puppetdb::globals::version"]]
stamp-1)
(is (= [{:certname_id 1 :type "hiera" :name "puppetdb::globals::version"}]
(query-to-vec "select * from catalog_inputs")))
(is (= [{:id 1 :certname "foo" :catalog_inputs_timestamp stamp-1 :catalog_inputs_uuid (:catalog_uuid catalog)}]
(query-to-vec "select certname, id, catalog_inputs_timestamp, catalog_inputs_uuid::text from certnames")))
;; Changes for newer time, removes old inputs, supports multiple inputs
(replace-catalog-inputs! "foo"
(:catalog_uuid catalog)
[["hiera", "puppetdb::disable_ssl"]
["hiera", "puppetdb::disable_cleartext"]]
stamp-2)
(is (= [{:certname_id 1 :type "hiera" :name "puppetdb::disable_ssl"}
{:certname_id 1 :type "hiera" :name "puppetdb::disable_cleartext"}]
(query-to-vec "select * from catalog_inputs")))
(is (= [{:id 1 :certname "foo" :catalog_inputs_timestamp stamp-2 :catalog_inputs_uuid (:catalog_uuid catalog)}]
(query-to-vec "select certname, id, catalog_inputs_timestamp, catalog_inputs_uuid::text from certnames")))
;; No effect if time is <=
(replace-catalog-inputs! "foo"
(:catalog_uuid catalog)
[["hiera", "puppetdb::globals::version"]]
stamp-1)
(is (= [{:certname_id 1 :type "hiera" :name "puppetdb::disable_ssl"}
{:certname_id 1 :type "hiera" :name "puppetdb::disable_cleartext"}]
(query-to-vec "select * from catalog_inputs")))
(is (= [{:id 1 :certname "foo" :catalog_inputs_timestamp stamp-2 :catalog_inputs_uuid (:catalog_uuid catalog)}]
(query-to-vec "select certname, id, catalog_inputs_timestamp, catalog_inputs_uuid::text from certnames")))))
|
[
{
"context": "Generator Macro & Guitar Instrument\"\n :author \"Roger Allen\"}\n (:use [overtone.music pitch time]\n [ov",
"end": 383,
"score": 0.999808669090271,
"start": 372,
"tag": "NAME",
"value": "Roger Allen"
}
] | src/overtone/synth/stringed.clj | ABaldwinHunter/overtone | 3,870 | ;; A Stringed Synth Generator Macro & Guitar Example Instrument
;;
;; See overtone/examples/instruments/guitar_synth.clj for example usage.
;;
;; Other instruments (like bass-guitar, ukelele, mandolin, etc.) may
;; use the same basic instrument. Watch this space...
(ns overtone.synth.stringed
^{:doc "A Stringed Synth Generator Macro & Guitar Instrument"
:author "Roger Allen"}
(:use [overtone.music pitch time]
[overtone.sc envelope node server synth ugens]
[overtone.sc.cgens mix]))
;; ======================================================================
(defmacro gen-stringed-synth
"Macro to generate a stringed defsynth with distortion, reverb and
a low-pass filter. Use the pluck-strings and strum-strings helper
functions to play the instrument.
Note: the strings need to be silenced with a gate -> 0 transition
before a gate -> 1 transition activates it. Testing
showed it needed > 25 ms between these transitions to be effective."
[name num-strings free-on-silence]
(let [note-ins (if (= num-strings 1)
[(symbol "note")]
(apply vector
(map #(symbol (format "note-%d" %)) (range num-strings))))
note-default-ins (apply vector
(flatten (map vector
note-ins
(repeat num-strings {:default 60 :min 0 :max 127}))))
gate-ins (if (= num-strings 1)
[(symbol "gate")]
(apply vector
(map #(symbol (format "gate-%d" %)) (range num-strings))))
gate-default-ins (apply vector (flatten (map vector
gate-ins
(repeat num-strings {:default 0}))))
both-default-ins (into note-default-ins gate-default-ins)
note-gate-pairs (apply vector (map vector note-ins gate-ins))
env-gen-fn (if free-on-silence
'(fn [x] (overtone.sc.ugens/env-gen
(overtone.sc.envelope/asr 0.0001 1 0.1)
:gate (second x)
:action overtone.sc.ugens/FREE))
'(fn [x] (overtone.sc.ugens/env-gen
(overtone.sc.envelope/asr 0.0001 1 0.1)
:gate (second x))))
]
`(defsynth ~name
~(str "a stringed instrument synth with " num-strings
" strings mixed and sent thru
distortion and reverb effects followed by a low-pass filter. Use
the pluck-strings and strum-strings helper functions to play the
instrument. Note: the strings need to be silenced with a gate -> 0
transition before a gate -> 1 transition activates it."
(if free-on-silence
" This instrument
is transient. When a string becomes silent, it will be freed."
" This instrument
is persistent. It will not be freed when the strings go silent."))
[~@both-default-ins
~'dur {:default 10.0 :min 1.0 :max 100.0}
~'decay {:default 30 :min 1 :max 100} ;; pluck decay
~'coef {:default 0.3 :min -1 :max 1} ;; pluck coef
~'noise-amp {:default 0.8 :min 0.0 :max 1.0}
~'pre-amp {:default 6.0 :min 0.0 :max 10.0}
~'amp {:default 1.0 :min 0.0 :max 10.0}
;; by default, no distortion, no reverb, no low-pass
~'distort {:default 0.0 :min 0.0 :max 0.9999999999}
~'rvb-mix {:default 0.0 :min 0.0 :max 1.0}
~'rvb-room {:default 0.0 :min 0.0 :max 1.0}
~'rvb-damp {:default 0.0 :min 0.0 :max 1.0}
~'lp-freq {:default 20000 :min 100 :max 20000}
~'lp-rq {:default 1.0 :min 0.1 :max 10.0}
~'pan {:default 0.0 :min -1 :max 1}
~'out-bus {:default 0 :min 0 :max 100}]
(let [strings# (map #(let [frq# (midicps (first %))
nze# (~'* ~'noise-amp (pink-noise))
plk# (pluck nze#
(second %)
(/ 1.0 8.0)
(~'/ 1.0 frq#)
~'decay
~'coef)]
(leak-dc (~'* plk# (~env-gen-fn %))
0.995))
~note-gate-pairs)
src# (~'* ~'pre-amp (mix strings#))
;; distortion from fx-distortion2
k# (~'/ (~'* 2 ~'distort) (~'- 1 ~'distort))
dis# (~'/ (~'* src# (~'+ 1 k#))
(~'+ 1 (~'* k# (abs src#))))
vrb# (free-verb dis# ~'rvb-mix ~'rvb-room ~'rvb-damp)
fil# (rlpf vrb# ~'lp-freq ~'lp-rq)]
(out ~'out-bus (pan2 (~'* ~'amp fil#) ~'pan))))))
;;(macroexpand-1 '(gen-stringed-synth ektara 1 true))
;; ======================================================================
;; common routines for stringed instruments
(defn- fret-to-note
"given a fret-offset, add to the base note index with special
handling for -1"
[base-note offset]
(if (>= offset 0)
(+ base-note offset)
offset))
(defn- mkarg
"useful for making arguments for the instruments strings"
[s i]
(keyword (format "%s-%d" s i)))
(defn- now+
"add an epsilon of time to (now) to avoid lots of 'late' error messages"
[]
(+ (now) 21)) ;; 21ms seems to get rid of most for me.
;; ======================================================================
;; Main helper functions used to play the instrument: pick or strum
(defn pick-string
"pick the instrument's string depending on the fret selected. A
fret value less than -1 will cause no event; -1 or greater causes
the previous note to be silenced; 0 or greater will also cause a
new note event."
([the-strings the-inst string-index fret t]
(let [the-note (fret-to-note (nth the-strings string-index) fret)]
;; turn off the previous note
(if (>= the-note -1)
(at t (ctl the-inst (mkarg "gate" string-index) 0)))
;; NOTE: there needs to be some time between these
;; FIXME: +50 seems conservative. Find minimum.
(if (>= the-note 0)
(at (+ t 50) (ctl the-inst
(mkarg "note" string-index) the-note
(mkarg "gate" string-index) 1)))))
([the-chord-frets the-inst string-index fret]
(pick-string the-chord-frets the-inst string-index fret (now+))))
;; ======================================================================
(defn strum-strings
"strum a chord on the instrument in a direction (:up or :down) with
a strum duration of strum-time at t. If the-chord is a vector, use
it directly for fret indexes."
([chord-fret-map the-strings the-inst the-chord direction strum-time t]
(let [num-strings (count (chord-fret-map :A))
;; ex: [-1 3 2 0 1 0]
chord-frets (if (vector? the-chord)
;; treat the-chord as a series of frets
;; and gracefully handle odd sized vectors
(vec (take num-strings
(into the-chord
(vec (repeat num-strings -1)))))
;; else use the-chord as an index
(chord-fret-map the-chord))
;; account for unplayed strings for delta time calc. Code
;; gets a bit complicated to deal with the case where
;; strings are muted and don't count towards the
;; strum-time.
;; ex: (0 0 1 2 3 4)
fret-times (map first
(rest (reductions
#(vector (if (>= (second %1) 0)
(inc (first %1))
(first %1))
%2)
[0 -1]
chord-frets)))]
(dotimes [i num-strings]
(let [j (if (= direction :up) (- num-strings 1 i) i)
max-t (apply max fret-times)
dt (if (> max-t 0)
(* 1000 (/ strum-time max-t))
0)
fret-delta (if (= direction :up)
(- max-t (nth fret-times j))
(nth fret-times i))]
(pick-string the-strings the-inst j
(nth chord-frets j)
(+ t (* fret-delta dt)))))))
([chord-fret-map the-strings the-inst the-chord direction strum-time]
(strum-strings chord-fret-map the-strings the-inst the-chord
direction strum-time (now+)))
([chord-fret-map the-strings the-inst the-chord direction]
(strum-strings chord-fret-map the-strings the-inst the-chord
direction 0.05 (now+)))
([chord-fret-map the-strings the-inst the-chord]
(strum-strings chord-fret-map the-strings the-inst the-chord
:down 0.05 (now+))))
;; ======================================================================
;; The Guitar Instrument Code
;; ======================================================================
;; A map of chords to frets held for that chord. This is not all
;; possible guitar chords, just some of them as there are many
;; alternatives to choose from. Add more as you find/need them.
;;
;; You can pass in your own arrays to strum, too. The values are the
;; fret number of the string to press. This selects the note to play.
;; -1 indicates you mute that string
;; -2 indicates you leave that string alone & keep the current state
;; of either playing or not
;;
(def guitar-chord-frets
{:A [ -1 0 2 2 2 0 ]
:A7 [ -1 0 2 0 2 0 ]
:A9 [ 0 0 2 4 2 3 ]
:Am [ 0 0 2 2 1 0 ]
:Am7 [ 0 0 2 0 1 0 ]
:Bb [ -1 1 3 3 3 1 ]
:Bb7 [ -1 -1 3 3 3 4 ]
:Bb9 [ -1 -1 0 1 1 1 ]
:Bbm [ -1 -1 3 3 2 1 ]
:Bbm7 [ 1 1 3 1 2 1 ]
:B [ -1 -1 4 4 4 2 ]
:B7 [ -1 2 1 2 0 2 ]
:B9 [ 2 -1 1 2 2 2 ]
:Bm [ -1 -1 4 4 3 2 ]
:Bm7 [ -1 2 0 2 0 2 ]
:C [ -1 3 2 0 1 0 ]
:C7 [ -1 3 2 3 1 0 ]
:C9 [ 3 3 2 3 3 3 ]
:Cm [ 3 3 5 5 4 3 ]
:Cm7 [ 3 3 5 3 4 3 ]
:Db [ -1 -1 3 1 2 1 ]
:Db7 [ -1 -1 3 4 2 4 ]
:Db9 [ 4 -1 3 4 4 4 ]
:Dbm [ -1 -1 2 1 2 0 ]
:Dbm7 [ -1 3 2 1 0 0 ]
:D [ -1 -1 0 2 3 2 ]
:D7 [ -1 -1 0 2 1 2 ]
:D9 [ -1 -1 4 2 1 0 ]
:Dm [ -1 0 0 2 3 1 ]
:Dm7 [ -1 -1 0 2 1 1 ]
:Eb [ -1 -1 5 3 4 3 ]
:Eb7 [ -1 -1 1 3 2 3 ]
:Eb9 [ -1 -1 1 0 2 1 ]
:Ebm [ -1 -1 4 3 4 2 ]
:Ebm7 [ -1 -1 1 3 2 2 ]
:E [ 0 2 2 1 0 0 ]
:E7 [ 0 2 0 1 0 0 ]
:E9 [ 0 2 0 1 3 2 ]
:Em [ 0 2 2 0 0 0 ]
:Em7 [ 0 2 2 0 3 0 ]
:F [ 1 3 3 2 1 1 ]
:F7 [ 1 -1 2 2 1 -1 ]
:F9 [ 1 0 3 0 1 -1 ]
:Fm [ 1 3 3 1 1 1 ]
:Fm7 [ 1 3 3 1 4 1 ]
:Gb [ 2 4 4 3 2 2 ]
:Gb7 [ -1 -1 4 3 2 1 ]
:Gb9 [ -1 4 -1 3 5 4 ]
:Gbm [ 2 4 4 2 2 2 ]
:Gbm7 [ 2 -1 2 2 2 -1 ]
:G [ 3 2 0 0 0 3 ]
:G7 [ 3 2 0 0 0 1 ]
:G9 [ -1 -1 0 2 0 1 ]
:Gm [ -1 -1 5 3 3 3 ]
:Gm7 [ -1 1 3 0 3 -1 ]
:Ab [ -1 -1 6 5 4 4 ]
:Ab7 [ -1 -1 1 1 1 2 ]
:Ab9 [ -1 -1 1 3 1 2 ]
:Abm [ -1 -1 6 4 4 4 ]
:Abm7 [ -1 -1 4 4 7 4 ]
:Gadd5 [ 3 2 0 0 3 3 ]
:Cadd9 [ -1 3 2 0 3 3 ]
:Dsus4 [ -1 -1 0 2 3 3 ]
})
;; ======================================================================
;; an array of 6 guitar strings: EADGBE
(def guitar-string-notes (map note [:e2 :a2 :d3 :g3 :b3 :e4]))
;; ======================================================================
;; Main helper functions. Use pick or strum to play the instrument.
(def guitar-pick (partial pick-string guitar-string-notes))
(def guitar-strum (partial strum-strings guitar-chord-frets guitar-string-notes))
;; ======================================================================
;; Create the guitar defsynth. Note that it is persistent and will
;; not be freed when any string goes silent.
(gen-stringed-synth guitar 6 false)
;; ======================================================================
;; Ektara - a single-string synth. Mainly for use with the midi-poly-player.
;;
;; Since "string" was too generic a name, I asked the google for some
;; help. Wikipedia tells me that there is a single-stringed
;; instrument called the "Ektara", so that is where the name comes
;; from.
;;
;; For use with midi-poly-player, we need to make the default gate 1.
;; Example:
;; (def mpp (midi-poly-player (partial ektara :gate 1)))
;;
;; Note that it is transient and will be freed when the string goes
;; silent.
;;
(gen-stringed-synth ektara 1 true)
| 106606 | ;; A Stringed Synth Generator Macro & Guitar Example Instrument
;;
;; See overtone/examples/instruments/guitar_synth.clj for example usage.
;;
;; Other instruments (like bass-guitar, ukelele, mandolin, etc.) may
;; use the same basic instrument. Watch this space...
(ns overtone.synth.stringed
^{:doc "A Stringed Synth Generator Macro & Guitar Instrument"
:author "<NAME>"}
(:use [overtone.music pitch time]
[overtone.sc envelope node server synth ugens]
[overtone.sc.cgens mix]))
;; ======================================================================
(defmacro gen-stringed-synth
"Macro to generate a stringed defsynth with distortion, reverb and
a low-pass filter. Use the pluck-strings and strum-strings helper
functions to play the instrument.
Note: the strings need to be silenced with a gate -> 0 transition
before a gate -> 1 transition activates it. Testing
showed it needed > 25 ms between these transitions to be effective."
[name num-strings free-on-silence]
(let [note-ins (if (= num-strings 1)
[(symbol "note")]
(apply vector
(map #(symbol (format "note-%d" %)) (range num-strings))))
note-default-ins (apply vector
(flatten (map vector
note-ins
(repeat num-strings {:default 60 :min 0 :max 127}))))
gate-ins (if (= num-strings 1)
[(symbol "gate")]
(apply vector
(map #(symbol (format "gate-%d" %)) (range num-strings))))
gate-default-ins (apply vector (flatten (map vector
gate-ins
(repeat num-strings {:default 0}))))
both-default-ins (into note-default-ins gate-default-ins)
note-gate-pairs (apply vector (map vector note-ins gate-ins))
env-gen-fn (if free-on-silence
'(fn [x] (overtone.sc.ugens/env-gen
(overtone.sc.envelope/asr 0.0001 1 0.1)
:gate (second x)
:action overtone.sc.ugens/FREE))
'(fn [x] (overtone.sc.ugens/env-gen
(overtone.sc.envelope/asr 0.0001 1 0.1)
:gate (second x))))
]
`(defsynth ~name
~(str "a stringed instrument synth with " num-strings
" strings mixed and sent thru
distortion and reverb effects followed by a low-pass filter. Use
the pluck-strings and strum-strings helper functions to play the
instrument. Note: the strings need to be silenced with a gate -> 0
transition before a gate -> 1 transition activates it."
(if free-on-silence
" This instrument
is transient. When a string becomes silent, it will be freed."
" This instrument
is persistent. It will not be freed when the strings go silent."))
[~@both-default-ins
~'dur {:default 10.0 :min 1.0 :max 100.0}
~'decay {:default 30 :min 1 :max 100} ;; pluck decay
~'coef {:default 0.3 :min -1 :max 1} ;; pluck coef
~'noise-amp {:default 0.8 :min 0.0 :max 1.0}
~'pre-amp {:default 6.0 :min 0.0 :max 10.0}
~'amp {:default 1.0 :min 0.0 :max 10.0}
;; by default, no distortion, no reverb, no low-pass
~'distort {:default 0.0 :min 0.0 :max 0.9999999999}
~'rvb-mix {:default 0.0 :min 0.0 :max 1.0}
~'rvb-room {:default 0.0 :min 0.0 :max 1.0}
~'rvb-damp {:default 0.0 :min 0.0 :max 1.0}
~'lp-freq {:default 20000 :min 100 :max 20000}
~'lp-rq {:default 1.0 :min 0.1 :max 10.0}
~'pan {:default 0.0 :min -1 :max 1}
~'out-bus {:default 0 :min 0 :max 100}]
(let [strings# (map #(let [frq# (midicps (first %))
nze# (~'* ~'noise-amp (pink-noise))
plk# (pluck nze#
(second %)
(/ 1.0 8.0)
(~'/ 1.0 frq#)
~'decay
~'coef)]
(leak-dc (~'* plk# (~env-gen-fn %))
0.995))
~note-gate-pairs)
src# (~'* ~'pre-amp (mix strings#))
;; distortion from fx-distortion2
k# (~'/ (~'* 2 ~'distort) (~'- 1 ~'distort))
dis# (~'/ (~'* src# (~'+ 1 k#))
(~'+ 1 (~'* k# (abs src#))))
vrb# (free-verb dis# ~'rvb-mix ~'rvb-room ~'rvb-damp)
fil# (rlpf vrb# ~'lp-freq ~'lp-rq)]
(out ~'out-bus (pan2 (~'* ~'amp fil#) ~'pan))))))
;;(macroexpand-1 '(gen-stringed-synth ektara 1 true))
;; ======================================================================
;; common routines for stringed instruments
(defn- fret-to-note
"given a fret-offset, add to the base note index with special
handling for -1"
[base-note offset]
(if (>= offset 0)
(+ base-note offset)
offset))
(defn- mkarg
"useful for making arguments for the instruments strings"
[s i]
(keyword (format "%s-%d" s i)))
(defn- now+
"add an epsilon of time to (now) to avoid lots of 'late' error messages"
[]
(+ (now) 21)) ;; 21ms seems to get rid of most for me.
;; ======================================================================
;; Main helper functions used to play the instrument: pick or strum
(defn pick-string
"pick the instrument's string depending on the fret selected. A
fret value less than -1 will cause no event; -1 or greater causes
the previous note to be silenced; 0 or greater will also cause a
new note event."
([the-strings the-inst string-index fret t]
(let [the-note (fret-to-note (nth the-strings string-index) fret)]
;; turn off the previous note
(if (>= the-note -1)
(at t (ctl the-inst (mkarg "gate" string-index) 0)))
;; NOTE: there needs to be some time between these
;; FIXME: +50 seems conservative. Find minimum.
(if (>= the-note 0)
(at (+ t 50) (ctl the-inst
(mkarg "note" string-index) the-note
(mkarg "gate" string-index) 1)))))
([the-chord-frets the-inst string-index fret]
(pick-string the-chord-frets the-inst string-index fret (now+))))
;; ======================================================================
(defn strum-strings
"strum a chord on the instrument in a direction (:up or :down) with
a strum duration of strum-time at t. If the-chord is a vector, use
it directly for fret indexes."
([chord-fret-map the-strings the-inst the-chord direction strum-time t]
(let [num-strings (count (chord-fret-map :A))
;; ex: [-1 3 2 0 1 0]
chord-frets (if (vector? the-chord)
;; treat the-chord as a series of frets
;; and gracefully handle odd sized vectors
(vec (take num-strings
(into the-chord
(vec (repeat num-strings -1)))))
;; else use the-chord as an index
(chord-fret-map the-chord))
;; account for unplayed strings for delta time calc. Code
;; gets a bit complicated to deal with the case where
;; strings are muted and don't count towards the
;; strum-time.
;; ex: (0 0 1 2 3 4)
fret-times (map first
(rest (reductions
#(vector (if (>= (second %1) 0)
(inc (first %1))
(first %1))
%2)
[0 -1]
chord-frets)))]
(dotimes [i num-strings]
(let [j (if (= direction :up) (- num-strings 1 i) i)
max-t (apply max fret-times)
dt (if (> max-t 0)
(* 1000 (/ strum-time max-t))
0)
fret-delta (if (= direction :up)
(- max-t (nth fret-times j))
(nth fret-times i))]
(pick-string the-strings the-inst j
(nth chord-frets j)
(+ t (* fret-delta dt)))))))
([chord-fret-map the-strings the-inst the-chord direction strum-time]
(strum-strings chord-fret-map the-strings the-inst the-chord
direction strum-time (now+)))
([chord-fret-map the-strings the-inst the-chord direction]
(strum-strings chord-fret-map the-strings the-inst the-chord
direction 0.05 (now+)))
([chord-fret-map the-strings the-inst the-chord]
(strum-strings chord-fret-map the-strings the-inst the-chord
:down 0.05 (now+))))
;; ======================================================================
;; The Guitar Instrument Code
;; ======================================================================
;; A map of chords to frets held for that chord. This is not all
;; possible guitar chords, just some of them as there are many
;; alternatives to choose from. Add more as you find/need them.
;;
;; You can pass in your own arrays to strum, too. The values are the
;; fret number of the string to press. This selects the note to play.
;; -1 indicates you mute that string
;; -2 indicates you leave that string alone & keep the current state
;; of either playing or not
;;
(def guitar-chord-frets
{:A [ -1 0 2 2 2 0 ]
:A7 [ -1 0 2 0 2 0 ]
:A9 [ 0 0 2 4 2 3 ]
:Am [ 0 0 2 2 1 0 ]
:Am7 [ 0 0 2 0 1 0 ]
:Bb [ -1 1 3 3 3 1 ]
:Bb7 [ -1 -1 3 3 3 4 ]
:Bb9 [ -1 -1 0 1 1 1 ]
:Bbm [ -1 -1 3 3 2 1 ]
:Bbm7 [ 1 1 3 1 2 1 ]
:B [ -1 -1 4 4 4 2 ]
:B7 [ -1 2 1 2 0 2 ]
:B9 [ 2 -1 1 2 2 2 ]
:Bm [ -1 -1 4 4 3 2 ]
:Bm7 [ -1 2 0 2 0 2 ]
:C [ -1 3 2 0 1 0 ]
:C7 [ -1 3 2 3 1 0 ]
:C9 [ 3 3 2 3 3 3 ]
:Cm [ 3 3 5 5 4 3 ]
:Cm7 [ 3 3 5 3 4 3 ]
:Db [ -1 -1 3 1 2 1 ]
:Db7 [ -1 -1 3 4 2 4 ]
:Db9 [ 4 -1 3 4 4 4 ]
:Dbm [ -1 -1 2 1 2 0 ]
:Dbm7 [ -1 3 2 1 0 0 ]
:D [ -1 -1 0 2 3 2 ]
:D7 [ -1 -1 0 2 1 2 ]
:D9 [ -1 -1 4 2 1 0 ]
:Dm [ -1 0 0 2 3 1 ]
:Dm7 [ -1 -1 0 2 1 1 ]
:Eb [ -1 -1 5 3 4 3 ]
:Eb7 [ -1 -1 1 3 2 3 ]
:Eb9 [ -1 -1 1 0 2 1 ]
:Ebm [ -1 -1 4 3 4 2 ]
:Ebm7 [ -1 -1 1 3 2 2 ]
:E [ 0 2 2 1 0 0 ]
:E7 [ 0 2 0 1 0 0 ]
:E9 [ 0 2 0 1 3 2 ]
:Em [ 0 2 2 0 0 0 ]
:Em7 [ 0 2 2 0 3 0 ]
:F [ 1 3 3 2 1 1 ]
:F7 [ 1 -1 2 2 1 -1 ]
:F9 [ 1 0 3 0 1 -1 ]
:Fm [ 1 3 3 1 1 1 ]
:Fm7 [ 1 3 3 1 4 1 ]
:Gb [ 2 4 4 3 2 2 ]
:Gb7 [ -1 -1 4 3 2 1 ]
:Gb9 [ -1 4 -1 3 5 4 ]
:Gbm [ 2 4 4 2 2 2 ]
:Gbm7 [ 2 -1 2 2 2 -1 ]
:G [ 3 2 0 0 0 3 ]
:G7 [ 3 2 0 0 0 1 ]
:G9 [ -1 -1 0 2 0 1 ]
:Gm [ -1 -1 5 3 3 3 ]
:Gm7 [ -1 1 3 0 3 -1 ]
:Ab [ -1 -1 6 5 4 4 ]
:Ab7 [ -1 -1 1 1 1 2 ]
:Ab9 [ -1 -1 1 3 1 2 ]
:Abm [ -1 -1 6 4 4 4 ]
:Abm7 [ -1 -1 4 4 7 4 ]
:Gadd5 [ 3 2 0 0 3 3 ]
:Cadd9 [ -1 3 2 0 3 3 ]
:Dsus4 [ -1 -1 0 2 3 3 ]
})
;; ======================================================================
;; an array of 6 guitar strings: EADGBE
(def guitar-string-notes (map note [:e2 :a2 :d3 :g3 :b3 :e4]))
;; ======================================================================
;; Main helper functions. Use pick or strum to play the instrument.
(def guitar-pick (partial pick-string guitar-string-notes))
(def guitar-strum (partial strum-strings guitar-chord-frets guitar-string-notes))
;; ======================================================================
;; Create the guitar defsynth. Note that it is persistent and will
;; not be freed when any string goes silent.
(gen-stringed-synth guitar 6 false)
;; ======================================================================
;; Ektara - a single-string synth. Mainly for use with the midi-poly-player.
;;
;; Since "string" was too generic a name, I asked the google for some
;; help. Wikipedia tells me that there is a single-stringed
;; instrument called the "Ektara", so that is where the name comes
;; from.
;;
;; For use with midi-poly-player, we need to make the default gate 1.
;; Example:
;; (def mpp (midi-poly-player (partial ektara :gate 1)))
;;
;; Note that it is transient and will be freed when the string goes
;; silent.
;;
(gen-stringed-synth ektara 1 true)
| true | ;; A Stringed Synth Generator Macro & Guitar Example Instrument
;;
;; See overtone/examples/instruments/guitar_synth.clj for example usage.
;;
;; Other instruments (like bass-guitar, ukelele, mandolin, etc.) may
;; use the same basic instrument. Watch this space...
(ns overtone.synth.stringed
^{:doc "A Stringed Synth Generator Macro & Guitar Instrument"
:author "PI:NAME:<NAME>END_PI"}
(:use [overtone.music pitch time]
[overtone.sc envelope node server synth ugens]
[overtone.sc.cgens mix]))
;; ======================================================================
(defmacro gen-stringed-synth
"Macro to generate a stringed defsynth with distortion, reverb and
a low-pass filter. Use the pluck-strings and strum-strings helper
functions to play the instrument.
Note: the strings need to be silenced with a gate -> 0 transition
before a gate -> 1 transition activates it. Testing
showed it needed > 25 ms between these transitions to be effective."
[name num-strings free-on-silence]
(let [note-ins (if (= num-strings 1)
[(symbol "note")]
(apply vector
(map #(symbol (format "note-%d" %)) (range num-strings))))
note-default-ins (apply vector
(flatten (map vector
note-ins
(repeat num-strings {:default 60 :min 0 :max 127}))))
gate-ins (if (= num-strings 1)
[(symbol "gate")]
(apply vector
(map #(symbol (format "gate-%d" %)) (range num-strings))))
gate-default-ins (apply vector (flatten (map vector
gate-ins
(repeat num-strings {:default 0}))))
both-default-ins (into note-default-ins gate-default-ins)
note-gate-pairs (apply vector (map vector note-ins gate-ins))
env-gen-fn (if free-on-silence
'(fn [x] (overtone.sc.ugens/env-gen
(overtone.sc.envelope/asr 0.0001 1 0.1)
:gate (second x)
:action overtone.sc.ugens/FREE))
'(fn [x] (overtone.sc.ugens/env-gen
(overtone.sc.envelope/asr 0.0001 1 0.1)
:gate (second x))))
]
`(defsynth ~name
~(str "a stringed instrument synth with " num-strings
" strings mixed and sent thru
distortion and reverb effects followed by a low-pass filter. Use
the pluck-strings and strum-strings helper functions to play the
instrument. Note: the strings need to be silenced with a gate -> 0
transition before a gate -> 1 transition activates it."
(if free-on-silence
" This instrument
is transient. When a string becomes silent, it will be freed."
" This instrument
is persistent. It will not be freed when the strings go silent."))
[~@both-default-ins
~'dur {:default 10.0 :min 1.0 :max 100.0}
~'decay {:default 30 :min 1 :max 100} ;; pluck decay
~'coef {:default 0.3 :min -1 :max 1} ;; pluck coef
~'noise-amp {:default 0.8 :min 0.0 :max 1.0}
~'pre-amp {:default 6.0 :min 0.0 :max 10.0}
~'amp {:default 1.0 :min 0.0 :max 10.0}
;; by default, no distortion, no reverb, no low-pass
~'distort {:default 0.0 :min 0.0 :max 0.9999999999}
~'rvb-mix {:default 0.0 :min 0.0 :max 1.0}
~'rvb-room {:default 0.0 :min 0.0 :max 1.0}
~'rvb-damp {:default 0.0 :min 0.0 :max 1.0}
~'lp-freq {:default 20000 :min 100 :max 20000}
~'lp-rq {:default 1.0 :min 0.1 :max 10.0}
~'pan {:default 0.0 :min -1 :max 1}
~'out-bus {:default 0 :min 0 :max 100}]
(let [strings# (map #(let [frq# (midicps (first %))
nze# (~'* ~'noise-amp (pink-noise))
plk# (pluck nze#
(second %)
(/ 1.0 8.0)
(~'/ 1.0 frq#)
~'decay
~'coef)]
(leak-dc (~'* plk# (~env-gen-fn %))
0.995))
~note-gate-pairs)
src# (~'* ~'pre-amp (mix strings#))
;; distortion from fx-distortion2
k# (~'/ (~'* 2 ~'distort) (~'- 1 ~'distort))
dis# (~'/ (~'* src# (~'+ 1 k#))
(~'+ 1 (~'* k# (abs src#))))
vrb# (free-verb dis# ~'rvb-mix ~'rvb-room ~'rvb-damp)
fil# (rlpf vrb# ~'lp-freq ~'lp-rq)]
(out ~'out-bus (pan2 (~'* ~'amp fil#) ~'pan))))))
;;(macroexpand-1 '(gen-stringed-synth ektara 1 true))
;; ======================================================================
;; common routines for stringed instruments
(defn- fret-to-note
"given a fret-offset, add to the base note index with special
handling for -1"
[base-note offset]
(if (>= offset 0)
(+ base-note offset)
offset))
(defn- mkarg
"useful for making arguments for the instruments strings"
[s i]
(keyword (format "%s-%d" s i)))
(defn- now+
"add an epsilon of time to (now) to avoid lots of 'late' error messages"
[]
(+ (now) 21)) ;; 21ms seems to get rid of most for me.
;; ======================================================================
;; Main helper functions used to play the instrument: pick or strum
(defn pick-string
"pick the instrument's string depending on the fret selected. A
fret value less than -1 will cause no event; -1 or greater causes
the previous note to be silenced; 0 or greater will also cause a
new note event."
([the-strings the-inst string-index fret t]
(let [the-note (fret-to-note (nth the-strings string-index) fret)]
;; turn off the previous note
(if (>= the-note -1)
(at t (ctl the-inst (mkarg "gate" string-index) 0)))
;; NOTE: there needs to be some time between these
;; FIXME: +50 seems conservative. Find minimum.
(if (>= the-note 0)
(at (+ t 50) (ctl the-inst
(mkarg "note" string-index) the-note
(mkarg "gate" string-index) 1)))))
([the-chord-frets the-inst string-index fret]
(pick-string the-chord-frets the-inst string-index fret (now+))))
;; ======================================================================
(defn strum-strings
"strum a chord on the instrument in a direction (:up or :down) with
a strum duration of strum-time at t. If the-chord is a vector, use
it directly for fret indexes."
([chord-fret-map the-strings the-inst the-chord direction strum-time t]
(let [num-strings (count (chord-fret-map :A))
;; ex: [-1 3 2 0 1 0]
chord-frets (if (vector? the-chord)
;; treat the-chord as a series of frets
;; and gracefully handle odd sized vectors
(vec (take num-strings
(into the-chord
(vec (repeat num-strings -1)))))
;; else use the-chord as an index
(chord-fret-map the-chord))
;; account for unplayed strings for delta time calc. Code
;; gets a bit complicated to deal with the case where
;; strings are muted and don't count towards the
;; strum-time.
;; ex: (0 0 1 2 3 4)
fret-times (map first
(rest (reductions
#(vector (if (>= (second %1) 0)
(inc (first %1))
(first %1))
%2)
[0 -1]
chord-frets)))]
(dotimes [i num-strings]
(let [j (if (= direction :up) (- num-strings 1 i) i)
max-t (apply max fret-times)
dt (if (> max-t 0)
(* 1000 (/ strum-time max-t))
0)
fret-delta (if (= direction :up)
(- max-t (nth fret-times j))
(nth fret-times i))]
(pick-string the-strings the-inst j
(nth chord-frets j)
(+ t (* fret-delta dt)))))))
([chord-fret-map the-strings the-inst the-chord direction strum-time]
(strum-strings chord-fret-map the-strings the-inst the-chord
direction strum-time (now+)))
([chord-fret-map the-strings the-inst the-chord direction]
(strum-strings chord-fret-map the-strings the-inst the-chord
direction 0.05 (now+)))
([chord-fret-map the-strings the-inst the-chord]
(strum-strings chord-fret-map the-strings the-inst the-chord
:down 0.05 (now+))))
;; ======================================================================
;; The Guitar Instrument Code
;; ======================================================================
;; A map of chords to frets held for that chord. This is not all
;; possible guitar chords, just some of them as there are many
;; alternatives to choose from. Add more as you find/need them.
;;
;; You can pass in your own arrays to strum, too. The values are the
;; fret number of the string to press. This selects the note to play.
;; -1 indicates you mute that string
;; -2 indicates you leave that string alone & keep the current state
;; of either playing or not
;;
(def guitar-chord-frets
{:A [ -1 0 2 2 2 0 ]
:A7 [ -1 0 2 0 2 0 ]
:A9 [ 0 0 2 4 2 3 ]
:Am [ 0 0 2 2 1 0 ]
:Am7 [ 0 0 2 0 1 0 ]
:Bb [ -1 1 3 3 3 1 ]
:Bb7 [ -1 -1 3 3 3 4 ]
:Bb9 [ -1 -1 0 1 1 1 ]
:Bbm [ -1 -1 3 3 2 1 ]
:Bbm7 [ 1 1 3 1 2 1 ]
:B [ -1 -1 4 4 4 2 ]
:B7 [ -1 2 1 2 0 2 ]
:B9 [ 2 -1 1 2 2 2 ]
:Bm [ -1 -1 4 4 3 2 ]
:Bm7 [ -1 2 0 2 0 2 ]
:C [ -1 3 2 0 1 0 ]
:C7 [ -1 3 2 3 1 0 ]
:C9 [ 3 3 2 3 3 3 ]
:Cm [ 3 3 5 5 4 3 ]
:Cm7 [ 3 3 5 3 4 3 ]
:Db [ -1 -1 3 1 2 1 ]
:Db7 [ -1 -1 3 4 2 4 ]
:Db9 [ 4 -1 3 4 4 4 ]
:Dbm [ -1 -1 2 1 2 0 ]
:Dbm7 [ -1 3 2 1 0 0 ]
:D [ -1 -1 0 2 3 2 ]
:D7 [ -1 -1 0 2 1 2 ]
:D9 [ -1 -1 4 2 1 0 ]
:Dm [ -1 0 0 2 3 1 ]
:Dm7 [ -1 -1 0 2 1 1 ]
:Eb [ -1 -1 5 3 4 3 ]
:Eb7 [ -1 -1 1 3 2 3 ]
:Eb9 [ -1 -1 1 0 2 1 ]
:Ebm [ -1 -1 4 3 4 2 ]
:Ebm7 [ -1 -1 1 3 2 2 ]
:E [ 0 2 2 1 0 0 ]
:E7 [ 0 2 0 1 0 0 ]
:E9 [ 0 2 0 1 3 2 ]
:Em [ 0 2 2 0 0 0 ]
:Em7 [ 0 2 2 0 3 0 ]
:F [ 1 3 3 2 1 1 ]
:F7 [ 1 -1 2 2 1 -1 ]
:F9 [ 1 0 3 0 1 -1 ]
:Fm [ 1 3 3 1 1 1 ]
:Fm7 [ 1 3 3 1 4 1 ]
:Gb [ 2 4 4 3 2 2 ]
:Gb7 [ -1 -1 4 3 2 1 ]
:Gb9 [ -1 4 -1 3 5 4 ]
:Gbm [ 2 4 4 2 2 2 ]
:Gbm7 [ 2 -1 2 2 2 -1 ]
:G [ 3 2 0 0 0 3 ]
:G7 [ 3 2 0 0 0 1 ]
:G9 [ -1 -1 0 2 0 1 ]
:Gm [ -1 -1 5 3 3 3 ]
:Gm7 [ -1 1 3 0 3 -1 ]
:Ab [ -1 -1 6 5 4 4 ]
:Ab7 [ -1 -1 1 1 1 2 ]
:Ab9 [ -1 -1 1 3 1 2 ]
:Abm [ -1 -1 6 4 4 4 ]
:Abm7 [ -1 -1 4 4 7 4 ]
:Gadd5 [ 3 2 0 0 3 3 ]
:Cadd9 [ -1 3 2 0 3 3 ]
:Dsus4 [ -1 -1 0 2 3 3 ]
})
;; ======================================================================
;; an array of 6 guitar strings: EADGBE
(def guitar-string-notes (map note [:e2 :a2 :d3 :g3 :b3 :e4]))
;; ======================================================================
;; Main helper functions. Use pick or strum to play the instrument.
(def guitar-pick (partial pick-string guitar-string-notes))
(def guitar-strum (partial strum-strings guitar-chord-frets guitar-string-notes))
;; ======================================================================
;; Create the guitar defsynth. Note that it is persistent and will
;; not be freed when any string goes silent.
(gen-stringed-synth guitar 6 false)
;; ======================================================================
;; Ektara - a single-string synth. Mainly for use with the midi-poly-player.
;;
;; Since "string" was too generic a name, I asked the google for some
;; help. Wikipedia tells me that there is a single-stringed
;; instrument called the "Ektara", so that is where the name comes
;; from.
;;
;; For use with midi-poly-player, we need to make the default gate 1.
;; Example:
;; (def mpp (midi-poly-player (partial ektara :gate 1)))
;;
;; Note that it is transient and will be freed when the string goes
;; silent.
;;
(gen-stringed-synth ektara 1 true)
|
[
{
"context": "\"Hello world for neanderthal/nvidia.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-04-24\"\n :version \"2017-05-29\"}",
"end": 293,
"score": 0.9698846340179443,
"start": 257,
"tag": "EMAIL",
"value": "palisades dot lakes at gmail dot com"
}
] | src/scripts/clojure/palisades/lakes/elements/scripts/uncomplicate/nvidia.clj | palisades-lakes/les-elemens | 0 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.elements.scripts.uncomplicate.nvidia
{:doc "Hello world for neanderthal/nvidia."
:author "palisades dot lakes at gmail dot com"
:since "2017-04-24"
:version "2017-05-29"}
(:require [clojure.pprint :as pp]
[palisades.lakes.elements.scripts.defs :as defs]))
;;----------------------------------------------------------------
(set! *warn-on-reflection* false) ;
(set! *unchecked-math* false)
(require '[uncomplicate.commons.core :as ucc])
(require '[uncomplicate.clojurecl
[core :as ucl2c]
[info :as ucl2i]
[legacy :as ucl2l]])
(require '[uncomplicate.neanderthal
[core :as unc]
[native :as unn]
[opencl :as uno]])
(require '[criterium.core :as criterium])
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(def u (into [] (defs/uniform-doubles (* 32 1024 1024))))
;;----------------------------------------------------------------
#_(println :default (count u))
#_(ucl2c/with-default
(uno/with-default-engine
(ucc/with-release [x (uno/clv u)]
(pp/pprint
(defs/simplify
(time
(criterium/benchmark (unc/sum x) {})))))))
;;----------------------------------------------------------------
(println :default-1 (count u))
(ucl2l/with-default-1
(uno/with-default-engine
(ucc/with-release [x (uno/clv u)]
(pp/pprint
(defs/simplify
(time
(criterium/benchmark (unc/sum x) {})))))))
;;----------------------------------------------------------------
(println :platform (count u))
(ucl2c/with-platform (first (ucl2c/platforms))
(let [dev (first (ucl2c/sort-by-cl-version (ucl2c/devices :gpu)))]
(ucl2c/with-context (ucl2c/context [dev])
(ucl2c/with-queue (ucl2l/command-queue-1 dev)
(uno/with-default-engine
(ucc/with-release [x (uno/clv u)]
(pp/pprint
(defs/simplify
(time
(criterium/benchmark (unc/sum x) {}))))))))))
;;----------------------------------------------------------------
| 72608 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.elements.scripts.uncomplicate.nvidia
{:doc "Hello world for neanderthal/nvidia."
:author "<EMAIL>"
:since "2017-04-24"
:version "2017-05-29"}
(:require [clojure.pprint :as pp]
[palisades.lakes.elements.scripts.defs :as defs]))
;;----------------------------------------------------------------
(set! *warn-on-reflection* false) ;
(set! *unchecked-math* false)
(require '[uncomplicate.commons.core :as ucc])
(require '[uncomplicate.clojurecl
[core :as ucl2c]
[info :as ucl2i]
[legacy :as ucl2l]])
(require '[uncomplicate.neanderthal
[core :as unc]
[native :as unn]
[opencl :as uno]])
(require '[criterium.core :as criterium])
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(def u (into [] (defs/uniform-doubles (* 32 1024 1024))))
;;----------------------------------------------------------------
#_(println :default (count u))
#_(ucl2c/with-default
(uno/with-default-engine
(ucc/with-release [x (uno/clv u)]
(pp/pprint
(defs/simplify
(time
(criterium/benchmark (unc/sum x) {})))))))
;;----------------------------------------------------------------
(println :default-1 (count u))
(ucl2l/with-default-1
(uno/with-default-engine
(ucc/with-release [x (uno/clv u)]
(pp/pprint
(defs/simplify
(time
(criterium/benchmark (unc/sum x) {})))))))
;;----------------------------------------------------------------
(println :platform (count u))
(ucl2c/with-platform (first (ucl2c/platforms))
(let [dev (first (ucl2c/sort-by-cl-version (ucl2c/devices :gpu)))]
(ucl2c/with-context (ucl2c/context [dev])
(ucl2c/with-queue (ucl2l/command-queue-1 dev)
(uno/with-default-engine
(ucc/with-release [x (uno/clv u)]
(pp/pprint
(defs/simplify
(time
(criterium/benchmark (unc/sum x) {}))))))))))
;;----------------------------------------------------------------
| true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.elements.scripts.uncomplicate.nvidia
{:doc "Hello world for neanderthal/nvidia."
:author "PI:EMAIL:<EMAIL>END_PI"
:since "2017-04-24"
:version "2017-05-29"}
(:require [clojure.pprint :as pp]
[palisades.lakes.elements.scripts.defs :as defs]))
;;----------------------------------------------------------------
(set! *warn-on-reflection* false) ;
(set! *unchecked-math* false)
(require '[uncomplicate.commons.core :as ucc])
(require '[uncomplicate.clojurecl
[core :as ucl2c]
[info :as ucl2i]
[legacy :as ucl2l]])
(require '[uncomplicate.neanderthal
[core :as unc]
[native :as unn]
[opencl :as uno]])
(require '[criterium.core :as criterium])
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(def u (into [] (defs/uniform-doubles (* 32 1024 1024))))
;;----------------------------------------------------------------
#_(println :default (count u))
#_(ucl2c/with-default
(uno/with-default-engine
(ucc/with-release [x (uno/clv u)]
(pp/pprint
(defs/simplify
(time
(criterium/benchmark (unc/sum x) {})))))))
;;----------------------------------------------------------------
(println :default-1 (count u))
(ucl2l/with-default-1
(uno/with-default-engine
(ucc/with-release [x (uno/clv u)]
(pp/pprint
(defs/simplify
(time
(criterium/benchmark (unc/sum x) {})))))))
;;----------------------------------------------------------------
(println :platform (count u))
(ucl2c/with-platform (first (ucl2c/platforms))
(let [dev (first (ucl2c/sort-by-cl-version (ucl2c/devices :gpu)))]
(ucl2c/with-context (ucl2c/context [dev])
(ucl2c/with-queue (ucl2l/command-queue-1 dev)
(uno/with-default-engine
(ucc/with-release [x (uno/clv u)]
(pp/pprint
(defs/simplify
(time
(criterium/benchmark (unc/sum x) {}))))))))))
;;----------------------------------------------------------------
|
[
{
"context": "; Copyright (c) 2017-present Walmart, Inc.\n;\n; Licensed under the Apache License",
"end": 30,
"score": 0.6211073398590088,
"start": 29,
"tag": "NAME",
"value": "W"
}
] | test/com/walmartlabs/lacinia/schema_test.clj | hagenek/lacinia | 1,762 | ; Copyright (c) 2017-present Walmart, Inc.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns com.walmartlabs.lacinia.schema-test
"Tests schema functions."
(:require
[clojure.test :refer [deftest testing is are try-expr do-report]]
[com.walmartlabs.test-reporting :refer [reporting]]
[clojure.spec.alpha :as s]
[com.walmartlabs.lacinia.schema :as schema]
[com.walmartlabs.lacinia.executor :as executor]
[com.walmartlabs.lacinia.util :as util]
[com.walmartlabs.test-utils :refer [is-thrown expect-exception execute]]
[clojure.string :as str]
[clojure.pprint :as pprint]))
(defmacro is-error?
[form]
`(let [tuple# (try-expr "Invoking enforcer." ~form)]
(when-not (-> tuple# second some?)
(do-report {:type :fail
:message "Expected some errors in the resolved tuple"}))))
(deftest schema-shape
(testing "schema with not required field"
(let [s {:objects
{:person
{:fields {:foo {:type 'String}}
:bar "I'm extra"}}}]
(is (seq (schema/compile s))
"should compile schema without any problems"))))
(def schema-object-references-unknown-interface
{:interfaces
{:fred
{}
:barney
{}}
:objects
{:dino
{:implements [:fred :barney :bam_bam :pebbles]
:fields {}}}})
(def schema-references-unknown-type
{:interfaces
{:fred
{}
:barney
{}}
:objects
{:dino
{:implements [:fred :barney]
:fields {:dinosaur {:type :raptor}}}}})
(def schema-generated-data
[:one :two :three])
(defn schema-generated-resolver [context args value]
(keys (executor/selections-tree context)))
(def schema-generated-lists
{:objects
(into {}
(for [f schema-generated-data]
[f {:fields {:name {:type 'String}}}]))
:queries
(into {}
(for [f schema-generated-data]
[f {:type `(~'list ~f)
:resolve :schema-generated-resolver}]))})
(deftest invalid-schemas
(expect-exception
"Object `dino' extends interface `pebbles', which does not exist."
{:object {:category :object
:fields {}
:implements [:fred
:barney
:bam_bam
:pebbles]
:type-name :dino}
:schema-types {:interface [:barney
:fred]
:object [:Mutation
:Query
:Subscription
:dino]
:scalar [:Boolean
:Float
:ID
:Int
:String]}}
(schema/compile schema-object-references-unknown-interface))
(expect-exception
"Field `dino/dinosaur' references unknown type `raptor'."
{:field-name :dino/dinosaur
:schema-types {:interface [:barney
:fred]
:object [:Mutation
:Query
:Subscription
:dino]
:scalar [:Boolean
:Float
:ID
:Int
:String]}}
(schema/compile schema-references-unknown-type))
(is (schema/compile
(util/attach-resolvers
schema-generated-lists
{:schema-generated-resolver schema-generated-resolver}))))
(deftest printing-support
(let [compiled-schema (schema/compile {})
as-map (into {} compiled-schema)]
(is (= "#CompiledSchema<>"
(pr-str compiled-schema)))
(is (= "#CompiledSchema<>"
(pprint/write compiled-schema :stream nil)))
(binding [schema/*verbose-schema-printing* true]
(is (= (pr-str as-map)
(pr-str compiled-schema)))
(is (= (pprint/write as-map :stream nil)
(pprint/write compiled-schema :stream nil))))))
(defmacro is-compile-exception
[schema expected-message]
`(is-thrown [e# (schema/compile ~schema)]
(let [msg# (.getMessage e#)]
(reporting {:message msg#}
(is (str/includes? msg# ~expected-message))))))
(deftest types-must-be-valid-ids
(is-compile-exception
{:objects {:not-valid-id {:fields {:id {:type :String}}}}}
"must be a valid GraphQL identifier"))
(deftest field-names-must-be-valid-ids
(is-compile-exception
{:queries {:invalid-field-name {:type :String
:resolve identity}}}
"must be a valid GraphQL identifier"))
(deftest enum-values-must-be-valid-ids
(is-compile-exception
{:enums {:episode {:values [:new-hope :empire :return-of-jedi]}}}
"must be a valid GraphQL identifier"))
(deftest requires-resolve-on-operation
(is-compile-exception
{:queries {:hopeless {:type :String}}}
"should contain key: :resolve"))
(deftest typename-at-root
(let [compiled-schema (schema/compile {})]
(is (= {:data {:__typename :Query}}
(execute compiled-schema "{ __typename }")))
(is (= {:data {:__typename :Mutation}}
(execute compiled-schema "mutation { __typename }")))))
| 80791 | ; Copyright (c) 2017-present <NAME>almart, Inc.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns com.walmartlabs.lacinia.schema-test
"Tests schema functions."
(:require
[clojure.test :refer [deftest testing is are try-expr do-report]]
[com.walmartlabs.test-reporting :refer [reporting]]
[clojure.spec.alpha :as s]
[com.walmartlabs.lacinia.schema :as schema]
[com.walmartlabs.lacinia.executor :as executor]
[com.walmartlabs.lacinia.util :as util]
[com.walmartlabs.test-utils :refer [is-thrown expect-exception execute]]
[clojure.string :as str]
[clojure.pprint :as pprint]))
(defmacro is-error?
[form]
`(let [tuple# (try-expr "Invoking enforcer." ~form)]
(when-not (-> tuple# second some?)
(do-report {:type :fail
:message "Expected some errors in the resolved tuple"}))))
(deftest schema-shape
(testing "schema with not required field"
(let [s {:objects
{:person
{:fields {:foo {:type 'String}}
:bar "I'm extra"}}}]
(is (seq (schema/compile s))
"should compile schema without any problems"))))
(def schema-object-references-unknown-interface
{:interfaces
{:fred
{}
:barney
{}}
:objects
{:dino
{:implements [:fred :barney :bam_bam :pebbles]
:fields {}}}})
(def schema-references-unknown-type
{:interfaces
{:fred
{}
:barney
{}}
:objects
{:dino
{:implements [:fred :barney]
:fields {:dinosaur {:type :raptor}}}}})
(def schema-generated-data
[:one :two :three])
(defn schema-generated-resolver [context args value]
(keys (executor/selections-tree context)))
(def schema-generated-lists
{:objects
(into {}
(for [f schema-generated-data]
[f {:fields {:name {:type 'String}}}]))
:queries
(into {}
(for [f schema-generated-data]
[f {:type `(~'list ~f)
:resolve :schema-generated-resolver}]))})
(deftest invalid-schemas
(expect-exception
"Object `dino' extends interface `pebbles', which does not exist."
{:object {:category :object
:fields {}
:implements [:fred
:barney
:bam_bam
:pebbles]
:type-name :dino}
:schema-types {:interface [:barney
:fred]
:object [:Mutation
:Query
:Subscription
:dino]
:scalar [:Boolean
:Float
:ID
:Int
:String]}}
(schema/compile schema-object-references-unknown-interface))
(expect-exception
"Field `dino/dinosaur' references unknown type `raptor'."
{:field-name :dino/dinosaur
:schema-types {:interface [:barney
:fred]
:object [:Mutation
:Query
:Subscription
:dino]
:scalar [:Boolean
:Float
:ID
:Int
:String]}}
(schema/compile schema-references-unknown-type))
(is (schema/compile
(util/attach-resolvers
schema-generated-lists
{:schema-generated-resolver schema-generated-resolver}))))
(deftest printing-support
(let [compiled-schema (schema/compile {})
as-map (into {} compiled-schema)]
(is (= "#CompiledSchema<>"
(pr-str compiled-schema)))
(is (= "#CompiledSchema<>"
(pprint/write compiled-schema :stream nil)))
(binding [schema/*verbose-schema-printing* true]
(is (= (pr-str as-map)
(pr-str compiled-schema)))
(is (= (pprint/write as-map :stream nil)
(pprint/write compiled-schema :stream nil))))))
(defmacro is-compile-exception
[schema expected-message]
`(is-thrown [e# (schema/compile ~schema)]
(let [msg# (.getMessage e#)]
(reporting {:message msg#}
(is (str/includes? msg# ~expected-message))))))
(deftest types-must-be-valid-ids
(is-compile-exception
{:objects {:not-valid-id {:fields {:id {:type :String}}}}}
"must be a valid GraphQL identifier"))
(deftest field-names-must-be-valid-ids
(is-compile-exception
{:queries {:invalid-field-name {:type :String
:resolve identity}}}
"must be a valid GraphQL identifier"))
(deftest enum-values-must-be-valid-ids
(is-compile-exception
{:enums {:episode {:values [:new-hope :empire :return-of-jedi]}}}
"must be a valid GraphQL identifier"))
(deftest requires-resolve-on-operation
(is-compile-exception
{:queries {:hopeless {:type :String}}}
"should contain key: :resolve"))
(deftest typename-at-root
(let [compiled-schema (schema/compile {})]
(is (= {:data {:__typename :Query}}
(execute compiled-schema "{ __typename }")))
(is (= {:data {:__typename :Mutation}}
(execute compiled-schema "mutation { __typename }")))))
| true | ; Copyright (c) 2017-present PI:NAME:<NAME>END_PIalmart, Inc.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns com.walmartlabs.lacinia.schema-test
"Tests schema functions."
(:require
[clojure.test :refer [deftest testing is are try-expr do-report]]
[com.walmartlabs.test-reporting :refer [reporting]]
[clojure.spec.alpha :as s]
[com.walmartlabs.lacinia.schema :as schema]
[com.walmartlabs.lacinia.executor :as executor]
[com.walmartlabs.lacinia.util :as util]
[com.walmartlabs.test-utils :refer [is-thrown expect-exception execute]]
[clojure.string :as str]
[clojure.pprint :as pprint]))
(defmacro is-error?
[form]
`(let [tuple# (try-expr "Invoking enforcer." ~form)]
(when-not (-> tuple# second some?)
(do-report {:type :fail
:message "Expected some errors in the resolved tuple"}))))
(deftest schema-shape
(testing "schema with not required field"
(let [s {:objects
{:person
{:fields {:foo {:type 'String}}
:bar "I'm extra"}}}]
(is (seq (schema/compile s))
"should compile schema without any problems"))))
(def schema-object-references-unknown-interface
{:interfaces
{:fred
{}
:barney
{}}
:objects
{:dino
{:implements [:fred :barney :bam_bam :pebbles]
:fields {}}}})
(def schema-references-unknown-type
{:interfaces
{:fred
{}
:barney
{}}
:objects
{:dino
{:implements [:fred :barney]
:fields {:dinosaur {:type :raptor}}}}})
(def schema-generated-data
[:one :two :three])
(defn schema-generated-resolver [context args value]
(keys (executor/selections-tree context)))
(def schema-generated-lists
{:objects
(into {}
(for [f schema-generated-data]
[f {:fields {:name {:type 'String}}}]))
:queries
(into {}
(for [f schema-generated-data]
[f {:type `(~'list ~f)
:resolve :schema-generated-resolver}]))})
(deftest invalid-schemas
(expect-exception
"Object `dino' extends interface `pebbles', which does not exist."
{:object {:category :object
:fields {}
:implements [:fred
:barney
:bam_bam
:pebbles]
:type-name :dino}
:schema-types {:interface [:barney
:fred]
:object [:Mutation
:Query
:Subscription
:dino]
:scalar [:Boolean
:Float
:ID
:Int
:String]}}
(schema/compile schema-object-references-unknown-interface))
(expect-exception
"Field `dino/dinosaur' references unknown type `raptor'."
{:field-name :dino/dinosaur
:schema-types {:interface [:barney
:fred]
:object [:Mutation
:Query
:Subscription
:dino]
:scalar [:Boolean
:Float
:ID
:Int
:String]}}
(schema/compile schema-references-unknown-type))
(is (schema/compile
(util/attach-resolvers
schema-generated-lists
{:schema-generated-resolver schema-generated-resolver}))))
(deftest printing-support
(let [compiled-schema (schema/compile {})
as-map (into {} compiled-schema)]
(is (= "#CompiledSchema<>"
(pr-str compiled-schema)))
(is (= "#CompiledSchema<>"
(pprint/write compiled-schema :stream nil)))
(binding [schema/*verbose-schema-printing* true]
(is (= (pr-str as-map)
(pr-str compiled-schema)))
(is (= (pprint/write as-map :stream nil)
(pprint/write compiled-schema :stream nil))))))
(defmacro is-compile-exception
[schema expected-message]
`(is-thrown [e# (schema/compile ~schema)]
(let [msg# (.getMessage e#)]
(reporting {:message msg#}
(is (str/includes? msg# ~expected-message))))))
(deftest types-must-be-valid-ids
(is-compile-exception
{:objects {:not-valid-id {:fields {:id {:type :String}}}}}
"must be a valid GraphQL identifier"))
(deftest field-names-must-be-valid-ids
(is-compile-exception
{:queries {:invalid-field-name {:type :String
:resolve identity}}}
"must be a valid GraphQL identifier"))
(deftest enum-values-must-be-valid-ids
(is-compile-exception
{:enums {:episode {:values [:new-hope :empire :return-of-jedi]}}}
"must be a valid GraphQL identifier"))
(deftest requires-resolve-on-operation
(is-compile-exception
{:queries {:hopeless {:type :String}}}
"should contain key: :resolve"))
(deftest typename-at-root
(let [compiled-schema (schema/compile {})]
(is (= {:data {:__typename :Query}}
(execute compiled-schema "{ __typename }")))
(is (= {:data {:__typename :Mutation}}
(execute compiled-schema "mutation { __typename }")))))
|
[
{
"context": ";; Copyright (C) 2018, 2019 by Vlad Kozin\n\n(ns bitfinex\n (:require [clojure.spec.alpha :as",
"end": 41,
"score": 0.9998327493667603,
"start": 31,
"tag": "NAME",
"value": "Vlad Kozin"
}
] | src/exch/bitfinex.clj | vkz/bot | 1 | ;; Copyright (C) 2018, 2019 by Vlad Kozin
(ns bitfinex
(:require [clojure.spec.alpha :as spec]
[clojure.spec.gen.alpha :as gen]
[medley.core :refer :all]
[aleph.http :as http]
[clj-http.client :as http-client]
[manifold.deferred :as d]
[manifold.stream :as s]
[byte-streams :as bs]
[cheshire.core :as json]
[clojure.string :as string]
[clojure.pprint :refer [pprint]]
[clojure.core.async :as a]
[clojure.core.async.impl.protocols :refer [Channel]]
[taoensso.timbre :as log]))
(require '[exch :as exch
:refer
[ticker ticker-kw base commodity currency
timestamp decimal conj-some
convert-incomming-msg
convert-outgoing-msg
advise unadvise apply-advice]])
;;* Utils & constants
(def ^:private NSNAME (str (ns-name *ns*)))
(defn- ns-keywordize [str]
(keyword NSNAME str))
(def ^:private URL "wss://api.bitfinex.com/ws/2")
(def ^:private pairs
#{"BTCUSD" "LTCUSD" "LTCBTC" "ETHUSD" "ETHBTC"
"ETCBTC" "ETCUSD" "RRTUSD" "RRTBTC" "ZECUSD"
"ZECBTC" "XMRUSD" "XMRBTC" "DSHUSD" "DSHBTC"
"BTCEUR" "XRPUSD" "XRPBTC" "IOTUSD" "IOTBTC"
"IOTETH" "EOSUSD" "EOSBTC" "EOSETH" "SANUSD"
"SANBTC" "SANETH" "OMGUSD" "OMGBTC" "OMGETH"
"BCHUSD" "BCHBTC" "BCHETH" "NEOUSD" "NEOBTC"
"NEOETH" "ETPUSD" "ETPBTC" "ETPETH" "QTMUSD"
"QTMBTC" "QTMETH" "AVTUSD" "AVTBTC" "AVTETH"
"EDOUSD" "EDOBTC" "EDOETH" "BTGUSD" "BTGBTC"
"DATUSD" "DATBTC" "DATETH" "QSHUSD" "QSHBTC"
"QSHETH" "YYWUSD" "YYWBTC" "YYWETH" "GNTUSD"
"GNTBTC" "GNTETH" "SNTUSD" "SNTBTC" "SNTETH"
"IOTEUR" "BATUSD" "BATBTC" "BATETH" "MNAUSD"
"MNABTC" "MNAETH" "FUNUSD" "FUNBTC" "FUNETH"
"ZRXUSD" "ZRXBTC" "ZRXETH" "TNBUSD" "TNBBTC"
"TNBETH" "SPKUSD" "SPKBTC" "SPKETH" "TRXUSD"
"TRXBTC" "TRXETH" "RCNUSD" "RCNBTC" "RCNETH"
"RLCUSD" "RLCBTC" "RLCETH" "AIDUSD" "AIDBTC"
"AIDETH" "SNGUSD" "SNGBTC" "SNGETH" "REPUSD"
"REPBTC" "REPETH" "ELFUSD" "ELFBTC" "ELFETH"})
(defrecord Product [symbol])
(defrecord Pair [symbol])
(def ^:private PAIRS
(->> pairs
(map ->Pair)
(into #{})))
(def ^:private PRODUCTS
(->> pairs
(map #(str "t" %))
(map ->Product)
(into #{})))
(extend-protocol exch/ITicker
Pair
(ticker [{sym :symbol
:as p}]
(let [kw
(comp keyword
string/lower-case)
[base qt]
[(subs sym 0 3)
(subs sym 3)]]
(exch/map->Ticker
{:base (kw base)
:quote (kw qt)})))
(base [p] (:base (ticker p)))
(currency [p] (:quote (ticker p)))
(commodity [p] (:base (ticker p)))
(ticker-kw [p] (ticker-kw (ticker p)))
Product
(ticker [{sym :symbol
:as p}]
(let [kw
(comp keyword
string/lower-case)
[base qt]
[(subs sym 1 4)
(subs sym 4)]]
(exch/map->Ticker
{:base (kw base)
:quote (kw qt)})))
(base [p] (:base (ticker p)))
(currency [p] (:quote (ticker p)))
(commodity [p] (:base (ticker p)))
(ticker-kw [p] (ticker-kw (ticker p))))
(def ^:private TICKERS-PAIRS
(->> PAIRS
(map #(vector (ticker %) %))
(into {})))
(def ^:private TICKERS-PRODUCTS
(->> PRODUCTS
(map #(vector (ticker %) %))
(into {})))
(defn- product [ticker]
(if-some [product (TICKERS-PRODUCTS ticker)]
product
(do
(log/error "Ticker " ticker " does not match any product.")
nil)))
#_((juxt ticker ticker-kw base commodity currency) (->Product "tETHBTC"))
#_((juxt ticker ticker-kw base commodity currency) (->Pair "ETHBTC"))
;;* State
(defprotocol StateProtocol
(set-stream [state stream])
(chan-of-ticker [state ticker])
(ticker-of-chan [state chan])
(add-chan [state chan ticker])
(rm-chan [state chan])
(toggle-status [state])
(state-advise [state advice])
(state-unadvise [state advice]))
(defrecord State [stream channels tickers status ads]
StateProtocol
(set-stream [state new-stream] (State. new-stream channels tickers status ads))
(chan-of-ticker [state ticker] (get tickers ticker))
(ticker-of-chan [state chan] (get channels chan))
(add-chan [state chan ticker]
(State.
stream
(assoc channels chan ticker)
(assoc tickers ticker chan)
status
ads))
(rm-chan [state chan]
(let [ticker (get channels chan)]
(State.
stream
(dissoc channels chan)
(dissoc tickers ticker)
status
ads)))
(toggle-status [state] (State. stream channels tickers (not status) ads))
(state-advise [state advice] (State. stream channels tickers status (update-in ads (:path advice) conj advice)))
(state-unadvise [state advice] (State. stream channels tickers status (update-in ads (:path advice) (fn [ad-vec] (->> ad-vec (remove #(= % advice)) vec))))))
(defn clean-state []
(State.
nil
{}
{}
false
{:before {:incomming []
:outgoing []}
:after {:incomming []
:outgoing []}}))
;;* Connection
(declare
-convert-incomming-msg
-convert-incomming-event-msg
-convert-outgoing-msg)
(defrecord Connection [in out state stub-in]
StateProtocol
(set-stream [conn stream] (swap! state set-stream stream) conn)
(chan-of-ticker [conn ticker] (chan-of-ticker @state ticker))
(ticker-of-chan [conn chan] (ticker-of-chan @state chan))
(add-chan [conn chan ticker] (swap! state add-chan chan ticker) conn)
(rm-chan [conn chan] (swap! state rm-chan chan) conn)
(toggle-status [conn] (swap! state toggle-status) conn)
(state-advise [conn advice] (swap! state state-advise advice))
(state-unadvise [conn advice] (swap! state state-unadvise advice))
exch/ConnectionProtocol
(convert-outgoing-msg [conn msg] (-convert-outgoing-msg conn msg))
(convert-incomming-msg [conn msg]
(let [msg (json/decode msg ns-keywordize)
exch-msg (spec/conform ::incomming-message msg)]
(if (spec/invalid? exch-msg)
(log/error
"Received message did not conform to spec\n"
(with-out-str
(spec/explain-data
::incomming-message
msg)))
(-convert-incomming-msg conn exch-msg))))
(advise [conn advice] (state-advise conn advice) conn)
(unadvise [conn advice] (state-unadvise conn advice) conn)
(apply-advice [conn ad-path msg]
(reduce (fn ad-do-it [msg advice] ((:fn advice) conn msg))
msg
(get-in @state
(case ad-path
[:before :incomming]
[:ads :before :incomming]
[:after :incomming]
[:ads :after :incomming]
[:before :outgoing]
[:ads :before :outgoing]
[:after :outgoing]
[:ads :after :outgoing]))))
(connect [conn]
(let [exch-stream
@(http/websocket-client
URL
{:max-frame-payload 1e6
:max-frame-size 1e6})
in-stream
;; sink of msgs from exchange for users to consume
(s/->sink in)
out-stream
;; source of user msgs to send to exchange
(s/->source out)
;; NOTE connect-via requires an explicit s/put! in the via-fn!
_
;; exchange <= out <= user
(s/connect-via out-stream
(fn [msg]
(->> msg
;; exch/msg
(apply-advice conn [:before :outgoing])
(convert-outgoing-msg conn)
(apply-advice conn [:after :outgoing])
;; json
(s/put! exch-stream)))
exch-stream)
_
;; exchange => in => user
(s/connect-via exch-stream
(fn [msg]
(->> msg
;; json
(apply-advice conn [:before :incomming])
(convert-incomming-msg conn)
(mapv #(apply-advice conn [:after :incomming] %))
;; exch/msg
(s/put-all! in-stream)))
in-stream
{ ;; close exch-stream if in-stream is closed
:upstream? true
;; do not close in-stream if exch-stream source
:downstream? false})
stub-exch-source
(s/->source stub-in)
_
(s/connect-via stub-exch-source
(fn [msg]
(->> msg
;; json
(apply-advice conn [:before :incomming])
(convert-incomming-msg conn)
;; => [msg ...], therefore
(mapv #(apply-advice conn [:after :incomming] %))
;; exch/msg
(s/put-all! in-stream)))
in-stream
{ ;; close exch-stream if in-stream is closed
:upstream? true
;; do not close in-stream if exch-stream source
:downstream? false})]
;; TODO Maybe have a proc sending out [:ping] to keep alive
(-> conn
(set-stream exch-stream)
;; TODO add stub-exch-source to State
;; (set-stub-exch-source stub-exch-source)
(toggle-status))))
(disconnect [conn] (a/close! in) (toggle-status conn))
(connected? [conn] (:status @state))
(send-out [conn msg] (a/put! (:out conn) msg))
(send-in [conn msg] (a/put! (:in conn) msg))
(conn-name [conn] (keyword NSNAME)))
(defn create-connection []
(let [in (a/chan 1)
out (a/chan 1)
stub-in (a/chan 1)]
(Connection. in out (atom (clean-state)) stub-in)))
;;* Message specs
(defn map-json-map [msg]
(-> msg
(json/encode)
(json/decode ns-keywordize)))
;;** - update
(spec/def ::update
(spec/spec
;; nested
(spec/cat :price number?
:orders number?
:size number?)))
(spec/def ::update-msg
(spec/cat
:channel number?
:update ::update))
;;** - snapshot
(spec/def ::snapshot
(spec/spec
;; nested
(spec/* ::update)))
(spec/def ::snapshot-msg
(spec/cat
:channel number?
:snapshot ::snapshot))
;;** - heartbeat
(spec/def ::hb-msg
(spec/cat :channel number?
:hb #{"hb"}))
;;** - event
(spec/def ::code (spec/and pos-int? #(< % 100000)))
(spec/def ::msg string?)
(defmulti event-type ::event)
(defmethod event-type "pong" [_]
(spec/keys :req [::event]))
(defmethod event-type "info" [_]
(spec/keys :req [::event]
:opt [::code ::msg]))
(defmethod event-type "subscribed" [_]
(spec/keys :req [::event ::pair ::chanId]))
(defmethod event-type "unsubscribed" [_]
(spec/keys :req [::event ::status ::chanId]))
(defmethod event-type "error" [_]
(spec/keys :req [::event ::code ::msg]))
(spec/def ::event-msg
(spec/multi-spec event-type ::event))
;;** - message
(spec/def ::incomming-message
(spec/or
:event ::event-msg
:heartbeat ::hb-msg
:snapshot ::snapshot-msg
:update ::update-msg))
;;* Convert incomming msg
;;** - dispatch by tag
(defmulti -convert-incomming-msg (fn [conn [tag]] tag))
(defn add-ticker-or-drop
[conn [tag {channel :channel
:as m}]]
(if-let [ticker (ticker-of-chan conn channel)]
[tag (assoc m :ticker ticker)]
(let [reason (str "Ticker for channel " channel " not found")]
(log/error reason)
[:drop (-> m
(assoc :tag tag)
(assoc :reason reason))])))
(defmethod -convert-incomming-msg :heartbeat
[conn msg]
(vector
(add-ticker-or-drop conn msg)))
(defn- snapshot->bids-asks [payload]
(let [{:keys [bids asks]}
(group-by (fn [{:keys [price size]}]
(if (neg? size)
:asks
:bids))
payload)
bids
(map (fn [{:keys [price orders size]}]
[(decimal price)
(if (zero? orders)
(decimal 0)
(decimal size))])
bids)
asks
(map (fn [{:keys [price orders size]}]
[(decimal price)
(if (zero? orders)
(decimal 0)
(decimal (- 0 size)))])
asks)]
{:bids bids
:asks asks}))
(defn- update->bids-asks [payload]
(snapshot->bids-asks payload))
#_
(=
(snapshot->bids-asks
[{:price 584.58, :orders 11, :size 65.64632441}
{:price 584.51, :orders 1, :size 0.93194317}
{:price 584.59, :orders 4, :size -23.39216286}
{:price 584.96, :orders 1, :size -7.23746288}
{:price 584.97, :orders 1, :size -12.3}])
'{:bids ([584.58M 65.64632441M]
[584.51M 0.93194317M])
:asks ([584.59M 23.39216286M]
[584.96M 7.23746288M]
[584.97M 12.3M])})
(defmethod -convert-incomming-msg :snapshot
[conn [tag payload]]
(vector
(add-ticker-or-drop
conn
[tag (update
payload
:snapshot snapshot->bids-asks)])))
(defmethod -convert-incomming-msg :update
[conn [_ {update :update
:as m}]]
(vector
(add-ticker-or-drop
conn
[:update
(assoc m :update
(update->bids-asks [update]))])))
(defmethod -convert-incomming-msg :event [conn [_ m]]
(-convert-incomming-event-msg conn m))
;;** - dispatch by event type
(defmulti -convert-incomming-event-msg (fn [conn msg] (::event msg)))
(defmethod -convert-incomming-event-msg "pong"
[conn {ts ::ts cid ::cid :as m}]
(vector
[:pong
(-> m
(assoc :timestamp (timestamp ts))
(assoc :id cid))]))
(defmethod -convert-incomming-event-msg "info"
[conn {event ::event code ::code msg ::msg :as m}]
(let [tag
(case code
20051 :reconnect
20060 :pause
20061 :resume
nil :info
;; else
(do
(log/error
"Received message of type event => " event
" with unrecognized code " code)
:drop))
[orig-tag reason]
(when (= tag :drop)
[:event
(str "Unrecognized code " code
" in message")])
payload
(-> m
(assoc-some :message msg)
(assoc-some :reason reason)
(assoc-some :tag orig-tag))]
(vector
[tag payload])))
(defmethod -convert-incomming-event-msg "subscribed"
[conn {pair ::pair channel ::chanId :as m}]
(let [ticker
(ticker
(->Pair pair))]
(add-chan conn channel ticker)
(log/info "Subscribed to ticker " ticker)
(vector
[:subscribed
(assoc m :ticker ticker)])))
(defmethod -convert-incomming-event-msg "unsubscribed"
[conn {channel ::chanId :as m}]
(vector
(if-let [ticker (ticker-of-chan conn channel)]
(do
(rm-chan conn channel)
(log/info "Unsubscribed ticker " ticker)
[:unsubscribed
(assoc m :ticker ticker)])
(do
(let [reason (str "Ticker for channel " channel " not found")]
(log/error reason)
[:drop
(-> m
(assoc :tag :unsubscribed)
(assoc :reason reason))])))))
(defmethod -convert-incomming-event-msg "error"
[conn {code ::code msg ::msg :as m}]
(let [tag
:error
payload
(-> m
(assoc :message msg)
(assoc :code code))]
(log/error
"Received error code from server:"
payload)
(vector
[tag payload])))
;;* Convert outgoing msg
(defmulti -convert-outgoing-msg (fn [conn [tag _]] tag))
(defmethod -convert-outgoing-msg :ping
[conn [_]]
(json/encode {:event "ping"}))
(defmethod -convert-outgoing-msg :subscribe
[conn [_ ticker]]
(json/encode
{:event "subscribe"
:channel "book"
:symbol (:symbol (product ticker))
:prec "P0"
:freq "F0"}))
(defmethod -convert-outgoing-msg :unsubscribe
[conn [_ ticker]]
(let [channel (chan-of-ticker conn ticker)]
(json/encode
{:event "unsubscribe"
:chanId channel})))
(defmethod -convert-outgoing-msg :default
[conn msg]
(json/encode msg))
;; Conf
;; {
;; event: "conf",
;; flags: FLAGS
;; }
| 33434 | ;; Copyright (C) 2018, 2019 by <NAME>
(ns bitfinex
(:require [clojure.spec.alpha :as spec]
[clojure.spec.gen.alpha :as gen]
[medley.core :refer :all]
[aleph.http :as http]
[clj-http.client :as http-client]
[manifold.deferred :as d]
[manifold.stream :as s]
[byte-streams :as bs]
[cheshire.core :as json]
[clojure.string :as string]
[clojure.pprint :refer [pprint]]
[clojure.core.async :as a]
[clojure.core.async.impl.protocols :refer [Channel]]
[taoensso.timbre :as log]))
(require '[exch :as exch
:refer
[ticker ticker-kw base commodity currency
timestamp decimal conj-some
convert-incomming-msg
convert-outgoing-msg
advise unadvise apply-advice]])
;;* Utils & constants
(def ^:private NSNAME (str (ns-name *ns*)))
(defn- ns-keywordize [str]
(keyword NSNAME str))
(def ^:private URL "wss://api.bitfinex.com/ws/2")
(def ^:private pairs
#{"BTCUSD" "LTCUSD" "LTCBTC" "ETHUSD" "ETHBTC"
"ETCBTC" "ETCUSD" "RRTUSD" "RRTBTC" "ZECUSD"
"ZECBTC" "XMRUSD" "XMRBTC" "DSHUSD" "DSHBTC"
"BTCEUR" "XRPUSD" "XRPBTC" "IOTUSD" "IOTBTC"
"IOTETH" "EOSUSD" "EOSBTC" "EOSETH" "SANUSD"
"SANBTC" "SANETH" "OMGUSD" "OMGBTC" "OMGETH"
"BCHUSD" "BCHBTC" "BCHETH" "NEOUSD" "NEOBTC"
"NEOETH" "ETPUSD" "ETPBTC" "ETPETH" "QTMUSD"
"QTMBTC" "QTMETH" "AVTUSD" "AVTBTC" "AVTETH"
"EDOUSD" "EDOBTC" "EDOETH" "BTGUSD" "BTGBTC"
"DATUSD" "DATBTC" "DATETH" "QSHUSD" "QSHBTC"
"QSHETH" "YYWUSD" "YYWBTC" "YYWETH" "GNTUSD"
"GNTBTC" "GNTETH" "SNTUSD" "SNTBTC" "SNTETH"
"IOTEUR" "BATUSD" "BATBTC" "BATETH" "MNAUSD"
"MNABTC" "MNAETH" "FUNUSD" "FUNBTC" "FUNETH"
"ZRXUSD" "ZRXBTC" "ZRXETH" "TNBUSD" "TNBBTC"
"TNBETH" "SPKUSD" "SPKBTC" "SPKETH" "TRXUSD"
"TRXBTC" "TRXETH" "RCNUSD" "RCNBTC" "RCNETH"
"RLCUSD" "RLCBTC" "RLCETH" "AIDUSD" "AIDBTC"
"AIDETH" "SNGUSD" "SNGBTC" "SNGETH" "REPUSD"
"REPBTC" "REPETH" "ELFUSD" "ELFBTC" "ELFETH"})
(defrecord Product [symbol])
(defrecord Pair [symbol])
(def ^:private PAIRS
(->> pairs
(map ->Pair)
(into #{})))
(def ^:private PRODUCTS
(->> pairs
(map #(str "t" %))
(map ->Product)
(into #{})))
(extend-protocol exch/ITicker
Pair
(ticker [{sym :symbol
:as p}]
(let [kw
(comp keyword
string/lower-case)
[base qt]
[(subs sym 0 3)
(subs sym 3)]]
(exch/map->Ticker
{:base (kw base)
:quote (kw qt)})))
(base [p] (:base (ticker p)))
(currency [p] (:quote (ticker p)))
(commodity [p] (:base (ticker p)))
(ticker-kw [p] (ticker-kw (ticker p)))
Product
(ticker [{sym :symbol
:as p}]
(let [kw
(comp keyword
string/lower-case)
[base qt]
[(subs sym 1 4)
(subs sym 4)]]
(exch/map->Ticker
{:base (kw base)
:quote (kw qt)})))
(base [p] (:base (ticker p)))
(currency [p] (:quote (ticker p)))
(commodity [p] (:base (ticker p)))
(ticker-kw [p] (ticker-kw (ticker p))))
(def ^:private TICKERS-PAIRS
(->> PAIRS
(map #(vector (ticker %) %))
(into {})))
(def ^:private TICKERS-PRODUCTS
(->> PRODUCTS
(map #(vector (ticker %) %))
(into {})))
(defn- product [ticker]
(if-some [product (TICKERS-PRODUCTS ticker)]
product
(do
(log/error "Ticker " ticker " does not match any product.")
nil)))
#_((juxt ticker ticker-kw base commodity currency) (->Product "tETHBTC"))
#_((juxt ticker ticker-kw base commodity currency) (->Pair "ETHBTC"))
;;* State
(defprotocol StateProtocol
(set-stream [state stream])
(chan-of-ticker [state ticker])
(ticker-of-chan [state chan])
(add-chan [state chan ticker])
(rm-chan [state chan])
(toggle-status [state])
(state-advise [state advice])
(state-unadvise [state advice]))
(defrecord State [stream channels tickers status ads]
StateProtocol
(set-stream [state new-stream] (State. new-stream channels tickers status ads))
(chan-of-ticker [state ticker] (get tickers ticker))
(ticker-of-chan [state chan] (get channels chan))
(add-chan [state chan ticker]
(State.
stream
(assoc channels chan ticker)
(assoc tickers ticker chan)
status
ads))
(rm-chan [state chan]
(let [ticker (get channels chan)]
(State.
stream
(dissoc channels chan)
(dissoc tickers ticker)
status
ads)))
(toggle-status [state] (State. stream channels tickers (not status) ads))
(state-advise [state advice] (State. stream channels tickers status (update-in ads (:path advice) conj advice)))
(state-unadvise [state advice] (State. stream channels tickers status (update-in ads (:path advice) (fn [ad-vec] (->> ad-vec (remove #(= % advice)) vec))))))
(defn clean-state []
(State.
nil
{}
{}
false
{:before {:incomming []
:outgoing []}
:after {:incomming []
:outgoing []}}))
;;* Connection
(declare
-convert-incomming-msg
-convert-incomming-event-msg
-convert-outgoing-msg)
(defrecord Connection [in out state stub-in]
StateProtocol
(set-stream [conn stream] (swap! state set-stream stream) conn)
(chan-of-ticker [conn ticker] (chan-of-ticker @state ticker))
(ticker-of-chan [conn chan] (ticker-of-chan @state chan))
(add-chan [conn chan ticker] (swap! state add-chan chan ticker) conn)
(rm-chan [conn chan] (swap! state rm-chan chan) conn)
(toggle-status [conn] (swap! state toggle-status) conn)
(state-advise [conn advice] (swap! state state-advise advice))
(state-unadvise [conn advice] (swap! state state-unadvise advice))
exch/ConnectionProtocol
(convert-outgoing-msg [conn msg] (-convert-outgoing-msg conn msg))
(convert-incomming-msg [conn msg]
(let [msg (json/decode msg ns-keywordize)
exch-msg (spec/conform ::incomming-message msg)]
(if (spec/invalid? exch-msg)
(log/error
"Received message did not conform to spec\n"
(with-out-str
(spec/explain-data
::incomming-message
msg)))
(-convert-incomming-msg conn exch-msg))))
(advise [conn advice] (state-advise conn advice) conn)
(unadvise [conn advice] (state-unadvise conn advice) conn)
(apply-advice [conn ad-path msg]
(reduce (fn ad-do-it [msg advice] ((:fn advice) conn msg))
msg
(get-in @state
(case ad-path
[:before :incomming]
[:ads :before :incomming]
[:after :incomming]
[:ads :after :incomming]
[:before :outgoing]
[:ads :before :outgoing]
[:after :outgoing]
[:ads :after :outgoing]))))
(connect [conn]
(let [exch-stream
@(http/websocket-client
URL
{:max-frame-payload 1e6
:max-frame-size 1e6})
in-stream
;; sink of msgs from exchange for users to consume
(s/->sink in)
out-stream
;; source of user msgs to send to exchange
(s/->source out)
;; NOTE connect-via requires an explicit s/put! in the via-fn!
_
;; exchange <= out <= user
(s/connect-via out-stream
(fn [msg]
(->> msg
;; exch/msg
(apply-advice conn [:before :outgoing])
(convert-outgoing-msg conn)
(apply-advice conn [:after :outgoing])
;; json
(s/put! exch-stream)))
exch-stream)
_
;; exchange => in => user
(s/connect-via exch-stream
(fn [msg]
(->> msg
;; json
(apply-advice conn [:before :incomming])
(convert-incomming-msg conn)
(mapv #(apply-advice conn [:after :incomming] %))
;; exch/msg
(s/put-all! in-stream)))
in-stream
{ ;; close exch-stream if in-stream is closed
:upstream? true
;; do not close in-stream if exch-stream source
:downstream? false})
stub-exch-source
(s/->source stub-in)
_
(s/connect-via stub-exch-source
(fn [msg]
(->> msg
;; json
(apply-advice conn [:before :incomming])
(convert-incomming-msg conn)
;; => [msg ...], therefore
(mapv #(apply-advice conn [:after :incomming] %))
;; exch/msg
(s/put-all! in-stream)))
in-stream
{ ;; close exch-stream if in-stream is closed
:upstream? true
;; do not close in-stream if exch-stream source
:downstream? false})]
;; TODO Maybe have a proc sending out [:ping] to keep alive
(-> conn
(set-stream exch-stream)
;; TODO add stub-exch-source to State
;; (set-stub-exch-source stub-exch-source)
(toggle-status))))
(disconnect [conn] (a/close! in) (toggle-status conn))
(connected? [conn] (:status @state))
(send-out [conn msg] (a/put! (:out conn) msg))
(send-in [conn msg] (a/put! (:in conn) msg))
(conn-name [conn] (keyword NSNAME)))
(defn create-connection []
(let [in (a/chan 1)
out (a/chan 1)
stub-in (a/chan 1)]
(Connection. in out (atom (clean-state)) stub-in)))
;;* Message specs
(defn map-json-map [msg]
(-> msg
(json/encode)
(json/decode ns-keywordize)))
;;** - update
(spec/def ::update
(spec/spec
;; nested
(spec/cat :price number?
:orders number?
:size number?)))
(spec/def ::update-msg
(spec/cat
:channel number?
:update ::update))
;;** - snapshot
(spec/def ::snapshot
(spec/spec
;; nested
(spec/* ::update)))
(spec/def ::snapshot-msg
(spec/cat
:channel number?
:snapshot ::snapshot))
;;** - heartbeat
(spec/def ::hb-msg
(spec/cat :channel number?
:hb #{"hb"}))
;;** - event
(spec/def ::code (spec/and pos-int? #(< % 100000)))
(spec/def ::msg string?)
(defmulti event-type ::event)
(defmethod event-type "pong" [_]
(spec/keys :req [::event]))
(defmethod event-type "info" [_]
(spec/keys :req [::event]
:opt [::code ::msg]))
(defmethod event-type "subscribed" [_]
(spec/keys :req [::event ::pair ::chanId]))
(defmethod event-type "unsubscribed" [_]
(spec/keys :req [::event ::status ::chanId]))
(defmethod event-type "error" [_]
(spec/keys :req [::event ::code ::msg]))
(spec/def ::event-msg
(spec/multi-spec event-type ::event))
;;** - message
(spec/def ::incomming-message
(spec/or
:event ::event-msg
:heartbeat ::hb-msg
:snapshot ::snapshot-msg
:update ::update-msg))
;;* Convert incomming msg
;;** - dispatch by tag
(defmulti -convert-incomming-msg (fn [conn [tag]] tag))
(defn add-ticker-or-drop
[conn [tag {channel :channel
:as m}]]
(if-let [ticker (ticker-of-chan conn channel)]
[tag (assoc m :ticker ticker)]
(let [reason (str "Ticker for channel " channel " not found")]
(log/error reason)
[:drop (-> m
(assoc :tag tag)
(assoc :reason reason))])))
(defmethod -convert-incomming-msg :heartbeat
[conn msg]
(vector
(add-ticker-or-drop conn msg)))
(defn- snapshot->bids-asks [payload]
(let [{:keys [bids asks]}
(group-by (fn [{:keys [price size]}]
(if (neg? size)
:asks
:bids))
payload)
bids
(map (fn [{:keys [price orders size]}]
[(decimal price)
(if (zero? orders)
(decimal 0)
(decimal size))])
bids)
asks
(map (fn [{:keys [price orders size]}]
[(decimal price)
(if (zero? orders)
(decimal 0)
(decimal (- 0 size)))])
asks)]
{:bids bids
:asks asks}))
(defn- update->bids-asks [payload]
(snapshot->bids-asks payload))
#_
(=
(snapshot->bids-asks
[{:price 584.58, :orders 11, :size 65.64632441}
{:price 584.51, :orders 1, :size 0.93194317}
{:price 584.59, :orders 4, :size -23.39216286}
{:price 584.96, :orders 1, :size -7.23746288}
{:price 584.97, :orders 1, :size -12.3}])
'{:bids ([584.58M 65.64632441M]
[584.51M 0.93194317M])
:asks ([584.59M 23.39216286M]
[584.96M 7.23746288M]
[584.97M 12.3M])})
(defmethod -convert-incomming-msg :snapshot
[conn [tag payload]]
(vector
(add-ticker-or-drop
conn
[tag (update
payload
:snapshot snapshot->bids-asks)])))
(defmethod -convert-incomming-msg :update
[conn [_ {update :update
:as m}]]
(vector
(add-ticker-or-drop
conn
[:update
(assoc m :update
(update->bids-asks [update]))])))
(defmethod -convert-incomming-msg :event [conn [_ m]]
(-convert-incomming-event-msg conn m))
;;** - dispatch by event type
(defmulti -convert-incomming-event-msg (fn [conn msg] (::event msg)))
(defmethod -convert-incomming-event-msg "pong"
[conn {ts ::ts cid ::cid :as m}]
(vector
[:pong
(-> m
(assoc :timestamp (timestamp ts))
(assoc :id cid))]))
(defmethod -convert-incomming-event-msg "info"
[conn {event ::event code ::code msg ::msg :as m}]
(let [tag
(case code
20051 :reconnect
20060 :pause
20061 :resume
nil :info
;; else
(do
(log/error
"Received message of type event => " event
" with unrecognized code " code)
:drop))
[orig-tag reason]
(when (= tag :drop)
[:event
(str "Unrecognized code " code
" in message")])
payload
(-> m
(assoc-some :message msg)
(assoc-some :reason reason)
(assoc-some :tag orig-tag))]
(vector
[tag payload])))
(defmethod -convert-incomming-event-msg "subscribed"
[conn {pair ::pair channel ::chanId :as m}]
(let [ticker
(ticker
(->Pair pair))]
(add-chan conn channel ticker)
(log/info "Subscribed to ticker " ticker)
(vector
[:subscribed
(assoc m :ticker ticker)])))
(defmethod -convert-incomming-event-msg "unsubscribed"
[conn {channel ::chanId :as m}]
(vector
(if-let [ticker (ticker-of-chan conn channel)]
(do
(rm-chan conn channel)
(log/info "Unsubscribed ticker " ticker)
[:unsubscribed
(assoc m :ticker ticker)])
(do
(let [reason (str "Ticker for channel " channel " not found")]
(log/error reason)
[:drop
(-> m
(assoc :tag :unsubscribed)
(assoc :reason reason))])))))
(defmethod -convert-incomming-event-msg "error"
[conn {code ::code msg ::msg :as m}]
(let [tag
:error
payload
(-> m
(assoc :message msg)
(assoc :code code))]
(log/error
"Received error code from server:"
payload)
(vector
[tag payload])))
;;* Convert outgoing msg
(defmulti -convert-outgoing-msg (fn [conn [tag _]] tag))
(defmethod -convert-outgoing-msg :ping
[conn [_]]
(json/encode {:event "ping"}))
(defmethod -convert-outgoing-msg :subscribe
[conn [_ ticker]]
(json/encode
{:event "subscribe"
:channel "book"
:symbol (:symbol (product ticker))
:prec "P0"
:freq "F0"}))
(defmethod -convert-outgoing-msg :unsubscribe
[conn [_ ticker]]
(let [channel (chan-of-ticker conn ticker)]
(json/encode
{:event "unsubscribe"
:chanId channel})))
(defmethod -convert-outgoing-msg :default
[conn msg]
(json/encode msg))
;; Conf
;; {
;; event: "conf",
;; flags: FLAGS
;; }
| true | ;; Copyright (C) 2018, 2019 by PI:NAME:<NAME>END_PI
(ns bitfinex
(:require [clojure.spec.alpha :as spec]
[clojure.spec.gen.alpha :as gen]
[medley.core :refer :all]
[aleph.http :as http]
[clj-http.client :as http-client]
[manifold.deferred :as d]
[manifold.stream :as s]
[byte-streams :as bs]
[cheshire.core :as json]
[clojure.string :as string]
[clojure.pprint :refer [pprint]]
[clojure.core.async :as a]
[clojure.core.async.impl.protocols :refer [Channel]]
[taoensso.timbre :as log]))
(require '[exch :as exch
:refer
[ticker ticker-kw base commodity currency
timestamp decimal conj-some
convert-incomming-msg
convert-outgoing-msg
advise unadvise apply-advice]])
;;* Utils & constants
(def ^:private NSNAME (str (ns-name *ns*)))
(defn- ns-keywordize [str]
(keyword NSNAME str))
(def ^:private URL "wss://api.bitfinex.com/ws/2")
(def ^:private pairs
#{"BTCUSD" "LTCUSD" "LTCBTC" "ETHUSD" "ETHBTC"
"ETCBTC" "ETCUSD" "RRTUSD" "RRTBTC" "ZECUSD"
"ZECBTC" "XMRUSD" "XMRBTC" "DSHUSD" "DSHBTC"
"BTCEUR" "XRPUSD" "XRPBTC" "IOTUSD" "IOTBTC"
"IOTETH" "EOSUSD" "EOSBTC" "EOSETH" "SANUSD"
"SANBTC" "SANETH" "OMGUSD" "OMGBTC" "OMGETH"
"BCHUSD" "BCHBTC" "BCHETH" "NEOUSD" "NEOBTC"
"NEOETH" "ETPUSD" "ETPBTC" "ETPETH" "QTMUSD"
"QTMBTC" "QTMETH" "AVTUSD" "AVTBTC" "AVTETH"
"EDOUSD" "EDOBTC" "EDOETH" "BTGUSD" "BTGBTC"
"DATUSD" "DATBTC" "DATETH" "QSHUSD" "QSHBTC"
"QSHETH" "YYWUSD" "YYWBTC" "YYWETH" "GNTUSD"
"GNTBTC" "GNTETH" "SNTUSD" "SNTBTC" "SNTETH"
"IOTEUR" "BATUSD" "BATBTC" "BATETH" "MNAUSD"
"MNABTC" "MNAETH" "FUNUSD" "FUNBTC" "FUNETH"
"ZRXUSD" "ZRXBTC" "ZRXETH" "TNBUSD" "TNBBTC"
"TNBETH" "SPKUSD" "SPKBTC" "SPKETH" "TRXUSD"
"TRXBTC" "TRXETH" "RCNUSD" "RCNBTC" "RCNETH"
"RLCUSD" "RLCBTC" "RLCETH" "AIDUSD" "AIDBTC"
"AIDETH" "SNGUSD" "SNGBTC" "SNGETH" "REPUSD"
"REPBTC" "REPETH" "ELFUSD" "ELFBTC" "ELFETH"})
(defrecord Product [symbol])
(defrecord Pair [symbol])
(def ^:private PAIRS
(->> pairs
(map ->Pair)
(into #{})))
(def ^:private PRODUCTS
(->> pairs
(map #(str "t" %))
(map ->Product)
(into #{})))
(extend-protocol exch/ITicker
Pair
(ticker [{sym :symbol
:as p}]
(let [kw
(comp keyword
string/lower-case)
[base qt]
[(subs sym 0 3)
(subs sym 3)]]
(exch/map->Ticker
{:base (kw base)
:quote (kw qt)})))
(base [p] (:base (ticker p)))
(currency [p] (:quote (ticker p)))
(commodity [p] (:base (ticker p)))
(ticker-kw [p] (ticker-kw (ticker p)))
Product
(ticker [{sym :symbol
:as p}]
(let [kw
(comp keyword
string/lower-case)
[base qt]
[(subs sym 1 4)
(subs sym 4)]]
(exch/map->Ticker
{:base (kw base)
:quote (kw qt)})))
(base [p] (:base (ticker p)))
(currency [p] (:quote (ticker p)))
(commodity [p] (:base (ticker p)))
(ticker-kw [p] (ticker-kw (ticker p))))
(def ^:private TICKERS-PAIRS
(->> PAIRS
(map #(vector (ticker %) %))
(into {})))
(def ^:private TICKERS-PRODUCTS
(->> PRODUCTS
(map #(vector (ticker %) %))
(into {})))
(defn- product [ticker]
(if-some [product (TICKERS-PRODUCTS ticker)]
product
(do
(log/error "Ticker " ticker " does not match any product.")
nil)))
#_((juxt ticker ticker-kw base commodity currency) (->Product "tETHBTC"))
#_((juxt ticker ticker-kw base commodity currency) (->Pair "ETHBTC"))
;;* State
(defprotocol StateProtocol
(set-stream [state stream])
(chan-of-ticker [state ticker])
(ticker-of-chan [state chan])
(add-chan [state chan ticker])
(rm-chan [state chan])
(toggle-status [state])
(state-advise [state advice])
(state-unadvise [state advice]))
(defrecord State [stream channels tickers status ads]
StateProtocol
(set-stream [state new-stream] (State. new-stream channels tickers status ads))
(chan-of-ticker [state ticker] (get tickers ticker))
(ticker-of-chan [state chan] (get channels chan))
(add-chan [state chan ticker]
(State.
stream
(assoc channels chan ticker)
(assoc tickers ticker chan)
status
ads))
(rm-chan [state chan]
(let [ticker (get channels chan)]
(State.
stream
(dissoc channels chan)
(dissoc tickers ticker)
status
ads)))
(toggle-status [state] (State. stream channels tickers (not status) ads))
(state-advise [state advice] (State. stream channels tickers status (update-in ads (:path advice) conj advice)))
(state-unadvise [state advice] (State. stream channels tickers status (update-in ads (:path advice) (fn [ad-vec] (->> ad-vec (remove #(= % advice)) vec))))))
(defn clean-state []
(State.
nil
{}
{}
false
{:before {:incomming []
:outgoing []}
:after {:incomming []
:outgoing []}}))
;;* Connection
(declare
-convert-incomming-msg
-convert-incomming-event-msg
-convert-outgoing-msg)
(defrecord Connection [in out state stub-in]
StateProtocol
(set-stream [conn stream] (swap! state set-stream stream) conn)
(chan-of-ticker [conn ticker] (chan-of-ticker @state ticker))
(ticker-of-chan [conn chan] (ticker-of-chan @state chan))
(add-chan [conn chan ticker] (swap! state add-chan chan ticker) conn)
(rm-chan [conn chan] (swap! state rm-chan chan) conn)
(toggle-status [conn] (swap! state toggle-status) conn)
(state-advise [conn advice] (swap! state state-advise advice))
(state-unadvise [conn advice] (swap! state state-unadvise advice))
exch/ConnectionProtocol
(convert-outgoing-msg [conn msg] (-convert-outgoing-msg conn msg))
(convert-incomming-msg [conn msg]
(let [msg (json/decode msg ns-keywordize)
exch-msg (spec/conform ::incomming-message msg)]
(if (spec/invalid? exch-msg)
(log/error
"Received message did not conform to spec\n"
(with-out-str
(spec/explain-data
::incomming-message
msg)))
(-convert-incomming-msg conn exch-msg))))
(advise [conn advice] (state-advise conn advice) conn)
(unadvise [conn advice] (state-unadvise conn advice) conn)
(apply-advice [conn ad-path msg]
(reduce (fn ad-do-it [msg advice] ((:fn advice) conn msg))
msg
(get-in @state
(case ad-path
[:before :incomming]
[:ads :before :incomming]
[:after :incomming]
[:ads :after :incomming]
[:before :outgoing]
[:ads :before :outgoing]
[:after :outgoing]
[:ads :after :outgoing]))))
(connect [conn]
(let [exch-stream
@(http/websocket-client
URL
{:max-frame-payload 1e6
:max-frame-size 1e6})
in-stream
;; sink of msgs from exchange for users to consume
(s/->sink in)
out-stream
;; source of user msgs to send to exchange
(s/->source out)
;; NOTE connect-via requires an explicit s/put! in the via-fn!
_
;; exchange <= out <= user
(s/connect-via out-stream
(fn [msg]
(->> msg
;; exch/msg
(apply-advice conn [:before :outgoing])
(convert-outgoing-msg conn)
(apply-advice conn [:after :outgoing])
;; json
(s/put! exch-stream)))
exch-stream)
_
;; exchange => in => user
(s/connect-via exch-stream
(fn [msg]
(->> msg
;; json
(apply-advice conn [:before :incomming])
(convert-incomming-msg conn)
(mapv #(apply-advice conn [:after :incomming] %))
;; exch/msg
(s/put-all! in-stream)))
in-stream
{ ;; close exch-stream if in-stream is closed
:upstream? true
;; do not close in-stream if exch-stream source
:downstream? false})
stub-exch-source
(s/->source stub-in)
_
(s/connect-via stub-exch-source
(fn [msg]
(->> msg
;; json
(apply-advice conn [:before :incomming])
(convert-incomming-msg conn)
;; => [msg ...], therefore
(mapv #(apply-advice conn [:after :incomming] %))
;; exch/msg
(s/put-all! in-stream)))
in-stream
{ ;; close exch-stream if in-stream is closed
:upstream? true
;; do not close in-stream if exch-stream source
:downstream? false})]
;; TODO Maybe have a proc sending out [:ping] to keep alive
(-> conn
(set-stream exch-stream)
;; TODO add stub-exch-source to State
;; (set-stub-exch-source stub-exch-source)
(toggle-status))))
(disconnect [conn] (a/close! in) (toggle-status conn))
(connected? [conn] (:status @state))
(send-out [conn msg] (a/put! (:out conn) msg))
(send-in [conn msg] (a/put! (:in conn) msg))
(conn-name [conn] (keyword NSNAME)))
(defn create-connection []
(let [in (a/chan 1)
out (a/chan 1)
stub-in (a/chan 1)]
(Connection. in out (atom (clean-state)) stub-in)))
;;* Message specs
(defn map-json-map [msg]
(-> msg
(json/encode)
(json/decode ns-keywordize)))
;;** - update
(spec/def ::update
(spec/spec
;; nested
(spec/cat :price number?
:orders number?
:size number?)))
(spec/def ::update-msg
(spec/cat
:channel number?
:update ::update))
;;** - snapshot
(spec/def ::snapshot
(spec/spec
;; nested
(spec/* ::update)))
(spec/def ::snapshot-msg
(spec/cat
:channel number?
:snapshot ::snapshot))
;;** - heartbeat
(spec/def ::hb-msg
(spec/cat :channel number?
:hb #{"hb"}))
;;** - event
(spec/def ::code (spec/and pos-int? #(< % 100000)))
(spec/def ::msg string?)
(defmulti event-type ::event)
(defmethod event-type "pong" [_]
(spec/keys :req [::event]))
(defmethod event-type "info" [_]
(spec/keys :req [::event]
:opt [::code ::msg]))
(defmethod event-type "subscribed" [_]
(spec/keys :req [::event ::pair ::chanId]))
(defmethod event-type "unsubscribed" [_]
(spec/keys :req [::event ::status ::chanId]))
(defmethod event-type "error" [_]
(spec/keys :req [::event ::code ::msg]))
(spec/def ::event-msg
(spec/multi-spec event-type ::event))
;;** - message
(spec/def ::incomming-message
(spec/or
:event ::event-msg
:heartbeat ::hb-msg
:snapshot ::snapshot-msg
:update ::update-msg))
;;* Convert incomming msg
;;** - dispatch by tag
(defmulti -convert-incomming-msg (fn [conn [tag]] tag))
(defn add-ticker-or-drop
[conn [tag {channel :channel
:as m}]]
(if-let [ticker (ticker-of-chan conn channel)]
[tag (assoc m :ticker ticker)]
(let [reason (str "Ticker for channel " channel " not found")]
(log/error reason)
[:drop (-> m
(assoc :tag tag)
(assoc :reason reason))])))
(defmethod -convert-incomming-msg :heartbeat
[conn msg]
(vector
(add-ticker-or-drop conn msg)))
(defn- snapshot->bids-asks [payload]
(let [{:keys [bids asks]}
(group-by (fn [{:keys [price size]}]
(if (neg? size)
:asks
:bids))
payload)
bids
(map (fn [{:keys [price orders size]}]
[(decimal price)
(if (zero? orders)
(decimal 0)
(decimal size))])
bids)
asks
(map (fn [{:keys [price orders size]}]
[(decimal price)
(if (zero? orders)
(decimal 0)
(decimal (- 0 size)))])
asks)]
{:bids bids
:asks asks}))
(defn- update->bids-asks [payload]
(snapshot->bids-asks payload))
#_
(=
(snapshot->bids-asks
[{:price 584.58, :orders 11, :size 65.64632441}
{:price 584.51, :orders 1, :size 0.93194317}
{:price 584.59, :orders 4, :size -23.39216286}
{:price 584.96, :orders 1, :size -7.23746288}
{:price 584.97, :orders 1, :size -12.3}])
'{:bids ([584.58M 65.64632441M]
[584.51M 0.93194317M])
:asks ([584.59M 23.39216286M]
[584.96M 7.23746288M]
[584.97M 12.3M])})
(defmethod -convert-incomming-msg :snapshot
[conn [tag payload]]
(vector
(add-ticker-or-drop
conn
[tag (update
payload
:snapshot snapshot->bids-asks)])))
(defmethod -convert-incomming-msg :update
[conn [_ {update :update
:as m}]]
(vector
(add-ticker-or-drop
conn
[:update
(assoc m :update
(update->bids-asks [update]))])))
(defmethod -convert-incomming-msg :event [conn [_ m]]
(-convert-incomming-event-msg conn m))
;;** - dispatch by event type
(defmulti -convert-incomming-event-msg (fn [conn msg] (::event msg)))
(defmethod -convert-incomming-event-msg "pong"
[conn {ts ::ts cid ::cid :as m}]
(vector
[:pong
(-> m
(assoc :timestamp (timestamp ts))
(assoc :id cid))]))
(defmethod -convert-incomming-event-msg "info"
[conn {event ::event code ::code msg ::msg :as m}]
(let [tag
(case code
20051 :reconnect
20060 :pause
20061 :resume
nil :info
;; else
(do
(log/error
"Received message of type event => " event
" with unrecognized code " code)
:drop))
[orig-tag reason]
(when (= tag :drop)
[:event
(str "Unrecognized code " code
" in message")])
payload
(-> m
(assoc-some :message msg)
(assoc-some :reason reason)
(assoc-some :tag orig-tag))]
(vector
[tag payload])))
(defmethod -convert-incomming-event-msg "subscribed"
[conn {pair ::pair channel ::chanId :as m}]
(let [ticker
(ticker
(->Pair pair))]
(add-chan conn channel ticker)
(log/info "Subscribed to ticker " ticker)
(vector
[:subscribed
(assoc m :ticker ticker)])))
(defmethod -convert-incomming-event-msg "unsubscribed"
[conn {channel ::chanId :as m}]
(vector
(if-let [ticker (ticker-of-chan conn channel)]
(do
(rm-chan conn channel)
(log/info "Unsubscribed ticker " ticker)
[:unsubscribed
(assoc m :ticker ticker)])
(do
(let [reason (str "Ticker for channel " channel " not found")]
(log/error reason)
[:drop
(-> m
(assoc :tag :unsubscribed)
(assoc :reason reason))])))))
(defmethod -convert-incomming-event-msg "error"
[conn {code ::code msg ::msg :as m}]
(let [tag
:error
payload
(-> m
(assoc :message msg)
(assoc :code code))]
(log/error
"Received error code from server:"
payload)
(vector
[tag payload])))
;;* Convert outgoing msg
(defmulti -convert-outgoing-msg (fn [conn [tag _]] tag))
(defmethod -convert-outgoing-msg :ping
[conn [_]]
(json/encode {:event "ping"}))
(defmethod -convert-outgoing-msg :subscribe
[conn [_ ticker]]
(json/encode
{:event "subscribe"
:channel "book"
:symbol (:symbol (product ticker))
:prec "P0"
:freq "F0"}))
(defmethod -convert-outgoing-msg :unsubscribe
[conn [_ ticker]]
(let [channel (chan-of-ticker conn ticker)]
(json/encode
{:event "unsubscribe"
:chanId channel})))
(defmethod -convert-outgoing-msg :default
[conn msg]
(json/encode msg))
;; Conf
;; {
;; event: "conf",
;; flags: FLAGS
;; }
|
[
{
"context": "ey) )) \n\n\n(defn -main [& args]\n (pretty-printer \"Alice\" finder))\n\n",
"end": 202,
"score": 0.9869930744171143,
"start": 197,
"tag": "NAME",
"value": "Alice"
}
] | Pres-DI-Clojure/demos/test3/src/test3/core.clj | cfalguiere/Presentations | 0 | (ns test3.core)
(defn finder [key] (str "value from the db")) ;; very complex finder
(defn pretty-printer [key finder] (str "This is a " (finder key) ))
(defn -main [& args]
(pretty-printer "Alice" finder))
| 53903 | (ns test3.core)
(defn finder [key] (str "value from the db")) ;; very complex finder
(defn pretty-printer [key finder] (str "This is a " (finder key) ))
(defn -main [& args]
(pretty-printer "<NAME>" finder))
| true | (ns test3.core)
(defn finder [key] (str "value from the db")) ;; very complex finder
(defn pretty-printer [key finder] (str "This is a " (finder key) ))
(defn -main [& args]
(pretty-printer "PI:NAME:<NAME>END_PI" finder))
|
[
{
"context": "ryption makes use of random values\r\n(def aes-key \"abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG\")\r\n(def appid \"wx2c2769f8efd9abc2\")\r\n(def sec-msg",
"end": 502,
"score": 0.999721884727478,
"start": 459,
"tag": "KEY",
"value": "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG"
},
{
"context": "\r\n(def appid \"wx2c2769f8efd9abc2\")\r\n(def sec-msg \"1B0w3EEkJGo/5Pc2sd9ZNhcSJKJrbhqcTT4DIh3hqRlRroeD1G8+UCT8RNLZUrm+OArzFmcJNqNhcSvkERnZ+XKE2gLY63KD2hGLKM+WVojzAWEc6DLq2H15r/QWtunLP1YY8u95ktcu9FSBKTC42R8gWUlyh1URB7a5xrigXesazHud17+ioZk9CSw5TlylzuW/EIN1xiEdhi5/j4S4jz4JgS8pQ4rPt9c5b+26qh4Jp94Lwnm2eJb54g5xKBbesyZ0WtdxCzcbh7yvDAn+t6i81Hm/dNOSLDsTsxp3mfnO0iaaGQdVW49Dc/RLzjDSwawK4y8OybDN1YxPALbEAHOKFAa5GBn30vZL9Ka9MRpxdWuAo73jsySRwUHj94Ej1Tuy0uvW7xoz8NM17+8wZGRlgrHVsv5FebaaQR9HhHkvDVRpdtg7janXlUiNPB+qloQaktrUZxk3yAQUvle59oBaVwRitC2e0aS8DC0s1OoJRgCY004tTkMCw6IUPFJgvRgUkVBBk6jg1ES36ZgkgacAMiWEcnmnpwXJ++eN6wnhKM3BXH6guAwy+Nqd4juHG1bLIyNN05kzA/+u3Plz4KVY+OQPxxOyekCgDlKRXhwQpF7d8zYiUqfu1Wsrf9wc\")\r\n(def msg \" <xml><ToUserName><![CDATA[oia2Tjjew",
"end": 1194,
"score": 0.9898781180381775,
"start": 554,
"tag": "KEY",
"value": "1B0w3EEkJGo/5Pc2sd9ZNhcSJKJrbhqcTT4DIh3hqRlRroeD1G8+UCT8RNLZUrm+OArzFmcJNqNhcSvkERnZ+XKE2gLY63KD2hGLKM+WVojzAWEc6DLq2H15r/QWtunLP1YY8u95ktcu9FSBKTC42R8gWUlyh1URB7a5xrigXesazHud17+ioZk9CSw5TlylzuW/EIN1xiEdhi5/j4S4jz4JgS8pQ4rPt9c5b+26qh4Jp94Lwnm2eJb54g5xKBbesyZ0WtdxCzcbh7yvDAn+t6i81Hm/dNOSLDsTsxp3mfnO0iaaGQdVW49Dc/RLzjDSwawK4y8OybDN1YxPALbEAHOKFAa5GBn30vZL9Ka9MRpxdWuAo73jsySRwUHj94Ej1Tuy0uvW7xoz8NM17+8wZGRlgrHVsv5FebaaQR9HhHkvDVRpdtg7janXlUiNPB+qloQaktrUZxk3yAQUvle59oBaVwRitC2e0aS8DC0s1OoJRgCY004tTkMCw6IUPFJgvRgUkVBBk6jg1ES36ZgkgacAMiWEcnmnpwXJ++eN6wnhKM3BXH6guAwy+Nqd4juHG1bLIyNN05kzA/+u3Plz4KVY+OQPxxOyekCgDlKRXhwQpF7d8zYiUqfu1Wsrf9wc"
}
] | test/liu/wx/aes_test.clj | emliunix/wxservice | 0 | (ns liu.wx.aes-test
(:require [clojure.test :refer [deftest is are]]
[liu.wx.util :refer [cat-bytes]]
[liu.wx.aes :as t])
(:import [java.util Arrays]))
;; These are values cited from official sample code of weixin,
;; so the reliability of the code is guranted if decryption functions.
;; However, encryption is not possiblly tested against the official
;; data since encryption makes use of random values
(def aes-key "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG")
(def appid "wx2c2769f8efd9abc2")
(def sec-msg "1B0w3EEkJGo/5Pc2sd9ZNhcSJKJrbhqcTT4DIh3hqRlRroeD1G8+UCT8RNLZUrm+OArzFmcJNqNhcSvkERnZ+XKE2gLY63KD2hGLKM+WVojzAWEc6DLq2H15r/QWtunLP1YY8u95ktcu9FSBKTC42R8gWUlyh1URB7a5xrigXesazHud17+ioZk9CSw5TlylzuW/EIN1xiEdhi5/j4S4jz4JgS8pQ4rPt9c5b+26qh4Jp94Lwnm2eJb54g5xKBbesyZ0WtdxCzcbh7yvDAn+t6i81Hm/dNOSLDsTsxp3mfnO0iaaGQdVW49Dc/RLzjDSwawK4y8OybDN1YxPALbEAHOKFAa5GBn30vZL9Ka9MRpxdWuAo73jsySRwUHj94Ej1Tuy0uvW7xoz8NM17+8wZGRlgrHVsv5FebaaQR9HhHkvDVRpdtg7janXlUiNPB+qloQaktrUZxk3yAQUvle59oBaVwRitC2e0aS8DC0s1OoJRgCY004tTkMCw6IUPFJgvRgUkVBBk6jg1ES36ZgkgacAMiWEcnmnpwXJ++eN6wnhKM3BXH6guAwy+Nqd4juHG1bLIyNN05kzA/+u3Plz4KVY+OQPxxOyekCgDlKRXhwQpF7d8zYiUqfu1Wsrf9wc")
(def msg " <xml><ToUserName><![CDATA[oia2TjjewbmiOUlr6X-1crbLOvLw]]></ToUserName><FromUserName><![CDATA[gh_7f083739789a]]></FromUserName><CreateTime>1407743423</CreateTime><MsgType> <![CDATA[video]]></MsgType><Video><MediaId><![CDATA[eYJ1MbwPRJtOvIEabaxHs7TX2D-HV71s79GUxqdUkjm6Gs2Ed1KF3ulAOA9H1xG0]]></MediaId><Title><![CDATA[testCallBackReplyVideo]]></Title><Descript ion><![CDATA[testCallBackReplyVideo]]></Description></Video></xml>")
(deftest int32-to-nbo-test
(is (Arrays/equals
;; the expected byte array
(into-array Byte/TYPE (map byte [1 2 3 4]))
(t/int32-to-nbo 16909060))))
(deftest nbo-to-int32-test
(is (= 16909060
(t/nbo-to-int32 (byte-array [1 2 3 4])))))
(deftest pkcs7-encode-test
(is (Arrays/equals (byte-array 32 (byte 32))
(t/pkcs7-encode 0))
"pkcs7-encode should return an 32-bytes length array of 32")
(is (Arrays/equals (byte-array 32 (byte 32))
(t/pkcs7-encode 64))
"exact n x 32 length, byte[32] of 32 should be returned.")
(is (Arrays/equals (byte-array 22 (byte 22))
(t/pkcs7-encode 42))))
(deftest pkcs7-decode-test
(is (Arrays/equals
(byte-array 123)
(t/pkcs7-decode (cat-bytes (byte-array 123) (t/pkcs7-encode 123))))))
(deftest random-16bytes-test
(is (= 16
(alength (t/random-16bytes))))
(is (= (type (bytes (byte-array 0)))
(type (t/random-16bytes)))))
;; Test encryption and decryption
;; Since encrypt make use of random 16-len bytes internally,
;; the encrypted msg is undetermined
;; Instead decrypt it and test the equality of the msg decrypted
;; with the original message.
(deftest cryption-test
(is (= msg
(t/decrypt aes-key appid (t/encrypt aes-key appid msg)))))
;; Test decryption functionality
(deftest decrypt-test
(is (= msg
(t/decrypt aes-key appid sec-msg))))
| 82308 | (ns liu.wx.aes-test
(:require [clojure.test :refer [deftest is are]]
[liu.wx.util :refer [cat-bytes]]
[liu.wx.aes :as t])
(:import [java.util Arrays]))
;; These are values cited from official sample code of weixin,
;; so the reliability of the code is guranted if decryption functions.
;; However, encryption is not possiblly tested against the official
;; data since encryption makes use of random values
(def aes-key "<KEY>")
(def appid "wx2c2769f8efd9abc2")
(def sec-msg "<KEY>")
(def msg " <xml><ToUserName><![CDATA[oia2TjjewbmiOUlr6X-1crbLOvLw]]></ToUserName><FromUserName><![CDATA[gh_7f083739789a]]></FromUserName><CreateTime>1407743423</CreateTime><MsgType> <![CDATA[video]]></MsgType><Video><MediaId><![CDATA[eYJ1MbwPRJtOvIEabaxHs7TX2D-HV71s79GUxqdUkjm6Gs2Ed1KF3ulAOA9H1xG0]]></MediaId><Title><![CDATA[testCallBackReplyVideo]]></Title><Descript ion><![CDATA[testCallBackReplyVideo]]></Description></Video></xml>")
(deftest int32-to-nbo-test
(is (Arrays/equals
;; the expected byte array
(into-array Byte/TYPE (map byte [1 2 3 4]))
(t/int32-to-nbo 16909060))))
(deftest nbo-to-int32-test
(is (= 16909060
(t/nbo-to-int32 (byte-array [1 2 3 4])))))
(deftest pkcs7-encode-test
(is (Arrays/equals (byte-array 32 (byte 32))
(t/pkcs7-encode 0))
"pkcs7-encode should return an 32-bytes length array of 32")
(is (Arrays/equals (byte-array 32 (byte 32))
(t/pkcs7-encode 64))
"exact n x 32 length, byte[32] of 32 should be returned.")
(is (Arrays/equals (byte-array 22 (byte 22))
(t/pkcs7-encode 42))))
(deftest pkcs7-decode-test
(is (Arrays/equals
(byte-array 123)
(t/pkcs7-decode (cat-bytes (byte-array 123) (t/pkcs7-encode 123))))))
(deftest random-16bytes-test
(is (= 16
(alength (t/random-16bytes))))
(is (= (type (bytes (byte-array 0)))
(type (t/random-16bytes)))))
;; Test encryption and decryption
;; Since encrypt make use of random 16-len bytes internally,
;; the encrypted msg is undetermined
;; Instead decrypt it and test the equality of the msg decrypted
;; with the original message.
(deftest cryption-test
(is (= msg
(t/decrypt aes-key appid (t/encrypt aes-key appid msg)))))
;; Test decryption functionality
(deftest decrypt-test
(is (= msg
(t/decrypt aes-key appid sec-msg))))
| true | (ns liu.wx.aes-test
(:require [clojure.test :refer [deftest is are]]
[liu.wx.util :refer [cat-bytes]]
[liu.wx.aes :as t])
(:import [java.util Arrays]))
;; These are values cited from official sample code of weixin,
;; so the reliability of the code is guranted if decryption functions.
;; However, encryption is not possiblly tested against the official
;; data since encryption makes use of random values
(def aes-key "PI:KEY:<KEY>END_PI")
(def appid "wx2c2769f8efd9abc2")
(def sec-msg "PI:KEY:<KEY>END_PI")
(def msg " <xml><ToUserName><![CDATA[oia2TjjewbmiOUlr6X-1crbLOvLw]]></ToUserName><FromUserName><![CDATA[gh_7f083739789a]]></FromUserName><CreateTime>1407743423</CreateTime><MsgType> <![CDATA[video]]></MsgType><Video><MediaId><![CDATA[eYJ1MbwPRJtOvIEabaxHs7TX2D-HV71s79GUxqdUkjm6Gs2Ed1KF3ulAOA9H1xG0]]></MediaId><Title><![CDATA[testCallBackReplyVideo]]></Title><Descript ion><![CDATA[testCallBackReplyVideo]]></Description></Video></xml>")
(deftest int32-to-nbo-test
(is (Arrays/equals
;; the expected byte array
(into-array Byte/TYPE (map byte [1 2 3 4]))
(t/int32-to-nbo 16909060))))
(deftest nbo-to-int32-test
(is (= 16909060
(t/nbo-to-int32 (byte-array [1 2 3 4])))))
(deftest pkcs7-encode-test
(is (Arrays/equals (byte-array 32 (byte 32))
(t/pkcs7-encode 0))
"pkcs7-encode should return an 32-bytes length array of 32")
(is (Arrays/equals (byte-array 32 (byte 32))
(t/pkcs7-encode 64))
"exact n x 32 length, byte[32] of 32 should be returned.")
(is (Arrays/equals (byte-array 22 (byte 22))
(t/pkcs7-encode 42))))
(deftest pkcs7-decode-test
(is (Arrays/equals
(byte-array 123)
(t/pkcs7-decode (cat-bytes (byte-array 123) (t/pkcs7-encode 123))))))
(deftest random-16bytes-test
(is (= 16
(alength (t/random-16bytes))))
(is (= (type (bytes (byte-array 0)))
(type (t/random-16bytes)))))
;; Test encryption and decryption
;; Since encrypt make use of random 16-len bytes internally,
;; the encrypted msg is undetermined
;; Instead decrypt it and test the equality of the msg decrypted
;; with the original message.
(deftest cryption-test
(is (= msg
(t/decrypt aes-key appid (t/encrypt aes-key appid msg)))))
;; Test decryption functionality
(deftest decrypt-test
(is (= msg
(t/decrypt aes-key appid sec-msg))))
|
[
{
"context": "\n \"Improved Tracers\" \"Hunter\"])\n (default-challenger))\n (",
"end": 10099,
"score": 0.8016990423202515,
"start": 10098,
"tag": "NAME",
"value": "H"
},
{
"context": "\")\n (prompt-select :contestant (find-card \"Oaktown Renovation\" (:hand (get-contestant))))\n ",
"end": 10897,
"score": 0.638375997543335,
"start": 10893,
"tag": "NAME",
"value": "Oakt"
},
{
"context": "))]\n (discard-from-hand state :challenger \"DaVinci\")\n (is (= contestant-creds (:credit (get-con",
"end": 18763,
"score": 0.6339872479438782,
"start": 18758,
"tag": "NAME",
"value": "Vinci"
},
{
"context": "ontestant)\n (play-from-hand state :challenger \"Inti\")\n (play-from-hand state :challenger \"Caldera\"",
"end": 26470,
"score": 0.980676531791687,
"start": 26466,
"tag": "NAME",
"value": "Inti"
},
{
"context": "er \"Inti\")\n (play-from-hand state :challenger \"Caldera\")\n (take-credits state :challenger)\n (play-",
"end": 26519,
"score": 0.99823397397995,
"start": 26512,
"tag": "NAME",
"value": "Caldera"
},
{
"context": " (is (= 1 (count (:discard (get-challenger)))) \"Caldera discarded\")))\n\n(deftest enhanced-login-protocol\n ",
"end": 26947,
"score": 0.9722785949707031,
"start": 26940,
"tag": "NAME",
"value": "Caldera"
},
{
"context": "Foxfire\" 2)])\n (default-challenger [\"Dyson Mem Chip\" \"Character Carver\"]))\n (take-credits state :c",
"end": 40936,
"score": 0.9803131222724915,
"start": 40922,
"tag": "NAME",
"value": "Dyson Mem Chip"
},
{
"context": "redit 100)\n (play-from-hand state :challenger \"Dyson Mem Chip\")\n (play-from-hand state :challenger \"Characte",
"end": 41096,
"score": 0.6791947484016418,
"start": 41082,
"tag": "NAME",
"value": "Dyson Mem Chip"
},
{
"context": "Mem Chip\")\n (play-from-hand state :challenger \"Character Carver\")\n (take-credits state :challenger)\n (play-",
"end": 41154,
"score": 0.58329838514328,
"start": 41138,
"tag": "NAME",
"value": "Character Carver"
},
{
"context": "d count)) \"Contestant should discard Character Carver from winning Foxfire trace\")))\n\n(deftest hard-hit",
"end": 41751,
"score": 0.6093780994415283,
"start": 41748,
"tag": "NAME",
"value": "ver"
},
{
"context": " (default-challenger [\"Daily Casts\" \"Dyson Mem Chip\"]))\n (play-from-hand state :contestant \"Dedi",
"end": 45244,
"score": 0.9969019889831543,
"start": 45230,
"tag": "NAME",
"value": "Dyson Mem Chip"
},
{
"context": " Casts\")\n (play-from-hand state :challenger \"Dyson Mem Chip\")\n (run-empty-locale state :party1)\n (p",
"end": 45525,
"score": 0.9988431930541992,
"start": 45511,
"tag": "NAME",
"value": "Dyson Mem Chip"
},
{
"context": " (default-challenger [\"Daily Casts\" \"Dyson Mem Chip\"]))\n (play-from-hand state :contestant \"Dedi",
"end": 46338,
"score": 0.9648164510726929,
"start": 46324,
"tag": "NAME",
"value": "Dyson Mem Chip"
},
{
"context": " Casts\")\n (play-from-hand state :challenger \"Dyson Mem Chip\")\n (run-empty-locale state :party1)\n (p",
"end": 46619,
"score": 0.9194452166557312,
"start": 46605,
"tag": "NAME",
"value": "Dyson Mem Chip"
},
{
"context": " (default-challenger [(qty \"Cache\" 2) \"Fall Guy\" \"Mr. Li\"]))\n (take-credits state :contestant)\n (pla",
"end": 49124,
"score": 0.522562563419342,
"start": 49118,
"tag": "NAME",
"value": "Mr. Li"
},
{
"context": "ache\")\n (prompt-select :challenger (find-card \"Mr. Li\" (:hand (get-challenger))))\n (is (empty? (:pro",
"end": 49440,
"score": 0.5143469572067261,
"start": 49434,
"tag": "NAME",
"value": "Mr. Li"
},
{
"context": "vealed\")\n (play-from-hand state :contestant \"Mushin No Shin\")\n (prompt-select :contestant (find-card \"Pr",
"end": 60788,
"score": 0.9167994856834412,
"start": 60774,
"tag": "NAME",
"value": "Mushin No Shin"
},
{
"context": "r \"Cache\")\n (play-from-hand state :challenger \"Grimoire\")\n (run-empty-locale state :archives)\n (tak",
"end": 67306,
"score": 0.8989879488945007,
"start": 67298,
"tag": "NAME",
"value": "Grimoire"
},
{
"context": "d Overload\"])\n (default-challenger [\"Dyson Mem Chip\"]))\n (take-credits state :contestant)",
"end": 68337,
"score": 0.7503408193588257,
"start": 68332,
"tag": "NAME",
"value": "Dyson"
},
{
"context": "ontestant)\n (play-from-hand state :challenger \"Dyson Mem Chip\")\n (run-empty-locale state :rd)\n (",
"end": 68432,
"score": 0.7281025648117065,
"start": 68427,
"tag": "NAME",
"value": "Dyson"
},
{
"context": " (is (= 1 (-> (get-challenger) :discard count)) \"Dyson Mem Chip should be in heap after Challenger lo",
"end": 68750,
"score": 0.7860421538352966,
"start": 68748,
"tag": "NAME",
"value": "Dy"
},
{
"context": "\" \"Adonis Campaign\"\n \"Quandary\" \"Jackson Howard\" \"Global Food Initiative\"])\n ",
"end": 69026,
"score": 0.9992659091949463,
"start": 69018,
"tag": "NAME",
"value": "Quandary"
},
{
"context": "ampaign\"\n \"Quandary\" \"Jackson Howard\" \"Global Food Initiative\"])\n (defaul",
"end": 69043,
"score": 0.9996355175971985,
"start": 69029,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "nition\")\n (prompt-card :contestant (find-card \"Caprcharacter Nisei\" (:deck (get-contestant))))\n (prompt-card :con",
"end": 69277,
"score": 0.9249592423439026,
"start": 69258,
"tag": "NAME",
"value": "Caprcharacter Nisei"
},
{
"context": "tant))))\n (prompt-card :contestant (find-card \"Quandary\" (:deck (get-contestant))))\n (prompt-card :con",
"end": 69440,
"score": 0.9974876046180725,
"start": 69432,
"tag": "NAME",
"value": "Quandary"
},
{
"context": "tant))))\n (prompt-card :contestant (find-card \"Jackson Howard\" (:deck (get-contestant))))\n (prompt-card :con",
"end": 69524,
"score": 0.9994956254959106,
"start": 69510,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "tant))))\n (prompt-card :contestant (find-card \"Jackson Howard\" (:deck (get-contestant))))\n (prompt-card :con",
"end": 69862,
"score": 0.999470055103302,
"start": 69848,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "tant))))\n (prompt-card :contestant (find-card \"Quandary\" (:deck (get-contestant))))\n (prompt-card :con",
"end": 69940,
"score": 0.990009069442749,
"start": 69932,
"tag": "NAME",
"value": "Quandary"
},
{
"context": " (prompt-choice :contestant \"Done\")\n (is (= \"Caprcharacter Nisei\" (:title (first (:deck (get-contestant))))))\n ",
"end": 70242,
"score": 0.9015263915061951,
"start": 70223,
"tag": "NAME",
"value": "Caprcharacter Nisei"
},
{
"context": "ond (:deck (get-contestant))))))\n (is (= \"Quandary\" (:title (second (rest (:deck (get-contestant))))",
"end": 70382,
"score": 0.5983203649520874,
"start": 70379,
"tag": "NAME",
"value": "ary"
},
{
"context": "d (rest (:deck (get-contestant)))))))\n (is (= \"Jackson Howard\" (:title (second (rest (rest (:deck (get-contesta",
"end": 70462,
"score": 0.9994720816612244,
"start": 70448,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "rompt-choice :contestant \"New party\")\n (is (= \"Caprcharacter Nisei\" (:title (get-content state :party1 0)))\n \"C",
"end": 74518,
"score": 0.8611037731170654,
"start": 74499,
"tag": "NAME",
"value": "Caprcharacter Nisei"
},
{
"context": "(:title (get-content state :party1 0)))\n \"Caprcharacter Nisei placed by Psychokinesis\")\n ;; Test placi",
"end": 74580,
"score": 0.6770492792129517,
"start": 74570,
"tag": "NAME",
"value": "rcharacter"
},
{
"context": "nvolving Subliminal being reshuffled into R&D with Jackson\"\n (do-game\n (new-game (default-contestant",
"end": 103268,
"score": 0.9531055688858032,
"start": 103261,
"tag": "NAME",
"value": "Jackson"
},
{
"context": "game (default-contestant [\"Subliminal Messaging\" \"Jackson Howard\"])\n (default-challenger))\n (p",
"end": 103358,
"score": 0.9997444152832031,
"start": 103344,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "saging\")\n (play-from-hand state :contestant \"Jackson Howard\" \"New party\")\n (take-credits state :contesta",
"end": 103519,
"score": 0.9997329711914062,
"start": 103505,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "\" 4)])\n (default-challenger [(qty \"Jarogniew Mercs\" 2) (qty \"Same Old Thing\" 2)]))\n (letfn [(re",
"end": 116745,
"score": 0.9785555005073547,
"start": 116730,
"tag": "NAME",
"value": "Jarogniew Mercs"
},
{
"context": "hing\")\n (play-from-hand state :challenger \"Jarogniew Mercs\")\n (take-credits state :challenger)\n ",
"end": 117011,
"score": 0.999102771282196,
"start": 116996,
"tag": "NAME",
"value": "Jarogniew Mercs"
},
{
"context": "tant \"The All-Seeing I\")\n (is (= 1 (res)) \"Jarogniew Mercs still placed\")\n (play-from-han",
"end": 117202,
"score": 0.796649694442749,
"start": 117199,
"tag": "NAME",
"value": "Jar"
},
{
"context": "stant)\n (play-from-hand state :challenger \"Jarogniew Mercs\") ;; Testing if order matters\n (play-from-",
"end": 117449,
"score": 0.9982425570487976,
"start": 117434,
"tag": "NAME",
"value": "Jarogniew Mercs"
},
{
"context": "tant \"The All-Seeing I\")\n (is (= 1 (res)) \"Jarogniew Mercs still placed\")\n (play-from-han",
"end": 117728,
"score": 0.6428014039993286,
"start": 117725,
"tag": "NAME",
"value": "Jar"
},
{
"context": ":credit 5)\n (play-from-hand state :challenger \"Desperado\")\n (play-from-hand state :challenger \"Corroder",
"end": 118487,
"score": 0.7899467349052429,
"start": 118478,
"tag": "NAME",
"value": "Desperado"
}
] | test/clj/game_test/cards/operations.clj | SylvanSign/cardnum | 0 | (ns game-test.cards.operations
(:require [game.core :as core]
[game-test.core :refer :all]
[game-test.utils :refer :all]
[game-test.macros :refer :all]
[clojure.test :refer :all]))
(use-fixtures :once load-all-cards (partial reset-card-defs "operations"))
(deftest ^{:card-title "24/7-news-cycle"}
twenty-four-seven-news
;; 24/7 News Cycle
(testing "Breaking News interaction"
(do-game
(new-game (default-contestant [(qty "Breaking News" 2) (qty "24/7 News Cycle" 3)])
(default-challenger))
(play-from-hand state :contestant "Breaking News" "New party")
(play-from-hand state :contestant "Breaking News" "New party")
(let [ag1 (get-content state :party1 0)
ag2 (get-content state :party2 0)]
(score-agenda state :contestant ag1)
(score-agenda state :contestant ag2)
(take-credits state :contestant)
(is (zero? (:tag (get-challenger)))) ; tags cleared
(take-credits state :challenger)
(play-from-hand state :contestant "24/7 News Cycle")
(prompt-select :contestant (find-card "Breaking News" (:scored (get-contestant))))
(is (= 1 (:agenda-point (get-contestant))) "Forfeited Breaking News")
(prompt-select :contestant (find-card "Breaking News" (:scored (get-contestant))))
(is (= 2 (:tag (get-challenger))) "Challenger given 2 tags")
(take-credits state :contestant 2)
(is (= 2 (:tag (get-challenger))) "Tags remained after Contestant ended turn"))))
(testing "Posted Bounty interaction -- Issue #1043"
(do-game
(new-game (default-contestant [(qty "Posted Bounty" 2) (qty "24/7 News Cycle" 3)])
(default-challenger))
(play-from-hand state :contestant "Posted Bounty" "New party")
(play-from-hand state :contestant "Posted Bounty" "New party")
(let [ag1 (get-content state :party1 0)
ag2 (get-content state :party2 0)]
(score-agenda state :contestant ag1)
(prompt-choice :contestant "No")
(score-agenda state :contestant ag2)
(prompt-choice :contestant "No")
(play-from-hand state :contestant "24/7 News Cycle")
(prompt-select :contestant (find-card "Posted Bounty" (:scored (get-contestant))))
(is (= 1 (:agenda-point (get-contestant))) "Forfeited Posted Bounty")
(prompt-select :contestant (find-card "Posted Bounty" (:scored (get-contestant))))
(prompt-choice :contestant "Yes") ; "Forfeit Posted Bounty to give 1 tag?"
(is (= 1 (:tag (get-challenger))) "Challenger given 1 tag")
(is (= 1 (:bad-publicity (get-contestant))) "Contestant has 1 bad publicity")
(is (zero? (:agenda-point (get-contestant))) "Forfeited Posted Bounty to 24/7 News Cycle"))))
(testing "Swapped agendas are able to be used. #1555"
(do-game
(new-game (default-contestant ["24/7 News Cycle" "Chronos Project"
"Philotic Entanglement" "Profiteering"])
(default-challenger [(qty "Turntable" 3)]))
(score-agenda state :contestant (find-card "Chronos Project" (:hand (get-contestant))))
(score-agenda state :contestant (find-card "Philotic Entanglement" (:hand (get-contestant))))
(take-credits state :contestant)
(play-from-hand state :challenger "Turntable")
(core/steal state :challenger (find-card "Profiteering" (:hand (get-contestant))))
(prompt-choice :challenger "Yes")
(prompt-select :challenger (find-card "Philotic Entanglement" (:scored (get-contestant))))
(is (= 2 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
(take-credits state :challenger)
(play-from-hand state :contestant "24/7 News Cycle")
(prompt-select :contestant (find-card "Chronos Project" (:scored (get-contestant))))
(is (= "Chronos Project" (:title (first (:rfg (get-contestant))))))
;; shouldn't work on an agenda in the Challenger's scored area
(is (= 2 (count (:hand (get-challenger)))))
(prompt-select :contestant (find-card "Philotic Entanglement" (:scored (get-challenger))))
(is (= 2 (count (:hand (get-challenger)))))
;; resolve 'when scored' ability on swapped Profiteering
(is (= 8 (:credit (get-contestant))))
(prompt-select :contestant (find-card "Profiteering" (:scored (get-contestant))))
(prompt-choice :contestant "3")
(is (= 1 (:agenda-point (get-contestant))))
(is (= 3 (:bad-publicity (get-contestant))))
(is (= 23 (:credit (get-contestant))) "Gained 15 credits"))))
(deftest accelerated-diagnostics
;; Accelerated Diagnostics - Interaction with prompt effects, like Shipment from SanSan
(testing "Basic test"
(do-game
(new-game (default-contestant ["Accelerated Diagnostics" "Cerebral Overwriter" "Shipment from SanSan"
"Hedge Fund" "Back Channels"])
(default-challenger))
(starting-hand state :contestant ["Accelerated Diagnostics" "Cerebral Overwriter"])
(play-from-hand state :contestant "Cerebral Overwriter" "New party")
(core/gain state :contestant :credit 1)
(play-from-hand state :contestant "Accelerated Diagnostics")
(let [playarea (get-in @state [:contestant :play-area])
hf (find-card "Hedge Fund" playarea)
ss (find-card "Shipment from SanSan" playarea)
bc (find-card "Back Channels" playarea)
co (get-content state :party1 0)]
(is (= 3 (count playarea)) "3 cards in play area")
(prompt-select :contestant ss)
(prompt-choice :contestant "2")
(prompt-select :contestant co)
(is (= 2 (get-counters (refresh co) :advancement)) "Cerebral Overwriter gained 2 advancements")
(prompt-select :contestant hf)
(is (= 9 (:credit (get-contestant))) "Contestant gained credits from Hedge Fund")
(prompt-select :contestant bc)
(prompt-select :contestant (refresh co))
(is (= 15 (:credit (get-contestant))) "Contestant gained 6 credits for Back Channels"))))
(testing "Interaction with Current"
(do-game
(new-game (default-contestant ["Accelerated Diagnostics" "Cerebral Overwriter"
"Enhanced Login Protocol" "Shipment from SanSan"
"Hedge Fund"])
(default-challenger))
(starting-hand state :contestant ["Accelerated Diagnostics" "Cerebral Overwriter"])
(play-from-hand state :contestant "Cerebral Overwriter" "New party")
(core/gain state :contestant :credit 3)
(play-from-hand state :contestant "Accelerated Diagnostics")
(let [playarea (get-in @state [:contestant :play-area])
hf (find-card "Hedge Fund" playarea)
ss (find-card "Shipment from SanSan" playarea)
elp (find-card "Enhanced Login Protocol" playarea)
co (get-content state :party1 0)]
(is (= 3 (count playarea)) "3 cards in play area")
(prompt-select :contestant elp)
(is (= "Enhanced Login Protocol" (:title (first (get-in @state [:contestant :current]))))
"Enhanced Login Protocol active in Current area")
(prompt-select :contestant ss)
(prompt-choice :contestant "2")
(prompt-select :contestant co)
(is (= 2 (get-counters (refresh co) :advancement)) "Cerebral Overwriter gained 2 advancements")
(prompt-select :contestant hf)
(is (= 9 (:credit (get-contestant))) "Contestant gained credits from Hedge Fund")))))
(deftest an-offer-you-can't-refuse
;; An Offer You Can't Refuse - exact card added to score area, not the last discarded one
(do-game
(new-game (default-contestant ["Celebrity Gift" "An Offer You Can't Refuse"])
(default-challenger))
(play-from-hand state :contestant "An Offer You Can't Refuse")
(prompt-choice :contestant "R&D")
(core/move state :contestant (find-card "Celebrity Gift" (:hand (get-contestant))) :discard)
(is (= 2 (count (:discard (get-contestant)))))
(prompt-choice :challenger "No")
(is (= 1 (:agenda-point (get-contestant))) "An Offer the Challenger refused")
(is (= 1 (count (:scored (get-contestant)))))
(is (find-card "An Offer You Can't Refuse" (:scored (get-contestant))))
(is (= 1 (count (:discard (get-contestant)))))
(is (find-card "Celebrity Gift" (:discard (get-contestant))))))
(deftest big-brother
;; Big Brother - Give the Challenger 2 tags if already tagged
(do-game
(new-game (default-contestant ["Big Brother"])
(default-challenger))
(play-from-hand state :contestant "Big Brother")
(is (= 1 (count (:hand (get-contestant)))) "Card not played because Challenger has no tags")
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "Big Brother")
(is (= 3 (:tag (get-challenger))) "Challenger gained 2 tags")))
(deftest biotic-labor
;; Biotic Labor - Gain 2 clicks
(do-game
(new-game (default-contestant ["Biotic Labor"])
(default-challenger))
(play-from-hand state :contestant "Biotic Labor")
(is (= 1 (:credit (get-contestant))))
(is (= 4 (:click (get-contestant))) "Spent 1 click to gain 2 additional clicks")))
(deftest blue-level-clearance
;; Blue Level Clearance - Gain 5 credits and draw 2 cards
(do-game
(new-game (default-contestant [(qty "Blue Level Clearance" 3)
(qty "Hedge Fund" 3)
(qty "Sweeps Week" 2)])
(default-challenger))
(play-from-hand state :contestant "Blue Level Clearance")
(is (= 8 (:credit (get-contestant))) "Gained 5 credits")
(is (= 1 (:click (get-contestant))))
(is (= 7 (count (:hand (get-contestant)))) "Drew 2 cards")))
(deftest casting-call
;; Casting Call - Only do card-init on the Public agendas. Issue #1128
(do-game
(new-game (default-contestant [(qty "Casting Call" 2) "Oaktown Renovation"
"Improved Tracers" "Hunter"])
(default-challenger))
(core/gain state :contestant :click 1)
(play-from-hand state :contestant "Hunter" "HQ")
(let [hunter (get-character state :hq 0)]
(core/reveal state :contestant hunter)
(is (= 4 (:current-strength (refresh hunter))))
(play-from-hand state :contestant "Casting Call")
(prompt-select :contestant (find-card "Improved Tracers" (:hand (get-contestant))))
(prompt-choice :contestant "New party")
(let [imptrac (get-content state :party1 0)]
(is (:revealed (refresh imptrac)) "Improved Tracers is faceup")
(is (= 4 (:current-strength (refresh hunter))) "Hunter hasn't gained strength")
(play-from-hand state :contestant "Casting Call")
(prompt-select :contestant (find-card "Oaktown Renovation" (:hand (get-contestant))))
(prompt-choice :contestant "New party")
(let [oak (get-content state :party2 0)]
(core/advance state :contestant {:card (refresh oak)})
(is (= 5 (:credit (get-contestant))) "Events on Public agenda work; gained 2 credits from advancing")
(take-credits state :contestant)
(run-empty-locale state "Locale 2")
(prompt-select :challenger oak)
(prompt-choice :challenger "Steal")
(is (= 2 (:tag (get-challenger))) "Challenger took 2 tags from accessing agenda with Casting Call hosted on it"))))))
(deftest cerebral-cast
;; Cerebral Cast
(testing "Challenger wins"
(do-game
(new-game (default-contestant ["Cerebral Cast"])
(default-challenger))
(play-from-hand state :contestant "Cerebral Cast")
(is (= 3 (:click (get-contestant))) "Cerebral Cast precondition not met; card not played")
(take-credits state :contestant)
(run-empty-locale state "Archives")
(take-credits state :challenger)
(play-from-hand state :contestant "Cerebral Cast")
(prompt-choice :contestant "0 [Credits]")
(prompt-choice :challenger "0 [Credits]")
(is (zero? (count (:discard (get-challenger)))) "Challenger took no damage")
(is (zero? (:tag (get-challenger))) "Challenger took no tags")))
(testing "Contestant wins"
(do-game
(new-game (default-contestant [(qty "Cerebral Cast" 2)])
(default-challenger))
(take-credits state :contestant)
(run-empty-locale state "Archives")
(take-credits state :challenger)
(play-from-hand state :contestant "Cerebral Cast")
(prompt-choice :contestant "0 [Credits]")
(prompt-choice :challenger "1 [Credits]")
(prompt-choice :challenger "1 brain damage")
(is (= 1 (count (:discard (get-challenger)))) "Challenger took a brain damage")
(is (zero? (:tag (get-challenger))) "Challenger took no tags from brain damage choice")
(play-from-hand state :contestant "Cerebral Cast")
(prompt-choice :contestant "0 [Credits]")
(prompt-choice :challenger "1 [Credits]")
(prompt-choice :challenger "1 tag")
(is (= 1 (count (:discard (get-challenger)))) "Challenger took no additional damage")
(is (= 1 (:tag (get-challenger))) "Challenger took a tag from Cerebral Cast choice"))))
(deftest cerebral-static
;; Cerebral Static
(testing "vs Chaos Theory"
(do-game
(new-game (default-contestant ["Cerebral Static" "Lag Time"])
(make-deck "Chaos Theory: Wünderkind" [(qty "Sure Gamble" 3)]))
(is (= 5 (core/available-mu state)) "CT starts with 5 memory")
(play-from-hand state :contestant "Cerebral Static")
(is (= 4 (core/available-mu state)) "Cerebral Static causes CT to have 4 memory")
(play-from-hand state :contestant "Lag Time")
(is (= 5 (core/available-mu state)) "CT 5 memory restored"))))
(deftest closed-accounts
;; Closed Accounts - Play if Challenger is tagged to make Challenger lose all credits
(do-game
(new-game (default-contestant ["Closed Accounts"])
(default-challenger))
(play-from-hand state :contestant "Closed Accounts")
(is (and (= 3 (:click (get-contestant)))
(= 5 (:credit (get-challenger))))
"Closed Accounts precondition not met; card not played")
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "Closed Accounts")
(is (zero? (:credit (get-challenger))) "Challenger lost all credits")))
(deftest commercialization
;; Commercialization
(testing "Single advancement token"
(do-game
(new-game (default-contestant ["Commercialization"
"Character Wall"])
(default-challenger))
(play-from-hand state :contestant "Character Wall" "HQ")
(core/add-counter state :contestant (refresh (get-character state :hq 0)) :advancement 1)
(play-from-hand state :contestant "Commercialization")
(prompt-select :contestant (refresh (get-character state :hq 0)))
(is (= 6 (:credit (get-contestant))) "Gained 1 for single advanced character from Commercialization")))
(testing "Two advancement tokens"
(do-game
(new-game (default-contestant ["Commercialization"
"Character Wall"])
(default-challenger))
(play-from-hand state :contestant "Character Wall" "HQ")
(core/add-counter state :contestant (refresh (get-character state :hq 0)) :advancement 2)
(play-from-hand state :contestant "Commercialization")
(prompt-select :contestant (refresh (get-character state :hq 0)))
(is (= 7 (:credit (get-contestant))) "Gained 2 for double advanced character from Commercialization"))))
(deftest consulting-visit
;; Consulting Visit - Only show single copies of operations contestant can afford as choices. Play chosen operation
(testing "Basic test"
(do-game
(new-game (default-contestant ["Consulting Visit"
(qty "Beanstalk Royalties" 2)
"Green Level Clearance"
"Breaking News"
"Hedge Fund"])
(default-challenger))
(is (= 5 (:credit (get-contestant))))
(starting-hand state :contestant ["Consulting Visit"])
(play-from-hand state :contestant "Consulting Visit")
(let [get-prompt (fn [] (first (#(get-in @state [:contestant :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-card :contestant (find-card "Beanstalk Royalties" (:deck (get-contestant))))
(is (= 6 (:credit (get-contestant)))))))
(testing "Works properly when played with Mumbad City Hall"
(do-game
(new-game (default-contestant ["Mumbad City Hall"
"Beanstalk Royalties"
"Green Level Clearance"
"Breaking News"
"Hedge Fund"
"Consulting Visit"
"Mumba Temple"])
(default-challenger))
(is (= 5 (:credit (get-contestant))))
(starting-hand state :contestant ["Mumbad City Hall"])
(play-from-hand state :contestant "Mumbad City Hall" "New party")
(let [hall (get-content state :party1 0)
get-prompt (fn [] (first (#(get-in @state [:contestant :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(card-ability state :contestant hall 0)
(is (= (list "Consulting Visit" "Mumba Temple" nil) (prompt-names)))
(prompt-card :contestant (find-card "Consulting Visit" (:deck (get-contestant))))
(is (= 3 (:credit (get-contestant))))
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-card :contestant (find-card "Green Level Clearance" (:deck (get-contestant))))
(is (= 5 (:credit (get-contestant))))))))
(deftest death-and-taxes
;; Death and Taxes gain credit on challenger place, challenger discard placed card
;; Also regression test for #3160
(do-game
(new-game (default-contestant ["Death and Taxes" "PAD Campaign"])
(default-challenger ["Aumakua" "DaVinci" "Fall Guy"]))
(play-from-hand state :contestant "Death and Taxes")
(is (= (- 5 2) (:credit (get-contestant))) "Contestant paid 2 to play Death and Taxes")
(play-from-hand state :contestant "PAD Campaign" "New party")
(take-credits state :contestant)
(let [contestant-creds (:credit (get-contestant))]
(discard-from-hand state :challenger "DaVinci")
(is (= contestant-creds (:credit (get-contestant))) "Contestant did not gain credit when challenger discards / discards from hand")
(play-from-hand state :challenger "Aumakua")
(is (= (+ 1 contestant-creds) (:credit (get-contestant))) "Contestant gained 1 when challenger placed Aumakua")
(play-from-hand state :challenger "Fall Guy")
(is (= (+ 2 contestant-creds) (:credit (get-contestant))) "Contestant gained 1 when challenger placed Fall Guy")
(card-ability state :challenger (get-radicle state 0) 1)
(is (= (+ 3 contestant-creds) (:credit (get-contestant))) "Contestant gained 1 when challenger discarded Fall Guy")
(run-empty-locale state :party1)
(prompt-choice-partial :challenger "Pay") ;; Challenger discards PAD Campaign
(is (= (+ 4 contestant-creds) (:credit (get-contestant))) "Contestant gained 1 when challenger discarded PAD Campaign"))))
(deftest defective-brainchips
;; Defective Brainchips - Do 1 add'l brain damage the first time Challenger takes some each turn
(do-game
(new-game (default-contestant ["Defective Brainchips" "Viktor 1.0"])
(default-challenger [(qty "Sure Gamble" 2) (qty "Shiv" 2)]))
(play-from-hand state :contestant "Defective Brainchips")
(play-from-hand state :contestant "Viktor 1.0" "HQ")
(take-credits state :contestant)
(run-on state :hq)
(let [vik (get-character state :hq 0)]
(core/reveal state :contestant vik)
(card-subroutine state :contestant vik 0)
(is (= 2 (count (:discard (get-challenger)))) "2 cards lost to brain damage")
(is (= 2 (:brain-damage (get-challenger))) "Brainchips dealt 1 additional brain dmg")
(card-subroutine state :contestant vik 0)
(is (= 3 (count (:discard (get-challenger)))) "2 cards lost to brain damage")
(is (= 3 (:brain-damage (get-challenger))) "Brainchips didn't do additional brain dmg"))))
(deftest distract-the-masses
(do-game
(new-game (default-contestant [(qty "Distract the Masses" 2) (qty "Hedge Fund" 3)])
(default-challenger))
(starting-hand state :contestant ["Hedge Fund" "Hedge Fund" "Hedge Fund" "Distract the Masses" "Distract the Masses"])
(play-from-hand state :contestant "Distract the Masses")
(prompt-select :contestant (first (:hand (get-contestant))))
(prompt-select :contestant (first (next (:hand (get-contestant)))))
(prompt-select :contestant (first (:discard (get-contestant))))
(prompt-choice :contestant "Done")
(is (= 1 (count (:discard (get-contestant)))) "1 card still discarded")
(is (= 1 (count (:deck (get-contestant)))) "1 card shuffled into R&D")
(is (= 1 (count (:rfg (get-contestant)))) "Distract the Masses removed from game")
(is (= 7 (:credit (get-challenger))) "Challenger gained 2 credits")
(play-from-hand state :contestant "Distract the Masses")
(prompt-select :contestant (first (:hand (get-contestant))))
(prompt-choice :contestant "Done")
(prompt-select :contestant (first (:discard (get-contestant))))
(prompt-select :contestant (first (next (:discard (get-contestant)))))
(is (zero? (count (:discard (get-contestant)))) "No cards left in archives")
(is (= 3 (count (:deck (get-contestant)))) "2 more cards shuffled into R&D")
(is (= 2 (count (:rfg (get-contestant)))) "Distract the Masses removed from game")
(is (= 9 (:credit (get-challenger))) "Challenger gained 2 credits")))
(deftest diversified-portfolio
(do-game
(new-game (default-contestant ["Diversified Portfolio"
"Paper Wall"
(qty "PAD Campaign" 3)])
(default-challenger))
(core/gain state :contestant :click 2)
(play-from-hand state :contestant "Paper Wall" "New party")
(play-from-hand state :contestant "PAD Campaign" "New party")
(play-from-hand state :contestant "PAD Campaign" "New party")
(play-from-hand state :contestant "PAD Campaign" "New party")
(play-from-hand state :contestant "Diversified Portfolio")
(is (= 7 (:credit (get-contestant))) "Ignored party with Character but no locale contents")))
(deftest door-to-door
;; Door to Door
(do-game
(new-game (default-contestant ["Door to Door"])
(default-challenger))
(play-from-hand state :contestant "Door to Door")
(take-credits state :contestant)
(is (zero? (:tag (get-challenger))) "Challenger should start with 0 tags")
(is (= 3 (-> (get-challenger) :hand count)) "Challenger should start with 3 cards in hand")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger should gain 1 tag from Door to Door")
(is (= 3 (-> (get-challenger) :hand count)) "Challenger should start with 3 cards in hand")
(take-credits state :challenger)
(take-credits state :contestant)
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger should still have 1 tag")
(is (= 2 (-> (get-challenger) :hand count)) "Challenger should take 1 meat damage from Door to Door")))
(deftest economic-warfare
;; Economic Warfare - If successful run last turn, make the challenger lose 4 credits if able
(do-game
(new-game (default-contestant [(qty "Economic Warfare" 3)])
(default-challenger))
(play-from-hand state :contestant "Economic Warfare")
(is (= 5 (:credit (get-challenger))) "Challenger has 5 credits")
(is (= 3 (count (:hand (get-contestant)))) "Contestant still has 3 cards")
(take-credits state :contestant)
(run-on state :archives)
(run-successful state)
(take-credits state :challenger)
(play-from-hand state :contestant "Economic Warfare")
(is (= 4 (:credit (get-challenger))) "Challenger has 4 credits")
(play-from-hand state :contestant "Economic Warfare")
(is (zero? (:credit (get-challenger))) "Challenger has 0 credits")
(take-credits state :contestant)
(run-on state :archives)
(take-credits state :challenger)
(play-from-hand state :contestant "Economic Warfare")
(is (= 3 (:credit (get-challenger))) "Challenger has 3 credits")))
(deftest election-day
(do-game
(new-game (default-contestant [(qty "Election Day" 7)])
(default-challenger))
(is (= 6 (count (:hand (get-contestant)))) "Contestant starts with 5 + 1 cards")
(core/move state :contestant (find-card "Election Day" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Election Day" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Election Day" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Election Day" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Election Day" (:hand (get-contestant))) :deck)
(play-from-hand state :contestant "Election Day")
(is (= 1 (count (:hand (get-contestant)))) "Could not play Election Day")
(take-credits state :contestant)
(take-credits state :challenger)
(is (= 2 (count (:hand (get-contestant)))) "Contestant has now 1 + 1 cards before Election Day")
(play-from-hand state :contestant "Election Day")
(is (= 5 (count (:hand (get-contestant)))) "Contestant has now 5 cards due to Election Day")))
(deftest enforcing-loyalty
;; Enforcing Loyalty - Win trace to discard placed card not of Challenger's faction
(do-game
(new-game (default-contestant [(qty "Enforcing Loyalty" 2)])
(make-deck "Chaos Theory: Wünderkind" ["Inti" "Caldera"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Inti")
(play-from-hand state :challenger "Caldera")
(take-credits state :challenger)
(play-from-hand state :contestant "Enforcing Loyalty")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-resource state 0))
(is (empty? (:discard (get-challenger))) "Can't target Inti; matches Challenger faction")
(prompt-select :contestant (get-radicle state 0))
(is (= 1 (count (:discard (get-challenger)))) "Caldera discarded")))
(deftest enhanced-login-protocol
;; Enhanced Login Protocol
(testing "First click run each turn costs an additional click"
(do-game
(new-game (default-contestant ["Enhanced Login Protocol"])
(default-challenger ["Employee Strike"]))
(play-from-hand state :contestant "Enhanced Login Protocol")
(take-credits state :contestant)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-challenger))) "Challenger spends 1 additional click to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger doesn't spend 1 additional click to make the second run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(take-credits state :challenger 3)
(is (= 1 (:click (get-challenger))) "Challenger has 1 click")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 1 (:click (get-challenger))) "Challenger has 1 click")
(take-credits state :challenger)
(take-credits state :contestant)
(play-from-hand state :challenger "Employee Strike")
(is (= 3 (:click (get-challenger))) "Challenger has 3 clicks")
(run-on state :archives)
(is (= 2 (:click (get-challenger))) "Challenger doesn't spend 1 additional click to make a run")))
(testing "Card ability runs don't cost additional clicks"
(do-game
(new-game (default-contestant ["Enhanced Login Protocol"])
(default-challenger ["Sneakdoor Beta"]))
(play-from-hand state :contestant "Enhanced Login Protocol")
(take-credits state :contestant)
(play-from-hand state :challenger "Sneakdoor Beta")
(take-credits state :challenger)
(take-credits state :contestant)
(is (= 4 (:click (get-challenger))) "Challenger has 2 clicks")
(let [sneakdoor (get-resource state 0)]
(card-ability state :challenger sneakdoor 0)
(is (= 3 (:click (get-challenger))) "Challenger doesn't spend 1 additional click to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger spends 1 additional click to make a run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-challenger))) "Challenger spends 1 additional click to make a run"))))
(testing "with New Angeles Sol, Enhanced Login Protocol discarded and replaced on steal doesn't double remove penalty"
(do-game
(new-game
(make-deck "New Angeles Sol: Your News" ["Enhanced Login Protocol" "Breaking News"])
(default-challenger))
(play-from-hand state :contestant "Breaking News" "New party")
(play-from-hand state :contestant "Enhanced Login Protocol")
(take-credits state :contestant)
(run-on state :party1)
(run-successful state)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Enhanced Login Protocol" (:discard (get-contestant))))
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger has 1 click")))
(testing "Run event don't cost additional clicks"
(do-game
(new-game (default-contestant ["Enhanced Login Protocol"])
(default-challenger ["Out of the Ashes"]))
(play-from-hand state :contestant "Enhanced Login Protocol")
(take-credits state :contestant)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(play-from-hand state :challenger "Out of the Ashes")
(prompt-choice :challenger "Archives")
(is (= 3 (:click (get-challenger))) "Challenger doesn't spend 1 additional click to run with a run event")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger spends 1 additional click to make a run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(prompt-choice :challenger "No") ; Out of the Ashes prompt
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-challenger))) "Challenger spends 1 additional click to make a run")))
(testing "Works when played on the challenger's turn"
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
["Enhanced Login Protocol"
"Breaking News"])
(default-challenger ["Hades Shard"]))
(discard-from-hand state :contestant "Breaking News")
(take-credits state :contestant)
(core/gain state :challenger :credit 2)
(play-from-hand state :challenger "Hades Shard")
(card-ability state :challenger (get-radicle state 0) 0)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Enhanced Login Protocol" (:hand (get-contestant))))
(is (find-card "Enhanced Login Protocol" (:current (get-contestant))) "Enhanced Login Protocol is in play")
(is (= 3 (:click (get-challenger))) "Challenger has 3 clicks")
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger spends 1 additional click to make a run")))
(testing "Doesn't fire if already run when played on the challenger's turn"
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
["Enhanced Login Protocol"
"Breaking News"])
(default-challenger ["Hades Shard"]))
(discard-from-hand state :contestant "Breaking News")
(take-credits state :contestant)
(run-on state :hq)
(run-successful state)
(prompt-choice :challenger "No action")
(core/gain state :challenger :credit 2)
(play-from-hand state :challenger "Hades Shard")
(card-ability state :challenger (get-radicle state 0) 0)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Enhanced Login Protocol" (:hand (get-contestant))))
(is (find-card "Enhanced Login Protocol" (:current (get-contestant))) "Enhanced Login Protocol is in play")
(is (= 2 (:click (get-challenger))) "Challenger has 2 clicks")
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger doesn't spend 1 additional click to make a run"))))
(deftest exchange-of-information
;; Exchange of Information
(testing "Basic test"
(do-game
(new-game (default-contestant ["Exchange of Information"
"Market Research"
"Breaking News"
"Project Beale"
"Explode-a-palooza"])
(default-challenger))
(score-agenda state :contestant (find-card "Market Research" (:hand (get-contestant))))
(score-agenda state :contestant (find-card "Breaking News" (:hand (get-contestant))))
(is (= 2 (:tag (get-challenger))) "Challenger gained 2 tags")
(take-credits state :contestant)
(is (zero? (:tag (get-challenger))) "Challenger lost 2 tags")
(core/steal state :challenger (find-card "Project Beale" (:hand (get-contestant))))
(core/steal state :challenger (find-card "Explode-a-palooza" (:hand (get-contestant))))
(take-credits state :challenger)
(is (= 4 (:agenda-point (get-challenger))))
(is (= 3 (:agenda-point (get-contestant))))
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "Project Beale" (:scored (get-challenger))))
(prompt-select :contestant (find-card "Breaking News" (:scored (get-contestant))))
(is (= 3 (:agenda-point (get-challenger))))
(is (= 4 (:agenda-point (get-contestant))))))
(testing "Swapping a just scored Breaking News keeps the tags"
(do-game
(new-game (default-contestant ["Exchange of Information"
"Market Research"
"Breaking News"
"Project Beale"
"Explode-a-palooza"])
(default-challenger))
(take-credits state :contestant)
(core/steal state :challenger (find-card "Project Beale" (:hand (get-contestant))))
(core/steal state :challenger (find-card "Explode-a-palooza" (:hand (get-contestant))))
(take-credits state :challenger)
(score-agenda state :contestant (find-card "Breaking News" (:hand (get-contestant))))
(is (= 2 (:tag (get-challenger))) "Challenger gained 2 tags")
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "Project Beale" (:scored (get-challenger))))
(prompt-select :contestant (find-card "Breaking News" (:scored (get-contestant))))
(is (= 2 (:tag (get-challenger))) "Still has tags after swap and before end of turn")
(take-credits state :contestant)
(is (= 3 (:agenda-point (get-challenger))))
(is (= 2 (:agenda-point (get-contestant))))
(is (= 2 (:tag (get-challenger))) "Challenger does not lose tags at end of turn")))
(testing "Swapping a 15 Minutes still keeps the ability. #1783"
(do-game
(new-game (default-contestant [(qty "Exchange of Information" 2) "15 Minutes"
"Project Beale"])
(default-challenger))
(score-agenda state :contestant (find-card "15 Minutes" (:hand (get-contestant))))
(take-credits state :contestant)
(core/gain state :challenger :tag 1)
(core/steal state :challenger (find-card "Project Beale" (:hand (get-contestant))))
(take-credits state :challenger)
(is (= 1 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "Project Beale" (:scored (get-challenger))))
(prompt-select :contestant (find-card "15 Minutes" (:scored (get-contestant))))
(is (= 2 (:agenda-point (get-contestant))))
(is (= 1 (:agenda-point (get-challenger))))
(is (zero? (count (:deck (get-contestant)))))
;; shuffle back into R&D from challenger's scored area
(let [fifm (get-scored state :challenger 0)]
(card-ability state :contestant fifm 0))
(is (= 2 (:agenda-point (get-contestant))))
(is (zero? (:agenda-point (get-challenger))))
(is (= "15 Minutes" (:title (first (:deck (get-contestant))))))
(take-credits state :contestant)
(core/steal state :challenger (find-card "15 Minutes" (:deck (get-contestant))))
(take-credits state :challenger)
(is (= 2 (:agenda-point (get-contestant))))
(is (= 1 (:agenda-point (get-challenger))))
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "15 Minutes" (:scored (get-challenger))))
(prompt-select :contestant (find-card "Project Beale" (:scored (get-contestant))))
(is (= 1 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
;; shuffle back into R&D from contestant's scored area
(let [fifm (get-scored state :contestant 0)]
(card-ability state :contestant fifm 0))
(is (= "15 Minutes" (:title (first (:deck (get-contestant))))))))
(testing "Swapping a Mandatory Regions gives the Contestant an additional click per turn. #1687"
(do-game
(new-game (default-contestant [(qty "Exchange of Information" 2) "Mandatory Regions"
"Global Food Initiative"])
(default-challenger))
(score-agenda state :contestant (find-card "Global Food Initiative" (:hand (get-contestant))))
(take-credits state :contestant)
(core/gain state :challenger :tag 1)
(core/steal state :challenger (find-card "Mandatory Regions" (:hand (get-contestant))))
(take-credits state :challenger)
(is (= 3 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
(is (= 3 (:click (get-contestant))))
(is (= 3 (:click-per-turn (get-contestant))))
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "Mandatory Regions" (:scored (get-challenger))))
(prompt-select :contestant (find-card "Global Food Initiative" (:scored (get-contestant))))
(is (= 2 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
(is (= 3 (:click (get-contestant))))
(is (= 4 (:click-per-turn (get-contestant))))
(take-credits state :contestant)
(take-credits state :challenger)
(is (= 4 (:click (get-contestant))))
(is (= 4 (:click-per-turn (get-contestant))))
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "Global Food Initiative" (:scored (get-challenger))))
(prompt-select :contestant (find-card "Mandatory Regions" (:scored (get-contestant))))
(is (= 3 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
(is (= 2 (:click (get-contestant))))
(is (= 3 (:click-per-turn (get-contestant))))
(take-credits state :contestant)
(take-credits state :challenger)
(is (= 3 (:click (get-contestant))))
(is (= 3 (:click-per-turn (get-contestant)))))))
(deftest foxfire
;; Foxfire
(do-game
(new-game (default-contestant [(qty "Foxfire" 2)])
(default-challenger ["Dyson Mem Chip" "Character Carver"]))
(take-credits state :contestant)
(core/gain state :challenger :credit 100)
(play-from-hand state :challenger "Dyson Mem Chip")
(play-from-hand state :challenger "Character Carver")
(take-credits state :challenger)
(play-from-hand state :contestant "Foxfire")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-hazard state 0))
(is (= 1 (-> (get-challenger) :discard count)) "Contestant should discard Dyson Mem Chip from winning Foxfire trace")
(play-from-hand state :contestant "Foxfire")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(is (= 2 (-> (get-challenger) :discard count)) "Contestant should discard Character Carver from winning Foxfire trace")))
(deftest hard-hitting-news
;; Hard-Hitting News
(do-game
(new-game (default-contestant ["Hard-Hitting News"])
(default-challenger))
(take-credits state :contestant)
(run-empty-locale state :rd)
(take-credits state :challenger)
(is (= 3 (:click (get-contestant))) "Contestant should start with 3 clicks")
(play-from-hand state :contestant "Hard-Hitting News")
(is (zero? (:click (get-contestant))) "Playing Hard-Hitting News should lose all remaining clicks")
(is (zero? (:tag (get-challenger))) "Challenger should start with 0 tags")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 4 (:tag (get-challenger))) "Challenger should gain 4 tags from losing Hard-Hitting News trace")))
(deftest hatchet-job
;; Hatchet Job - Win trace to add placed non-virtual to grip
(do-game
(new-game (default-contestant ["Hatchet Job"])
(default-challenger ["Upya" "Ghost Challenger"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Ghost Challenger")
(play-from-hand state :challenger "Upya")
(take-credits state :challenger)
(play-from-hand state :contestant "Hatchet Job")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(is (empty? (:hand (get-challenger))) "Can't choose virtual card")
(is (not (empty? (:prompt (get-contestant)))))
(prompt-select :contestant (get-resource state 0))
(is (= 1 (count (:hand (get-challenger)))) "Upya returned to grip")))
(deftest hedge-fund
(do-game
(new-game (default-contestant) (default-challenger))
(is (= 5 (:credit (get-contestant))))
(play-from-hand state :contestant "Hedge Fund")
(is (= 9 (:credit (get-contestant))))))
(deftest hellion-alpha-test
;; Hellion Alpha Test
(do-game
(new-game (default-contestant [(qty "Hellion Alpha Test" 2)])
(default-challenger ["Daily Casts"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Daily Casts")
(take-credits state :challenger)
(play-from-hand state :contestant "Hellion Alpha Test")
(is (zero? (-> (get-challenger) :deck count)) "Challenger should have no cards in Stack")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(is (= 1 (-> (get-challenger) :deck count)) "Challenger should have 1 card in Stack from losing Hellion Alpha Test trace")
(is (= "Daily Casts" (-> (get-challenger) :deck first :title))
"Challenger should have Daily Casts on top of Stack from losing Hellion Alpha Test trace")
(take-credits state :contestant)
(core/draw state :challenger)
(play-from-hand state :challenger "Daily Casts")
(take-credits state :challenger)
(play-from-hand state :contestant "Hellion Alpha Test")
(is (zero? (:bad-publicity (get-contestant))) "Contestant should start with 0 bad publicity")
(prompt-choice :contestant 0)
(prompt-choice :challenger 2)
(is (= 1 (:bad-publicity (get-contestant))) "Contestant should gain 1 bad publicity from losing Hellion Alpha Test trace")))
(deftest hellion-beta-test
;; Hellion Beta Test
(testing "Winning Trace - Discarding 2 cards"
(do-game
(new-game (default-contestant ["Dedicated Response Team" "Hellion Beta Test"])
(default-challenger ["Daily Casts" "Dyson Mem Chip"]))
(play-from-hand state :contestant "Dedicated Response Team" "New party")
(take-credits state :contestant)
(core/gain state :challenger :credit 100)
(play-from-hand state :challenger "Daily Casts")
(play-from-hand state :challenger "Dyson Mem Chip")
(run-empty-locale state :party1)
(prompt-choice-partial :challenger "Pay")
(take-credits state :challenger)
(is (zero? (-> (get-challenger) :discard count)) "Challenger's heap should be empty")
(play-from-hand state :contestant "Hellion Beta Test")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(prompt-select :contestant (get-hazard state 0))
(is (= 2 (-> (get-challenger) :discard count)) "Challenger should have 2 cards in heap after losing Hellion Beta Test trace")))
(testing "Losing trace - Gaining bad publicity"
(do-game
(new-game (default-contestant ["Dedicated Response Team" "Hellion Beta Test"])
(default-challenger ["Daily Casts" "Dyson Mem Chip"]))
(play-from-hand state :contestant "Dedicated Response Team" "New party")
(take-credits state :contestant)
(core/gain state :challenger :credit 100)
(play-from-hand state :challenger "Daily Casts")
(play-from-hand state :challenger "Dyson Mem Chip")
(run-empty-locale state :party1)
(prompt-choice-partial :challenger "Pay")
(take-credits state :challenger)
(is (zero? (:bad-publicity (get-contestant))) "Contestant should start with 0 bad publicity")
(play-from-hand state :contestant "Hellion Beta Test")
(prompt-choice :contestant 0)
(prompt-choice :challenger 2)
(is (= 1 (:bad-publicity (get-contestant))) "Contestant should gain 1 bad publicity from losing Hellion Beta Test trace"))))
(deftest high-profile-target
(testing "when the challenger has no tags"
(do-game
(new-game (default-contestant [(qty "High-Profile Target" 6)])
(default-challenger [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(play-from-hand state :contestant "High-Profile Target")
(is (= 3 (:click (get-contestant))) "Contestant not charged a click")
(is (= 5 (count (:hand (get-challenger)))) "Challenger did not take damage")))
(testing "when the challenger has one tag"
(do-game
(new-game (default-contestant [(qty "High-Profile Target" 6)])
(default-challenger [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "High-Profile Target")
(is (= 3 (count (:hand (get-challenger)))) "Challenger has 3 cards in hand")))
(testing "when the challenger has two tags"
(do-game
(new-game (default-contestant [(qty "High-Profile Target" 6)])
(default-challenger [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :challenger :tag 2)
(play-from-hand state :contestant "High-Profile Target")
(is (= 1 (count (:hand (get-challenger)))) "Challenger has 1 card in hand")))
(testing "When the challenger has three tags, gg"
(do-game
(new-game (default-contestant [(qty "High-Profile Target" 10)])
(default-challenger))
(core/gain state :challenger :tag 3)
(play-from-hand state :contestant "High-Profile Target")
(is (zero? (count (:hand (get-challenger)))) "Challenger has 0 cards in hand")
(is (= :contestant (:winner @state)) "Contestant wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline"))))
(deftest housekeeping
;; Housekeeping - Challenger must discard a card from Grip on first place of a turn
(do-game
(new-game (default-contestant ["Housekeeping"])
(default-challenger [(qty "Cache" 2) "Fall Guy" "Mr. Li"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Fall Guy")
(take-credits state :challenger)
(play-from-hand state :contestant "Housekeeping")
(take-credits state :contestant)
(play-from-hand state :challenger "Cache")
(prompt-select :challenger (find-card "Mr. Li" (:hand (get-challenger))))
(is (empty? (:prompt (get-challenger))) "Fall Guy prevention didn't trigger")
(is (= 1 (count (:discard (get-challenger)))) "Card discarded")
(play-from-hand state :challenger "Cache")
(is (empty? (:prompt (get-challenger))) "Housekeeping didn't trigger on 2nd place")))
(deftest invasion-of-privacy
;; Invasion of Privacy - Full test
(do-game
(new-game (default-contestant [(qty "Invasion of Privacy" 3)])
(default-challenger [(qty "Sure Gamble" 2) "Fall Guy" (qty "Cache" 2)]))
(core/gain state :contestant :click 3 :credit 6)
;; discard 2 cards
(play-from-hand state :contestant "Invasion of Privacy")
(prompt-choice :contestant 0) ; default trace
(prompt-choice :challenger 0) ; Challenger won't match
(is (= 5 (count (:hand (get-challenger)))))
(let [get-prompt (fn [] (first (#(get-in @state [:contestant :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" "Sure Gamble" nil) (prompt-names)))
(prompt-card :contestant (find-card "Sure Gamble" (:hand (get-challenger))))
(prompt-card :contestant (find-card "Sure Gamble" (:hand (get-challenger)))))
(is (= 3 (count (:hand (get-challenger)))))
;; able to discard 2 cards but only 1 available target in Challenger's hand
(play-from-hand state :contestant "Invasion of Privacy")
(prompt-choice :contestant 0) ; default trace
(prompt-choice :challenger 0) ; Challenger won't match
(is (= 3 (count (:hand (get-challenger)))))
(let [get-prompt (fn [] (first (#(get-in @state [:contestant :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" nil) (prompt-names)))
(prompt-card :contestant (find-card "Fall Guy" (:hand (get-challenger))))
(is (empty? (get-in @state [:contestant :prompt])) "No prompt for second card"))
(is (= 2 (count (:hand (get-challenger)))))
;; failed trace - take the bad publicity
(play-from-hand state :contestant "Invasion of Privacy")
(prompt-choice :contestant 0) ; default trace
(prompt-choice :challenger 2) ; Challenger matches
(is (= 1 (:bad-publicity (get-contestant))))))
(deftest ipo
;; IPO - credits with Terminal operations
(do-game
(new-game
(default-contestant ["IPO"])
(default-challenger))
(take-credits state :contestant)
(take-credits state :challenger)
(play-from-hand state :contestant "IPO")
(is (= 13 (:credit (get-contestant))))
(is (zero? (:click (get-contestant))) "Terminal ends turns")))
(deftest kill-switch
;; Kill Switch
(do-game
(new-game (default-contestant ["Kill Switch" (qty "Hostile Takeover" 2)])
(default-challenger))
(play-from-hand state :contestant "Kill Switch")
(play-from-hand state :contestant "Hostile Takeover" "New party")
(is (zero? (:brain-damage (get-challenger))) "Challenger should start with 0 brain damage")
(play-and-score state "Hostile Takeover")
(prompt-choice :contestant "Hostile Takeover")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:brain-damage (get-challenger))) "Challenger should get 1 brain damage from Kill Switch after Contestant scores an agenda")
(take-credits state :contestant)
(run-empty-locale state :party1)
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 2 (:brain-damage (get-challenger))) "Challenger should get 1 brain damage from Kill Switch after accecssing an agenda")))
(deftest lag-time
(do-game
(new-game (default-contestant ["Lag Time" "Vanilla" "Lotus Field"])
(default-challenger))
(take-credits state :contestant)
(take-credits state :challenger)
(play-from-hand state :contestant "Vanilla" "HQ")
(play-from-hand state :contestant "Lotus Field" "R&D")
(play-from-hand state :contestant "Lag Time")
(core/reveal state :contestant (get-character state :hq 0))
(core/reveal state :contestant (get-character state :rd 0))
(is (= 1 (:current-strength (get-character state :hq 0))) "Vanilla at 1 strength")
(is (= 5 (:current-strength (get-character state :rd 0))) "Lotus Field at 5 strength")))
(deftest lateral-growth
(do-game
(new-game (default-contestant ["Lateral Growth" "Breaking News"])
(default-challenger))
(is (= 5 (:credit (get-contestant))))
(play-from-hand state :contestant "Lateral Growth")
(prompt-select :contestant (find-card "Breaking News" (:hand (get-contestant))))
(prompt-choice :contestant "New party")
(is (= "Breaking News" (:title (get-content state :party1 0)))
"Breaking News placed by Lateral Growth")
(is (= 7 (:credit (get-contestant))))))
(deftest manhunt
;; Manhunt - only fires once per turn. Unreported issue.
(do-game
(new-game (default-contestant ["Manhunt" (qty "Hedge Fund" 3)])
(default-challenger))
(play-from-hand state :contestant "Manhunt")
(take-credits state :contestant)
(run-empty-locale state "HQ")
(is (:prompt (get-contestant)) "Manhunt trace initiated")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger took 1 tag")
(prompt-choice :challenger "No action")
(is (not (:run @state)) "Run ended")
(run-empty-locale state "HQ")
(is (empty? (:prompt (get-contestant))) "No Manhunt trace on second run")
(prompt-choice :challenger "No action")
(is (not (:run @state)) "Run ended")))
(deftest market-forces
(testing "Full test"
(letfn [(market-forces-credit-test
[{:keys [tag-count challenger-creds expected-credit-diff]}]
(testing (str "when the challenger has " tag-count " tags and " challenger-creds " credits")
(do-game
(new-game (default-contestant [(qty "Market Forces" 6)])
(default-challenger))
(swap! state assoc-in [:contestant :credit] 0)
(swap! state assoc-in [:challenger :credit] challenger-creds)
(core/gain state :challenger :tag tag-count)
(play-from-hand state :contestant "Market Forces")
(is (= expected-credit-diff (:credit (get-contestant)))
(str "the contestant gains " expected-credit-diff " credits"))
(is (= expected-credit-diff (- challenger-creds (:credit (get-challenger))))
(str "the challenger loses " expected-credit-diff " credits")))))]
(doall (map market-forces-credit-test
[{:tag-count 1
:challenger-creds 10
:expected-credit-diff 3}
{:tag-count 2
:challenger-creds 10
:expected-credit-diff 6}
{:tag-count 3
:challenger-creds 10
:expected-credit-diff 9}
{:tag-count 3
:challenger-creds 0
:expected-credit-diff 0}
{:tag-count 3
:challenger-creds 5
:expected-credit-diff 5}]))))
(testing "when the challenger is not tagged"
(do-game
(new-game (default-contestant [(qty "Market Forces" 6)])
(default-challenger))
(play-from-hand state :contestant "Market Forces")
(is (= 6 (count (:hand (get-contestant))))
"Market Forces is not played")
(is (= 3 (:click (get-contestant)))
"the contestant does not spend a click")
(is (= 5 (:credit (get-contestant)) (:credit (get-challenger)))
"credits are unaffected"))))
(deftest mass-commercialization
;; Mass Commercialization
(do-game
(new-game (default-contestant ["Mass Commercialization"
(qty "Character Wall" 3)])
(default-challenger))
(play-from-hand state :contestant "Character Wall" "HQ")
(play-from-hand state :contestant "Character Wall" "R&D")
(play-from-hand state :contestant "Character Wall" "Archives")
(take-credits state :challenger)
(core/advance state :contestant {:card (refresh (get-character state :hq 0))})
(core/advance state :contestant {:card (refresh (get-character state :archives 0))})
(core/advance state :contestant {:card (refresh (get-character state :rd 0))})
(take-credits state :challenger)
(play-from-hand state :contestant "Mass Commercialization")
(is (= 8 (:credit (get-contestant))) "Gained 6 for 3 advanced character from Mass Commercialization")))
(deftest medical-research-fundraiser
;; Medical Research Fundraiser - challenger gains 8creds, challenger gains 3creds
(do-game
(new-game (default-contestant ["Medical Research Fundraiser"])
(default-challenger))
(is (= 5 (:credit (get-contestant))) "Contestant starts with 5 credits")
(is (= 5 (:credit (get-challenger))) "Challenger starts with 5 credits")
(play-from-hand state :contestant "Medical Research Fundraiser")
(is (= 10 (:credit (get-contestant))) "Contestant gains 8 credits")
(is (= 8 (:credit (get-challenger))) "Challenger gains 3 credits")))
(deftest midseason-replacements
;; Midseason Replacements - Trace to give Challenger tags after they steal an agenda
(do-game
(new-game (default-contestant ["Midseason Replacements" "Breaking News"])
(default-challenger))
(play-from-hand state :contestant "Midseason Replacements")
(is (= 3 (:click (get-contestant))) "Midseason precondition not met; Contestant not charged a click")
(play-from-hand state :contestant "Breaking News" "New party")
(take-credits state :contestant)
(is (= 7 (:credit (get-contestant))))
(let [bn (get-content state :party1 0)]
(run-empty-locale state "Locale 1")
(prompt-choice :challenger "Steal")
(is (= 1 (:agenda-point (get-challenger))) "Stole Breaking News")
(take-credits state :challenger)
(play-from-hand state :contestant "Midseason Replacements")
(prompt-choice :contestant 0) ; default trace
(prompt-choice :challenger 0) ; Challenger won't match
(is (= 6 (:tag (get-challenger))) "Challenger took 6 tags"))))
(deftest mushin-no-shin
;; Mushin No Shin - Add 3 advancements to a card; prevent reveal/score of that card the rest of the turn
(do-game
(new-game (default-contestant [(qty "Mushin No Shin" 2) "Ronin" "Profiteering"])
(default-challenger))
(play-from-hand state :contestant "Mushin No Shin")
(prompt-select :contestant (find-card "Ronin" (:hand (get-contestant))))
(let [ronin (get-content state :party1 0)]
(is (= 3 (get-counters (refresh ronin) :advancement)) "3 advancements placed on Ronin")
(core/reveal state :contestant (refresh ronin))
(is (not (:revealed (refresh ronin))) "Ronin did not reveal")
(take-credits state :contestant)
(take-credits state :challenger)
(core/reveal state :contestant (refresh ronin))
(is (:revealed (refresh ronin)) "Ronin now revealed")
(play-from-hand state :contestant "Mushin No Shin")
(prompt-select :contestant (find-card "Profiteering" (:hand (get-contestant))))
(let [prof (get-content state :party2 0)]
(core/score state :contestant (refresh prof))
(is (empty? (:scored (get-contestant))) "Profiteering not scored")
(is (zero? (:agenda-point (get-contestant))))
(take-credits state :contestant)
(take-credits state :challenger)
(core/score state :contestant (refresh prof))
(prompt-choice :contestant "0")
(is (= 1 (:agenda-point (get-contestant))) "Profiteering was able to be scored")))))
(deftest mutate
;; Mutate - discard a revealed piece of character, place and reveal one from R&D
(testing "Basic operation"
(do-game
(new-game (default-contestant ["Mutate" "Character Wall" "Enigma" "Hedge Fund"])
(default-challenger))
(core/move state :contestant (find-card "Hedge Fund" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Enigma" (:hand (get-contestant))) :deck)
(play-from-hand state :contestant "Character Wall" "HQ")
(core/reveal state :contestant (get-character state :hq 0))
(is (= 1 (count (get-character state :hq))) "1 character placed")
(is (= "Character Wall" (:title (get-character state :hq 0))) "Character Wall is placed")
(play-from-hand state :contestant "Mutate")
(prompt-select :contestant (get-character state :hq 0))
(is (= 1 (count (get-character state :hq))) "1 character placed")
(is (= "Enigma" (:title (get-character state :hq 0))) "Enigma is placed")
(is (:revealed (get-character state :hq 0)) "Enigma is revealed")
(is (second-last-log-contains? state "Hedge Fund") "Skipped card name was logged")
(is (second-last-log-contains? state "Enigma") "Placed card name was logged")))
(testing "No character in R&D"
(do-game
(new-game (default-contestant ["Mutate" "Character Wall" "Enigma" "Hedge Fund"])
(default-challenger))
(core/move state :contestant (find-card "Hedge Fund" (:hand (get-contestant))) :deck)
(play-from-hand state :contestant "Character Wall" "HQ")
(core/reveal state :contestant (get-character state :hq 0))
(is (= 1 (count (get-character state :hq))) "1 character placed")
(is (= "Character Wall" (:title (get-character state :hq 0))) "Character Wall is placed")
(play-from-hand state :contestant "Mutate")
(prompt-select :contestant (get-character state :hq 0))
(is (empty? (get-character state :hq)) "No character placed")
(is (second-last-log-contains? state "Hedge Fund") "Skipped card name was logged"))))
(deftest neural-emp
;; Neural EMP - Play if Challenger made a run the previous turn to do 1 net damage
(do-game
(new-game (default-contestant ["Neural EMP"])
(default-challenger))
(play-from-hand state :contestant "Neural EMP")
(is (= 3 (:click (get-contestant))) "Neural precondition not met; card not played")
(take-credits state :contestant)
(run-empty-locale state "Archives")
(take-credits state :challenger)
(play-from-hand state :contestant "Neural EMP")
(is (= 1 (count (:discard (get-challenger)))) "Challenger took 1 net damage")))
(deftest oversight-ai
;; Oversight AI - Reveal a piece of Character ignoring all costs
(do-game
(new-game (default-contestant ["Oversight AI" "Archer"])
(default-challenger))
(play-from-hand state :contestant "Archer" "R&D")
(let [archer (get-character state :rd 0)]
(play-from-hand state :contestant "Oversight AI")
(prompt-select :contestant archer)
(is (:revealed (refresh archer)))
(is (= 4 (:credit (get-contestant))) "Archer revealed at no credit cost")
(is (= "Oversight AI" (:title (first (:hosted (refresh archer)))))
"Archer hosting OAI as a condition"))))
(deftest patch
;; Patch - +2 current strength
(do-game
(new-game (default-contestant ["Patch" "Vanilla"])
(default-challenger))
(play-from-hand state :contestant "Vanilla" "HQ")
(core/reveal state :contestant (get-character state :hq 0))
(play-from-hand state :contestant "Patch")
(prompt-select :contestant (get-character state :hq 0))
(is (= 2 (:current-strength (get-character state :hq 0))) "Vanilla at 2 strength")))
(deftest paywall-implementation
;; Paywall Implementation - Gain 1 credit for every successful run
(do-game
(new-game (default-contestant ["Paywall Implementation"])
(default-challenger))
(play-from-hand state :contestant "Paywall Implementation")
(is (= "Paywall Implementation" (:title (first (get-in @state [:contestant :current]))))
"Paywall active in Current area")
(take-credits state :contestant)
(is (= 7 (:credit (get-contestant))))
(run-empty-locale state "Archives")
(is (= 8 (:credit (get-contestant))) "Gained 1 credit from successful run")
(run-empty-locale state "Archives")
(is (= 9 (:credit (get-contestant))) "Gained 1 credit from successful run")))
(deftest peak-efficiency
;; Peak Efficiency - Gain 1 credit for each revealed Character
(do-game
(new-game (default-contestant ["Peak Efficiency" (qty "Paper Wall" 3) "Wraparound"])
(default-challenger))
(core/gain state :contestant :click 3)
(play-from-hand state :contestant "Paper Wall" "HQ")
(play-from-hand state :contestant "Paper Wall" "R&D")
(play-from-hand state :contestant "Paper Wall" "New party")
(play-from-hand state :contestant "Wraparound" "New party")
(core/reveal state :contestant (get-character state :hq 0))
(core/reveal state :contestant (get-character state :rd 0))
(core/reveal state :contestant (get-character state :party1 0))
(play-from-hand state :contestant "Peak Efficiency")
(is (= 7 (:credit (get-contestant))) "Gained 3 credits for 3 revealed Character; unrevealed Character ignored")))
(deftest power-shutdown
;; Power Shutdown - Discard cards from R&D to force Challenger to discard a resource or hazard
(do-game
(new-game (default-contestant [(qty "Power Shutdown" 3) (qty "Hive" 3)])
(default-challenger ["Grimoire" "Cache"]))
(play-from-hand state :contestant "Power Shutdown")
(is (empty? (:discard (get-contestant))) "Not played, no run last turn")
(take-credits state :contestant)
(play-from-hand state :challenger "Cache")
(play-from-hand state :challenger "Grimoire")
(run-empty-locale state :archives)
(take-credits state :challenger)
(core/move state :contestant (find-card "Hive" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Hive" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Hive" (:hand (get-contestant))) :deck)
(play-from-hand state :contestant "Power Shutdown")
(prompt-choice :contestant 2)
(is (= 3 (count (:discard (get-contestant)))) "2 cards discarded from R&D")
(is (= 1 (count (:deck (get-contestant)))) "1 card remaining in R&D")
(prompt-select :challenger (get-hazard state 0)) ; try targeting Grimoire
(is (empty? (:discard (get-challenger))) "Grimoire too expensive to be targeted")
(prompt-select :challenger (get-resource state 0))
(is (= 1 (count (:discard (get-challenger)))) "Cache discarded")))
(deftest power-grid-overload
;; Power Grid Overload
(do-game
(new-game (default-contestant ["Power Grid Overload"])
(default-challenger ["Dyson Mem Chip"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Dyson Mem Chip")
(run-empty-locale state :rd)
(take-credits state :challenger)
(play-from-hand state :contestant "Power Grid Overload")
(prompt-choice :contestant 3)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-hazard state 0))
(is (= 1 (-> (get-challenger) :discard count)) "Dyson Mem Chip should be in heap after Challenger loses Power Grid Overload trace")))
(deftest precognition
;; Precognition - Full test
(do-game
(new-game (default-contestant ["Precognition" "Caprcharacter Nisei" "Adonis Campaign"
"Quandary" "Jackson Howard" "Global Food Initiative"])
(default-challenger))
(starting-hand state :contestant ["Precognition"])
(play-from-hand state :contestant "Precognition")
(prompt-card :contestant (find-card "Caprcharacter Nisei" (:deck (get-contestant))))
(prompt-card :contestant (find-card "Adonis Campaign" (:deck (get-contestant))))
(prompt-card :contestant (find-card "Quandary" (:deck (get-contestant))))
(prompt-card :contestant (find-card "Jackson Howard" (:deck (get-contestant))))
(prompt-card :contestant (find-card "Global Food Initiative" (:deck (get-contestant))))
;; try starting over
(prompt-choice :contestant "Start over")
(prompt-card :contestant (find-card "Global Food Initiative" (:deck (get-contestant))))
(prompt-card :contestant (find-card "Jackson Howard" (:deck (get-contestant))))
(prompt-card :contestant (find-card "Quandary" (:deck (get-contestant))))
(prompt-card :contestant (find-card "Adonis Campaign" (:deck (get-contestant))))
(prompt-card :contestant (find-card "Caprcharacter Nisei" (:deck (get-contestant)))) ;this is the top card of R&D
(prompt-choice :contestant "Done")
(is (= "Caprcharacter Nisei" (:title (first (:deck (get-contestant))))))
(is (= "Adonis Campaign" (:title (second (:deck (get-contestant))))))
(is (= "Quandary" (:title (second (rest (:deck (get-contestant)))))))
(is (= "Jackson Howard" (:title (second (rest (rest (:deck (get-contestant))))))))
(is (= "Global Food Initiative" (:title (second (rest (rest (rest (:deck (get-contestant)))))))))))
(deftest preemptive-action
;; Preemptive Action - Shuffles cards into R&D and removes itself from game
(testing "Basic test"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 3)
"Preemptive Action"])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Preemptive Action")
(prompt-select :contestant (first (:discard (get-contestant))))
(prompt-select :contestant (second (:discard (get-contestant))))
(prompt-select :contestant (last (:discard (get-contestant))))
(is (zero? (count (:discard (get-contestant)))))
(is (= 1 (count (:rfg (get-contestant)))))))
(testing "forces you to take 3 if there are three, and removes itself from game"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 3)
(qty "Preemptive Action" 1)])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Preemptive Action")
(prompt-select :contestant (first (:discard (get-contestant))))
(prompt-select :contestant (last (:discard (get-contestant))))
(is (= 3 (count (:discard (get-contestant)))))
(is (= 1 (count (:rfg (get-contestant)))))))
(testing "Shuffles all archives cards into R&D if Archives has less than 3 cards, and removes itself from game"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 2)
(qty "Preemptive Action" 1)])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Preemptive Action")
(prompt-select :contestant (first (:discard (get-contestant))))
(prompt-select :contestant (last (:discard (get-contestant))))
(is (zero? (count (:discard (get-contestant)))))
(is (= 1 (count (:rfg (get-contestant))))))))
(deftest psychographics
;; Psychographics - Place advancements up to the number of Challenger tags on a card
(do-game
(new-game (default-contestant ["Psychographics" "Project Junebug"])
(default-challenger))
(core/gain state :challenger :tag 4)
(play-from-hand state :contestant "Project Junebug" "New party")
(let [pj (get-content state :party1 0)]
(play-from-hand state :contestant "Psychographics")
(prompt-choice :contestant 4)
(prompt-select :contestant pj)
(is (= 1 (:credit (get-contestant))) "Spent 4 credits")
(is (= 4 (get-counters (refresh pj) :advancement)) "Junebug has 4 advancements"))))
(deftest psychokinesis
;; Pyschokinesis - Terminal Event (end the turn); Look at R&D, place an Site, Agenda, or Region in a Party Locale
(do-game
(new-game (default-contestant [(qty "Psychokinesis" 3) "Caprcharacter Nisei" "Adonis Campaign"
"Global Food Initiative" "Mwanza City Grid"])
(default-challenger))
(starting-hand state :contestant ["Psychokinesis" "Psychokinesis" "Psychokinesis"])
;; Test placing an Region
(play-from-hand state :contestant "Psychokinesis")
(is (not-any? #{"Mwanza City Grid"} (map :title (-> (get-contestant) :prompt first :choices)))
"Mwanza City Grid is not on the list of placeable cards")
(prompt-card :contestant (find-card "Caprcharacter Nisei" (:deck (get-contestant))))
(prompt-choice :contestant "New party")
(is (= "Caprcharacter Nisei" (:title (get-content state :party1 0)))
"Caprcharacter Nisei placed by Psychokinesis")
;; Test placing an Site
(core/gain state :contestant :click 1)
(play-from-hand state :contestant "Psychokinesis")
(prompt-card :contestant (find-card "Adonis Campaign" (:deck (get-contestant))))
(prompt-choice :contestant "New party")
(is (= "Adonis Campaign" (:title (get-content state :party2 0)))
"Adonis Campaign placed by Psychokinesis")
;; Test placing an Agenda
(core/gain state :contestant :click 1)
(play-from-hand state :contestant "Psychokinesis")
(prompt-card :contestant (find-card "Global Food Initiative" (:deck (get-contestant))))
(prompt-choice :contestant "New party")
(is (= "Global Food Initiative" (:title (get-content state :party3 0)))
"Global Food Initiative placed by Psychokinesis")
;; Test selecting "None"
(core/gain state :contestant :click 1)
(core/move state :contestant (find-card "Psychokinesis" (:discard (get-contestant))) :hand)
(play-from-hand state :contestant "Psychokinesis")
(prompt-choice :contestant "None")
(is (= nil (:title (get-content state :party4 0)))
"Nothing is placed by Psychokinesis")))
(deftest punitive-counterstrike
;; Punitive Counterstrike - deal meat damage equal to printed agenda points
(do-game
(new-game (default-contestant ["Global Food Initiative" "Punitive Counterstrike"])
(default-challenger))
(play-from-hand state :contestant "Global Food Initiative" "New party")
(take-credits state :contestant)
(run-empty-locale state :party1)
(prompt-choice :challenger "Steal")
(is (= 2 (:agenda-point (get-challenger))) "Challenger scored 2 points")
(take-credits state :challenger)
(play-from-hand state :contestant "Punitive Counterstrike")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (empty? (:hand (get-challenger))) "Challenger took 3 meat damage")))
(deftest red-planet-couriers
;; Red Planet Couriers - Move all advancements on cards to 1 advanceable card
(do-game
(new-game (default-contestant ["Red Planet Couriers" (qty "Character Wall" 2)
"GRNDL Refinery" "Government Takeover"])
(default-challenger))
(core/gain state :contestant :click 4)
(play-from-hand state :contestant "Government Takeover" "New party")
(play-from-hand state :contestant "GRNDL Refinery" "New party")
(play-from-hand state :contestant "Character Wall" "HQ")
(play-from-hand state :contestant "Character Wall" "R&D")
(let [gt (get-content state :party1 0)
gr (get-content state :party2 0)
iw1 (get-character state :hq 0)
iw2 (get-character state :rd 0)]
(core/add-prop state :contestant gr :advance-counter 3)
(core/add-prop state :contestant iw1 :advance-counter 2)
(core/add-prop state :contestant iw2 :advance-counter 1)
(play-from-hand state :contestant "Red Planet Couriers")
(prompt-select :contestant gt)
(is (zero? (get-counters (refresh gr) :advancement)) "Advancements removed")
(is (zero? (get-counters (refresh iw1) :advancement)) "Advancements removed")
(is (zero? (get-counters (refresh iw2) :advancement)) "Advancements removed")
(is (= 6 (get-counters (refresh gt) :advancement)) "Gained 6 advancements"))))
(deftest reuse
;; Reuse - Gain 2 credits for each card discarded from HQ
(do-game
(new-game (default-contestant [(qty "Reuse" 2) "Hive" "IQ"
"Character Wall"])
(default-challenger))
(play-from-hand state :contestant "Reuse")
(prompt-select :contestant (find-card "Character Wall" (:hand (get-contestant))))
(prompt-select :contestant (find-card "Hive" (:hand (get-contestant))))
(prompt-select :contestant (find-card "IQ" (:hand (get-contestant))))
(prompt-choice :contestant "Done")
(is (= 4 (count (:discard (get-contestant)))) "3 cards discarded plus operation played")
(is (= 11 (:credit (get-contestant))) "Gained 6 credits")
(is (= 1 (:click (get-contestant))) "Spent 2 clicks")))
(deftest reverse-infection
;; Reverse Infection - purge and discard 1 card from stack for every 3 counters purged - or gain 2 credits
(do-game
(new-game (default-contestant [(qty "Reverse Infection" 2)])
(default-challenger ["Virus Breeding Ground" "Datasucker" (qty "Sure Gamble" 3)]))
(starting-hand state :challenger ["Virus Breeding Ground" "Datasucker"])
(play-from-hand state :contestant "Reverse Infection")
(prompt-choice :contestant "Gain 2 [Credits]")
(is (= 7 (:credit (get-contestant))) "Contestant gained 2 credits")
(take-credits state :contestant)
(play-from-hand state :challenger "Virus Breeding Ground")
(play-from-hand state :challenger "Datasucker")
(take-credits state :challenger)
(core/add-counter state :challenger (get-radicle state 0) :virus 4)
(core/add-counter state :challenger (get-resource state 0) :virus 3)
(play-from-hand state :contestant "Reverse Infection")
(prompt-choice :contestant "Purge virus counters.")
(is (= 9 (:credit (get-contestant))) "Contestant did not gain credits")
(is (zero? (get-counters (get-radicle state 0) :virus)) "Viruses purged from VBG")
(is (zero? (get-counters (get-resource state 0) :virus)) "Viruses purged from Datasucker")
(is (= 2 (count (:discard (get-challenger)))) "Two cards discarded from stack")))
(deftest riot-suppression
;; Riot Suppression - lose 3 clicks or take 1 brain damage
(testing "Take 1 brain damage"
(do-game
(new-game (default-contestant ["Riot Suppression" "Adonis Campaign"])
(default-challenger))
(play-from-hand state :contestant "Adonis Campaign" "New party")
(take-credits state :contestant)
(run-empty-locale state "Locale 1")
(prompt-choice-partial :challenger "Pay")
(take-credits state :challenger)
(play-from-hand state :contestant "Riot Suppression")
(is (empty? (:discard (get-challenger))) "Challenger discard is empty")
(is (zero? (:brain-damage (get-challenger))) "Challenger starts with no brain damage")
(prompt-choice-partial :challenger "Yes")
(is (= 1 (count (:discard (get-challenger)))) "1 card lost to brain damage")
(is (= 1 (:brain-damage (get-challenger))) "Challenger took 1 brain damage")
(is (= 1 (count (:discard (get-contestant)))) "No contestant cards discarded")
(is (= 1 (count (:rfg (get-contestant)))) "Riot Suppestion removed from game")
(take-credits state :contestant)
(is (= 4 (:click (get-challenger))) "Challenger has all clicks the following turn")))
(testing "Lose 3 clicks"
(do-game
(new-game (default-contestant ["Riot Suppression" "Adonis Campaign"])
(default-challenger))
(play-from-hand state :contestant "Adonis Campaign" "New party")
(take-credits state :contestant)
(run-empty-locale state "Locale 1")
(prompt-choice-partial :challenger "Pay")
(take-credits state :challenger)
(play-from-hand state :contestant "Riot Suppression")
(is (empty? (:discard (get-challenger))) "Challenger discard is empty")
(is (zero? (:brain-damage (get-challenger))) "Challenger starts with no brain damage")
(prompt-choice-partial :challenger "No")
(is (empty? (:discard (get-challenger))) "Challenger discard statys empty")
(is (zero? (:brain-damage (get-challenger))) "Challenger takes no brain damage")
(is (= 1 (count (:discard (get-contestant)))) "No contestant cards discarded")
(is (= 1 (count (:rfg (get-contestant)))) "Riot Suppestion removed from game")
(take-credits state :contestant)
(is (= 1 (:click (get-challenger))) "Challenger has 3 fewer clicks following turn"))))
(deftest rolling-brownout
;; Rolling Brownout - Increase cost of events/operations by 1, gain 1c on first Challenger event of turn
(do-game
(new-game (default-contestant ["Rolling Brownout" "Beanstalk Royalties"
"Domestic Sleepers"])
(default-challenger [(qty "Easy Mark" 3)]))
(play-from-hand state :contestant "Rolling Brownout")
(play-from-hand state :contestant "Beanstalk Royalties")
(is (= 5 (:credit (get-contestant))) "Beanstalk netted only 2c")
(play-from-hand state :contestant "Domestic Sleepers" "New party")
(take-credits state :contestant)
(play-from-hand state :challenger "Easy Mark")
(is (= 7 (:credit (get-challenger))) "Easy Mark netted only 2c")
(is (= 6 (:credit (get-contestant))) "Contestant gained 1c from Brownout")
(play-from-hand state :challenger "Easy Mark")
(is (= 6 (:credit (get-contestant))) "No Contestant credit gain from 2nd event")
(run-empty-locale state "Locale 1")
(prompt-choice :challenger "Steal")
(play-from-hand state :challenger "Easy Mark")
(is (= 12 (:credit (get-challenger))) "Easy Mark netted 3c after Brownout discarded")))
(deftest salem's-hospitality
;; Salem's Hospitality - Full test
(do-game
(new-game (default-contestant [(qty "Salem's Hospitality" 3)])
(default-challenger [(qty "I've Had Worse" 3) "Faust"
"Levy AR Lab Access"]))
(play-from-hand state :contestant "Salem's Hospitality")
(is (= 5 (count (:hand (get-challenger)))))
(prompt-choice :contestant "I've Had Worse")
(is (= 2 (count (:hand (get-challenger)))))
(play-from-hand state :contestant "Salem's Hospitality")
(prompt-choice :contestant "Plascrete Carapace")
(is (= 2 (count (:hand (get-challenger)))))))
(deftest scorched-earth
;; Scorched Earth
(testing "Basic test"
(do-game
(new-game (default-contestant ["Scorched Earth"])
(default-challenger [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "Scorched Earth")
(is (= 1 (count (:hand (get-challenger)))) "Challenger has 1 card in hand")))
(testing "not tagged"
(do-game
(new-game (default-contestant ["Scorched Earth"])
(default-challenger [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(play-from-hand state :contestant "Scorched Earth")
(is (= 3 (:click (get-contestant))) "Contestant not charged a click")
(is (= 5 (count (:hand (get-challenger)))) "Challenger did not take damage")))
(testing "flatline"
(do-game
(new-game (default-contestant [(qty "Scorched Earth" 10)])
(default-challenger))
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "Scorched Earth")
(is (zero? (count (:hand (get-challenger)))) "Challenger has 0 cards in hand")
(is (= :contestant (:winner @state)) "Contestant wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline"))))
(deftest sea-source
;; SEA Source
(do-game
(new-game (default-contestant ["SEA Source"])
(default-challenger))
(take-credits state :contestant)
(run-empty-locale state :rd)
(take-credits state :challenger)
(is (zero? (:tag (get-challenger))) "Challenger should start with 0 tags")
(play-from-hand state :contestant "SEA Source")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger should get 1 tag from losing SEA Source trace")))
(deftest self-growth-resource
;; Self-Growth Resource - Add 2 placed cards to grip if challenger is tagged
(do-game
(new-game (default-contestant ["Self-Growth Resource"])
(default-challenger ["Clone Chip" "Inti"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Clone Chip")
(play-from-hand state :challenger "Inti")
(take-credits state :challenger)
(play-from-hand state :contestant "Self-Growth Resource")
(is (= 3 (:click (get-contestant))) "Self-Growth Resource precondition not met; card not played")
(core/gain state :challenger :tag 1)
(is (zero? (count (:hand (get-challenger)))) "Challenger hand is empty")
(let [inti (get-resource state 0)
cc (get-hazard state 0)]
(play-from-hand state :contestant "Self-Growth Resource")
(prompt-select :contestant inti)
(prompt-select :contestant cc))
(is (= 2 (count (:hand (get-challenger)))) "2 cards returned to hand")
(is (zero? (count (get-resource state))) "No resources placed")
(is (zero? (count (get-hazard state))) "No hazard placed")))
(deftest servcharacter-outage
;; Servcharacter Outage
(testing "First click run each turn costs a credit"
(do-game
(new-game (default-contestant ["Servcharacter Outage"])
(default-challenger ["Employee Strike"]))
(play-from-hand state :contestant "Servcharacter Outage")
(take-credits state :contestant)
(is (= 5 (:credit (get-challenger))) "Challenger has 5 credits")
(run-on state :archives)
(is (= 4 (:credit (get-challenger)))
"Challenger spends 1 credit to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 4 (:credit (get-challenger)))
"Challenger doesn't spend 1 credit to make the second run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(core/lose state :challenger :credit 6)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (zero? (:credit (get-challenger))) "Challenger has 0 credits")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (zero? (:credit (get-challenger))) "Challenger has 0 credits")
(take-credits state :challenger)
(take-credits state :contestant)
(core/lose state :challenger :credit 2)
(play-from-hand state :challenger "Employee Strike")
(is (= 1 (:credit (get-challenger))) "Challenger has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-challenger)))
"Challenger doesn't spend 1 credit to make a run")))
(testing "First card ability run each turn costs an additional credit"
(do-game
(new-game (default-contestant ["Servcharacter Outage"])
(default-challenger ["Sneakdoor Beta"]))
(play-from-hand state :contestant "Servcharacter Outage")
(take-credits state :contestant)
(play-from-hand state :challenger "Sneakdoor Beta")
(take-credits state :challenger 1)
(is (= 2 (:credit (get-challenger))) "Challenger has 2 credits")
(let [sneakdoor (get-resource state 0)]
(card-ability state :challenger sneakdoor 0)
(is (= 1 (:credit (get-challenger)))
"Challenger spends 1 additional credit to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:credit (get-challenger)))
"Challenger doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(core/lose state :challenger :credit 1)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (zero? (:credit (get-challenger))) "Challenger has 0 credits")
(card-ability state :challenger sneakdoor 0)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (zero? (:credit (get-challenger))) "Challenger has 0 credits"))))
(testing "First run event each turn costs an additional credit"
(do-game
(new-game (default-contestant ["Servcharacter Outage"])
(default-challenger [(qty "Out of the Ashes" 2)]))
(play-from-hand state :contestant "Servcharacter Outage")
(take-credits state :contestant)
(is (= 5 (:credit (get-challenger))) "Challenger has 5 credits")
(play-from-hand state :challenger "Out of the Ashes")
(is (= 3 (:credit (get-challenger)))
"Challenger spends 1 additional credit to run with a run event")
(prompt-choice :challenger "Archives")
(run-successful state)
(run-on state :archives)
(is (= 3 (:credit (get-challenger)))
"Challenger doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(prompt-choice :challenger "No") ; Out of the Ashes prompt
(core/lose state :challenger :credit 4)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (= 1 (:credit (get-challenger))) "Challenger has 1 credit")
(play-from-hand state :challenger "Out of the Ashes")
(is (empty? (get-in @state [:challenger :prompt]))
"Out of the Ashes was not played")
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (= 1 (:credit (get-challenger))) "Challenger has 1 credit")))
(testing "Works when played on the challenger's turn"
(do-game
(new-game (make-deck "New Angeles Sol: Your News" ["Servcharacter Outage"
"Breaking News"])
(default-challenger ["Hades Shard"]))
(discard-from-hand state :contestant "Breaking News")
(take-credits state :contestant)
(core/gain state :challenger :credit 3)
(play-from-hand state :challenger "Hades Shard")
(card-ability state :challenger (get-radicle state 0) 0)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Servcharacter Outage" (:hand (get-contestant))))
(is (find-card "Servcharacter Outage" (:current (get-contestant)))
"Servcharacter Outage is in play")
(is (= 1 (:credit (get-challenger))) "Challenger has 1 credit")
(run-on state :archives)
(is (zero? (:credit (get-challenger)))
"Challenger spends 1 additional credit to make a run")))
(testing "Doesn't fire if already run when played on the challenger's turn"
(do-game
(new-game (make-deck "New Angeles Sol: Your News" ["Servcharacter Outage"
"Breaking News"])
(default-challenger ["Hades Shard"]))
(discard-from-hand state :contestant "Breaking News")
(take-credits state :contestant)
(run-on state :hq)
(run-successful state)
(prompt-choice :challenger "No action")
(core/gain state :challenger :credit 3)
(play-from-hand state :challenger "Hades Shard")
(card-ability state :challenger (get-radicle state 0) 0)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Servcharacter Outage" (:hand (get-contestant))))
(is (find-card "Servcharacter Outage" (:current (get-contestant)))
"Servcharacter Outage is in play")
(is (= 1 (:credit (get-challenger))) "Challenger has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-challenger)))
"Challenger doesn't spend 1 additional credit to make a run")))
(testing "discarded and replaced on steal doesn't double remove penalty"
(do-game
(new-game
(make-deck "New Angeles Sol: Your News" ["Servcharacter Outage"
"Breaking News"])
(default-challenger))
(play-from-hand state :contestant "Breaking News" "New party")
(play-from-hand state :contestant "Servcharacter Outage")
(take-credits state :contestant)
(run-on state :party1)
(run-successful state)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Servcharacter Outage" (:discard (get-contestant))))
(take-credits state :challenger)
(take-credits state :contestant)
(is (= 7 (:credit (get-challenger))) "Challenger has 7 credits")
(run-on state :archives)
(is (= 6 (:credit (get-challenger))) "Challenger spends 1 credit to make a run"))))
(deftest shipment-from-sansan
;; Shipment from SanSan - placing advancements
(do-game
(new-game (default-contestant [(qty "Shipment from SanSan" 3) (qty "Character Wall" 3)])
(default-challenger))
(play-from-hand state :contestant "Character Wall" "HQ")
(let [iwall (get-character state :hq 0)]
(play-from-hand state :contestant "Shipment from SanSan")
(prompt-choice :contestant "2")
(prompt-select :contestant iwall)
(is (= 5 (:credit (get-contestant))))
(is (= 2 (get-counters (refresh iwall) :advancement))))))
(deftest snatch-and-grab
;; Snatch and Grab
(do-game
(new-game (default-contestant [(qty "Snatch and Grab" 2)])
(default-challenger ["Scrubber"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Scrubber")
(take-credits state :challenger)
(is (zero? (:tag (get-challenger))) "Challenger should start with 0 tags")
(play-from-hand state :contestant "Snatch and Grab")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(prompt-choice :challenger "Yes")
(is (= 1 (:tag (get-challenger))) "Challenger should get 1 tag from losing Snatch and Grab trace and opting to take the tag")
(is (zero? (-> (get-challenger) :discard count)) "Challenger should start with 0 cards in heap")
(play-from-hand state :contestant "Snatch and Grab")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(prompt-choice :challenger "No")
(is (= 1 (-> (get-challenger) :discard count)) "Scrubber should be in Challenger's heap after losing Snatch and Grab trace")))
(deftest stock-buy-back
;; Stock Buy-Back - Gain 3c for every agenda in Challenger's area
(do-game
(new-game (default-contestant [(qty "Hostile Takeover" 2) (qty "Stock Buy-Back" 3)])
(default-challenger))
(play-from-hand state :contestant "Hostile Takeover" "New party")
(play-from-hand state :contestant "Hostile Takeover" "New party")
(take-credits state :contestant)
(run-empty-locale state "Locale 1")
(prompt-choice :challenger "Steal")
(run-empty-locale state "Locale 2")
(prompt-choice :challenger "Steal")
(take-credits state :challenger)
(is (= 2 (count (:scored (get-challenger)))))
(play-from-hand state :contestant "Stock Buy-Back")
(is (= 11 (:credit (get-contestant))))))
(deftest sub-boost
;; Sub Boost - Give Character Barrier
(do-game
(new-game (default-contestant ["Sub Boost" "Quandary"])
(default-challenger))
(play-from-hand state :contestant "Quandary" "HQ")
(let [qu (get-character state :hq 0)]
(core/reveal state :contestant qu)
(is (not (core/has-subtype? (refresh qu) "Barrier")) "Quandry starts without Barrier")
(is (= 1 (count (:subroutines (refresh qu)))) "Quandry has 1 subroutine")
(play-from-hand state :contestant "Sub Boost")
(prompt-select :contestant (refresh qu))
(is (core/has-subtype? (refresh qu) "Code Gate") "Quandary has Code Gate")
(is (core/has-subtype? (refresh qu) "Barrier") "Quandary Character Barrier")
(is (= 2 (count (:subroutines (refresh qu)))) "Quandry gains a subroutine"))))
(deftest subcontract
;; Subcontract
(testing "Don't allow second operation until damage prevention completes"
(do-game
(new-game (default-contestant [(qty "Scorched Earth" 2) "Subcontract"])
(default-challenger ["Plascrete Carapace"]))
(take-credits state :contestant)
(core/gain state :challenger :tag 1)
(play-from-hand state :challenger "Plascrete Carapace")
(take-credits state :challenger)
(play-from-hand state :contestant "Subcontract")
(prompt-select :contestant (find-card "Scorched Earth" (:hand (get-contestant))))
(is (and (= 1 (count (:prompt (get-contestant)))) (= :waiting (-> (get-contestant) :prompt first :prompt-type)))
"Contestant does not have Subcontract prompt until damage prevention completes")
(prompt-choice :challenger "Done")
(is (not-empty (:prompt (get-contestant))) "Contestant can now play second Subcontract operation")))
(testing "interaction with Terminal operations"
(do-game
(new-game
(default-contestant [(qty "Hard-Hitting News" 2) "Subcontract"])
(default-challenger))
(core/gain state :challenger :tag 1)
(take-credits state :contestant)
(run-empty-locale state :archives)
(take-credits state :challenger)
(play-from-hand state :contestant "Subcontract")
(prompt-select :contestant (find-card "Hard-Hitting News" (:hand (get-contestant))))
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 5 (:tag (get-challenger))) "Challenger has 5 tags")
(is (empty? (:prompt (get-contestant))) "Contestant does not have a second Subcontract selection prompt"))))
(deftest subliminal-messaging
;; Subliminal Messaging - Playing/discarding/milling will all prompt returning to hand
(testing "Basic test"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 3)])
(make-deck "Noise: Hacker Extraordinaire" [(qty "Cache" 3) "Utopia Shard"]))
(play-from-hand state :contestant "Subliminal Messaging")
(is (= 6 (:credit (get-contestant))))
(is (= 3 (:click (get-contestant))) "First Subliminal Messaging gains 1 click")
(play-from-hand state :contestant "Subliminal Messaging")
(is (= 7 (:credit (get-contestant))))
(is (= 2 (:click (get-contestant))) "Second Subliminal Messaging does not gain 1 click")
(discard-from-hand state :contestant "Subliminal Messaging")
(is (zero? (count (:hand (get-contestant)))))
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(is (= 3 (count (:hand (get-contestant)))) "All 3 Subliminals returned to HQ")
(core/move state :contestant (find-card "Subliminal Messaging" (:hand (get-contestant))) :deck)
(take-credits state :contestant)
(play-from-hand state :challenger "Cache")
(play-from-hand state :challenger "Utopia Shard")
(let [utopia (get-radicle state 0)]
(card-ability state :challenger utopia 0))
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(is (= 3 (count (:hand (get-contestant)))) "All 3 Subliminals returned to HQ")
(play-from-hand state :contestant "Subliminal Messaging")
(take-credits state :contestant)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :challenger)
(is (empty? (get-in @state [:contestant :prompt])) "No prompt here because challenger made a run last turn")
(take-credits state :contestant)
(is (= 2 (count (:hand (get-contestant)))))
(is (= 1 (count (:discard (get-contestant)))) "1 Subliminal not returned because challenger made a run last turn")))
(testing "Scenario involving Subliminal being added to HQ with Archived Memories"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 2) "Archived Memories"])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Archived Memories")
(prompt-select :contestant (find-card "Subliminal Messaging" (:discard (get-contestant))))
(is (= 2 (count (:discard (get-contestant)))))
(is (= 1 (count (:hand (get-contestant)))))
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "No")
(is (empty? (get-in @state [:contestant :prompt])) "Only 1 Subliminal prompt")
(play-from-hand state :contestant "Subliminal Messaging")
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(is (empty? (get-in @state [:contestant :prompt]))
"Only 2 Subliminal prompts - there will be a third if flag not cleared")))
(testing "Scenario involving Subliminal being reshuffled into R&D with Jackson"
(do-game
(new-game (default-contestant ["Subliminal Messaging" "Jackson Howard"])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Jackson Howard" "New party")
(take-credits state :contestant)
(let [jhow (get-content state :party1 0)]
(core/reveal state :contestant jhow)
(card-ability state :contestant jhow 1)
(prompt-select :contestant (find-card "Subliminal Messaging" (:discard (get-contestant))))
(prompt-choice :contestant "Done")
(is (zero? (count (:discard (get-contestant)))))
(is (= 1 (count (:rfg (get-contestant))))))
(take-credits state :challenger)
(play-from-hand state :contestant "Subliminal Messaging")
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(is (= 1 (count (:hand (get-contestant)))) "Subliminal returned to HQ")
(is (empty? (get-in @state [:contestant :prompt]))
"Subliminal prompt cleared - there will be a second prompt if flag not cleared")))
(testing "Challenger made run, ensure game asks again next turn"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 2)])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(discard-from-hand state :contestant "Subliminal Messaging")
(take-credits state :contestant)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :challenger)
(is (empty? (get-in @state [:contestant :prompt])) "No prompt here because challenger made a run last turn")
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(is (= 2 (count (:hand (get-contestant)))) "Both Subliminals returned to HQ")
(is (zero? (count (:discard (get-contestant)))) "No Subliminals in Archives")))
(testing "User declines to return to hand, ensure game asks again next turn"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 2)])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(discard-from-hand state :contestant "Subliminal Messaging")
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "No")
(prompt-choice :contestant "No")
(is (zero? (count (:hand (get-contestant)))) "Neither Subliminal returned to HQ")
(is (= 2 (count (:discard (get-contestant)))) "Both Subliminals in Archives")
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(is (= 2 (count (:hand (get-contestant)))) "Both Subliminals returned to HQ")
(is (zero? (count (:discard (get-contestant)))) "No Subliminals in Archives"))))
(deftest success
;; Success
(testing "Works with bad publicity"
(do-game
(new-game (default-contestant ["NAPD Contract" "Project Beale" "Success"])
(default-challenger))
(play-from-hand state :contestant "NAPD Contract" "New party")
(play-from-hand state :contestant "Project Beale" "New party")
(core/gain state :contestant :bad-publicity 9)
(core/gain state :contestant :credit 8)
(core/gain state :contestant :click 15)
(let [napd (get-content state :party1 0)
beale (get-content state :party2 0)]
(dotimes [_ 13] (core/advance state :contestant {:card (refresh napd)}))
(is (= 13 (get-counters (refresh napd) :advancement)))
(core/score state :contestant {:card (refresh napd)})
(is (= 2 (:agenda-point (get-contestant))))
(play-from-hand state :contestant "Success")
(prompt-select :contestant (get-scored state :contestant 0))
(is (= "NAPD Contract" (:title (first (:rfg (get-contestant))))))
(prompt-select :contestant (refresh beale))
(is (= 13 (get-counters (refresh beale) :advancement)))
(core/score state :contestant {:card (refresh beale)})
(is (= 7 (:agenda-point (get-contestant)))))))
(testing "Works with public agendas"
(do-game
(new-game (default-contestant ["Oaktown Renovation" "Vanity Project" "Success"])
(default-challenger))
(core/gain state :contestant :click 1)
(score-agenda state :contestant (find-card "Vanity Project" (:hand (get-contestant))))
(is (= 4 (:agenda-point (get-contestant))))
(play-from-hand state :contestant "Oaktown Renovation" "New party")
(is (= 5 (:credit (get-contestant))))
(play-from-hand state :contestant "Success")
(prompt-select :contestant (get-scored state :contestant 0))
(is (= "Vanity Project" (:title (first (:rfg (get-contestant))))))
(let [oaktown (get-content state :party1 0)]
(prompt-select :contestant (refresh oaktown))
(is (= 6 (get-counters (refresh oaktown) :advancement)))
(is (= 19 (:credit (get-contestant))) "Gain 2 + 2 + 2 + 2 + 3 + 3 = 14 credits for advancing Oaktown")
(core/score state :contestant {:card (refresh oaktown)})
(is (= 2 (:agenda-point (get-contestant)))))))
(testing "interaction with Jemison, regression test for issue #2704"
(do-game
(new-game (make-deck "Jemison Astronautics: Sacrifcharacter. Audacity. Success."
["Success"
"High-Risk Investment"
"Government Takeover"])
(default-challenger))
(core/gain state :contestant :click 1)
(score-agenda state :contestant (find-card "High-Risk Investment" (:hand (get-contestant))))
(play-from-hand state :contestant "Government Takeover" "New party")
(play-from-hand state :contestant "Success")
(prompt-select :contestant (get-in (get-contestant) [:scored 0]))
(let [gto (get-content state :party1 0)]
;; Prompt for Jemison
(prompt-select :contestant (refresh gto))
(is (= 4 (get-counters (refresh gto) :advancement)) "Added 4 counters from Jemison trigger")
;; Prompt for Success
(prompt-select :contestant (refresh gto))
(is (= (+ 4 5) (get-counters (refresh gto) :advancement)) "Advance 5 times from Success")))))
(deftest successful-demonstration
;; Successful Demonstration - Play if only Challenger made unsuccessful run last turn; gain 7 credits
(do-game
(new-game (default-contestant ["Successful Demonstration"])
(default-challenger))
(play-from-hand state :contestant "Successful Demonstration")
(is (and (= 3 (:click (get-contestant)))
(= 5 (:credit (get-challenger))))
"Successful Demonstration precondition not met; card not played")
(take-credits state :contestant)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :challenger)
(play-from-hand state :contestant "Successful Demonstration")
(is (= 13 (:credit (get-contestant))) "Paid 2 to play event; gained 7 credits")))
(deftest surveillance-sweep
;; Surveillance Sweep
(testing "Basic test"
(do-game
(new-game (default-contestant ["Restructured Datapool" "Surveillance Sweep" "Data Raven"])
(default-challenger ["Scrubbed"]))
(is (zero? (:tag (get-challenger))) "Challenger should start with no tags")
(play-from-hand state :contestant "Surveillance Sweep")
(play-and-score state "Restructured Datapool")
(let [rd-scored (get-scored state :contestant 0)]
(card-ability state :contestant rd-scored 0)
(is (not= :waiting (-> (get-contestant) :prompt first :prompt-type)) "Surveillance Sweep only works during a run")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger should gain a tag from Restructured Datapool ability"))
(take-credits state :contestant)
(take-credits state :challenger)
(play-from-hand state :contestant "Data Raven" "HQ")
(take-credits state :contestant)
(let [dr (get-character state :hq 0)]
(core/reveal state :contestant (refresh dr))
(run-on state :hq)
(card-subroutine state :contestant dr 0)
(is (= :waiting (-> (get-contestant) :prompt first :prompt-type)) "During a run, Contestant should wait on Challenger first")
(prompt-choice :challenger 0)
(prompt-choice :contestant 0)
(is (= 1 (get-counters (refresh dr) :power)) "Data Raven should gain a power counter from trace")
(run-successful state)
(play-from-hand state :challenger "Scrubbed")
(run-on state :hq)
(card-subroutine state :contestant dr 0)
(is (not= :waiting (-> (get-contestant) :prompt first :prompt-type)) "Challenger should now be waiting on Contestant")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 2 (get-counters (refresh dr) :power)) "Data Raven should gain a power counter from trace")
(run-successful state))))
(testing "trace during run after stealing an agenda"
(do-game
(new-game (default-contestant ["Surveillance Sweep" "Breaking News" "Forced Connection" "Data Raven"])
(default-challenger))
(core/gain state :contestant :click 4)
(core/gain state :contestant :credit 20)
(play-from-hand state :contestant "Surveillance Sweep")
(play-from-hand state :contestant "Breaking News" "New party")
(play-from-hand state :contestant "Forced Connection" "Locale 1")
(play-from-hand state :contestant "Data Raven" "Locale 1")
(take-credits state :contestant)
(let [dr (get-character state :party1 0)
bn (get-content state :party1 0)
fc (get-content state :party1 1)]
(core/reveal state :contestant (refresh dr))
(run-on state :party1)
(card-subroutine state :contestant dr 0)
(is (= :waiting (-> (get-contestant) :prompt first :prompt-type)) "During a run, Contestant should wait on Challenger first")
(prompt-choice :challenger 0)
(prompt-choice :contestant 0)
(is (= 1 (get-counters (refresh dr) :power)) "Data Raven should gain a power counter from trace")
(run-successful state)
(prompt-select :challenger bn)
(prompt-choice :challenger "Steal")
(prompt-select :challenger fc)
(is (not= :waiting (-> (get-contestant) :prompt first :prompt-type)) "After steal, Surveillance Sweep leaves play and Challenger waits on Contestant")))))
(deftest the-all-seeing-i
(testing "Counts number of cards if one card is prevented discarded with fall guy"
(do-game
(new-game (default-contestant ["The All-Seeing I"])
(default-challenger ["Fall Guy" (qty "Same Old Thing" 2)]))
(letfn [(res [] (count (get-in (get-challenger) [:rig :radicle])))]
(take-credits state :contestant)
(play-from-hand state :challenger "Same Old Thing")
(play-from-hand state :challenger "Fall Guy")
(play-from-hand state :challenger "Same Old Thing")
(take-credits state :challenger)
(play-from-hand state :contestant "The All-Seeing I")
(is (= 1 (count (:hand (get-contestant)))) "Contestant could not play All Seeing I when challenger was not tagged")
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "The All-Seeing I")
(let [fall-guy (get-radicle state 1)]
(card-ability state :challenger fall-guy 0))
(prompt-choice :challenger "Done")
(is (= 1 (res)) "One placed radicle saved by Fall Guy")
(is (= 2 (count (:discard (get-challenger)))) "Two cards in heap"))))
(testing "Checks that All-seeing I does not double-discard hosted cards, discards hosted cards"
(do-game
(new-game (default-contestant ["The All-Seeing I"])
(default-challenger [(qty "Fall Guy" 2) "Off-Campus Apartment"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Off-Campus Apartment")
(let [oca (get-radicle state 0)
fg1 (get-in (get-challenger) [:hand 0])
fg2 (get-in (get-challenger) [:hand 1])]
(card-ability state :challenger oca 0)
(prompt-select :challenger fg1)
(card-ability state :challenger oca 0)
(prompt-select :challenger fg2))
(core/gain state :challenger :tag 1)
(take-credits state :challenger)
(play-from-hand state :contestant "The All-Seeing I")
(prompt-choice :challenger "Done")
(prompt-choice :challenger "Done")
(let [fall-guy (find-card "Fall Guy" (core/all-active-placed state :challenger))]
(card-ability state :challenger fall-guy 0))
(prompt-choice :challenger "Done") ;; This assumes hosted cards get put in discard-list before host
(is (= 1 (count (core/all-active-placed state :challenger))) "One placed card (Off-Campus)")
(is (= 2 (count (:discard (get-challenger)))) "Two cards in heap")))
(testing "should not discard Jarogniew Mercs if there are other placed radicles"
(do-game
(new-game (default-contestant [(qty "The All-Seeing I" 4)])
(default-challenger [(qty "Jarogniew Mercs" 2) (qty "Same Old Thing" 2)]))
(letfn [(res [] (count (get-in (get-challenger) [:rig :radicle])))]
(take-credits state :contestant)
(play-from-hand state :challenger "Same Old Thing")
(play-from-hand state :challenger "Jarogniew Mercs")
(take-credits state :challenger)
(is (= 2 (res)) "There are two placed radicles")
(play-from-hand state :contestant "The All-Seeing I")
(is (= 1 (res)) "Jarogniew Mercs still placed")
(play-from-hand state :contestant "The All-Seeing I")
(is (zero? (res)) "There are no placed radicles")
(take-credits state :contestant)
(play-from-hand state :challenger "Jarogniew Mercs") ;; Testing if order matters
(play-from-hand state :challenger "Same Old Thing")
(take-credits state :challenger)
(is (= 2 (res)) "There are two placed radicles")
(play-from-hand state :contestant "The All-Seeing I")
(is (= 1 (res)) "Jarogniew Mercs still placed")
(play-from-hand state :contestant "The All-Seeing I")
(is (zero? (res)) "There are no placed radicles")))))
(deftest threat-assessment
;; Threat Assessment - play only if challenger discarded a card last turn, move a card to the stack or take 2 tags
(do-game
(new-game (default-contestant [(qty "Threat Assessment" 3) "Adonis Campaign"])
(default-challenger ["Desperado" "Corroder"]))
(play-from-hand state :contestant "Adonis Campaign" "New party")
(take-credits state :contestant)
(run-on state :party1)
(run-successful state)
(prompt-choice-partial :challenger "Pay") ;discard
(core/gain state :challenger :credit 5)
(play-from-hand state :challenger "Desperado")
(play-from-hand state :challenger "Corroder")
(take-credits state :challenger)
(is (zero? (:tag (get-challenger))) "Challenger starts with 0 tags")
(play-from-hand state :contestant "Threat Assessment")
(prompt-select :contestant (find-card "Desperado" (-> (get-challenger) :rig :hazard)))
(prompt-choice :challenger "2 tags")
(is (= 2 (:tag (get-challenger))) "Challenger took 2 tags")
(is (= 1 (count (-> (get-challenger) :rig :hazard))) "Didn't discard Desperado")
(is (= "Threat Assessment" (:title (first (:rfg (get-contestant))))) "Threat Assessment removed from game")
(play-from-hand state :contestant "Threat Assessment")
(prompt-select :contestant (find-card "Corroder" (-> (get-challenger) :rig :resource)))
(prompt-choice :challenger "Move Corroder")
(is (= 2 (:tag (get-challenger))) "Challenger didn't take tags")
(is (= "Corroder" (:title (first (:deck (get-challenger))))) "Moved Corroder to the deck")
(is (= 2 (count (:rfg (get-contestant)))))
(take-credits state :challenger)
(take-credits state :contestant)
(take-credits state :challenger)
(play-from-hand state :contestant "Threat Assessment")
(is (empty? (:prompt (get-contestant))) "Threat Assessment triggered with no discard")))
(deftest threat-level-alpha
;; Threat Level Alpha - Win trace to give tags = Challenger tags; or 1 tag if 0
(do-game
(new-game (default-contestant [(qty "Threat Level Alpha" 2)])
(default-challenger))
(core/gain state :contestant :click 2)
(core/gain state :contestant :credit 2)
(is (zero? (:tag (get-challenger))))
(play-from-hand state :contestant "Threat Level Alpha")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger took 1 tag because they had 0")
(core/gain state :challenger :tag 2)
(play-from-hand state :contestant "Threat Level Alpha")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 6 (:tag (get-challenger))) "Challenger took 3 tag because they had 3")))
(deftest transparency-initiative
;; Transparency Initiative - Full test
(do-game
(new-game (default-contestant ["Transparency Initiative" "Oaktown Renovation"
"Project Atlas" "Hostile Takeover" "Casting Call"])
(default-challenger))
(core/gain state :contestant :click 5)
(play-from-hand state :contestant "Oaktown Renovation" "New party")
(play-from-hand state :contestant "Casting Call")
(prompt-select :contestant (find-card "Project Atlas" (:hand (get-contestant))))
(prompt-choice :contestant "New party")
(play-from-hand state :contestant "Hostile Takeover" "New party")
(let [oaktown (get-content state :party1 0)
atlas (get-content state :party2 0)
hostile (get-content state :party3 0)]
(play-from-hand state :contestant "Transparency Initiative")
(prompt-select :contestant (refresh oaktown))
;; doesn't work on face-up agendas
(is (zero? (count (:hosted (refresh oaktown)))))
(prompt-select :contestant (refresh atlas))
(is (= 1 (count (:hosted (refresh atlas)))) "Casting Call")
;; works on facedown agenda
(prompt-select :contestant (refresh hostile))
(is (= 1 (count (:hosted (refresh hostile)))))
;; gains Public subtype
(is (core/has-subtype? (refresh hostile) "Public"))
;; gain 1 credit when advancing
(is (= 5 (:credit (get-contestant))))
(core/advance state :contestant {:card (refresh hostile)})
(is (= 5 (:credit (get-contestant))))
;; make sure advancing other agendas doesn't gain 1
(core/advance state :contestant {:card (refresh oaktown)})
(is (= 6 (:credit (get-contestant))) "Transparency initiative didn't fire")
(core/advance state :contestant {:card (refresh atlas)})
(is (= 5 (:credit (get-contestant))) "Transparency initiative didn't fire"))))
(deftest trojan-horse
;; Trojan Horse
(do-game
(new-game (default-contestant ["Trojan Horse" "Dedicated Response Team"])
(default-challenger ["Wyrm"]))
(play-from-hand state :contestant "Dedicated Response Team" "New party")
(take-credits state :contestant)
(play-from-hand state :challenger "Wyrm")
(run-empty-locale state :party1)
(take-credits state :challenger)
(is (zero? (-> (get-challenger) :discard count)) "Challenger should start with 0 cards in heap")
(play-from-hand state :contestant "Trojan Horse")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-resource state 0))
(is (= 1 (-> (get-challenger) :discard count)) "Wyrm should be in heap after Challenger loses Trojan Horse trace")))
(deftest wake-up-call
;; Wake Up Call
(testing "should fire after using En Passant to discard character"
(do-game
(new-game (default-contestant ["Enigma" "Wake Up Call"])
(default-challenger ["En Passant" "Maya"]))
(play-from-hand state :contestant "Enigma" "HQ")
(take-credits state :contestant)
(play-from-hand state :challenger "Maya")
(run-on state :hq)
(run-successful state)
(prompt-choice :challenger "No action")
(is (zero? (count (:discard (get-contestant)))) "Contestant starts with no discards")
(play-from-hand state :challenger "En Passant")
(prompt-select :challenger (get-character state :hq 0))
(is (= 1 (count (:discard (get-contestant)))) "Contestant discards placed character")
(take-credits state :challenger)
(is (= 1 (count (:discard (get-challenger)))) "Challenger starts with 1 discarded card (En Passant)")
(play-from-hand state :contestant "Wake Up Call")
(prompt-select :contestant (get-hazard state 0))
(prompt-choice :challenger "Discard Maya")
(is (= 2 (count (:discard (get-challenger)))) "Maya is discarded")
(is (= 1 (count (:rfg (get-contestant)))) "Wake Up Call is removed from the game"))))
(deftest wetwork-refit
;; Wetwork Refit - Only works on Bioroid Character and adds a subroutine
(do-game
(new-game (default-contestant ["Eli 1.0"
"Vanilla"
(qty "Wetwork Refit" 3)])
(default-challenger))
(core/gain state :contestant :credit 20)
(core/gain state :contestant :click 10)
(play-from-hand state :contestant "Eli 1.0" "R&D")
(play-from-hand state :contestant "Vanilla" "HQ")
(let [eli (get-character state :rd 0)
vanilla (get-character state :hq 0)]
(play-from-hand state :contestant "Wetwork Refit")
(is (not-any? #{"Eli 1.0"} (get-in @state [:contestant :prompt :choices]))
"Unrevealed Eli 1.0 is not a choice to host Wetwork Refit")
(prompt-choice :contestant "Done")
(take-credits state :contestant)
(take-credits state :challenger)
(core/reveal state :contestant (refresh eli))
(core/reveal state :contestant (refresh vanilla))
(play-from-hand state :contestant "Wetwork Refit")
(prompt-select :contestant (refresh eli))
(is (= "Wetwork Refit" (:title (first (:hosted (refresh eli)))))
"Wetwork Refit is hosted on Eli 1.0")
(is (= 2 (count (:subroutines (refresh eli))))
"Eli 1.0 has 2 different subroutines")
(is (= "[Wetwork Refit] Do 1 brain damage" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has a brain damage subroutine as his first subroutine")
(core/move state :contestant (first (:hosted (refresh eli))) :hand)
(is (empty? (:hosted (refresh eli))) "No cards are hosted on Eli 1.0")
(is (= 1 (count (:subroutines (refresh eli))))
"Eli 1.0 has 1 different subroutine")
(is (= "End the run" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has an end the run subroutine as his first subroutine")
(play-from-hand state :contestant "Wetwork Refit")
(prompt-select :contestant (refresh vanilla))
(is (not= "Wetwork Refit" (:title (first (:hosted (refresh vanilla)))))
"Wetwork Refit is not hosted on Vanilla"))))
| 42167 | (ns game-test.cards.operations
(:require [game.core :as core]
[game-test.core :refer :all]
[game-test.utils :refer :all]
[game-test.macros :refer :all]
[clojure.test :refer :all]))
(use-fixtures :once load-all-cards (partial reset-card-defs "operations"))
(deftest ^{:card-title "24/7-news-cycle"}
twenty-four-seven-news
;; 24/7 News Cycle
(testing "Breaking News interaction"
(do-game
(new-game (default-contestant [(qty "Breaking News" 2) (qty "24/7 News Cycle" 3)])
(default-challenger))
(play-from-hand state :contestant "Breaking News" "New party")
(play-from-hand state :contestant "Breaking News" "New party")
(let [ag1 (get-content state :party1 0)
ag2 (get-content state :party2 0)]
(score-agenda state :contestant ag1)
(score-agenda state :contestant ag2)
(take-credits state :contestant)
(is (zero? (:tag (get-challenger)))) ; tags cleared
(take-credits state :challenger)
(play-from-hand state :contestant "24/7 News Cycle")
(prompt-select :contestant (find-card "Breaking News" (:scored (get-contestant))))
(is (= 1 (:agenda-point (get-contestant))) "Forfeited Breaking News")
(prompt-select :contestant (find-card "Breaking News" (:scored (get-contestant))))
(is (= 2 (:tag (get-challenger))) "Challenger given 2 tags")
(take-credits state :contestant 2)
(is (= 2 (:tag (get-challenger))) "Tags remained after Contestant ended turn"))))
(testing "Posted Bounty interaction -- Issue #1043"
(do-game
(new-game (default-contestant [(qty "Posted Bounty" 2) (qty "24/7 News Cycle" 3)])
(default-challenger))
(play-from-hand state :contestant "Posted Bounty" "New party")
(play-from-hand state :contestant "Posted Bounty" "New party")
(let [ag1 (get-content state :party1 0)
ag2 (get-content state :party2 0)]
(score-agenda state :contestant ag1)
(prompt-choice :contestant "No")
(score-agenda state :contestant ag2)
(prompt-choice :contestant "No")
(play-from-hand state :contestant "24/7 News Cycle")
(prompt-select :contestant (find-card "Posted Bounty" (:scored (get-contestant))))
(is (= 1 (:agenda-point (get-contestant))) "Forfeited Posted Bounty")
(prompt-select :contestant (find-card "Posted Bounty" (:scored (get-contestant))))
(prompt-choice :contestant "Yes") ; "Forfeit Posted Bounty to give 1 tag?"
(is (= 1 (:tag (get-challenger))) "Challenger given 1 tag")
(is (= 1 (:bad-publicity (get-contestant))) "Contestant has 1 bad publicity")
(is (zero? (:agenda-point (get-contestant))) "Forfeited Posted Bounty to 24/7 News Cycle"))))
(testing "Swapped agendas are able to be used. #1555"
(do-game
(new-game (default-contestant ["24/7 News Cycle" "Chronos Project"
"Philotic Entanglement" "Profiteering"])
(default-challenger [(qty "Turntable" 3)]))
(score-agenda state :contestant (find-card "Chronos Project" (:hand (get-contestant))))
(score-agenda state :contestant (find-card "Philotic Entanglement" (:hand (get-contestant))))
(take-credits state :contestant)
(play-from-hand state :challenger "Turntable")
(core/steal state :challenger (find-card "Profiteering" (:hand (get-contestant))))
(prompt-choice :challenger "Yes")
(prompt-select :challenger (find-card "Philotic Entanglement" (:scored (get-contestant))))
(is (= 2 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
(take-credits state :challenger)
(play-from-hand state :contestant "24/7 News Cycle")
(prompt-select :contestant (find-card "Chronos Project" (:scored (get-contestant))))
(is (= "Chronos Project" (:title (first (:rfg (get-contestant))))))
;; shouldn't work on an agenda in the Challenger's scored area
(is (= 2 (count (:hand (get-challenger)))))
(prompt-select :contestant (find-card "Philotic Entanglement" (:scored (get-challenger))))
(is (= 2 (count (:hand (get-challenger)))))
;; resolve 'when scored' ability on swapped Profiteering
(is (= 8 (:credit (get-contestant))))
(prompt-select :contestant (find-card "Profiteering" (:scored (get-contestant))))
(prompt-choice :contestant "3")
(is (= 1 (:agenda-point (get-contestant))))
(is (= 3 (:bad-publicity (get-contestant))))
(is (= 23 (:credit (get-contestant))) "Gained 15 credits"))))
(deftest accelerated-diagnostics
;; Accelerated Diagnostics - Interaction with prompt effects, like Shipment from SanSan
(testing "Basic test"
(do-game
(new-game (default-contestant ["Accelerated Diagnostics" "Cerebral Overwriter" "Shipment from SanSan"
"Hedge Fund" "Back Channels"])
(default-challenger))
(starting-hand state :contestant ["Accelerated Diagnostics" "Cerebral Overwriter"])
(play-from-hand state :contestant "Cerebral Overwriter" "New party")
(core/gain state :contestant :credit 1)
(play-from-hand state :contestant "Accelerated Diagnostics")
(let [playarea (get-in @state [:contestant :play-area])
hf (find-card "Hedge Fund" playarea)
ss (find-card "Shipment from SanSan" playarea)
bc (find-card "Back Channels" playarea)
co (get-content state :party1 0)]
(is (= 3 (count playarea)) "3 cards in play area")
(prompt-select :contestant ss)
(prompt-choice :contestant "2")
(prompt-select :contestant co)
(is (= 2 (get-counters (refresh co) :advancement)) "Cerebral Overwriter gained 2 advancements")
(prompt-select :contestant hf)
(is (= 9 (:credit (get-contestant))) "Contestant gained credits from Hedge Fund")
(prompt-select :contestant bc)
(prompt-select :contestant (refresh co))
(is (= 15 (:credit (get-contestant))) "Contestant gained 6 credits for Back Channels"))))
(testing "Interaction with Current"
(do-game
(new-game (default-contestant ["Accelerated Diagnostics" "Cerebral Overwriter"
"Enhanced Login Protocol" "Shipment from SanSan"
"Hedge Fund"])
(default-challenger))
(starting-hand state :contestant ["Accelerated Diagnostics" "Cerebral Overwriter"])
(play-from-hand state :contestant "Cerebral Overwriter" "New party")
(core/gain state :contestant :credit 3)
(play-from-hand state :contestant "Accelerated Diagnostics")
(let [playarea (get-in @state [:contestant :play-area])
hf (find-card "Hedge Fund" playarea)
ss (find-card "Shipment from SanSan" playarea)
elp (find-card "Enhanced Login Protocol" playarea)
co (get-content state :party1 0)]
(is (= 3 (count playarea)) "3 cards in play area")
(prompt-select :contestant elp)
(is (= "Enhanced Login Protocol" (:title (first (get-in @state [:contestant :current]))))
"Enhanced Login Protocol active in Current area")
(prompt-select :contestant ss)
(prompt-choice :contestant "2")
(prompt-select :contestant co)
(is (= 2 (get-counters (refresh co) :advancement)) "Cerebral Overwriter gained 2 advancements")
(prompt-select :contestant hf)
(is (= 9 (:credit (get-contestant))) "Contestant gained credits from Hedge Fund")))))
(deftest an-offer-you-can't-refuse
;; An Offer You Can't Refuse - exact card added to score area, not the last discarded one
(do-game
(new-game (default-contestant ["Celebrity Gift" "An Offer You Can't Refuse"])
(default-challenger))
(play-from-hand state :contestant "An Offer You Can't Refuse")
(prompt-choice :contestant "R&D")
(core/move state :contestant (find-card "Celebrity Gift" (:hand (get-contestant))) :discard)
(is (= 2 (count (:discard (get-contestant)))))
(prompt-choice :challenger "No")
(is (= 1 (:agenda-point (get-contestant))) "An Offer the Challenger refused")
(is (= 1 (count (:scored (get-contestant)))))
(is (find-card "An Offer You Can't Refuse" (:scored (get-contestant))))
(is (= 1 (count (:discard (get-contestant)))))
(is (find-card "Celebrity Gift" (:discard (get-contestant))))))
(deftest big-brother
;; Big Brother - Give the Challenger 2 tags if already tagged
(do-game
(new-game (default-contestant ["Big Brother"])
(default-challenger))
(play-from-hand state :contestant "Big Brother")
(is (= 1 (count (:hand (get-contestant)))) "Card not played because Challenger has no tags")
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "Big Brother")
(is (= 3 (:tag (get-challenger))) "Challenger gained 2 tags")))
(deftest biotic-labor
;; Biotic Labor - Gain 2 clicks
(do-game
(new-game (default-contestant ["Biotic Labor"])
(default-challenger))
(play-from-hand state :contestant "Biotic Labor")
(is (= 1 (:credit (get-contestant))))
(is (= 4 (:click (get-contestant))) "Spent 1 click to gain 2 additional clicks")))
(deftest blue-level-clearance
;; Blue Level Clearance - Gain 5 credits and draw 2 cards
(do-game
(new-game (default-contestant [(qty "Blue Level Clearance" 3)
(qty "Hedge Fund" 3)
(qty "Sweeps Week" 2)])
(default-challenger))
(play-from-hand state :contestant "Blue Level Clearance")
(is (= 8 (:credit (get-contestant))) "Gained 5 credits")
(is (= 1 (:click (get-contestant))))
(is (= 7 (count (:hand (get-contestant)))) "Drew 2 cards")))
(deftest casting-call
;; Casting Call - Only do card-init on the Public agendas. Issue #1128
(do-game
(new-game (default-contestant [(qty "Casting Call" 2) "Oaktown Renovation"
"Improved Tracers" "<NAME>unter"])
(default-challenger))
(core/gain state :contestant :click 1)
(play-from-hand state :contestant "Hunter" "HQ")
(let [hunter (get-character state :hq 0)]
(core/reveal state :contestant hunter)
(is (= 4 (:current-strength (refresh hunter))))
(play-from-hand state :contestant "Casting Call")
(prompt-select :contestant (find-card "Improved Tracers" (:hand (get-contestant))))
(prompt-choice :contestant "New party")
(let [imptrac (get-content state :party1 0)]
(is (:revealed (refresh imptrac)) "Improved Tracers is faceup")
(is (= 4 (:current-strength (refresh hunter))) "Hunter hasn't gained strength")
(play-from-hand state :contestant "Casting Call")
(prompt-select :contestant (find-card "<NAME>own Renovation" (:hand (get-contestant))))
(prompt-choice :contestant "New party")
(let [oak (get-content state :party2 0)]
(core/advance state :contestant {:card (refresh oak)})
(is (= 5 (:credit (get-contestant))) "Events on Public agenda work; gained 2 credits from advancing")
(take-credits state :contestant)
(run-empty-locale state "Locale 2")
(prompt-select :challenger oak)
(prompt-choice :challenger "Steal")
(is (= 2 (:tag (get-challenger))) "Challenger took 2 tags from accessing agenda with Casting Call hosted on it"))))))
(deftest cerebral-cast
;; Cerebral Cast
(testing "Challenger wins"
(do-game
(new-game (default-contestant ["Cerebral Cast"])
(default-challenger))
(play-from-hand state :contestant "Cerebral Cast")
(is (= 3 (:click (get-contestant))) "Cerebral Cast precondition not met; card not played")
(take-credits state :contestant)
(run-empty-locale state "Archives")
(take-credits state :challenger)
(play-from-hand state :contestant "Cerebral Cast")
(prompt-choice :contestant "0 [Credits]")
(prompt-choice :challenger "0 [Credits]")
(is (zero? (count (:discard (get-challenger)))) "Challenger took no damage")
(is (zero? (:tag (get-challenger))) "Challenger took no tags")))
(testing "Contestant wins"
(do-game
(new-game (default-contestant [(qty "Cerebral Cast" 2)])
(default-challenger))
(take-credits state :contestant)
(run-empty-locale state "Archives")
(take-credits state :challenger)
(play-from-hand state :contestant "Cerebral Cast")
(prompt-choice :contestant "0 [Credits]")
(prompt-choice :challenger "1 [Credits]")
(prompt-choice :challenger "1 brain damage")
(is (= 1 (count (:discard (get-challenger)))) "Challenger took a brain damage")
(is (zero? (:tag (get-challenger))) "Challenger took no tags from brain damage choice")
(play-from-hand state :contestant "Cerebral Cast")
(prompt-choice :contestant "0 [Credits]")
(prompt-choice :challenger "1 [Credits]")
(prompt-choice :challenger "1 tag")
(is (= 1 (count (:discard (get-challenger)))) "Challenger took no additional damage")
(is (= 1 (:tag (get-challenger))) "Challenger took a tag from Cerebral Cast choice"))))
(deftest cerebral-static
;; Cerebral Static
(testing "vs Chaos Theory"
(do-game
(new-game (default-contestant ["Cerebral Static" "Lag Time"])
(make-deck "Chaos Theory: Wünderkind" [(qty "Sure Gamble" 3)]))
(is (= 5 (core/available-mu state)) "CT starts with 5 memory")
(play-from-hand state :contestant "Cerebral Static")
(is (= 4 (core/available-mu state)) "Cerebral Static causes CT to have 4 memory")
(play-from-hand state :contestant "Lag Time")
(is (= 5 (core/available-mu state)) "CT 5 memory restored"))))
(deftest closed-accounts
;; Closed Accounts - Play if Challenger is tagged to make Challenger lose all credits
(do-game
(new-game (default-contestant ["Closed Accounts"])
(default-challenger))
(play-from-hand state :contestant "Closed Accounts")
(is (and (= 3 (:click (get-contestant)))
(= 5 (:credit (get-challenger))))
"Closed Accounts precondition not met; card not played")
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "Closed Accounts")
(is (zero? (:credit (get-challenger))) "Challenger lost all credits")))
(deftest commercialization
;; Commercialization
(testing "Single advancement token"
(do-game
(new-game (default-contestant ["Commercialization"
"Character Wall"])
(default-challenger))
(play-from-hand state :contestant "Character Wall" "HQ")
(core/add-counter state :contestant (refresh (get-character state :hq 0)) :advancement 1)
(play-from-hand state :contestant "Commercialization")
(prompt-select :contestant (refresh (get-character state :hq 0)))
(is (= 6 (:credit (get-contestant))) "Gained 1 for single advanced character from Commercialization")))
(testing "Two advancement tokens"
(do-game
(new-game (default-contestant ["Commercialization"
"Character Wall"])
(default-challenger))
(play-from-hand state :contestant "Character Wall" "HQ")
(core/add-counter state :contestant (refresh (get-character state :hq 0)) :advancement 2)
(play-from-hand state :contestant "Commercialization")
(prompt-select :contestant (refresh (get-character state :hq 0)))
(is (= 7 (:credit (get-contestant))) "Gained 2 for double advanced character from Commercialization"))))
(deftest consulting-visit
;; Consulting Visit - Only show single copies of operations contestant can afford as choices. Play chosen operation
(testing "Basic test"
(do-game
(new-game (default-contestant ["Consulting Visit"
(qty "Beanstalk Royalties" 2)
"Green Level Clearance"
"Breaking News"
"Hedge Fund"])
(default-challenger))
(is (= 5 (:credit (get-contestant))))
(starting-hand state :contestant ["Consulting Visit"])
(play-from-hand state :contestant "Consulting Visit")
(let [get-prompt (fn [] (first (#(get-in @state [:contestant :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-card :contestant (find-card "Beanstalk Royalties" (:deck (get-contestant))))
(is (= 6 (:credit (get-contestant)))))))
(testing "Works properly when played with Mumbad City Hall"
(do-game
(new-game (default-contestant ["Mumbad City Hall"
"Beanstalk Royalties"
"Green Level Clearance"
"Breaking News"
"Hedge Fund"
"Consulting Visit"
"Mumba Temple"])
(default-challenger))
(is (= 5 (:credit (get-contestant))))
(starting-hand state :contestant ["Mumbad City Hall"])
(play-from-hand state :contestant "Mumbad City Hall" "New party")
(let [hall (get-content state :party1 0)
get-prompt (fn [] (first (#(get-in @state [:contestant :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(card-ability state :contestant hall 0)
(is (= (list "Consulting Visit" "Mumba Temple" nil) (prompt-names)))
(prompt-card :contestant (find-card "Consulting Visit" (:deck (get-contestant))))
(is (= 3 (:credit (get-contestant))))
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-card :contestant (find-card "Green Level Clearance" (:deck (get-contestant))))
(is (= 5 (:credit (get-contestant))))))))
(deftest death-and-taxes
;; Death and Taxes gain credit on challenger place, challenger discard placed card
;; Also regression test for #3160
(do-game
(new-game (default-contestant ["Death and Taxes" "PAD Campaign"])
(default-challenger ["Aumakua" "DaVinci" "Fall Guy"]))
(play-from-hand state :contestant "Death and Taxes")
(is (= (- 5 2) (:credit (get-contestant))) "Contestant paid 2 to play Death and Taxes")
(play-from-hand state :contestant "PAD Campaign" "New party")
(take-credits state :contestant)
(let [contestant-creds (:credit (get-contestant))]
(discard-from-hand state :challenger "Da<NAME>")
(is (= contestant-creds (:credit (get-contestant))) "Contestant did not gain credit when challenger discards / discards from hand")
(play-from-hand state :challenger "Aumakua")
(is (= (+ 1 contestant-creds) (:credit (get-contestant))) "Contestant gained 1 when challenger placed Aumakua")
(play-from-hand state :challenger "Fall Guy")
(is (= (+ 2 contestant-creds) (:credit (get-contestant))) "Contestant gained 1 when challenger placed Fall Guy")
(card-ability state :challenger (get-radicle state 0) 1)
(is (= (+ 3 contestant-creds) (:credit (get-contestant))) "Contestant gained 1 when challenger discarded Fall Guy")
(run-empty-locale state :party1)
(prompt-choice-partial :challenger "Pay") ;; Challenger discards PAD Campaign
(is (= (+ 4 contestant-creds) (:credit (get-contestant))) "Contestant gained 1 when challenger discarded PAD Campaign"))))
(deftest defective-brainchips
;; Defective Brainchips - Do 1 add'l brain damage the first time Challenger takes some each turn
(do-game
(new-game (default-contestant ["Defective Brainchips" "Viktor 1.0"])
(default-challenger [(qty "Sure Gamble" 2) (qty "Shiv" 2)]))
(play-from-hand state :contestant "Defective Brainchips")
(play-from-hand state :contestant "Viktor 1.0" "HQ")
(take-credits state :contestant)
(run-on state :hq)
(let [vik (get-character state :hq 0)]
(core/reveal state :contestant vik)
(card-subroutine state :contestant vik 0)
(is (= 2 (count (:discard (get-challenger)))) "2 cards lost to brain damage")
(is (= 2 (:brain-damage (get-challenger))) "Brainchips dealt 1 additional brain dmg")
(card-subroutine state :contestant vik 0)
(is (= 3 (count (:discard (get-challenger)))) "2 cards lost to brain damage")
(is (= 3 (:brain-damage (get-challenger))) "Brainchips didn't do additional brain dmg"))))
(deftest distract-the-masses
(do-game
(new-game (default-contestant [(qty "Distract the Masses" 2) (qty "Hedge Fund" 3)])
(default-challenger))
(starting-hand state :contestant ["Hedge Fund" "Hedge Fund" "Hedge Fund" "Distract the Masses" "Distract the Masses"])
(play-from-hand state :contestant "Distract the Masses")
(prompt-select :contestant (first (:hand (get-contestant))))
(prompt-select :contestant (first (next (:hand (get-contestant)))))
(prompt-select :contestant (first (:discard (get-contestant))))
(prompt-choice :contestant "Done")
(is (= 1 (count (:discard (get-contestant)))) "1 card still discarded")
(is (= 1 (count (:deck (get-contestant)))) "1 card shuffled into R&D")
(is (= 1 (count (:rfg (get-contestant)))) "Distract the Masses removed from game")
(is (= 7 (:credit (get-challenger))) "Challenger gained 2 credits")
(play-from-hand state :contestant "Distract the Masses")
(prompt-select :contestant (first (:hand (get-contestant))))
(prompt-choice :contestant "Done")
(prompt-select :contestant (first (:discard (get-contestant))))
(prompt-select :contestant (first (next (:discard (get-contestant)))))
(is (zero? (count (:discard (get-contestant)))) "No cards left in archives")
(is (= 3 (count (:deck (get-contestant)))) "2 more cards shuffled into R&D")
(is (= 2 (count (:rfg (get-contestant)))) "Distract the Masses removed from game")
(is (= 9 (:credit (get-challenger))) "Challenger gained 2 credits")))
(deftest diversified-portfolio
(do-game
(new-game (default-contestant ["Diversified Portfolio"
"Paper Wall"
(qty "PAD Campaign" 3)])
(default-challenger))
(core/gain state :contestant :click 2)
(play-from-hand state :contestant "Paper Wall" "New party")
(play-from-hand state :contestant "PAD Campaign" "New party")
(play-from-hand state :contestant "PAD Campaign" "New party")
(play-from-hand state :contestant "PAD Campaign" "New party")
(play-from-hand state :contestant "Diversified Portfolio")
(is (= 7 (:credit (get-contestant))) "Ignored party with Character but no locale contents")))
(deftest door-to-door
;; Door to Door
(do-game
(new-game (default-contestant ["Door to Door"])
(default-challenger))
(play-from-hand state :contestant "Door to Door")
(take-credits state :contestant)
(is (zero? (:tag (get-challenger))) "Challenger should start with 0 tags")
(is (= 3 (-> (get-challenger) :hand count)) "Challenger should start with 3 cards in hand")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger should gain 1 tag from Door to Door")
(is (= 3 (-> (get-challenger) :hand count)) "Challenger should start with 3 cards in hand")
(take-credits state :challenger)
(take-credits state :contestant)
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger should still have 1 tag")
(is (= 2 (-> (get-challenger) :hand count)) "Challenger should take 1 meat damage from Door to Door")))
(deftest economic-warfare
;; Economic Warfare - If successful run last turn, make the challenger lose 4 credits if able
(do-game
(new-game (default-contestant [(qty "Economic Warfare" 3)])
(default-challenger))
(play-from-hand state :contestant "Economic Warfare")
(is (= 5 (:credit (get-challenger))) "Challenger has 5 credits")
(is (= 3 (count (:hand (get-contestant)))) "Contestant still has 3 cards")
(take-credits state :contestant)
(run-on state :archives)
(run-successful state)
(take-credits state :challenger)
(play-from-hand state :contestant "Economic Warfare")
(is (= 4 (:credit (get-challenger))) "Challenger has 4 credits")
(play-from-hand state :contestant "Economic Warfare")
(is (zero? (:credit (get-challenger))) "Challenger has 0 credits")
(take-credits state :contestant)
(run-on state :archives)
(take-credits state :challenger)
(play-from-hand state :contestant "Economic Warfare")
(is (= 3 (:credit (get-challenger))) "Challenger has 3 credits")))
(deftest election-day
(do-game
(new-game (default-contestant [(qty "Election Day" 7)])
(default-challenger))
(is (= 6 (count (:hand (get-contestant)))) "Contestant starts with 5 + 1 cards")
(core/move state :contestant (find-card "Election Day" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Election Day" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Election Day" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Election Day" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Election Day" (:hand (get-contestant))) :deck)
(play-from-hand state :contestant "Election Day")
(is (= 1 (count (:hand (get-contestant)))) "Could not play Election Day")
(take-credits state :contestant)
(take-credits state :challenger)
(is (= 2 (count (:hand (get-contestant)))) "Contestant has now 1 + 1 cards before Election Day")
(play-from-hand state :contestant "Election Day")
(is (= 5 (count (:hand (get-contestant)))) "Contestant has now 5 cards due to Election Day")))
(deftest enforcing-loyalty
;; Enforcing Loyalty - Win trace to discard placed card not of Challenger's faction
(do-game
(new-game (default-contestant [(qty "Enforcing Loyalty" 2)])
(make-deck "Chaos Theory: Wünderkind" ["Inti" "Caldera"]))
(take-credits state :contestant)
(play-from-hand state :challenger "<NAME>")
(play-from-hand state :challenger "<NAME>")
(take-credits state :challenger)
(play-from-hand state :contestant "Enforcing Loyalty")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-resource state 0))
(is (empty? (:discard (get-challenger))) "Can't target Inti; matches Challenger faction")
(prompt-select :contestant (get-radicle state 0))
(is (= 1 (count (:discard (get-challenger)))) "<NAME> discarded")))
(deftest enhanced-login-protocol
;; Enhanced Login Protocol
(testing "First click run each turn costs an additional click"
(do-game
(new-game (default-contestant ["Enhanced Login Protocol"])
(default-challenger ["Employee Strike"]))
(play-from-hand state :contestant "Enhanced Login Protocol")
(take-credits state :contestant)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-challenger))) "Challenger spends 1 additional click to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger doesn't spend 1 additional click to make the second run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(take-credits state :challenger 3)
(is (= 1 (:click (get-challenger))) "Challenger has 1 click")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 1 (:click (get-challenger))) "Challenger has 1 click")
(take-credits state :challenger)
(take-credits state :contestant)
(play-from-hand state :challenger "Employee Strike")
(is (= 3 (:click (get-challenger))) "Challenger has 3 clicks")
(run-on state :archives)
(is (= 2 (:click (get-challenger))) "Challenger doesn't spend 1 additional click to make a run")))
(testing "Card ability runs don't cost additional clicks"
(do-game
(new-game (default-contestant ["Enhanced Login Protocol"])
(default-challenger ["Sneakdoor Beta"]))
(play-from-hand state :contestant "Enhanced Login Protocol")
(take-credits state :contestant)
(play-from-hand state :challenger "Sneakdoor Beta")
(take-credits state :challenger)
(take-credits state :contestant)
(is (= 4 (:click (get-challenger))) "Challenger has 2 clicks")
(let [sneakdoor (get-resource state 0)]
(card-ability state :challenger sneakdoor 0)
(is (= 3 (:click (get-challenger))) "Challenger doesn't spend 1 additional click to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger spends 1 additional click to make a run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-challenger))) "Challenger spends 1 additional click to make a run"))))
(testing "with New Angeles Sol, Enhanced Login Protocol discarded and replaced on steal doesn't double remove penalty"
(do-game
(new-game
(make-deck "New Angeles Sol: Your News" ["Enhanced Login Protocol" "Breaking News"])
(default-challenger))
(play-from-hand state :contestant "Breaking News" "New party")
(play-from-hand state :contestant "Enhanced Login Protocol")
(take-credits state :contestant)
(run-on state :party1)
(run-successful state)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Enhanced Login Protocol" (:discard (get-contestant))))
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger has 1 click")))
(testing "Run event don't cost additional clicks"
(do-game
(new-game (default-contestant ["Enhanced Login Protocol"])
(default-challenger ["Out of the Ashes"]))
(play-from-hand state :contestant "Enhanced Login Protocol")
(take-credits state :contestant)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(play-from-hand state :challenger "Out of the Ashes")
(prompt-choice :challenger "Archives")
(is (= 3 (:click (get-challenger))) "Challenger doesn't spend 1 additional click to run with a run event")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger spends 1 additional click to make a run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(prompt-choice :challenger "No") ; Out of the Ashes prompt
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-challenger))) "Challenger spends 1 additional click to make a run")))
(testing "Works when played on the challenger's turn"
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
["Enhanced Login Protocol"
"Breaking News"])
(default-challenger ["Hades Shard"]))
(discard-from-hand state :contestant "Breaking News")
(take-credits state :contestant)
(core/gain state :challenger :credit 2)
(play-from-hand state :challenger "Hades Shard")
(card-ability state :challenger (get-radicle state 0) 0)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Enhanced Login Protocol" (:hand (get-contestant))))
(is (find-card "Enhanced Login Protocol" (:current (get-contestant))) "Enhanced Login Protocol is in play")
(is (= 3 (:click (get-challenger))) "Challenger has 3 clicks")
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger spends 1 additional click to make a run")))
(testing "Doesn't fire if already run when played on the challenger's turn"
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
["Enhanced Login Protocol"
"Breaking News"])
(default-challenger ["Hades Shard"]))
(discard-from-hand state :contestant "Breaking News")
(take-credits state :contestant)
(run-on state :hq)
(run-successful state)
(prompt-choice :challenger "No action")
(core/gain state :challenger :credit 2)
(play-from-hand state :challenger "Hades Shard")
(card-ability state :challenger (get-radicle state 0) 0)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Enhanced Login Protocol" (:hand (get-contestant))))
(is (find-card "Enhanced Login Protocol" (:current (get-contestant))) "Enhanced Login Protocol is in play")
(is (= 2 (:click (get-challenger))) "Challenger has 2 clicks")
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger doesn't spend 1 additional click to make a run"))))
(deftest exchange-of-information
;; Exchange of Information
(testing "Basic test"
(do-game
(new-game (default-contestant ["Exchange of Information"
"Market Research"
"Breaking News"
"Project Beale"
"Explode-a-palooza"])
(default-challenger))
(score-agenda state :contestant (find-card "Market Research" (:hand (get-contestant))))
(score-agenda state :contestant (find-card "Breaking News" (:hand (get-contestant))))
(is (= 2 (:tag (get-challenger))) "Challenger gained 2 tags")
(take-credits state :contestant)
(is (zero? (:tag (get-challenger))) "Challenger lost 2 tags")
(core/steal state :challenger (find-card "Project Beale" (:hand (get-contestant))))
(core/steal state :challenger (find-card "Explode-a-palooza" (:hand (get-contestant))))
(take-credits state :challenger)
(is (= 4 (:agenda-point (get-challenger))))
(is (= 3 (:agenda-point (get-contestant))))
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "Project Beale" (:scored (get-challenger))))
(prompt-select :contestant (find-card "Breaking News" (:scored (get-contestant))))
(is (= 3 (:agenda-point (get-challenger))))
(is (= 4 (:agenda-point (get-contestant))))))
(testing "Swapping a just scored Breaking News keeps the tags"
(do-game
(new-game (default-contestant ["Exchange of Information"
"Market Research"
"Breaking News"
"Project Beale"
"Explode-a-palooza"])
(default-challenger))
(take-credits state :contestant)
(core/steal state :challenger (find-card "Project Beale" (:hand (get-contestant))))
(core/steal state :challenger (find-card "Explode-a-palooza" (:hand (get-contestant))))
(take-credits state :challenger)
(score-agenda state :contestant (find-card "Breaking News" (:hand (get-contestant))))
(is (= 2 (:tag (get-challenger))) "Challenger gained 2 tags")
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "Project Beale" (:scored (get-challenger))))
(prompt-select :contestant (find-card "Breaking News" (:scored (get-contestant))))
(is (= 2 (:tag (get-challenger))) "Still has tags after swap and before end of turn")
(take-credits state :contestant)
(is (= 3 (:agenda-point (get-challenger))))
(is (= 2 (:agenda-point (get-contestant))))
(is (= 2 (:tag (get-challenger))) "Challenger does not lose tags at end of turn")))
(testing "Swapping a 15 Minutes still keeps the ability. #1783"
(do-game
(new-game (default-contestant [(qty "Exchange of Information" 2) "15 Minutes"
"Project Beale"])
(default-challenger))
(score-agenda state :contestant (find-card "15 Minutes" (:hand (get-contestant))))
(take-credits state :contestant)
(core/gain state :challenger :tag 1)
(core/steal state :challenger (find-card "Project Beale" (:hand (get-contestant))))
(take-credits state :challenger)
(is (= 1 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "Project Beale" (:scored (get-challenger))))
(prompt-select :contestant (find-card "15 Minutes" (:scored (get-contestant))))
(is (= 2 (:agenda-point (get-contestant))))
(is (= 1 (:agenda-point (get-challenger))))
(is (zero? (count (:deck (get-contestant)))))
;; shuffle back into R&D from challenger's scored area
(let [fifm (get-scored state :challenger 0)]
(card-ability state :contestant fifm 0))
(is (= 2 (:agenda-point (get-contestant))))
(is (zero? (:agenda-point (get-challenger))))
(is (= "15 Minutes" (:title (first (:deck (get-contestant))))))
(take-credits state :contestant)
(core/steal state :challenger (find-card "15 Minutes" (:deck (get-contestant))))
(take-credits state :challenger)
(is (= 2 (:agenda-point (get-contestant))))
(is (= 1 (:agenda-point (get-challenger))))
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "15 Minutes" (:scored (get-challenger))))
(prompt-select :contestant (find-card "Project Beale" (:scored (get-contestant))))
(is (= 1 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
;; shuffle back into R&D from contestant's scored area
(let [fifm (get-scored state :contestant 0)]
(card-ability state :contestant fifm 0))
(is (= "15 Minutes" (:title (first (:deck (get-contestant))))))))
(testing "Swapping a Mandatory Regions gives the Contestant an additional click per turn. #1687"
(do-game
(new-game (default-contestant [(qty "Exchange of Information" 2) "Mandatory Regions"
"Global Food Initiative"])
(default-challenger))
(score-agenda state :contestant (find-card "Global Food Initiative" (:hand (get-contestant))))
(take-credits state :contestant)
(core/gain state :challenger :tag 1)
(core/steal state :challenger (find-card "Mandatory Regions" (:hand (get-contestant))))
(take-credits state :challenger)
(is (= 3 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
(is (= 3 (:click (get-contestant))))
(is (= 3 (:click-per-turn (get-contestant))))
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "Mandatory Regions" (:scored (get-challenger))))
(prompt-select :contestant (find-card "Global Food Initiative" (:scored (get-contestant))))
(is (= 2 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
(is (= 3 (:click (get-contestant))))
(is (= 4 (:click-per-turn (get-contestant))))
(take-credits state :contestant)
(take-credits state :challenger)
(is (= 4 (:click (get-contestant))))
(is (= 4 (:click-per-turn (get-contestant))))
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "Global Food Initiative" (:scored (get-challenger))))
(prompt-select :contestant (find-card "Mandatory Regions" (:scored (get-contestant))))
(is (= 3 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
(is (= 2 (:click (get-contestant))))
(is (= 3 (:click-per-turn (get-contestant))))
(take-credits state :contestant)
(take-credits state :challenger)
(is (= 3 (:click (get-contestant))))
(is (= 3 (:click-per-turn (get-contestant)))))))
(deftest foxfire
;; Foxfire
(do-game
(new-game (default-contestant [(qty "Foxfire" 2)])
(default-challenger ["<NAME>" "Character Carver"]))
(take-credits state :contestant)
(core/gain state :challenger :credit 100)
(play-from-hand state :challenger "<NAME>")
(play-from-hand state :challenger "<NAME>")
(take-credits state :challenger)
(play-from-hand state :contestant "Foxfire")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-hazard state 0))
(is (= 1 (-> (get-challenger) :discard count)) "Contestant should discard Dyson Mem Chip from winning Foxfire trace")
(play-from-hand state :contestant "Foxfire")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(is (= 2 (-> (get-challenger) :discard count)) "Contestant should discard Character Car<NAME> from winning Foxfire trace")))
(deftest hard-hitting-news
;; Hard-Hitting News
(do-game
(new-game (default-contestant ["Hard-Hitting News"])
(default-challenger))
(take-credits state :contestant)
(run-empty-locale state :rd)
(take-credits state :challenger)
(is (= 3 (:click (get-contestant))) "Contestant should start with 3 clicks")
(play-from-hand state :contestant "Hard-Hitting News")
(is (zero? (:click (get-contestant))) "Playing Hard-Hitting News should lose all remaining clicks")
(is (zero? (:tag (get-challenger))) "Challenger should start with 0 tags")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 4 (:tag (get-challenger))) "Challenger should gain 4 tags from losing Hard-Hitting News trace")))
(deftest hatchet-job
;; Hatchet Job - Win trace to add placed non-virtual to grip
(do-game
(new-game (default-contestant ["Hatchet Job"])
(default-challenger ["Upya" "Ghost Challenger"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Ghost Challenger")
(play-from-hand state :challenger "Upya")
(take-credits state :challenger)
(play-from-hand state :contestant "Hatchet Job")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(is (empty? (:hand (get-challenger))) "Can't choose virtual card")
(is (not (empty? (:prompt (get-contestant)))))
(prompt-select :contestant (get-resource state 0))
(is (= 1 (count (:hand (get-challenger)))) "Upya returned to grip")))
(deftest hedge-fund
(do-game
(new-game (default-contestant) (default-challenger))
(is (= 5 (:credit (get-contestant))))
(play-from-hand state :contestant "Hedge Fund")
(is (= 9 (:credit (get-contestant))))))
(deftest hellion-alpha-test
;; Hellion Alpha Test
(do-game
(new-game (default-contestant [(qty "Hellion Alpha Test" 2)])
(default-challenger ["Daily Casts"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Daily Casts")
(take-credits state :challenger)
(play-from-hand state :contestant "Hellion Alpha Test")
(is (zero? (-> (get-challenger) :deck count)) "Challenger should have no cards in Stack")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(is (= 1 (-> (get-challenger) :deck count)) "Challenger should have 1 card in Stack from losing Hellion Alpha Test trace")
(is (= "Daily Casts" (-> (get-challenger) :deck first :title))
"Challenger should have Daily Casts on top of Stack from losing Hellion Alpha Test trace")
(take-credits state :contestant)
(core/draw state :challenger)
(play-from-hand state :challenger "Daily Casts")
(take-credits state :challenger)
(play-from-hand state :contestant "Hellion Alpha Test")
(is (zero? (:bad-publicity (get-contestant))) "Contestant should start with 0 bad publicity")
(prompt-choice :contestant 0)
(prompt-choice :challenger 2)
(is (= 1 (:bad-publicity (get-contestant))) "Contestant should gain 1 bad publicity from losing Hellion Alpha Test trace")))
(deftest hellion-beta-test
;; Hellion Beta Test
(testing "Winning Trace - Discarding 2 cards"
(do-game
(new-game (default-contestant ["Dedicated Response Team" "Hellion Beta Test"])
(default-challenger ["Daily Casts" "<NAME>"]))
(play-from-hand state :contestant "Dedicated Response Team" "New party")
(take-credits state :contestant)
(core/gain state :challenger :credit 100)
(play-from-hand state :challenger "Daily Casts")
(play-from-hand state :challenger "<NAME>")
(run-empty-locale state :party1)
(prompt-choice-partial :challenger "Pay")
(take-credits state :challenger)
(is (zero? (-> (get-challenger) :discard count)) "Challenger's heap should be empty")
(play-from-hand state :contestant "Hellion Beta Test")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(prompt-select :contestant (get-hazard state 0))
(is (= 2 (-> (get-challenger) :discard count)) "Challenger should have 2 cards in heap after losing Hellion Beta Test trace")))
(testing "Losing trace - Gaining bad publicity"
(do-game
(new-game (default-contestant ["Dedicated Response Team" "Hellion Beta Test"])
(default-challenger ["Daily Casts" "<NAME>"]))
(play-from-hand state :contestant "Dedicated Response Team" "New party")
(take-credits state :contestant)
(core/gain state :challenger :credit 100)
(play-from-hand state :challenger "Daily Casts")
(play-from-hand state :challenger "<NAME>")
(run-empty-locale state :party1)
(prompt-choice-partial :challenger "Pay")
(take-credits state :challenger)
(is (zero? (:bad-publicity (get-contestant))) "Contestant should start with 0 bad publicity")
(play-from-hand state :contestant "Hellion Beta Test")
(prompt-choice :contestant 0)
(prompt-choice :challenger 2)
(is (= 1 (:bad-publicity (get-contestant))) "Contestant should gain 1 bad publicity from losing Hellion Beta Test trace"))))
(deftest high-profile-target
(testing "when the challenger has no tags"
(do-game
(new-game (default-contestant [(qty "High-Profile Target" 6)])
(default-challenger [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(play-from-hand state :contestant "High-Profile Target")
(is (= 3 (:click (get-contestant))) "Contestant not charged a click")
(is (= 5 (count (:hand (get-challenger)))) "Challenger did not take damage")))
(testing "when the challenger has one tag"
(do-game
(new-game (default-contestant [(qty "High-Profile Target" 6)])
(default-challenger [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "High-Profile Target")
(is (= 3 (count (:hand (get-challenger)))) "Challenger has 3 cards in hand")))
(testing "when the challenger has two tags"
(do-game
(new-game (default-contestant [(qty "High-Profile Target" 6)])
(default-challenger [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :challenger :tag 2)
(play-from-hand state :contestant "High-Profile Target")
(is (= 1 (count (:hand (get-challenger)))) "Challenger has 1 card in hand")))
(testing "When the challenger has three tags, gg"
(do-game
(new-game (default-contestant [(qty "High-Profile Target" 10)])
(default-challenger))
(core/gain state :challenger :tag 3)
(play-from-hand state :contestant "High-Profile Target")
(is (zero? (count (:hand (get-challenger)))) "Challenger has 0 cards in hand")
(is (= :contestant (:winner @state)) "Contestant wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline"))))
(deftest housekeeping
;; Housekeeping - Challenger must discard a card from Grip on first place of a turn
(do-game
(new-game (default-contestant ["Housekeeping"])
(default-challenger [(qty "Cache" 2) "Fall Guy" "<NAME>"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Fall Guy")
(take-credits state :challenger)
(play-from-hand state :contestant "Housekeeping")
(take-credits state :contestant)
(play-from-hand state :challenger "Cache")
(prompt-select :challenger (find-card "<NAME>" (:hand (get-challenger))))
(is (empty? (:prompt (get-challenger))) "Fall Guy prevention didn't trigger")
(is (= 1 (count (:discard (get-challenger)))) "Card discarded")
(play-from-hand state :challenger "Cache")
(is (empty? (:prompt (get-challenger))) "Housekeeping didn't trigger on 2nd place")))
(deftest invasion-of-privacy
;; Invasion of Privacy - Full test
(do-game
(new-game (default-contestant [(qty "Invasion of Privacy" 3)])
(default-challenger [(qty "Sure Gamble" 2) "Fall Guy" (qty "Cache" 2)]))
(core/gain state :contestant :click 3 :credit 6)
;; discard 2 cards
(play-from-hand state :contestant "Invasion of Privacy")
(prompt-choice :contestant 0) ; default trace
(prompt-choice :challenger 0) ; Challenger won't match
(is (= 5 (count (:hand (get-challenger)))))
(let [get-prompt (fn [] (first (#(get-in @state [:contestant :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" "Sure Gamble" nil) (prompt-names)))
(prompt-card :contestant (find-card "Sure Gamble" (:hand (get-challenger))))
(prompt-card :contestant (find-card "Sure Gamble" (:hand (get-challenger)))))
(is (= 3 (count (:hand (get-challenger)))))
;; able to discard 2 cards but only 1 available target in Challenger's hand
(play-from-hand state :contestant "Invasion of Privacy")
(prompt-choice :contestant 0) ; default trace
(prompt-choice :challenger 0) ; Challenger won't match
(is (= 3 (count (:hand (get-challenger)))))
(let [get-prompt (fn [] (first (#(get-in @state [:contestant :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" nil) (prompt-names)))
(prompt-card :contestant (find-card "Fall Guy" (:hand (get-challenger))))
(is (empty? (get-in @state [:contestant :prompt])) "No prompt for second card"))
(is (= 2 (count (:hand (get-challenger)))))
;; failed trace - take the bad publicity
(play-from-hand state :contestant "Invasion of Privacy")
(prompt-choice :contestant 0) ; default trace
(prompt-choice :challenger 2) ; Challenger matches
(is (= 1 (:bad-publicity (get-contestant))))))
(deftest ipo
;; IPO - credits with Terminal operations
(do-game
(new-game
(default-contestant ["IPO"])
(default-challenger))
(take-credits state :contestant)
(take-credits state :challenger)
(play-from-hand state :contestant "IPO")
(is (= 13 (:credit (get-contestant))))
(is (zero? (:click (get-contestant))) "Terminal ends turns")))
(deftest kill-switch
;; Kill Switch
(do-game
(new-game (default-contestant ["Kill Switch" (qty "Hostile Takeover" 2)])
(default-challenger))
(play-from-hand state :contestant "Kill Switch")
(play-from-hand state :contestant "Hostile Takeover" "New party")
(is (zero? (:brain-damage (get-challenger))) "Challenger should start with 0 brain damage")
(play-and-score state "Hostile Takeover")
(prompt-choice :contestant "Hostile Takeover")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:brain-damage (get-challenger))) "Challenger should get 1 brain damage from Kill Switch after Contestant scores an agenda")
(take-credits state :contestant)
(run-empty-locale state :party1)
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 2 (:brain-damage (get-challenger))) "Challenger should get 1 brain damage from Kill Switch after accecssing an agenda")))
(deftest lag-time
(do-game
(new-game (default-contestant ["Lag Time" "Vanilla" "Lotus Field"])
(default-challenger))
(take-credits state :contestant)
(take-credits state :challenger)
(play-from-hand state :contestant "Vanilla" "HQ")
(play-from-hand state :contestant "Lotus Field" "R&D")
(play-from-hand state :contestant "Lag Time")
(core/reveal state :contestant (get-character state :hq 0))
(core/reveal state :contestant (get-character state :rd 0))
(is (= 1 (:current-strength (get-character state :hq 0))) "Vanilla at 1 strength")
(is (= 5 (:current-strength (get-character state :rd 0))) "Lotus Field at 5 strength")))
(deftest lateral-growth
(do-game
(new-game (default-contestant ["Lateral Growth" "Breaking News"])
(default-challenger))
(is (= 5 (:credit (get-contestant))))
(play-from-hand state :contestant "Lateral Growth")
(prompt-select :contestant (find-card "Breaking News" (:hand (get-contestant))))
(prompt-choice :contestant "New party")
(is (= "Breaking News" (:title (get-content state :party1 0)))
"Breaking News placed by Lateral Growth")
(is (= 7 (:credit (get-contestant))))))
(deftest manhunt
;; Manhunt - only fires once per turn. Unreported issue.
(do-game
(new-game (default-contestant ["Manhunt" (qty "Hedge Fund" 3)])
(default-challenger))
(play-from-hand state :contestant "Manhunt")
(take-credits state :contestant)
(run-empty-locale state "HQ")
(is (:prompt (get-contestant)) "Manhunt trace initiated")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger took 1 tag")
(prompt-choice :challenger "No action")
(is (not (:run @state)) "Run ended")
(run-empty-locale state "HQ")
(is (empty? (:prompt (get-contestant))) "No Manhunt trace on second run")
(prompt-choice :challenger "No action")
(is (not (:run @state)) "Run ended")))
(deftest market-forces
(testing "Full test"
(letfn [(market-forces-credit-test
[{:keys [tag-count challenger-creds expected-credit-diff]}]
(testing (str "when the challenger has " tag-count " tags and " challenger-creds " credits")
(do-game
(new-game (default-contestant [(qty "Market Forces" 6)])
(default-challenger))
(swap! state assoc-in [:contestant :credit] 0)
(swap! state assoc-in [:challenger :credit] challenger-creds)
(core/gain state :challenger :tag tag-count)
(play-from-hand state :contestant "Market Forces")
(is (= expected-credit-diff (:credit (get-contestant)))
(str "the contestant gains " expected-credit-diff " credits"))
(is (= expected-credit-diff (- challenger-creds (:credit (get-challenger))))
(str "the challenger loses " expected-credit-diff " credits")))))]
(doall (map market-forces-credit-test
[{:tag-count 1
:challenger-creds 10
:expected-credit-diff 3}
{:tag-count 2
:challenger-creds 10
:expected-credit-diff 6}
{:tag-count 3
:challenger-creds 10
:expected-credit-diff 9}
{:tag-count 3
:challenger-creds 0
:expected-credit-diff 0}
{:tag-count 3
:challenger-creds 5
:expected-credit-diff 5}]))))
(testing "when the challenger is not tagged"
(do-game
(new-game (default-contestant [(qty "Market Forces" 6)])
(default-challenger))
(play-from-hand state :contestant "Market Forces")
(is (= 6 (count (:hand (get-contestant))))
"Market Forces is not played")
(is (= 3 (:click (get-contestant)))
"the contestant does not spend a click")
(is (= 5 (:credit (get-contestant)) (:credit (get-challenger)))
"credits are unaffected"))))
(deftest mass-commercialization
;; Mass Commercialization
(do-game
(new-game (default-contestant ["Mass Commercialization"
(qty "Character Wall" 3)])
(default-challenger))
(play-from-hand state :contestant "Character Wall" "HQ")
(play-from-hand state :contestant "Character Wall" "R&D")
(play-from-hand state :contestant "Character Wall" "Archives")
(take-credits state :challenger)
(core/advance state :contestant {:card (refresh (get-character state :hq 0))})
(core/advance state :contestant {:card (refresh (get-character state :archives 0))})
(core/advance state :contestant {:card (refresh (get-character state :rd 0))})
(take-credits state :challenger)
(play-from-hand state :contestant "Mass Commercialization")
(is (= 8 (:credit (get-contestant))) "Gained 6 for 3 advanced character from Mass Commercialization")))
(deftest medical-research-fundraiser
;; Medical Research Fundraiser - challenger gains 8creds, challenger gains 3creds
(do-game
(new-game (default-contestant ["Medical Research Fundraiser"])
(default-challenger))
(is (= 5 (:credit (get-contestant))) "Contestant starts with 5 credits")
(is (= 5 (:credit (get-challenger))) "Challenger starts with 5 credits")
(play-from-hand state :contestant "Medical Research Fundraiser")
(is (= 10 (:credit (get-contestant))) "Contestant gains 8 credits")
(is (= 8 (:credit (get-challenger))) "Challenger gains 3 credits")))
(deftest midseason-replacements
;; Midseason Replacements - Trace to give Challenger tags after they steal an agenda
(do-game
(new-game (default-contestant ["Midseason Replacements" "Breaking News"])
(default-challenger))
(play-from-hand state :contestant "Midseason Replacements")
(is (= 3 (:click (get-contestant))) "Midseason precondition not met; Contestant not charged a click")
(play-from-hand state :contestant "Breaking News" "New party")
(take-credits state :contestant)
(is (= 7 (:credit (get-contestant))))
(let [bn (get-content state :party1 0)]
(run-empty-locale state "Locale 1")
(prompt-choice :challenger "Steal")
(is (= 1 (:agenda-point (get-challenger))) "Stole Breaking News")
(take-credits state :challenger)
(play-from-hand state :contestant "Midseason Replacements")
(prompt-choice :contestant 0) ; default trace
(prompt-choice :challenger 0) ; Challenger won't match
(is (= 6 (:tag (get-challenger))) "Challenger took 6 tags"))))
(deftest mushin-no-shin
;; Mushin No Shin - Add 3 advancements to a card; prevent reveal/score of that card the rest of the turn
(do-game
(new-game (default-contestant [(qty "Mushin No Shin" 2) "Ronin" "Profiteering"])
(default-challenger))
(play-from-hand state :contestant "Mushin No Shin")
(prompt-select :contestant (find-card "Ronin" (:hand (get-contestant))))
(let [ronin (get-content state :party1 0)]
(is (= 3 (get-counters (refresh ronin) :advancement)) "3 advancements placed on Ronin")
(core/reveal state :contestant (refresh ronin))
(is (not (:revealed (refresh ronin))) "Ronin did not reveal")
(take-credits state :contestant)
(take-credits state :challenger)
(core/reveal state :contestant (refresh ronin))
(is (:revealed (refresh ronin)) "Ronin now revealed")
(play-from-hand state :contestant "<NAME>")
(prompt-select :contestant (find-card "Profiteering" (:hand (get-contestant))))
(let [prof (get-content state :party2 0)]
(core/score state :contestant (refresh prof))
(is (empty? (:scored (get-contestant))) "Profiteering not scored")
(is (zero? (:agenda-point (get-contestant))))
(take-credits state :contestant)
(take-credits state :challenger)
(core/score state :contestant (refresh prof))
(prompt-choice :contestant "0")
(is (= 1 (:agenda-point (get-contestant))) "Profiteering was able to be scored")))))
(deftest mutate
;; Mutate - discard a revealed piece of character, place and reveal one from R&D
(testing "Basic operation"
(do-game
(new-game (default-contestant ["Mutate" "Character Wall" "Enigma" "Hedge Fund"])
(default-challenger))
(core/move state :contestant (find-card "Hedge Fund" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Enigma" (:hand (get-contestant))) :deck)
(play-from-hand state :contestant "Character Wall" "HQ")
(core/reveal state :contestant (get-character state :hq 0))
(is (= 1 (count (get-character state :hq))) "1 character placed")
(is (= "Character Wall" (:title (get-character state :hq 0))) "Character Wall is placed")
(play-from-hand state :contestant "Mutate")
(prompt-select :contestant (get-character state :hq 0))
(is (= 1 (count (get-character state :hq))) "1 character placed")
(is (= "Enigma" (:title (get-character state :hq 0))) "Enigma is placed")
(is (:revealed (get-character state :hq 0)) "Enigma is revealed")
(is (second-last-log-contains? state "Hedge Fund") "Skipped card name was logged")
(is (second-last-log-contains? state "Enigma") "Placed card name was logged")))
(testing "No character in R&D"
(do-game
(new-game (default-contestant ["Mutate" "Character Wall" "Enigma" "Hedge Fund"])
(default-challenger))
(core/move state :contestant (find-card "Hedge Fund" (:hand (get-contestant))) :deck)
(play-from-hand state :contestant "Character Wall" "HQ")
(core/reveal state :contestant (get-character state :hq 0))
(is (= 1 (count (get-character state :hq))) "1 character placed")
(is (= "Character Wall" (:title (get-character state :hq 0))) "Character Wall is placed")
(play-from-hand state :contestant "Mutate")
(prompt-select :contestant (get-character state :hq 0))
(is (empty? (get-character state :hq)) "No character placed")
(is (second-last-log-contains? state "Hedge Fund") "Skipped card name was logged"))))
(deftest neural-emp
;; Neural EMP - Play if Challenger made a run the previous turn to do 1 net damage
(do-game
(new-game (default-contestant ["Neural EMP"])
(default-challenger))
(play-from-hand state :contestant "Neural EMP")
(is (= 3 (:click (get-contestant))) "Neural precondition not met; card not played")
(take-credits state :contestant)
(run-empty-locale state "Archives")
(take-credits state :challenger)
(play-from-hand state :contestant "Neural EMP")
(is (= 1 (count (:discard (get-challenger)))) "Challenger took 1 net damage")))
(deftest oversight-ai
;; Oversight AI - Reveal a piece of Character ignoring all costs
(do-game
(new-game (default-contestant ["Oversight AI" "Archer"])
(default-challenger))
(play-from-hand state :contestant "Archer" "R&D")
(let [archer (get-character state :rd 0)]
(play-from-hand state :contestant "Oversight AI")
(prompt-select :contestant archer)
(is (:revealed (refresh archer)))
(is (= 4 (:credit (get-contestant))) "Archer revealed at no credit cost")
(is (= "Oversight AI" (:title (first (:hosted (refresh archer)))))
"Archer hosting OAI as a condition"))))
(deftest patch
;; Patch - +2 current strength
(do-game
(new-game (default-contestant ["Patch" "Vanilla"])
(default-challenger))
(play-from-hand state :contestant "Vanilla" "HQ")
(core/reveal state :contestant (get-character state :hq 0))
(play-from-hand state :contestant "Patch")
(prompt-select :contestant (get-character state :hq 0))
(is (= 2 (:current-strength (get-character state :hq 0))) "Vanilla at 2 strength")))
(deftest paywall-implementation
;; Paywall Implementation - Gain 1 credit for every successful run
(do-game
(new-game (default-contestant ["Paywall Implementation"])
(default-challenger))
(play-from-hand state :contestant "Paywall Implementation")
(is (= "Paywall Implementation" (:title (first (get-in @state [:contestant :current]))))
"Paywall active in Current area")
(take-credits state :contestant)
(is (= 7 (:credit (get-contestant))))
(run-empty-locale state "Archives")
(is (= 8 (:credit (get-contestant))) "Gained 1 credit from successful run")
(run-empty-locale state "Archives")
(is (= 9 (:credit (get-contestant))) "Gained 1 credit from successful run")))
(deftest peak-efficiency
;; Peak Efficiency - Gain 1 credit for each revealed Character
(do-game
(new-game (default-contestant ["Peak Efficiency" (qty "Paper Wall" 3) "Wraparound"])
(default-challenger))
(core/gain state :contestant :click 3)
(play-from-hand state :contestant "Paper Wall" "HQ")
(play-from-hand state :contestant "Paper Wall" "R&D")
(play-from-hand state :contestant "Paper Wall" "New party")
(play-from-hand state :contestant "Wraparound" "New party")
(core/reveal state :contestant (get-character state :hq 0))
(core/reveal state :contestant (get-character state :rd 0))
(core/reveal state :contestant (get-character state :party1 0))
(play-from-hand state :contestant "Peak Efficiency")
(is (= 7 (:credit (get-contestant))) "Gained 3 credits for 3 revealed Character; unrevealed Character ignored")))
(deftest power-shutdown
;; Power Shutdown - Discard cards from R&D to force Challenger to discard a resource or hazard
(do-game
(new-game (default-contestant [(qty "Power Shutdown" 3) (qty "Hive" 3)])
(default-challenger ["Grimoire" "Cache"]))
(play-from-hand state :contestant "Power Shutdown")
(is (empty? (:discard (get-contestant))) "Not played, no run last turn")
(take-credits state :contestant)
(play-from-hand state :challenger "Cache")
(play-from-hand state :challenger "<NAME>")
(run-empty-locale state :archives)
(take-credits state :challenger)
(core/move state :contestant (find-card "Hive" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Hive" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Hive" (:hand (get-contestant))) :deck)
(play-from-hand state :contestant "Power Shutdown")
(prompt-choice :contestant 2)
(is (= 3 (count (:discard (get-contestant)))) "2 cards discarded from R&D")
(is (= 1 (count (:deck (get-contestant)))) "1 card remaining in R&D")
(prompt-select :challenger (get-hazard state 0)) ; try targeting Grimoire
(is (empty? (:discard (get-challenger))) "Grimoire too expensive to be targeted")
(prompt-select :challenger (get-resource state 0))
(is (= 1 (count (:discard (get-challenger)))) "Cache discarded")))
(deftest power-grid-overload
;; Power Grid Overload
(do-game
(new-game (default-contestant ["Power Grid Overload"])
(default-challenger ["<NAME> Mem Chip"]))
(take-credits state :contestant)
(play-from-hand state :challenger "<NAME> Mem Chip")
(run-empty-locale state :rd)
(take-credits state :challenger)
(play-from-hand state :contestant "Power Grid Overload")
(prompt-choice :contestant 3)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-hazard state 0))
(is (= 1 (-> (get-challenger) :discard count)) "<NAME>son Mem Chip should be in heap after Challenger loses Power Grid Overload trace")))
(deftest precognition
;; Precognition - Full test
(do-game
(new-game (default-contestant ["Precognition" "Caprcharacter Nisei" "Adonis Campaign"
"<NAME>" "<NAME>" "Global Food Initiative"])
(default-challenger))
(starting-hand state :contestant ["Precognition"])
(play-from-hand state :contestant "Precognition")
(prompt-card :contestant (find-card "<NAME>" (:deck (get-contestant))))
(prompt-card :contestant (find-card "Adonis Campaign" (:deck (get-contestant))))
(prompt-card :contestant (find-card "<NAME>" (:deck (get-contestant))))
(prompt-card :contestant (find-card "<NAME>" (:deck (get-contestant))))
(prompt-card :contestant (find-card "Global Food Initiative" (:deck (get-contestant))))
;; try starting over
(prompt-choice :contestant "Start over")
(prompt-card :contestant (find-card "Global Food Initiative" (:deck (get-contestant))))
(prompt-card :contestant (find-card "<NAME>" (:deck (get-contestant))))
(prompt-card :contestant (find-card "<NAME>" (:deck (get-contestant))))
(prompt-card :contestant (find-card "Adonis Campaign" (:deck (get-contestant))))
(prompt-card :contestant (find-card "Caprcharacter Nisei" (:deck (get-contestant)))) ;this is the top card of R&D
(prompt-choice :contestant "Done")
(is (= "<NAME>" (:title (first (:deck (get-contestant))))))
(is (= "Adonis Campaign" (:title (second (:deck (get-contestant))))))
(is (= "Quand<NAME>" (:title (second (rest (:deck (get-contestant)))))))
(is (= "<NAME>" (:title (second (rest (rest (:deck (get-contestant))))))))
(is (= "Global Food Initiative" (:title (second (rest (rest (rest (:deck (get-contestant)))))))))))
(deftest preemptive-action
;; Preemptive Action - Shuffles cards into R&D and removes itself from game
(testing "Basic test"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 3)
"Preemptive Action"])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Preemptive Action")
(prompt-select :contestant (first (:discard (get-contestant))))
(prompt-select :contestant (second (:discard (get-contestant))))
(prompt-select :contestant (last (:discard (get-contestant))))
(is (zero? (count (:discard (get-contestant)))))
(is (= 1 (count (:rfg (get-contestant)))))))
(testing "forces you to take 3 if there are three, and removes itself from game"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 3)
(qty "Preemptive Action" 1)])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Preemptive Action")
(prompt-select :contestant (first (:discard (get-contestant))))
(prompt-select :contestant (last (:discard (get-contestant))))
(is (= 3 (count (:discard (get-contestant)))))
(is (= 1 (count (:rfg (get-contestant)))))))
(testing "Shuffles all archives cards into R&D if Archives has less than 3 cards, and removes itself from game"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 2)
(qty "Preemptive Action" 1)])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Preemptive Action")
(prompt-select :contestant (first (:discard (get-contestant))))
(prompt-select :contestant (last (:discard (get-contestant))))
(is (zero? (count (:discard (get-contestant)))))
(is (= 1 (count (:rfg (get-contestant))))))))
(deftest psychographics
;; Psychographics - Place advancements up to the number of Challenger tags on a card
(do-game
(new-game (default-contestant ["Psychographics" "Project Junebug"])
(default-challenger))
(core/gain state :challenger :tag 4)
(play-from-hand state :contestant "Project Junebug" "New party")
(let [pj (get-content state :party1 0)]
(play-from-hand state :contestant "Psychographics")
(prompt-choice :contestant 4)
(prompt-select :contestant pj)
(is (= 1 (:credit (get-contestant))) "Spent 4 credits")
(is (= 4 (get-counters (refresh pj) :advancement)) "Junebug has 4 advancements"))))
(deftest psychokinesis
;; Pyschokinesis - Terminal Event (end the turn); Look at R&D, place an Site, Agenda, or Region in a Party Locale
(do-game
(new-game (default-contestant [(qty "Psychokinesis" 3) "Caprcharacter Nisei" "Adonis Campaign"
"Global Food Initiative" "Mwanza City Grid"])
(default-challenger))
(starting-hand state :contestant ["Psychokinesis" "Psychokinesis" "Psychokinesis"])
;; Test placing an Region
(play-from-hand state :contestant "Psychokinesis")
(is (not-any? #{"Mwanza City Grid"} (map :title (-> (get-contestant) :prompt first :choices)))
"Mwanza City Grid is not on the list of placeable cards")
(prompt-card :contestant (find-card "Caprcharacter Nisei" (:deck (get-contestant))))
(prompt-choice :contestant "New party")
(is (= "<NAME>" (:title (get-content state :party1 0)))
"Cap<NAME> Nisei placed by Psychokinesis")
;; Test placing an Site
(core/gain state :contestant :click 1)
(play-from-hand state :contestant "Psychokinesis")
(prompt-card :contestant (find-card "Adonis Campaign" (:deck (get-contestant))))
(prompt-choice :contestant "New party")
(is (= "Adonis Campaign" (:title (get-content state :party2 0)))
"Adonis Campaign placed by Psychokinesis")
;; Test placing an Agenda
(core/gain state :contestant :click 1)
(play-from-hand state :contestant "Psychokinesis")
(prompt-card :contestant (find-card "Global Food Initiative" (:deck (get-contestant))))
(prompt-choice :contestant "New party")
(is (= "Global Food Initiative" (:title (get-content state :party3 0)))
"Global Food Initiative placed by Psychokinesis")
;; Test selecting "None"
(core/gain state :contestant :click 1)
(core/move state :contestant (find-card "Psychokinesis" (:discard (get-contestant))) :hand)
(play-from-hand state :contestant "Psychokinesis")
(prompt-choice :contestant "None")
(is (= nil (:title (get-content state :party4 0)))
"Nothing is placed by Psychokinesis")))
(deftest punitive-counterstrike
;; Punitive Counterstrike - deal meat damage equal to printed agenda points
(do-game
(new-game (default-contestant ["Global Food Initiative" "Punitive Counterstrike"])
(default-challenger))
(play-from-hand state :contestant "Global Food Initiative" "New party")
(take-credits state :contestant)
(run-empty-locale state :party1)
(prompt-choice :challenger "Steal")
(is (= 2 (:agenda-point (get-challenger))) "Challenger scored 2 points")
(take-credits state :challenger)
(play-from-hand state :contestant "Punitive Counterstrike")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (empty? (:hand (get-challenger))) "Challenger took 3 meat damage")))
(deftest red-planet-couriers
;; Red Planet Couriers - Move all advancements on cards to 1 advanceable card
(do-game
(new-game (default-contestant ["Red Planet Couriers" (qty "Character Wall" 2)
"GRNDL Refinery" "Government Takeover"])
(default-challenger))
(core/gain state :contestant :click 4)
(play-from-hand state :contestant "Government Takeover" "New party")
(play-from-hand state :contestant "GRNDL Refinery" "New party")
(play-from-hand state :contestant "Character Wall" "HQ")
(play-from-hand state :contestant "Character Wall" "R&D")
(let [gt (get-content state :party1 0)
gr (get-content state :party2 0)
iw1 (get-character state :hq 0)
iw2 (get-character state :rd 0)]
(core/add-prop state :contestant gr :advance-counter 3)
(core/add-prop state :contestant iw1 :advance-counter 2)
(core/add-prop state :contestant iw2 :advance-counter 1)
(play-from-hand state :contestant "Red Planet Couriers")
(prompt-select :contestant gt)
(is (zero? (get-counters (refresh gr) :advancement)) "Advancements removed")
(is (zero? (get-counters (refresh iw1) :advancement)) "Advancements removed")
(is (zero? (get-counters (refresh iw2) :advancement)) "Advancements removed")
(is (= 6 (get-counters (refresh gt) :advancement)) "Gained 6 advancements"))))
(deftest reuse
;; Reuse - Gain 2 credits for each card discarded from HQ
(do-game
(new-game (default-contestant [(qty "Reuse" 2) "Hive" "IQ"
"Character Wall"])
(default-challenger))
(play-from-hand state :contestant "Reuse")
(prompt-select :contestant (find-card "Character Wall" (:hand (get-contestant))))
(prompt-select :contestant (find-card "Hive" (:hand (get-contestant))))
(prompt-select :contestant (find-card "IQ" (:hand (get-contestant))))
(prompt-choice :contestant "Done")
(is (= 4 (count (:discard (get-contestant)))) "3 cards discarded plus operation played")
(is (= 11 (:credit (get-contestant))) "Gained 6 credits")
(is (= 1 (:click (get-contestant))) "Spent 2 clicks")))
(deftest reverse-infection
;; Reverse Infection - purge and discard 1 card from stack for every 3 counters purged - or gain 2 credits
(do-game
(new-game (default-contestant [(qty "Reverse Infection" 2)])
(default-challenger ["Virus Breeding Ground" "Datasucker" (qty "Sure Gamble" 3)]))
(starting-hand state :challenger ["Virus Breeding Ground" "Datasucker"])
(play-from-hand state :contestant "Reverse Infection")
(prompt-choice :contestant "Gain 2 [Credits]")
(is (= 7 (:credit (get-contestant))) "Contestant gained 2 credits")
(take-credits state :contestant)
(play-from-hand state :challenger "Virus Breeding Ground")
(play-from-hand state :challenger "Datasucker")
(take-credits state :challenger)
(core/add-counter state :challenger (get-radicle state 0) :virus 4)
(core/add-counter state :challenger (get-resource state 0) :virus 3)
(play-from-hand state :contestant "Reverse Infection")
(prompt-choice :contestant "Purge virus counters.")
(is (= 9 (:credit (get-contestant))) "Contestant did not gain credits")
(is (zero? (get-counters (get-radicle state 0) :virus)) "Viruses purged from VBG")
(is (zero? (get-counters (get-resource state 0) :virus)) "Viruses purged from Datasucker")
(is (= 2 (count (:discard (get-challenger)))) "Two cards discarded from stack")))
(deftest riot-suppression
;; Riot Suppression - lose 3 clicks or take 1 brain damage
(testing "Take 1 brain damage"
(do-game
(new-game (default-contestant ["Riot Suppression" "Adonis Campaign"])
(default-challenger))
(play-from-hand state :contestant "Adonis Campaign" "New party")
(take-credits state :contestant)
(run-empty-locale state "Locale 1")
(prompt-choice-partial :challenger "Pay")
(take-credits state :challenger)
(play-from-hand state :contestant "Riot Suppression")
(is (empty? (:discard (get-challenger))) "Challenger discard is empty")
(is (zero? (:brain-damage (get-challenger))) "Challenger starts with no brain damage")
(prompt-choice-partial :challenger "Yes")
(is (= 1 (count (:discard (get-challenger)))) "1 card lost to brain damage")
(is (= 1 (:brain-damage (get-challenger))) "Challenger took 1 brain damage")
(is (= 1 (count (:discard (get-contestant)))) "No contestant cards discarded")
(is (= 1 (count (:rfg (get-contestant)))) "Riot Suppestion removed from game")
(take-credits state :contestant)
(is (= 4 (:click (get-challenger))) "Challenger has all clicks the following turn")))
(testing "Lose 3 clicks"
(do-game
(new-game (default-contestant ["Riot Suppression" "Adonis Campaign"])
(default-challenger))
(play-from-hand state :contestant "Adonis Campaign" "New party")
(take-credits state :contestant)
(run-empty-locale state "Locale 1")
(prompt-choice-partial :challenger "Pay")
(take-credits state :challenger)
(play-from-hand state :contestant "Riot Suppression")
(is (empty? (:discard (get-challenger))) "Challenger discard is empty")
(is (zero? (:brain-damage (get-challenger))) "Challenger starts with no brain damage")
(prompt-choice-partial :challenger "No")
(is (empty? (:discard (get-challenger))) "Challenger discard statys empty")
(is (zero? (:brain-damage (get-challenger))) "Challenger takes no brain damage")
(is (= 1 (count (:discard (get-contestant)))) "No contestant cards discarded")
(is (= 1 (count (:rfg (get-contestant)))) "Riot Suppestion removed from game")
(take-credits state :contestant)
(is (= 1 (:click (get-challenger))) "Challenger has 3 fewer clicks following turn"))))
(deftest rolling-brownout
;; Rolling Brownout - Increase cost of events/operations by 1, gain 1c on first Challenger event of turn
(do-game
(new-game (default-contestant ["Rolling Brownout" "Beanstalk Royalties"
"Domestic Sleepers"])
(default-challenger [(qty "Easy Mark" 3)]))
(play-from-hand state :contestant "Rolling Brownout")
(play-from-hand state :contestant "Beanstalk Royalties")
(is (= 5 (:credit (get-contestant))) "Beanstalk netted only 2c")
(play-from-hand state :contestant "Domestic Sleepers" "New party")
(take-credits state :contestant)
(play-from-hand state :challenger "Easy Mark")
(is (= 7 (:credit (get-challenger))) "Easy Mark netted only 2c")
(is (= 6 (:credit (get-contestant))) "Contestant gained 1c from Brownout")
(play-from-hand state :challenger "Easy Mark")
(is (= 6 (:credit (get-contestant))) "No Contestant credit gain from 2nd event")
(run-empty-locale state "Locale 1")
(prompt-choice :challenger "Steal")
(play-from-hand state :challenger "Easy Mark")
(is (= 12 (:credit (get-challenger))) "Easy Mark netted 3c after Brownout discarded")))
(deftest salem's-hospitality
;; Salem's Hospitality - Full test
(do-game
(new-game (default-contestant [(qty "Salem's Hospitality" 3)])
(default-challenger [(qty "I've Had Worse" 3) "Faust"
"Levy AR Lab Access"]))
(play-from-hand state :contestant "Salem's Hospitality")
(is (= 5 (count (:hand (get-challenger)))))
(prompt-choice :contestant "I've Had Worse")
(is (= 2 (count (:hand (get-challenger)))))
(play-from-hand state :contestant "Salem's Hospitality")
(prompt-choice :contestant "Plascrete Carapace")
(is (= 2 (count (:hand (get-challenger)))))))
(deftest scorched-earth
;; Scorched Earth
(testing "Basic test"
(do-game
(new-game (default-contestant ["Scorched Earth"])
(default-challenger [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "Scorched Earth")
(is (= 1 (count (:hand (get-challenger)))) "Challenger has 1 card in hand")))
(testing "not tagged"
(do-game
(new-game (default-contestant ["Scorched Earth"])
(default-challenger [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(play-from-hand state :contestant "Scorched Earth")
(is (= 3 (:click (get-contestant))) "Contestant not charged a click")
(is (= 5 (count (:hand (get-challenger)))) "Challenger did not take damage")))
(testing "flatline"
(do-game
(new-game (default-contestant [(qty "Scorched Earth" 10)])
(default-challenger))
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "Scorched Earth")
(is (zero? (count (:hand (get-challenger)))) "Challenger has 0 cards in hand")
(is (= :contestant (:winner @state)) "Contestant wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline"))))
(deftest sea-source
;; SEA Source
(do-game
(new-game (default-contestant ["SEA Source"])
(default-challenger))
(take-credits state :contestant)
(run-empty-locale state :rd)
(take-credits state :challenger)
(is (zero? (:tag (get-challenger))) "Challenger should start with 0 tags")
(play-from-hand state :contestant "SEA Source")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger should get 1 tag from losing SEA Source trace")))
(deftest self-growth-resource
;; Self-Growth Resource - Add 2 placed cards to grip if challenger is tagged
(do-game
(new-game (default-contestant ["Self-Growth Resource"])
(default-challenger ["Clone Chip" "Inti"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Clone Chip")
(play-from-hand state :challenger "Inti")
(take-credits state :challenger)
(play-from-hand state :contestant "Self-Growth Resource")
(is (= 3 (:click (get-contestant))) "Self-Growth Resource precondition not met; card not played")
(core/gain state :challenger :tag 1)
(is (zero? (count (:hand (get-challenger)))) "Challenger hand is empty")
(let [inti (get-resource state 0)
cc (get-hazard state 0)]
(play-from-hand state :contestant "Self-Growth Resource")
(prompt-select :contestant inti)
(prompt-select :contestant cc))
(is (= 2 (count (:hand (get-challenger)))) "2 cards returned to hand")
(is (zero? (count (get-resource state))) "No resources placed")
(is (zero? (count (get-hazard state))) "No hazard placed")))
(deftest servcharacter-outage
;; Servcharacter Outage
(testing "First click run each turn costs a credit"
(do-game
(new-game (default-contestant ["Servcharacter Outage"])
(default-challenger ["Employee Strike"]))
(play-from-hand state :contestant "Servcharacter Outage")
(take-credits state :contestant)
(is (= 5 (:credit (get-challenger))) "Challenger has 5 credits")
(run-on state :archives)
(is (= 4 (:credit (get-challenger)))
"Challenger spends 1 credit to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 4 (:credit (get-challenger)))
"Challenger doesn't spend 1 credit to make the second run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(core/lose state :challenger :credit 6)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (zero? (:credit (get-challenger))) "Challenger has 0 credits")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (zero? (:credit (get-challenger))) "Challenger has 0 credits")
(take-credits state :challenger)
(take-credits state :contestant)
(core/lose state :challenger :credit 2)
(play-from-hand state :challenger "Employee Strike")
(is (= 1 (:credit (get-challenger))) "Challenger has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-challenger)))
"Challenger doesn't spend 1 credit to make a run")))
(testing "First card ability run each turn costs an additional credit"
(do-game
(new-game (default-contestant ["Servcharacter Outage"])
(default-challenger ["Sneakdoor Beta"]))
(play-from-hand state :contestant "Servcharacter Outage")
(take-credits state :contestant)
(play-from-hand state :challenger "Sneakdoor Beta")
(take-credits state :challenger 1)
(is (= 2 (:credit (get-challenger))) "Challenger has 2 credits")
(let [sneakdoor (get-resource state 0)]
(card-ability state :challenger sneakdoor 0)
(is (= 1 (:credit (get-challenger)))
"Challenger spends 1 additional credit to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:credit (get-challenger)))
"Challenger doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(core/lose state :challenger :credit 1)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (zero? (:credit (get-challenger))) "Challenger has 0 credits")
(card-ability state :challenger sneakdoor 0)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (zero? (:credit (get-challenger))) "Challenger has 0 credits"))))
(testing "First run event each turn costs an additional credit"
(do-game
(new-game (default-contestant ["Servcharacter Outage"])
(default-challenger [(qty "Out of the Ashes" 2)]))
(play-from-hand state :contestant "Servcharacter Outage")
(take-credits state :contestant)
(is (= 5 (:credit (get-challenger))) "Challenger has 5 credits")
(play-from-hand state :challenger "Out of the Ashes")
(is (= 3 (:credit (get-challenger)))
"Challenger spends 1 additional credit to run with a run event")
(prompt-choice :challenger "Archives")
(run-successful state)
(run-on state :archives)
(is (= 3 (:credit (get-challenger)))
"Challenger doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(prompt-choice :challenger "No") ; Out of the Ashes prompt
(core/lose state :challenger :credit 4)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (= 1 (:credit (get-challenger))) "Challenger has 1 credit")
(play-from-hand state :challenger "Out of the Ashes")
(is (empty? (get-in @state [:challenger :prompt]))
"Out of the Ashes was not played")
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (= 1 (:credit (get-challenger))) "Challenger has 1 credit")))
(testing "Works when played on the challenger's turn"
(do-game
(new-game (make-deck "New Angeles Sol: Your News" ["Servcharacter Outage"
"Breaking News"])
(default-challenger ["Hades Shard"]))
(discard-from-hand state :contestant "Breaking News")
(take-credits state :contestant)
(core/gain state :challenger :credit 3)
(play-from-hand state :challenger "Hades Shard")
(card-ability state :challenger (get-radicle state 0) 0)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Servcharacter Outage" (:hand (get-contestant))))
(is (find-card "Servcharacter Outage" (:current (get-contestant)))
"Servcharacter Outage is in play")
(is (= 1 (:credit (get-challenger))) "Challenger has 1 credit")
(run-on state :archives)
(is (zero? (:credit (get-challenger)))
"Challenger spends 1 additional credit to make a run")))
(testing "Doesn't fire if already run when played on the challenger's turn"
(do-game
(new-game (make-deck "New Angeles Sol: Your News" ["Servcharacter Outage"
"Breaking News"])
(default-challenger ["Hades Shard"]))
(discard-from-hand state :contestant "Breaking News")
(take-credits state :contestant)
(run-on state :hq)
(run-successful state)
(prompt-choice :challenger "No action")
(core/gain state :challenger :credit 3)
(play-from-hand state :challenger "Hades Shard")
(card-ability state :challenger (get-radicle state 0) 0)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Servcharacter Outage" (:hand (get-contestant))))
(is (find-card "Servcharacter Outage" (:current (get-contestant)))
"Servcharacter Outage is in play")
(is (= 1 (:credit (get-challenger))) "Challenger has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-challenger)))
"Challenger doesn't spend 1 additional credit to make a run")))
(testing "discarded and replaced on steal doesn't double remove penalty"
(do-game
(new-game
(make-deck "New Angeles Sol: Your News" ["Servcharacter Outage"
"Breaking News"])
(default-challenger))
(play-from-hand state :contestant "Breaking News" "New party")
(play-from-hand state :contestant "Servcharacter Outage")
(take-credits state :contestant)
(run-on state :party1)
(run-successful state)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Servcharacter Outage" (:discard (get-contestant))))
(take-credits state :challenger)
(take-credits state :contestant)
(is (= 7 (:credit (get-challenger))) "Challenger has 7 credits")
(run-on state :archives)
(is (= 6 (:credit (get-challenger))) "Challenger spends 1 credit to make a run"))))
(deftest shipment-from-sansan
;; Shipment from SanSan - placing advancements
(do-game
(new-game (default-contestant [(qty "Shipment from SanSan" 3) (qty "Character Wall" 3)])
(default-challenger))
(play-from-hand state :contestant "Character Wall" "HQ")
(let [iwall (get-character state :hq 0)]
(play-from-hand state :contestant "Shipment from SanSan")
(prompt-choice :contestant "2")
(prompt-select :contestant iwall)
(is (= 5 (:credit (get-contestant))))
(is (= 2 (get-counters (refresh iwall) :advancement))))))
(deftest snatch-and-grab
;; Snatch and Grab
(do-game
(new-game (default-contestant [(qty "Snatch and Grab" 2)])
(default-challenger ["Scrubber"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Scrubber")
(take-credits state :challenger)
(is (zero? (:tag (get-challenger))) "Challenger should start with 0 tags")
(play-from-hand state :contestant "Snatch and Grab")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(prompt-choice :challenger "Yes")
(is (= 1 (:tag (get-challenger))) "Challenger should get 1 tag from losing Snatch and Grab trace and opting to take the tag")
(is (zero? (-> (get-challenger) :discard count)) "Challenger should start with 0 cards in heap")
(play-from-hand state :contestant "Snatch and Grab")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(prompt-choice :challenger "No")
(is (= 1 (-> (get-challenger) :discard count)) "Scrubber should be in Challenger's heap after losing Snatch and Grab trace")))
(deftest stock-buy-back
;; Stock Buy-Back - Gain 3c for every agenda in Challenger's area
(do-game
(new-game (default-contestant [(qty "Hostile Takeover" 2) (qty "Stock Buy-Back" 3)])
(default-challenger))
(play-from-hand state :contestant "Hostile Takeover" "New party")
(play-from-hand state :contestant "Hostile Takeover" "New party")
(take-credits state :contestant)
(run-empty-locale state "Locale 1")
(prompt-choice :challenger "Steal")
(run-empty-locale state "Locale 2")
(prompt-choice :challenger "Steal")
(take-credits state :challenger)
(is (= 2 (count (:scored (get-challenger)))))
(play-from-hand state :contestant "Stock Buy-Back")
(is (= 11 (:credit (get-contestant))))))
(deftest sub-boost
;; Sub Boost - Give Character Barrier
(do-game
(new-game (default-contestant ["Sub Boost" "Quandary"])
(default-challenger))
(play-from-hand state :contestant "Quandary" "HQ")
(let [qu (get-character state :hq 0)]
(core/reveal state :contestant qu)
(is (not (core/has-subtype? (refresh qu) "Barrier")) "Quandry starts without Barrier")
(is (= 1 (count (:subroutines (refresh qu)))) "Quandry has 1 subroutine")
(play-from-hand state :contestant "Sub Boost")
(prompt-select :contestant (refresh qu))
(is (core/has-subtype? (refresh qu) "Code Gate") "Quandary has Code Gate")
(is (core/has-subtype? (refresh qu) "Barrier") "Quandary Character Barrier")
(is (= 2 (count (:subroutines (refresh qu)))) "Quandry gains a subroutine"))))
(deftest subcontract
;; Subcontract
(testing "Don't allow second operation until damage prevention completes"
(do-game
(new-game (default-contestant [(qty "Scorched Earth" 2) "Subcontract"])
(default-challenger ["Plascrete Carapace"]))
(take-credits state :contestant)
(core/gain state :challenger :tag 1)
(play-from-hand state :challenger "Plascrete Carapace")
(take-credits state :challenger)
(play-from-hand state :contestant "Subcontract")
(prompt-select :contestant (find-card "Scorched Earth" (:hand (get-contestant))))
(is (and (= 1 (count (:prompt (get-contestant)))) (= :waiting (-> (get-contestant) :prompt first :prompt-type)))
"Contestant does not have Subcontract prompt until damage prevention completes")
(prompt-choice :challenger "Done")
(is (not-empty (:prompt (get-contestant))) "Contestant can now play second Subcontract operation")))
(testing "interaction with Terminal operations"
(do-game
(new-game
(default-contestant [(qty "Hard-Hitting News" 2) "Subcontract"])
(default-challenger))
(core/gain state :challenger :tag 1)
(take-credits state :contestant)
(run-empty-locale state :archives)
(take-credits state :challenger)
(play-from-hand state :contestant "Subcontract")
(prompt-select :contestant (find-card "Hard-Hitting News" (:hand (get-contestant))))
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 5 (:tag (get-challenger))) "Challenger has 5 tags")
(is (empty? (:prompt (get-contestant))) "Contestant does not have a second Subcontract selection prompt"))))
(deftest subliminal-messaging
;; Subliminal Messaging - Playing/discarding/milling will all prompt returning to hand
(testing "Basic test"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 3)])
(make-deck "Noise: Hacker Extraordinaire" [(qty "Cache" 3) "Utopia Shard"]))
(play-from-hand state :contestant "Subliminal Messaging")
(is (= 6 (:credit (get-contestant))))
(is (= 3 (:click (get-contestant))) "First Subliminal Messaging gains 1 click")
(play-from-hand state :contestant "Subliminal Messaging")
(is (= 7 (:credit (get-contestant))))
(is (= 2 (:click (get-contestant))) "Second Subliminal Messaging does not gain 1 click")
(discard-from-hand state :contestant "Subliminal Messaging")
(is (zero? (count (:hand (get-contestant)))))
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(is (= 3 (count (:hand (get-contestant)))) "All 3 Subliminals returned to HQ")
(core/move state :contestant (find-card "Subliminal Messaging" (:hand (get-contestant))) :deck)
(take-credits state :contestant)
(play-from-hand state :challenger "Cache")
(play-from-hand state :challenger "Utopia Shard")
(let [utopia (get-radicle state 0)]
(card-ability state :challenger utopia 0))
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(is (= 3 (count (:hand (get-contestant)))) "All 3 Subliminals returned to HQ")
(play-from-hand state :contestant "Subliminal Messaging")
(take-credits state :contestant)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :challenger)
(is (empty? (get-in @state [:contestant :prompt])) "No prompt here because challenger made a run last turn")
(take-credits state :contestant)
(is (= 2 (count (:hand (get-contestant)))))
(is (= 1 (count (:discard (get-contestant)))) "1 Subliminal not returned because challenger made a run last turn")))
(testing "Scenario involving Subliminal being added to HQ with Archived Memories"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 2) "Archived Memories"])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Archived Memories")
(prompt-select :contestant (find-card "Subliminal Messaging" (:discard (get-contestant))))
(is (= 2 (count (:discard (get-contestant)))))
(is (= 1 (count (:hand (get-contestant)))))
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "No")
(is (empty? (get-in @state [:contestant :prompt])) "Only 1 Subliminal prompt")
(play-from-hand state :contestant "Subliminal Messaging")
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(is (empty? (get-in @state [:contestant :prompt]))
"Only 2 Subliminal prompts - there will be a third if flag not cleared")))
(testing "Scenario involving Subliminal being reshuffled into R&D with <NAME>"
(do-game
(new-game (default-contestant ["Subliminal Messaging" "<NAME>"])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "<NAME>" "New party")
(take-credits state :contestant)
(let [jhow (get-content state :party1 0)]
(core/reveal state :contestant jhow)
(card-ability state :contestant jhow 1)
(prompt-select :contestant (find-card "Subliminal Messaging" (:discard (get-contestant))))
(prompt-choice :contestant "Done")
(is (zero? (count (:discard (get-contestant)))))
(is (= 1 (count (:rfg (get-contestant))))))
(take-credits state :challenger)
(play-from-hand state :contestant "Subliminal Messaging")
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(is (= 1 (count (:hand (get-contestant)))) "Subliminal returned to HQ")
(is (empty? (get-in @state [:contestant :prompt]))
"Subliminal prompt cleared - there will be a second prompt if flag not cleared")))
(testing "Challenger made run, ensure game asks again next turn"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 2)])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(discard-from-hand state :contestant "Subliminal Messaging")
(take-credits state :contestant)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :challenger)
(is (empty? (get-in @state [:contestant :prompt])) "No prompt here because challenger made a run last turn")
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(is (= 2 (count (:hand (get-contestant)))) "Both Subliminals returned to HQ")
(is (zero? (count (:discard (get-contestant)))) "No Subliminals in Archives")))
(testing "User declines to return to hand, ensure game asks again next turn"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 2)])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(discard-from-hand state :contestant "Subliminal Messaging")
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "No")
(prompt-choice :contestant "No")
(is (zero? (count (:hand (get-contestant)))) "Neither Subliminal returned to HQ")
(is (= 2 (count (:discard (get-contestant)))) "Both Subliminals in Archives")
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(is (= 2 (count (:hand (get-contestant)))) "Both Subliminals returned to HQ")
(is (zero? (count (:discard (get-contestant)))) "No Subliminals in Archives"))))
(deftest success
;; Success
(testing "Works with bad publicity"
(do-game
(new-game (default-contestant ["NAPD Contract" "Project Beale" "Success"])
(default-challenger))
(play-from-hand state :contestant "NAPD Contract" "New party")
(play-from-hand state :contestant "Project Beale" "New party")
(core/gain state :contestant :bad-publicity 9)
(core/gain state :contestant :credit 8)
(core/gain state :contestant :click 15)
(let [napd (get-content state :party1 0)
beale (get-content state :party2 0)]
(dotimes [_ 13] (core/advance state :contestant {:card (refresh napd)}))
(is (= 13 (get-counters (refresh napd) :advancement)))
(core/score state :contestant {:card (refresh napd)})
(is (= 2 (:agenda-point (get-contestant))))
(play-from-hand state :contestant "Success")
(prompt-select :contestant (get-scored state :contestant 0))
(is (= "NAPD Contract" (:title (first (:rfg (get-contestant))))))
(prompt-select :contestant (refresh beale))
(is (= 13 (get-counters (refresh beale) :advancement)))
(core/score state :contestant {:card (refresh beale)})
(is (= 7 (:agenda-point (get-contestant)))))))
(testing "Works with public agendas"
(do-game
(new-game (default-contestant ["Oaktown Renovation" "Vanity Project" "Success"])
(default-challenger))
(core/gain state :contestant :click 1)
(score-agenda state :contestant (find-card "Vanity Project" (:hand (get-contestant))))
(is (= 4 (:agenda-point (get-contestant))))
(play-from-hand state :contestant "Oaktown Renovation" "New party")
(is (= 5 (:credit (get-contestant))))
(play-from-hand state :contestant "Success")
(prompt-select :contestant (get-scored state :contestant 0))
(is (= "Vanity Project" (:title (first (:rfg (get-contestant))))))
(let [oaktown (get-content state :party1 0)]
(prompt-select :contestant (refresh oaktown))
(is (= 6 (get-counters (refresh oaktown) :advancement)))
(is (= 19 (:credit (get-contestant))) "Gain 2 + 2 + 2 + 2 + 3 + 3 = 14 credits for advancing Oaktown")
(core/score state :contestant {:card (refresh oaktown)})
(is (= 2 (:agenda-point (get-contestant)))))))
(testing "interaction with Jemison, regression test for issue #2704"
(do-game
(new-game (make-deck "Jemison Astronautics: Sacrifcharacter. Audacity. Success."
["Success"
"High-Risk Investment"
"Government Takeover"])
(default-challenger))
(core/gain state :contestant :click 1)
(score-agenda state :contestant (find-card "High-Risk Investment" (:hand (get-contestant))))
(play-from-hand state :contestant "Government Takeover" "New party")
(play-from-hand state :contestant "Success")
(prompt-select :contestant (get-in (get-contestant) [:scored 0]))
(let [gto (get-content state :party1 0)]
;; Prompt for Jemison
(prompt-select :contestant (refresh gto))
(is (= 4 (get-counters (refresh gto) :advancement)) "Added 4 counters from Jemison trigger")
;; Prompt for Success
(prompt-select :contestant (refresh gto))
(is (= (+ 4 5) (get-counters (refresh gto) :advancement)) "Advance 5 times from Success")))))
(deftest successful-demonstration
;; Successful Demonstration - Play if only Challenger made unsuccessful run last turn; gain 7 credits
(do-game
(new-game (default-contestant ["Successful Demonstration"])
(default-challenger))
(play-from-hand state :contestant "Successful Demonstration")
(is (and (= 3 (:click (get-contestant)))
(= 5 (:credit (get-challenger))))
"Successful Demonstration precondition not met; card not played")
(take-credits state :contestant)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :challenger)
(play-from-hand state :contestant "Successful Demonstration")
(is (= 13 (:credit (get-contestant))) "Paid 2 to play event; gained 7 credits")))
(deftest surveillance-sweep
;; Surveillance Sweep
(testing "Basic test"
(do-game
(new-game (default-contestant ["Restructured Datapool" "Surveillance Sweep" "Data Raven"])
(default-challenger ["Scrubbed"]))
(is (zero? (:tag (get-challenger))) "Challenger should start with no tags")
(play-from-hand state :contestant "Surveillance Sweep")
(play-and-score state "Restructured Datapool")
(let [rd-scored (get-scored state :contestant 0)]
(card-ability state :contestant rd-scored 0)
(is (not= :waiting (-> (get-contestant) :prompt first :prompt-type)) "Surveillance Sweep only works during a run")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger should gain a tag from Restructured Datapool ability"))
(take-credits state :contestant)
(take-credits state :challenger)
(play-from-hand state :contestant "Data Raven" "HQ")
(take-credits state :contestant)
(let [dr (get-character state :hq 0)]
(core/reveal state :contestant (refresh dr))
(run-on state :hq)
(card-subroutine state :contestant dr 0)
(is (= :waiting (-> (get-contestant) :prompt first :prompt-type)) "During a run, Contestant should wait on Challenger first")
(prompt-choice :challenger 0)
(prompt-choice :contestant 0)
(is (= 1 (get-counters (refresh dr) :power)) "Data Raven should gain a power counter from trace")
(run-successful state)
(play-from-hand state :challenger "Scrubbed")
(run-on state :hq)
(card-subroutine state :contestant dr 0)
(is (not= :waiting (-> (get-contestant) :prompt first :prompt-type)) "Challenger should now be waiting on Contestant")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 2 (get-counters (refresh dr) :power)) "Data Raven should gain a power counter from trace")
(run-successful state))))
(testing "trace during run after stealing an agenda"
(do-game
(new-game (default-contestant ["Surveillance Sweep" "Breaking News" "Forced Connection" "Data Raven"])
(default-challenger))
(core/gain state :contestant :click 4)
(core/gain state :contestant :credit 20)
(play-from-hand state :contestant "Surveillance Sweep")
(play-from-hand state :contestant "Breaking News" "New party")
(play-from-hand state :contestant "Forced Connection" "Locale 1")
(play-from-hand state :contestant "Data Raven" "Locale 1")
(take-credits state :contestant)
(let [dr (get-character state :party1 0)
bn (get-content state :party1 0)
fc (get-content state :party1 1)]
(core/reveal state :contestant (refresh dr))
(run-on state :party1)
(card-subroutine state :contestant dr 0)
(is (= :waiting (-> (get-contestant) :prompt first :prompt-type)) "During a run, Contestant should wait on Challenger first")
(prompt-choice :challenger 0)
(prompt-choice :contestant 0)
(is (= 1 (get-counters (refresh dr) :power)) "Data Raven should gain a power counter from trace")
(run-successful state)
(prompt-select :challenger bn)
(prompt-choice :challenger "Steal")
(prompt-select :challenger fc)
(is (not= :waiting (-> (get-contestant) :prompt first :prompt-type)) "After steal, Surveillance Sweep leaves play and Challenger waits on Contestant")))))
(deftest the-all-seeing-i
(testing "Counts number of cards if one card is prevented discarded with fall guy"
(do-game
(new-game (default-contestant ["The All-Seeing I"])
(default-challenger ["Fall Guy" (qty "Same Old Thing" 2)]))
(letfn [(res [] (count (get-in (get-challenger) [:rig :radicle])))]
(take-credits state :contestant)
(play-from-hand state :challenger "Same Old Thing")
(play-from-hand state :challenger "Fall Guy")
(play-from-hand state :challenger "Same Old Thing")
(take-credits state :challenger)
(play-from-hand state :contestant "The All-Seeing I")
(is (= 1 (count (:hand (get-contestant)))) "Contestant could not play All Seeing I when challenger was not tagged")
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "The All-Seeing I")
(let [fall-guy (get-radicle state 1)]
(card-ability state :challenger fall-guy 0))
(prompt-choice :challenger "Done")
(is (= 1 (res)) "One placed radicle saved by Fall Guy")
(is (= 2 (count (:discard (get-challenger)))) "Two cards in heap"))))
(testing "Checks that All-seeing I does not double-discard hosted cards, discards hosted cards"
(do-game
(new-game (default-contestant ["The All-Seeing I"])
(default-challenger [(qty "Fall Guy" 2) "Off-Campus Apartment"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Off-Campus Apartment")
(let [oca (get-radicle state 0)
fg1 (get-in (get-challenger) [:hand 0])
fg2 (get-in (get-challenger) [:hand 1])]
(card-ability state :challenger oca 0)
(prompt-select :challenger fg1)
(card-ability state :challenger oca 0)
(prompt-select :challenger fg2))
(core/gain state :challenger :tag 1)
(take-credits state :challenger)
(play-from-hand state :contestant "The All-Seeing I")
(prompt-choice :challenger "Done")
(prompt-choice :challenger "Done")
(let [fall-guy (find-card "Fall Guy" (core/all-active-placed state :challenger))]
(card-ability state :challenger fall-guy 0))
(prompt-choice :challenger "Done") ;; This assumes hosted cards get put in discard-list before host
(is (= 1 (count (core/all-active-placed state :challenger))) "One placed card (Off-Campus)")
(is (= 2 (count (:discard (get-challenger)))) "Two cards in heap")))
(testing "should not discard Jarogniew Mercs if there are other placed radicles"
(do-game
(new-game (default-contestant [(qty "The All-Seeing I" 4)])
(default-challenger [(qty "<NAME>" 2) (qty "Same Old Thing" 2)]))
(letfn [(res [] (count (get-in (get-challenger) [:rig :radicle])))]
(take-credits state :contestant)
(play-from-hand state :challenger "Same Old Thing")
(play-from-hand state :challenger "<NAME>")
(take-credits state :challenger)
(is (= 2 (res)) "There are two placed radicles")
(play-from-hand state :contestant "The All-Seeing I")
(is (= 1 (res)) "<NAME>ogniew Mercs still placed")
(play-from-hand state :contestant "The All-Seeing I")
(is (zero? (res)) "There are no placed radicles")
(take-credits state :contestant)
(play-from-hand state :challenger "<NAME>") ;; Testing if order matters
(play-from-hand state :challenger "Same Old Thing")
(take-credits state :challenger)
(is (= 2 (res)) "There are two placed radicles")
(play-from-hand state :contestant "The All-Seeing I")
(is (= 1 (res)) "<NAME>ogniew Mercs still placed")
(play-from-hand state :contestant "The All-Seeing I")
(is (zero? (res)) "There are no placed radicles")))))
(deftest threat-assessment
;; Threat Assessment - play only if challenger discarded a card last turn, move a card to the stack or take 2 tags
(do-game
(new-game (default-contestant [(qty "Threat Assessment" 3) "Adonis Campaign"])
(default-challenger ["Desperado" "Corroder"]))
(play-from-hand state :contestant "Adonis Campaign" "New party")
(take-credits state :contestant)
(run-on state :party1)
(run-successful state)
(prompt-choice-partial :challenger "Pay") ;discard
(core/gain state :challenger :credit 5)
(play-from-hand state :challenger "<NAME>")
(play-from-hand state :challenger "Corroder")
(take-credits state :challenger)
(is (zero? (:tag (get-challenger))) "Challenger starts with 0 tags")
(play-from-hand state :contestant "Threat Assessment")
(prompt-select :contestant (find-card "Desperado" (-> (get-challenger) :rig :hazard)))
(prompt-choice :challenger "2 tags")
(is (= 2 (:tag (get-challenger))) "Challenger took 2 tags")
(is (= 1 (count (-> (get-challenger) :rig :hazard))) "Didn't discard Desperado")
(is (= "Threat Assessment" (:title (first (:rfg (get-contestant))))) "Threat Assessment removed from game")
(play-from-hand state :contestant "Threat Assessment")
(prompt-select :contestant (find-card "Corroder" (-> (get-challenger) :rig :resource)))
(prompt-choice :challenger "Move Corroder")
(is (= 2 (:tag (get-challenger))) "Challenger didn't take tags")
(is (= "Corroder" (:title (first (:deck (get-challenger))))) "Moved Corroder to the deck")
(is (= 2 (count (:rfg (get-contestant)))))
(take-credits state :challenger)
(take-credits state :contestant)
(take-credits state :challenger)
(play-from-hand state :contestant "Threat Assessment")
(is (empty? (:prompt (get-contestant))) "Threat Assessment triggered with no discard")))
(deftest threat-level-alpha
;; Threat Level Alpha - Win trace to give tags = Challenger tags; or 1 tag if 0
(do-game
(new-game (default-contestant [(qty "Threat Level Alpha" 2)])
(default-challenger))
(core/gain state :contestant :click 2)
(core/gain state :contestant :credit 2)
(is (zero? (:tag (get-challenger))))
(play-from-hand state :contestant "Threat Level Alpha")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger took 1 tag because they had 0")
(core/gain state :challenger :tag 2)
(play-from-hand state :contestant "Threat Level Alpha")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 6 (:tag (get-challenger))) "Challenger took 3 tag because they had 3")))
(deftest transparency-initiative
;; Transparency Initiative - Full test
(do-game
(new-game (default-contestant ["Transparency Initiative" "Oaktown Renovation"
"Project Atlas" "Hostile Takeover" "Casting Call"])
(default-challenger))
(core/gain state :contestant :click 5)
(play-from-hand state :contestant "Oaktown Renovation" "New party")
(play-from-hand state :contestant "Casting Call")
(prompt-select :contestant (find-card "Project Atlas" (:hand (get-contestant))))
(prompt-choice :contestant "New party")
(play-from-hand state :contestant "Hostile Takeover" "New party")
(let [oaktown (get-content state :party1 0)
atlas (get-content state :party2 0)
hostile (get-content state :party3 0)]
(play-from-hand state :contestant "Transparency Initiative")
(prompt-select :contestant (refresh oaktown))
;; doesn't work on face-up agendas
(is (zero? (count (:hosted (refresh oaktown)))))
(prompt-select :contestant (refresh atlas))
(is (= 1 (count (:hosted (refresh atlas)))) "Casting Call")
;; works on facedown agenda
(prompt-select :contestant (refresh hostile))
(is (= 1 (count (:hosted (refresh hostile)))))
;; gains Public subtype
(is (core/has-subtype? (refresh hostile) "Public"))
;; gain 1 credit when advancing
(is (= 5 (:credit (get-contestant))))
(core/advance state :contestant {:card (refresh hostile)})
(is (= 5 (:credit (get-contestant))))
;; make sure advancing other agendas doesn't gain 1
(core/advance state :contestant {:card (refresh oaktown)})
(is (= 6 (:credit (get-contestant))) "Transparency initiative didn't fire")
(core/advance state :contestant {:card (refresh atlas)})
(is (= 5 (:credit (get-contestant))) "Transparency initiative didn't fire"))))
(deftest trojan-horse
;; Trojan Horse
(do-game
(new-game (default-contestant ["Trojan Horse" "Dedicated Response Team"])
(default-challenger ["Wyrm"]))
(play-from-hand state :contestant "Dedicated Response Team" "New party")
(take-credits state :contestant)
(play-from-hand state :challenger "Wyrm")
(run-empty-locale state :party1)
(take-credits state :challenger)
(is (zero? (-> (get-challenger) :discard count)) "Challenger should start with 0 cards in heap")
(play-from-hand state :contestant "Trojan Horse")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-resource state 0))
(is (= 1 (-> (get-challenger) :discard count)) "Wyrm should be in heap after Challenger loses Trojan Horse trace")))
(deftest wake-up-call
;; Wake Up Call
(testing "should fire after using En Passant to discard character"
(do-game
(new-game (default-contestant ["Enigma" "Wake Up Call"])
(default-challenger ["En Passant" "Maya"]))
(play-from-hand state :contestant "Enigma" "HQ")
(take-credits state :contestant)
(play-from-hand state :challenger "Maya")
(run-on state :hq)
(run-successful state)
(prompt-choice :challenger "No action")
(is (zero? (count (:discard (get-contestant)))) "Contestant starts with no discards")
(play-from-hand state :challenger "En Passant")
(prompt-select :challenger (get-character state :hq 0))
(is (= 1 (count (:discard (get-contestant)))) "Contestant discards placed character")
(take-credits state :challenger)
(is (= 1 (count (:discard (get-challenger)))) "Challenger starts with 1 discarded card (En Passant)")
(play-from-hand state :contestant "Wake Up Call")
(prompt-select :contestant (get-hazard state 0))
(prompt-choice :challenger "Discard Maya")
(is (= 2 (count (:discard (get-challenger)))) "Maya is discarded")
(is (= 1 (count (:rfg (get-contestant)))) "Wake Up Call is removed from the game"))))
(deftest wetwork-refit
;; Wetwork Refit - Only works on Bioroid Character and adds a subroutine
(do-game
(new-game (default-contestant ["Eli 1.0"
"Vanilla"
(qty "Wetwork Refit" 3)])
(default-challenger))
(core/gain state :contestant :credit 20)
(core/gain state :contestant :click 10)
(play-from-hand state :contestant "Eli 1.0" "R&D")
(play-from-hand state :contestant "Vanilla" "HQ")
(let [eli (get-character state :rd 0)
vanilla (get-character state :hq 0)]
(play-from-hand state :contestant "Wetwork Refit")
(is (not-any? #{"Eli 1.0"} (get-in @state [:contestant :prompt :choices]))
"Unrevealed Eli 1.0 is not a choice to host Wetwork Refit")
(prompt-choice :contestant "Done")
(take-credits state :contestant)
(take-credits state :challenger)
(core/reveal state :contestant (refresh eli))
(core/reveal state :contestant (refresh vanilla))
(play-from-hand state :contestant "Wetwork Refit")
(prompt-select :contestant (refresh eli))
(is (= "Wetwork Refit" (:title (first (:hosted (refresh eli)))))
"Wetwork Refit is hosted on Eli 1.0")
(is (= 2 (count (:subroutines (refresh eli))))
"Eli 1.0 has 2 different subroutines")
(is (= "[Wetwork Refit] Do 1 brain damage" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has a brain damage subroutine as his first subroutine")
(core/move state :contestant (first (:hosted (refresh eli))) :hand)
(is (empty? (:hosted (refresh eli))) "No cards are hosted on Eli 1.0")
(is (= 1 (count (:subroutines (refresh eli))))
"Eli 1.0 has 1 different subroutine")
(is (= "End the run" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has an end the run subroutine as his first subroutine")
(play-from-hand state :contestant "Wetwork Refit")
(prompt-select :contestant (refresh vanilla))
(is (not= "Wetwork Refit" (:title (first (:hosted (refresh vanilla)))))
"Wetwork Refit is not hosted on Vanilla"))))
| true | (ns game-test.cards.operations
(:require [game.core :as core]
[game-test.core :refer :all]
[game-test.utils :refer :all]
[game-test.macros :refer :all]
[clojure.test :refer :all]))
(use-fixtures :once load-all-cards (partial reset-card-defs "operations"))
(deftest ^{:card-title "24/7-news-cycle"}
twenty-four-seven-news
;; 24/7 News Cycle
(testing "Breaking News interaction"
(do-game
(new-game (default-contestant [(qty "Breaking News" 2) (qty "24/7 News Cycle" 3)])
(default-challenger))
(play-from-hand state :contestant "Breaking News" "New party")
(play-from-hand state :contestant "Breaking News" "New party")
(let [ag1 (get-content state :party1 0)
ag2 (get-content state :party2 0)]
(score-agenda state :contestant ag1)
(score-agenda state :contestant ag2)
(take-credits state :contestant)
(is (zero? (:tag (get-challenger)))) ; tags cleared
(take-credits state :challenger)
(play-from-hand state :contestant "24/7 News Cycle")
(prompt-select :contestant (find-card "Breaking News" (:scored (get-contestant))))
(is (= 1 (:agenda-point (get-contestant))) "Forfeited Breaking News")
(prompt-select :contestant (find-card "Breaking News" (:scored (get-contestant))))
(is (= 2 (:tag (get-challenger))) "Challenger given 2 tags")
(take-credits state :contestant 2)
(is (= 2 (:tag (get-challenger))) "Tags remained after Contestant ended turn"))))
(testing "Posted Bounty interaction -- Issue #1043"
(do-game
(new-game (default-contestant [(qty "Posted Bounty" 2) (qty "24/7 News Cycle" 3)])
(default-challenger))
(play-from-hand state :contestant "Posted Bounty" "New party")
(play-from-hand state :contestant "Posted Bounty" "New party")
(let [ag1 (get-content state :party1 0)
ag2 (get-content state :party2 0)]
(score-agenda state :contestant ag1)
(prompt-choice :contestant "No")
(score-agenda state :contestant ag2)
(prompt-choice :contestant "No")
(play-from-hand state :contestant "24/7 News Cycle")
(prompt-select :contestant (find-card "Posted Bounty" (:scored (get-contestant))))
(is (= 1 (:agenda-point (get-contestant))) "Forfeited Posted Bounty")
(prompt-select :contestant (find-card "Posted Bounty" (:scored (get-contestant))))
(prompt-choice :contestant "Yes") ; "Forfeit Posted Bounty to give 1 tag?"
(is (= 1 (:tag (get-challenger))) "Challenger given 1 tag")
(is (= 1 (:bad-publicity (get-contestant))) "Contestant has 1 bad publicity")
(is (zero? (:agenda-point (get-contestant))) "Forfeited Posted Bounty to 24/7 News Cycle"))))
(testing "Swapped agendas are able to be used. #1555"
(do-game
(new-game (default-contestant ["24/7 News Cycle" "Chronos Project"
"Philotic Entanglement" "Profiteering"])
(default-challenger [(qty "Turntable" 3)]))
(score-agenda state :contestant (find-card "Chronos Project" (:hand (get-contestant))))
(score-agenda state :contestant (find-card "Philotic Entanglement" (:hand (get-contestant))))
(take-credits state :contestant)
(play-from-hand state :challenger "Turntable")
(core/steal state :challenger (find-card "Profiteering" (:hand (get-contestant))))
(prompt-choice :challenger "Yes")
(prompt-select :challenger (find-card "Philotic Entanglement" (:scored (get-contestant))))
(is (= 2 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
(take-credits state :challenger)
(play-from-hand state :contestant "24/7 News Cycle")
(prompt-select :contestant (find-card "Chronos Project" (:scored (get-contestant))))
(is (= "Chronos Project" (:title (first (:rfg (get-contestant))))))
;; shouldn't work on an agenda in the Challenger's scored area
(is (= 2 (count (:hand (get-challenger)))))
(prompt-select :contestant (find-card "Philotic Entanglement" (:scored (get-challenger))))
(is (= 2 (count (:hand (get-challenger)))))
;; resolve 'when scored' ability on swapped Profiteering
(is (= 8 (:credit (get-contestant))))
(prompt-select :contestant (find-card "Profiteering" (:scored (get-contestant))))
(prompt-choice :contestant "3")
(is (= 1 (:agenda-point (get-contestant))))
(is (= 3 (:bad-publicity (get-contestant))))
(is (= 23 (:credit (get-contestant))) "Gained 15 credits"))))
(deftest accelerated-diagnostics
;; Accelerated Diagnostics - Interaction with prompt effects, like Shipment from SanSan
(testing "Basic test"
(do-game
(new-game (default-contestant ["Accelerated Diagnostics" "Cerebral Overwriter" "Shipment from SanSan"
"Hedge Fund" "Back Channels"])
(default-challenger))
(starting-hand state :contestant ["Accelerated Diagnostics" "Cerebral Overwriter"])
(play-from-hand state :contestant "Cerebral Overwriter" "New party")
(core/gain state :contestant :credit 1)
(play-from-hand state :contestant "Accelerated Diagnostics")
(let [playarea (get-in @state [:contestant :play-area])
hf (find-card "Hedge Fund" playarea)
ss (find-card "Shipment from SanSan" playarea)
bc (find-card "Back Channels" playarea)
co (get-content state :party1 0)]
(is (= 3 (count playarea)) "3 cards in play area")
(prompt-select :contestant ss)
(prompt-choice :contestant "2")
(prompt-select :contestant co)
(is (= 2 (get-counters (refresh co) :advancement)) "Cerebral Overwriter gained 2 advancements")
(prompt-select :contestant hf)
(is (= 9 (:credit (get-contestant))) "Contestant gained credits from Hedge Fund")
(prompt-select :contestant bc)
(prompt-select :contestant (refresh co))
(is (= 15 (:credit (get-contestant))) "Contestant gained 6 credits for Back Channels"))))
(testing "Interaction with Current"
(do-game
(new-game (default-contestant ["Accelerated Diagnostics" "Cerebral Overwriter"
"Enhanced Login Protocol" "Shipment from SanSan"
"Hedge Fund"])
(default-challenger))
(starting-hand state :contestant ["Accelerated Diagnostics" "Cerebral Overwriter"])
(play-from-hand state :contestant "Cerebral Overwriter" "New party")
(core/gain state :contestant :credit 3)
(play-from-hand state :contestant "Accelerated Diagnostics")
(let [playarea (get-in @state [:contestant :play-area])
hf (find-card "Hedge Fund" playarea)
ss (find-card "Shipment from SanSan" playarea)
elp (find-card "Enhanced Login Protocol" playarea)
co (get-content state :party1 0)]
(is (= 3 (count playarea)) "3 cards in play area")
(prompt-select :contestant elp)
(is (= "Enhanced Login Protocol" (:title (first (get-in @state [:contestant :current]))))
"Enhanced Login Protocol active in Current area")
(prompt-select :contestant ss)
(prompt-choice :contestant "2")
(prompt-select :contestant co)
(is (= 2 (get-counters (refresh co) :advancement)) "Cerebral Overwriter gained 2 advancements")
(prompt-select :contestant hf)
(is (= 9 (:credit (get-contestant))) "Contestant gained credits from Hedge Fund")))))
(deftest an-offer-you-can't-refuse
;; An Offer You Can't Refuse - exact card added to score area, not the last discarded one
(do-game
(new-game (default-contestant ["Celebrity Gift" "An Offer You Can't Refuse"])
(default-challenger))
(play-from-hand state :contestant "An Offer You Can't Refuse")
(prompt-choice :contestant "R&D")
(core/move state :contestant (find-card "Celebrity Gift" (:hand (get-contestant))) :discard)
(is (= 2 (count (:discard (get-contestant)))))
(prompt-choice :challenger "No")
(is (= 1 (:agenda-point (get-contestant))) "An Offer the Challenger refused")
(is (= 1 (count (:scored (get-contestant)))))
(is (find-card "An Offer You Can't Refuse" (:scored (get-contestant))))
(is (= 1 (count (:discard (get-contestant)))))
(is (find-card "Celebrity Gift" (:discard (get-contestant))))))
(deftest big-brother
;; Big Brother - Give the Challenger 2 tags if already tagged
(do-game
(new-game (default-contestant ["Big Brother"])
(default-challenger))
(play-from-hand state :contestant "Big Brother")
(is (= 1 (count (:hand (get-contestant)))) "Card not played because Challenger has no tags")
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "Big Brother")
(is (= 3 (:tag (get-challenger))) "Challenger gained 2 tags")))
(deftest biotic-labor
;; Biotic Labor - Gain 2 clicks
(do-game
(new-game (default-contestant ["Biotic Labor"])
(default-challenger))
(play-from-hand state :contestant "Biotic Labor")
(is (= 1 (:credit (get-contestant))))
(is (= 4 (:click (get-contestant))) "Spent 1 click to gain 2 additional clicks")))
(deftest blue-level-clearance
;; Blue Level Clearance - Gain 5 credits and draw 2 cards
(do-game
(new-game (default-contestant [(qty "Blue Level Clearance" 3)
(qty "Hedge Fund" 3)
(qty "Sweeps Week" 2)])
(default-challenger))
(play-from-hand state :contestant "Blue Level Clearance")
(is (= 8 (:credit (get-contestant))) "Gained 5 credits")
(is (= 1 (:click (get-contestant))))
(is (= 7 (count (:hand (get-contestant)))) "Drew 2 cards")))
(deftest casting-call
;; Casting Call - Only do card-init on the Public agendas. Issue #1128
(do-game
(new-game (default-contestant [(qty "Casting Call" 2) "Oaktown Renovation"
"Improved Tracers" "PI:NAME:<NAME>END_PIunter"])
(default-challenger))
(core/gain state :contestant :click 1)
(play-from-hand state :contestant "Hunter" "HQ")
(let [hunter (get-character state :hq 0)]
(core/reveal state :contestant hunter)
(is (= 4 (:current-strength (refresh hunter))))
(play-from-hand state :contestant "Casting Call")
(prompt-select :contestant (find-card "Improved Tracers" (:hand (get-contestant))))
(prompt-choice :contestant "New party")
(let [imptrac (get-content state :party1 0)]
(is (:revealed (refresh imptrac)) "Improved Tracers is faceup")
(is (= 4 (:current-strength (refresh hunter))) "Hunter hasn't gained strength")
(play-from-hand state :contestant "Casting Call")
(prompt-select :contestant (find-card "PI:NAME:<NAME>END_PIown Renovation" (:hand (get-contestant))))
(prompt-choice :contestant "New party")
(let [oak (get-content state :party2 0)]
(core/advance state :contestant {:card (refresh oak)})
(is (= 5 (:credit (get-contestant))) "Events on Public agenda work; gained 2 credits from advancing")
(take-credits state :contestant)
(run-empty-locale state "Locale 2")
(prompt-select :challenger oak)
(prompt-choice :challenger "Steal")
(is (= 2 (:tag (get-challenger))) "Challenger took 2 tags from accessing agenda with Casting Call hosted on it"))))))
(deftest cerebral-cast
;; Cerebral Cast
(testing "Challenger wins"
(do-game
(new-game (default-contestant ["Cerebral Cast"])
(default-challenger))
(play-from-hand state :contestant "Cerebral Cast")
(is (= 3 (:click (get-contestant))) "Cerebral Cast precondition not met; card not played")
(take-credits state :contestant)
(run-empty-locale state "Archives")
(take-credits state :challenger)
(play-from-hand state :contestant "Cerebral Cast")
(prompt-choice :contestant "0 [Credits]")
(prompt-choice :challenger "0 [Credits]")
(is (zero? (count (:discard (get-challenger)))) "Challenger took no damage")
(is (zero? (:tag (get-challenger))) "Challenger took no tags")))
(testing "Contestant wins"
(do-game
(new-game (default-contestant [(qty "Cerebral Cast" 2)])
(default-challenger))
(take-credits state :contestant)
(run-empty-locale state "Archives")
(take-credits state :challenger)
(play-from-hand state :contestant "Cerebral Cast")
(prompt-choice :contestant "0 [Credits]")
(prompt-choice :challenger "1 [Credits]")
(prompt-choice :challenger "1 brain damage")
(is (= 1 (count (:discard (get-challenger)))) "Challenger took a brain damage")
(is (zero? (:tag (get-challenger))) "Challenger took no tags from brain damage choice")
(play-from-hand state :contestant "Cerebral Cast")
(prompt-choice :contestant "0 [Credits]")
(prompt-choice :challenger "1 [Credits]")
(prompt-choice :challenger "1 tag")
(is (= 1 (count (:discard (get-challenger)))) "Challenger took no additional damage")
(is (= 1 (:tag (get-challenger))) "Challenger took a tag from Cerebral Cast choice"))))
(deftest cerebral-static
;; Cerebral Static
(testing "vs Chaos Theory"
(do-game
(new-game (default-contestant ["Cerebral Static" "Lag Time"])
(make-deck "Chaos Theory: Wünderkind" [(qty "Sure Gamble" 3)]))
(is (= 5 (core/available-mu state)) "CT starts with 5 memory")
(play-from-hand state :contestant "Cerebral Static")
(is (= 4 (core/available-mu state)) "Cerebral Static causes CT to have 4 memory")
(play-from-hand state :contestant "Lag Time")
(is (= 5 (core/available-mu state)) "CT 5 memory restored"))))
(deftest closed-accounts
;; Closed Accounts - Play if Challenger is tagged to make Challenger lose all credits
(do-game
(new-game (default-contestant ["Closed Accounts"])
(default-challenger))
(play-from-hand state :contestant "Closed Accounts")
(is (and (= 3 (:click (get-contestant)))
(= 5 (:credit (get-challenger))))
"Closed Accounts precondition not met; card not played")
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "Closed Accounts")
(is (zero? (:credit (get-challenger))) "Challenger lost all credits")))
(deftest commercialization
;; Commercialization
(testing "Single advancement token"
(do-game
(new-game (default-contestant ["Commercialization"
"Character Wall"])
(default-challenger))
(play-from-hand state :contestant "Character Wall" "HQ")
(core/add-counter state :contestant (refresh (get-character state :hq 0)) :advancement 1)
(play-from-hand state :contestant "Commercialization")
(prompt-select :contestant (refresh (get-character state :hq 0)))
(is (= 6 (:credit (get-contestant))) "Gained 1 for single advanced character from Commercialization")))
(testing "Two advancement tokens"
(do-game
(new-game (default-contestant ["Commercialization"
"Character Wall"])
(default-challenger))
(play-from-hand state :contestant "Character Wall" "HQ")
(core/add-counter state :contestant (refresh (get-character state :hq 0)) :advancement 2)
(play-from-hand state :contestant "Commercialization")
(prompt-select :contestant (refresh (get-character state :hq 0)))
(is (= 7 (:credit (get-contestant))) "Gained 2 for double advanced character from Commercialization"))))
(deftest consulting-visit
;; Consulting Visit - Only show single copies of operations contestant can afford as choices. Play chosen operation
(testing "Basic test"
(do-game
(new-game (default-contestant ["Consulting Visit"
(qty "Beanstalk Royalties" 2)
"Green Level Clearance"
"Breaking News"
"Hedge Fund"])
(default-challenger))
(is (= 5 (:credit (get-contestant))))
(starting-hand state :contestant ["Consulting Visit"])
(play-from-hand state :contestant "Consulting Visit")
(let [get-prompt (fn [] (first (#(get-in @state [:contestant :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-card :contestant (find-card "Beanstalk Royalties" (:deck (get-contestant))))
(is (= 6 (:credit (get-contestant)))))))
(testing "Works properly when played with Mumbad City Hall"
(do-game
(new-game (default-contestant ["Mumbad City Hall"
"Beanstalk Royalties"
"Green Level Clearance"
"Breaking News"
"Hedge Fund"
"Consulting Visit"
"Mumba Temple"])
(default-challenger))
(is (= 5 (:credit (get-contestant))))
(starting-hand state :contestant ["Mumbad City Hall"])
(play-from-hand state :contestant "Mumbad City Hall" "New party")
(let [hall (get-content state :party1 0)
get-prompt (fn [] (first (#(get-in @state [:contestant :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(card-ability state :contestant hall 0)
(is (= (list "Consulting Visit" "Mumba Temple" nil) (prompt-names)))
(prompt-card :contestant (find-card "Consulting Visit" (:deck (get-contestant))))
(is (= 3 (:credit (get-contestant))))
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-card :contestant (find-card "Green Level Clearance" (:deck (get-contestant))))
(is (= 5 (:credit (get-contestant))))))))
(deftest death-and-taxes
;; Death and Taxes gain credit on challenger place, challenger discard placed card
;; Also regression test for #3160
(do-game
(new-game (default-contestant ["Death and Taxes" "PAD Campaign"])
(default-challenger ["Aumakua" "DaVinci" "Fall Guy"]))
(play-from-hand state :contestant "Death and Taxes")
(is (= (- 5 2) (:credit (get-contestant))) "Contestant paid 2 to play Death and Taxes")
(play-from-hand state :contestant "PAD Campaign" "New party")
(take-credits state :contestant)
(let [contestant-creds (:credit (get-contestant))]
(discard-from-hand state :challenger "DaPI:NAME:<NAME>END_PI")
(is (= contestant-creds (:credit (get-contestant))) "Contestant did not gain credit when challenger discards / discards from hand")
(play-from-hand state :challenger "Aumakua")
(is (= (+ 1 contestant-creds) (:credit (get-contestant))) "Contestant gained 1 when challenger placed Aumakua")
(play-from-hand state :challenger "Fall Guy")
(is (= (+ 2 contestant-creds) (:credit (get-contestant))) "Contestant gained 1 when challenger placed Fall Guy")
(card-ability state :challenger (get-radicle state 0) 1)
(is (= (+ 3 contestant-creds) (:credit (get-contestant))) "Contestant gained 1 when challenger discarded Fall Guy")
(run-empty-locale state :party1)
(prompt-choice-partial :challenger "Pay") ;; Challenger discards PAD Campaign
(is (= (+ 4 contestant-creds) (:credit (get-contestant))) "Contestant gained 1 when challenger discarded PAD Campaign"))))
(deftest defective-brainchips
;; Defective Brainchips - Do 1 add'l brain damage the first time Challenger takes some each turn
(do-game
(new-game (default-contestant ["Defective Brainchips" "Viktor 1.0"])
(default-challenger [(qty "Sure Gamble" 2) (qty "Shiv" 2)]))
(play-from-hand state :contestant "Defective Brainchips")
(play-from-hand state :contestant "Viktor 1.0" "HQ")
(take-credits state :contestant)
(run-on state :hq)
(let [vik (get-character state :hq 0)]
(core/reveal state :contestant vik)
(card-subroutine state :contestant vik 0)
(is (= 2 (count (:discard (get-challenger)))) "2 cards lost to brain damage")
(is (= 2 (:brain-damage (get-challenger))) "Brainchips dealt 1 additional brain dmg")
(card-subroutine state :contestant vik 0)
(is (= 3 (count (:discard (get-challenger)))) "2 cards lost to brain damage")
(is (= 3 (:brain-damage (get-challenger))) "Brainchips didn't do additional brain dmg"))))
(deftest distract-the-masses
(do-game
(new-game (default-contestant [(qty "Distract the Masses" 2) (qty "Hedge Fund" 3)])
(default-challenger))
(starting-hand state :contestant ["Hedge Fund" "Hedge Fund" "Hedge Fund" "Distract the Masses" "Distract the Masses"])
(play-from-hand state :contestant "Distract the Masses")
(prompt-select :contestant (first (:hand (get-contestant))))
(prompt-select :contestant (first (next (:hand (get-contestant)))))
(prompt-select :contestant (first (:discard (get-contestant))))
(prompt-choice :contestant "Done")
(is (= 1 (count (:discard (get-contestant)))) "1 card still discarded")
(is (= 1 (count (:deck (get-contestant)))) "1 card shuffled into R&D")
(is (= 1 (count (:rfg (get-contestant)))) "Distract the Masses removed from game")
(is (= 7 (:credit (get-challenger))) "Challenger gained 2 credits")
(play-from-hand state :contestant "Distract the Masses")
(prompt-select :contestant (first (:hand (get-contestant))))
(prompt-choice :contestant "Done")
(prompt-select :contestant (first (:discard (get-contestant))))
(prompt-select :contestant (first (next (:discard (get-contestant)))))
(is (zero? (count (:discard (get-contestant)))) "No cards left in archives")
(is (= 3 (count (:deck (get-contestant)))) "2 more cards shuffled into R&D")
(is (= 2 (count (:rfg (get-contestant)))) "Distract the Masses removed from game")
(is (= 9 (:credit (get-challenger))) "Challenger gained 2 credits")))
(deftest diversified-portfolio
(do-game
(new-game (default-contestant ["Diversified Portfolio"
"Paper Wall"
(qty "PAD Campaign" 3)])
(default-challenger))
(core/gain state :contestant :click 2)
(play-from-hand state :contestant "Paper Wall" "New party")
(play-from-hand state :contestant "PAD Campaign" "New party")
(play-from-hand state :contestant "PAD Campaign" "New party")
(play-from-hand state :contestant "PAD Campaign" "New party")
(play-from-hand state :contestant "Diversified Portfolio")
(is (= 7 (:credit (get-contestant))) "Ignored party with Character but no locale contents")))
(deftest door-to-door
;; Door to Door
(do-game
(new-game (default-contestant ["Door to Door"])
(default-challenger))
(play-from-hand state :contestant "Door to Door")
(take-credits state :contestant)
(is (zero? (:tag (get-challenger))) "Challenger should start with 0 tags")
(is (= 3 (-> (get-challenger) :hand count)) "Challenger should start with 3 cards in hand")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger should gain 1 tag from Door to Door")
(is (= 3 (-> (get-challenger) :hand count)) "Challenger should start with 3 cards in hand")
(take-credits state :challenger)
(take-credits state :contestant)
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger should still have 1 tag")
(is (= 2 (-> (get-challenger) :hand count)) "Challenger should take 1 meat damage from Door to Door")))
(deftest economic-warfare
;; Economic Warfare - If successful run last turn, make the challenger lose 4 credits if able
(do-game
(new-game (default-contestant [(qty "Economic Warfare" 3)])
(default-challenger))
(play-from-hand state :contestant "Economic Warfare")
(is (= 5 (:credit (get-challenger))) "Challenger has 5 credits")
(is (= 3 (count (:hand (get-contestant)))) "Contestant still has 3 cards")
(take-credits state :contestant)
(run-on state :archives)
(run-successful state)
(take-credits state :challenger)
(play-from-hand state :contestant "Economic Warfare")
(is (= 4 (:credit (get-challenger))) "Challenger has 4 credits")
(play-from-hand state :contestant "Economic Warfare")
(is (zero? (:credit (get-challenger))) "Challenger has 0 credits")
(take-credits state :contestant)
(run-on state :archives)
(take-credits state :challenger)
(play-from-hand state :contestant "Economic Warfare")
(is (= 3 (:credit (get-challenger))) "Challenger has 3 credits")))
(deftest election-day
(do-game
(new-game (default-contestant [(qty "Election Day" 7)])
(default-challenger))
(is (= 6 (count (:hand (get-contestant)))) "Contestant starts with 5 + 1 cards")
(core/move state :contestant (find-card "Election Day" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Election Day" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Election Day" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Election Day" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Election Day" (:hand (get-contestant))) :deck)
(play-from-hand state :contestant "Election Day")
(is (= 1 (count (:hand (get-contestant)))) "Could not play Election Day")
(take-credits state :contestant)
(take-credits state :challenger)
(is (= 2 (count (:hand (get-contestant)))) "Contestant has now 1 + 1 cards before Election Day")
(play-from-hand state :contestant "Election Day")
(is (= 5 (count (:hand (get-contestant)))) "Contestant has now 5 cards due to Election Day")))
(deftest enforcing-loyalty
;; Enforcing Loyalty - Win trace to discard placed card not of Challenger's faction
(do-game
(new-game (default-contestant [(qty "Enforcing Loyalty" 2)])
(make-deck "Chaos Theory: Wünderkind" ["Inti" "Caldera"]))
(take-credits state :contestant)
(play-from-hand state :challenger "PI:NAME:<NAME>END_PI")
(play-from-hand state :challenger "PI:NAME:<NAME>END_PI")
(take-credits state :challenger)
(play-from-hand state :contestant "Enforcing Loyalty")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-resource state 0))
(is (empty? (:discard (get-challenger))) "Can't target Inti; matches Challenger faction")
(prompt-select :contestant (get-radicle state 0))
(is (= 1 (count (:discard (get-challenger)))) "PI:NAME:<NAME>END_PI discarded")))
(deftest enhanced-login-protocol
;; Enhanced Login Protocol
(testing "First click run each turn costs an additional click"
(do-game
(new-game (default-contestant ["Enhanced Login Protocol"])
(default-challenger ["Employee Strike"]))
(play-from-hand state :contestant "Enhanced Login Protocol")
(take-credits state :contestant)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-challenger))) "Challenger spends 1 additional click to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger doesn't spend 1 additional click to make the second run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(take-credits state :challenger 3)
(is (= 1 (:click (get-challenger))) "Challenger has 1 click")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 1 (:click (get-challenger))) "Challenger has 1 click")
(take-credits state :challenger)
(take-credits state :contestant)
(play-from-hand state :challenger "Employee Strike")
(is (= 3 (:click (get-challenger))) "Challenger has 3 clicks")
(run-on state :archives)
(is (= 2 (:click (get-challenger))) "Challenger doesn't spend 1 additional click to make a run")))
(testing "Card ability runs don't cost additional clicks"
(do-game
(new-game (default-contestant ["Enhanced Login Protocol"])
(default-challenger ["Sneakdoor Beta"]))
(play-from-hand state :contestant "Enhanced Login Protocol")
(take-credits state :contestant)
(play-from-hand state :challenger "Sneakdoor Beta")
(take-credits state :challenger)
(take-credits state :contestant)
(is (= 4 (:click (get-challenger))) "Challenger has 2 clicks")
(let [sneakdoor (get-resource state 0)]
(card-ability state :challenger sneakdoor 0)
(is (= 3 (:click (get-challenger))) "Challenger doesn't spend 1 additional click to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger spends 1 additional click to make a run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-challenger))) "Challenger spends 1 additional click to make a run"))))
(testing "with New Angeles Sol, Enhanced Login Protocol discarded and replaced on steal doesn't double remove penalty"
(do-game
(new-game
(make-deck "New Angeles Sol: Your News" ["Enhanced Login Protocol" "Breaking News"])
(default-challenger))
(play-from-hand state :contestant "Breaking News" "New party")
(play-from-hand state :contestant "Enhanced Login Protocol")
(take-credits state :contestant)
(run-on state :party1)
(run-successful state)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Enhanced Login Protocol" (:discard (get-contestant))))
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger has 1 click")))
(testing "Run event don't cost additional clicks"
(do-game
(new-game (default-contestant ["Enhanced Login Protocol"])
(default-challenger ["Out of the Ashes"]))
(play-from-hand state :contestant "Enhanced Login Protocol")
(take-credits state :contestant)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(play-from-hand state :challenger "Out of the Ashes")
(prompt-choice :challenger "Archives")
(is (= 3 (:click (get-challenger))) "Challenger doesn't spend 1 additional click to run with a run event")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger spends 1 additional click to make a run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(prompt-choice :challenger "No") ; Out of the Ashes prompt
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-challenger))) "Challenger spends 1 additional click to make a run")))
(testing "Works when played on the challenger's turn"
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
["Enhanced Login Protocol"
"Breaking News"])
(default-challenger ["Hades Shard"]))
(discard-from-hand state :contestant "Breaking News")
(take-credits state :contestant)
(core/gain state :challenger :credit 2)
(play-from-hand state :challenger "Hades Shard")
(card-ability state :challenger (get-radicle state 0) 0)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Enhanced Login Protocol" (:hand (get-contestant))))
(is (find-card "Enhanced Login Protocol" (:current (get-contestant))) "Enhanced Login Protocol is in play")
(is (= 3 (:click (get-challenger))) "Challenger has 3 clicks")
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger spends 1 additional click to make a run")))
(testing "Doesn't fire if already run when played on the challenger's turn"
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
["Enhanced Login Protocol"
"Breaking News"])
(default-challenger ["Hades Shard"]))
(discard-from-hand state :contestant "Breaking News")
(take-credits state :contestant)
(run-on state :hq)
(run-successful state)
(prompt-choice :challenger "No action")
(core/gain state :challenger :credit 2)
(play-from-hand state :challenger "Hades Shard")
(card-ability state :challenger (get-radicle state 0) 0)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Enhanced Login Protocol" (:hand (get-contestant))))
(is (find-card "Enhanced Login Protocol" (:current (get-contestant))) "Enhanced Login Protocol is in play")
(is (= 2 (:click (get-challenger))) "Challenger has 2 clicks")
(run-on state :archives)
(is (= 1 (:click (get-challenger))) "Challenger doesn't spend 1 additional click to make a run"))))
(deftest exchange-of-information
;; Exchange of Information
(testing "Basic test"
(do-game
(new-game (default-contestant ["Exchange of Information"
"Market Research"
"Breaking News"
"Project Beale"
"Explode-a-palooza"])
(default-challenger))
(score-agenda state :contestant (find-card "Market Research" (:hand (get-contestant))))
(score-agenda state :contestant (find-card "Breaking News" (:hand (get-contestant))))
(is (= 2 (:tag (get-challenger))) "Challenger gained 2 tags")
(take-credits state :contestant)
(is (zero? (:tag (get-challenger))) "Challenger lost 2 tags")
(core/steal state :challenger (find-card "Project Beale" (:hand (get-contestant))))
(core/steal state :challenger (find-card "Explode-a-palooza" (:hand (get-contestant))))
(take-credits state :challenger)
(is (= 4 (:agenda-point (get-challenger))))
(is (= 3 (:agenda-point (get-contestant))))
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "Project Beale" (:scored (get-challenger))))
(prompt-select :contestant (find-card "Breaking News" (:scored (get-contestant))))
(is (= 3 (:agenda-point (get-challenger))))
(is (= 4 (:agenda-point (get-contestant))))))
(testing "Swapping a just scored Breaking News keeps the tags"
(do-game
(new-game (default-contestant ["Exchange of Information"
"Market Research"
"Breaking News"
"Project Beale"
"Explode-a-palooza"])
(default-challenger))
(take-credits state :contestant)
(core/steal state :challenger (find-card "Project Beale" (:hand (get-contestant))))
(core/steal state :challenger (find-card "Explode-a-palooza" (:hand (get-contestant))))
(take-credits state :challenger)
(score-agenda state :contestant (find-card "Breaking News" (:hand (get-contestant))))
(is (= 2 (:tag (get-challenger))) "Challenger gained 2 tags")
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "Project Beale" (:scored (get-challenger))))
(prompt-select :contestant (find-card "Breaking News" (:scored (get-contestant))))
(is (= 2 (:tag (get-challenger))) "Still has tags after swap and before end of turn")
(take-credits state :contestant)
(is (= 3 (:agenda-point (get-challenger))))
(is (= 2 (:agenda-point (get-contestant))))
(is (= 2 (:tag (get-challenger))) "Challenger does not lose tags at end of turn")))
(testing "Swapping a 15 Minutes still keeps the ability. #1783"
(do-game
(new-game (default-contestant [(qty "Exchange of Information" 2) "15 Minutes"
"Project Beale"])
(default-challenger))
(score-agenda state :contestant (find-card "15 Minutes" (:hand (get-contestant))))
(take-credits state :contestant)
(core/gain state :challenger :tag 1)
(core/steal state :challenger (find-card "Project Beale" (:hand (get-contestant))))
(take-credits state :challenger)
(is (= 1 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "Project Beale" (:scored (get-challenger))))
(prompt-select :contestant (find-card "15 Minutes" (:scored (get-contestant))))
(is (= 2 (:agenda-point (get-contestant))))
(is (= 1 (:agenda-point (get-challenger))))
(is (zero? (count (:deck (get-contestant)))))
;; shuffle back into R&D from challenger's scored area
(let [fifm (get-scored state :challenger 0)]
(card-ability state :contestant fifm 0))
(is (= 2 (:agenda-point (get-contestant))))
(is (zero? (:agenda-point (get-challenger))))
(is (= "15 Minutes" (:title (first (:deck (get-contestant))))))
(take-credits state :contestant)
(core/steal state :challenger (find-card "15 Minutes" (:deck (get-contestant))))
(take-credits state :challenger)
(is (= 2 (:agenda-point (get-contestant))))
(is (= 1 (:agenda-point (get-challenger))))
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "15 Minutes" (:scored (get-challenger))))
(prompt-select :contestant (find-card "Project Beale" (:scored (get-contestant))))
(is (= 1 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
;; shuffle back into R&D from contestant's scored area
(let [fifm (get-scored state :contestant 0)]
(card-ability state :contestant fifm 0))
(is (= "15 Minutes" (:title (first (:deck (get-contestant))))))))
(testing "Swapping a Mandatory Regions gives the Contestant an additional click per turn. #1687"
(do-game
(new-game (default-contestant [(qty "Exchange of Information" 2) "Mandatory Regions"
"Global Food Initiative"])
(default-challenger))
(score-agenda state :contestant (find-card "Global Food Initiative" (:hand (get-contestant))))
(take-credits state :contestant)
(core/gain state :challenger :tag 1)
(core/steal state :challenger (find-card "Mandatory Regions" (:hand (get-contestant))))
(take-credits state :challenger)
(is (= 3 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
(is (= 3 (:click (get-contestant))))
(is (= 3 (:click-per-turn (get-contestant))))
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "Mandatory Regions" (:scored (get-challenger))))
(prompt-select :contestant (find-card "Global Food Initiative" (:scored (get-contestant))))
(is (= 2 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
(is (= 3 (:click (get-contestant))))
(is (= 4 (:click-per-turn (get-contestant))))
(take-credits state :contestant)
(take-credits state :challenger)
(is (= 4 (:click (get-contestant))))
(is (= 4 (:click-per-turn (get-contestant))))
(play-from-hand state :contestant "Exchange of Information")
(prompt-select :contestant (find-card "Global Food Initiative" (:scored (get-challenger))))
(prompt-select :contestant (find-card "Mandatory Regions" (:scored (get-contestant))))
(is (= 3 (:agenda-point (get-contestant))))
(is (= 2 (:agenda-point (get-challenger))))
(is (= 2 (:click (get-contestant))))
(is (= 3 (:click-per-turn (get-contestant))))
(take-credits state :contestant)
(take-credits state :challenger)
(is (= 3 (:click (get-contestant))))
(is (= 3 (:click-per-turn (get-contestant)))))))
(deftest foxfire
;; Foxfire
(do-game
(new-game (default-contestant [(qty "Foxfire" 2)])
(default-challenger ["PI:NAME:<NAME>END_PI" "Character Carver"]))
(take-credits state :contestant)
(core/gain state :challenger :credit 100)
(play-from-hand state :challenger "PI:NAME:<NAME>END_PI")
(play-from-hand state :challenger "PI:NAME:<NAME>END_PI")
(take-credits state :challenger)
(play-from-hand state :contestant "Foxfire")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-hazard state 0))
(is (= 1 (-> (get-challenger) :discard count)) "Contestant should discard Dyson Mem Chip from winning Foxfire trace")
(play-from-hand state :contestant "Foxfire")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(is (= 2 (-> (get-challenger) :discard count)) "Contestant should discard Character CarPI:NAME:<NAME>END_PI from winning Foxfire trace")))
(deftest hard-hitting-news
;; Hard-Hitting News
(do-game
(new-game (default-contestant ["Hard-Hitting News"])
(default-challenger))
(take-credits state :contestant)
(run-empty-locale state :rd)
(take-credits state :challenger)
(is (= 3 (:click (get-contestant))) "Contestant should start with 3 clicks")
(play-from-hand state :contestant "Hard-Hitting News")
(is (zero? (:click (get-contestant))) "Playing Hard-Hitting News should lose all remaining clicks")
(is (zero? (:tag (get-challenger))) "Challenger should start with 0 tags")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 4 (:tag (get-challenger))) "Challenger should gain 4 tags from losing Hard-Hitting News trace")))
(deftest hatchet-job
;; Hatchet Job - Win trace to add placed non-virtual to grip
(do-game
(new-game (default-contestant ["Hatchet Job"])
(default-challenger ["Upya" "Ghost Challenger"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Ghost Challenger")
(play-from-hand state :challenger "Upya")
(take-credits state :challenger)
(play-from-hand state :contestant "Hatchet Job")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(is (empty? (:hand (get-challenger))) "Can't choose virtual card")
(is (not (empty? (:prompt (get-contestant)))))
(prompt-select :contestant (get-resource state 0))
(is (= 1 (count (:hand (get-challenger)))) "Upya returned to grip")))
(deftest hedge-fund
(do-game
(new-game (default-contestant) (default-challenger))
(is (= 5 (:credit (get-contestant))))
(play-from-hand state :contestant "Hedge Fund")
(is (= 9 (:credit (get-contestant))))))
(deftest hellion-alpha-test
;; Hellion Alpha Test
(do-game
(new-game (default-contestant [(qty "Hellion Alpha Test" 2)])
(default-challenger ["Daily Casts"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Daily Casts")
(take-credits state :challenger)
(play-from-hand state :contestant "Hellion Alpha Test")
(is (zero? (-> (get-challenger) :deck count)) "Challenger should have no cards in Stack")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(is (= 1 (-> (get-challenger) :deck count)) "Challenger should have 1 card in Stack from losing Hellion Alpha Test trace")
(is (= "Daily Casts" (-> (get-challenger) :deck first :title))
"Challenger should have Daily Casts on top of Stack from losing Hellion Alpha Test trace")
(take-credits state :contestant)
(core/draw state :challenger)
(play-from-hand state :challenger "Daily Casts")
(take-credits state :challenger)
(play-from-hand state :contestant "Hellion Alpha Test")
(is (zero? (:bad-publicity (get-contestant))) "Contestant should start with 0 bad publicity")
(prompt-choice :contestant 0)
(prompt-choice :challenger 2)
(is (= 1 (:bad-publicity (get-contestant))) "Contestant should gain 1 bad publicity from losing Hellion Alpha Test trace")))
(deftest hellion-beta-test
;; Hellion Beta Test
(testing "Winning Trace - Discarding 2 cards"
(do-game
(new-game (default-contestant ["Dedicated Response Team" "Hellion Beta Test"])
(default-challenger ["Daily Casts" "PI:NAME:<NAME>END_PI"]))
(play-from-hand state :contestant "Dedicated Response Team" "New party")
(take-credits state :contestant)
(core/gain state :challenger :credit 100)
(play-from-hand state :challenger "Daily Casts")
(play-from-hand state :challenger "PI:NAME:<NAME>END_PI")
(run-empty-locale state :party1)
(prompt-choice-partial :challenger "Pay")
(take-credits state :challenger)
(is (zero? (-> (get-challenger) :discard count)) "Challenger's heap should be empty")
(play-from-hand state :contestant "Hellion Beta Test")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(prompt-select :contestant (get-hazard state 0))
(is (= 2 (-> (get-challenger) :discard count)) "Challenger should have 2 cards in heap after losing Hellion Beta Test trace")))
(testing "Losing trace - Gaining bad publicity"
(do-game
(new-game (default-contestant ["Dedicated Response Team" "Hellion Beta Test"])
(default-challenger ["Daily Casts" "PI:NAME:<NAME>END_PI"]))
(play-from-hand state :contestant "Dedicated Response Team" "New party")
(take-credits state :contestant)
(core/gain state :challenger :credit 100)
(play-from-hand state :challenger "Daily Casts")
(play-from-hand state :challenger "PI:NAME:<NAME>END_PI")
(run-empty-locale state :party1)
(prompt-choice-partial :challenger "Pay")
(take-credits state :challenger)
(is (zero? (:bad-publicity (get-contestant))) "Contestant should start with 0 bad publicity")
(play-from-hand state :contestant "Hellion Beta Test")
(prompt-choice :contestant 0)
(prompt-choice :challenger 2)
(is (= 1 (:bad-publicity (get-contestant))) "Contestant should gain 1 bad publicity from losing Hellion Beta Test trace"))))
(deftest high-profile-target
(testing "when the challenger has no tags"
(do-game
(new-game (default-contestant [(qty "High-Profile Target" 6)])
(default-challenger [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(play-from-hand state :contestant "High-Profile Target")
(is (= 3 (:click (get-contestant))) "Contestant not charged a click")
(is (= 5 (count (:hand (get-challenger)))) "Challenger did not take damage")))
(testing "when the challenger has one tag"
(do-game
(new-game (default-contestant [(qty "High-Profile Target" 6)])
(default-challenger [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "High-Profile Target")
(is (= 3 (count (:hand (get-challenger)))) "Challenger has 3 cards in hand")))
(testing "when the challenger has two tags"
(do-game
(new-game (default-contestant [(qty "High-Profile Target" 6)])
(default-challenger [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :challenger :tag 2)
(play-from-hand state :contestant "High-Profile Target")
(is (= 1 (count (:hand (get-challenger)))) "Challenger has 1 card in hand")))
(testing "When the challenger has three tags, gg"
(do-game
(new-game (default-contestant [(qty "High-Profile Target" 10)])
(default-challenger))
(core/gain state :challenger :tag 3)
(play-from-hand state :contestant "High-Profile Target")
(is (zero? (count (:hand (get-challenger)))) "Challenger has 0 cards in hand")
(is (= :contestant (:winner @state)) "Contestant wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline"))))
(deftest housekeeping
;; Housekeeping - Challenger must discard a card from Grip on first place of a turn
(do-game
(new-game (default-contestant ["Housekeeping"])
(default-challenger [(qty "Cache" 2) "Fall Guy" "PI:NAME:<NAME>END_PI"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Fall Guy")
(take-credits state :challenger)
(play-from-hand state :contestant "Housekeeping")
(take-credits state :contestant)
(play-from-hand state :challenger "Cache")
(prompt-select :challenger (find-card "PI:NAME:<NAME>END_PI" (:hand (get-challenger))))
(is (empty? (:prompt (get-challenger))) "Fall Guy prevention didn't trigger")
(is (= 1 (count (:discard (get-challenger)))) "Card discarded")
(play-from-hand state :challenger "Cache")
(is (empty? (:prompt (get-challenger))) "Housekeeping didn't trigger on 2nd place")))
(deftest invasion-of-privacy
;; Invasion of Privacy - Full test
(do-game
(new-game (default-contestant [(qty "Invasion of Privacy" 3)])
(default-challenger [(qty "Sure Gamble" 2) "Fall Guy" (qty "Cache" 2)]))
(core/gain state :contestant :click 3 :credit 6)
;; discard 2 cards
(play-from-hand state :contestant "Invasion of Privacy")
(prompt-choice :contestant 0) ; default trace
(prompt-choice :challenger 0) ; Challenger won't match
(is (= 5 (count (:hand (get-challenger)))))
(let [get-prompt (fn [] (first (#(get-in @state [:contestant :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" "Sure Gamble" nil) (prompt-names)))
(prompt-card :contestant (find-card "Sure Gamble" (:hand (get-challenger))))
(prompt-card :contestant (find-card "Sure Gamble" (:hand (get-challenger)))))
(is (= 3 (count (:hand (get-challenger)))))
;; able to discard 2 cards but only 1 available target in Challenger's hand
(play-from-hand state :contestant "Invasion of Privacy")
(prompt-choice :contestant 0) ; default trace
(prompt-choice :challenger 0) ; Challenger won't match
(is (= 3 (count (:hand (get-challenger)))))
(let [get-prompt (fn [] (first (#(get-in @state [:contestant :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" nil) (prompt-names)))
(prompt-card :contestant (find-card "Fall Guy" (:hand (get-challenger))))
(is (empty? (get-in @state [:contestant :prompt])) "No prompt for second card"))
(is (= 2 (count (:hand (get-challenger)))))
;; failed trace - take the bad publicity
(play-from-hand state :contestant "Invasion of Privacy")
(prompt-choice :contestant 0) ; default trace
(prompt-choice :challenger 2) ; Challenger matches
(is (= 1 (:bad-publicity (get-contestant))))))
(deftest ipo
;; IPO - credits with Terminal operations
(do-game
(new-game
(default-contestant ["IPO"])
(default-challenger))
(take-credits state :contestant)
(take-credits state :challenger)
(play-from-hand state :contestant "IPO")
(is (= 13 (:credit (get-contestant))))
(is (zero? (:click (get-contestant))) "Terminal ends turns")))
(deftest kill-switch
;; Kill Switch
(do-game
(new-game (default-contestant ["Kill Switch" (qty "Hostile Takeover" 2)])
(default-challenger))
(play-from-hand state :contestant "Kill Switch")
(play-from-hand state :contestant "Hostile Takeover" "New party")
(is (zero? (:brain-damage (get-challenger))) "Challenger should start with 0 brain damage")
(play-and-score state "Hostile Takeover")
(prompt-choice :contestant "Hostile Takeover")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:brain-damage (get-challenger))) "Challenger should get 1 brain damage from Kill Switch after Contestant scores an agenda")
(take-credits state :contestant)
(run-empty-locale state :party1)
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 2 (:brain-damage (get-challenger))) "Challenger should get 1 brain damage from Kill Switch after accecssing an agenda")))
(deftest lag-time
(do-game
(new-game (default-contestant ["Lag Time" "Vanilla" "Lotus Field"])
(default-challenger))
(take-credits state :contestant)
(take-credits state :challenger)
(play-from-hand state :contestant "Vanilla" "HQ")
(play-from-hand state :contestant "Lotus Field" "R&D")
(play-from-hand state :contestant "Lag Time")
(core/reveal state :contestant (get-character state :hq 0))
(core/reveal state :contestant (get-character state :rd 0))
(is (= 1 (:current-strength (get-character state :hq 0))) "Vanilla at 1 strength")
(is (= 5 (:current-strength (get-character state :rd 0))) "Lotus Field at 5 strength")))
(deftest lateral-growth
(do-game
(new-game (default-contestant ["Lateral Growth" "Breaking News"])
(default-challenger))
(is (= 5 (:credit (get-contestant))))
(play-from-hand state :contestant "Lateral Growth")
(prompt-select :contestant (find-card "Breaking News" (:hand (get-contestant))))
(prompt-choice :contestant "New party")
(is (= "Breaking News" (:title (get-content state :party1 0)))
"Breaking News placed by Lateral Growth")
(is (= 7 (:credit (get-contestant))))))
(deftest manhunt
;; Manhunt - only fires once per turn. Unreported issue.
(do-game
(new-game (default-contestant ["Manhunt" (qty "Hedge Fund" 3)])
(default-challenger))
(play-from-hand state :contestant "Manhunt")
(take-credits state :contestant)
(run-empty-locale state "HQ")
(is (:prompt (get-contestant)) "Manhunt trace initiated")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger took 1 tag")
(prompt-choice :challenger "No action")
(is (not (:run @state)) "Run ended")
(run-empty-locale state "HQ")
(is (empty? (:prompt (get-contestant))) "No Manhunt trace on second run")
(prompt-choice :challenger "No action")
(is (not (:run @state)) "Run ended")))
(deftest market-forces
(testing "Full test"
(letfn [(market-forces-credit-test
[{:keys [tag-count challenger-creds expected-credit-diff]}]
(testing (str "when the challenger has " tag-count " tags and " challenger-creds " credits")
(do-game
(new-game (default-contestant [(qty "Market Forces" 6)])
(default-challenger))
(swap! state assoc-in [:contestant :credit] 0)
(swap! state assoc-in [:challenger :credit] challenger-creds)
(core/gain state :challenger :tag tag-count)
(play-from-hand state :contestant "Market Forces")
(is (= expected-credit-diff (:credit (get-contestant)))
(str "the contestant gains " expected-credit-diff " credits"))
(is (= expected-credit-diff (- challenger-creds (:credit (get-challenger))))
(str "the challenger loses " expected-credit-diff " credits")))))]
(doall (map market-forces-credit-test
[{:tag-count 1
:challenger-creds 10
:expected-credit-diff 3}
{:tag-count 2
:challenger-creds 10
:expected-credit-diff 6}
{:tag-count 3
:challenger-creds 10
:expected-credit-diff 9}
{:tag-count 3
:challenger-creds 0
:expected-credit-diff 0}
{:tag-count 3
:challenger-creds 5
:expected-credit-diff 5}]))))
(testing "when the challenger is not tagged"
(do-game
(new-game (default-contestant [(qty "Market Forces" 6)])
(default-challenger))
(play-from-hand state :contestant "Market Forces")
(is (= 6 (count (:hand (get-contestant))))
"Market Forces is not played")
(is (= 3 (:click (get-contestant)))
"the contestant does not spend a click")
(is (= 5 (:credit (get-contestant)) (:credit (get-challenger)))
"credits are unaffected"))))
(deftest mass-commercialization
;; Mass Commercialization
(do-game
(new-game (default-contestant ["Mass Commercialization"
(qty "Character Wall" 3)])
(default-challenger))
(play-from-hand state :contestant "Character Wall" "HQ")
(play-from-hand state :contestant "Character Wall" "R&D")
(play-from-hand state :contestant "Character Wall" "Archives")
(take-credits state :challenger)
(core/advance state :contestant {:card (refresh (get-character state :hq 0))})
(core/advance state :contestant {:card (refresh (get-character state :archives 0))})
(core/advance state :contestant {:card (refresh (get-character state :rd 0))})
(take-credits state :challenger)
(play-from-hand state :contestant "Mass Commercialization")
(is (= 8 (:credit (get-contestant))) "Gained 6 for 3 advanced character from Mass Commercialization")))
(deftest medical-research-fundraiser
;; Medical Research Fundraiser - challenger gains 8creds, challenger gains 3creds
(do-game
(new-game (default-contestant ["Medical Research Fundraiser"])
(default-challenger))
(is (= 5 (:credit (get-contestant))) "Contestant starts with 5 credits")
(is (= 5 (:credit (get-challenger))) "Challenger starts with 5 credits")
(play-from-hand state :contestant "Medical Research Fundraiser")
(is (= 10 (:credit (get-contestant))) "Contestant gains 8 credits")
(is (= 8 (:credit (get-challenger))) "Challenger gains 3 credits")))
(deftest midseason-replacements
;; Midseason Replacements - Trace to give Challenger tags after they steal an agenda
(do-game
(new-game (default-contestant ["Midseason Replacements" "Breaking News"])
(default-challenger))
(play-from-hand state :contestant "Midseason Replacements")
(is (= 3 (:click (get-contestant))) "Midseason precondition not met; Contestant not charged a click")
(play-from-hand state :contestant "Breaking News" "New party")
(take-credits state :contestant)
(is (= 7 (:credit (get-contestant))))
(let [bn (get-content state :party1 0)]
(run-empty-locale state "Locale 1")
(prompt-choice :challenger "Steal")
(is (= 1 (:agenda-point (get-challenger))) "Stole Breaking News")
(take-credits state :challenger)
(play-from-hand state :contestant "Midseason Replacements")
(prompt-choice :contestant 0) ; default trace
(prompt-choice :challenger 0) ; Challenger won't match
(is (= 6 (:tag (get-challenger))) "Challenger took 6 tags"))))
(deftest mushin-no-shin
;; Mushin No Shin - Add 3 advancements to a card; prevent reveal/score of that card the rest of the turn
(do-game
(new-game (default-contestant [(qty "Mushin No Shin" 2) "Ronin" "Profiteering"])
(default-challenger))
(play-from-hand state :contestant "Mushin No Shin")
(prompt-select :contestant (find-card "Ronin" (:hand (get-contestant))))
(let [ronin (get-content state :party1 0)]
(is (= 3 (get-counters (refresh ronin) :advancement)) "3 advancements placed on Ronin")
(core/reveal state :contestant (refresh ronin))
(is (not (:revealed (refresh ronin))) "Ronin did not reveal")
(take-credits state :contestant)
(take-credits state :challenger)
(core/reveal state :contestant (refresh ronin))
(is (:revealed (refresh ronin)) "Ronin now revealed")
(play-from-hand state :contestant "PI:NAME:<NAME>END_PI")
(prompt-select :contestant (find-card "Profiteering" (:hand (get-contestant))))
(let [prof (get-content state :party2 0)]
(core/score state :contestant (refresh prof))
(is (empty? (:scored (get-contestant))) "Profiteering not scored")
(is (zero? (:agenda-point (get-contestant))))
(take-credits state :contestant)
(take-credits state :challenger)
(core/score state :contestant (refresh prof))
(prompt-choice :contestant "0")
(is (= 1 (:agenda-point (get-contestant))) "Profiteering was able to be scored")))))
(deftest mutate
;; Mutate - discard a revealed piece of character, place and reveal one from R&D
(testing "Basic operation"
(do-game
(new-game (default-contestant ["Mutate" "Character Wall" "Enigma" "Hedge Fund"])
(default-challenger))
(core/move state :contestant (find-card "Hedge Fund" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Enigma" (:hand (get-contestant))) :deck)
(play-from-hand state :contestant "Character Wall" "HQ")
(core/reveal state :contestant (get-character state :hq 0))
(is (= 1 (count (get-character state :hq))) "1 character placed")
(is (= "Character Wall" (:title (get-character state :hq 0))) "Character Wall is placed")
(play-from-hand state :contestant "Mutate")
(prompt-select :contestant (get-character state :hq 0))
(is (= 1 (count (get-character state :hq))) "1 character placed")
(is (= "Enigma" (:title (get-character state :hq 0))) "Enigma is placed")
(is (:revealed (get-character state :hq 0)) "Enigma is revealed")
(is (second-last-log-contains? state "Hedge Fund") "Skipped card name was logged")
(is (second-last-log-contains? state "Enigma") "Placed card name was logged")))
(testing "No character in R&D"
(do-game
(new-game (default-contestant ["Mutate" "Character Wall" "Enigma" "Hedge Fund"])
(default-challenger))
(core/move state :contestant (find-card "Hedge Fund" (:hand (get-contestant))) :deck)
(play-from-hand state :contestant "Character Wall" "HQ")
(core/reveal state :contestant (get-character state :hq 0))
(is (= 1 (count (get-character state :hq))) "1 character placed")
(is (= "Character Wall" (:title (get-character state :hq 0))) "Character Wall is placed")
(play-from-hand state :contestant "Mutate")
(prompt-select :contestant (get-character state :hq 0))
(is (empty? (get-character state :hq)) "No character placed")
(is (second-last-log-contains? state "Hedge Fund") "Skipped card name was logged"))))
(deftest neural-emp
;; Neural EMP - Play if Challenger made a run the previous turn to do 1 net damage
(do-game
(new-game (default-contestant ["Neural EMP"])
(default-challenger))
(play-from-hand state :contestant "Neural EMP")
(is (= 3 (:click (get-contestant))) "Neural precondition not met; card not played")
(take-credits state :contestant)
(run-empty-locale state "Archives")
(take-credits state :challenger)
(play-from-hand state :contestant "Neural EMP")
(is (= 1 (count (:discard (get-challenger)))) "Challenger took 1 net damage")))
(deftest oversight-ai
;; Oversight AI - Reveal a piece of Character ignoring all costs
(do-game
(new-game (default-contestant ["Oversight AI" "Archer"])
(default-challenger))
(play-from-hand state :contestant "Archer" "R&D")
(let [archer (get-character state :rd 0)]
(play-from-hand state :contestant "Oversight AI")
(prompt-select :contestant archer)
(is (:revealed (refresh archer)))
(is (= 4 (:credit (get-contestant))) "Archer revealed at no credit cost")
(is (= "Oversight AI" (:title (first (:hosted (refresh archer)))))
"Archer hosting OAI as a condition"))))
(deftest patch
;; Patch - +2 current strength
(do-game
(new-game (default-contestant ["Patch" "Vanilla"])
(default-challenger))
(play-from-hand state :contestant "Vanilla" "HQ")
(core/reveal state :contestant (get-character state :hq 0))
(play-from-hand state :contestant "Patch")
(prompt-select :contestant (get-character state :hq 0))
(is (= 2 (:current-strength (get-character state :hq 0))) "Vanilla at 2 strength")))
(deftest paywall-implementation
;; Paywall Implementation - Gain 1 credit for every successful run
(do-game
(new-game (default-contestant ["Paywall Implementation"])
(default-challenger))
(play-from-hand state :contestant "Paywall Implementation")
(is (= "Paywall Implementation" (:title (first (get-in @state [:contestant :current]))))
"Paywall active in Current area")
(take-credits state :contestant)
(is (= 7 (:credit (get-contestant))))
(run-empty-locale state "Archives")
(is (= 8 (:credit (get-contestant))) "Gained 1 credit from successful run")
(run-empty-locale state "Archives")
(is (= 9 (:credit (get-contestant))) "Gained 1 credit from successful run")))
(deftest peak-efficiency
;; Peak Efficiency - Gain 1 credit for each revealed Character
(do-game
(new-game (default-contestant ["Peak Efficiency" (qty "Paper Wall" 3) "Wraparound"])
(default-challenger))
(core/gain state :contestant :click 3)
(play-from-hand state :contestant "Paper Wall" "HQ")
(play-from-hand state :contestant "Paper Wall" "R&D")
(play-from-hand state :contestant "Paper Wall" "New party")
(play-from-hand state :contestant "Wraparound" "New party")
(core/reveal state :contestant (get-character state :hq 0))
(core/reveal state :contestant (get-character state :rd 0))
(core/reveal state :contestant (get-character state :party1 0))
(play-from-hand state :contestant "Peak Efficiency")
(is (= 7 (:credit (get-contestant))) "Gained 3 credits for 3 revealed Character; unrevealed Character ignored")))
(deftest power-shutdown
;; Power Shutdown - Discard cards from R&D to force Challenger to discard a resource or hazard
(do-game
(new-game (default-contestant [(qty "Power Shutdown" 3) (qty "Hive" 3)])
(default-challenger ["Grimoire" "Cache"]))
(play-from-hand state :contestant "Power Shutdown")
(is (empty? (:discard (get-contestant))) "Not played, no run last turn")
(take-credits state :contestant)
(play-from-hand state :challenger "Cache")
(play-from-hand state :challenger "PI:NAME:<NAME>END_PI")
(run-empty-locale state :archives)
(take-credits state :challenger)
(core/move state :contestant (find-card "Hive" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Hive" (:hand (get-contestant))) :deck)
(core/move state :contestant (find-card "Hive" (:hand (get-contestant))) :deck)
(play-from-hand state :contestant "Power Shutdown")
(prompt-choice :contestant 2)
(is (= 3 (count (:discard (get-contestant)))) "2 cards discarded from R&D")
(is (= 1 (count (:deck (get-contestant)))) "1 card remaining in R&D")
(prompt-select :challenger (get-hazard state 0)) ; try targeting Grimoire
(is (empty? (:discard (get-challenger))) "Grimoire too expensive to be targeted")
(prompt-select :challenger (get-resource state 0))
(is (= 1 (count (:discard (get-challenger)))) "Cache discarded")))
(deftest power-grid-overload
;; Power Grid Overload
(do-game
(new-game (default-contestant ["Power Grid Overload"])
(default-challenger ["PI:NAME:<NAME>END_PI Mem Chip"]))
(take-credits state :contestant)
(play-from-hand state :challenger "PI:NAME:<NAME>END_PI Mem Chip")
(run-empty-locale state :rd)
(take-credits state :challenger)
(play-from-hand state :contestant "Power Grid Overload")
(prompt-choice :contestant 3)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-hazard state 0))
(is (= 1 (-> (get-challenger) :discard count)) "PI:NAME:<NAME>END_PIson Mem Chip should be in heap after Challenger loses Power Grid Overload trace")))
(deftest precognition
;; Precognition - Full test
(do-game
(new-game (default-contestant ["Precognition" "Caprcharacter Nisei" "Adonis Campaign"
"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "Global Food Initiative"])
(default-challenger))
(starting-hand state :contestant ["Precognition"])
(play-from-hand state :contestant "Precognition")
(prompt-card :contestant (find-card "PI:NAME:<NAME>END_PI" (:deck (get-contestant))))
(prompt-card :contestant (find-card "Adonis Campaign" (:deck (get-contestant))))
(prompt-card :contestant (find-card "PI:NAME:<NAME>END_PI" (:deck (get-contestant))))
(prompt-card :contestant (find-card "PI:NAME:<NAME>END_PI" (:deck (get-contestant))))
(prompt-card :contestant (find-card "Global Food Initiative" (:deck (get-contestant))))
;; try starting over
(prompt-choice :contestant "Start over")
(prompt-card :contestant (find-card "Global Food Initiative" (:deck (get-contestant))))
(prompt-card :contestant (find-card "PI:NAME:<NAME>END_PI" (:deck (get-contestant))))
(prompt-card :contestant (find-card "PI:NAME:<NAME>END_PI" (:deck (get-contestant))))
(prompt-card :contestant (find-card "Adonis Campaign" (:deck (get-contestant))))
(prompt-card :contestant (find-card "Caprcharacter Nisei" (:deck (get-contestant)))) ;this is the top card of R&D
(prompt-choice :contestant "Done")
(is (= "PI:NAME:<NAME>END_PI" (:title (first (:deck (get-contestant))))))
(is (= "Adonis Campaign" (:title (second (:deck (get-contestant))))))
(is (= "QuandPI:NAME:<NAME>END_PI" (:title (second (rest (:deck (get-contestant)))))))
(is (= "PI:NAME:<NAME>END_PI" (:title (second (rest (rest (:deck (get-contestant))))))))
(is (= "Global Food Initiative" (:title (second (rest (rest (rest (:deck (get-contestant)))))))))))
(deftest preemptive-action
;; Preemptive Action - Shuffles cards into R&D and removes itself from game
(testing "Basic test"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 3)
"Preemptive Action"])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Preemptive Action")
(prompt-select :contestant (first (:discard (get-contestant))))
(prompt-select :contestant (second (:discard (get-contestant))))
(prompt-select :contestant (last (:discard (get-contestant))))
(is (zero? (count (:discard (get-contestant)))))
(is (= 1 (count (:rfg (get-contestant)))))))
(testing "forces you to take 3 if there are three, and removes itself from game"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 3)
(qty "Preemptive Action" 1)])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Preemptive Action")
(prompt-select :contestant (first (:discard (get-contestant))))
(prompt-select :contestant (last (:discard (get-contestant))))
(is (= 3 (count (:discard (get-contestant)))))
(is (= 1 (count (:rfg (get-contestant)))))))
(testing "Shuffles all archives cards into R&D if Archives has less than 3 cards, and removes itself from game"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 2)
(qty "Preemptive Action" 1)])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Preemptive Action")
(prompt-select :contestant (first (:discard (get-contestant))))
(prompt-select :contestant (last (:discard (get-contestant))))
(is (zero? (count (:discard (get-contestant)))))
(is (= 1 (count (:rfg (get-contestant))))))))
(deftest psychographics
;; Psychographics - Place advancements up to the number of Challenger tags on a card
(do-game
(new-game (default-contestant ["Psychographics" "Project Junebug"])
(default-challenger))
(core/gain state :challenger :tag 4)
(play-from-hand state :contestant "Project Junebug" "New party")
(let [pj (get-content state :party1 0)]
(play-from-hand state :contestant "Psychographics")
(prompt-choice :contestant 4)
(prompt-select :contestant pj)
(is (= 1 (:credit (get-contestant))) "Spent 4 credits")
(is (= 4 (get-counters (refresh pj) :advancement)) "Junebug has 4 advancements"))))
(deftest psychokinesis
;; Pyschokinesis - Terminal Event (end the turn); Look at R&D, place an Site, Agenda, or Region in a Party Locale
(do-game
(new-game (default-contestant [(qty "Psychokinesis" 3) "Caprcharacter Nisei" "Adonis Campaign"
"Global Food Initiative" "Mwanza City Grid"])
(default-challenger))
(starting-hand state :contestant ["Psychokinesis" "Psychokinesis" "Psychokinesis"])
;; Test placing an Region
(play-from-hand state :contestant "Psychokinesis")
(is (not-any? #{"Mwanza City Grid"} (map :title (-> (get-contestant) :prompt first :choices)))
"Mwanza City Grid is not on the list of placeable cards")
(prompt-card :contestant (find-card "Caprcharacter Nisei" (:deck (get-contestant))))
(prompt-choice :contestant "New party")
(is (= "PI:NAME:<NAME>END_PI" (:title (get-content state :party1 0)))
"CapPI:NAME:<NAME>END_PI Nisei placed by Psychokinesis")
;; Test placing an Site
(core/gain state :contestant :click 1)
(play-from-hand state :contestant "Psychokinesis")
(prompt-card :contestant (find-card "Adonis Campaign" (:deck (get-contestant))))
(prompt-choice :contestant "New party")
(is (= "Adonis Campaign" (:title (get-content state :party2 0)))
"Adonis Campaign placed by Psychokinesis")
;; Test placing an Agenda
(core/gain state :contestant :click 1)
(play-from-hand state :contestant "Psychokinesis")
(prompt-card :contestant (find-card "Global Food Initiative" (:deck (get-contestant))))
(prompt-choice :contestant "New party")
(is (= "Global Food Initiative" (:title (get-content state :party3 0)))
"Global Food Initiative placed by Psychokinesis")
;; Test selecting "None"
(core/gain state :contestant :click 1)
(core/move state :contestant (find-card "Psychokinesis" (:discard (get-contestant))) :hand)
(play-from-hand state :contestant "Psychokinesis")
(prompt-choice :contestant "None")
(is (= nil (:title (get-content state :party4 0)))
"Nothing is placed by Psychokinesis")))
(deftest punitive-counterstrike
;; Punitive Counterstrike - deal meat damage equal to printed agenda points
(do-game
(new-game (default-contestant ["Global Food Initiative" "Punitive Counterstrike"])
(default-challenger))
(play-from-hand state :contestant "Global Food Initiative" "New party")
(take-credits state :contestant)
(run-empty-locale state :party1)
(prompt-choice :challenger "Steal")
(is (= 2 (:agenda-point (get-challenger))) "Challenger scored 2 points")
(take-credits state :challenger)
(play-from-hand state :contestant "Punitive Counterstrike")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (empty? (:hand (get-challenger))) "Challenger took 3 meat damage")))
(deftest red-planet-couriers
;; Red Planet Couriers - Move all advancements on cards to 1 advanceable card
(do-game
(new-game (default-contestant ["Red Planet Couriers" (qty "Character Wall" 2)
"GRNDL Refinery" "Government Takeover"])
(default-challenger))
(core/gain state :contestant :click 4)
(play-from-hand state :contestant "Government Takeover" "New party")
(play-from-hand state :contestant "GRNDL Refinery" "New party")
(play-from-hand state :contestant "Character Wall" "HQ")
(play-from-hand state :contestant "Character Wall" "R&D")
(let [gt (get-content state :party1 0)
gr (get-content state :party2 0)
iw1 (get-character state :hq 0)
iw2 (get-character state :rd 0)]
(core/add-prop state :contestant gr :advance-counter 3)
(core/add-prop state :contestant iw1 :advance-counter 2)
(core/add-prop state :contestant iw2 :advance-counter 1)
(play-from-hand state :contestant "Red Planet Couriers")
(prompt-select :contestant gt)
(is (zero? (get-counters (refresh gr) :advancement)) "Advancements removed")
(is (zero? (get-counters (refresh iw1) :advancement)) "Advancements removed")
(is (zero? (get-counters (refresh iw2) :advancement)) "Advancements removed")
(is (= 6 (get-counters (refresh gt) :advancement)) "Gained 6 advancements"))))
(deftest reuse
;; Reuse - Gain 2 credits for each card discarded from HQ
(do-game
(new-game (default-contestant [(qty "Reuse" 2) "Hive" "IQ"
"Character Wall"])
(default-challenger))
(play-from-hand state :contestant "Reuse")
(prompt-select :contestant (find-card "Character Wall" (:hand (get-contestant))))
(prompt-select :contestant (find-card "Hive" (:hand (get-contestant))))
(prompt-select :contestant (find-card "IQ" (:hand (get-contestant))))
(prompt-choice :contestant "Done")
(is (= 4 (count (:discard (get-contestant)))) "3 cards discarded plus operation played")
(is (= 11 (:credit (get-contestant))) "Gained 6 credits")
(is (= 1 (:click (get-contestant))) "Spent 2 clicks")))
(deftest reverse-infection
;; Reverse Infection - purge and discard 1 card from stack for every 3 counters purged - or gain 2 credits
(do-game
(new-game (default-contestant [(qty "Reverse Infection" 2)])
(default-challenger ["Virus Breeding Ground" "Datasucker" (qty "Sure Gamble" 3)]))
(starting-hand state :challenger ["Virus Breeding Ground" "Datasucker"])
(play-from-hand state :contestant "Reverse Infection")
(prompt-choice :contestant "Gain 2 [Credits]")
(is (= 7 (:credit (get-contestant))) "Contestant gained 2 credits")
(take-credits state :contestant)
(play-from-hand state :challenger "Virus Breeding Ground")
(play-from-hand state :challenger "Datasucker")
(take-credits state :challenger)
(core/add-counter state :challenger (get-radicle state 0) :virus 4)
(core/add-counter state :challenger (get-resource state 0) :virus 3)
(play-from-hand state :contestant "Reverse Infection")
(prompt-choice :contestant "Purge virus counters.")
(is (= 9 (:credit (get-contestant))) "Contestant did not gain credits")
(is (zero? (get-counters (get-radicle state 0) :virus)) "Viruses purged from VBG")
(is (zero? (get-counters (get-resource state 0) :virus)) "Viruses purged from Datasucker")
(is (= 2 (count (:discard (get-challenger)))) "Two cards discarded from stack")))
(deftest riot-suppression
;; Riot Suppression - lose 3 clicks or take 1 brain damage
(testing "Take 1 brain damage"
(do-game
(new-game (default-contestant ["Riot Suppression" "Adonis Campaign"])
(default-challenger))
(play-from-hand state :contestant "Adonis Campaign" "New party")
(take-credits state :contestant)
(run-empty-locale state "Locale 1")
(prompt-choice-partial :challenger "Pay")
(take-credits state :challenger)
(play-from-hand state :contestant "Riot Suppression")
(is (empty? (:discard (get-challenger))) "Challenger discard is empty")
(is (zero? (:brain-damage (get-challenger))) "Challenger starts with no brain damage")
(prompt-choice-partial :challenger "Yes")
(is (= 1 (count (:discard (get-challenger)))) "1 card lost to brain damage")
(is (= 1 (:brain-damage (get-challenger))) "Challenger took 1 brain damage")
(is (= 1 (count (:discard (get-contestant)))) "No contestant cards discarded")
(is (= 1 (count (:rfg (get-contestant)))) "Riot Suppestion removed from game")
(take-credits state :contestant)
(is (= 4 (:click (get-challenger))) "Challenger has all clicks the following turn")))
(testing "Lose 3 clicks"
(do-game
(new-game (default-contestant ["Riot Suppression" "Adonis Campaign"])
(default-challenger))
(play-from-hand state :contestant "Adonis Campaign" "New party")
(take-credits state :contestant)
(run-empty-locale state "Locale 1")
(prompt-choice-partial :challenger "Pay")
(take-credits state :challenger)
(play-from-hand state :contestant "Riot Suppression")
(is (empty? (:discard (get-challenger))) "Challenger discard is empty")
(is (zero? (:brain-damage (get-challenger))) "Challenger starts with no brain damage")
(prompt-choice-partial :challenger "No")
(is (empty? (:discard (get-challenger))) "Challenger discard statys empty")
(is (zero? (:brain-damage (get-challenger))) "Challenger takes no brain damage")
(is (= 1 (count (:discard (get-contestant)))) "No contestant cards discarded")
(is (= 1 (count (:rfg (get-contestant)))) "Riot Suppestion removed from game")
(take-credits state :contestant)
(is (= 1 (:click (get-challenger))) "Challenger has 3 fewer clicks following turn"))))
(deftest rolling-brownout
;; Rolling Brownout - Increase cost of events/operations by 1, gain 1c on first Challenger event of turn
(do-game
(new-game (default-contestant ["Rolling Brownout" "Beanstalk Royalties"
"Domestic Sleepers"])
(default-challenger [(qty "Easy Mark" 3)]))
(play-from-hand state :contestant "Rolling Brownout")
(play-from-hand state :contestant "Beanstalk Royalties")
(is (= 5 (:credit (get-contestant))) "Beanstalk netted only 2c")
(play-from-hand state :contestant "Domestic Sleepers" "New party")
(take-credits state :contestant)
(play-from-hand state :challenger "Easy Mark")
(is (= 7 (:credit (get-challenger))) "Easy Mark netted only 2c")
(is (= 6 (:credit (get-contestant))) "Contestant gained 1c from Brownout")
(play-from-hand state :challenger "Easy Mark")
(is (= 6 (:credit (get-contestant))) "No Contestant credit gain from 2nd event")
(run-empty-locale state "Locale 1")
(prompt-choice :challenger "Steal")
(play-from-hand state :challenger "Easy Mark")
(is (= 12 (:credit (get-challenger))) "Easy Mark netted 3c after Brownout discarded")))
(deftest salem's-hospitality
;; Salem's Hospitality - Full test
(do-game
(new-game (default-contestant [(qty "Salem's Hospitality" 3)])
(default-challenger [(qty "I've Had Worse" 3) "Faust"
"Levy AR Lab Access"]))
(play-from-hand state :contestant "Salem's Hospitality")
(is (= 5 (count (:hand (get-challenger)))))
(prompt-choice :contestant "I've Had Worse")
(is (= 2 (count (:hand (get-challenger)))))
(play-from-hand state :contestant "Salem's Hospitality")
(prompt-choice :contestant "Plascrete Carapace")
(is (= 2 (count (:hand (get-challenger)))))))
(deftest scorched-earth
;; Scorched Earth
(testing "Basic test"
(do-game
(new-game (default-contestant ["Scorched Earth"])
(default-challenger [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "Scorched Earth")
(is (= 1 (count (:hand (get-challenger)))) "Challenger has 1 card in hand")))
(testing "not tagged"
(do-game
(new-game (default-contestant ["Scorched Earth"])
(default-challenger [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(play-from-hand state :contestant "Scorched Earth")
(is (= 3 (:click (get-contestant))) "Contestant not charged a click")
(is (= 5 (count (:hand (get-challenger)))) "Challenger did not take damage")))
(testing "flatline"
(do-game
(new-game (default-contestant [(qty "Scorched Earth" 10)])
(default-challenger))
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "Scorched Earth")
(is (zero? (count (:hand (get-challenger)))) "Challenger has 0 cards in hand")
(is (= :contestant (:winner @state)) "Contestant wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline"))))
(deftest sea-source
;; SEA Source
(do-game
(new-game (default-contestant ["SEA Source"])
(default-challenger))
(take-credits state :contestant)
(run-empty-locale state :rd)
(take-credits state :challenger)
(is (zero? (:tag (get-challenger))) "Challenger should start with 0 tags")
(play-from-hand state :contestant "SEA Source")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger should get 1 tag from losing SEA Source trace")))
(deftest self-growth-resource
;; Self-Growth Resource - Add 2 placed cards to grip if challenger is tagged
(do-game
(new-game (default-contestant ["Self-Growth Resource"])
(default-challenger ["Clone Chip" "Inti"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Clone Chip")
(play-from-hand state :challenger "Inti")
(take-credits state :challenger)
(play-from-hand state :contestant "Self-Growth Resource")
(is (= 3 (:click (get-contestant))) "Self-Growth Resource precondition not met; card not played")
(core/gain state :challenger :tag 1)
(is (zero? (count (:hand (get-challenger)))) "Challenger hand is empty")
(let [inti (get-resource state 0)
cc (get-hazard state 0)]
(play-from-hand state :contestant "Self-Growth Resource")
(prompt-select :contestant inti)
(prompt-select :contestant cc))
(is (= 2 (count (:hand (get-challenger)))) "2 cards returned to hand")
(is (zero? (count (get-resource state))) "No resources placed")
(is (zero? (count (get-hazard state))) "No hazard placed")))
(deftest servcharacter-outage
;; Servcharacter Outage
(testing "First click run each turn costs a credit"
(do-game
(new-game (default-contestant ["Servcharacter Outage"])
(default-challenger ["Employee Strike"]))
(play-from-hand state :contestant "Servcharacter Outage")
(take-credits state :contestant)
(is (= 5 (:credit (get-challenger))) "Challenger has 5 credits")
(run-on state :archives)
(is (= 4 (:credit (get-challenger)))
"Challenger spends 1 credit to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 4 (:credit (get-challenger)))
"Challenger doesn't spend 1 credit to make the second run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(core/lose state :challenger :credit 6)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (zero? (:credit (get-challenger))) "Challenger has 0 credits")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (zero? (:credit (get-challenger))) "Challenger has 0 credits")
(take-credits state :challenger)
(take-credits state :contestant)
(core/lose state :challenger :credit 2)
(play-from-hand state :challenger "Employee Strike")
(is (= 1 (:credit (get-challenger))) "Challenger has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-challenger)))
"Challenger doesn't spend 1 credit to make a run")))
(testing "First card ability run each turn costs an additional credit"
(do-game
(new-game (default-contestant ["Servcharacter Outage"])
(default-challenger ["Sneakdoor Beta"]))
(play-from-hand state :contestant "Servcharacter Outage")
(take-credits state :contestant)
(play-from-hand state :challenger "Sneakdoor Beta")
(take-credits state :challenger 1)
(is (= 2 (:credit (get-challenger))) "Challenger has 2 credits")
(let [sneakdoor (get-resource state 0)]
(card-ability state :challenger sneakdoor 0)
(is (= 1 (:credit (get-challenger)))
"Challenger spends 1 additional credit to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:credit (get-challenger)))
"Challenger doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(core/lose state :challenger :credit 1)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (zero? (:credit (get-challenger))) "Challenger has 0 credits")
(card-ability state :challenger sneakdoor 0)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (zero? (:credit (get-challenger))) "Challenger has 0 credits"))))
(testing "First run event each turn costs an additional credit"
(do-game
(new-game (default-contestant ["Servcharacter Outage"])
(default-challenger [(qty "Out of the Ashes" 2)]))
(play-from-hand state :contestant "Servcharacter Outage")
(take-credits state :contestant)
(is (= 5 (:credit (get-challenger))) "Challenger has 5 credits")
(play-from-hand state :challenger "Out of the Ashes")
(is (= 3 (:credit (get-challenger)))
"Challenger spends 1 additional credit to run with a run event")
(prompt-choice :challenger "Archives")
(run-successful state)
(run-on state :archives)
(is (= 3 (:credit (get-challenger)))
"Challenger doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :challenger)
(take-credits state :contestant)
(prompt-choice :challenger "No") ; Out of the Ashes prompt
(core/lose state :challenger :credit 4)
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (= 1 (:credit (get-challenger))) "Challenger has 1 credit")
(play-from-hand state :challenger "Out of the Ashes")
(is (empty? (get-in @state [:challenger :prompt]))
"Out of the Ashes was not played")
(is (= 4 (:click (get-challenger))) "Challenger has 4 clicks")
(is (= 1 (:credit (get-challenger))) "Challenger has 1 credit")))
(testing "Works when played on the challenger's turn"
(do-game
(new-game (make-deck "New Angeles Sol: Your News" ["Servcharacter Outage"
"Breaking News"])
(default-challenger ["Hades Shard"]))
(discard-from-hand state :contestant "Breaking News")
(take-credits state :contestant)
(core/gain state :challenger :credit 3)
(play-from-hand state :challenger "Hades Shard")
(card-ability state :challenger (get-radicle state 0) 0)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Servcharacter Outage" (:hand (get-contestant))))
(is (find-card "Servcharacter Outage" (:current (get-contestant)))
"Servcharacter Outage is in play")
(is (= 1 (:credit (get-challenger))) "Challenger has 1 credit")
(run-on state :archives)
(is (zero? (:credit (get-challenger)))
"Challenger spends 1 additional credit to make a run")))
(testing "Doesn't fire if already run when played on the challenger's turn"
(do-game
(new-game (make-deck "New Angeles Sol: Your News" ["Servcharacter Outage"
"Breaking News"])
(default-challenger ["Hades Shard"]))
(discard-from-hand state :contestant "Breaking News")
(take-credits state :contestant)
(run-on state :hq)
(run-successful state)
(prompt-choice :challenger "No action")
(core/gain state :challenger :credit 3)
(play-from-hand state :challenger "Hades Shard")
(card-ability state :challenger (get-radicle state 0) 0)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Servcharacter Outage" (:hand (get-contestant))))
(is (find-card "Servcharacter Outage" (:current (get-contestant)))
"Servcharacter Outage is in play")
(is (= 1 (:credit (get-challenger))) "Challenger has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-challenger)))
"Challenger doesn't spend 1 additional credit to make a run")))
(testing "discarded and replaced on steal doesn't double remove penalty"
(do-game
(new-game
(make-deck "New Angeles Sol: Your News" ["Servcharacter Outage"
"Breaking News"])
(default-challenger))
(play-from-hand state :contestant "Breaking News" "New party")
(play-from-hand state :contestant "Servcharacter Outage")
(take-credits state :contestant)
(run-on state :party1)
(run-successful state)
(prompt-choice :challenger "Steal")
(prompt-choice :contestant "Yes")
(prompt-select :contestant (find-card "Servcharacter Outage" (:discard (get-contestant))))
(take-credits state :challenger)
(take-credits state :contestant)
(is (= 7 (:credit (get-challenger))) "Challenger has 7 credits")
(run-on state :archives)
(is (= 6 (:credit (get-challenger))) "Challenger spends 1 credit to make a run"))))
(deftest shipment-from-sansan
;; Shipment from SanSan - placing advancements
(do-game
(new-game (default-contestant [(qty "Shipment from SanSan" 3) (qty "Character Wall" 3)])
(default-challenger))
(play-from-hand state :contestant "Character Wall" "HQ")
(let [iwall (get-character state :hq 0)]
(play-from-hand state :contestant "Shipment from SanSan")
(prompt-choice :contestant "2")
(prompt-select :contestant iwall)
(is (= 5 (:credit (get-contestant))))
(is (= 2 (get-counters (refresh iwall) :advancement))))))
(deftest snatch-and-grab
;; Snatch and Grab
(do-game
(new-game (default-contestant [(qty "Snatch and Grab" 2)])
(default-challenger ["Scrubber"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Scrubber")
(take-credits state :challenger)
(is (zero? (:tag (get-challenger))) "Challenger should start with 0 tags")
(play-from-hand state :contestant "Snatch and Grab")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(prompt-choice :challenger "Yes")
(is (= 1 (:tag (get-challenger))) "Challenger should get 1 tag from losing Snatch and Grab trace and opting to take the tag")
(is (zero? (-> (get-challenger) :discard count)) "Challenger should start with 0 cards in heap")
(play-from-hand state :contestant "Snatch and Grab")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-radicle state 0))
(prompt-choice :challenger "No")
(is (= 1 (-> (get-challenger) :discard count)) "Scrubber should be in Challenger's heap after losing Snatch and Grab trace")))
(deftest stock-buy-back
;; Stock Buy-Back - Gain 3c for every agenda in Challenger's area
(do-game
(new-game (default-contestant [(qty "Hostile Takeover" 2) (qty "Stock Buy-Back" 3)])
(default-challenger))
(play-from-hand state :contestant "Hostile Takeover" "New party")
(play-from-hand state :contestant "Hostile Takeover" "New party")
(take-credits state :contestant)
(run-empty-locale state "Locale 1")
(prompt-choice :challenger "Steal")
(run-empty-locale state "Locale 2")
(prompt-choice :challenger "Steal")
(take-credits state :challenger)
(is (= 2 (count (:scored (get-challenger)))))
(play-from-hand state :contestant "Stock Buy-Back")
(is (= 11 (:credit (get-contestant))))))
(deftest sub-boost
;; Sub Boost - Give Character Barrier
(do-game
(new-game (default-contestant ["Sub Boost" "Quandary"])
(default-challenger))
(play-from-hand state :contestant "Quandary" "HQ")
(let [qu (get-character state :hq 0)]
(core/reveal state :contestant qu)
(is (not (core/has-subtype? (refresh qu) "Barrier")) "Quandry starts without Barrier")
(is (= 1 (count (:subroutines (refresh qu)))) "Quandry has 1 subroutine")
(play-from-hand state :contestant "Sub Boost")
(prompt-select :contestant (refresh qu))
(is (core/has-subtype? (refresh qu) "Code Gate") "Quandary has Code Gate")
(is (core/has-subtype? (refresh qu) "Barrier") "Quandary Character Barrier")
(is (= 2 (count (:subroutines (refresh qu)))) "Quandry gains a subroutine"))))
(deftest subcontract
;; Subcontract
(testing "Don't allow second operation until damage prevention completes"
(do-game
(new-game (default-contestant [(qty "Scorched Earth" 2) "Subcontract"])
(default-challenger ["Plascrete Carapace"]))
(take-credits state :contestant)
(core/gain state :challenger :tag 1)
(play-from-hand state :challenger "Plascrete Carapace")
(take-credits state :challenger)
(play-from-hand state :contestant "Subcontract")
(prompt-select :contestant (find-card "Scorched Earth" (:hand (get-contestant))))
(is (and (= 1 (count (:prompt (get-contestant)))) (= :waiting (-> (get-contestant) :prompt first :prompt-type)))
"Contestant does not have Subcontract prompt until damage prevention completes")
(prompt-choice :challenger "Done")
(is (not-empty (:prompt (get-contestant))) "Contestant can now play second Subcontract operation")))
(testing "interaction with Terminal operations"
(do-game
(new-game
(default-contestant [(qty "Hard-Hitting News" 2) "Subcontract"])
(default-challenger))
(core/gain state :challenger :tag 1)
(take-credits state :contestant)
(run-empty-locale state :archives)
(take-credits state :challenger)
(play-from-hand state :contestant "Subcontract")
(prompt-select :contestant (find-card "Hard-Hitting News" (:hand (get-contestant))))
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 5 (:tag (get-challenger))) "Challenger has 5 tags")
(is (empty? (:prompt (get-contestant))) "Contestant does not have a second Subcontract selection prompt"))))
(deftest subliminal-messaging
;; Subliminal Messaging - Playing/discarding/milling will all prompt returning to hand
(testing "Basic test"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 3)])
(make-deck "Noise: Hacker Extraordinaire" [(qty "Cache" 3) "Utopia Shard"]))
(play-from-hand state :contestant "Subliminal Messaging")
(is (= 6 (:credit (get-contestant))))
(is (= 3 (:click (get-contestant))) "First Subliminal Messaging gains 1 click")
(play-from-hand state :contestant "Subliminal Messaging")
(is (= 7 (:credit (get-contestant))))
(is (= 2 (:click (get-contestant))) "Second Subliminal Messaging does not gain 1 click")
(discard-from-hand state :contestant "Subliminal Messaging")
(is (zero? (count (:hand (get-contestant)))))
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(is (= 3 (count (:hand (get-contestant)))) "All 3 Subliminals returned to HQ")
(core/move state :contestant (find-card "Subliminal Messaging" (:hand (get-contestant))) :deck)
(take-credits state :contestant)
(play-from-hand state :challenger "Cache")
(play-from-hand state :challenger "Utopia Shard")
(let [utopia (get-radicle state 0)]
(card-ability state :challenger utopia 0))
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(is (= 3 (count (:hand (get-contestant)))) "All 3 Subliminals returned to HQ")
(play-from-hand state :contestant "Subliminal Messaging")
(take-credits state :contestant)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :challenger)
(is (empty? (get-in @state [:contestant :prompt])) "No prompt here because challenger made a run last turn")
(take-credits state :contestant)
(is (= 2 (count (:hand (get-contestant)))))
(is (= 1 (count (:discard (get-contestant)))) "1 Subliminal not returned because challenger made a run last turn")))
(testing "Scenario involving Subliminal being added to HQ with Archived Memories"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 2) "Archived Memories"])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "Archived Memories")
(prompt-select :contestant (find-card "Subliminal Messaging" (:discard (get-contestant))))
(is (= 2 (count (:discard (get-contestant)))))
(is (= 1 (count (:hand (get-contestant)))))
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "No")
(is (empty? (get-in @state [:contestant :prompt])) "Only 1 Subliminal prompt")
(play-from-hand state :contestant "Subliminal Messaging")
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(is (empty? (get-in @state [:contestant :prompt]))
"Only 2 Subliminal prompts - there will be a third if flag not cleared")))
(testing "Scenario involving Subliminal being reshuffled into R&D with PI:NAME:<NAME>END_PI"
(do-game
(new-game (default-contestant ["Subliminal Messaging" "PI:NAME:<NAME>END_PI"])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(play-from-hand state :contestant "PI:NAME:<NAME>END_PI" "New party")
(take-credits state :contestant)
(let [jhow (get-content state :party1 0)]
(core/reveal state :contestant jhow)
(card-ability state :contestant jhow 1)
(prompt-select :contestant (find-card "Subliminal Messaging" (:discard (get-contestant))))
(prompt-choice :contestant "Done")
(is (zero? (count (:discard (get-contestant)))))
(is (= 1 (count (:rfg (get-contestant))))))
(take-credits state :challenger)
(play-from-hand state :contestant "Subliminal Messaging")
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(is (= 1 (count (:hand (get-contestant)))) "Subliminal returned to HQ")
(is (empty? (get-in @state [:contestant :prompt]))
"Subliminal prompt cleared - there will be a second prompt if flag not cleared")))
(testing "Challenger made run, ensure game asks again next turn"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 2)])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(discard-from-hand state :contestant "Subliminal Messaging")
(take-credits state :contestant)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :challenger)
(is (empty? (get-in @state [:contestant :prompt])) "No prompt here because challenger made a run last turn")
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(is (= 2 (count (:hand (get-contestant)))) "Both Subliminals returned to HQ")
(is (zero? (count (:discard (get-contestant)))) "No Subliminals in Archives")))
(testing "User declines to return to hand, ensure game asks again next turn"
(do-game
(new-game (default-contestant [(qty "Subliminal Messaging" 2)])
(default-challenger))
(play-from-hand state :contestant "Subliminal Messaging")
(discard-from-hand state :contestant "Subliminal Messaging")
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "No")
(prompt-choice :contestant "No")
(is (zero? (count (:hand (get-contestant)))) "Neither Subliminal returned to HQ")
(is (= 2 (count (:discard (get-contestant)))) "Both Subliminals in Archives")
(take-credits state :contestant)
(take-credits state :challenger)
(prompt-choice :contestant "Yes")
(prompt-choice :contestant "Yes")
(is (= 2 (count (:hand (get-contestant)))) "Both Subliminals returned to HQ")
(is (zero? (count (:discard (get-contestant)))) "No Subliminals in Archives"))))
(deftest success
;; Success
(testing "Works with bad publicity"
(do-game
(new-game (default-contestant ["NAPD Contract" "Project Beale" "Success"])
(default-challenger))
(play-from-hand state :contestant "NAPD Contract" "New party")
(play-from-hand state :contestant "Project Beale" "New party")
(core/gain state :contestant :bad-publicity 9)
(core/gain state :contestant :credit 8)
(core/gain state :contestant :click 15)
(let [napd (get-content state :party1 0)
beale (get-content state :party2 0)]
(dotimes [_ 13] (core/advance state :contestant {:card (refresh napd)}))
(is (= 13 (get-counters (refresh napd) :advancement)))
(core/score state :contestant {:card (refresh napd)})
(is (= 2 (:agenda-point (get-contestant))))
(play-from-hand state :contestant "Success")
(prompt-select :contestant (get-scored state :contestant 0))
(is (= "NAPD Contract" (:title (first (:rfg (get-contestant))))))
(prompt-select :contestant (refresh beale))
(is (= 13 (get-counters (refresh beale) :advancement)))
(core/score state :contestant {:card (refresh beale)})
(is (= 7 (:agenda-point (get-contestant)))))))
(testing "Works with public agendas"
(do-game
(new-game (default-contestant ["Oaktown Renovation" "Vanity Project" "Success"])
(default-challenger))
(core/gain state :contestant :click 1)
(score-agenda state :contestant (find-card "Vanity Project" (:hand (get-contestant))))
(is (= 4 (:agenda-point (get-contestant))))
(play-from-hand state :contestant "Oaktown Renovation" "New party")
(is (= 5 (:credit (get-contestant))))
(play-from-hand state :contestant "Success")
(prompt-select :contestant (get-scored state :contestant 0))
(is (= "Vanity Project" (:title (first (:rfg (get-contestant))))))
(let [oaktown (get-content state :party1 0)]
(prompt-select :contestant (refresh oaktown))
(is (= 6 (get-counters (refresh oaktown) :advancement)))
(is (= 19 (:credit (get-contestant))) "Gain 2 + 2 + 2 + 2 + 3 + 3 = 14 credits for advancing Oaktown")
(core/score state :contestant {:card (refresh oaktown)})
(is (= 2 (:agenda-point (get-contestant)))))))
(testing "interaction with Jemison, regression test for issue #2704"
(do-game
(new-game (make-deck "Jemison Astronautics: Sacrifcharacter. Audacity. Success."
["Success"
"High-Risk Investment"
"Government Takeover"])
(default-challenger))
(core/gain state :contestant :click 1)
(score-agenda state :contestant (find-card "High-Risk Investment" (:hand (get-contestant))))
(play-from-hand state :contestant "Government Takeover" "New party")
(play-from-hand state :contestant "Success")
(prompt-select :contestant (get-in (get-contestant) [:scored 0]))
(let [gto (get-content state :party1 0)]
;; Prompt for Jemison
(prompt-select :contestant (refresh gto))
(is (= 4 (get-counters (refresh gto) :advancement)) "Added 4 counters from Jemison trigger")
;; Prompt for Success
(prompt-select :contestant (refresh gto))
(is (= (+ 4 5) (get-counters (refresh gto) :advancement)) "Advance 5 times from Success")))))
(deftest successful-demonstration
;; Successful Demonstration - Play if only Challenger made unsuccessful run last turn; gain 7 credits
(do-game
(new-game (default-contestant ["Successful Demonstration"])
(default-challenger))
(play-from-hand state :contestant "Successful Demonstration")
(is (and (= 3 (:click (get-contestant)))
(= 5 (:credit (get-challenger))))
"Successful Demonstration precondition not met; card not played")
(take-credits state :contestant)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :challenger)
(play-from-hand state :contestant "Successful Demonstration")
(is (= 13 (:credit (get-contestant))) "Paid 2 to play event; gained 7 credits")))
(deftest surveillance-sweep
;; Surveillance Sweep
(testing "Basic test"
(do-game
(new-game (default-contestant ["Restructured Datapool" "Surveillance Sweep" "Data Raven"])
(default-challenger ["Scrubbed"]))
(is (zero? (:tag (get-challenger))) "Challenger should start with no tags")
(play-from-hand state :contestant "Surveillance Sweep")
(play-and-score state "Restructured Datapool")
(let [rd-scored (get-scored state :contestant 0)]
(card-ability state :contestant rd-scored 0)
(is (not= :waiting (-> (get-contestant) :prompt first :prompt-type)) "Surveillance Sweep only works during a run")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger should gain a tag from Restructured Datapool ability"))
(take-credits state :contestant)
(take-credits state :challenger)
(play-from-hand state :contestant "Data Raven" "HQ")
(take-credits state :contestant)
(let [dr (get-character state :hq 0)]
(core/reveal state :contestant (refresh dr))
(run-on state :hq)
(card-subroutine state :contestant dr 0)
(is (= :waiting (-> (get-contestant) :prompt first :prompt-type)) "During a run, Contestant should wait on Challenger first")
(prompt-choice :challenger 0)
(prompt-choice :contestant 0)
(is (= 1 (get-counters (refresh dr) :power)) "Data Raven should gain a power counter from trace")
(run-successful state)
(play-from-hand state :challenger "Scrubbed")
(run-on state :hq)
(card-subroutine state :contestant dr 0)
(is (not= :waiting (-> (get-contestant) :prompt first :prompt-type)) "Challenger should now be waiting on Contestant")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 2 (get-counters (refresh dr) :power)) "Data Raven should gain a power counter from trace")
(run-successful state))))
(testing "trace during run after stealing an agenda"
(do-game
(new-game (default-contestant ["Surveillance Sweep" "Breaking News" "Forced Connection" "Data Raven"])
(default-challenger))
(core/gain state :contestant :click 4)
(core/gain state :contestant :credit 20)
(play-from-hand state :contestant "Surveillance Sweep")
(play-from-hand state :contestant "Breaking News" "New party")
(play-from-hand state :contestant "Forced Connection" "Locale 1")
(play-from-hand state :contestant "Data Raven" "Locale 1")
(take-credits state :contestant)
(let [dr (get-character state :party1 0)
bn (get-content state :party1 0)
fc (get-content state :party1 1)]
(core/reveal state :contestant (refresh dr))
(run-on state :party1)
(card-subroutine state :contestant dr 0)
(is (= :waiting (-> (get-contestant) :prompt first :prompt-type)) "During a run, Contestant should wait on Challenger first")
(prompt-choice :challenger 0)
(prompt-choice :contestant 0)
(is (= 1 (get-counters (refresh dr) :power)) "Data Raven should gain a power counter from trace")
(run-successful state)
(prompt-select :challenger bn)
(prompt-choice :challenger "Steal")
(prompt-select :challenger fc)
(is (not= :waiting (-> (get-contestant) :prompt first :prompt-type)) "After steal, Surveillance Sweep leaves play and Challenger waits on Contestant")))))
(deftest the-all-seeing-i
(testing "Counts number of cards if one card is prevented discarded with fall guy"
(do-game
(new-game (default-contestant ["The All-Seeing I"])
(default-challenger ["Fall Guy" (qty "Same Old Thing" 2)]))
(letfn [(res [] (count (get-in (get-challenger) [:rig :radicle])))]
(take-credits state :contestant)
(play-from-hand state :challenger "Same Old Thing")
(play-from-hand state :challenger "Fall Guy")
(play-from-hand state :challenger "Same Old Thing")
(take-credits state :challenger)
(play-from-hand state :contestant "The All-Seeing I")
(is (= 1 (count (:hand (get-contestant)))) "Contestant could not play All Seeing I when challenger was not tagged")
(core/gain state :challenger :tag 1)
(play-from-hand state :contestant "The All-Seeing I")
(let [fall-guy (get-radicle state 1)]
(card-ability state :challenger fall-guy 0))
(prompt-choice :challenger "Done")
(is (= 1 (res)) "One placed radicle saved by Fall Guy")
(is (= 2 (count (:discard (get-challenger)))) "Two cards in heap"))))
(testing "Checks that All-seeing I does not double-discard hosted cards, discards hosted cards"
(do-game
(new-game (default-contestant ["The All-Seeing I"])
(default-challenger [(qty "Fall Guy" 2) "Off-Campus Apartment"]))
(take-credits state :contestant)
(play-from-hand state :challenger "Off-Campus Apartment")
(let [oca (get-radicle state 0)
fg1 (get-in (get-challenger) [:hand 0])
fg2 (get-in (get-challenger) [:hand 1])]
(card-ability state :challenger oca 0)
(prompt-select :challenger fg1)
(card-ability state :challenger oca 0)
(prompt-select :challenger fg2))
(core/gain state :challenger :tag 1)
(take-credits state :challenger)
(play-from-hand state :contestant "The All-Seeing I")
(prompt-choice :challenger "Done")
(prompt-choice :challenger "Done")
(let [fall-guy (find-card "Fall Guy" (core/all-active-placed state :challenger))]
(card-ability state :challenger fall-guy 0))
(prompt-choice :challenger "Done") ;; This assumes hosted cards get put in discard-list before host
(is (= 1 (count (core/all-active-placed state :challenger))) "One placed card (Off-Campus)")
(is (= 2 (count (:discard (get-challenger)))) "Two cards in heap")))
(testing "should not discard Jarogniew Mercs if there are other placed radicles"
(do-game
(new-game (default-contestant [(qty "The All-Seeing I" 4)])
(default-challenger [(qty "PI:NAME:<NAME>END_PI" 2) (qty "Same Old Thing" 2)]))
(letfn [(res [] (count (get-in (get-challenger) [:rig :radicle])))]
(take-credits state :contestant)
(play-from-hand state :challenger "Same Old Thing")
(play-from-hand state :challenger "PI:NAME:<NAME>END_PI")
(take-credits state :challenger)
(is (= 2 (res)) "There are two placed radicles")
(play-from-hand state :contestant "The All-Seeing I")
(is (= 1 (res)) "PI:NAME:<NAME>END_PIogniew Mercs still placed")
(play-from-hand state :contestant "The All-Seeing I")
(is (zero? (res)) "There are no placed radicles")
(take-credits state :contestant)
(play-from-hand state :challenger "PI:NAME:<NAME>END_PI") ;; Testing if order matters
(play-from-hand state :challenger "Same Old Thing")
(take-credits state :challenger)
(is (= 2 (res)) "There are two placed radicles")
(play-from-hand state :contestant "The All-Seeing I")
(is (= 1 (res)) "PI:NAME:<NAME>END_PIogniew Mercs still placed")
(play-from-hand state :contestant "The All-Seeing I")
(is (zero? (res)) "There are no placed radicles")))))
(deftest threat-assessment
;; Threat Assessment - play only if challenger discarded a card last turn, move a card to the stack or take 2 tags
(do-game
(new-game (default-contestant [(qty "Threat Assessment" 3) "Adonis Campaign"])
(default-challenger ["Desperado" "Corroder"]))
(play-from-hand state :contestant "Adonis Campaign" "New party")
(take-credits state :contestant)
(run-on state :party1)
(run-successful state)
(prompt-choice-partial :challenger "Pay") ;discard
(core/gain state :challenger :credit 5)
(play-from-hand state :challenger "PI:NAME:<NAME>END_PI")
(play-from-hand state :challenger "Corroder")
(take-credits state :challenger)
(is (zero? (:tag (get-challenger))) "Challenger starts with 0 tags")
(play-from-hand state :contestant "Threat Assessment")
(prompt-select :contestant (find-card "Desperado" (-> (get-challenger) :rig :hazard)))
(prompt-choice :challenger "2 tags")
(is (= 2 (:tag (get-challenger))) "Challenger took 2 tags")
(is (= 1 (count (-> (get-challenger) :rig :hazard))) "Didn't discard Desperado")
(is (= "Threat Assessment" (:title (first (:rfg (get-contestant))))) "Threat Assessment removed from game")
(play-from-hand state :contestant "Threat Assessment")
(prompt-select :contestant (find-card "Corroder" (-> (get-challenger) :rig :resource)))
(prompt-choice :challenger "Move Corroder")
(is (= 2 (:tag (get-challenger))) "Challenger didn't take tags")
(is (= "Corroder" (:title (first (:deck (get-challenger))))) "Moved Corroder to the deck")
(is (= 2 (count (:rfg (get-contestant)))))
(take-credits state :challenger)
(take-credits state :contestant)
(take-credits state :challenger)
(play-from-hand state :contestant "Threat Assessment")
(is (empty? (:prompt (get-contestant))) "Threat Assessment triggered with no discard")))
(deftest threat-level-alpha
;; Threat Level Alpha - Win trace to give tags = Challenger tags; or 1 tag if 0
(do-game
(new-game (default-contestant [(qty "Threat Level Alpha" 2)])
(default-challenger))
(core/gain state :contestant :click 2)
(core/gain state :contestant :credit 2)
(is (zero? (:tag (get-challenger))))
(play-from-hand state :contestant "Threat Level Alpha")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 1 (:tag (get-challenger))) "Challenger took 1 tag because they had 0")
(core/gain state :challenger :tag 2)
(play-from-hand state :contestant "Threat Level Alpha")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (= 6 (:tag (get-challenger))) "Challenger took 3 tag because they had 3")))
(deftest transparency-initiative
;; Transparency Initiative - Full test
(do-game
(new-game (default-contestant ["Transparency Initiative" "Oaktown Renovation"
"Project Atlas" "Hostile Takeover" "Casting Call"])
(default-challenger))
(core/gain state :contestant :click 5)
(play-from-hand state :contestant "Oaktown Renovation" "New party")
(play-from-hand state :contestant "Casting Call")
(prompt-select :contestant (find-card "Project Atlas" (:hand (get-contestant))))
(prompt-choice :contestant "New party")
(play-from-hand state :contestant "Hostile Takeover" "New party")
(let [oaktown (get-content state :party1 0)
atlas (get-content state :party2 0)
hostile (get-content state :party3 0)]
(play-from-hand state :contestant "Transparency Initiative")
(prompt-select :contestant (refresh oaktown))
;; doesn't work on face-up agendas
(is (zero? (count (:hosted (refresh oaktown)))))
(prompt-select :contestant (refresh atlas))
(is (= 1 (count (:hosted (refresh atlas)))) "Casting Call")
;; works on facedown agenda
(prompt-select :contestant (refresh hostile))
(is (= 1 (count (:hosted (refresh hostile)))))
;; gains Public subtype
(is (core/has-subtype? (refresh hostile) "Public"))
;; gain 1 credit when advancing
(is (= 5 (:credit (get-contestant))))
(core/advance state :contestant {:card (refresh hostile)})
(is (= 5 (:credit (get-contestant))))
;; make sure advancing other agendas doesn't gain 1
(core/advance state :contestant {:card (refresh oaktown)})
(is (= 6 (:credit (get-contestant))) "Transparency initiative didn't fire")
(core/advance state :contestant {:card (refresh atlas)})
(is (= 5 (:credit (get-contestant))) "Transparency initiative didn't fire"))))
(deftest trojan-horse
;; Trojan Horse
(do-game
(new-game (default-contestant ["Trojan Horse" "Dedicated Response Team"])
(default-challenger ["Wyrm"]))
(play-from-hand state :contestant "Dedicated Response Team" "New party")
(take-credits state :contestant)
(play-from-hand state :challenger "Wyrm")
(run-empty-locale state :party1)
(take-credits state :challenger)
(is (zero? (-> (get-challenger) :discard count)) "Challenger should start with 0 cards in heap")
(play-from-hand state :contestant "Trojan Horse")
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(prompt-select :contestant (get-resource state 0))
(is (= 1 (-> (get-challenger) :discard count)) "Wyrm should be in heap after Challenger loses Trojan Horse trace")))
(deftest wake-up-call
;; Wake Up Call
(testing "should fire after using En Passant to discard character"
(do-game
(new-game (default-contestant ["Enigma" "Wake Up Call"])
(default-challenger ["En Passant" "Maya"]))
(play-from-hand state :contestant "Enigma" "HQ")
(take-credits state :contestant)
(play-from-hand state :challenger "Maya")
(run-on state :hq)
(run-successful state)
(prompt-choice :challenger "No action")
(is (zero? (count (:discard (get-contestant)))) "Contestant starts with no discards")
(play-from-hand state :challenger "En Passant")
(prompt-select :challenger (get-character state :hq 0))
(is (= 1 (count (:discard (get-contestant)))) "Contestant discards placed character")
(take-credits state :challenger)
(is (= 1 (count (:discard (get-challenger)))) "Challenger starts with 1 discarded card (En Passant)")
(play-from-hand state :contestant "Wake Up Call")
(prompt-select :contestant (get-hazard state 0))
(prompt-choice :challenger "Discard Maya")
(is (= 2 (count (:discard (get-challenger)))) "Maya is discarded")
(is (= 1 (count (:rfg (get-contestant)))) "Wake Up Call is removed from the game"))))
(deftest wetwork-refit
;; Wetwork Refit - Only works on Bioroid Character and adds a subroutine
(do-game
(new-game (default-contestant ["Eli 1.0"
"Vanilla"
(qty "Wetwork Refit" 3)])
(default-challenger))
(core/gain state :contestant :credit 20)
(core/gain state :contestant :click 10)
(play-from-hand state :contestant "Eli 1.0" "R&D")
(play-from-hand state :contestant "Vanilla" "HQ")
(let [eli (get-character state :rd 0)
vanilla (get-character state :hq 0)]
(play-from-hand state :contestant "Wetwork Refit")
(is (not-any? #{"Eli 1.0"} (get-in @state [:contestant :prompt :choices]))
"Unrevealed Eli 1.0 is not a choice to host Wetwork Refit")
(prompt-choice :contestant "Done")
(take-credits state :contestant)
(take-credits state :challenger)
(core/reveal state :contestant (refresh eli))
(core/reveal state :contestant (refresh vanilla))
(play-from-hand state :contestant "Wetwork Refit")
(prompt-select :contestant (refresh eli))
(is (= "Wetwork Refit" (:title (first (:hosted (refresh eli)))))
"Wetwork Refit is hosted on Eli 1.0")
(is (= 2 (count (:subroutines (refresh eli))))
"Eli 1.0 has 2 different subroutines")
(is (= "[Wetwork Refit] Do 1 brain damage" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has a brain damage subroutine as his first subroutine")
(core/move state :contestant (first (:hosted (refresh eli))) :hand)
(is (empty? (:hosted (refresh eli))) "No cards are hosted on Eli 1.0")
(is (= 1 (count (:subroutines (refresh eli))))
"Eli 1.0 has 1 different subroutine")
(is (= "End the run" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has an end the run subroutine as his first subroutine")
(play-from-hand state :contestant "Wetwork Refit")
(prompt-select :contestant (refresh vanilla))
(is (not= "Wetwork Refit" (:title (first (:hosted (refresh vanilla)))))
"Wetwork Refit is not hosted on Vanilla"))))
|
[
{
"context": " [{auth-identity ::auth/identity\n :keys [com.yetanalytics/lrs xapi] :as ctx}]\n (let [{params :xapi.agen",
"end": 882,
"score": 0.7665648460388184,
"start": 870,
"tag": "KEY",
"value": "yetanalytics"
}
] | src/main/com/yetanalytics/lrs/pedestal/routes/agents.cljc | yetanalytics/lrs | 1 | (ns com.yetanalytics.lrs.pedestal.routes.agents
(:require [com.yetanalytics.lrs :as lrs]
[com.yetanalytics.lrs.protocol :as p]
[clojure.core.async :as a :include-macros true]
[com.yetanalytics.lrs.auth :as auth]
[clojure.spec.alpha :as s :include-macros true]))
(s/fdef get-response
:args (s/cat :ctx map?
:get-about-ret ::p/get-person-ret))
(defn get-response
[ctx {:keys [error person] ?etag :etag :as _lrs-response}]
(if error
(assoc ctx :io.pedestal.interceptor.chain/error error)
(cond-> (assoc ctx :response
{:status 200 :body person})
?etag (assoc
:com.yetanalytics.lrs.pedestal.interceptor/etag
?etag))))
(def handle-get
{:name ::handle-get
:enter
(fn handle-get-fn
[{auth-identity ::auth/identity
:keys [com.yetanalytics/lrs xapi] :as ctx}]
(let [{params :xapi.agents.GET.request/params} xapi]
(if (p/agent-info-resource-async? lrs)
(a/go
(get-response ctx (a/<!
(lrs/get-person-async lrs auth-identity params))))
(get-response ctx (lrs/get-person lrs auth-identity params)))))})
| 18935 | (ns com.yetanalytics.lrs.pedestal.routes.agents
(:require [com.yetanalytics.lrs :as lrs]
[com.yetanalytics.lrs.protocol :as p]
[clojure.core.async :as a :include-macros true]
[com.yetanalytics.lrs.auth :as auth]
[clojure.spec.alpha :as s :include-macros true]))
(s/fdef get-response
:args (s/cat :ctx map?
:get-about-ret ::p/get-person-ret))
(defn get-response
[ctx {:keys [error person] ?etag :etag :as _lrs-response}]
(if error
(assoc ctx :io.pedestal.interceptor.chain/error error)
(cond-> (assoc ctx :response
{:status 200 :body person})
?etag (assoc
:com.yetanalytics.lrs.pedestal.interceptor/etag
?etag))))
(def handle-get
{:name ::handle-get
:enter
(fn handle-get-fn
[{auth-identity ::auth/identity
:keys [com.<KEY>/lrs xapi] :as ctx}]
(let [{params :xapi.agents.GET.request/params} xapi]
(if (p/agent-info-resource-async? lrs)
(a/go
(get-response ctx (a/<!
(lrs/get-person-async lrs auth-identity params))))
(get-response ctx (lrs/get-person lrs auth-identity params)))))})
| true | (ns com.yetanalytics.lrs.pedestal.routes.agents
(:require [com.yetanalytics.lrs :as lrs]
[com.yetanalytics.lrs.protocol :as p]
[clojure.core.async :as a :include-macros true]
[com.yetanalytics.lrs.auth :as auth]
[clojure.spec.alpha :as s :include-macros true]))
(s/fdef get-response
:args (s/cat :ctx map?
:get-about-ret ::p/get-person-ret))
(defn get-response
[ctx {:keys [error person] ?etag :etag :as _lrs-response}]
(if error
(assoc ctx :io.pedestal.interceptor.chain/error error)
(cond-> (assoc ctx :response
{:status 200 :body person})
?etag (assoc
:com.yetanalytics.lrs.pedestal.interceptor/etag
?etag))))
(def handle-get
{:name ::handle-get
:enter
(fn handle-get-fn
[{auth-identity ::auth/identity
:keys [com.PI:KEY:<KEY>END_PI/lrs xapi] :as ctx}]
(let [{params :xapi.agents.GET.request/params} xapi]
(if (p/agent-info-resource-async? lrs)
(a/go
(get-response ctx (a/<!
(lrs/get-person-async lrs auth-identity params))))
(get-response ctx (lrs/get-person lrs auth-identity params)))))})
|
[
{
"context": " #_(get-lhd-count-for-date! config \"2021-08-20\" \"Hunter New England\")\n [{:keys [api-url dataset]} date lhd]\n (let [",
"end": 3140,
"score": 0.7733110189437866,
"start": 3122,
"tag": "NAME",
"value": "Hunter New England"
}
] | src/covis/downloader.clj | wongjoel/covid-dataset-visualisation | 0 | (ns covis.downloader
(:require [clj-http.client :as client]
[clojure.data.json :as json])
(:import (java.time LocalDate LocalDateTime ZonedDateTime ZoneId)
(java.time.format DateTimeFormatter)))
(defn gen-date-seq
#_(gen-date-seq (LocalDate/parse "2020-01-01") (LocalDate/parse "2020-02-01"))
"Generated the sequence of dates from the start date (inclusive) to the end date (exclusive)"
[start-date end-date]
(iterator-seq (.iterator (.datesUntil start-date end-date))))
(defn get-dataset-update-from-metadata!
#_(get-dataset-update-from-metadata! config)
[{:keys [metadata-url]}]
(let [response (client/get metadata-url)
body (json/read-str (:body response))
datetime-str (get (first (get-in body ["result" "resources"])) "last_modified")
formatter (DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ss.nX")
datetime (.withZoneSameInstant (ZonedDateTime/parse (str datetime-str "Z") formatter) (ZoneId/systemDefault))]
(.toLocalDateTime datetime)))
(defn simple-sql-get!
[url sql]
(client/get url {:query-params {:sql sql}}))
(defn make-sql-star-unsafe
#_(make-sql-star-unsafe "abc")
[dataset]
(str "SELECT * FROM \"" dataset "\""))
(defn make-sql-distinct-unsafe
#_(make-sql-distinct-unsafe "abc")
[dataset]
(str "SELECT DISTINCT lhd_2010_name FROM \"" dataset "\""))
(defn make-sql-count-lhd-unsafe
#_(make-sql-count-lhd-unsafe "abc" "2020" "def")
[dataset date lhd]
(str "SELECT COUNT(notification_date) FROM \"" dataset "\" WHERE notification_date='" date "' AND lhd_2010_name='" lhd "'"))
(defn make-sql-count-null-unsafe
#_(make-sql-count-null-unsafe "abc" "2020")
[dataset date]
(str "SELECT COUNT(notification_date) FROM \"" dataset "\" WHERE notification_date='" date "' AND lhd_2010_name is NULL"))
(defn make-sql-count-total-unsafe
#_(make-sql-count-total-unsafe "abc" "2020")
[dataset date]
(str "SELECT COUNT(notification_date) FROM \"" dataset "\" WHERE notification_date='" date "'"))
(defn get-lhd-names!
#_(get-lhd-names config)
[{:keys [api-url dataset] :as config}]
(let [response (simple-sql-get! api-url (make-sql-distinct-unsafe dataset))
body (json/read-str (:body response))
records (get-in body ["result" "records"])]
(->> records
(map (fn [record] (get record "lhd_2010_name"))))))
(defn get-total-count-for-date!
#_(get-total-count-for-date! config "2021-08-20")
[{:keys [api-url dataset]} date]
(let [response (simple-sql-get! api-url (make-sql-count-total-unsafe dataset date))
body (json/read-str (:body response))
records (get-in body ["result" "records"])]
(get (first records) "count")))
(defn get-null-count-for-date!
#_(get-null-count-for-date! config "2021-08-20")
[{:keys [api-url dataset]} date]
(let [response (simple-sql-get! api-url (make-sql-count-null-unsafe dataset date))
body (json/read-str (:body response))
records (get-in body ["result" "records"])]
(get (first records) "count")))
(defn get-lhd-count-for-date!
#_(get-lhd-count-for-date! config "2021-08-20" "Hunter New England")
[{:keys [api-url dataset]} date lhd]
(let [response (simple-sql-get! api-url (make-sql-count-lhd-unsafe dataset date lhd))
body (json/read-str (:body response))
records (get-in body ["result" "records"])]
(get (first records) "count")))
(defn get-region-count-for-date!
#_(get-region-count-for-date! config "2021-08-20" "Hunter New England")
#_(get-region-count-for-date! config "2021-08-20" nil)
[config date lhd]
(if (some? lhd)
(get-lhd-count-for-date! config date lhd)
(get-null-count-for-date! config date)))
(defn get-counts-by-lhd-and-date!
#_(get-counts-by-lhd-and-date! config (get-lhd-names! config) "2021-08-25")
[config lhd-names last-update]
(->> (for [lhd lhd-names
date (gen-date-seq (.minusDays (.toLocalDate last-update) 15) (.toLocalDate last-update))]
{:lhd lhd
:date date})
(map (fn [{:keys [date lhd] :as run}] (assoc run :count (get-region-count-for-date! config date lhd))))
(map (fn [{:keys [date lhd count]}] {:count count
:notification-date (str date)
:health-district (if (some? lhd) lhd "Not Listed")}))))
(comment
(def dataset1 "21304414-1ff1-4243-a5d2-f52778048b29")
(def dataset2 "97ea2424-abaf-4f3e-a9f2-b5c883f42b6a")
(def api-url "https://data.nsw.gov.au/data/api/3/action/datastore_search_sql")
(def config
{:api-url "https://data.nsw.gov.au/data/api/3/action/datastore_search_sql"
:metadata-url "https://data.nsw.gov.au/data/api/3/action/package_show?id=aefcde60-3b0c-4bc0-9af1-6fe652944ec2"
:dataset "21304414-1ff1-4243-a5d2-f52778048b29"})
(def response1
(client/get (:metadata-url config)))
(def response2
(client/get "https://data.nsw.gov.au/data/api/3/action/datastore_search" {:query-params {:resource_id "2776dbb8-f807-4fb2-b1ed-184a6fc2c8aa"}}))
(def response3
(client/get "https://data.nsw.gov.au/data/api/3/action/datastore_search_sql" {:query-params {:sql "SELECT COUNT(notification_date) FROM \"2776dbb8-f807-4fb2-b1ed-184a6fc2c8aa\" WHERE notification_date='2021-08-20'"}}))
)
| 64102 | (ns covis.downloader
(:require [clj-http.client :as client]
[clojure.data.json :as json])
(:import (java.time LocalDate LocalDateTime ZonedDateTime ZoneId)
(java.time.format DateTimeFormatter)))
(defn gen-date-seq
#_(gen-date-seq (LocalDate/parse "2020-01-01") (LocalDate/parse "2020-02-01"))
"Generated the sequence of dates from the start date (inclusive) to the end date (exclusive)"
[start-date end-date]
(iterator-seq (.iterator (.datesUntil start-date end-date))))
(defn get-dataset-update-from-metadata!
#_(get-dataset-update-from-metadata! config)
[{:keys [metadata-url]}]
(let [response (client/get metadata-url)
body (json/read-str (:body response))
datetime-str (get (first (get-in body ["result" "resources"])) "last_modified")
formatter (DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ss.nX")
datetime (.withZoneSameInstant (ZonedDateTime/parse (str datetime-str "Z") formatter) (ZoneId/systemDefault))]
(.toLocalDateTime datetime)))
(defn simple-sql-get!
[url sql]
(client/get url {:query-params {:sql sql}}))
(defn make-sql-star-unsafe
#_(make-sql-star-unsafe "abc")
[dataset]
(str "SELECT * FROM \"" dataset "\""))
(defn make-sql-distinct-unsafe
#_(make-sql-distinct-unsafe "abc")
[dataset]
(str "SELECT DISTINCT lhd_2010_name FROM \"" dataset "\""))
(defn make-sql-count-lhd-unsafe
#_(make-sql-count-lhd-unsafe "abc" "2020" "def")
[dataset date lhd]
(str "SELECT COUNT(notification_date) FROM \"" dataset "\" WHERE notification_date='" date "' AND lhd_2010_name='" lhd "'"))
(defn make-sql-count-null-unsafe
#_(make-sql-count-null-unsafe "abc" "2020")
[dataset date]
(str "SELECT COUNT(notification_date) FROM \"" dataset "\" WHERE notification_date='" date "' AND lhd_2010_name is NULL"))
(defn make-sql-count-total-unsafe
#_(make-sql-count-total-unsafe "abc" "2020")
[dataset date]
(str "SELECT COUNT(notification_date) FROM \"" dataset "\" WHERE notification_date='" date "'"))
(defn get-lhd-names!
#_(get-lhd-names config)
[{:keys [api-url dataset] :as config}]
(let [response (simple-sql-get! api-url (make-sql-distinct-unsafe dataset))
body (json/read-str (:body response))
records (get-in body ["result" "records"])]
(->> records
(map (fn [record] (get record "lhd_2010_name"))))))
(defn get-total-count-for-date!
#_(get-total-count-for-date! config "2021-08-20")
[{:keys [api-url dataset]} date]
(let [response (simple-sql-get! api-url (make-sql-count-total-unsafe dataset date))
body (json/read-str (:body response))
records (get-in body ["result" "records"])]
(get (first records) "count")))
(defn get-null-count-for-date!
#_(get-null-count-for-date! config "2021-08-20")
[{:keys [api-url dataset]} date]
(let [response (simple-sql-get! api-url (make-sql-count-null-unsafe dataset date))
body (json/read-str (:body response))
records (get-in body ["result" "records"])]
(get (first records) "count")))
(defn get-lhd-count-for-date!
#_(get-lhd-count-for-date! config "2021-08-20" "<NAME>")
[{:keys [api-url dataset]} date lhd]
(let [response (simple-sql-get! api-url (make-sql-count-lhd-unsafe dataset date lhd))
body (json/read-str (:body response))
records (get-in body ["result" "records"])]
(get (first records) "count")))
(defn get-region-count-for-date!
#_(get-region-count-for-date! config "2021-08-20" "Hunter New England")
#_(get-region-count-for-date! config "2021-08-20" nil)
[config date lhd]
(if (some? lhd)
(get-lhd-count-for-date! config date lhd)
(get-null-count-for-date! config date)))
(defn get-counts-by-lhd-and-date!
#_(get-counts-by-lhd-and-date! config (get-lhd-names! config) "2021-08-25")
[config lhd-names last-update]
(->> (for [lhd lhd-names
date (gen-date-seq (.minusDays (.toLocalDate last-update) 15) (.toLocalDate last-update))]
{:lhd lhd
:date date})
(map (fn [{:keys [date lhd] :as run}] (assoc run :count (get-region-count-for-date! config date lhd))))
(map (fn [{:keys [date lhd count]}] {:count count
:notification-date (str date)
:health-district (if (some? lhd) lhd "Not Listed")}))))
(comment
(def dataset1 "21304414-1ff1-4243-a5d2-f52778048b29")
(def dataset2 "97ea2424-abaf-4f3e-a9f2-b5c883f42b6a")
(def api-url "https://data.nsw.gov.au/data/api/3/action/datastore_search_sql")
(def config
{:api-url "https://data.nsw.gov.au/data/api/3/action/datastore_search_sql"
:metadata-url "https://data.nsw.gov.au/data/api/3/action/package_show?id=aefcde60-3b0c-4bc0-9af1-6fe652944ec2"
:dataset "21304414-1ff1-4243-a5d2-f52778048b29"})
(def response1
(client/get (:metadata-url config)))
(def response2
(client/get "https://data.nsw.gov.au/data/api/3/action/datastore_search" {:query-params {:resource_id "2776dbb8-f807-4fb2-b1ed-184a6fc2c8aa"}}))
(def response3
(client/get "https://data.nsw.gov.au/data/api/3/action/datastore_search_sql" {:query-params {:sql "SELECT COUNT(notification_date) FROM \"2776dbb8-f807-4fb2-b1ed-184a6fc2c8aa\" WHERE notification_date='2021-08-20'"}}))
)
| true | (ns covis.downloader
(:require [clj-http.client :as client]
[clojure.data.json :as json])
(:import (java.time LocalDate LocalDateTime ZonedDateTime ZoneId)
(java.time.format DateTimeFormatter)))
(defn gen-date-seq
#_(gen-date-seq (LocalDate/parse "2020-01-01") (LocalDate/parse "2020-02-01"))
"Generated the sequence of dates from the start date (inclusive) to the end date (exclusive)"
[start-date end-date]
(iterator-seq (.iterator (.datesUntil start-date end-date))))
(defn get-dataset-update-from-metadata!
#_(get-dataset-update-from-metadata! config)
[{:keys [metadata-url]}]
(let [response (client/get metadata-url)
body (json/read-str (:body response))
datetime-str (get (first (get-in body ["result" "resources"])) "last_modified")
formatter (DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ss.nX")
datetime (.withZoneSameInstant (ZonedDateTime/parse (str datetime-str "Z") formatter) (ZoneId/systemDefault))]
(.toLocalDateTime datetime)))
(defn simple-sql-get!
[url sql]
(client/get url {:query-params {:sql sql}}))
(defn make-sql-star-unsafe
#_(make-sql-star-unsafe "abc")
[dataset]
(str "SELECT * FROM \"" dataset "\""))
(defn make-sql-distinct-unsafe
#_(make-sql-distinct-unsafe "abc")
[dataset]
(str "SELECT DISTINCT lhd_2010_name FROM \"" dataset "\""))
(defn make-sql-count-lhd-unsafe
#_(make-sql-count-lhd-unsafe "abc" "2020" "def")
[dataset date lhd]
(str "SELECT COUNT(notification_date) FROM \"" dataset "\" WHERE notification_date='" date "' AND lhd_2010_name='" lhd "'"))
(defn make-sql-count-null-unsafe
#_(make-sql-count-null-unsafe "abc" "2020")
[dataset date]
(str "SELECT COUNT(notification_date) FROM \"" dataset "\" WHERE notification_date='" date "' AND lhd_2010_name is NULL"))
(defn make-sql-count-total-unsafe
#_(make-sql-count-total-unsafe "abc" "2020")
[dataset date]
(str "SELECT COUNT(notification_date) FROM \"" dataset "\" WHERE notification_date='" date "'"))
(defn get-lhd-names!
#_(get-lhd-names config)
[{:keys [api-url dataset] :as config}]
(let [response (simple-sql-get! api-url (make-sql-distinct-unsafe dataset))
body (json/read-str (:body response))
records (get-in body ["result" "records"])]
(->> records
(map (fn [record] (get record "lhd_2010_name"))))))
(defn get-total-count-for-date!
#_(get-total-count-for-date! config "2021-08-20")
[{:keys [api-url dataset]} date]
(let [response (simple-sql-get! api-url (make-sql-count-total-unsafe dataset date))
body (json/read-str (:body response))
records (get-in body ["result" "records"])]
(get (first records) "count")))
(defn get-null-count-for-date!
#_(get-null-count-for-date! config "2021-08-20")
[{:keys [api-url dataset]} date]
(let [response (simple-sql-get! api-url (make-sql-count-null-unsafe dataset date))
body (json/read-str (:body response))
records (get-in body ["result" "records"])]
(get (first records) "count")))
(defn get-lhd-count-for-date!
#_(get-lhd-count-for-date! config "2021-08-20" "PI:NAME:<NAME>END_PI")
[{:keys [api-url dataset]} date lhd]
(let [response (simple-sql-get! api-url (make-sql-count-lhd-unsafe dataset date lhd))
body (json/read-str (:body response))
records (get-in body ["result" "records"])]
(get (first records) "count")))
(defn get-region-count-for-date!
#_(get-region-count-for-date! config "2021-08-20" "Hunter New England")
#_(get-region-count-for-date! config "2021-08-20" nil)
[config date lhd]
(if (some? lhd)
(get-lhd-count-for-date! config date lhd)
(get-null-count-for-date! config date)))
(defn get-counts-by-lhd-and-date!
#_(get-counts-by-lhd-and-date! config (get-lhd-names! config) "2021-08-25")
[config lhd-names last-update]
(->> (for [lhd lhd-names
date (gen-date-seq (.minusDays (.toLocalDate last-update) 15) (.toLocalDate last-update))]
{:lhd lhd
:date date})
(map (fn [{:keys [date lhd] :as run}] (assoc run :count (get-region-count-for-date! config date lhd))))
(map (fn [{:keys [date lhd count]}] {:count count
:notification-date (str date)
:health-district (if (some? lhd) lhd "Not Listed")}))))
(comment
(def dataset1 "21304414-1ff1-4243-a5d2-f52778048b29")
(def dataset2 "97ea2424-abaf-4f3e-a9f2-b5c883f42b6a")
(def api-url "https://data.nsw.gov.au/data/api/3/action/datastore_search_sql")
(def config
{:api-url "https://data.nsw.gov.au/data/api/3/action/datastore_search_sql"
:metadata-url "https://data.nsw.gov.au/data/api/3/action/package_show?id=aefcde60-3b0c-4bc0-9af1-6fe652944ec2"
:dataset "21304414-1ff1-4243-a5d2-f52778048b29"})
(def response1
(client/get (:metadata-url config)))
(def response2
(client/get "https://data.nsw.gov.au/data/api/3/action/datastore_search" {:query-params {:resource_id "2776dbb8-f807-4fb2-b1ed-184a6fc2c8aa"}}))
(def response3
(client/get "https://data.nsw.gov.au/data/api/3/action/datastore_search_sql" {:query-params {:sql "SELECT COUNT(notification_date) FROM \"2776dbb8-f807-4fb2-b1ed-184a6fc2c8aa\" WHERE notification_date='2021-08-20'"}}))
)
|
[
{
"context": "ogin']\\\")\n (input-text \\\"#login_field\\\" \\\"your_username\\\")\n (-> \\\"#password\\\"\n (input-t",
"end": 8717,
"score": 0.996135950088501,
"start": 8704,
"tag": "USERNAME",
"value": "your_username"
},
{
"context": " (-> \\\"#password\\\"\n (input-text \\\"your_password\\\")\n submit))\"\n [arg & body]\n ",
"end": 8777,
"score": 0.7203990817070007,
"start": 8773,
"tag": "PASSWORD",
"value": "your"
}
] | src/clj/shale/client.clj | cardforcoin/shale | 10 | (ns shale.client
(:require [clojure.set :refer [rename-keys]]
[clojure.walk :as walk]
[clj-http.client :as client]
[cheshire [core :as json]]
[clj-webdriver.taxi :as taxi]
[slingshot.slingshot :refer [try+ throw+]]
[taoensso.timbre :as timbre :refer [error]]
[schema.core :as s]
[camel-snake-kebab.core :refer [->snake_case_string]]
[camel-snake-kebab.extras :refer [transform-keys]]
[shale.sessions :as sessions]
[shale.webdriver :as webdriver])
(:use [clj-webdriver.remote.driver :only [session-id]]
shale.utils))
(def default-url-root "http://localhost:5000")
(def ^:private sessions-url
(memoize
(fn [url-root]
(clojure.string/join "/" [url-root "sessions"]))))
(def ^:private nodes-url
(memoize
(fn [url-root]
(clojure.string/join "/" [url-root "nodes"]) )))
(def ^:private proxies-url
(memoize
(fn [url-root]
(clojure.string/join "/" [url-root "proxies"]) )))
(defn ^:private proxy-url [url-root id]
(clojure.string/join "/" [(proxies-url url-root) id]))
(defn ^:private node-url [url-root id]
(clojure.string/join "/" [(nodes-url url-root) id]))
(defn ^:private session-url [url-root id]
(clojure.string/join "/" [(sessions-url url-root) id]))
(defn ^:private session-by-webdriver-url [url-root webdriver-id]
(clojure.string/join "/" [(sessions-url url-root) "webdriver" webdriver-id]))
(s/defschema SessionIdentifier
(s/either
s/Str
{:id s/Str}
{:session-id s/Str}
{:webdriver-id s/Str}))
(s/defn ^:always-validate map->session-url
[url-root :- s/Str
m-or-id :- SessionIdentifier]
(if (map? m-or-id)
(if (contains? m-or-id :webdriver-id)
(session-by-webdriver-url url-root (:webdriver-id m-or-id))
(session-url url-root (or (:session-id m-or-id) (:id m-or-id))))
(session-url url-root m-or-id)))
(defn sessions
([] (sessions default-url-root))
([url-root]
(let [response (try+
(client/get (sessions-url url-root))
(catch [:status 400] {:keys [body]} (error body) (throw+)))]
(json/parse-string (response :body)))))
(defn nodes
([] (nodes default-url-root))
([url-root]
(let [response (try+ (client/get (nodes-url url-root))
(catch [:status 400] {:keys [body]} (error body) (throw+)))]
(json/parse-string (response :body)))))
(defn proxies
([] (proxies default-url-root))
([url-root]
(let [response (try+ (client/get (proxies-url url-root))
(catch [:status 400] {:keys [body]}
(error body)
(throw+)))]
(json/parse-string (response :body)))))
(defn create-proxy!
([requirements] (create-proxy! default-url-root
requirements))
([url-root {:keys [proxy-type
host
port
public-ip
shared
active]
:or {proxy-type "socks5"
shared true
active true
public-ip nil}
:as requirements}]
(let [body (->> (rename-keys requirements
{:proxy-type :type})
(transform-keys ->snake_case_string))
response (try+
(client/post (proxies-url url-root)
{:body (json/generate-string body)
:content-type :json
:accept :json})
(catch [:status 400] {:keys [body]}
(error body)
(throw+)))]
(json/parse-string (response :body)))))
(defn modify-proxy!
([id options] (modify-proxy! default-url-root id options))
([url-root id {:keys [shared active]
:or {shared nil
active nil}
:as modifications}]
(let [url (proxy-url url-root id)
body (->> modifications
(filter #(not (nil? (val %))))
(into {})
(transform-keys ->snake_case_string))
response (try+
(client/patch url
{:body (json/generate-string body)
:content-type :json
:accept :json})
(catch [:status 400] {:keys [body]}
(error body)
(throw+)))]
(json/parse-string (response :body)))))
(defn session
([id] (session default-url-root id))
([url-root id]
(let [url (map->session-url url-root id)
response (client/get url)]
(json/parse-string (response :body)))))
(s/defn get-or-create-session!
([arg :- sessions/GetOrCreateArg]
(get-or-create-session! default-url-root arg))
([url-root :- s/Str
arg :- sessions/GetOrCreateArg]
(let [body (walk/postwalk
#(cond
(= % :socks5) "socks5"
(keyword? %) (->snake_case_string %)
:else %)
arg)
response (try+
(client/post (sessions-url url-root)
{:body (json/generate-string body)
:content-type :json
:accept :json})
(catch [:status 400] {:keys [body]} (error body) (throw+)))]
(json/parse-string (response :body)))))
(s/defn ^:always-validate modify-session!
([id :- SessionIdentifier
modifications :- [sessions/ModifyArg]]
(modify-session! default-url-root id modifications))
([url-root :- s/Str
id :- SessionIdentifier
modifications :- [sessions/ModifyArg]]
(let [url (map->session-url url-root id)
body (->> modifications
(map #(transform-keys ->snake_case_string %))
vec)
response (try+
(client/patch url
{:body (json/generate-string body)
:content-type :json
:accept :json})
(catch [:status 400] {:keys [body]}
(error body)
(throw+)))]
(json/parse-string (response :body)))))
(defn reserve-session!
([id] (reserve-session! default-url-root id))
([url-root id]
(modify-session! url-root id [[:reserve true]])))
(defn release-session!
([id] (release-session! default-url-root id))
([url-root id]
(modify-session! url-root id [[:reserve false]])))
(s/defn destroy-session!
([id] (destroy-session! default-url-root id))
([url-root
id]
(let [url (map->session-url url-root id)]
(client/delete url {:query-params {"immediately" "true"}}))
nil))
(defn destroy-sessions!
([] (destroy-sessions! default-url-root))
([url-root]
(client/delete (sessions-url url-root) {:query-params {"immediately" "true"}})
nil))
(defn refresh-sessions!
([] (refresh-sessions! default-url-root))
([url-root]
(let [response (try+
(client/post
(clojure.string/join "/"
[(sessions-url url-root) "refresh"])
{})
(catch [:status 400] {:keys [body]} (error body) (throw+)))]
(json/parse-string (response :body)))))
(s/defn get-or-create-webdriver!
([arg :- sessions/GetOrCreateArg]
(get-or-create-webdriver! default-url-root arg))
([url-root :- s/Str
arg :- sessions/GetOrCreateArg]
(let [session (get-or-create-session! url-root arg)]
(webdriver/resume-webdriver
(get session "webdriver_id")
(get-in session ["node" "url"])
{"platform" "ANY"
"browserName" (get session "browser_name")}))))
(defn release-webdriver!
([driver] (release-webdriver! default-url-root driver))
([url-root driver]
(if-let [session-id (session-id driver)]
(release-session! url-root {:webdriver-id session-id}))))
(defmacro with-webdriver*
"Given tags and a browser name to get or create a new webdriver session,
execute the forms in `body`, then unreserve the webdriver session.
Example :
========
;;
;; Log into Github
;;
(use 'clj-webdriver.taxi)
(with-webdriver* {:require [:and [[:browser-name :firefox]
[:tag \"github\"]]]}
(to \"https://github.com\")
(click \"a[href*='login']\")
(input-text \"#login_field\" \"your_username\")
(-> \"#password\"
(input-text \"your_password\")
submit))"
[arg & body]
`(binding [~'clj-webdriver.taxi/*driver*
(get-or-create-webdriver! ~arg)]
(try
~@body
(finally
(release-webdriver! ~'clj-webdriver.taxi/*driver*)))))
| 60253 | (ns shale.client
(:require [clojure.set :refer [rename-keys]]
[clojure.walk :as walk]
[clj-http.client :as client]
[cheshire [core :as json]]
[clj-webdriver.taxi :as taxi]
[slingshot.slingshot :refer [try+ throw+]]
[taoensso.timbre :as timbre :refer [error]]
[schema.core :as s]
[camel-snake-kebab.core :refer [->snake_case_string]]
[camel-snake-kebab.extras :refer [transform-keys]]
[shale.sessions :as sessions]
[shale.webdriver :as webdriver])
(:use [clj-webdriver.remote.driver :only [session-id]]
shale.utils))
(def default-url-root "http://localhost:5000")
(def ^:private sessions-url
(memoize
(fn [url-root]
(clojure.string/join "/" [url-root "sessions"]))))
(def ^:private nodes-url
(memoize
(fn [url-root]
(clojure.string/join "/" [url-root "nodes"]) )))
(def ^:private proxies-url
(memoize
(fn [url-root]
(clojure.string/join "/" [url-root "proxies"]) )))
(defn ^:private proxy-url [url-root id]
(clojure.string/join "/" [(proxies-url url-root) id]))
(defn ^:private node-url [url-root id]
(clojure.string/join "/" [(nodes-url url-root) id]))
(defn ^:private session-url [url-root id]
(clojure.string/join "/" [(sessions-url url-root) id]))
(defn ^:private session-by-webdriver-url [url-root webdriver-id]
(clojure.string/join "/" [(sessions-url url-root) "webdriver" webdriver-id]))
(s/defschema SessionIdentifier
(s/either
s/Str
{:id s/Str}
{:session-id s/Str}
{:webdriver-id s/Str}))
(s/defn ^:always-validate map->session-url
[url-root :- s/Str
m-or-id :- SessionIdentifier]
(if (map? m-or-id)
(if (contains? m-or-id :webdriver-id)
(session-by-webdriver-url url-root (:webdriver-id m-or-id))
(session-url url-root (or (:session-id m-or-id) (:id m-or-id))))
(session-url url-root m-or-id)))
(defn sessions
([] (sessions default-url-root))
([url-root]
(let [response (try+
(client/get (sessions-url url-root))
(catch [:status 400] {:keys [body]} (error body) (throw+)))]
(json/parse-string (response :body)))))
(defn nodes
([] (nodes default-url-root))
([url-root]
(let [response (try+ (client/get (nodes-url url-root))
(catch [:status 400] {:keys [body]} (error body) (throw+)))]
(json/parse-string (response :body)))))
(defn proxies
([] (proxies default-url-root))
([url-root]
(let [response (try+ (client/get (proxies-url url-root))
(catch [:status 400] {:keys [body]}
(error body)
(throw+)))]
(json/parse-string (response :body)))))
(defn create-proxy!
([requirements] (create-proxy! default-url-root
requirements))
([url-root {:keys [proxy-type
host
port
public-ip
shared
active]
:or {proxy-type "socks5"
shared true
active true
public-ip nil}
:as requirements}]
(let [body (->> (rename-keys requirements
{:proxy-type :type})
(transform-keys ->snake_case_string))
response (try+
(client/post (proxies-url url-root)
{:body (json/generate-string body)
:content-type :json
:accept :json})
(catch [:status 400] {:keys [body]}
(error body)
(throw+)))]
(json/parse-string (response :body)))))
(defn modify-proxy!
([id options] (modify-proxy! default-url-root id options))
([url-root id {:keys [shared active]
:or {shared nil
active nil}
:as modifications}]
(let [url (proxy-url url-root id)
body (->> modifications
(filter #(not (nil? (val %))))
(into {})
(transform-keys ->snake_case_string))
response (try+
(client/patch url
{:body (json/generate-string body)
:content-type :json
:accept :json})
(catch [:status 400] {:keys [body]}
(error body)
(throw+)))]
(json/parse-string (response :body)))))
(defn session
([id] (session default-url-root id))
([url-root id]
(let [url (map->session-url url-root id)
response (client/get url)]
(json/parse-string (response :body)))))
(s/defn get-or-create-session!
([arg :- sessions/GetOrCreateArg]
(get-or-create-session! default-url-root arg))
([url-root :- s/Str
arg :- sessions/GetOrCreateArg]
(let [body (walk/postwalk
#(cond
(= % :socks5) "socks5"
(keyword? %) (->snake_case_string %)
:else %)
arg)
response (try+
(client/post (sessions-url url-root)
{:body (json/generate-string body)
:content-type :json
:accept :json})
(catch [:status 400] {:keys [body]} (error body) (throw+)))]
(json/parse-string (response :body)))))
(s/defn ^:always-validate modify-session!
([id :- SessionIdentifier
modifications :- [sessions/ModifyArg]]
(modify-session! default-url-root id modifications))
([url-root :- s/Str
id :- SessionIdentifier
modifications :- [sessions/ModifyArg]]
(let [url (map->session-url url-root id)
body (->> modifications
(map #(transform-keys ->snake_case_string %))
vec)
response (try+
(client/patch url
{:body (json/generate-string body)
:content-type :json
:accept :json})
(catch [:status 400] {:keys [body]}
(error body)
(throw+)))]
(json/parse-string (response :body)))))
(defn reserve-session!
([id] (reserve-session! default-url-root id))
([url-root id]
(modify-session! url-root id [[:reserve true]])))
(defn release-session!
([id] (release-session! default-url-root id))
([url-root id]
(modify-session! url-root id [[:reserve false]])))
(s/defn destroy-session!
([id] (destroy-session! default-url-root id))
([url-root
id]
(let [url (map->session-url url-root id)]
(client/delete url {:query-params {"immediately" "true"}}))
nil))
(defn destroy-sessions!
([] (destroy-sessions! default-url-root))
([url-root]
(client/delete (sessions-url url-root) {:query-params {"immediately" "true"}})
nil))
(defn refresh-sessions!
([] (refresh-sessions! default-url-root))
([url-root]
(let [response (try+
(client/post
(clojure.string/join "/"
[(sessions-url url-root) "refresh"])
{})
(catch [:status 400] {:keys [body]} (error body) (throw+)))]
(json/parse-string (response :body)))))
(s/defn get-or-create-webdriver!
([arg :- sessions/GetOrCreateArg]
(get-or-create-webdriver! default-url-root arg))
([url-root :- s/Str
arg :- sessions/GetOrCreateArg]
(let [session (get-or-create-session! url-root arg)]
(webdriver/resume-webdriver
(get session "webdriver_id")
(get-in session ["node" "url"])
{"platform" "ANY"
"browserName" (get session "browser_name")}))))
(defn release-webdriver!
([driver] (release-webdriver! default-url-root driver))
([url-root driver]
(if-let [session-id (session-id driver)]
(release-session! url-root {:webdriver-id session-id}))))
(defmacro with-webdriver*
"Given tags and a browser name to get or create a new webdriver session,
execute the forms in `body`, then unreserve the webdriver session.
Example :
========
;;
;; Log into Github
;;
(use 'clj-webdriver.taxi)
(with-webdriver* {:require [:and [[:browser-name :firefox]
[:tag \"github\"]]]}
(to \"https://github.com\")
(click \"a[href*='login']\")
(input-text \"#login_field\" \"your_username\")
(-> \"#password\"
(input-text \"<PASSWORD>_password\")
submit))"
[arg & body]
`(binding [~'clj-webdriver.taxi/*driver*
(get-or-create-webdriver! ~arg)]
(try
~@body
(finally
(release-webdriver! ~'clj-webdriver.taxi/*driver*)))))
| true | (ns shale.client
(:require [clojure.set :refer [rename-keys]]
[clojure.walk :as walk]
[clj-http.client :as client]
[cheshire [core :as json]]
[clj-webdriver.taxi :as taxi]
[slingshot.slingshot :refer [try+ throw+]]
[taoensso.timbre :as timbre :refer [error]]
[schema.core :as s]
[camel-snake-kebab.core :refer [->snake_case_string]]
[camel-snake-kebab.extras :refer [transform-keys]]
[shale.sessions :as sessions]
[shale.webdriver :as webdriver])
(:use [clj-webdriver.remote.driver :only [session-id]]
shale.utils))
(def default-url-root "http://localhost:5000")
(def ^:private sessions-url
(memoize
(fn [url-root]
(clojure.string/join "/" [url-root "sessions"]))))
(def ^:private nodes-url
(memoize
(fn [url-root]
(clojure.string/join "/" [url-root "nodes"]) )))
(def ^:private proxies-url
(memoize
(fn [url-root]
(clojure.string/join "/" [url-root "proxies"]) )))
(defn ^:private proxy-url [url-root id]
(clojure.string/join "/" [(proxies-url url-root) id]))
(defn ^:private node-url [url-root id]
(clojure.string/join "/" [(nodes-url url-root) id]))
(defn ^:private session-url [url-root id]
(clojure.string/join "/" [(sessions-url url-root) id]))
(defn ^:private session-by-webdriver-url [url-root webdriver-id]
(clojure.string/join "/" [(sessions-url url-root) "webdriver" webdriver-id]))
(s/defschema SessionIdentifier
(s/either
s/Str
{:id s/Str}
{:session-id s/Str}
{:webdriver-id s/Str}))
(s/defn ^:always-validate map->session-url
[url-root :- s/Str
m-or-id :- SessionIdentifier]
(if (map? m-or-id)
(if (contains? m-or-id :webdriver-id)
(session-by-webdriver-url url-root (:webdriver-id m-or-id))
(session-url url-root (or (:session-id m-or-id) (:id m-or-id))))
(session-url url-root m-or-id)))
(defn sessions
([] (sessions default-url-root))
([url-root]
(let [response (try+
(client/get (sessions-url url-root))
(catch [:status 400] {:keys [body]} (error body) (throw+)))]
(json/parse-string (response :body)))))
(defn nodes
([] (nodes default-url-root))
([url-root]
(let [response (try+ (client/get (nodes-url url-root))
(catch [:status 400] {:keys [body]} (error body) (throw+)))]
(json/parse-string (response :body)))))
(defn proxies
([] (proxies default-url-root))
([url-root]
(let [response (try+ (client/get (proxies-url url-root))
(catch [:status 400] {:keys [body]}
(error body)
(throw+)))]
(json/parse-string (response :body)))))
(defn create-proxy!
([requirements] (create-proxy! default-url-root
requirements))
([url-root {:keys [proxy-type
host
port
public-ip
shared
active]
:or {proxy-type "socks5"
shared true
active true
public-ip nil}
:as requirements}]
(let [body (->> (rename-keys requirements
{:proxy-type :type})
(transform-keys ->snake_case_string))
response (try+
(client/post (proxies-url url-root)
{:body (json/generate-string body)
:content-type :json
:accept :json})
(catch [:status 400] {:keys [body]}
(error body)
(throw+)))]
(json/parse-string (response :body)))))
(defn modify-proxy!
([id options] (modify-proxy! default-url-root id options))
([url-root id {:keys [shared active]
:or {shared nil
active nil}
:as modifications}]
(let [url (proxy-url url-root id)
body (->> modifications
(filter #(not (nil? (val %))))
(into {})
(transform-keys ->snake_case_string))
response (try+
(client/patch url
{:body (json/generate-string body)
:content-type :json
:accept :json})
(catch [:status 400] {:keys [body]}
(error body)
(throw+)))]
(json/parse-string (response :body)))))
(defn session
([id] (session default-url-root id))
([url-root id]
(let [url (map->session-url url-root id)
response (client/get url)]
(json/parse-string (response :body)))))
(s/defn get-or-create-session!
([arg :- sessions/GetOrCreateArg]
(get-or-create-session! default-url-root arg))
([url-root :- s/Str
arg :- sessions/GetOrCreateArg]
(let [body (walk/postwalk
#(cond
(= % :socks5) "socks5"
(keyword? %) (->snake_case_string %)
:else %)
arg)
response (try+
(client/post (sessions-url url-root)
{:body (json/generate-string body)
:content-type :json
:accept :json})
(catch [:status 400] {:keys [body]} (error body) (throw+)))]
(json/parse-string (response :body)))))
(s/defn ^:always-validate modify-session!
([id :- SessionIdentifier
modifications :- [sessions/ModifyArg]]
(modify-session! default-url-root id modifications))
([url-root :- s/Str
id :- SessionIdentifier
modifications :- [sessions/ModifyArg]]
(let [url (map->session-url url-root id)
body (->> modifications
(map #(transform-keys ->snake_case_string %))
vec)
response (try+
(client/patch url
{:body (json/generate-string body)
:content-type :json
:accept :json})
(catch [:status 400] {:keys [body]}
(error body)
(throw+)))]
(json/parse-string (response :body)))))
(defn reserve-session!
([id] (reserve-session! default-url-root id))
([url-root id]
(modify-session! url-root id [[:reserve true]])))
(defn release-session!
([id] (release-session! default-url-root id))
([url-root id]
(modify-session! url-root id [[:reserve false]])))
(s/defn destroy-session!
([id] (destroy-session! default-url-root id))
([url-root
id]
(let [url (map->session-url url-root id)]
(client/delete url {:query-params {"immediately" "true"}}))
nil))
(defn destroy-sessions!
([] (destroy-sessions! default-url-root))
([url-root]
(client/delete (sessions-url url-root) {:query-params {"immediately" "true"}})
nil))
(defn refresh-sessions!
([] (refresh-sessions! default-url-root))
([url-root]
(let [response (try+
(client/post
(clojure.string/join "/"
[(sessions-url url-root) "refresh"])
{})
(catch [:status 400] {:keys [body]} (error body) (throw+)))]
(json/parse-string (response :body)))))
(s/defn get-or-create-webdriver!
([arg :- sessions/GetOrCreateArg]
(get-or-create-webdriver! default-url-root arg))
([url-root :- s/Str
arg :- sessions/GetOrCreateArg]
(let [session (get-or-create-session! url-root arg)]
(webdriver/resume-webdriver
(get session "webdriver_id")
(get-in session ["node" "url"])
{"platform" "ANY"
"browserName" (get session "browser_name")}))))
(defn release-webdriver!
([driver] (release-webdriver! default-url-root driver))
([url-root driver]
(if-let [session-id (session-id driver)]
(release-session! url-root {:webdriver-id session-id}))))
(defmacro with-webdriver*
"Given tags and a browser name to get or create a new webdriver session,
execute the forms in `body`, then unreserve the webdriver session.
Example :
========
;;
;; Log into Github
;;
(use 'clj-webdriver.taxi)
(with-webdriver* {:require [:and [[:browser-name :firefox]
[:tag \"github\"]]]}
(to \"https://github.com\")
(click \"a[href*='login']\")
(input-text \"#login_field\" \"your_username\")
(-> \"#password\"
(input-text \"PI:PASSWORD:<PASSWORD>END_PI_password\")
submit))"
[arg & body]
`(binding [~'clj-webdriver.taxi/*driver*
(get-or-create-webdriver! ~arg)]
(try
~@body
(finally
(release-webdriver! ~'clj-webdriver.taxi/*driver*)))))
|
[
{
"context": "using the Java Prefernces\nsystem.\"\n :author \"Paul Landes\"}\n zensols.cisql.conf\n (:require [clojure.str",
"end": 113,
"score": 0.9998839497566223,
"start": 102,
"tag": "NAME",
"value": "Paul Landes"
},
{
"context": "a-inst (atom nil))\n\n(def ^:private parse-keys\n #{:errorlong :gui})\n\n(def ^:private help-message\n \"t",
"end": 1900,
"score": 0.6202082633972168,
"start": 1900,
"tag": "KEY",
"value": ""
},
{
"context": "-inst (atom nil))\n\n(def ^:private parse-keys\n #{:errorlong :gui})\n\n(def ^:private help-message\n \"type 'help",
"end": 1910,
"score": 0.712441623210907,
"start": 1901,
"tag": "KEY",
"value": "errorlong"
},
{
"context": " nil))\n\n(def ^:private parse-keys\n #{:errorlong :gui})\n\n(def ^:private help-message\n \"type 'help' to ",
"end": 1915,
"score": 0.7303723096847534,
"start": 1912,
"tag": "KEY",
"value": "gui"
},
{
"context": "\n (format \"Clojure Interactive SQL (cisql) %s\n(C) Paul Landes 2015 - 2021\"\n (format-version)))\n\n(defn ",
"end": 5837,
"score": 0.9998672008514404,
"start": 5826,
"tag": "NAME",
"value": "Paul Landes"
}
] | src/clojure/zensols/cisql/conf.clj | plandes/cisql | 12 | (ns ^{:doc "Manages application level configuration using the Java Prefernces
system."
:author "Paul Landes"}
zensols.cisql.conf
(:require [clojure.string :as str]
[clojure.tools.logging :as log]
[clojure.set :refer (difference)]
[zensols.cisql.version :as ver]
[zensols.cisql.pref :as pref]))
(def ^:private var-meta
[[:loglevel "info" "logging verbosity (<error|warn|info|debug|trace>)"]
[:catalog nil "set the catalog (resets connection)"]
[:schema nil "set the schema (resets connection)"]
[:strict true "if true, do not allow setting of free variables"
"built-in-and-user-variables"]
[:linesep ";" "tell where to end a query and then send"]
[:rowcount nil "the number of rows to display (all be default)" "row-count"]
[:errorlong false "if true, provide more SQL level error information"]
[:prex false "print exception stack traces"]
[:prompt " %1$s > " "a format string for the promp"
"variables"]
[:sigintercept true "if true, intercept and break on Control-C signals"]
[:gui false "use a graphical window to display result sets"
"graphical-results"]
[:guiheight 0 "the number of pixels to add to the height of the GUI window"]
[:guiwidth 0 "the number of pixels to add to the width of the GUI window"]
[:headless true "use separate window for GUI (require restart)"
"graphical-results"]])
(def ^:private default-config
(->> var-meta
(map #(array-map (first %) (second %)))
(apply merge)))
(def ^:private help-sections
(->> var-meta
(map #(array-map (first %) (if (> (count %) 3)
(nth % 3))))
(apply merge)))
(def ^:private system-properties
{:headless "apple.awt.UIElement"})
(def ^:private set-config-hooks (atom #{}))
(def ^:private config-data-inst (atom nil))
(def ^:private parse-keys
#{:errorlong :gui})
(def ^:private help-message
"type 'help' to see a list of commands")
(def ^:private our-ns *ns*)
(defn- update-system-properties [key value]
(let [k (get system-properties key)
k (if k (name k))
value (str value)]
(when k
(log/debugf "settings prop: %s -> %s" k value)
(System/setProperty k value))))
(defn add-set-config-hook [callback-fn]
(swap! set-config-hooks #(conj % callback-fn)))
(add-set-config-hook update-system-properties)
(defn- config-data []
(swap! config-data-inst
(fn [prefs]
(if (nil? prefs)
(let [prefs (pref/environment default-config)]
(doseq [[k v] prefs]
(doseq [callback @set-config-hooks]
((eval callback) k v)))
prefs)
prefs))))
(defn config
([]
(config nil))
([key & {:keys [expect?]
:or {expect? nil}}]
(if (nil? key)
(config-data)
(let [val (get (config-data) key)]
(if (and (nil? val) expect?)
(-> (format "no such variable: %s" (name key))
(ex-info {:key key})
throw))
val))))
(defn set-config
"Set variable with name **key** to **value** and save."
[key value]
(log/tracef "%s -> %s" key value)
(config)
(if (and @config-data-inst (config :strict)
(not (contains? default-config key)))
(-> (format "no such variable: %s" (name key))
(ex-info {:key key :value value})
throw))
(let [val (if (and (contains? parse-keys key)
(string? value))
(read-string value)
value)]
(swap! config-data-inst assoc key val)
(doseq [callback @set-config-hooks]
((eval callback) key value))
(pref/set-environment @config-data-inst)
(log/tracef "vars: %s" @config-data-inst)))
(defn remove-config
"Remove variable with name **key** and save."
[key]
(if (contains? default-config key)
(-> (format "can not delete built in variable: %s" key)
(ex-info {:key key})
throw))
(if (not (contains? (config) key))
(-> (format "no such user variable: %s" key)
(ex-info {:key key})
throw))
(swap! config-data-inst dissoc key)
(pref/set-environment @config-data-inst))
(defn- user-variable-names
"Return a list of the variable keys in user space."
[]
(->> (keys default-config)
set
(difference (set (keys (config))))))
(defn print-key-values
"Print state of variable key/value pairs as markdown."
[]
(let [conf (config)]
(letfn [(pr-conf [key]
(let [val (get conf key)
val (if (nil? val)
"<none>"
val)]
(println (format " * %s: %s" (name key) val))))]
(println "# Built in variables:")
(->> (map first var-meta)
(map pr-conf)
doall)
(println "# User variables:")
(->> (user-variable-names)
(map pr-conf)
doall))))
(defn print-key-desc
"Print variable names and documentation as markdown."
[space]
(let [space (or space 0)
space (->> (map first var-meta)
(map #(-> % name count))
(reduce max)
(max 0)
inc
(max space))
fmt (str " * %-" space "s %s")]
(->> var-meta
(map (fn [[k d v]]
(println (format fmt (str (name k)) v))))
doall)))
(defn help-section
"Return help section for the variable with **key** if there is one."
[key]
(get help-sections key))
(defn reset
"Reset **all** variable data to it's initial nascent state."
[]
(pref/clear :var 'environment)
(reset! config-data-inst nil)
(config))
(defn format-version []
(format "v%s " ver/version))
(defn format-intro []
(format "Clojure Interactive SQL (cisql) %s
(C) Paul Landes 2015 - 2021"
(format-version)))
(defn print-help []
(println (format-intro))
(println help-message))
| 5449 | (ns ^{:doc "Manages application level configuration using the Java Prefernces
system."
:author "<NAME>"}
zensols.cisql.conf
(:require [clojure.string :as str]
[clojure.tools.logging :as log]
[clojure.set :refer (difference)]
[zensols.cisql.version :as ver]
[zensols.cisql.pref :as pref]))
(def ^:private var-meta
[[:loglevel "info" "logging verbosity (<error|warn|info|debug|trace>)"]
[:catalog nil "set the catalog (resets connection)"]
[:schema nil "set the schema (resets connection)"]
[:strict true "if true, do not allow setting of free variables"
"built-in-and-user-variables"]
[:linesep ";" "tell where to end a query and then send"]
[:rowcount nil "the number of rows to display (all be default)" "row-count"]
[:errorlong false "if true, provide more SQL level error information"]
[:prex false "print exception stack traces"]
[:prompt " %1$s > " "a format string for the promp"
"variables"]
[:sigintercept true "if true, intercept and break on Control-C signals"]
[:gui false "use a graphical window to display result sets"
"graphical-results"]
[:guiheight 0 "the number of pixels to add to the height of the GUI window"]
[:guiwidth 0 "the number of pixels to add to the width of the GUI window"]
[:headless true "use separate window for GUI (require restart)"
"graphical-results"]])
(def ^:private default-config
(->> var-meta
(map #(array-map (first %) (second %)))
(apply merge)))
(def ^:private help-sections
(->> var-meta
(map #(array-map (first %) (if (> (count %) 3)
(nth % 3))))
(apply merge)))
(def ^:private system-properties
{:headless "apple.awt.UIElement"})
(def ^:private set-config-hooks (atom #{}))
(def ^:private config-data-inst (atom nil))
(def ^:private parse-keys
#{<KEY>:<KEY> :<KEY>})
(def ^:private help-message
"type 'help' to see a list of commands")
(def ^:private our-ns *ns*)
(defn- update-system-properties [key value]
(let [k (get system-properties key)
k (if k (name k))
value (str value)]
(when k
(log/debugf "settings prop: %s -> %s" k value)
(System/setProperty k value))))
(defn add-set-config-hook [callback-fn]
(swap! set-config-hooks #(conj % callback-fn)))
(add-set-config-hook update-system-properties)
(defn- config-data []
(swap! config-data-inst
(fn [prefs]
(if (nil? prefs)
(let [prefs (pref/environment default-config)]
(doseq [[k v] prefs]
(doseq [callback @set-config-hooks]
((eval callback) k v)))
prefs)
prefs))))
(defn config
([]
(config nil))
([key & {:keys [expect?]
:or {expect? nil}}]
(if (nil? key)
(config-data)
(let [val (get (config-data) key)]
(if (and (nil? val) expect?)
(-> (format "no such variable: %s" (name key))
(ex-info {:key key})
throw))
val))))
(defn set-config
"Set variable with name **key** to **value** and save."
[key value]
(log/tracef "%s -> %s" key value)
(config)
(if (and @config-data-inst (config :strict)
(not (contains? default-config key)))
(-> (format "no such variable: %s" (name key))
(ex-info {:key key :value value})
throw))
(let [val (if (and (contains? parse-keys key)
(string? value))
(read-string value)
value)]
(swap! config-data-inst assoc key val)
(doseq [callback @set-config-hooks]
((eval callback) key value))
(pref/set-environment @config-data-inst)
(log/tracef "vars: %s" @config-data-inst)))
(defn remove-config
"Remove variable with name **key** and save."
[key]
(if (contains? default-config key)
(-> (format "can not delete built in variable: %s" key)
(ex-info {:key key})
throw))
(if (not (contains? (config) key))
(-> (format "no such user variable: %s" key)
(ex-info {:key key})
throw))
(swap! config-data-inst dissoc key)
(pref/set-environment @config-data-inst))
(defn- user-variable-names
"Return a list of the variable keys in user space."
[]
(->> (keys default-config)
set
(difference (set (keys (config))))))
(defn print-key-values
"Print state of variable key/value pairs as markdown."
[]
(let [conf (config)]
(letfn [(pr-conf [key]
(let [val (get conf key)
val (if (nil? val)
"<none>"
val)]
(println (format " * %s: %s" (name key) val))))]
(println "# Built in variables:")
(->> (map first var-meta)
(map pr-conf)
doall)
(println "# User variables:")
(->> (user-variable-names)
(map pr-conf)
doall))))
(defn print-key-desc
"Print variable names and documentation as markdown."
[space]
(let [space (or space 0)
space (->> (map first var-meta)
(map #(-> % name count))
(reduce max)
(max 0)
inc
(max space))
fmt (str " * %-" space "s %s")]
(->> var-meta
(map (fn [[k d v]]
(println (format fmt (str (name k)) v))))
doall)))
(defn help-section
"Return help section for the variable with **key** if there is one."
[key]
(get help-sections key))
(defn reset
"Reset **all** variable data to it's initial nascent state."
[]
(pref/clear :var 'environment)
(reset! config-data-inst nil)
(config))
(defn format-version []
(format "v%s " ver/version))
(defn format-intro []
(format "Clojure Interactive SQL (cisql) %s
(C) <NAME> 2015 - 2021"
(format-version)))
(defn print-help []
(println (format-intro))
(println help-message))
| true | (ns ^{:doc "Manages application level configuration using the Java Prefernces
system."
:author "PI:NAME:<NAME>END_PI"}
zensols.cisql.conf
(:require [clojure.string :as str]
[clojure.tools.logging :as log]
[clojure.set :refer (difference)]
[zensols.cisql.version :as ver]
[zensols.cisql.pref :as pref]))
(def ^:private var-meta
[[:loglevel "info" "logging verbosity (<error|warn|info|debug|trace>)"]
[:catalog nil "set the catalog (resets connection)"]
[:schema nil "set the schema (resets connection)"]
[:strict true "if true, do not allow setting of free variables"
"built-in-and-user-variables"]
[:linesep ";" "tell where to end a query and then send"]
[:rowcount nil "the number of rows to display (all be default)" "row-count"]
[:errorlong false "if true, provide more SQL level error information"]
[:prex false "print exception stack traces"]
[:prompt " %1$s > " "a format string for the promp"
"variables"]
[:sigintercept true "if true, intercept and break on Control-C signals"]
[:gui false "use a graphical window to display result sets"
"graphical-results"]
[:guiheight 0 "the number of pixels to add to the height of the GUI window"]
[:guiwidth 0 "the number of pixels to add to the width of the GUI window"]
[:headless true "use separate window for GUI (require restart)"
"graphical-results"]])
(def ^:private default-config
(->> var-meta
(map #(array-map (first %) (second %)))
(apply merge)))
(def ^:private help-sections
(->> var-meta
(map #(array-map (first %) (if (> (count %) 3)
(nth % 3))))
(apply merge)))
(def ^:private system-properties
{:headless "apple.awt.UIElement"})
(def ^:private set-config-hooks (atom #{}))
(def ^:private config-data-inst (atom nil))
(def ^:private parse-keys
#{PI:KEY:<KEY>END_PI:PI:KEY:<KEY>END_PI :PI:KEY:<KEY>END_PI})
(def ^:private help-message
"type 'help' to see a list of commands")
(def ^:private our-ns *ns*)
(defn- update-system-properties [key value]
(let [k (get system-properties key)
k (if k (name k))
value (str value)]
(when k
(log/debugf "settings prop: %s -> %s" k value)
(System/setProperty k value))))
(defn add-set-config-hook [callback-fn]
(swap! set-config-hooks #(conj % callback-fn)))
(add-set-config-hook update-system-properties)
(defn- config-data []
(swap! config-data-inst
(fn [prefs]
(if (nil? prefs)
(let [prefs (pref/environment default-config)]
(doseq [[k v] prefs]
(doseq [callback @set-config-hooks]
((eval callback) k v)))
prefs)
prefs))))
(defn config
([]
(config nil))
([key & {:keys [expect?]
:or {expect? nil}}]
(if (nil? key)
(config-data)
(let [val (get (config-data) key)]
(if (and (nil? val) expect?)
(-> (format "no such variable: %s" (name key))
(ex-info {:key key})
throw))
val))))
(defn set-config
"Set variable with name **key** to **value** and save."
[key value]
(log/tracef "%s -> %s" key value)
(config)
(if (and @config-data-inst (config :strict)
(not (contains? default-config key)))
(-> (format "no such variable: %s" (name key))
(ex-info {:key key :value value})
throw))
(let [val (if (and (contains? parse-keys key)
(string? value))
(read-string value)
value)]
(swap! config-data-inst assoc key val)
(doseq [callback @set-config-hooks]
((eval callback) key value))
(pref/set-environment @config-data-inst)
(log/tracef "vars: %s" @config-data-inst)))
(defn remove-config
"Remove variable with name **key** and save."
[key]
(if (contains? default-config key)
(-> (format "can not delete built in variable: %s" key)
(ex-info {:key key})
throw))
(if (not (contains? (config) key))
(-> (format "no such user variable: %s" key)
(ex-info {:key key})
throw))
(swap! config-data-inst dissoc key)
(pref/set-environment @config-data-inst))
(defn- user-variable-names
"Return a list of the variable keys in user space."
[]
(->> (keys default-config)
set
(difference (set (keys (config))))))
(defn print-key-values
"Print state of variable key/value pairs as markdown."
[]
(let [conf (config)]
(letfn [(pr-conf [key]
(let [val (get conf key)
val (if (nil? val)
"<none>"
val)]
(println (format " * %s: %s" (name key) val))))]
(println "# Built in variables:")
(->> (map first var-meta)
(map pr-conf)
doall)
(println "# User variables:")
(->> (user-variable-names)
(map pr-conf)
doall))))
(defn print-key-desc
"Print variable names and documentation as markdown."
[space]
(let [space (or space 0)
space (->> (map first var-meta)
(map #(-> % name count))
(reduce max)
(max 0)
inc
(max space))
fmt (str " * %-" space "s %s")]
(->> var-meta
(map (fn [[k d v]]
(println (format fmt (str (name k)) v))))
doall)))
(defn help-section
"Return help section for the variable with **key** if there is one."
[key]
(get help-sections key))
(defn reset
"Reset **all** variable data to it's initial nascent state."
[]
(pref/clear :var 'environment)
(reset! config-data-inst nil)
(config))
(defn format-version []
(format "v%s " ver/version))
(defn format-intro []
(format "Clojure Interactive SQL (cisql) %s
(C) PI:NAME:<NAME>END_PI 2015 - 2021"
(format-version)))
(defn print-help []
(println (format-intro))
(println help-message))
|
[
{
"context": " :port 5672\n :username \"rabbit\"\n :password \"rabbit\"\n ",
"end": 760,
"score": 0.9927424192428589,
"start": 754,
"tag": "USERNAME",
"value": "rabbit"
},
{
"context": "name \"rabbit\"\n :password \"rabbit\"\n :channel-timeout 2000\n ",
"end": 804,
"score": 0.9993006587028503,
"start": 798,
"tag": "PASSWORD",
"value": "rabbit"
},
{
"context": "oint \"http://localhost:15672\"\n username \"test\"\n password \"test\"\n ha-policy-bo",
"end": 2198,
"score": 0.9978131651878357,
"start": 2194,
"tag": "USERNAME",
"value": "test"
},
{
"context": "72\"\n username \"test\"\n password \"test\"\n ha-policy-body {:foo \"bar\"}\n ",
"end": 2224,
"score": 0.9995585680007935,
"start": 2220,
"tag": "PASSWORD",
"value": "test"
},
{
"context": "oint \"http://localhost:15672\"\n username \"test\"\n password \"test\"\n ha-policy-bo",
"end": 3097,
"score": 0.9981662631034851,
"start": 3093,
"tag": "USERNAME",
"value": "test"
},
{
"context": "72\"\n username \"test\"\n password \"test\"\n ha-policy-body {:foo \"bar\"}\n ",
"end": 3123,
"score": 0.9995689988136292,
"start": 3119,
"tag": "PASSWORD",
"value": "test"
},
{
"context": " (= lh/*username* \"rabbit\")\n ",
"end": 6215,
"score": 0.9741514325141907,
"start": 6209,
"tag": "USERNAME",
"value": "rabbit"
},
{
"context": " (= lh/*username* \"rabbit\")\n ",
"end": 9112,
"score": 0.9994269609451294,
"start": 9106,
"tag": "USERNAME",
"value": "rabbit"
},
{
"context": " (= lh/*password* \"rabbit\")\n ",
"end": 9186,
"score": 0.9992631077766418,
"start": 9180,
"tag": "PASSWORD",
"value": "rabbit"
},
{
"context": " (= lh/*username* \"rabbit\")\n ",
"end": 11940,
"score": 0.9594285488128662,
"start": 11934,
"tag": "USERNAME",
"value": "rabbit"
},
{
"context": " (= lh/*password* \"rabbit\")\n ",
"end": 12014,
"score": 0.9994404911994934,
"start": 12008,
"tag": "PASSWORD",
"value": "rabbit"
}
] | test/ziggurat/messaging/rabbitmq/cluster/producer_test.clj | WickedBrat/ziggurat | 0 | (ns ziggurat.messaging.rabbitmq.cluster.producer-test
(:require [clojure.test :refer :all]
[ziggurat.messaging.rabbitmq.cluster.producer :as rmc-prod]
[langohr.queue :as lq]
[langohr.exchange :as le]
[langohr.channel :as lch]
[langohr.http :as lh]
[ziggurat.fixtures :as fix]
[clojure.string :as str])
(:import (com.rabbitmq.client Channel Connection)
(org.apache.kafka.common.header Header)))
(use-fixtures :once (join-fixtures [fix/mount-only-config
fix/silence-logging]))
(def rmq-cluster-config {:hosts "localhost-1,localhost-2,localhost-3"
:port 5672
:username "rabbit"
:password "rabbit"
:channel-timeout 2000
:ha-mode "all"
:ha-params 1
:ha-sync-mode "automatic"})
(def rmq-cluster-config-without-ha-config (dissoc rmq-cluster-config :ha-mode :ha-params :ha-sync-mode))
(defn- create-mock-channel [] (reify Channel
(close [_] nil)))
(deftest get-default-ha-policy-test
(testing "it should ignore `:ha-params` when `:ha-mode` is `all`"
(let [expected-ha-policy {:ha-mode "all" :ha-sync-mode "automatic"}
ha-policy (rmc-prod/get-default-ha-policy rmq-cluster-config (count (:hosts rmq-cluster-config)))]
(is (= ha-policy expected-ha-policy))))
(testing "it should use the `:ha-params` if specified when `:ha-mode` is `exactly`"
(let [expected-ha-policy {:ha-mode "exactly" :ha-sync-mode "automatic" :ha-params 1}
rmq-cluster-conf-with-ha-mode-exactly (assoc rmq-cluster-config :ha-mode "exactly")
ha-policy (rmc-prod/get-default-ha-policy rmq-cluster-conf-with-ha-mode-exactly (count (:hosts rmq-cluster-config)))]
(is (= ha-policy expected-ha-policy)))))
(deftest set-ha-policy-on-host-test
(testing "it should apply ha-policy on a host and return a non-nil response"
(let [host-endpoint "http://localhost:15672"
username "test"
password "test"
ha-policy-body {:foo "bar"}
exchange-name "test-exchange"
queue-name "test-queue"
ha-policy-name (str queue-name "_ha_policy")]
(with-redefs [lh/set-policy (fn [^String vhost ^String name policy]
(when (and (= vhost "/")
(= policy {:apply-to "all", :pattern "^test-queue|test-exchange$", :definition {:foo "bar"}})
(= name ha-policy-name))
{}))]
(is (not (nil? (rmc-prod/set-ha-policy-on-host host-endpoint username password ha-policy-body exchange-name queue-name)))))))
(testing "it should apply ha-policy on a host and return a nil response when an exception is thrown"
(let [host-endpoint "http://localhost:15672"
username "test"
password "test"
ha-policy-body {:foo "bar"}
exchange-name "test-exchange"
queue-name "test-queue"]
(with-redefs [lh/set-policy (fn [^String vhost ^String name policy]
(throw (Exception. "error applying ha policies")))]
(is (nil? (rmc-prod/set-ha-policy-on-host host-endpoint username password ha-policy-body exchange-name queue-name))))))
(testing "it should set ha-policies `hosts` number of times if an excpetion is thrown"
(let [call-count (atom 0)]
(with-redefs [lh/set-policy (fn [^String vhost ^String name policy]
(swap! call-count inc)
(throw (Exception. "error applying ha policies")))]
(rmc-prod/set-ha-policy "" "" {:hosts "localhost-1,localhost-2,localhost-3"})
(is (= @call-count 3))))))
(deftest create-and-bind-queue-test
(testing "it should create a queue,an exchange and bind the queue to the exchange but not tag the queue with a dead-letter exchange"
(let [default-props {:durable true :auto-delete false}
default-props-with-arguments (assoc default-props :arguments {})
exchange-type "fanout"
queue-name "test-queue"
exchange-name "test-exchange"
ha-policy-name (str queue-name "_ha_policy")
ha-policy-body {:apply-to "all"
:pattern (str "^" queue-name "|" exchange-name "$")
:definition {:ha-mode (:ha-mode rmq-cluster-config)
:ha-sync-mode (:ha-sync-mode rmq-cluster-config)}}
exchange-declare-called? (atom false)
queue-declare-called? (atom false)
bind-called? (atom false)
http-called? (atom false)]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String queue props]
(when (and (= props default-props-with-arguments)
(= queue-name queue))
(reset! queue-declare-called? true)))
le/declare (fn [^Channel _ ^String name ^String type props]
(when (and (= name exchange-name)
(= props default-props)
(= exchange-type type))
(reset! exchange-declare-called? true)))
lq/bind (fn [^Channel _ ^String queue ^String exchange]
(when (and (= queue queue-name)
(= exchange exchange-name))
(reset! bind-called? true)))
lh/set-policy (fn [^String vhost ^String name policy]
(when (and (= "/" vhost)
(= lh/*endpoint* "http://localhost-1:15672")
(= lh/*username* "rabbit")
(= lh/*password* "rabbit")
(= ha-policy-name name)
(= policy ha-policy-body))
(reset! http-called? true)))]
(rmc-prod/create-and-bind-queue rmq-cluster-config nil queue-name exchange-name nil))
(is (true? @bind-called?))
(is (true? @exchange-declare-called?))
(is (true? @http-called?))
(is (true? @queue-declare-called?))))
(testing "it should create a queue, an exchange, bind the queue to the exchange and tag it with dead-letter-exchange"
(let [default-props {:durable true :auto-delete false}
dead-letter-exchange-name "test-dead-letter-exchange"
queue-name "test-queue"
exchange-name "test-exchange"
exchange-type "fanout"
ha-policy-body {:apply-to "all"
:pattern (str "^" queue-name "|" exchange-name "$")
:definition {:ha-mode (:ha-mode rmq-cluster-config)
:ha-sync-mode (:ha-sync-mode rmq-cluster-config)}}
ha-policy-name (str queue-name "_ha_policy")
default-props-with-arguments (assoc default-props :arguments {"x-dead-letter-exchange" dead-letter-exchange-name})
exchange-declare-called? (atom false)
queue-declare-called? (atom false)
bind-called? (atom false)
http-called? (atom false)]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String queue props]
(when (and (= props default-props-with-arguments)
(= queue-name queue))
(reset! queue-declare-called? true)))
le/declare (fn [^Channel _ ^String name ^String type props]
(when (and (= name exchange-name)
(= props default-props)
(= type exchange-type))
(reset! exchange-declare-called? true)))
lq/bind (fn [^Channel _ ^String queue ^String exchange]
(when (and (= queue queue-name)
(= exchange exchange-name))
(reset! bind-called? true)))
lh/set-policy (fn [^String vhost ^String name policy]
(when (and (= "/" vhost)
(= ha-policy-name name)
(= lh/*endpoint* "http://localhost-1:15672")
(= lh/*username* "rabbit")
(= lh/*password* "rabbit")
(= policy ha-policy-body))
(reset! http-called? true)))]
(rmc-prod/create-and-bind-queue rmq-cluster-config nil queue-name exchange-name dead-letter-exchange-name))
(is (true? @bind-called?))
(is (true? @exchange-declare-called?))
(is (true? @http-called?))
(is (true? @queue-declare-called?))))
(testing "it should apply default ha-config when ha-config is not defined in the config"
(let [default-props {:durable true :auto-delete false}
dead-letter-exchange-name "test-dead-letter-exchange"
queue-name "test-queue"
exchange-name "test-exchange"
exchange-type "fanout"
ha-policy-body {:apply-to "all"
:pattern (str "^" queue-name "|" exchange-name "$")
:definition {:ha-mode "exactly"
:ha-sync-mode "automatic"
:ha-params 2}}
ha-policy-name (str queue-name "_ha_policy")
default-props-with-arguments (assoc default-props :arguments {"x-dead-letter-exchange" dead-letter-exchange-name})
exchange-declare-called? (atom false)
queue-declare-called? (atom false)
bind-called? (atom false)
http-called? (atom false)]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String queue props]
(when (and (= props default-props-with-arguments)
(= queue-name queue))
(reset! queue-declare-called? true)))
le/declare (fn [^Channel _ ^String name ^String type props]
(when (and (= name exchange-name)
(= props default-props)
(= type exchange-type))
(reset! exchange-declare-called? true)))
lq/bind (fn [^Channel _ ^String queue ^String exchange]
(when (and (= queue queue-name)
(= exchange exchange-name))
(reset! bind-called? true)))
lh/set-policy (fn [^String vhost ^String name policy]
(when (and (= "/" vhost)
(= ha-policy-name name)
(= lh/*endpoint* "http://localhost-1:15672")
(= lh/*username* "rabbit")
(= lh/*password* "rabbit")
(= policy ha-policy-body))
(reset! http-called? true)))]
(rmc-prod/create-and-bind-queue rmq-cluster-config-without-ha-config nil queue-name exchange-name dead-letter-exchange-name))
(is (true? @bind-called?))
(is (true? @exchange-declare-called?))
(is (true? @http-called?))
(is (true? @queue-declare-called?))))
(testing "it should catch an exception when create queue raises an exception"
(let [dead-letter-exchange-name "test-dead-letter-exchange"
queue-name "test-queue"
exchange-name "test-exchange"]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String _ _] (throw (Exception. "error creating a queue")))]
(is (thrown? Exception (rmc-prod/create-and-bind-queue rmq-cluster-config nil queue-name exchange-name dead-letter-exchange-name))))))
(testing "it should catch an exception when declare exchange raises an exception"
(let [dead-letter-exchange-name "test-dead-letter-exchange"
queue-name "test-queue"
exchange-name "test-exchange"]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String _ _] nil)
le/declare (fn [^Channel _ ^String name ^String type props]
(throw (Exception. "error declaring an exchange")))]
(is (thrown? Exception (rmc-prod/create-and-bind-queue rmq-cluster-config nil queue-name exchange-name dead-letter-exchange-name))))))
(testing "it should catch an exception when bind queue to exchange raises an exception"
(let [dead-letter-exchange-name "test-dead-letter-exchange"
queue-name "test-queue"
exchange-name "test-exchange"]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String _ _] nil)
le/declare (fn [^Channel _ ^String name ^String type props] nil)
lq/bind (fn [^Channel _ ^String queue ^String exchange] (throw (Exception. "error binding the queue to exchange")))]
(is (thrown? Exception (rmc-prod/create-and-bind-queue rmq-cluster-config nil queue-name exchange-name dead-letter-exchange-name)))))))
| 58632 | (ns ziggurat.messaging.rabbitmq.cluster.producer-test
(:require [clojure.test :refer :all]
[ziggurat.messaging.rabbitmq.cluster.producer :as rmc-prod]
[langohr.queue :as lq]
[langohr.exchange :as le]
[langohr.channel :as lch]
[langohr.http :as lh]
[ziggurat.fixtures :as fix]
[clojure.string :as str])
(:import (com.rabbitmq.client Channel Connection)
(org.apache.kafka.common.header Header)))
(use-fixtures :once (join-fixtures [fix/mount-only-config
fix/silence-logging]))
(def rmq-cluster-config {:hosts "localhost-1,localhost-2,localhost-3"
:port 5672
:username "rabbit"
:password "<PASSWORD>"
:channel-timeout 2000
:ha-mode "all"
:ha-params 1
:ha-sync-mode "automatic"})
(def rmq-cluster-config-without-ha-config (dissoc rmq-cluster-config :ha-mode :ha-params :ha-sync-mode))
(defn- create-mock-channel [] (reify Channel
(close [_] nil)))
(deftest get-default-ha-policy-test
(testing "it should ignore `:ha-params` when `:ha-mode` is `all`"
(let [expected-ha-policy {:ha-mode "all" :ha-sync-mode "automatic"}
ha-policy (rmc-prod/get-default-ha-policy rmq-cluster-config (count (:hosts rmq-cluster-config)))]
(is (= ha-policy expected-ha-policy))))
(testing "it should use the `:ha-params` if specified when `:ha-mode` is `exactly`"
(let [expected-ha-policy {:ha-mode "exactly" :ha-sync-mode "automatic" :ha-params 1}
rmq-cluster-conf-with-ha-mode-exactly (assoc rmq-cluster-config :ha-mode "exactly")
ha-policy (rmc-prod/get-default-ha-policy rmq-cluster-conf-with-ha-mode-exactly (count (:hosts rmq-cluster-config)))]
(is (= ha-policy expected-ha-policy)))))
(deftest set-ha-policy-on-host-test
(testing "it should apply ha-policy on a host and return a non-nil response"
(let [host-endpoint "http://localhost:15672"
username "test"
password "<PASSWORD>"
ha-policy-body {:foo "bar"}
exchange-name "test-exchange"
queue-name "test-queue"
ha-policy-name (str queue-name "_ha_policy")]
(with-redefs [lh/set-policy (fn [^String vhost ^String name policy]
(when (and (= vhost "/")
(= policy {:apply-to "all", :pattern "^test-queue|test-exchange$", :definition {:foo "bar"}})
(= name ha-policy-name))
{}))]
(is (not (nil? (rmc-prod/set-ha-policy-on-host host-endpoint username password ha-policy-body exchange-name queue-name)))))))
(testing "it should apply ha-policy on a host and return a nil response when an exception is thrown"
(let [host-endpoint "http://localhost:15672"
username "test"
password "<PASSWORD>"
ha-policy-body {:foo "bar"}
exchange-name "test-exchange"
queue-name "test-queue"]
(with-redefs [lh/set-policy (fn [^String vhost ^String name policy]
(throw (Exception. "error applying ha policies")))]
(is (nil? (rmc-prod/set-ha-policy-on-host host-endpoint username password ha-policy-body exchange-name queue-name))))))
(testing "it should set ha-policies `hosts` number of times if an excpetion is thrown"
(let [call-count (atom 0)]
(with-redefs [lh/set-policy (fn [^String vhost ^String name policy]
(swap! call-count inc)
(throw (Exception. "error applying ha policies")))]
(rmc-prod/set-ha-policy "" "" {:hosts "localhost-1,localhost-2,localhost-3"})
(is (= @call-count 3))))))
(deftest create-and-bind-queue-test
(testing "it should create a queue,an exchange and bind the queue to the exchange but not tag the queue with a dead-letter exchange"
(let [default-props {:durable true :auto-delete false}
default-props-with-arguments (assoc default-props :arguments {})
exchange-type "fanout"
queue-name "test-queue"
exchange-name "test-exchange"
ha-policy-name (str queue-name "_ha_policy")
ha-policy-body {:apply-to "all"
:pattern (str "^" queue-name "|" exchange-name "$")
:definition {:ha-mode (:ha-mode rmq-cluster-config)
:ha-sync-mode (:ha-sync-mode rmq-cluster-config)}}
exchange-declare-called? (atom false)
queue-declare-called? (atom false)
bind-called? (atom false)
http-called? (atom false)]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String queue props]
(when (and (= props default-props-with-arguments)
(= queue-name queue))
(reset! queue-declare-called? true)))
le/declare (fn [^Channel _ ^String name ^String type props]
(when (and (= name exchange-name)
(= props default-props)
(= exchange-type type))
(reset! exchange-declare-called? true)))
lq/bind (fn [^Channel _ ^String queue ^String exchange]
(when (and (= queue queue-name)
(= exchange exchange-name))
(reset! bind-called? true)))
lh/set-policy (fn [^String vhost ^String name policy]
(when (and (= "/" vhost)
(= lh/*endpoint* "http://localhost-1:15672")
(= lh/*username* "rabbit")
(= lh/*password* "rabbit")
(= ha-policy-name name)
(= policy ha-policy-body))
(reset! http-called? true)))]
(rmc-prod/create-and-bind-queue rmq-cluster-config nil queue-name exchange-name nil))
(is (true? @bind-called?))
(is (true? @exchange-declare-called?))
(is (true? @http-called?))
(is (true? @queue-declare-called?))))
(testing "it should create a queue, an exchange, bind the queue to the exchange and tag it with dead-letter-exchange"
(let [default-props {:durable true :auto-delete false}
dead-letter-exchange-name "test-dead-letter-exchange"
queue-name "test-queue"
exchange-name "test-exchange"
exchange-type "fanout"
ha-policy-body {:apply-to "all"
:pattern (str "^" queue-name "|" exchange-name "$")
:definition {:ha-mode (:ha-mode rmq-cluster-config)
:ha-sync-mode (:ha-sync-mode rmq-cluster-config)}}
ha-policy-name (str queue-name "_ha_policy")
default-props-with-arguments (assoc default-props :arguments {"x-dead-letter-exchange" dead-letter-exchange-name})
exchange-declare-called? (atom false)
queue-declare-called? (atom false)
bind-called? (atom false)
http-called? (atom false)]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String queue props]
(when (and (= props default-props-with-arguments)
(= queue-name queue))
(reset! queue-declare-called? true)))
le/declare (fn [^Channel _ ^String name ^String type props]
(when (and (= name exchange-name)
(= props default-props)
(= type exchange-type))
(reset! exchange-declare-called? true)))
lq/bind (fn [^Channel _ ^String queue ^String exchange]
(when (and (= queue queue-name)
(= exchange exchange-name))
(reset! bind-called? true)))
lh/set-policy (fn [^String vhost ^String name policy]
(when (and (= "/" vhost)
(= ha-policy-name name)
(= lh/*endpoint* "http://localhost-1:15672")
(= lh/*username* "rabbit")
(= lh/*password* "<PASSWORD>")
(= policy ha-policy-body))
(reset! http-called? true)))]
(rmc-prod/create-and-bind-queue rmq-cluster-config nil queue-name exchange-name dead-letter-exchange-name))
(is (true? @bind-called?))
(is (true? @exchange-declare-called?))
(is (true? @http-called?))
(is (true? @queue-declare-called?))))
(testing "it should apply default ha-config when ha-config is not defined in the config"
(let [default-props {:durable true :auto-delete false}
dead-letter-exchange-name "test-dead-letter-exchange"
queue-name "test-queue"
exchange-name "test-exchange"
exchange-type "fanout"
ha-policy-body {:apply-to "all"
:pattern (str "^" queue-name "|" exchange-name "$")
:definition {:ha-mode "exactly"
:ha-sync-mode "automatic"
:ha-params 2}}
ha-policy-name (str queue-name "_ha_policy")
default-props-with-arguments (assoc default-props :arguments {"x-dead-letter-exchange" dead-letter-exchange-name})
exchange-declare-called? (atom false)
queue-declare-called? (atom false)
bind-called? (atom false)
http-called? (atom false)]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String queue props]
(when (and (= props default-props-with-arguments)
(= queue-name queue))
(reset! queue-declare-called? true)))
le/declare (fn [^Channel _ ^String name ^String type props]
(when (and (= name exchange-name)
(= props default-props)
(= type exchange-type))
(reset! exchange-declare-called? true)))
lq/bind (fn [^Channel _ ^String queue ^String exchange]
(when (and (= queue queue-name)
(= exchange exchange-name))
(reset! bind-called? true)))
lh/set-policy (fn [^String vhost ^String name policy]
(when (and (= "/" vhost)
(= ha-policy-name name)
(= lh/*endpoint* "http://localhost-1:15672")
(= lh/*username* "rabbit")
(= lh/*password* "<PASSWORD>")
(= policy ha-policy-body))
(reset! http-called? true)))]
(rmc-prod/create-and-bind-queue rmq-cluster-config-without-ha-config nil queue-name exchange-name dead-letter-exchange-name))
(is (true? @bind-called?))
(is (true? @exchange-declare-called?))
(is (true? @http-called?))
(is (true? @queue-declare-called?))))
(testing "it should catch an exception when create queue raises an exception"
(let [dead-letter-exchange-name "test-dead-letter-exchange"
queue-name "test-queue"
exchange-name "test-exchange"]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String _ _] (throw (Exception. "error creating a queue")))]
(is (thrown? Exception (rmc-prod/create-and-bind-queue rmq-cluster-config nil queue-name exchange-name dead-letter-exchange-name))))))
(testing "it should catch an exception when declare exchange raises an exception"
(let [dead-letter-exchange-name "test-dead-letter-exchange"
queue-name "test-queue"
exchange-name "test-exchange"]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String _ _] nil)
le/declare (fn [^Channel _ ^String name ^String type props]
(throw (Exception. "error declaring an exchange")))]
(is (thrown? Exception (rmc-prod/create-and-bind-queue rmq-cluster-config nil queue-name exchange-name dead-letter-exchange-name))))))
(testing "it should catch an exception when bind queue to exchange raises an exception"
(let [dead-letter-exchange-name "test-dead-letter-exchange"
queue-name "test-queue"
exchange-name "test-exchange"]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String _ _] nil)
le/declare (fn [^Channel _ ^String name ^String type props] nil)
lq/bind (fn [^Channel _ ^String queue ^String exchange] (throw (Exception. "error binding the queue to exchange")))]
(is (thrown? Exception (rmc-prod/create-and-bind-queue rmq-cluster-config nil queue-name exchange-name dead-letter-exchange-name)))))))
| true | (ns ziggurat.messaging.rabbitmq.cluster.producer-test
(:require [clojure.test :refer :all]
[ziggurat.messaging.rabbitmq.cluster.producer :as rmc-prod]
[langohr.queue :as lq]
[langohr.exchange :as le]
[langohr.channel :as lch]
[langohr.http :as lh]
[ziggurat.fixtures :as fix]
[clojure.string :as str])
(:import (com.rabbitmq.client Channel Connection)
(org.apache.kafka.common.header Header)))
(use-fixtures :once (join-fixtures [fix/mount-only-config
fix/silence-logging]))
(def rmq-cluster-config {:hosts "localhost-1,localhost-2,localhost-3"
:port 5672
:username "rabbit"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:channel-timeout 2000
:ha-mode "all"
:ha-params 1
:ha-sync-mode "automatic"})
(def rmq-cluster-config-without-ha-config (dissoc rmq-cluster-config :ha-mode :ha-params :ha-sync-mode))
(defn- create-mock-channel [] (reify Channel
(close [_] nil)))
(deftest get-default-ha-policy-test
(testing "it should ignore `:ha-params` when `:ha-mode` is `all`"
(let [expected-ha-policy {:ha-mode "all" :ha-sync-mode "automatic"}
ha-policy (rmc-prod/get-default-ha-policy rmq-cluster-config (count (:hosts rmq-cluster-config)))]
(is (= ha-policy expected-ha-policy))))
(testing "it should use the `:ha-params` if specified when `:ha-mode` is `exactly`"
(let [expected-ha-policy {:ha-mode "exactly" :ha-sync-mode "automatic" :ha-params 1}
rmq-cluster-conf-with-ha-mode-exactly (assoc rmq-cluster-config :ha-mode "exactly")
ha-policy (rmc-prod/get-default-ha-policy rmq-cluster-conf-with-ha-mode-exactly (count (:hosts rmq-cluster-config)))]
(is (= ha-policy expected-ha-policy)))))
(deftest set-ha-policy-on-host-test
(testing "it should apply ha-policy on a host and return a non-nil response"
(let [host-endpoint "http://localhost:15672"
username "test"
password "PI:PASSWORD:<PASSWORD>END_PI"
ha-policy-body {:foo "bar"}
exchange-name "test-exchange"
queue-name "test-queue"
ha-policy-name (str queue-name "_ha_policy")]
(with-redefs [lh/set-policy (fn [^String vhost ^String name policy]
(when (and (= vhost "/")
(= policy {:apply-to "all", :pattern "^test-queue|test-exchange$", :definition {:foo "bar"}})
(= name ha-policy-name))
{}))]
(is (not (nil? (rmc-prod/set-ha-policy-on-host host-endpoint username password ha-policy-body exchange-name queue-name)))))))
(testing "it should apply ha-policy on a host and return a nil response when an exception is thrown"
(let [host-endpoint "http://localhost:15672"
username "test"
password "PI:PASSWORD:<PASSWORD>END_PI"
ha-policy-body {:foo "bar"}
exchange-name "test-exchange"
queue-name "test-queue"]
(with-redefs [lh/set-policy (fn [^String vhost ^String name policy]
(throw (Exception. "error applying ha policies")))]
(is (nil? (rmc-prod/set-ha-policy-on-host host-endpoint username password ha-policy-body exchange-name queue-name))))))
(testing "it should set ha-policies `hosts` number of times if an excpetion is thrown"
(let [call-count (atom 0)]
(with-redefs [lh/set-policy (fn [^String vhost ^String name policy]
(swap! call-count inc)
(throw (Exception. "error applying ha policies")))]
(rmc-prod/set-ha-policy "" "" {:hosts "localhost-1,localhost-2,localhost-3"})
(is (= @call-count 3))))))
(deftest create-and-bind-queue-test
(testing "it should create a queue,an exchange and bind the queue to the exchange but not tag the queue with a dead-letter exchange"
(let [default-props {:durable true :auto-delete false}
default-props-with-arguments (assoc default-props :arguments {})
exchange-type "fanout"
queue-name "test-queue"
exchange-name "test-exchange"
ha-policy-name (str queue-name "_ha_policy")
ha-policy-body {:apply-to "all"
:pattern (str "^" queue-name "|" exchange-name "$")
:definition {:ha-mode (:ha-mode rmq-cluster-config)
:ha-sync-mode (:ha-sync-mode rmq-cluster-config)}}
exchange-declare-called? (atom false)
queue-declare-called? (atom false)
bind-called? (atom false)
http-called? (atom false)]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String queue props]
(when (and (= props default-props-with-arguments)
(= queue-name queue))
(reset! queue-declare-called? true)))
le/declare (fn [^Channel _ ^String name ^String type props]
(when (and (= name exchange-name)
(= props default-props)
(= exchange-type type))
(reset! exchange-declare-called? true)))
lq/bind (fn [^Channel _ ^String queue ^String exchange]
(when (and (= queue queue-name)
(= exchange exchange-name))
(reset! bind-called? true)))
lh/set-policy (fn [^String vhost ^String name policy]
(when (and (= "/" vhost)
(= lh/*endpoint* "http://localhost-1:15672")
(= lh/*username* "rabbit")
(= lh/*password* "rabbit")
(= ha-policy-name name)
(= policy ha-policy-body))
(reset! http-called? true)))]
(rmc-prod/create-and-bind-queue rmq-cluster-config nil queue-name exchange-name nil))
(is (true? @bind-called?))
(is (true? @exchange-declare-called?))
(is (true? @http-called?))
(is (true? @queue-declare-called?))))
(testing "it should create a queue, an exchange, bind the queue to the exchange and tag it with dead-letter-exchange"
(let [default-props {:durable true :auto-delete false}
dead-letter-exchange-name "test-dead-letter-exchange"
queue-name "test-queue"
exchange-name "test-exchange"
exchange-type "fanout"
ha-policy-body {:apply-to "all"
:pattern (str "^" queue-name "|" exchange-name "$")
:definition {:ha-mode (:ha-mode rmq-cluster-config)
:ha-sync-mode (:ha-sync-mode rmq-cluster-config)}}
ha-policy-name (str queue-name "_ha_policy")
default-props-with-arguments (assoc default-props :arguments {"x-dead-letter-exchange" dead-letter-exchange-name})
exchange-declare-called? (atom false)
queue-declare-called? (atom false)
bind-called? (atom false)
http-called? (atom false)]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String queue props]
(when (and (= props default-props-with-arguments)
(= queue-name queue))
(reset! queue-declare-called? true)))
le/declare (fn [^Channel _ ^String name ^String type props]
(when (and (= name exchange-name)
(= props default-props)
(= type exchange-type))
(reset! exchange-declare-called? true)))
lq/bind (fn [^Channel _ ^String queue ^String exchange]
(when (and (= queue queue-name)
(= exchange exchange-name))
(reset! bind-called? true)))
lh/set-policy (fn [^String vhost ^String name policy]
(when (and (= "/" vhost)
(= ha-policy-name name)
(= lh/*endpoint* "http://localhost-1:15672")
(= lh/*username* "rabbit")
(= lh/*password* "PI:PASSWORD:<PASSWORD>END_PI")
(= policy ha-policy-body))
(reset! http-called? true)))]
(rmc-prod/create-and-bind-queue rmq-cluster-config nil queue-name exchange-name dead-letter-exchange-name))
(is (true? @bind-called?))
(is (true? @exchange-declare-called?))
(is (true? @http-called?))
(is (true? @queue-declare-called?))))
(testing "it should apply default ha-config when ha-config is not defined in the config"
(let [default-props {:durable true :auto-delete false}
dead-letter-exchange-name "test-dead-letter-exchange"
queue-name "test-queue"
exchange-name "test-exchange"
exchange-type "fanout"
ha-policy-body {:apply-to "all"
:pattern (str "^" queue-name "|" exchange-name "$")
:definition {:ha-mode "exactly"
:ha-sync-mode "automatic"
:ha-params 2}}
ha-policy-name (str queue-name "_ha_policy")
default-props-with-arguments (assoc default-props :arguments {"x-dead-letter-exchange" dead-letter-exchange-name})
exchange-declare-called? (atom false)
queue-declare-called? (atom false)
bind-called? (atom false)
http-called? (atom false)]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String queue props]
(when (and (= props default-props-with-arguments)
(= queue-name queue))
(reset! queue-declare-called? true)))
le/declare (fn [^Channel _ ^String name ^String type props]
(when (and (= name exchange-name)
(= props default-props)
(= type exchange-type))
(reset! exchange-declare-called? true)))
lq/bind (fn [^Channel _ ^String queue ^String exchange]
(when (and (= queue queue-name)
(= exchange exchange-name))
(reset! bind-called? true)))
lh/set-policy (fn [^String vhost ^String name policy]
(when (and (= "/" vhost)
(= ha-policy-name name)
(= lh/*endpoint* "http://localhost-1:15672")
(= lh/*username* "rabbit")
(= lh/*password* "PI:PASSWORD:<PASSWORD>END_PI")
(= policy ha-policy-body))
(reset! http-called? true)))]
(rmc-prod/create-and-bind-queue rmq-cluster-config-without-ha-config nil queue-name exchange-name dead-letter-exchange-name))
(is (true? @bind-called?))
(is (true? @exchange-declare-called?))
(is (true? @http-called?))
(is (true? @queue-declare-called?))))
(testing "it should catch an exception when create queue raises an exception"
(let [dead-letter-exchange-name "test-dead-letter-exchange"
queue-name "test-queue"
exchange-name "test-exchange"]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String _ _] (throw (Exception. "error creating a queue")))]
(is (thrown? Exception (rmc-prod/create-and-bind-queue rmq-cluster-config nil queue-name exchange-name dead-letter-exchange-name))))))
(testing "it should catch an exception when declare exchange raises an exception"
(let [dead-letter-exchange-name "test-dead-letter-exchange"
queue-name "test-queue"
exchange-name "test-exchange"]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String _ _] nil)
le/declare (fn [^Channel _ ^String name ^String type props]
(throw (Exception. "error declaring an exchange")))]
(is (thrown? Exception (rmc-prod/create-and-bind-queue rmq-cluster-config nil queue-name exchange-name dead-letter-exchange-name))))))
(testing "it should catch an exception when bind queue to exchange raises an exception"
(let [dead-letter-exchange-name "test-dead-letter-exchange"
queue-name "test-queue"
exchange-name "test-exchange"]
(with-redefs [lch/open (fn [^Connection _] (create-mock-channel))
lq/declare (fn [^Channel _ ^String _ _] nil)
le/declare (fn [^Channel _ ^String name ^String type props] nil)
lq/bind (fn [^Channel _ ^String queue ^String exchange] (throw (Exception. "error binding the queue to exchange")))]
(is (thrown? Exception (rmc-prod/create-and-bind-queue rmq-cluster-config nil queue-name exchange-name dead-letter-exchange-name)))))))
|
[
{
"context": " [middleware.utils.core :as u]))\n\n; TODO(Richo): Concatenating strings seems very inefficient\n\n(",
"end": 165,
"score": 0.9935930967330933,
"start": 160,
"tag": "NAME",
"value": "Richo"
}
] | middleware/server/src/middleware/compilation/codegen.cljc | GIRA/PhysicalBits | 2 | (ns middleware.compilation.codegen
(:refer-clojure :exclude [print])
(:require [clojure.string :as str]
[middleware.utils.core :as u]))
; TODO(Richo): Concatenating strings seems very inefficient
(defmulti print-node :__class__)
(defn print [node] (print-node node))
(defn print-optional-block [block]
(if (empty? (:statements block))
";"
(str " " (print-node block))))
(defn- remove-empty [& colls]
(remove empty? colls))
(defmethod print-node "UziProgramNode" [node]
(str/join (flatten
(interpose "\n\n"
(remove-empty
(interpose "\n" (map print-node (:imports node)))
(interpose "\n" (map print-node (:globals node)))
(interpose "\n" (map print-node (:primitives node)))
(interpose "\n\n" (map print-node (:scripts node))))))))
(defmethod print-node "UziPrimitiveDeclarationNode" [node]
(u/format "prim %1;"
(if (= (:alias node) (:name node))
(:alias node)
(u/format "%1 : %2"
(:alias node)
(:name node)))))
(defmethod print-node "UziImportNode" [node]
(u/format "import %1 from '%2'%3"
(:alias node)
(:path node)
(print-optional-block (:initializationBlock node))))
(defmethod print-node "UziVariableDeclarationNode" [node]
(if (:value node)
(u/format "var %1 = %2;"
(:name node)
(print-node (:value node)))
(u/format "var %1;"
(:name node))))
(defmethod print-node "UziNumberLiteralNode" [node]
(str (:value node)))
(defmethod print-node "UziPinLiteralNode" [node]
(str (:type node) (:number node)))
(defmethod print-node "UziTaskNode" [node]
(u/format "task %1()%2%3 %4"
(:name node)
(if (= "once" (:state node)) "" (str " " (:state node)))
(if (nil? (:tickingRate node)) "" (print-node (:tickingRate node)))
(print-node (:body node))))
(defmethod print-node "UziFunctionNode" [node]
(u/format "func %1(%2) %3"
(:name node)
(str/join ", " (map :name (:arguments node)))
(print-node (:body node))))
(defmethod print-node "UziProcedureNode" [node]
(u/format "proc %1(%2) %3"
(:name node)
(str/join ", " (map :name (:arguments node)))
(print-node (:body node))))
(defmethod print-node "UziTickingRateNode" [node]
(u/format " %1/%2" (:value node) (:scale node)))
(defn add-indent-level [lines]
(str/join (map (fn [line] (str "\t" line "\n"))
(filter (fn [line] (and (not= "\n" line)
(not= "" line)))
(str/split-lines lines)))))
(defmethod print-node "UziBlockNode" [node]
(if (empty? (:statements node))
"{}"
(u/format "{\n%1}"
(add-indent-level
(str/join "\n"
(map (fn [expr]
(if (or (str/ends-with? expr "}")
(str/ends-with? expr ";"))
expr
(str expr ";")))
(map print-node (:statements node))))))))
(defn print-operator-expression [node]
(if (= 1 (-> node :arguments count))
;unary
(u/format "(%1%2)"
(:selector node)
(print-node (first (:arguments node))))
;binary
(u/format "(%1 %2 %3)"
(print-node (first (:arguments node)))
(:selector node)
(print-node (second (:arguments node))))))
(defmethod print-node "UziCallNode" [node]
(if (nil? (re-matches #"[^a-zA-Z0-9\s\[\]\(\)\{\}\"\':#_;,]+"
(:selector node)))
;non-operator
(u/format "%1(%2)"
(:selector node)
(str/join ", " (map print-node (:arguments node))))
(print-operator-expression node)))
(defmethod print-node "Association" [node]
(str (if (nil? (:key node)) "" (str (:key node) ": "))
(print-node (:value node))))
(defmethod print-node "UziVariableNode" [node] (:name node))
(defmethod print-node "UziReturnNode" [node]
(if (nil? (:value node))
"return"
(u/format "return %1" (print-node (:value node)))))
(defmethod print-node "UziYieldNode" [node] "yield")
(defmethod print-node "UziForNode" [node]
(u/format "for %1 = %2 to %3 by %4 %5"
(:name (:counter node))
(print-node (:start node))
(print-node (:stop node))
(print-node (:step node))
(print-node (:body node))))
(defmethod print-node "UziWhileNode" [node]
(u/format "while %1%2"
(print-node (:condition node))
(print-optional-block (:post node))))
(defmethod print-node "UziDoWhileNode" [node]
(u/format "do %1 while(%2)"
(print-node (:pre node))
(print-node (:condition node))))
(defmethod print-node "UziUntilNode" [node]
(u/format "until %1%2"
(print-node (:condition node))
(print-optional-block (:post node))))
(defmethod print-node "UziDoUntilNode" [node]
(u/format "do %1 until(%2)"
(print-node (:pre node))
(print-node (:condition node))))
(defmethod print-node "UziForeverNode" [node]
(u/format "forever %1"
(print-node (:body node))))
(defmethod print-node "UziRepeatNode" [node]
(u/format "repeat %1 %2"
(print-node (:times node))
(print-node (:body node))))
(defmethod print-node "UziConditionalNode" [node]
(let [trueBranch (u/format "if %1 %2"
(print-node (:condition node))
(print-node (:trueBranch node)))]
(if (empty? (-> node :falseBranch :statements))
trueBranch
(str trueBranch " else " (print-node (:falseBranch node))))))
(defmethod print-node "UziAssignmentNode" [node]
(u/format "%1 = %2"
(print-node (:left node))
(print-node (:right node))))
(defmethod print-node "UziScriptStartNode" [node]
(u/format "start %1"
(str/join ", " (:scripts node))))
(defmethod print-node "UziScriptStopNode" [node]
(u/format "stop %1"
(str/join ", " (:scripts node))))
(defmethod print-node "UziScriptPauseNode" [node]
(u/format "pause %1"
(str/join ", " (:scripts node))))
(defmethod print-node "UziScriptResumeNode" [node]
(u/format "resume %1"
(str/join ", " (:scripts node))))
(defmethod print-node "UziLogicalAndNode" [node]
(u/format "(%1 && %2)"
(print-node (:left node))
(print-node (:right node))))
(defmethod print-node "UziLogicalOrNode" [node]
(u/format "(%1 || %2)"
(print-node (:left node))
(print-node (:right node))))
(defmethod print-node :default [node]
(throw (ex-info "Not Implemented node reached: " {:node node})))
| 357 | (ns middleware.compilation.codegen
(:refer-clojure :exclude [print])
(:require [clojure.string :as str]
[middleware.utils.core :as u]))
; TODO(<NAME>): Concatenating strings seems very inefficient
(defmulti print-node :__class__)
(defn print [node] (print-node node))
(defn print-optional-block [block]
(if (empty? (:statements block))
";"
(str " " (print-node block))))
(defn- remove-empty [& colls]
(remove empty? colls))
(defmethod print-node "UziProgramNode" [node]
(str/join (flatten
(interpose "\n\n"
(remove-empty
(interpose "\n" (map print-node (:imports node)))
(interpose "\n" (map print-node (:globals node)))
(interpose "\n" (map print-node (:primitives node)))
(interpose "\n\n" (map print-node (:scripts node))))))))
(defmethod print-node "UziPrimitiveDeclarationNode" [node]
(u/format "prim %1;"
(if (= (:alias node) (:name node))
(:alias node)
(u/format "%1 : %2"
(:alias node)
(:name node)))))
(defmethod print-node "UziImportNode" [node]
(u/format "import %1 from '%2'%3"
(:alias node)
(:path node)
(print-optional-block (:initializationBlock node))))
(defmethod print-node "UziVariableDeclarationNode" [node]
(if (:value node)
(u/format "var %1 = %2;"
(:name node)
(print-node (:value node)))
(u/format "var %1;"
(:name node))))
(defmethod print-node "UziNumberLiteralNode" [node]
(str (:value node)))
(defmethod print-node "UziPinLiteralNode" [node]
(str (:type node) (:number node)))
(defmethod print-node "UziTaskNode" [node]
(u/format "task %1()%2%3 %4"
(:name node)
(if (= "once" (:state node)) "" (str " " (:state node)))
(if (nil? (:tickingRate node)) "" (print-node (:tickingRate node)))
(print-node (:body node))))
(defmethod print-node "UziFunctionNode" [node]
(u/format "func %1(%2) %3"
(:name node)
(str/join ", " (map :name (:arguments node)))
(print-node (:body node))))
(defmethod print-node "UziProcedureNode" [node]
(u/format "proc %1(%2) %3"
(:name node)
(str/join ", " (map :name (:arguments node)))
(print-node (:body node))))
(defmethod print-node "UziTickingRateNode" [node]
(u/format " %1/%2" (:value node) (:scale node)))
(defn add-indent-level [lines]
(str/join (map (fn [line] (str "\t" line "\n"))
(filter (fn [line] (and (not= "\n" line)
(not= "" line)))
(str/split-lines lines)))))
(defmethod print-node "UziBlockNode" [node]
(if (empty? (:statements node))
"{}"
(u/format "{\n%1}"
(add-indent-level
(str/join "\n"
(map (fn [expr]
(if (or (str/ends-with? expr "}")
(str/ends-with? expr ";"))
expr
(str expr ";")))
(map print-node (:statements node))))))))
(defn print-operator-expression [node]
(if (= 1 (-> node :arguments count))
;unary
(u/format "(%1%2)"
(:selector node)
(print-node (first (:arguments node))))
;binary
(u/format "(%1 %2 %3)"
(print-node (first (:arguments node)))
(:selector node)
(print-node (second (:arguments node))))))
(defmethod print-node "UziCallNode" [node]
(if (nil? (re-matches #"[^a-zA-Z0-9\s\[\]\(\)\{\}\"\':#_;,]+"
(:selector node)))
;non-operator
(u/format "%1(%2)"
(:selector node)
(str/join ", " (map print-node (:arguments node))))
(print-operator-expression node)))
(defmethod print-node "Association" [node]
(str (if (nil? (:key node)) "" (str (:key node) ": "))
(print-node (:value node))))
(defmethod print-node "UziVariableNode" [node] (:name node))
(defmethod print-node "UziReturnNode" [node]
(if (nil? (:value node))
"return"
(u/format "return %1" (print-node (:value node)))))
(defmethod print-node "UziYieldNode" [node] "yield")
(defmethod print-node "UziForNode" [node]
(u/format "for %1 = %2 to %3 by %4 %5"
(:name (:counter node))
(print-node (:start node))
(print-node (:stop node))
(print-node (:step node))
(print-node (:body node))))
(defmethod print-node "UziWhileNode" [node]
(u/format "while %1%2"
(print-node (:condition node))
(print-optional-block (:post node))))
(defmethod print-node "UziDoWhileNode" [node]
(u/format "do %1 while(%2)"
(print-node (:pre node))
(print-node (:condition node))))
(defmethod print-node "UziUntilNode" [node]
(u/format "until %1%2"
(print-node (:condition node))
(print-optional-block (:post node))))
(defmethod print-node "UziDoUntilNode" [node]
(u/format "do %1 until(%2)"
(print-node (:pre node))
(print-node (:condition node))))
(defmethod print-node "UziForeverNode" [node]
(u/format "forever %1"
(print-node (:body node))))
(defmethod print-node "UziRepeatNode" [node]
(u/format "repeat %1 %2"
(print-node (:times node))
(print-node (:body node))))
(defmethod print-node "UziConditionalNode" [node]
(let [trueBranch (u/format "if %1 %2"
(print-node (:condition node))
(print-node (:trueBranch node)))]
(if (empty? (-> node :falseBranch :statements))
trueBranch
(str trueBranch " else " (print-node (:falseBranch node))))))
(defmethod print-node "UziAssignmentNode" [node]
(u/format "%1 = %2"
(print-node (:left node))
(print-node (:right node))))
(defmethod print-node "UziScriptStartNode" [node]
(u/format "start %1"
(str/join ", " (:scripts node))))
(defmethod print-node "UziScriptStopNode" [node]
(u/format "stop %1"
(str/join ", " (:scripts node))))
(defmethod print-node "UziScriptPauseNode" [node]
(u/format "pause %1"
(str/join ", " (:scripts node))))
(defmethod print-node "UziScriptResumeNode" [node]
(u/format "resume %1"
(str/join ", " (:scripts node))))
(defmethod print-node "UziLogicalAndNode" [node]
(u/format "(%1 && %2)"
(print-node (:left node))
(print-node (:right node))))
(defmethod print-node "UziLogicalOrNode" [node]
(u/format "(%1 || %2)"
(print-node (:left node))
(print-node (:right node))))
(defmethod print-node :default [node]
(throw (ex-info "Not Implemented node reached: " {:node node})))
| true | (ns middleware.compilation.codegen
(:refer-clojure :exclude [print])
(:require [clojure.string :as str]
[middleware.utils.core :as u]))
; TODO(PI:NAME:<NAME>END_PI): Concatenating strings seems very inefficient
(defmulti print-node :__class__)
(defn print [node] (print-node node))
(defn print-optional-block [block]
(if (empty? (:statements block))
";"
(str " " (print-node block))))
(defn- remove-empty [& colls]
(remove empty? colls))
(defmethod print-node "UziProgramNode" [node]
(str/join (flatten
(interpose "\n\n"
(remove-empty
(interpose "\n" (map print-node (:imports node)))
(interpose "\n" (map print-node (:globals node)))
(interpose "\n" (map print-node (:primitives node)))
(interpose "\n\n" (map print-node (:scripts node))))))))
(defmethod print-node "UziPrimitiveDeclarationNode" [node]
(u/format "prim %1;"
(if (= (:alias node) (:name node))
(:alias node)
(u/format "%1 : %2"
(:alias node)
(:name node)))))
(defmethod print-node "UziImportNode" [node]
(u/format "import %1 from '%2'%3"
(:alias node)
(:path node)
(print-optional-block (:initializationBlock node))))
(defmethod print-node "UziVariableDeclarationNode" [node]
(if (:value node)
(u/format "var %1 = %2;"
(:name node)
(print-node (:value node)))
(u/format "var %1;"
(:name node))))
(defmethod print-node "UziNumberLiteralNode" [node]
(str (:value node)))
(defmethod print-node "UziPinLiteralNode" [node]
(str (:type node) (:number node)))
(defmethod print-node "UziTaskNode" [node]
(u/format "task %1()%2%3 %4"
(:name node)
(if (= "once" (:state node)) "" (str " " (:state node)))
(if (nil? (:tickingRate node)) "" (print-node (:tickingRate node)))
(print-node (:body node))))
(defmethod print-node "UziFunctionNode" [node]
(u/format "func %1(%2) %3"
(:name node)
(str/join ", " (map :name (:arguments node)))
(print-node (:body node))))
(defmethod print-node "UziProcedureNode" [node]
(u/format "proc %1(%2) %3"
(:name node)
(str/join ", " (map :name (:arguments node)))
(print-node (:body node))))
(defmethod print-node "UziTickingRateNode" [node]
(u/format " %1/%2" (:value node) (:scale node)))
(defn add-indent-level [lines]
(str/join (map (fn [line] (str "\t" line "\n"))
(filter (fn [line] (and (not= "\n" line)
(not= "" line)))
(str/split-lines lines)))))
(defmethod print-node "UziBlockNode" [node]
(if (empty? (:statements node))
"{}"
(u/format "{\n%1}"
(add-indent-level
(str/join "\n"
(map (fn [expr]
(if (or (str/ends-with? expr "}")
(str/ends-with? expr ";"))
expr
(str expr ";")))
(map print-node (:statements node))))))))
(defn print-operator-expression [node]
(if (= 1 (-> node :arguments count))
;unary
(u/format "(%1%2)"
(:selector node)
(print-node (first (:arguments node))))
;binary
(u/format "(%1 %2 %3)"
(print-node (first (:arguments node)))
(:selector node)
(print-node (second (:arguments node))))))
(defmethod print-node "UziCallNode" [node]
(if (nil? (re-matches #"[^a-zA-Z0-9\s\[\]\(\)\{\}\"\':#_;,]+"
(:selector node)))
;non-operator
(u/format "%1(%2)"
(:selector node)
(str/join ", " (map print-node (:arguments node))))
(print-operator-expression node)))
(defmethod print-node "Association" [node]
(str (if (nil? (:key node)) "" (str (:key node) ": "))
(print-node (:value node))))
(defmethod print-node "UziVariableNode" [node] (:name node))
(defmethod print-node "UziReturnNode" [node]
(if (nil? (:value node))
"return"
(u/format "return %1" (print-node (:value node)))))
(defmethod print-node "UziYieldNode" [node] "yield")
(defmethod print-node "UziForNode" [node]
(u/format "for %1 = %2 to %3 by %4 %5"
(:name (:counter node))
(print-node (:start node))
(print-node (:stop node))
(print-node (:step node))
(print-node (:body node))))
(defmethod print-node "UziWhileNode" [node]
(u/format "while %1%2"
(print-node (:condition node))
(print-optional-block (:post node))))
(defmethod print-node "UziDoWhileNode" [node]
(u/format "do %1 while(%2)"
(print-node (:pre node))
(print-node (:condition node))))
(defmethod print-node "UziUntilNode" [node]
(u/format "until %1%2"
(print-node (:condition node))
(print-optional-block (:post node))))
(defmethod print-node "UziDoUntilNode" [node]
(u/format "do %1 until(%2)"
(print-node (:pre node))
(print-node (:condition node))))
(defmethod print-node "UziForeverNode" [node]
(u/format "forever %1"
(print-node (:body node))))
(defmethod print-node "UziRepeatNode" [node]
(u/format "repeat %1 %2"
(print-node (:times node))
(print-node (:body node))))
(defmethod print-node "UziConditionalNode" [node]
(let [trueBranch (u/format "if %1 %2"
(print-node (:condition node))
(print-node (:trueBranch node)))]
(if (empty? (-> node :falseBranch :statements))
trueBranch
(str trueBranch " else " (print-node (:falseBranch node))))))
(defmethod print-node "UziAssignmentNode" [node]
(u/format "%1 = %2"
(print-node (:left node))
(print-node (:right node))))
(defmethod print-node "UziScriptStartNode" [node]
(u/format "start %1"
(str/join ", " (:scripts node))))
(defmethod print-node "UziScriptStopNode" [node]
(u/format "stop %1"
(str/join ", " (:scripts node))))
(defmethod print-node "UziScriptPauseNode" [node]
(u/format "pause %1"
(str/join ", " (:scripts node))))
(defmethod print-node "UziScriptResumeNode" [node]
(u/format "resume %1"
(str/join ", " (:scripts node))))
(defmethod print-node "UziLogicalAndNode" [node]
(u/format "(%1 && %2)"
(print-node (:left node))
(print-node (:right node))))
(defmethod print-node "UziLogicalOrNode" [node]
(u/format "(%1 || %2)"
(print-node (:left node))
(print-node (:right node))))
(defmethod print-node :default [node]
(throw (ex-info "Not Implemented node reached: " {:node node})))
|
[
{
"context": "einingen.core.main :as lein]\n [robert.hooke :as hooke])\n (:import (com.jcraft.jsch JSch Se",
"end": 306,
"score": 0.44888558983802795,
"start": 304,
"tag": "NAME",
"value": "oo"
},
{
"context": "]\n (if (= key \"IdentityFile\")\n (into-arr",
"end": 4587,
"score": 0.9741489291191101,
"start": 4575,
"tag": "KEY",
"value": "IdentityFile"
}
] | src/lein_git_down/impl/git.clj | Folcon/lein-git-down | 73 | (ns lein-git-down.impl.git
(:refer-clojure :exclude [resolve])
(:require [clojure.java.io :as io]
[clojure.string :as string]
[clojure.tools.gitlibs :as git]
[clojure.tools.gitlibs.impl :as git-impl]
[leiningen.core.main :as lein]
[robert.hooke :as hooke])
(:import (com.jcraft.jsch JSch Session UserInfo ConfigRepository ConfigRepository$Config KeyPair)
(com.jcraft.jsch.agentproxy ConnectorFactory RemoteIdentityRepository)
(org.eclipse.jgit.api TransportConfigCallback Git)
(org.eclipse.jgit.transport SshTransport JschConfigSessionFactory OpenSshConfig)
(java.io File)))
;; This namespace provides patched `procure` & `resolve` functions that fix
;; issues in JGit's implementation of JSCH. The first is a problem that causes
;; failure if using an encrypted (password protected) SSH key to connect to a
;; private repository. There is a [patch](https://dev.clojure.org/jira/browse/TDEPS-49)
;; submitted to gitlibs for this. The second is how JSCH handles keys in an
;; unsupported format. Without the patch it will fail at the first key it
;; encounters that it does not recognize, which is undesirable as the user
;; may have another key configured that will work. The patched impl below
;; will print a warn message and move on to the next key.
(def ^:dynamic *monkeypatch-tools-gitlibs* true)
(defn valid-key?
[jsch v]
(try
(KeyPair/load ^JSch jsch v)
true
(catch Throwable e
(let [m (if (.startsWith (.getMessage e) "invalid privatekey")
"The private key file is in an unsupported format."
(.getMessage e))]
(lein/warn "Exception processing private key," v ":"
m "Skipping..."))
false)))
(defn get-unsupported-algorithms
[^Session session k]
(into #{}
(filter #(nil? (JSch/getConfig %)))
(some-> (.getConfig session k) (string/split #","))))
(defn check-algorithms
"Jsch fails with an NPE when an unsupported algorithm is configured in the
ssh config file. This provides the user with more helpful information as to
the cause of the error."
[^Session session]
(let [kex (get-unsupported-algorithms session "kex")
cph (get-unsupported-algorithms session "cipher.c2s")
mac (get-unsupported-algorithms session "mac.c2s")
msg (str "Detected unsupported algorithm(s) configured for the '%s' "
"property in ssh config: %s")]
(when (not-empty kex) (lein/warn (format msg "KexAlgorithms" kex)))
(when (not-empty cph) (lein/warn (format msg "Ciphers" cph)))
(when (not-empty mac) (lein/warn (format msg "MACs" mac)))))
(def ssh-callback
(delay
(let [factory (doto (ConnectorFactory/getDefault)
(.setPreferredUSocketFactories "jna,nc"))
connector (.createConnector factory)]
(JSch/setConfig "PreferredAuthentications" "publickey")
(reify TransportConfigCallback
(configure [_ transport]
(.setSshSessionFactory
^SshTransport transport
(proxy [JschConfigSessionFactory] []
(configure [_host session]
(check-algorithms session)
(.setUserInfo
^Session session
(proxy [UserInfo] []
(getPassword [])
(promptYesNo [_] true)
(getPassphrase [])
(promptPassphrase [_] true)
(promptPassword [_] true)
(showMessage [_]))))
(getJSch [_hc fs]
(let [jsch (proxy-super createDefaultJSch fs)]
(doto jsch
(.setIdentityRepository
(RemoteIdentityRepository. connector))
(.setConfigRepository
(let [osc (OpenSshConfig/get fs)]
(proxy [ConfigRepository] []
(getConfig [host-name]
(let [oscc (.getConfig osc host-name)]
(proxy [ConfigRepository$Config] []
(getHostname [] (.getHostname oscc))
(getUser [] (.getUser oscc))
(getPort [] (.getPort oscc))
(getValue [key] (.getValue oscc key))
(getValues [key]
(let [vs (.getValues oscc key)]
(if (= key "IdentityFile")
(into-array String
(filter (partial valid-key? jsch) vs))
vs)))))))))))))))))))
(defn dev-null-hook
[_ & _])
(defn procure
"Monkey patches gitlibs/procure to resolve some JSCH issues unless explicitly
told not to. Writes a meta-data file with information about the source."
[uri mvn-coords rev]
(hooke/with-scope
(hooke/add-hook #'git-impl/printerrln #'dev-null-hook)
(let [path (if *monkeypatch-tools-gitlibs*
(with-redefs [git-impl/ssh-callback ssh-callback]
(git/procure uri mvn-coords rev))
(git/procure uri mvn-coords rev))
meta (io/file path ".lein-git-down")]
(when-not (.exists meta)
(spit meta {:uri uri :mvn-coords mvn-coords :rev rev}))
path)))
(defn resolve
"Monkey patches gitlibs/resolve to resolve some JSCH issues unless explicitly
told not to."
[uri version]
(hooke/with-scope
(hooke/add-hook #'git-impl/printerrln #'dev-null-hook)
(if *monkeypatch-tools-gitlibs*
(with-redefs [git-impl/ssh-callback ssh-callback]
(git/resolve uri version))
(git/resolve uri version))))
(defn init
"Initializes a fresh git repository at `project-dir` and sets HEAD to the
provided rev, which allows tooling to retrieve the correct HEAD commit in
the gitlibs repo directory. Returns the .git directory."
[^File project-dir rev]
(let [git-dir (.. (Git/init)
(setDirectory project-dir)
call
getRepository
getDirectory)]
(spit (io/file git-dir "HEAD") rev)
git-dir))
(defn rm
"Removes the .git directory returning a checkout back to just the checked
out code."
[^File git-dir]
(when (and (.exists git-dir) (= ".git" (.getName git-dir)))
(->> (file-seq git-dir)
reverse
(run! #(when (.exists %) (.delete %))))))
| 72725 | (ns lein-git-down.impl.git
(:refer-clojure :exclude [resolve])
(:require [clojure.java.io :as io]
[clojure.string :as string]
[clojure.tools.gitlibs :as git]
[clojure.tools.gitlibs.impl :as git-impl]
[leiningen.core.main :as lein]
[robert.h<NAME>ke :as hooke])
(:import (com.jcraft.jsch JSch Session UserInfo ConfigRepository ConfigRepository$Config KeyPair)
(com.jcraft.jsch.agentproxy ConnectorFactory RemoteIdentityRepository)
(org.eclipse.jgit.api TransportConfigCallback Git)
(org.eclipse.jgit.transport SshTransport JschConfigSessionFactory OpenSshConfig)
(java.io File)))
;; This namespace provides patched `procure` & `resolve` functions that fix
;; issues in JGit's implementation of JSCH. The first is a problem that causes
;; failure if using an encrypted (password protected) SSH key to connect to a
;; private repository. There is a [patch](https://dev.clojure.org/jira/browse/TDEPS-49)
;; submitted to gitlibs for this. The second is how JSCH handles keys in an
;; unsupported format. Without the patch it will fail at the first key it
;; encounters that it does not recognize, which is undesirable as the user
;; may have another key configured that will work. The patched impl below
;; will print a warn message and move on to the next key.
(def ^:dynamic *monkeypatch-tools-gitlibs* true)
(defn valid-key?
[jsch v]
(try
(KeyPair/load ^JSch jsch v)
true
(catch Throwable e
(let [m (if (.startsWith (.getMessage e) "invalid privatekey")
"The private key file is in an unsupported format."
(.getMessage e))]
(lein/warn "Exception processing private key," v ":"
m "Skipping..."))
false)))
(defn get-unsupported-algorithms
[^Session session k]
(into #{}
(filter #(nil? (JSch/getConfig %)))
(some-> (.getConfig session k) (string/split #","))))
(defn check-algorithms
"Jsch fails with an NPE when an unsupported algorithm is configured in the
ssh config file. This provides the user with more helpful information as to
the cause of the error."
[^Session session]
(let [kex (get-unsupported-algorithms session "kex")
cph (get-unsupported-algorithms session "cipher.c2s")
mac (get-unsupported-algorithms session "mac.c2s")
msg (str "Detected unsupported algorithm(s) configured for the '%s' "
"property in ssh config: %s")]
(when (not-empty kex) (lein/warn (format msg "KexAlgorithms" kex)))
(when (not-empty cph) (lein/warn (format msg "Ciphers" cph)))
(when (not-empty mac) (lein/warn (format msg "MACs" mac)))))
(def ssh-callback
(delay
(let [factory (doto (ConnectorFactory/getDefault)
(.setPreferredUSocketFactories "jna,nc"))
connector (.createConnector factory)]
(JSch/setConfig "PreferredAuthentications" "publickey")
(reify TransportConfigCallback
(configure [_ transport]
(.setSshSessionFactory
^SshTransport transport
(proxy [JschConfigSessionFactory] []
(configure [_host session]
(check-algorithms session)
(.setUserInfo
^Session session
(proxy [UserInfo] []
(getPassword [])
(promptYesNo [_] true)
(getPassphrase [])
(promptPassphrase [_] true)
(promptPassword [_] true)
(showMessage [_]))))
(getJSch [_hc fs]
(let [jsch (proxy-super createDefaultJSch fs)]
(doto jsch
(.setIdentityRepository
(RemoteIdentityRepository. connector))
(.setConfigRepository
(let [osc (OpenSshConfig/get fs)]
(proxy [ConfigRepository] []
(getConfig [host-name]
(let [oscc (.getConfig osc host-name)]
(proxy [ConfigRepository$Config] []
(getHostname [] (.getHostname oscc))
(getUser [] (.getUser oscc))
(getPort [] (.getPort oscc))
(getValue [key] (.getValue oscc key))
(getValues [key]
(let [vs (.getValues oscc key)]
(if (= key "<KEY>")
(into-array String
(filter (partial valid-key? jsch) vs))
vs)))))))))))))))))))
(defn dev-null-hook
[_ & _])
(defn procure
"Monkey patches gitlibs/procure to resolve some JSCH issues unless explicitly
told not to. Writes a meta-data file with information about the source."
[uri mvn-coords rev]
(hooke/with-scope
(hooke/add-hook #'git-impl/printerrln #'dev-null-hook)
(let [path (if *monkeypatch-tools-gitlibs*
(with-redefs [git-impl/ssh-callback ssh-callback]
(git/procure uri mvn-coords rev))
(git/procure uri mvn-coords rev))
meta (io/file path ".lein-git-down")]
(when-not (.exists meta)
(spit meta {:uri uri :mvn-coords mvn-coords :rev rev}))
path)))
(defn resolve
"Monkey patches gitlibs/resolve to resolve some JSCH issues unless explicitly
told not to."
[uri version]
(hooke/with-scope
(hooke/add-hook #'git-impl/printerrln #'dev-null-hook)
(if *monkeypatch-tools-gitlibs*
(with-redefs [git-impl/ssh-callback ssh-callback]
(git/resolve uri version))
(git/resolve uri version))))
(defn init
"Initializes a fresh git repository at `project-dir` and sets HEAD to the
provided rev, which allows tooling to retrieve the correct HEAD commit in
the gitlibs repo directory. Returns the .git directory."
[^File project-dir rev]
(let [git-dir (.. (Git/init)
(setDirectory project-dir)
call
getRepository
getDirectory)]
(spit (io/file git-dir "HEAD") rev)
git-dir))
(defn rm
"Removes the .git directory returning a checkout back to just the checked
out code."
[^File git-dir]
(when (and (.exists git-dir) (= ".git" (.getName git-dir)))
(->> (file-seq git-dir)
reverse
(run! #(when (.exists %) (.delete %))))))
| true | (ns lein-git-down.impl.git
(:refer-clojure :exclude [resolve])
(:require [clojure.java.io :as io]
[clojure.string :as string]
[clojure.tools.gitlibs :as git]
[clojure.tools.gitlibs.impl :as git-impl]
[leiningen.core.main :as lein]
[robert.hPI:NAME:<NAME>END_PIke :as hooke])
(:import (com.jcraft.jsch JSch Session UserInfo ConfigRepository ConfigRepository$Config KeyPair)
(com.jcraft.jsch.agentproxy ConnectorFactory RemoteIdentityRepository)
(org.eclipse.jgit.api TransportConfigCallback Git)
(org.eclipse.jgit.transport SshTransport JschConfigSessionFactory OpenSshConfig)
(java.io File)))
;; This namespace provides patched `procure` & `resolve` functions that fix
;; issues in JGit's implementation of JSCH. The first is a problem that causes
;; failure if using an encrypted (password protected) SSH key to connect to a
;; private repository. There is a [patch](https://dev.clojure.org/jira/browse/TDEPS-49)
;; submitted to gitlibs for this. The second is how JSCH handles keys in an
;; unsupported format. Without the patch it will fail at the first key it
;; encounters that it does not recognize, which is undesirable as the user
;; may have another key configured that will work. The patched impl below
;; will print a warn message and move on to the next key.
(def ^:dynamic *monkeypatch-tools-gitlibs* true)
(defn valid-key?
[jsch v]
(try
(KeyPair/load ^JSch jsch v)
true
(catch Throwable e
(let [m (if (.startsWith (.getMessage e) "invalid privatekey")
"The private key file is in an unsupported format."
(.getMessage e))]
(lein/warn "Exception processing private key," v ":"
m "Skipping..."))
false)))
(defn get-unsupported-algorithms
[^Session session k]
(into #{}
(filter #(nil? (JSch/getConfig %)))
(some-> (.getConfig session k) (string/split #","))))
(defn check-algorithms
"Jsch fails with an NPE when an unsupported algorithm is configured in the
ssh config file. This provides the user with more helpful information as to
the cause of the error."
[^Session session]
(let [kex (get-unsupported-algorithms session "kex")
cph (get-unsupported-algorithms session "cipher.c2s")
mac (get-unsupported-algorithms session "mac.c2s")
msg (str "Detected unsupported algorithm(s) configured for the '%s' "
"property in ssh config: %s")]
(when (not-empty kex) (lein/warn (format msg "KexAlgorithms" kex)))
(when (not-empty cph) (lein/warn (format msg "Ciphers" cph)))
(when (not-empty mac) (lein/warn (format msg "MACs" mac)))))
(def ssh-callback
(delay
(let [factory (doto (ConnectorFactory/getDefault)
(.setPreferredUSocketFactories "jna,nc"))
connector (.createConnector factory)]
(JSch/setConfig "PreferredAuthentications" "publickey")
(reify TransportConfigCallback
(configure [_ transport]
(.setSshSessionFactory
^SshTransport transport
(proxy [JschConfigSessionFactory] []
(configure [_host session]
(check-algorithms session)
(.setUserInfo
^Session session
(proxy [UserInfo] []
(getPassword [])
(promptYesNo [_] true)
(getPassphrase [])
(promptPassphrase [_] true)
(promptPassword [_] true)
(showMessage [_]))))
(getJSch [_hc fs]
(let [jsch (proxy-super createDefaultJSch fs)]
(doto jsch
(.setIdentityRepository
(RemoteIdentityRepository. connector))
(.setConfigRepository
(let [osc (OpenSshConfig/get fs)]
(proxy [ConfigRepository] []
(getConfig [host-name]
(let [oscc (.getConfig osc host-name)]
(proxy [ConfigRepository$Config] []
(getHostname [] (.getHostname oscc))
(getUser [] (.getUser oscc))
(getPort [] (.getPort oscc))
(getValue [key] (.getValue oscc key))
(getValues [key]
(let [vs (.getValues oscc key)]
(if (= key "PI:KEY:<KEY>END_PI")
(into-array String
(filter (partial valid-key? jsch) vs))
vs)))))))))))))))))))
(defn dev-null-hook
[_ & _])
(defn procure
"Monkey patches gitlibs/procure to resolve some JSCH issues unless explicitly
told not to. Writes a meta-data file with information about the source."
[uri mvn-coords rev]
(hooke/with-scope
(hooke/add-hook #'git-impl/printerrln #'dev-null-hook)
(let [path (if *monkeypatch-tools-gitlibs*
(with-redefs [git-impl/ssh-callback ssh-callback]
(git/procure uri mvn-coords rev))
(git/procure uri mvn-coords rev))
meta (io/file path ".lein-git-down")]
(when-not (.exists meta)
(spit meta {:uri uri :mvn-coords mvn-coords :rev rev}))
path)))
(defn resolve
"Monkey patches gitlibs/resolve to resolve some JSCH issues unless explicitly
told not to."
[uri version]
(hooke/with-scope
(hooke/add-hook #'git-impl/printerrln #'dev-null-hook)
(if *monkeypatch-tools-gitlibs*
(with-redefs [git-impl/ssh-callback ssh-callback]
(git/resolve uri version))
(git/resolve uri version))))
(defn init
"Initializes a fresh git repository at `project-dir` and sets HEAD to the
provided rev, which allows tooling to retrieve the correct HEAD commit in
the gitlibs repo directory. Returns the .git directory."
[^File project-dir rev]
(let [git-dir (.. (Git/init)
(setDirectory project-dir)
call
getRepository
getDirectory)]
(spit (io/file git-dir "HEAD") rev)
git-dir))
(defn rm
"Removes the .git directory returning a checkout back to just the checked
out code."
[^File git-dir]
(when (and (.exists git-dir) (= ".git" (.getName git-dir)))
(->> (file-seq git-dir)
reverse
(run! #(when (.exists %) (.delete %))))))
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 29,
"score": 0.999869704246521,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "\"High level nREPL client support.\"\n :author \"Chas Emerick\"}\n clojure.tools.nrepl\n (:require [clojure.tool",
"end": 537,
"score": 0.9998819231987,
"start": 525,
"tag": "NAME",
"value": "Chas Emerick"
},
{
"context": "L/URI. Valid\n examples include:\n\n nrepl://192.168.0.12:7889\n telnet://localhost:5000\n http://y",
"end": 8209,
"score": 0.9963632225990295,
"start": 8197,
"tag": "IP_ADDRESS",
"value": "192.168.0.12"
}
] | server/target/clojure/tools/nrepl.clj | OctavioBR/healthcheck | 14 | ; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns ^{:doc "High level nREPL client support."
:author "Chas Emerick"}
clojure.tools.nrepl
(:require [clojure.tools.nrepl.transport :as transport]
clojure.set
[clojure.java.io :as io])
(:use [clojure.tools.nrepl.misc :only (uuid)])
(:import clojure.lang.LineNumberingPushbackReader
(java.io Reader StringReader Writer PrintWriter)))
(defn response-seq
"Returns a lazy seq of messages received via the given Transport.
Called with no further arguments, will block waiting for each message.
The seq will end only when the underlying Transport is closed (i.e.
returns nil from `recv`) or if a message takes longer than `timeout`
millis to arrive."
([transport] (response-seq transport Long/MAX_VALUE))
([transport timeout]
(take-while identity (repeatedly #(transport/recv transport timeout)))))
(defn client
"Returns a fn of zero and one argument, both of which return the current head of a single
response-seq being read off of the given client-side transport. The one-arg arity will
send a given message on the transport before returning the seq.
Most REPL interactions are best performed via `message` and `client-session` on top of
a client fn returned from this fn."
[transport response-timeout]
(let [latest-head (atom nil)
update #(swap! latest-head
(fn [[timestamp seq :as head] now]
(if (< timestamp now)
[now %]
head))
; nanoTime appropriate here; looking to maintain ordering, not actual timestamps
(System/nanoTime))
tracking-seq (fn tracking-seq [responses]
(lazy-seq
(if (seq responses)
(let [rst (tracking-seq (rest responses))]
(update rst)
(cons (first responses) rst))
(do (update nil) nil))))
restart #(let [head (-> transport
(response-seq response-timeout)
tracking-seq)]
(reset! latest-head [0 head])
head)]
^{::transport transport ::timeout response-timeout}
(fn this
([] (or (second @latest-head)
(restart)))
([msg]
(transport/send transport msg)
(this)))))
(defn- take-until
"Like (take-while (complement f) coll), but includes the first item in coll that
returns true for f."
[f coll]
(let [[head tail] (split-with (complement f) coll)]
(concat head (take 1 tail))))
(defn- delimited-transport-seq
[client termination-statuses delimited-slots]
(with-meta
(comp (partial take-until (comp #(seq (clojure.set/intersection % termination-statuses))
set
:status))
(let [keys (keys delimited-slots)]
(partial filter #(= delimited-slots (select-keys % keys))))
client
#(merge % delimited-slots))
(-> (meta client)
(update-in [::termination-statuses] (fnil into #{}) termination-statuses)
(update-in [::taking-until] merge delimited-slots))))
(defn message
"Sends a message via [client] with a fixed message :id added to it.
Returns the head of the client's response seq, filtered to include only
messages related to the message :id that will terminate upon receipt of a
\"done\" :status."
[client {:keys [id] :as msg :or {id (uuid)}}]
(let [f (delimited-transport-seq client #{"done"} {:id id})]
(f (assoc msg :id id))))
(defn new-session
"Provokes the creation and retention of a new session, optionally as a clone
of an existing retained session, the id of which must be provided as a :clone
kwarg. Returns the new session's id."
[client & {:keys [clone]}]
(let [resp (first (message client (merge {:op "clone"} (when clone {:session clone}))))]
(or (:new-session resp)
(throw (IllegalStateException.
(str "Could not open new session; :clone response: " resp))))))
(defn client-session
"Returns a function of one argument. Accepts a message that is sent via the
client provided with a fixed :session id added to it. Returns the
head of the client's response seq, filtered to include only
messages related to the :session id that will terminate when the session is
closed."
[client & {:keys [session clone]}]
(let [session (or session (apply new-session client (when clone [:clone clone])))]
(delimited-transport-seq client #{"session-closed"} {:session session})))
(defn combine-responses
"Combines the provided seq of response messages into a single response map.
Certain message slots are combined in special ways:
- only the last :ns is retained
- :value is accumulated into an ordered collection
- :status and :session are accumulated into a set
- string values (associated with e.g. :out and :err) are concatenated"
[responses]
(reduce
(fn [m [k v]]
(case k
(:id :ns) (assoc m k v)
:value (update-in m [k] (fnil conj []) v)
:status (update-in m [k] (fnil into #{}) v)
:session (update-in m [k] (fnil conj #{}) v)
(if (string? v)
(update-in m [k] #(str % v))
(assoc m k v))))
{} (apply concat responses)))
(defn code*
"Returns a single string containing the pr-str'd representations
of the given expressions."
[& expressions]
(apply str (map pr-str expressions)))
(defmacro code
"Expands into a string consisting of the macro's body's forms
(literally, no interpolation/quasiquoting of locals or other
references), suitable for use in an :eval message, e.g.:
{:op :eval, :code (code (+ 1 1) (slurp \"foo.txt\"))}"
[& body]
(apply code* body))
(defn read-response-value
"Returns the provided response message, replacing its :value string with
the result of (read)ing it. Returns the message unchanged if the :value
slot is empty or not a string."
[{:keys [value] :as msg}]
(if-not (string? value)
msg
(try
(assoc msg :value (read-string value))
(catch Exception e
(throw (IllegalStateException. (str "Could not read response value: " value) e))))))
(defn response-values
"Given a seq of responses (as from response-seq or returned from any function returned
by client or client-session), returns a seq of values read from :value slots found
therein."
[responses]
(->> responses
(map read-response-value)
combine-responses
:value))
(defn connect
"Connects to a socket-based REPL at the given host (defaults to localhost) and port,
returning the Transport (by default clojure.tools.nrepl.transport/bencode)
for that connection.
Transports are most easily used with `client`, `client-session`, and
`message`, depending on the semantics desired."
[& {:keys [port host transport-fn] :or {transport-fn transport/bencode
host "localhost"}}]
{:pre [transport-fn port]}
(transport-fn (java.net.Socket. ^String host (int port))))
(defn- ^java.net.URI to-uri
[x]
{:post [(instance? java.net.URI %)]}
(if (string? x)
(java.net.URI. x)
x))
(defn- socket-info
[x]
(let [uri (to-uri x)
port (.getPort uri)]
(merge {:host (.getHost uri)}
(when (pos? port)
{:port port}))))
(def ^{:private false} uri-scheme #(-> (to-uri %) .getScheme .toLowerCase))
(defmulti url-connect
"Connects to an nREPL endpoint identified by the given URL/URI. Valid
examples include:
nrepl://192.168.0.12:7889
telnet://localhost:5000
http://your-app-name.heroku.com/repl
This is a multimethod that dispatches on the scheme of the URI provided
(which can be a string or java.net.URI). By default, implementations for
nrepl (corresponding to using the default bencode transport) and
telnet (using the clojure.tools.nrepl.transport/tty transport) are
registered. Alternative implementations may add support for other schemes,
such as HTTP, HTTPS, JMX, existing message queues, etc."
uri-scheme)
;; TODO oh so ugly
(defn- add-socket-connect-method!
[protocol connect-defaults]
(defmethod url-connect protocol
[uri]
(apply connect (mapcat identity
(merge connect-defaults
(socket-info uri))))))
(add-socket-connect-method! "nrepl" {:transport-fn transport/bencode
:port 7888})
(add-socket-connect-method! "telnet" {:transport-fn transport/tty})
(defmethod url-connect :default
[uri]
(throw (IllegalArgumentException.
(format "No nREPL support known for scheme %s, url %s" (uri-scheme uri) uri))))
(def ^{:doc "Current version of nREPL, map of :major, :minor, :incremental, and :qualifier."}
version
(when-let [in (.getResourceAsStream (class connect) "/clojure/tools/nrepl/version.txt")]
(with-open [^java.io.BufferedReader reader (io/reader in)]
(let [version-string (-> reader .readLine .trim)]
(assoc (->> version-string
(re-find #"(\d+)\.(\d+)\.(\d+)-?(.*)")
rest
(zipmap [:major :minor :incremental :qualifier]))
:version-string version-string)))))
| 54643 | ; Copyright (c) <NAME>. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns ^{:doc "High level nREPL client support."
:author "<NAME>"}
clojure.tools.nrepl
(:require [clojure.tools.nrepl.transport :as transport]
clojure.set
[clojure.java.io :as io])
(:use [clojure.tools.nrepl.misc :only (uuid)])
(:import clojure.lang.LineNumberingPushbackReader
(java.io Reader StringReader Writer PrintWriter)))
(defn response-seq
"Returns a lazy seq of messages received via the given Transport.
Called with no further arguments, will block waiting for each message.
The seq will end only when the underlying Transport is closed (i.e.
returns nil from `recv`) or if a message takes longer than `timeout`
millis to arrive."
([transport] (response-seq transport Long/MAX_VALUE))
([transport timeout]
(take-while identity (repeatedly #(transport/recv transport timeout)))))
(defn client
"Returns a fn of zero and one argument, both of which return the current head of a single
response-seq being read off of the given client-side transport. The one-arg arity will
send a given message on the transport before returning the seq.
Most REPL interactions are best performed via `message` and `client-session` on top of
a client fn returned from this fn."
[transport response-timeout]
(let [latest-head (atom nil)
update #(swap! latest-head
(fn [[timestamp seq :as head] now]
(if (< timestamp now)
[now %]
head))
; nanoTime appropriate here; looking to maintain ordering, not actual timestamps
(System/nanoTime))
tracking-seq (fn tracking-seq [responses]
(lazy-seq
(if (seq responses)
(let [rst (tracking-seq (rest responses))]
(update rst)
(cons (first responses) rst))
(do (update nil) nil))))
restart #(let [head (-> transport
(response-seq response-timeout)
tracking-seq)]
(reset! latest-head [0 head])
head)]
^{::transport transport ::timeout response-timeout}
(fn this
([] (or (second @latest-head)
(restart)))
([msg]
(transport/send transport msg)
(this)))))
(defn- take-until
"Like (take-while (complement f) coll), but includes the first item in coll that
returns true for f."
[f coll]
(let [[head tail] (split-with (complement f) coll)]
(concat head (take 1 tail))))
(defn- delimited-transport-seq
[client termination-statuses delimited-slots]
(with-meta
(comp (partial take-until (comp #(seq (clojure.set/intersection % termination-statuses))
set
:status))
(let [keys (keys delimited-slots)]
(partial filter #(= delimited-slots (select-keys % keys))))
client
#(merge % delimited-slots))
(-> (meta client)
(update-in [::termination-statuses] (fnil into #{}) termination-statuses)
(update-in [::taking-until] merge delimited-slots))))
(defn message
"Sends a message via [client] with a fixed message :id added to it.
Returns the head of the client's response seq, filtered to include only
messages related to the message :id that will terminate upon receipt of a
\"done\" :status."
[client {:keys [id] :as msg :or {id (uuid)}}]
(let [f (delimited-transport-seq client #{"done"} {:id id})]
(f (assoc msg :id id))))
(defn new-session
"Provokes the creation and retention of a new session, optionally as a clone
of an existing retained session, the id of which must be provided as a :clone
kwarg. Returns the new session's id."
[client & {:keys [clone]}]
(let [resp (first (message client (merge {:op "clone"} (when clone {:session clone}))))]
(or (:new-session resp)
(throw (IllegalStateException.
(str "Could not open new session; :clone response: " resp))))))
(defn client-session
"Returns a function of one argument. Accepts a message that is sent via the
client provided with a fixed :session id added to it. Returns the
head of the client's response seq, filtered to include only
messages related to the :session id that will terminate when the session is
closed."
[client & {:keys [session clone]}]
(let [session (or session (apply new-session client (when clone [:clone clone])))]
(delimited-transport-seq client #{"session-closed"} {:session session})))
(defn combine-responses
"Combines the provided seq of response messages into a single response map.
Certain message slots are combined in special ways:
- only the last :ns is retained
- :value is accumulated into an ordered collection
- :status and :session are accumulated into a set
- string values (associated with e.g. :out and :err) are concatenated"
[responses]
(reduce
(fn [m [k v]]
(case k
(:id :ns) (assoc m k v)
:value (update-in m [k] (fnil conj []) v)
:status (update-in m [k] (fnil into #{}) v)
:session (update-in m [k] (fnil conj #{}) v)
(if (string? v)
(update-in m [k] #(str % v))
(assoc m k v))))
{} (apply concat responses)))
(defn code*
"Returns a single string containing the pr-str'd representations
of the given expressions."
[& expressions]
(apply str (map pr-str expressions)))
(defmacro code
"Expands into a string consisting of the macro's body's forms
(literally, no interpolation/quasiquoting of locals or other
references), suitable for use in an :eval message, e.g.:
{:op :eval, :code (code (+ 1 1) (slurp \"foo.txt\"))}"
[& body]
(apply code* body))
(defn read-response-value
"Returns the provided response message, replacing its :value string with
the result of (read)ing it. Returns the message unchanged if the :value
slot is empty or not a string."
[{:keys [value] :as msg}]
(if-not (string? value)
msg
(try
(assoc msg :value (read-string value))
(catch Exception e
(throw (IllegalStateException. (str "Could not read response value: " value) e))))))
(defn response-values
"Given a seq of responses (as from response-seq or returned from any function returned
by client or client-session), returns a seq of values read from :value slots found
therein."
[responses]
(->> responses
(map read-response-value)
combine-responses
:value))
(defn connect
"Connects to a socket-based REPL at the given host (defaults to localhost) and port,
returning the Transport (by default clojure.tools.nrepl.transport/bencode)
for that connection.
Transports are most easily used with `client`, `client-session`, and
`message`, depending on the semantics desired."
[& {:keys [port host transport-fn] :or {transport-fn transport/bencode
host "localhost"}}]
{:pre [transport-fn port]}
(transport-fn (java.net.Socket. ^String host (int port))))
(defn- ^java.net.URI to-uri
[x]
{:post [(instance? java.net.URI %)]}
(if (string? x)
(java.net.URI. x)
x))
(defn- socket-info
[x]
(let [uri (to-uri x)
port (.getPort uri)]
(merge {:host (.getHost uri)}
(when (pos? port)
{:port port}))))
(def ^{:private false} uri-scheme #(-> (to-uri %) .getScheme .toLowerCase))
(defmulti url-connect
"Connects to an nREPL endpoint identified by the given URL/URI. Valid
examples include:
nrepl://192.168.0.12:7889
telnet://localhost:5000
http://your-app-name.heroku.com/repl
This is a multimethod that dispatches on the scheme of the URI provided
(which can be a string or java.net.URI). By default, implementations for
nrepl (corresponding to using the default bencode transport) and
telnet (using the clojure.tools.nrepl.transport/tty transport) are
registered. Alternative implementations may add support for other schemes,
such as HTTP, HTTPS, JMX, existing message queues, etc."
uri-scheme)
;; TODO oh so ugly
(defn- add-socket-connect-method!
[protocol connect-defaults]
(defmethod url-connect protocol
[uri]
(apply connect (mapcat identity
(merge connect-defaults
(socket-info uri))))))
(add-socket-connect-method! "nrepl" {:transport-fn transport/bencode
:port 7888})
(add-socket-connect-method! "telnet" {:transport-fn transport/tty})
(defmethod url-connect :default
[uri]
(throw (IllegalArgumentException.
(format "No nREPL support known for scheme %s, url %s" (uri-scheme uri) uri))))
(def ^{:doc "Current version of nREPL, map of :major, :minor, :incremental, and :qualifier."}
version
(when-let [in (.getResourceAsStream (class connect) "/clojure/tools/nrepl/version.txt")]
(with-open [^java.io.BufferedReader reader (io/reader in)]
(let [version-string (-> reader .readLine .trim)]
(assoc (->> version-string
(re-find #"(\d+)\.(\d+)\.(\d+)-?(.*)")
rest
(zipmap [:major :minor :incremental :qualifier]))
:version-string version-string)))))
| true | ; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns ^{:doc "High level nREPL client support."
:author "PI:NAME:<NAME>END_PI"}
clojure.tools.nrepl
(:require [clojure.tools.nrepl.transport :as transport]
clojure.set
[clojure.java.io :as io])
(:use [clojure.tools.nrepl.misc :only (uuid)])
(:import clojure.lang.LineNumberingPushbackReader
(java.io Reader StringReader Writer PrintWriter)))
(defn response-seq
"Returns a lazy seq of messages received via the given Transport.
Called with no further arguments, will block waiting for each message.
The seq will end only when the underlying Transport is closed (i.e.
returns nil from `recv`) or if a message takes longer than `timeout`
millis to arrive."
([transport] (response-seq transport Long/MAX_VALUE))
([transport timeout]
(take-while identity (repeatedly #(transport/recv transport timeout)))))
(defn client
"Returns a fn of zero and one argument, both of which return the current head of a single
response-seq being read off of the given client-side transport. The one-arg arity will
send a given message on the transport before returning the seq.
Most REPL interactions are best performed via `message` and `client-session` on top of
a client fn returned from this fn."
[transport response-timeout]
(let [latest-head (atom nil)
update #(swap! latest-head
(fn [[timestamp seq :as head] now]
(if (< timestamp now)
[now %]
head))
; nanoTime appropriate here; looking to maintain ordering, not actual timestamps
(System/nanoTime))
tracking-seq (fn tracking-seq [responses]
(lazy-seq
(if (seq responses)
(let [rst (tracking-seq (rest responses))]
(update rst)
(cons (first responses) rst))
(do (update nil) nil))))
restart #(let [head (-> transport
(response-seq response-timeout)
tracking-seq)]
(reset! latest-head [0 head])
head)]
^{::transport transport ::timeout response-timeout}
(fn this
([] (or (second @latest-head)
(restart)))
([msg]
(transport/send transport msg)
(this)))))
(defn- take-until
"Like (take-while (complement f) coll), but includes the first item in coll that
returns true for f."
[f coll]
(let [[head tail] (split-with (complement f) coll)]
(concat head (take 1 tail))))
(defn- delimited-transport-seq
[client termination-statuses delimited-slots]
(with-meta
(comp (partial take-until (comp #(seq (clojure.set/intersection % termination-statuses))
set
:status))
(let [keys (keys delimited-slots)]
(partial filter #(= delimited-slots (select-keys % keys))))
client
#(merge % delimited-slots))
(-> (meta client)
(update-in [::termination-statuses] (fnil into #{}) termination-statuses)
(update-in [::taking-until] merge delimited-slots))))
(defn message
"Sends a message via [client] with a fixed message :id added to it.
Returns the head of the client's response seq, filtered to include only
messages related to the message :id that will terminate upon receipt of a
\"done\" :status."
[client {:keys [id] :as msg :or {id (uuid)}}]
(let [f (delimited-transport-seq client #{"done"} {:id id})]
(f (assoc msg :id id))))
(defn new-session
"Provokes the creation and retention of a new session, optionally as a clone
of an existing retained session, the id of which must be provided as a :clone
kwarg. Returns the new session's id."
[client & {:keys [clone]}]
(let [resp (first (message client (merge {:op "clone"} (when clone {:session clone}))))]
(or (:new-session resp)
(throw (IllegalStateException.
(str "Could not open new session; :clone response: " resp))))))
(defn client-session
"Returns a function of one argument. Accepts a message that is sent via the
client provided with a fixed :session id added to it. Returns the
head of the client's response seq, filtered to include only
messages related to the :session id that will terminate when the session is
closed."
[client & {:keys [session clone]}]
(let [session (or session (apply new-session client (when clone [:clone clone])))]
(delimited-transport-seq client #{"session-closed"} {:session session})))
(defn combine-responses
"Combines the provided seq of response messages into a single response map.
Certain message slots are combined in special ways:
- only the last :ns is retained
- :value is accumulated into an ordered collection
- :status and :session are accumulated into a set
- string values (associated with e.g. :out and :err) are concatenated"
[responses]
(reduce
(fn [m [k v]]
(case k
(:id :ns) (assoc m k v)
:value (update-in m [k] (fnil conj []) v)
:status (update-in m [k] (fnil into #{}) v)
:session (update-in m [k] (fnil conj #{}) v)
(if (string? v)
(update-in m [k] #(str % v))
(assoc m k v))))
{} (apply concat responses)))
(defn code*
"Returns a single string containing the pr-str'd representations
of the given expressions."
[& expressions]
(apply str (map pr-str expressions)))
(defmacro code
"Expands into a string consisting of the macro's body's forms
(literally, no interpolation/quasiquoting of locals or other
references), suitable for use in an :eval message, e.g.:
{:op :eval, :code (code (+ 1 1) (slurp \"foo.txt\"))}"
[& body]
(apply code* body))
(defn read-response-value
"Returns the provided response message, replacing its :value string with
the result of (read)ing it. Returns the message unchanged if the :value
slot is empty or not a string."
[{:keys [value] :as msg}]
(if-not (string? value)
msg
(try
(assoc msg :value (read-string value))
(catch Exception e
(throw (IllegalStateException. (str "Could not read response value: " value) e))))))
(defn response-values
"Given a seq of responses (as from response-seq or returned from any function returned
by client or client-session), returns a seq of values read from :value slots found
therein."
[responses]
(->> responses
(map read-response-value)
combine-responses
:value))
(defn connect
"Connects to a socket-based REPL at the given host (defaults to localhost) and port,
returning the Transport (by default clojure.tools.nrepl.transport/bencode)
for that connection.
Transports are most easily used with `client`, `client-session`, and
`message`, depending on the semantics desired."
[& {:keys [port host transport-fn] :or {transport-fn transport/bencode
host "localhost"}}]
{:pre [transport-fn port]}
(transport-fn (java.net.Socket. ^String host (int port))))
(defn- ^java.net.URI to-uri
[x]
{:post [(instance? java.net.URI %)]}
(if (string? x)
(java.net.URI. x)
x))
(defn- socket-info
[x]
(let [uri (to-uri x)
port (.getPort uri)]
(merge {:host (.getHost uri)}
(when (pos? port)
{:port port}))))
(def ^{:private false} uri-scheme #(-> (to-uri %) .getScheme .toLowerCase))
(defmulti url-connect
"Connects to an nREPL endpoint identified by the given URL/URI. Valid
examples include:
nrepl://192.168.0.12:7889
telnet://localhost:5000
http://your-app-name.heroku.com/repl
This is a multimethod that dispatches on the scheme of the URI provided
(which can be a string or java.net.URI). By default, implementations for
nrepl (corresponding to using the default bencode transport) and
telnet (using the clojure.tools.nrepl.transport/tty transport) are
registered. Alternative implementations may add support for other schemes,
such as HTTP, HTTPS, JMX, existing message queues, etc."
uri-scheme)
;; TODO oh so ugly
(defn- add-socket-connect-method!
[protocol connect-defaults]
(defmethod url-connect protocol
[uri]
(apply connect (mapcat identity
(merge connect-defaults
(socket-info uri))))))
(add-socket-connect-method! "nrepl" {:transport-fn transport/bencode
:port 7888})
(add-socket-connect-method! "telnet" {:transport-fn transport/tty})
(defmethod url-connect :default
[uri]
(throw (IllegalArgumentException.
(format "No nREPL support known for scheme %s, url %s" (uri-scheme uri) uri))))
(def ^{:doc "Current version of nREPL, map of :major, :minor, :incremental, and :qualifier."}
version
(when-let [in (.getResourceAsStream (class connect) "/clojure/tools/nrepl/version.txt")]
(with-open [^java.io.BufferedReader reader (io/reader in)]
(let [version-string (-> reader .readLine .trim)]
(assoc (->> version-string
(re-find #"(\d+)\.(\d+)\.(\d+)-?(.*)")
rest
(zipmap [:major :minor :incremental :qualifier]))
:version-string version-string)))))
|
[
{
"context": "k.org\\\"\n :api-key \\\"EDC33DA4D977CFDF7B90545565E07324\\\"\n :app-id \\\"administ",
"end": 750,
"score": 0.9930311441421509,
"start": 716,
"tag": "KEY",
"value": "EDC33DA4D977CFDF7B90545565E07324\\\""
}
] | src/clj_osf/crud/delete.clj | structureddynamics/clj-osf | 4 | (ns clj-osf.crud.delete
"Send a CRUD Delete Query to a OSF Crud Delete web service endpoint
The CRUD: Delete Web service is used to delete an existing instance record indexed
in some target dataset of a WSF. When the instance record gets deleted, all of the
information archived in the dataset is deleted as well.
To use the CRUD Delete code, you have to:
```
;; Use/require the namespace
(require '[clj-osf.crud.delete :as crud])
;; Define the OSF Sandbox credentials (or your own):
(require '[clj-osf.core :as osf])
(osf/defosf osf-test-endpoint {:protocol :http
:domain \"sandbox.opensemanticframework.org\"
:api-key \"EDC33DA4D977CFDF7B90545565E07324\"
:app-id \"administer\"})
(osf/defuser osf-test-user {:uri \"http://sandbox.opensemanticframework.org/wsf/users/admin\"})
```
[Open Semantic Framework Endpoint Documentation](http://wiki.opensemanticframework.org/index.php/CRUD:_Delete#Web_Service_Endpoint_Information)"
(:require [clj-osf.core :as core]
[clojure.string :as string]))
(defn dataset
"Set the URI(s) of the dataset where the instance record is indexed.
The usage of this function is **Required**
##### Parameters
* `[uris]` Dataset URI where to index the RDF document
##### Usage
```
(crud/delete
(crud/dataset \"http://sandbox.opensemanticframework.org/datasets/test/bob\"))
```"
[uri]
{:dataset uri})
(defn hard
"Specify that this query will delete the published record and all its revisions.
The usage of this function is **Required**
##### Usage
```
(crud/delete
(crud/hard))
```"
[]
{:mode "hard"})
(defn soft
"Specify that this query will only delete the published record and not any of its
possible revision.
The usage of this function is **Required**
##### Usage
```
(crud/delete
(crud/soft))
```" []
{:mode "soft"})
(defn uri
"Set the URI(s) of the dataset where the instance record is indexed.
The usage of this function is **Required**
##### Parameters
* `[uris]` Dataset URI where to index the RDF document
##### Usage
```
(crud/delete
(crud/uri \"http://sandbox.opensemanticframework.org/datasets/test/bob\"))
```"
[uri]
{:uri uri})
(defn delete
"CRUD Delete query.
**Required**
##### Usage
```
(use '[clj-turtle.core])
(require '[clj-osf.crud.delete :as crud-d])
;; Delete an existing record, but keeping the revisions of that record
;; This action is like unpublishing the record. It could be recreated
;; from its revisions.
(crud-d/delete
(crud-d/dataset \"http://sandbox.opensemanticframework.org/datasets/test/\")
(crud-d/uri \"http://sandbox.opensemanticframework.org/datasets/test/bob\")
(crud-d/soft))
;; Delete an existing record, but deleting all its revisions as well
(crud-d/delete
(crud-d/dataset \"http://sandbox.opensemanticframework.org/datasets/test/\")
(crud-d/uri \"http://sandbox.opensemanticframework.org/datasets/test/bob\")
(crud-d/hard))
```"
[& body]
(let [params (apply merge body)
default (apply merge
(soft)
(core/->get)
(core/->mime "application/json"))
params (merge default params)]
(core/osf-query "/ws/crud/delete/" params)))
| 29459 | (ns clj-osf.crud.delete
"Send a CRUD Delete Query to a OSF Crud Delete web service endpoint
The CRUD: Delete Web service is used to delete an existing instance record indexed
in some target dataset of a WSF. When the instance record gets deleted, all of the
information archived in the dataset is deleted as well.
To use the CRUD Delete code, you have to:
```
;; Use/require the namespace
(require '[clj-osf.crud.delete :as crud])
;; Define the OSF Sandbox credentials (or your own):
(require '[clj-osf.core :as osf])
(osf/defosf osf-test-endpoint {:protocol :http
:domain \"sandbox.opensemanticframework.org\"
:api-key \"<KEY>
:app-id \"administer\"})
(osf/defuser osf-test-user {:uri \"http://sandbox.opensemanticframework.org/wsf/users/admin\"})
```
[Open Semantic Framework Endpoint Documentation](http://wiki.opensemanticframework.org/index.php/CRUD:_Delete#Web_Service_Endpoint_Information)"
(:require [clj-osf.core :as core]
[clojure.string :as string]))
(defn dataset
"Set the URI(s) of the dataset where the instance record is indexed.
The usage of this function is **Required**
##### Parameters
* `[uris]` Dataset URI where to index the RDF document
##### Usage
```
(crud/delete
(crud/dataset \"http://sandbox.opensemanticframework.org/datasets/test/bob\"))
```"
[uri]
{:dataset uri})
(defn hard
"Specify that this query will delete the published record and all its revisions.
The usage of this function is **Required**
##### Usage
```
(crud/delete
(crud/hard))
```"
[]
{:mode "hard"})
(defn soft
"Specify that this query will only delete the published record and not any of its
possible revision.
The usage of this function is **Required**
##### Usage
```
(crud/delete
(crud/soft))
```" []
{:mode "soft"})
(defn uri
"Set the URI(s) of the dataset where the instance record is indexed.
The usage of this function is **Required**
##### Parameters
* `[uris]` Dataset URI where to index the RDF document
##### Usage
```
(crud/delete
(crud/uri \"http://sandbox.opensemanticframework.org/datasets/test/bob\"))
```"
[uri]
{:uri uri})
(defn delete
"CRUD Delete query.
**Required**
##### Usage
```
(use '[clj-turtle.core])
(require '[clj-osf.crud.delete :as crud-d])
;; Delete an existing record, but keeping the revisions of that record
;; This action is like unpublishing the record. It could be recreated
;; from its revisions.
(crud-d/delete
(crud-d/dataset \"http://sandbox.opensemanticframework.org/datasets/test/\")
(crud-d/uri \"http://sandbox.opensemanticframework.org/datasets/test/bob\")
(crud-d/soft))
;; Delete an existing record, but deleting all its revisions as well
(crud-d/delete
(crud-d/dataset \"http://sandbox.opensemanticframework.org/datasets/test/\")
(crud-d/uri \"http://sandbox.opensemanticframework.org/datasets/test/bob\")
(crud-d/hard))
```"
[& body]
(let [params (apply merge body)
default (apply merge
(soft)
(core/->get)
(core/->mime "application/json"))
params (merge default params)]
(core/osf-query "/ws/crud/delete/" params)))
| true | (ns clj-osf.crud.delete
"Send a CRUD Delete Query to a OSF Crud Delete web service endpoint
The CRUD: Delete Web service is used to delete an existing instance record indexed
in some target dataset of a WSF. When the instance record gets deleted, all of the
information archived in the dataset is deleted as well.
To use the CRUD Delete code, you have to:
```
;; Use/require the namespace
(require '[clj-osf.crud.delete :as crud])
;; Define the OSF Sandbox credentials (or your own):
(require '[clj-osf.core :as osf])
(osf/defosf osf-test-endpoint {:protocol :http
:domain \"sandbox.opensemanticframework.org\"
:api-key \"PI:KEY:<KEY>END_PI
:app-id \"administer\"})
(osf/defuser osf-test-user {:uri \"http://sandbox.opensemanticframework.org/wsf/users/admin\"})
```
[Open Semantic Framework Endpoint Documentation](http://wiki.opensemanticframework.org/index.php/CRUD:_Delete#Web_Service_Endpoint_Information)"
(:require [clj-osf.core :as core]
[clojure.string :as string]))
(defn dataset
"Set the URI(s) of the dataset where the instance record is indexed.
The usage of this function is **Required**
##### Parameters
* `[uris]` Dataset URI where to index the RDF document
##### Usage
```
(crud/delete
(crud/dataset \"http://sandbox.opensemanticframework.org/datasets/test/bob\"))
```"
[uri]
{:dataset uri})
(defn hard
"Specify that this query will delete the published record and all its revisions.
The usage of this function is **Required**
##### Usage
```
(crud/delete
(crud/hard))
```"
[]
{:mode "hard"})
(defn soft
"Specify that this query will only delete the published record and not any of its
possible revision.
The usage of this function is **Required**
##### Usage
```
(crud/delete
(crud/soft))
```" []
{:mode "soft"})
(defn uri
"Set the URI(s) of the dataset where the instance record is indexed.
The usage of this function is **Required**
##### Parameters
* `[uris]` Dataset URI where to index the RDF document
##### Usage
```
(crud/delete
(crud/uri \"http://sandbox.opensemanticframework.org/datasets/test/bob\"))
```"
[uri]
{:uri uri})
(defn delete
"CRUD Delete query.
**Required**
##### Usage
```
(use '[clj-turtle.core])
(require '[clj-osf.crud.delete :as crud-d])
;; Delete an existing record, but keeping the revisions of that record
;; This action is like unpublishing the record. It could be recreated
;; from its revisions.
(crud-d/delete
(crud-d/dataset \"http://sandbox.opensemanticframework.org/datasets/test/\")
(crud-d/uri \"http://sandbox.opensemanticframework.org/datasets/test/bob\")
(crud-d/soft))
;; Delete an existing record, but deleting all its revisions as well
(crud-d/delete
(crud-d/dataset \"http://sandbox.opensemanticframework.org/datasets/test/\")
(crud-d/uri \"http://sandbox.opensemanticframework.org/datasets/test/bob\")
(crud-d/hard))
```"
[& body]
(let [params (apply merge body)
default (apply merge
(soft)
(core/->get)
(core/->mime "application/json"))
params (merge default params)]
(core/osf-query "/ws/crud/delete/" params)))
|
[
{
"context": "n-his-entity\n (assert-successful-get (get-image \"john@doe.com\")))\n\n(deftest a-user-cannot-view-an-image-in-anot",
"end": 2090,
"score": 0.9999078512191772,
"start": 2078,
"tag": "EMAIL",
"value": "john@doe.com"
},
{
"context": "n-anothers-entity\n (assert-not-found (get-image \"jane@doe.com\")))\n\n(deftest an-unauthenticated-user-cannot-view",
"end": 2196,
"score": 0.9999005198478699,
"start": 2184,
"tag": "EMAIL",
"value": "jane@doe.com"
}
] | test/clj_money/web/images_test.clj | dgknght/clj-money | 5 | (ns clj-money.web.images-test
(:require [clojure.test :refer [deftest use-fixtures is]]
[ring.mock.request :as req]
[clj-time.core :as t]
[dgknght.app-lib.web :refer [path]]
[clj-money.test-helpers :refer [reset-db]]
[clj-money.test-context :refer [basic-context
realize
find-image
find-user]]
[clj-money.web.auth :as auth]
[clj-money.web.server :refer [app]]))
(use-fixtures :each reset-db)
(def image-context
(assoc basic-context
:transactions [{:transaction-date (t/local-date 2015 1 1)
:description "Paycheck"
:debit-account-id "Checking"
:credit-account-id "Salary"
:quantity 1000M}]
:images [{:original-filename "attachment.jpg"
:content-type "image/jpg"
:body "resources/fixtures/attachment.jpg"}]
:attachments [{:image-id "attachment.jpg"
:transaction-id {:transaction-date (t/local-date 2015 1 1)
:description "Paycheck"}}]))
(defn- add-auth-cookie
[req user]
(req/cookie req :auth-token (auth/make-token user)))
(defn- get-image
[email]
(let [ctx (realize image-context)
image (find-image ctx "attachment.jpg")
user (when email (find-user ctx email))]
(-> (req/request :get (path :images
(:id image)))
(add-auth-cookie user)
app)))
(defn- assert-successful-get
[response]
; TODO: check response body?
(is (= 200 (:status response))))
(defn- assert-not-found
[response]
; TODO: check response body?
(is (= 404 (:status response))))
(defn- assert-unauthorized
[response]
; TODO: check response body?
(is (= 401 (:status response))))
(deftest a-user-can-view-an-image-in-his-entity
(assert-successful-get (get-image "john@doe.com")))
(deftest a-user-cannot-view-an-image-in-anothers-entity
(assert-not-found (get-image "jane@doe.com")))
(deftest an-unauthenticated-user-cannot-view-an-image
(assert-unauthorized (get-image nil)))
| 103852 | (ns clj-money.web.images-test
(:require [clojure.test :refer [deftest use-fixtures is]]
[ring.mock.request :as req]
[clj-time.core :as t]
[dgknght.app-lib.web :refer [path]]
[clj-money.test-helpers :refer [reset-db]]
[clj-money.test-context :refer [basic-context
realize
find-image
find-user]]
[clj-money.web.auth :as auth]
[clj-money.web.server :refer [app]]))
(use-fixtures :each reset-db)
(def image-context
(assoc basic-context
:transactions [{:transaction-date (t/local-date 2015 1 1)
:description "Paycheck"
:debit-account-id "Checking"
:credit-account-id "Salary"
:quantity 1000M}]
:images [{:original-filename "attachment.jpg"
:content-type "image/jpg"
:body "resources/fixtures/attachment.jpg"}]
:attachments [{:image-id "attachment.jpg"
:transaction-id {:transaction-date (t/local-date 2015 1 1)
:description "Paycheck"}}]))
(defn- add-auth-cookie
[req user]
(req/cookie req :auth-token (auth/make-token user)))
(defn- get-image
[email]
(let [ctx (realize image-context)
image (find-image ctx "attachment.jpg")
user (when email (find-user ctx email))]
(-> (req/request :get (path :images
(:id image)))
(add-auth-cookie user)
app)))
(defn- assert-successful-get
[response]
; TODO: check response body?
(is (= 200 (:status response))))
(defn- assert-not-found
[response]
; TODO: check response body?
(is (= 404 (:status response))))
(defn- assert-unauthorized
[response]
; TODO: check response body?
(is (= 401 (:status response))))
(deftest a-user-can-view-an-image-in-his-entity
(assert-successful-get (get-image "<EMAIL>")))
(deftest a-user-cannot-view-an-image-in-anothers-entity
(assert-not-found (get-image "<EMAIL>")))
(deftest an-unauthenticated-user-cannot-view-an-image
(assert-unauthorized (get-image nil)))
| true | (ns clj-money.web.images-test
(:require [clojure.test :refer [deftest use-fixtures is]]
[ring.mock.request :as req]
[clj-time.core :as t]
[dgknght.app-lib.web :refer [path]]
[clj-money.test-helpers :refer [reset-db]]
[clj-money.test-context :refer [basic-context
realize
find-image
find-user]]
[clj-money.web.auth :as auth]
[clj-money.web.server :refer [app]]))
(use-fixtures :each reset-db)
(def image-context
(assoc basic-context
:transactions [{:transaction-date (t/local-date 2015 1 1)
:description "Paycheck"
:debit-account-id "Checking"
:credit-account-id "Salary"
:quantity 1000M}]
:images [{:original-filename "attachment.jpg"
:content-type "image/jpg"
:body "resources/fixtures/attachment.jpg"}]
:attachments [{:image-id "attachment.jpg"
:transaction-id {:transaction-date (t/local-date 2015 1 1)
:description "Paycheck"}}]))
(defn- add-auth-cookie
[req user]
(req/cookie req :auth-token (auth/make-token user)))
(defn- get-image
[email]
(let [ctx (realize image-context)
image (find-image ctx "attachment.jpg")
user (when email (find-user ctx email))]
(-> (req/request :get (path :images
(:id image)))
(add-auth-cookie user)
app)))
(defn- assert-successful-get
[response]
; TODO: check response body?
(is (= 200 (:status response))))
(defn- assert-not-found
[response]
; TODO: check response body?
(is (= 404 (:status response))))
(defn- assert-unauthorized
[response]
; TODO: check response body?
(is (= 401 (:status response))))
(deftest a-user-can-view-an-image-in-his-entity
(assert-successful-get (get-image "PI:EMAIL:<EMAIL>END_PI")))
(deftest a-user-cannot-view-an-image-in-anothers-entity
(assert-not-found (get-image "PI:EMAIL:<EMAIL>END_PI")))
(deftest an-unauthenticated-user-cannot-view-an-image
(assert-unauthorized (get-image nil)))
|
[
{
"context": "(ns nastok.config)\n\n(def firebase\n {:apiKey \"AIzaSyBBpI2MQnuNYbfTj-1PQzSDDKS6CJqSj3w\"\n :authDomain \"nastok-3652b.fireba",
"end": 84,
"score": 0.9997581243515015,
"start": 45,
"tag": "KEY",
"value": "AIzaSyBBpI2MQnuNYbfTj-1PQzSDDKS6CJqSj3w"
}
] | src/nastok/config.cljs | jurkotroll/nastok | 0 | (ns nastok.config)
(def firebase
{:apiKey "AIzaSyBBpI2MQnuNYbfTj-1PQzSDDKS6CJqSj3w"
:authDomain "nastok-3652b.firebaseapp.com"
:databaseURL "https://nastok-3652b.firebaseio.com"
:projectId "nastok-3652b"
:storageBucket "nastok-3652b.appspot.com"
:messagingSenderId "172271390257"})
| 18074 | (ns nastok.config)
(def firebase
{:apiKey "<KEY>"
:authDomain "nastok-3652b.firebaseapp.com"
:databaseURL "https://nastok-3652b.firebaseio.com"
:projectId "nastok-3652b"
:storageBucket "nastok-3652b.appspot.com"
:messagingSenderId "172271390257"})
| true | (ns nastok.config)
(def firebase
{:apiKey "PI:KEY:<KEY>END_PI"
:authDomain "nastok-3652b.firebaseapp.com"
:databaseURL "https://nastok-3652b.firebaseio.com"
:projectId "nastok-3652b"
:storageBucket "nastok-3652b.appspot.com"
:messagingSenderId "172271390257"})
|
[
{
"context": "rument Onyx workflows\"\n :url \"https://github.com/onyx-platform/onyx-metrics\"\n :license {:name \"Eclipse Public L",
"end": 136,
"score": 0.9880319833755493,
"start": 123,
"tag": "USERNAME",
"value": "onyx-platform"
},
{
"context": "m/onyx \"0.10.0\"]\n ^{:voom {:repo \"git@github.com:onyx-platform/onyx.git\" :branch \"master\"}}\n ",
"end": 758,
"score": 0.9883869886398315,
"start": 744,
"tag": "EMAIL",
"value": "git@github.com"
}
] | data/train/clojure/74466d84d3fe86472f0f7c1b2551c2e3fc7a8a24project.clj | harshp8l/deep-learning-lang-detection | 84 | (defproject org.onyxplatform/onyx-metrics "0.10.0.0"
:description "Instrument Onyx workflows"
:url "https://github.com/onyx-platform/onyx-metrics"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:repositories {"snapshots" {:url "https://clojars.org/repo"
:username :env
:password :env
:sign-releases false}
"releases" {:url "https://clojars.org/repo"
:username :env
:password :env
:sign-releases false}}
:dependencies [[org.onyxplatform/onyx "0.10.0"]
^{:voom {:repo "git@github.com:onyx-platform/onyx.git" :branch "master"}}
[org.clojure/clojure "1.8.0"]
[metrics-clojure "2.8.0"]]
:java-opts ^:replace ["-server" "-Xmx3g"]
:global-vars {*warn-on-reflection* true
*assert* false
*unchecked-math* :warn-on-boxed}
:profiles {:dev {:jvm-opts ["-Xmx2500M"
"-XX:+UnlockCommercialFeatures"
"-XX:+FlightRecorder"
"-Dcom.sun.management.jmxremote.port=5555"
"-Dcom.sun.management.jmxremote.authenticate=false"
"-Dcom.sun.management.jmxremote.ssl=false"
"-XX:StartFlightRecording=duration=1080s,filename=recording.jfr"]
:dependencies [[riemann-clojure-client "0.4.1"]
[stylefruits/gniazdo "0.4.0"]
[org.clojure/java.jmx "0.3.3"]
[clj-http "2.1.0"]
[cheshire "5.5.0"]
[cognician/dogstatsd-clj "0.1.1"]]
:plugins [[lein-set-version "0.4.1"]
[lein-update-dependency "0.1.2"]
[lein-pprint "1.1.1"]]}})
| 88654 | (defproject org.onyxplatform/onyx-metrics "0.10.0.0"
:description "Instrument Onyx workflows"
:url "https://github.com/onyx-platform/onyx-metrics"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:repositories {"snapshots" {:url "https://clojars.org/repo"
:username :env
:password :env
:sign-releases false}
"releases" {:url "https://clojars.org/repo"
:username :env
:password :env
:sign-releases false}}
:dependencies [[org.onyxplatform/onyx "0.10.0"]
^{:voom {:repo "<EMAIL>:onyx-platform/onyx.git" :branch "master"}}
[org.clojure/clojure "1.8.0"]
[metrics-clojure "2.8.0"]]
:java-opts ^:replace ["-server" "-Xmx3g"]
:global-vars {*warn-on-reflection* true
*assert* false
*unchecked-math* :warn-on-boxed}
:profiles {:dev {:jvm-opts ["-Xmx2500M"
"-XX:+UnlockCommercialFeatures"
"-XX:+FlightRecorder"
"-Dcom.sun.management.jmxremote.port=5555"
"-Dcom.sun.management.jmxremote.authenticate=false"
"-Dcom.sun.management.jmxremote.ssl=false"
"-XX:StartFlightRecording=duration=1080s,filename=recording.jfr"]
:dependencies [[riemann-clojure-client "0.4.1"]
[stylefruits/gniazdo "0.4.0"]
[org.clojure/java.jmx "0.3.3"]
[clj-http "2.1.0"]
[cheshire "5.5.0"]
[cognician/dogstatsd-clj "0.1.1"]]
:plugins [[lein-set-version "0.4.1"]
[lein-update-dependency "0.1.2"]
[lein-pprint "1.1.1"]]}})
| true | (defproject org.onyxplatform/onyx-metrics "0.10.0.0"
:description "Instrument Onyx workflows"
:url "https://github.com/onyx-platform/onyx-metrics"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:repositories {"snapshots" {:url "https://clojars.org/repo"
:username :env
:password :env
:sign-releases false}
"releases" {:url "https://clojars.org/repo"
:username :env
:password :env
:sign-releases false}}
:dependencies [[org.onyxplatform/onyx "0.10.0"]
^{:voom {:repo "PI:EMAIL:<EMAIL>END_PI:onyx-platform/onyx.git" :branch "master"}}
[org.clojure/clojure "1.8.0"]
[metrics-clojure "2.8.0"]]
:java-opts ^:replace ["-server" "-Xmx3g"]
:global-vars {*warn-on-reflection* true
*assert* false
*unchecked-math* :warn-on-boxed}
:profiles {:dev {:jvm-opts ["-Xmx2500M"
"-XX:+UnlockCommercialFeatures"
"-XX:+FlightRecorder"
"-Dcom.sun.management.jmxremote.port=5555"
"-Dcom.sun.management.jmxremote.authenticate=false"
"-Dcom.sun.management.jmxremote.ssl=false"
"-XX:StartFlightRecording=duration=1080s,filename=recording.jfr"]
:dependencies [[riemann-clojure-client "0.4.1"]
[stylefruits/gniazdo "0.4.0"]
[org.clojure/java.jmx "0.3.3"]
[clj-http "2.1.0"]
[cheshire "5.5.0"]
[cognician/dogstatsd-clj "0.1.1"]]
:plugins [[lein-set-version "0.4.1"]
[lein-update-dependency "0.1.2"]
[lein-pprint "1.1.1"]]}})
|
[
{
"context": "ef default-street \"111 Main\")\n(def default-email \"nobody@example.net\")\n\n(defattr person-id :person/id :uuid {::attr/id",
"end": 833,
"score": 0.9997199177742004,
"start": 815,
"tag": "EMAIL",
"value": "nobody@example.net"
},
{
"context": "tart-create uism-env {:initial-state {:test/name \"Bob\"}})\n complete-fields (fns/get-in-graph s",
"end": 7190,
"score": 0.9870945811271667,
"start": 7187,
"tag": "NAME",
"value": "Bob"
}
] | src/test/com/fulcrologic/rad/form_spec.cljc | morgancmartin/fulcro-rad | 0 | (ns com.fulcrologic.rad.form-spec
(:require
[clojure.pprint :refer [pprint]]
[clojure.test :refer [use-fixtures]]
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[com.fulcrologic.fulcro.algorithms.normalized-state :as fns]
[com.fulcrologic.fulcro.algorithms.tempid :as tempid]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.ui-state-machines :as uism]
[com.fulcrologic.rad.attributes :as attr :refer [defattr]]
[com.fulcrologic.rad.attributes-options :as ao]
[com.fulcrologic.rad.form :as form]
[com.fulcrologic.rad.form-options :as fo]
[fulcro-spec.core :refer [assertions specification behavior when-mocking! component]]
[taoensso.timbre :as log]))
(declare =>)
(def default-street "111 Main")
(def default-email "nobody@example.net")
(defattr person-id :person/id :uuid {::attr/identity? true})
(defattr person-name :person/name :string {})
(defattr account-id :account/id :uuid {::attr/identity? true})
(defattr spouse :account/spouse :ref {::attr/cardinality :one
::attr/target :person/id})
(defattr email :account/email :string {::attr/required? true
::form/default-value default-email})
(defattr addresses :account/addresses :ref {::attr/target :address/id
::attr/cardinality :many})
(defattr address-id :address/id :uuid {::attr/identity? true})
(defattr street :address/street :string {::attr/required? true})
(defsc AddressForm [_ _]
{::form/attributes [street]
::form/default-values {:address/street default-street}
::attr/target :address/id
::form/id address-id
:query [:mocked/query]})
(defsc PersonForm [_ _]
{::form/attributes [person-name]
::form/id person-id})
(defsc AccountForm [_ _]
{::form/attributes [email addresses spouse]
::form/id account-id
::form/default-values {:account/spouse {}}
::form/subforms {:account/addresses {::form/ui AddressForm}
:account/spouse {::form/ui PersonForm}}})
(specification "attributes->form-query"
(component "Single-level query conversion"
(let [eql (form/form-options->form-query (comp/component-options AddressForm))
eql-items (set eql)]
(assertions
"Returns an EQL vector"
(vector? eql) => true
"Includes the ID of the form in the query"
(contains? eql-items :address/id) => true
"Includes the ASM table"
(contains? eql-items [::uism/asm-id '_]) => true
"Includes the form config join"
(contains? eql-items fs/form-config-join) => true
"Includes the scalar attribute keys"
(contains? eql-items :address/street) => true)))
(component "Nested query conversion"
(let [eql (form/form-options->form-query (comp/component-options AccountForm))
eql-items (set eql)]
(assertions
"Includes a join to the proper sub-query"
(contains? eql-items {:account/addresses [:mocked/query]}) => true))))
(specification "New entity initial state"
(component "simple entity"
(let [id (tempid/tempid)
v (form/default-state AddressForm id)]
(assertions
"Includes the new ID as the ID of the entity"
(get v :address/id) => id
"Adds any default fields to the entity"
(get v :address/street) => default-street)))
(component "nested entity"
(let [id (tempid/tempid)
v (form/default-state AccountForm id)]
(assertions
"Includes the new ID as the ID of the entity"
(get v :account/id) => id
"Adds default values from attribute declaration to the entity"
(get v :account/email) => default-email
"Includes a map with a new tempid for to-one entities that have a default value"
(some-> (get-in v [:account/spouse :person/id]) (tempid/tempid?)) => true
"Includes an empty vector for any to-many relation that has no default"
(get v :account/addresses) => []))))
(defattr test-id :test/id :uuid {ao/identity? true})
(defattr test-name :test/name :string {ao/identities #{:test/id} ao/required? true})
(defattr test-note :test/note :string {ao/identities #{:test/id}})
(defattr test-marketing :test/marketing? :boolean {ao/identities #{:test/id}})
(defattr test-agree :test/agree? :boolean {ao/identities #{:test/id} ao/required? true})
(defattr test-children :test/children :ref {ao/identities #{:child/id} ao/target :child/id ao/cardinality :many})
(defattr child-id :child/id :uuid {ao/identity? true})
(defattr child-a :child/a :string {ao/identities #{:child/id} ao/required? true})
(defattr child-b :child/b :string {ao/identities #{:child/id}})
(defattr child-node :child/node :ref {ao/identities #{:child/id} ao/target :subchild/id})
(defattr subchild-id :subchild/id :uuid {ao/identity? true})
(defattr subchild-x :subchild/x :string {ao/identities #{:subchild/id}})
(defattr subchild-y :subchild/y :string {ao/identities #{:subchild/id} ao/required? true})
(form/defsc-form SubChildForm [this props]
{fo/attributes [subchild-x subchild-y]
fo/id subchild-id})
(form/defsc-form ChildForm [this props]
{fo/attributes [child-a child-b child-node]
fo/id child-id
fo/subforms {:child/node {fo/ui SubChildForm}}})
(form/defsc-form TestForm [this props]
{fo/attributes [test-name test-note test-marketing test-agree test-children]
fo/id test-id
fo/subforms {:test/children {fo/ui ChildForm}}})
(specification "find-fields"
(let [fields (form/find-fields TestForm #(#{:ref :boolean} (get % ::attr/type)))]
(assertions
"Finds all of the fields (recursively) that match the predicate."
fields => #{:test/children :test/marketing? :test/agree? :child/node})))
(specification "optional-fields"
(let [fields (form/optional-fields TestForm)]
(assertions
"Finds all of the fields (recursively) that are used in forms but are not required by the data model."
;; Booleans??? What if we just want to leave false == nil?
fields => #{:test/note :test/children :test/marketing? :child/b :child/node :subchild/x})))
(specification "Form state initialization" :focus
(component "NEW entities"
(let [id (tempid/tempid)
state-map {:test/id {id {}}
::uism/asm-id {:id (uism/new-asm {::uism/asm-id :id
::uism/state-machine-id (::uism/state-machine-id form/form-machine)
::uism/event-data {}
::uism/actor->component-name {:actor/form ::TestForm}
::uism/actor->ident {:actor/form [:test/id id]}})}}
uism-env (uism/state-machine-env state-map :id)
{::uism/keys [state-map] :as after-setup} (#'form/start-create uism-env {:initial-state {:test/name "Bob"}})
complete-fields (fns/get-in-graph state-map
[:test/id id ::fs/config ::fs/complete?])]
(behavior "Required fields without an initial value are NOT complete"
(assertions
(contains? complete-fields :test/agree?) => false))
(behavior "Optional fields are marked complete"
(assertions
(contains? complete-fields :test/note) => true
(contains? complete-fields :test/marketing?) => true))
(behavior "Fields with default values are marked complete"
(assertions
(contains? complete-fields :test/name) => true))))) | 27317 | (ns com.fulcrologic.rad.form-spec
(:require
[clojure.pprint :refer [pprint]]
[clojure.test :refer [use-fixtures]]
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[com.fulcrologic.fulcro.algorithms.normalized-state :as fns]
[com.fulcrologic.fulcro.algorithms.tempid :as tempid]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.ui-state-machines :as uism]
[com.fulcrologic.rad.attributes :as attr :refer [defattr]]
[com.fulcrologic.rad.attributes-options :as ao]
[com.fulcrologic.rad.form :as form]
[com.fulcrologic.rad.form-options :as fo]
[fulcro-spec.core :refer [assertions specification behavior when-mocking! component]]
[taoensso.timbre :as log]))
(declare =>)
(def default-street "111 Main")
(def default-email "<EMAIL>")
(defattr person-id :person/id :uuid {::attr/identity? true})
(defattr person-name :person/name :string {})
(defattr account-id :account/id :uuid {::attr/identity? true})
(defattr spouse :account/spouse :ref {::attr/cardinality :one
::attr/target :person/id})
(defattr email :account/email :string {::attr/required? true
::form/default-value default-email})
(defattr addresses :account/addresses :ref {::attr/target :address/id
::attr/cardinality :many})
(defattr address-id :address/id :uuid {::attr/identity? true})
(defattr street :address/street :string {::attr/required? true})
(defsc AddressForm [_ _]
{::form/attributes [street]
::form/default-values {:address/street default-street}
::attr/target :address/id
::form/id address-id
:query [:mocked/query]})
(defsc PersonForm [_ _]
{::form/attributes [person-name]
::form/id person-id})
(defsc AccountForm [_ _]
{::form/attributes [email addresses spouse]
::form/id account-id
::form/default-values {:account/spouse {}}
::form/subforms {:account/addresses {::form/ui AddressForm}
:account/spouse {::form/ui PersonForm}}})
(specification "attributes->form-query"
(component "Single-level query conversion"
(let [eql (form/form-options->form-query (comp/component-options AddressForm))
eql-items (set eql)]
(assertions
"Returns an EQL vector"
(vector? eql) => true
"Includes the ID of the form in the query"
(contains? eql-items :address/id) => true
"Includes the ASM table"
(contains? eql-items [::uism/asm-id '_]) => true
"Includes the form config join"
(contains? eql-items fs/form-config-join) => true
"Includes the scalar attribute keys"
(contains? eql-items :address/street) => true)))
(component "Nested query conversion"
(let [eql (form/form-options->form-query (comp/component-options AccountForm))
eql-items (set eql)]
(assertions
"Includes a join to the proper sub-query"
(contains? eql-items {:account/addresses [:mocked/query]}) => true))))
(specification "New entity initial state"
(component "simple entity"
(let [id (tempid/tempid)
v (form/default-state AddressForm id)]
(assertions
"Includes the new ID as the ID of the entity"
(get v :address/id) => id
"Adds any default fields to the entity"
(get v :address/street) => default-street)))
(component "nested entity"
(let [id (tempid/tempid)
v (form/default-state AccountForm id)]
(assertions
"Includes the new ID as the ID of the entity"
(get v :account/id) => id
"Adds default values from attribute declaration to the entity"
(get v :account/email) => default-email
"Includes a map with a new tempid for to-one entities that have a default value"
(some-> (get-in v [:account/spouse :person/id]) (tempid/tempid?)) => true
"Includes an empty vector for any to-many relation that has no default"
(get v :account/addresses) => []))))
(defattr test-id :test/id :uuid {ao/identity? true})
(defattr test-name :test/name :string {ao/identities #{:test/id} ao/required? true})
(defattr test-note :test/note :string {ao/identities #{:test/id}})
(defattr test-marketing :test/marketing? :boolean {ao/identities #{:test/id}})
(defattr test-agree :test/agree? :boolean {ao/identities #{:test/id} ao/required? true})
(defattr test-children :test/children :ref {ao/identities #{:child/id} ao/target :child/id ao/cardinality :many})
(defattr child-id :child/id :uuid {ao/identity? true})
(defattr child-a :child/a :string {ao/identities #{:child/id} ao/required? true})
(defattr child-b :child/b :string {ao/identities #{:child/id}})
(defattr child-node :child/node :ref {ao/identities #{:child/id} ao/target :subchild/id})
(defattr subchild-id :subchild/id :uuid {ao/identity? true})
(defattr subchild-x :subchild/x :string {ao/identities #{:subchild/id}})
(defattr subchild-y :subchild/y :string {ao/identities #{:subchild/id} ao/required? true})
(form/defsc-form SubChildForm [this props]
{fo/attributes [subchild-x subchild-y]
fo/id subchild-id})
(form/defsc-form ChildForm [this props]
{fo/attributes [child-a child-b child-node]
fo/id child-id
fo/subforms {:child/node {fo/ui SubChildForm}}})
(form/defsc-form TestForm [this props]
{fo/attributes [test-name test-note test-marketing test-agree test-children]
fo/id test-id
fo/subforms {:test/children {fo/ui ChildForm}}})
(specification "find-fields"
(let [fields (form/find-fields TestForm #(#{:ref :boolean} (get % ::attr/type)))]
(assertions
"Finds all of the fields (recursively) that match the predicate."
fields => #{:test/children :test/marketing? :test/agree? :child/node})))
(specification "optional-fields"
(let [fields (form/optional-fields TestForm)]
(assertions
"Finds all of the fields (recursively) that are used in forms but are not required by the data model."
;; Booleans??? What if we just want to leave false == nil?
fields => #{:test/note :test/children :test/marketing? :child/b :child/node :subchild/x})))
(specification "Form state initialization" :focus
(component "NEW entities"
(let [id (tempid/tempid)
state-map {:test/id {id {}}
::uism/asm-id {:id (uism/new-asm {::uism/asm-id :id
::uism/state-machine-id (::uism/state-machine-id form/form-machine)
::uism/event-data {}
::uism/actor->component-name {:actor/form ::TestForm}
::uism/actor->ident {:actor/form [:test/id id]}})}}
uism-env (uism/state-machine-env state-map :id)
{::uism/keys [state-map] :as after-setup} (#'form/start-create uism-env {:initial-state {:test/name "<NAME>"}})
complete-fields (fns/get-in-graph state-map
[:test/id id ::fs/config ::fs/complete?])]
(behavior "Required fields without an initial value are NOT complete"
(assertions
(contains? complete-fields :test/agree?) => false))
(behavior "Optional fields are marked complete"
(assertions
(contains? complete-fields :test/note) => true
(contains? complete-fields :test/marketing?) => true))
(behavior "Fields with default values are marked complete"
(assertions
(contains? complete-fields :test/name) => true))))) | true | (ns com.fulcrologic.rad.form-spec
(:require
[clojure.pprint :refer [pprint]]
[clojure.test :refer [use-fixtures]]
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[com.fulcrologic.fulcro.algorithms.normalized-state :as fns]
[com.fulcrologic.fulcro.algorithms.tempid :as tempid]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.ui-state-machines :as uism]
[com.fulcrologic.rad.attributes :as attr :refer [defattr]]
[com.fulcrologic.rad.attributes-options :as ao]
[com.fulcrologic.rad.form :as form]
[com.fulcrologic.rad.form-options :as fo]
[fulcro-spec.core :refer [assertions specification behavior when-mocking! component]]
[taoensso.timbre :as log]))
(declare =>)
(def default-street "111 Main")
(def default-email "PI:EMAIL:<EMAIL>END_PI")
(defattr person-id :person/id :uuid {::attr/identity? true})
(defattr person-name :person/name :string {})
(defattr account-id :account/id :uuid {::attr/identity? true})
(defattr spouse :account/spouse :ref {::attr/cardinality :one
::attr/target :person/id})
(defattr email :account/email :string {::attr/required? true
::form/default-value default-email})
(defattr addresses :account/addresses :ref {::attr/target :address/id
::attr/cardinality :many})
(defattr address-id :address/id :uuid {::attr/identity? true})
(defattr street :address/street :string {::attr/required? true})
(defsc AddressForm [_ _]
{::form/attributes [street]
::form/default-values {:address/street default-street}
::attr/target :address/id
::form/id address-id
:query [:mocked/query]})
(defsc PersonForm [_ _]
{::form/attributes [person-name]
::form/id person-id})
(defsc AccountForm [_ _]
{::form/attributes [email addresses spouse]
::form/id account-id
::form/default-values {:account/spouse {}}
::form/subforms {:account/addresses {::form/ui AddressForm}
:account/spouse {::form/ui PersonForm}}})
(specification "attributes->form-query"
(component "Single-level query conversion"
(let [eql (form/form-options->form-query (comp/component-options AddressForm))
eql-items (set eql)]
(assertions
"Returns an EQL vector"
(vector? eql) => true
"Includes the ID of the form in the query"
(contains? eql-items :address/id) => true
"Includes the ASM table"
(contains? eql-items [::uism/asm-id '_]) => true
"Includes the form config join"
(contains? eql-items fs/form-config-join) => true
"Includes the scalar attribute keys"
(contains? eql-items :address/street) => true)))
(component "Nested query conversion"
(let [eql (form/form-options->form-query (comp/component-options AccountForm))
eql-items (set eql)]
(assertions
"Includes a join to the proper sub-query"
(contains? eql-items {:account/addresses [:mocked/query]}) => true))))
(specification "New entity initial state"
(component "simple entity"
(let [id (tempid/tempid)
v (form/default-state AddressForm id)]
(assertions
"Includes the new ID as the ID of the entity"
(get v :address/id) => id
"Adds any default fields to the entity"
(get v :address/street) => default-street)))
(component "nested entity"
(let [id (tempid/tempid)
v (form/default-state AccountForm id)]
(assertions
"Includes the new ID as the ID of the entity"
(get v :account/id) => id
"Adds default values from attribute declaration to the entity"
(get v :account/email) => default-email
"Includes a map with a new tempid for to-one entities that have a default value"
(some-> (get-in v [:account/spouse :person/id]) (tempid/tempid?)) => true
"Includes an empty vector for any to-many relation that has no default"
(get v :account/addresses) => []))))
(defattr test-id :test/id :uuid {ao/identity? true})
(defattr test-name :test/name :string {ao/identities #{:test/id} ao/required? true})
(defattr test-note :test/note :string {ao/identities #{:test/id}})
(defattr test-marketing :test/marketing? :boolean {ao/identities #{:test/id}})
(defattr test-agree :test/agree? :boolean {ao/identities #{:test/id} ao/required? true})
(defattr test-children :test/children :ref {ao/identities #{:child/id} ao/target :child/id ao/cardinality :many})
(defattr child-id :child/id :uuid {ao/identity? true})
(defattr child-a :child/a :string {ao/identities #{:child/id} ao/required? true})
(defattr child-b :child/b :string {ao/identities #{:child/id}})
(defattr child-node :child/node :ref {ao/identities #{:child/id} ao/target :subchild/id})
(defattr subchild-id :subchild/id :uuid {ao/identity? true})
(defattr subchild-x :subchild/x :string {ao/identities #{:subchild/id}})
(defattr subchild-y :subchild/y :string {ao/identities #{:subchild/id} ao/required? true})
(form/defsc-form SubChildForm [this props]
{fo/attributes [subchild-x subchild-y]
fo/id subchild-id})
(form/defsc-form ChildForm [this props]
{fo/attributes [child-a child-b child-node]
fo/id child-id
fo/subforms {:child/node {fo/ui SubChildForm}}})
(form/defsc-form TestForm [this props]
{fo/attributes [test-name test-note test-marketing test-agree test-children]
fo/id test-id
fo/subforms {:test/children {fo/ui ChildForm}}})
(specification "find-fields"
(let [fields (form/find-fields TestForm #(#{:ref :boolean} (get % ::attr/type)))]
(assertions
"Finds all of the fields (recursively) that match the predicate."
fields => #{:test/children :test/marketing? :test/agree? :child/node})))
(specification "optional-fields"
(let [fields (form/optional-fields TestForm)]
(assertions
"Finds all of the fields (recursively) that are used in forms but are not required by the data model."
;; Booleans??? What if we just want to leave false == nil?
fields => #{:test/note :test/children :test/marketing? :child/b :child/node :subchild/x})))
(specification "Form state initialization" :focus
(component "NEW entities"
(let [id (tempid/tempid)
state-map {:test/id {id {}}
::uism/asm-id {:id (uism/new-asm {::uism/asm-id :id
::uism/state-machine-id (::uism/state-machine-id form/form-machine)
::uism/event-data {}
::uism/actor->component-name {:actor/form ::TestForm}
::uism/actor->ident {:actor/form [:test/id id]}})}}
uism-env (uism/state-machine-env state-map :id)
{::uism/keys [state-map] :as after-setup} (#'form/start-create uism-env {:initial-state {:test/name "PI:NAME:<NAME>END_PI"}})
complete-fields (fns/get-in-graph state-map
[:test/id id ::fs/config ::fs/complete?])]
(behavior "Required fields without an initial value are NOT complete"
(assertions
(contains? complete-fields :test/agree?) => false))
(behavior "Optional fields are marked complete"
(assertions
(contains? complete-fields :test/note) => true
(contains? complete-fields :test/marketing?) => true))
(behavior "Fields with default values are marked complete"
(assertions
(contains? complete-fields :test/name) => true))))) |
[
{
"context": ";; Copyright 2020, Di Sera Luca\n;; Contacts: disera.luca@gmail.com\n;; ",
"end": 31,
"score": 0.9998770952224731,
"start": 19,
"tag": "NAME",
"value": "Di Sera Luca"
},
{
"context": " Copyright 2020, Di Sera Luca\n;; Contacts: disera.luca@gmail.com\n;; https://github.com/diseraluc",
"end": 74,
"score": 0.9999309182167053,
"start": 53,
"tag": "EMAIL",
"value": "disera.luca@gmail.com"
},
{
"context": "gmail.com\n;; https://github.com/diseraluca\n;; https://www.linkedin.com/in/",
"end": 125,
"score": 0.9996873736381531,
"start": 115,
"tag": "USERNAME",
"value": "diseraluca"
},
{
"context": "\n;; https://www.linkedin.com/in/luca-di-sera-200023167\n;;\n;; This code is licensed under the MIT License",
"end": 197,
"score": 0.9995616674423218,
"start": 175,
"tag": "USERNAME",
"value": "luca-di-sera-200023167"
}
] | pmal/src/pmal/backend/core.clj | diseraluca/pmal | 0 | ;; Copyright 2020, Di Sera Luca
;; Contacts: disera.luca@gmail.com
;; https://github.com/diseraluca
;; https://www.linkedin.com/in/luca-di-sera-200023167
;;
;; This code is licensed under the MIT License.
;; More information can be found in the LICENSE file in the root of this repository
(ns pmal.backend.core
(:require [pmal.backend.packages.core :as packages]))
;; TODO: When more than one initialization failure is implemented change to an Either-Monad-like approach.
(defn can-be-used?
"Tests the backend to check that the needed external resources are available."
[]
(packages/available?))
(defn package
"Retrieves the details of the package with the given name.
Returns nil if the package is unknown."
[pkgname]
(packages/package-details pkgname))
| 124015 | ;; Copyright 2020, <NAME>
;; Contacts: <EMAIL>
;; https://github.com/diseraluca
;; https://www.linkedin.com/in/luca-di-sera-200023167
;;
;; This code is licensed under the MIT License.
;; More information can be found in the LICENSE file in the root of this repository
(ns pmal.backend.core
(:require [pmal.backend.packages.core :as packages]))
;; TODO: When more than one initialization failure is implemented change to an Either-Monad-like approach.
(defn can-be-used?
"Tests the backend to check that the needed external resources are available."
[]
(packages/available?))
(defn package
"Retrieves the details of the package with the given name.
Returns nil if the package is unknown."
[pkgname]
(packages/package-details pkgname))
| true | ;; Copyright 2020, PI:NAME:<NAME>END_PI
;; Contacts: PI:EMAIL:<EMAIL>END_PI
;; https://github.com/diseraluca
;; https://www.linkedin.com/in/luca-di-sera-200023167
;;
;; This code is licensed under the MIT License.
;; More information can be found in the LICENSE file in the root of this repository
(ns pmal.backend.core
(:require [pmal.backend.packages.core :as packages]))
;; TODO: When more than one initialization failure is implemented change to an Either-Monad-like approach.
(defn can-be-used?
"Tests the backend to check that the needed external resources are available."
[]
(packages/available?))
(defn package
"Retrieves the details of the package with the given name.
Returns nil if the package is unknown."
[pkgname]
(packages/package-details pkgname))
|
[
{
"context": "fn create-user\n [session-admin & {:keys [username password email activated?]}]\n (let [validation-link (atom",
"end": 1120,
"score": 0.8276830315589905,
"start": 1112,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "href\n :password password\n :username use",
"end": 1373,
"score": 0.8367648124694824,
"start": 1365,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "word\n :username username\n :email ema",
"end": 1428,
"score": 0.9968990683555603,
"start": 1420,
"tag": "USERNAME",
"value": "username"
},
{
"context": " (fn [_] {:host \"smtp@example.com\"\n :",
"end": 1604,
"score": 0.9969555139541626,
"start": 1588,
"tag": "EMAIL",
"value": "smtp@example.com"
},
{
"context": " :pass \"password\"})\n\n ;; WARNING: This is a fragi",
"end": 1844,
"score": 0.9995282888412476,
"start": 1836,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " can create session\n (let [username \"user/jane\"\n plaintext-password \"JaneJane-0\"\n\n ",
"end": 4226,
"score": 0.9996190071105957,
"start": 4217,
"tag": "USERNAME",
"value": "user/jane"
},
{
"context": " \"user/jane\"\n plaintext-password \"JaneJane-0\"\n\n valid-create {:name ",
"end": 4259,
"score": 0.9984890222549438,
"start": 4258,
"tag": "PASSWORD",
"value": "J"
},
{
"context": " :username username\n :pass",
"end": 4558,
"score": 0.9985299110412598,
"start": 4550,
"tag": "USERNAME",
"value": "username"
},
{
"context": " :password plaintext-password}}]\n\n ;; create a user\n (create-user ses",
"end": 4631,
"score": 0.9992084503173828,
"start": 4613,
"tag": "PASSWORD",
"value": "plaintext-password"
},
{
"context": "te-user session-admin\n :username username\n :password plaintext-password\n ",
"end": 4729,
"score": 0.9985786080360413,
"start": 4721,
"tag": "USERNAME",
"value": "username"
},
{
"context": " :username username\n :password plaintext-password\n :activated? true\n ",
"end": 4777,
"score": 0.9992436766624451,
"start": 4759,
"tag": "PASSWORD",
"value": "plaintext-password"
},
{
"context": " :activated? true\n :email \"jane@example.org\")\n\n ; anonymous create must succeed\n (l",
"end": 4857,
"score": 0.9999211430549622,
"start": 4841,
"tag": "EMAIL",
"value": "jane@example.org"
}
] | code/test/sixsq/nuvla/server/resources/session/utils_test.clj | nuvla/server | 0 | (ns sixsq.nuvla.server.resources.session.utils-test
(:require
[clojure.data.json :as json]
[clojure.test :refer [deftest is use-fixtures]]
[peridot.core :refer [content-type header request session]]
[postal.core :as postal]
[sixsq.nuvla.server.app.params :as p]
[sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]]
[sixsq.nuvla.server.resources.email.sending :as email-sending]
[sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu]
[sixsq.nuvla.server.resources.session :as session]
[sixsq.nuvla.server.resources.session-template :as st]
[sixsq.nuvla.server.resources.session.utils :as session-utils]
[sixsq.nuvla.server.resources.user :as user]
[sixsq.nuvla.server.resources.user-template :as user-tpl]
[sixsq.nuvla.server.resources.user-template-email-password :as email-password]))
(use-fixtures :once ltu/with-test-server-fixture)
(def base-uri (str p/service-context session/resource-type))
(def session-template-base-uri (str p/service-context st/resource-type))
(defn create-user
[session-admin & {:keys [username password email activated?]}]
(let [validation-link (atom nil)
href (str user-tpl/resource-type "/" email-password/registration-method)
href-create {:template {:href href
:password password
:username username
:email email}}]
(with-redefs [email-sending/extract-smtp-cfg
(fn [_] {:host "smtp@example.com"
:port 465
:ssl true
:user "admin"
:pass "password"})
;; WARNING: This is a fragile! Regex matching to recover callback URL.
postal/send-message (fn [_ {:keys [body]}]
(let [url (->> body second :content
(re-matches #"(?s).*visit:\n\n\s+(.*?)\n.*")
second)]
(reset! validation-link url))
{:code 0, :error :SUCCESS, :message "OK"})]
(let [user-id (-> session-admin
(request (str p/service-context user/resource-type)
:request-method :post
:body (json/write-str href-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))]
(when activated?
(is (re-matches #"^email.*successfully validated$"
(-> session-admin
(request @validation-link)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body)
:message))))
user-id))))
;; verifies that a session can be updated internally
;; session setup is taken from the password session lifecycle test
(deftest check-session-update
(let [app (ltu/ring-app)
session-json (content-type (session app) "application/json")
session-admin (header session-json authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
session-anon (header session-json authn-info-header "user/unknown user/unknown group/nuvla-anon")
session-user (header session-json authn-info-header "user group/nuvla-user")
href (str st/resource-type "/password")
template-url (str p/service-context href)
name-attr "name"
description-attr "description"
tags-attr ["one", "two"]]
;; password session template must exist
(-> session-anon
(request template-url)
(ltu/body->edn)
(ltu/is-status 200))
;; anon with valid activated user can create session
(let [username "user/jane"
plaintext-password "JaneJane-0"
valid-create {:name name-attr
:description description-attr
:tags tags-attr
:template {:href href
:username username
:password plaintext-password}}]
;; create a user
(create-user session-admin
:username username
:password plaintext-password
:activated? true
:email "jane@example.org")
; anonymous create must succeed
(let [resp (-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-set-cookie)
(ltu/is-status 201))
id (ltu/body-resource-id resp)
abs-url (ltu/location-url resp)
{:keys [name description tags] :as original-session}
(-> session-user
(header authn-info-header (str "user/user group/nuvla-user group/nuvla-anon " id))
(request abs-url)
(ltu/body->edn)
:response
:body)]
; check contents of session
(is (= name name-attr))
(is (= description description-attr))
(is (= tags tags-attr))
;; After the setup, NOW verify that the session can be updated!
(let [new-name "UPDATED SESSION NAME"
correct-session (assoc original-session :name new-name)]
(session-utils/update-session (:id original-session) correct-session)
(let [updated-session (-> session-user
(header authn-info-header (str "user/user group/nuvla-user group/nuvla-anon " id))
(request abs-url)
(ltu/body->edn)
:response
:body)]
(is (= new-name (:name updated-session)))
(is (not= (:updated original-session) (:updated updated-session)))
(is (= (dissoc correct-session :updated)
(dissoc updated-session :updated :updated-by)))))))))
| 45861 | (ns sixsq.nuvla.server.resources.session.utils-test
(:require
[clojure.data.json :as json]
[clojure.test :refer [deftest is use-fixtures]]
[peridot.core :refer [content-type header request session]]
[postal.core :as postal]
[sixsq.nuvla.server.app.params :as p]
[sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]]
[sixsq.nuvla.server.resources.email.sending :as email-sending]
[sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu]
[sixsq.nuvla.server.resources.session :as session]
[sixsq.nuvla.server.resources.session-template :as st]
[sixsq.nuvla.server.resources.session.utils :as session-utils]
[sixsq.nuvla.server.resources.user :as user]
[sixsq.nuvla.server.resources.user-template :as user-tpl]
[sixsq.nuvla.server.resources.user-template-email-password :as email-password]))
(use-fixtures :once ltu/with-test-server-fixture)
(def base-uri (str p/service-context session/resource-type))
(def session-template-base-uri (str p/service-context st/resource-type))
(defn create-user
[session-admin & {:keys [username <PASSWORD> email activated?]}]
(let [validation-link (atom nil)
href (str user-tpl/resource-type "/" email-password/registration-method)
href-create {:template {:href href
:password <PASSWORD>
:username username
:email email}}]
(with-redefs [email-sending/extract-smtp-cfg
(fn [_] {:host "<EMAIL>"
:port 465
:ssl true
:user "admin"
:pass "<PASSWORD>"})
;; WARNING: This is a fragile! Regex matching to recover callback URL.
postal/send-message (fn [_ {:keys [body]}]
(let [url (->> body second :content
(re-matches #"(?s).*visit:\n\n\s+(.*?)\n.*")
second)]
(reset! validation-link url))
{:code 0, :error :SUCCESS, :message "OK"})]
(let [user-id (-> session-admin
(request (str p/service-context user/resource-type)
:request-method :post
:body (json/write-str href-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))]
(when activated?
(is (re-matches #"^email.*successfully validated$"
(-> session-admin
(request @validation-link)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body)
:message))))
user-id))))
;; verifies that a session can be updated internally
;; session setup is taken from the password session lifecycle test
(deftest check-session-update
(let [app (ltu/ring-app)
session-json (content-type (session app) "application/json")
session-admin (header session-json authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
session-anon (header session-json authn-info-header "user/unknown user/unknown group/nuvla-anon")
session-user (header session-json authn-info-header "user group/nuvla-user")
href (str st/resource-type "/password")
template-url (str p/service-context href)
name-attr "name"
description-attr "description"
tags-attr ["one", "two"]]
;; password session template must exist
(-> session-anon
(request template-url)
(ltu/body->edn)
(ltu/is-status 200))
;; anon with valid activated user can create session
(let [username "user/jane"
plaintext-password "<PASSWORD>aneJane-0"
valid-create {:name name-attr
:description description-attr
:tags tags-attr
:template {:href href
:username username
:password <PASSWORD>}}]
;; create a user
(create-user session-admin
:username username
:password <PASSWORD>
:activated? true
:email "<EMAIL>")
; anonymous create must succeed
(let [resp (-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-set-cookie)
(ltu/is-status 201))
id (ltu/body-resource-id resp)
abs-url (ltu/location-url resp)
{:keys [name description tags] :as original-session}
(-> session-user
(header authn-info-header (str "user/user group/nuvla-user group/nuvla-anon " id))
(request abs-url)
(ltu/body->edn)
:response
:body)]
; check contents of session
(is (= name name-attr))
(is (= description description-attr))
(is (= tags tags-attr))
;; After the setup, NOW verify that the session can be updated!
(let [new-name "UPDATED SESSION NAME"
correct-session (assoc original-session :name new-name)]
(session-utils/update-session (:id original-session) correct-session)
(let [updated-session (-> session-user
(header authn-info-header (str "user/user group/nuvla-user group/nuvla-anon " id))
(request abs-url)
(ltu/body->edn)
:response
:body)]
(is (= new-name (:name updated-session)))
(is (not= (:updated original-session) (:updated updated-session)))
(is (= (dissoc correct-session :updated)
(dissoc updated-session :updated :updated-by)))))))))
| true | (ns sixsq.nuvla.server.resources.session.utils-test
(:require
[clojure.data.json :as json]
[clojure.test :refer [deftest is use-fixtures]]
[peridot.core :refer [content-type header request session]]
[postal.core :as postal]
[sixsq.nuvla.server.app.params :as p]
[sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]]
[sixsq.nuvla.server.resources.email.sending :as email-sending]
[sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu]
[sixsq.nuvla.server.resources.session :as session]
[sixsq.nuvla.server.resources.session-template :as st]
[sixsq.nuvla.server.resources.session.utils :as session-utils]
[sixsq.nuvla.server.resources.user :as user]
[sixsq.nuvla.server.resources.user-template :as user-tpl]
[sixsq.nuvla.server.resources.user-template-email-password :as email-password]))
(use-fixtures :once ltu/with-test-server-fixture)
(def base-uri (str p/service-context session/resource-type))
(def session-template-base-uri (str p/service-context st/resource-type))
(defn create-user
[session-admin & {:keys [username PI:PASSWORD:<PASSWORD>END_PI email activated?]}]
(let [validation-link (atom nil)
href (str user-tpl/resource-type "/" email-password/registration-method)
href-create {:template {:href href
:password PI:PASSWORD:<PASSWORD>END_PI
:username username
:email email}}]
(with-redefs [email-sending/extract-smtp-cfg
(fn [_] {:host "PI:EMAIL:<EMAIL>END_PI"
:port 465
:ssl true
:user "admin"
:pass "PI:PASSWORD:<PASSWORD>END_PI"})
;; WARNING: This is a fragile! Regex matching to recover callback URL.
postal/send-message (fn [_ {:keys [body]}]
(let [url (->> body second :content
(re-matches #"(?s).*visit:\n\n\s+(.*?)\n.*")
second)]
(reset! validation-link url))
{:code 0, :error :SUCCESS, :message "OK"})]
(let [user-id (-> session-admin
(request (str p/service-context user/resource-type)
:request-method :post
:body (json/write-str href-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))]
(when activated?
(is (re-matches #"^email.*successfully validated$"
(-> session-admin
(request @validation-link)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body)
:message))))
user-id))))
;; verifies that a session can be updated internally
;; session setup is taken from the password session lifecycle test
(deftest check-session-update
(let [app (ltu/ring-app)
session-json (content-type (session app) "application/json")
session-admin (header session-json authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
session-anon (header session-json authn-info-header "user/unknown user/unknown group/nuvla-anon")
session-user (header session-json authn-info-header "user group/nuvla-user")
href (str st/resource-type "/password")
template-url (str p/service-context href)
name-attr "name"
description-attr "description"
tags-attr ["one", "two"]]
;; password session template must exist
(-> session-anon
(request template-url)
(ltu/body->edn)
(ltu/is-status 200))
;; anon with valid activated user can create session
(let [username "user/jane"
plaintext-password "PI:PASSWORD:<PASSWORD>END_PIaneJane-0"
valid-create {:name name-attr
:description description-attr
:tags tags-attr
:template {:href href
:username username
:password PI:PASSWORD:<PASSWORD>END_PI}}]
;; create a user
(create-user session-admin
:username username
:password PI:PASSWORD:<PASSWORD>END_PI
:activated? true
:email "PI:EMAIL:<EMAIL>END_PI")
; anonymous create must succeed
(let [resp (-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-set-cookie)
(ltu/is-status 201))
id (ltu/body-resource-id resp)
abs-url (ltu/location-url resp)
{:keys [name description tags] :as original-session}
(-> session-user
(header authn-info-header (str "user/user group/nuvla-user group/nuvla-anon " id))
(request abs-url)
(ltu/body->edn)
:response
:body)]
; check contents of session
(is (= name name-attr))
(is (= description description-attr))
(is (= tags tags-attr))
;; After the setup, NOW verify that the session can be updated!
(let [new-name "UPDATED SESSION NAME"
correct-session (assoc original-session :name new-name)]
(session-utils/update-session (:id original-session) correct-session)
(let [updated-session (-> session-user
(header authn-info-header (str "user/user group/nuvla-user group/nuvla-anon " id))
(request abs-url)
(ltu/body->edn)
:response
:body)]
(is (= new-name (:name updated-session)))
(is (not= (:updated original-session) (:updated updated-session)))
(is (= (dissoc correct-session :updated)
(dissoc updated-session :updated :updated-by)))))))))
|
[
{
"context": "hart_user\"\n :password \"anychart_pass\"}})\n\n\n(def prod-config (assoc-in base-config [:we",
"end": 530,
"score": 0.999348521232605,
"start": 517,
"tag": "PASSWORD",
"value": "anychart_pass"
}
] | src/sample/core.clj | anychart-integrations/anychart-clojure-sample | 15 | (ns sample.core
(:require [sample.db.core :as db]
[sample.web.core :as web]
[com.stuartsierra.component :as component])
(:gen-class))
(def base-config {:web {:port 9197
:debug true}
:jdbc {:subprotocol "postgresql"
:subname "//localhost:5432/anychart_sample"
:classname "org.postgresql.Driver"
:user "anychart_user"
:password "anychart_pass"}})
(def prod-config (assoc-in base-config [:web :debug] false))
(defn app-system
"App system with jdbc and http-kit web server"
[config]
(component/system-map
:jdbc (db/new-jdbc (:jdbc config))
:web (component/using (web/new-web (:web config)) [:jdbc])))
(def dev (app-system base-config))
(defn start
"Start dev system"
[]
(alter-var-root #'dev component/start))
(defn stop
"Stop dev system"
[]
(alter-var-root #'dev component/stop))
(defn -main
"Start prod system"
[]
(println "starting server http://localhost:9197/")
(component/start (app-system prod-config)))
| 100525 | (ns sample.core
(:require [sample.db.core :as db]
[sample.web.core :as web]
[com.stuartsierra.component :as component])
(:gen-class))
(def base-config {:web {:port 9197
:debug true}
:jdbc {:subprotocol "postgresql"
:subname "//localhost:5432/anychart_sample"
:classname "org.postgresql.Driver"
:user "anychart_user"
:password "<PASSWORD>"}})
(def prod-config (assoc-in base-config [:web :debug] false))
(defn app-system
"App system with jdbc and http-kit web server"
[config]
(component/system-map
:jdbc (db/new-jdbc (:jdbc config))
:web (component/using (web/new-web (:web config)) [:jdbc])))
(def dev (app-system base-config))
(defn start
"Start dev system"
[]
(alter-var-root #'dev component/start))
(defn stop
"Stop dev system"
[]
(alter-var-root #'dev component/stop))
(defn -main
"Start prod system"
[]
(println "starting server http://localhost:9197/")
(component/start (app-system prod-config)))
| true | (ns sample.core
(:require [sample.db.core :as db]
[sample.web.core :as web]
[com.stuartsierra.component :as component])
(:gen-class))
(def base-config {:web {:port 9197
:debug true}
:jdbc {:subprotocol "postgresql"
:subname "//localhost:5432/anychart_sample"
:classname "org.postgresql.Driver"
:user "anychart_user"
:password "PI:PASSWORD:<PASSWORD>END_PI"}})
(def prod-config (assoc-in base-config [:web :debug] false))
(defn app-system
"App system with jdbc and http-kit web server"
[config]
(component/system-map
:jdbc (db/new-jdbc (:jdbc config))
:web (component/using (web/new-web (:web config)) [:jdbc])))
(def dev (app-system base-config))
(defn start
"Start dev system"
[]
(alter-var-root #'dev component/start))
(defn stop
"Stop dev system"
[]
(alter-var-root #'dev component/stop))
(defn -main
"Start prod system"
[]
(println "starting server http://localhost:9197/")
(component/start (app-system prod-config)))
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :date \"2018-04-16\"\n ",
"end": 96,
"score": 0.700814425945282,
"start": 87,
"tag": "EMAIL",
"value": "wahpenayo"
},
{
"context": "-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :date \"2018-04-16\"\n :doc \"Common def",
"end": 113,
"score": 0.7262927293777466,
"start": 100,
"tag": "EMAIL",
"value": "gmail dot com"
}
] | src/test/clojure/taiga/test/regress/data/defs.clj | wahpenayo/taiga | 4 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "wahpenayo at gmail dot com"
:date "2018-04-16"
:doc "Common definitions for unit tests." }
taiga.test.regress.data.defs
(:require [clojure.java.io :as io]
[clojure.string :as s]
[clojure.pprint :as pp]
[clojure.test :as test]
[zana.api :as z]
[taiga.api :as taiga]
[taiga.test.regress.data.record :as record])
(:import [java.util Map]
[java.io File]
[clojure.lang IFn IFn$OD IFn$OOD]))
;;----------------------------------------------------------------
(defn options
([^Map attributes
^Map bindings
^IFn generator
^IFn$OD mean
sigma
n]
(let [n (int n)
sigma (double sigma)
data (z/map (generator mean sigma) (range (* 2 n)))
[train test] (z/split-at n data)
_ (test/is (== n (z/count train) (z/count test)))
m (int (z/count bindings))
;;_ (test/is (== 8 (z/count bindings)))
mtry (Math/min m (int (Math/round (Math/sqrt m))))
nterms 128
mincount 127
options {:data train
:test-data test
:attributes attributes
:nterms nterms
:mincount mincount
:mtry mtry}]
;;_ (test/is (== 10 (count (:attributes options))))
;;_ (test/is (== 3 (:mtry options)))
options))
([^Map attributes
^Map bindings
^IFn generator
^IFn$OD mean
sigma]
(options attributes bindings generator mean sigma (* 32 1024))))
;;----------------------------------------------------------------
(defn forest-file [nss options forest]
(let [tokens (s/split nss #"\.")
^File folder (apply io/file "tst" (butlast tokens))
_ (.mkdirs folder)
fname (last tokens)
file (File/createTempFile
(str fname
"-" (z/count (:data options))
"-" (taiga/nterms forest)
"-" (:mincount options)
"-" (:mtry options))
(str "." (:ext options "edn.gz"))
(io/file folder))]
(println (.getPath file))
file))
;;----------------------------------------------------------------
(defn affine-edn-file [nss]
(let [tokens (s/split nss #"\.")
^File folder (apply io/file "tst" (butlast tokens))
_ (.mkdirs folder)
fname (last tokens)
file (File/createTempFile
(str fname "-affine-")
".edn"
(io/file folder))]
(println (.getPath file))
file))
;;----------------------------------------------------------------
(defn linear-edn-file [nss]
(let [tokens (s/split nss #"\.")
^File folder (apply io/file "tst" (butlast tokens))
_ (.mkdirs folder)
fname (last tokens)
file (File/createTempFile
(str fname "-linear-")
".edn"
(io/file folder))]
(println (.getPath file))
file))
;;----------------------------------------------------------------
(defn json-test [nss options forest]
(let [json-file (forest-file nss
(assoc options :ext "json.gz")
forest)]
(taiga/write-json forest json-file)))
;;----------------------------------------------------------------
(defn edn-test [model edn-file]
(taiga/write-edn model edn-file)
(test/is (= model (taiga/read-edn edn-file))))
;;----------------------------------------------------------------
(defn prediction-file [nss options prefix model]
(let [tokens (s/split nss #"\.")
folder (apply io/file "tst" (butlast tokens))
fname (last tokens)
file (io/file folder
(str "predictions"
"-" prefix
"-" fname
"-" (z/count (:data options))
"-" (taiga/nterms model)
"-" (:mincount options)
"-" (:mtry options)
".tsv.gz"))]
(io/make-parents file)
file))
;;----------------------------------------------------------------
(defn predictions
(^Iterable [^IFn$OOD model bindings data k]
(z/map #(assoc % k (.invokePrim model bindings %)) data))
(^Iterable [^IFn$OD model data k]
(z/map #(assoc % k (.invokePrim model %)) data)))
;;----------------------------------------------------------------
(defn write-predictions [nss options prefix model predictions]
(record/write-tsv-file
predictions
(prediction-file nss options prefix model)))
;;----------------------------------------------------------------
(defn print-residual-summary
([^double p ^IFn$OD y ^IFn$OD yhat data]
(let [^IFn$OD residual (fn residual ^double [datum]
(- (.invokePrim y datum)
(.invokePrim yhat datum)))
residuals (z/map-to-doubles residual data)
n (z/count data)
results {:rmean (z/mean residuals)
:rmse (Math/sqrt (/ (z/l2-norm residuals) n))
:rmad (z/mean-absolute-difference y yhat data)
:rmqr (z/mean-qr-cost p y yhat data)
:rmrq (z/mean-rq-cost p y yhat data)}]
(pp/pprint results)
results))
([^IFn$OD y ^IFn$OD yhat data]
(print-residual-summary 0.5 y yhat data)))
;;;----------------------------------------------------------------
(defn by-nterms-file [nss options model]
(let [tokens (s/split nss #"\.")
folder (apply io/file "tst" (butlast tokens))
fname (last tokens)
file (io/file folder
(str "by-nterms"
"-" fname
"-" (z/count (:data options))
"-" (taiga/nterms model)
"-" (:mincount options)
"-" (:mtry options)
".tsv.gz"))]
(io/make-parents file)
file))
;;----------------------------------------------------------------
(defn by-nterms [nss options forest bindings]
(let [nterms (taiga/nterms forest)
train (:data options)
test (:test-data options)
delta 4]
(with-open [w (z/print-writer
(by-nterms-file nss options forest))]
(.println w
(s/join "\t" ["nterms" "trainTest" "mad" "mmad"]))
(loop [n 1]
(when (< n nterms)
(when (zero? (rem n 16)) (println "nterms:" n))
(let [^IFn$OOD model (taiga/take-terms n forest)
^IFn$OD yhat (fn yhat ^double [datum]
(.invokePrim model
bindings datum))]
(.println w
(s/join
"\t"
[n "train"
(z/mean-absolute-difference
record/y yhat train)
(z/mean-absolute-difference
record/mean yhat train)]))
(.println w
(s/join
"\t"
[n "test"
(z/mean-absolute-difference
record/y yhat test)
(z/mean-absolute-difference
record/mean yhat test)])))
(recur (+ delta n)))))))
;;----------------------------------------------------------------
| 14443 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<EMAIL> at <EMAIL>"
:date "2018-04-16"
:doc "Common definitions for unit tests." }
taiga.test.regress.data.defs
(:require [clojure.java.io :as io]
[clojure.string :as s]
[clojure.pprint :as pp]
[clojure.test :as test]
[zana.api :as z]
[taiga.api :as taiga]
[taiga.test.regress.data.record :as record])
(:import [java.util Map]
[java.io File]
[clojure.lang IFn IFn$OD IFn$OOD]))
;;----------------------------------------------------------------
(defn options
([^Map attributes
^Map bindings
^IFn generator
^IFn$OD mean
sigma
n]
(let [n (int n)
sigma (double sigma)
data (z/map (generator mean sigma) (range (* 2 n)))
[train test] (z/split-at n data)
_ (test/is (== n (z/count train) (z/count test)))
m (int (z/count bindings))
;;_ (test/is (== 8 (z/count bindings)))
mtry (Math/min m (int (Math/round (Math/sqrt m))))
nterms 128
mincount 127
options {:data train
:test-data test
:attributes attributes
:nterms nterms
:mincount mincount
:mtry mtry}]
;;_ (test/is (== 10 (count (:attributes options))))
;;_ (test/is (== 3 (:mtry options)))
options))
([^Map attributes
^Map bindings
^IFn generator
^IFn$OD mean
sigma]
(options attributes bindings generator mean sigma (* 32 1024))))
;;----------------------------------------------------------------
(defn forest-file [nss options forest]
(let [tokens (s/split nss #"\.")
^File folder (apply io/file "tst" (butlast tokens))
_ (.mkdirs folder)
fname (last tokens)
file (File/createTempFile
(str fname
"-" (z/count (:data options))
"-" (taiga/nterms forest)
"-" (:mincount options)
"-" (:mtry options))
(str "." (:ext options "edn.gz"))
(io/file folder))]
(println (.getPath file))
file))
;;----------------------------------------------------------------
(defn affine-edn-file [nss]
(let [tokens (s/split nss #"\.")
^File folder (apply io/file "tst" (butlast tokens))
_ (.mkdirs folder)
fname (last tokens)
file (File/createTempFile
(str fname "-affine-")
".edn"
(io/file folder))]
(println (.getPath file))
file))
;;----------------------------------------------------------------
(defn linear-edn-file [nss]
(let [tokens (s/split nss #"\.")
^File folder (apply io/file "tst" (butlast tokens))
_ (.mkdirs folder)
fname (last tokens)
file (File/createTempFile
(str fname "-linear-")
".edn"
(io/file folder))]
(println (.getPath file))
file))
;;----------------------------------------------------------------
(defn json-test [nss options forest]
(let [json-file (forest-file nss
(assoc options :ext "json.gz")
forest)]
(taiga/write-json forest json-file)))
;;----------------------------------------------------------------
(defn edn-test [model edn-file]
(taiga/write-edn model edn-file)
(test/is (= model (taiga/read-edn edn-file))))
;;----------------------------------------------------------------
(defn prediction-file [nss options prefix model]
(let [tokens (s/split nss #"\.")
folder (apply io/file "tst" (butlast tokens))
fname (last tokens)
file (io/file folder
(str "predictions"
"-" prefix
"-" fname
"-" (z/count (:data options))
"-" (taiga/nterms model)
"-" (:mincount options)
"-" (:mtry options)
".tsv.gz"))]
(io/make-parents file)
file))
;;----------------------------------------------------------------
(defn predictions
(^Iterable [^IFn$OOD model bindings data k]
(z/map #(assoc % k (.invokePrim model bindings %)) data))
(^Iterable [^IFn$OD model data k]
(z/map #(assoc % k (.invokePrim model %)) data)))
;;----------------------------------------------------------------
(defn write-predictions [nss options prefix model predictions]
(record/write-tsv-file
predictions
(prediction-file nss options prefix model)))
;;----------------------------------------------------------------
(defn print-residual-summary
([^double p ^IFn$OD y ^IFn$OD yhat data]
(let [^IFn$OD residual (fn residual ^double [datum]
(- (.invokePrim y datum)
(.invokePrim yhat datum)))
residuals (z/map-to-doubles residual data)
n (z/count data)
results {:rmean (z/mean residuals)
:rmse (Math/sqrt (/ (z/l2-norm residuals) n))
:rmad (z/mean-absolute-difference y yhat data)
:rmqr (z/mean-qr-cost p y yhat data)
:rmrq (z/mean-rq-cost p y yhat data)}]
(pp/pprint results)
results))
([^IFn$OD y ^IFn$OD yhat data]
(print-residual-summary 0.5 y yhat data)))
;;;----------------------------------------------------------------
(defn by-nterms-file [nss options model]
(let [tokens (s/split nss #"\.")
folder (apply io/file "tst" (butlast tokens))
fname (last tokens)
file (io/file folder
(str "by-nterms"
"-" fname
"-" (z/count (:data options))
"-" (taiga/nterms model)
"-" (:mincount options)
"-" (:mtry options)
".tsv.gz"))]
(io/make-parents file)
file))
;;----------------------------------------------------------------
(defn by-nterms [nss options forest bindings]
(let [nterms (taiga/nterms forest)
train (:data options)
test (:test-data options)
delta 4]
(with-open [w (z/print-writer
(by-nterms-file nss options forest))]
(.println w
(s/join "\t" ["nterms" "trainTest" "mad" "mmad"]))
(loop [n 1]
(when (< n nterms)
(when (zero? (rem n 16)) (println "nterms:" n))
(let [^IFn$OOD model (taiga/take-terms n forest)
^IFn$OD yhat (fn yhat ^double [datum]
(.invokePrim model
bindings datum))]
(.println w
(s/join
"\t"
[n "train"
(z/mean-absolute-difference
record/y yhat train)
(z/mean-absolute-difference
record/mean yhat train)]))
(.println w
(s/join
"\t"
[n "test"
(z/mean-absolute-difference
record/y yhat test)
(z/mean-absolute-difference
record/mean yhat test)])))
(recur (+ delta n)))))))
;;----------------------------------------------------------------
| true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:EMAIL:<EMAIL>END_PI at PI:EMAIL:<EMAIL>END_PI"
:date "2018-04-16"
:doc "Common definitions for unit tests." }
taiga.test.regress.data.defs
(:require [clojure.java.io :as io]
[clojure.string :as s]
[clojure.pprint :as pp]
[clojure.test :as test]
[zana.api :as z]
[taiga.api :as taiga]
[taiga.test.regress.data.record :as record])
(:import [java.util Map]
[java.io File]
[clojure.lang IFn IFn$OD IFn$OOD]))
;;----------------------------------------------------------------
(defn options
([^Map attributes
^Map bindings
^IFn generator
^IFn$OD mean
sigma
n]
(let [n (int n)
sigma (double sigma)
data (z/map (generator mean sigma) (range (* 2 n)))
[train test] (z/split-at n data)
_ (test/is (== n (z/count train) (z/count test)))
m (int (z/count bindings))
;;_ (test/is (== 8 (z/count bindings)))
mtry (Math/min m (int (Math/round (Math/sqrt m))))
nterms 128
mincount 127
options {:data train
:test-data test
:attributes attributes
:nterms nterms
:mincount mincount
:mtry mtry}]
;;_ (test/is (== 10 (count (:attributes options))))
;;_ (test/is (== 3 (:mtry options)))
options))
([^Map attributes
^Map bindings
^IFn generator
^IFn$OD mean
sigma]
(options attributes bindings generator mean sigma (* 32 1024))))
;;----------------------------------------------------------------
(defn forest-file [nss options forest]
(let [tokens (s/split nss #"\.")
^File folder (apply io/file "tst" (butlast tokens))
_ (.mkdirs folder)
fname (last tokens)
file (File/createTempFile
(str fname
"-" (z/count (:data options))
"-" (taiga/nterms forest)
"-" (:mincount options)
"-" (:mtry options))
(str "." (:ext options "edn.gz"))
(io/file folder))]
(println (.getPath file))
file))
;;----------------------------------------------------------------
(defn affine-edn-file [nss]
(let [tokens (s/split nss #"\.")
^File folder (apply io/file "tst" (butlast tokens))
_ (.mkdirs folder)
fname (last tokens)
file (File/createTempFile
(str fname "-affine-")
".edn"
(io/file folder))]
(println (.getPath file))
file))
;;----------------------------------------------------------------
(defn linear-edn-file [nss]
(let [tokens (s/split nss #"\.")
^File folder (apply io/file "tst" (butlast tokens))
_ (.mkdirs folder)
fname (last tokens)
file (File/createTempFile
(str fname "-linear-")
".edn"
(io/file folder))]
(println (.getPath file))
file))
;;----------------------------------------------------------------
(defn json-test [nss options forest]
(let [json-file (forest-file nss
(assoc options :ext "json.gz")
forest)]
(taiga/write-json forest json-file)))
;;----------------------------------------------------------------
(defn edn-test [model edn-file]
(taiga/write-edn model edn-file)
(test/is (= model (taiga/read-edn edn-file))))
;;----------------------------------------------------------------
(defn prediction-file [nss options prefix model]
(let [tokens (s/split nss #"\.")
folder (apply io/file "tst" (butlast tokens))
fname (last tokens)
file (io/file folder
(str "predictions"
"-" prefix
"-" fname
"-" (z/count (:data options))
"-" (taiga/nterms model)
"-" (:mincount options)
"-" (:mtry options)
".tsv.gz"))]
(io/make-parents file)
file))
;;----------------------------------------------------------------
(defn predictions
(^Iterable [^IFn$OOD model bindings data k]
(z/map #(assoc % k (.invokePrim model bindings %)) data))
(^Iterable [^IFn$OD model data k]
(z/map #(assoc % k (.invokePrim model %)) data)))
;;----------------------------------------------------------------
(defn write-predictions [nss options prefix model predictions]
(record/write-tsv-file
predictions
(prediction-file nss options prefix model)))
;;----------------------------------------------------------------
(defn print-residual-summary
([^double p ^IFn$OD y ^IFn$OD yhat data]
(let [^IFn$OD residual (fn residual ^double [datum]
(- (.invokePrim y datum)
(.invokePrim yhat datum)))
residuals (z/map-to-doubles residual data)
n (z/count data)
results {:rmean (z/mean residuals)
:rmse (Math/sqrt (/ (z/l2-norm residuals) n))
:rmad (z/mean-absolute-difference y yhat data)
:rmqr (z/mean-qr-cost p y yhat data)
:rmrq (z/mean-rq-cost p y yhat data)}]
(pp/pprint results)
results))
([^IFn$OD y ^IFn$OD yhat data]
(print-residual-summary 0.5 y yhat data)))
;;;----------------------------------------------------------------
(defn by-nterms-file [nss options model]
(let [tokens (s/split nss #"\.")
folder (apply io/file "tst" (butlast tokens))
fname (last tokens)
file (io/file folder
(str "by-nterms"
"-" fname
"-" (z/count (:data options))
"-" (taiga/nterms model)
"-" (:mincount options)
"-" (:mtry options)
".tsv.gz"))]
(io/make-parents file)
file))
;;----------------------------------------------------------------
(defn by-nterms [nss options forest bindings]
(let [nterms (taiga/nterms forest)
train (:data options)
test (:test-data options)
delta 4]
(with-open [w (z/print-writer
(by-nterms-file nss options forest))]
(.println w
(s/join "\t" ["nterms" "trainTest" "mad" "mmad"]))
(loop [n 1]
(when (< n nterms)
(when (zero? (rem n 16)) (println "nterms:" n))
(let [^IFn$OOD model (taiga/take-terms n forest)
^IFn$OD yhat (fn yhat ^double [datum]
(.invokePrim model
bindings datum))]
(.println w
(s/join
"\t"
[n "train"
(z/mean-absolute-difference
record/y yhat train)
(z/mean-absolute-difference
record/mean yhat train)]))
(.println w
(s/join
"\t"
[n "test"
(z/mean-absolute-difference
record/y yhat test)
(z/mean-absolute-difference
record/mean yhat test)])))
(recur (+ delta n)))))))
;;----------------------------------------------------------------
|
[
{
"context": "x0rz3jtxtEre/giphy.gif\"}]\n [c/h1 \"My name is Uģis\"]\n [:section {:style {:align-self \"flex-sta",
"end": 611,
"score": 0.9994019269943237,
"start": 607,
"tag": "NAME",
"value": "Uģis"
},
{
"context": " 20}}\n [:li\n [:a {:href \"mailto:berzinsu@gmail.com\"}\n \"berzinsu@gmail.com\"]]]]\n [c/h",
"end": 1079,
"score": 0.9999226331710815,
"start": 1061,
"tag": "EMAIL",
"value": "berzinsu@gmail.com"
},
{
"context": "a {:href \"mailto:berzinsu@gmail.com\"}\n \"berzinsu@gmail.com\"]]]]\n [c/h3\n \"More coming soon...\"]]",
"end": 1112,
"score": 0.9999241828918457,
"start": 1094,
"tag": "EMAIL",
"value": "berzinsu@gmail.com"
}
] | src/ugis_be/core.cljs | BerzinsU/ugis.be | 0 | (ns ugis_be.core
(:require [reagent.core :as reagent]
[re-frame.core :as rf]
[ugis_be.components :as c]))
;; -------------------------
;; Views
(defn home-page []
[:div {:style {:display "flex"
:flex-direction "column"
:align-items "center"}}
[:img {:style {:margin-bottom 25
:max-width "100%"
:width "auto"
:height "auto"}
:src "https://media2.giphy.com/media/Nx0rz3jtxtEre/giphy.gif"}]
[c/h1 "My name is Uģis"]
[:section {:style {:align-self "flex-start"}}
[c/h2 "Current endevours:"]
[:ul {:style {:margin-bottom 25
:padding-left 20}}
[:li "Making this page.... (now on ClojureScript)"]]]
[:section {:style {:align-self "flex-start"}}
[c/h2 "Where to contact:"]
[:ul {:style {:margin-bottom 25
:padding-left 20}}
[:li
[:a {:href "mailto:berzinsu@gmail.com"}
"berzinsu@gmail.com"]]]]
[c/h3
"More coming soon..."]])
;; -------------------------
;; Initialize app
(defn render
[]
(reagent/render [home-page]
(js/document.getElementById "app")))
(defn ^:dev/after-load clear-cache-and-render!
[]
;; The `:dev/after-load` metadata causes this function to be called
;; after shadow-cljs hot-reloads code. We force a UI update by clearing
;; the Reframe subscription cache.
(rf/clear-subscription-cache!)
(render))
(defn run
[]
(render)) ;; mount the application's ui into '<div id="app" />'
| 114326 | (ns ugis_be.core
(:require [reagent.core :as reagent]
[re-frame.core :as rf]
[ugis_be.components :as c]))
;; -------------------------
;; Views
(defn home-page []
[:div {:style {:display "flex"
:flex-direction "column"
:align-items "center"}}
[:img {:style {:margin-bottom 25
:max-width "100%"
:width "auto"
:height "auto"}
:src "https://media2.giphy.com/media/Nx0rz3jtxtEre/giphy.gif"}]
[c/h1 "My name is <NAME>"]
[:section {:style {:align-self "flex-start"}}
[c/h2 "Current endevours:"]
[:ul {:style {:margin-bottom 25
:padding-left 20}}
[:li "Making this page.... (now on ClojureScript)"]]]
[:section {:style {:align-self "flex-start"}}
[c/h2 "Where to contact:"]
[:ul {:style {:margin-bottom 25
:padding-left 20}}
[:li
[:a {:href "mailto:<EMAIL>"}
"<EMAIL>"]]]]
[c/h3
"More coming soon..."]])
;; -------------------------
;; Initialize app
(defn render
[]
(reagent/render [home-page]
(js/document.getElementById "app")))
(defn ^:dev/after-load clear-cache-and-render!
[]
;; The `:dev/after-load` metadata causes this function to be called
;; after shadow-cljs hot-reloads code. We force a UI update by clearing
;; the Reframe subscription cache.
(rf/clear-subscription-cache!)
(render))
(defn run
[]
(render)) ;; mount the application's ui into '<div id="app" />'
| true | (ns ugis_be.core
(:require [reagent.core :as reagent]
[re-frame.core :as rf]
[ugis_be.components :as c]))
;; -------------------------
;; Views
(defn home-page []
[:div {:style {:display "flex"
:flex-direction "column"
:align-items "center"}}
[:img {:style {:margin-bottom 25
:max-width "100%"
:width "auto"
:height "auto"}
:src "https://media2.giphy.com/media/Nx0rz3jtxtEre/giphy.gif"}]
[c/h1 "My name is PI:NAME:<NAME>END_PI"]
[:section {:style {:align-self "flex-start"}}
[c/h2 "Current endevours:"]
[:ul {:style {:margin-bottom 25
:padding-left 20}}
[:li "Making this page.... (now on ClojureScript)"]]]
[:section {:style {:align-self "flex-start"}}
[c/h2 "Where to contact:"]
[:ul {:style {:margin-bottom 25
:padding-left 20}}
[:li
[:a {:href "mailto:PI:EMAIL:<EMAIL>END_PI"}
"PI:EMAIL:<EMAIL>END_PI"]]]]
[c/h3
"More coming soon..."]])
;; -------------------------
;; Initialize app
(defn render
[]
(reagent/render [home-page]
(js/document.getElementById "app")))
(defn ^:dev/after-load clear-cache-and-render!
[]
;; The `:dev/after-load` metadata causes this function to be called
;; after shadow-cljs hot-reloads code. We force a UI update by clearing
;; the Reframe subscription cache.
(rf/clear-subscription-cache!)
(render))
(defn run
[]
(render)) ;; mount the application's ui into '<div id="app" />'
|
[
{
"context": "ork\"))\n\n(def discuss-fallback \"https://github.com/borkdude/blog/discussions/categories/posts\")\n\n(doseq [{:ke",
"end": 1969,
"score": 0.9988023638725281,
"start": 1961,
"tag": "USERNAME",
"value": "borkdude"
},
{
"context": "ot]\n [::atom/author\n [::atom/name \"Michiel Borkent\"]]\n (for [{:keys [title date file preview]",
"end": 5900,
"score": 0.9998951554298401,
"start": 5885,
"tag": "NAME",
"value": "Michiel Borkent"
}
] | render.clj | fuse-code/blog | 14 | (ns render
(:require
[babashka.fs :as fs]
[clojure.data.xml :as xml]
[clojure.edn :as edn]
[clojure.string :as str]
[hiccup2.core :as hiccup]
[highlighter :as h]
[markdown.core :as md]
[selmer.parser :as selmer]))
(def posts (sort-by :date (comp - compare)
(edn/read-string (format "[%s]"
(slurp "posts.edn")))))
(def out-dir "public")
(def base-html
(slurp "templates/base.html"))
;;;; Sync images and CSS
(def asset-dir (fs/create-dirs (fs/file out-dir "assets")))
(fs/copy-tree "assets" asset-dir {:replace-existing true})
(spit (fs/file out-dir "style.css")
(slurp "templates/style.css"))
;;;; Generate posts from markdown
(def post-template
"<h1>{{title}}</h1>
{{body | safe }}
<p>Discuss this post <a href=\"{{discuss}}\">here</a>.</p>
<p><i>Published: {{date}}</i></p>
")
(defn markdown->html [file]
(let [_ (println "Processing markdown for file:" (str file))
markdown (slurp file)
markdown (h/highlight-clojure markdown)
;; make links without markup clickable
markdown (str/replace markdown #"http[A-Za-z0-9/:.=#?_-]+([\s])"
(fn [[match ws]]
(format "[%s](%s)%s"
(str/trim match)
(str/trim match)
ws)))
;; allow links with markup over multiple lines
markdown (str/replace markdown #"\[[^\]]+\n"
(fn [match]
(str/replace match "\n" "$$RET$$")))
html (md/md-to-html-string markdown)
html (str/replace html "$$RET$$" "\n")]
html))
;; re-used when generating atom.xml
(def bodies (atom {}))
(defn html-file [file]
(str/replace file ".md" ".html"))
(fs/create-dirs (fs/file ".work"))
(def discuss-fallback "https://github.com/borkdude/blog/discussions/categories/posts")
(doseq [{:keys [file title date legacy discuss]
:or {discuss discuss-fallback}}
posts]
(let [cache-file (fs/file ".work" (html-file file))
markdown-file (fs/file "posts" file)
stale? (seq (fs/modified-since cache-file
[markdown-file
"posts.edn"
"templates"
"render.clj"
"highlighter.clj"]))
body (if stale?
(let [body (markdown->html markdown-file)]
(spit cache-file body)
body)
(slurp cache-file))
_ (swap! bodies assoc file body)
body (selmer/render post-template {:body body
:title title
:date date
:discuss discuss})
html (selmer/render base-html
{:title title
:body body})
html-file (str/replace file ".md" ".html")]
(spit (fs/file out-dir html-file) html)
(let [legacy-dir (fs/file out-dir (str/replace date "-" "/")
(str/replace file ".md" "")
)]
(when legacy
(fs/create-dirs legacy-dir)
(let [redirect-html (selmer/render"
<html><head>
<meta http-equiv=\"refresh\" content=\"0; URL=/{{new_url}}\" />
</head></html>"
{:new_url html-file})]
(spit (fs/file (fs/file legacy-dir "index.html")) redirect-html))))))
;;;; Generate archive page
(defn post-links []
[:div {:style "width: 600px;"}
[:h1 "Archive"]
[:ul.index
(for [{:keys [file title date preview]} posts
:when (not preview)]
[:li [:span
[:a {:href (str/replace file ".md" ".html")}
title]
" - "
date]])]])
(spit (fs/file out-dir "archive.html")
(selmer/render base-html
{:skip-archive true
:body (hiccup/html (post-links))}))
;;;; Generate index page with last 3 posts
(defn index []
(for [{:keys [file title date preview discuss]
:or {discuss discuss-fallback}} (take 3 posts)
:when (not preview)]
[:div
[:h1 [:a {:href (str/replace file ".md" ".html")}
title]]
(get @bodies file)
[:p "Discuss this post " [:a {:href discuss} "here"] "."]
[:p [:i "Published: " date]]]))
(spit (fs/file out-dir "index.html")
(selmer/render base-html
{:body (hiccup/html {:escape-strings? false} (index))}))
;;;; Generate atom feeds
(xml/alias-uri 'atom "http://www.w3.org/2005/Atom")
(import java.time.format.DateTimeFormatter)
(defn rfc-3339-now []
(let [fmt (DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ssxxx")
now (java.time.ZonedDateTime/now java.time.ZoneOffset/UTC)]
(.format now fmt)))
(defn rfc-3339 [yyyy-MM-dd]
(let [in-fmt (DateTimeFormatter/ofPattern "yyyy-MM-dd")
local-date (java.time.LocalDate/parse yyyy-MM-dd in-fmt)
fmt (DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ssxxx")
now (java.time.ZonedDateTime/of (.atTime local-date 23 59 59) java.time.ZoneOffset/UTC)]
(.format now fmt)))
(def blog-root "https://blog.michielborkent.nl/")
(defn atom-feed
;; validate at https://validator.w3.org/feed/check.cgi
[posts]
(-> (xml/sexp-as-element
[::atom/feed
{:xmlns "http://www.w3.org/2005/Atom"}
[::atom/title "REPL adventures"]
[::atom/link {:href (str blog-root "atom.xml") :rel "self"}]
[::atom/link {:href blog-root}]
[::atom/updated (rfc-3339-now)]
[::atom/id blog-root]
[::atom/author
[::atom/name "Michiel Borkent"]]
(for [{:keys [title date file preview]} posts
:when (not preview)
:let [html (str/replace file ".md" ".html")
link (str blog-root html)]]
[::atom/entry
[::atom/id link]
[::atom/link {:href link}]
[::atom/title title]
[::atom/updated (rfc-3339 date)]
[::atom/content {:type "html"}
[:-cdata (get @bodies file)]]])])
xml/indent-str))
(spit (fs/file out-dir "atom.xml") (atom-feed posts))
(spit (fs/file out-dir "planetclojure.xml")
(atom-feed (filter
(fn [post]
(some (:categories post) ["clojure" "clojurescript"]))
posts)))
;; for JVM Clojure:
(defn -main [& _args]
(System/exit 0))
| 63362 | (ns render
(:require
[babashka.fs :as fs]
[clojure.data.xml :as xml]
[clojure.edn :as edn]
[clojure.string :as str]
[hiccup2.core :as hiccup]
[highlighter :as h]
[markdown.core :as md]
[selmer.parser :as selmer]))
(def posts (sort-by :date (comp - compare)
(edn/read-string (format "[%s]"
(slurp "posts.edn")))))
(def out-dir "public")
(def base-html
(slurp "templates/base.html"))
;;;; Sync images and CSS
(def asset-dir (fs/create-dirs (fs/file out-dir "assets")))
(fs/copy-tree "assets" asset-dir {:replace-existing true})
(spit (fs/file out-dir "style.css")
(slurp "templates/style.css"))
;;;; Generate posts from markdown
(def post-template
"<h1>{{title}}</h1>
{{body | safe }}
<p>Discuss this post <a href=\"{{discuss}}\">here</a>.</p>
<p><i>Published: {{date}}</i></p>
")
(defn markdown->html [file]
(let [_ (println "Processing markdown for file:" (str file))
markdown (slurp file)
markdown (h/highlight-clojure markdown)
;; make links without markup clickable
markdown (str/replace markdown #"http[A-Za-z0-9/:.=#?_-]+([\s])"
(fn [[match ws]]
(format "[%s](%s)%s"
(str/trim match)
(str/trim match)
ws)))
;; allow links with markup over multiple lines
markdown (str/replace markdown #"\[[^\]]+\n"
(fn [match]
(str/replace match "\n" "$$RET$$")))
html (md/md-to-html-string markdown)
html (str/replace html "$$RET$$" "\n")]
html))
;; re-used when generating atom.xml
(def bodies (atom {}))
(defn html-file [file]
(str/replace file ".md" ".html"))
(fs/create-dirs (fs/file ".work"))
(def discuss-fallback "https://github.com/borkdude/blog/discussions/categories/posts")
(doseq [{:keys [file title date legacy discuss]
:or {discuss discuss-fallback}}
posts]
(let [cache-file (fs/file ".work" (html-file file))
markdown-file (fs/file "posts" file)
stale? (seq (fs/modified-since cache-file
[markdown-file
"posts.edn"
"templates"
"render.clj"
"highlighter.clj"]))
body (if stale?
(let [body (markdown->html markdown-file)]
(spit cache-file body)
body)
(slurp cache-file))
_ (swap! bodies assoc file body)
body (selmer/render post-template {:body body
:title title
:date date
:discuss discuss})
html (selmer/render base-html
{:title title
:body body})
html-file (str/replace file ".md" ".html")]
(spit (fs/file out-dir html-file) html)
(let [legacy-dir (fs/file out-dir (str/replace date "-" "/")
(str/replace file ".md" "")
)]
(when legacy
(fs/create-dirs legacy-dir)
(let [redirect-html (selmer/render"
<html><head>
<meta http-equiv=\"refresh\" content=\"0; URL=/{{new_url}}\" />
</head></html>"
{:new_url html-file})]
(spit (fs/file (fs/file legacy-dir "index.html")) redirect-html))))))
;;;; Generate archive page
(defn post-links []
[:div {:style "width: 600px;"}
[:h1 "Archive"]
[:ul.index
(for [{:keys [file title date preview]} posts
:when (not preview)]
[:li [:span
[:a {:href (str/replace file ".md" ".html")}
title]
" - "
date]])]])
(spit (fs/file out-dir "archive.html")
(selmer/render base-html
{:skip-archive true
:body (hiccup/html (post-links))}))
;;;; Generate index page with last 3 posts
(defn index []
(for [{:keys [file title date preview discuss]
:or {discuss discuss-fallback}} (take 3 posts)
:when (not preview)]
[:div
[:h1 [:a {:href (str/replace file ".md" ".html")}
title]]
(get @bodies file)
[:p "Discuss this post " [:a {:href discuss} "here"] "."]
[:p [:i "Published: " date]]]))
(spit (fs/file out-dir "index.html")
(selmer/render base-html
{:body (hiccup/html {:escape-strings? false} (index))}))
;;;; Generate atom feeds
(xml/alias-uri 'atom "http://www.w3.org/2005/Atom")
(import java.time.format.DateTimeFormatter)
(defn rfc-3339-now []
(let [fmt (DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ssxxx")
now (java.time.ZonedDateTime/now java.time.ZoneOffset/UTC)]
(.format now fmt)))
(defn rfc-3339 [yyyy-MM-dd]
(let [in-fmt (DateTimeFormatter/ofPattern "yyyy-MM-dd")
local-date (java.time.LocalDate/parse yyyy-MM-dd in-fmt)
fmt (DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ssxxx")
now (java.time.ZonedDateTime/of (.atTime local-date 23 59 59) java.time.ZoneOffset/UTC)]
(.format now fmt)))
(def blog-root "https://blog.michielborkent.nl/")
(defn atom-feed
;; validate at https://validator.w3.org/feed/check.cgi
[posts]
(-> (xml/sexp-as-element
[::atom/feed
{:xmlns "http://www.w3.org/2005/Atom"}
[::atom/title "REPL adventures"]
[::atom/link {:href (str blog-root "atom.xml") :rel "self"}]
[::atom/link {:href blog-root}]
[::atom/updated (rfc-3339-now)]
[::atom/id blog-root]
[::atom/author
[::atom/name "<NAME>"]]
(for [{:keys [title date file preview]} posts
:when (not preview)
:let [html (str/replace file ".md" ".html")
link (str blog-root html)]]
[::atom/entry
[::atom/id link]
[::atom/link {:href link}]
[::atom/title title]
[::atom/updated (rfc-3339 date)]
[::atom/content {:type "html"}
[:-cdata (get @bodies file)]]])])
xml/indent-str))
(spit (fs/file out-dir "atom.xml") (atom-feed posts))
(spit (fs/file out-dir "planetclojure.xml")
(atom-feed (filter
(fn [post]
(some (:categories post) ["clojure" "clojurescript"]))
posts)))
;; for JVM Clojure:
(defn -main [& _args]
(System/exit 0))
| true | (ns render
(:require
[babashka.fs :as fs]
[clojure.data.xml :as xml]
[clojure.edn :as edn]
[clojure.string :as str]
[hiccup2.core :as hiccup]
[highlighter :as h]
[markdown.core :as md]
[selmer.parser :as selmer]))
(def posts (sort-by :date (comp - compare)
(edn/read-string (format "[%s]"
(slurp "posts.edn")))))
(def out-dir "public")
(def base-html
(slurp "templates/base.html"))
;;;; Sync images and CSS
(def asset-dir (fs/create-dirs (fs/file out-dir "assets")))
(fs/copy-tree "assets" asset-dir {:replace-existing true})
(spit (fs/file out-dir "style.css")
(slurp "templates/style.css"))
;;;; Generate posts from markdown
(def post-template
"<h1>{{title}}</h1>
{{body | safe }}
<p>Discuss this post <a href=\"{{discuss}}\">here</a>.</p>
<p><i>Published: {{date}}</i></p>
")
(defn markdown->html [file]
(let [_ (println "Processing markdown for file:" (str file))
markdown (slurp file)
markdown (h/highlight-clojure markdown)
;; make links without markup clickable
markdown (str/replace markdown #"http[A-Za-z0-9/:.=#?_-]+([\s])"
(fn [[match ws]]
(format "[%s](%s)%s"
(str/trim match)
(str/trim match)
ws)))
;; allow links with markup over multiple lines
markdown (str/replace markdown #"\[[^\]]+\n"
(fn [match]
(str/replace match "\n" "$$RET$$")))
html (md/md-to-html-string markdown)
html (str/replace html "$$RET$$" "\n")]
html))
;; re-used when generating atom.xml
(def bodies (atom {}))
(defn html-file [file]
(str/replace file ".md" ".html"))
(fs/create-dirs (fs/file ".work"))
(def discuss-fallback "https://github.com/borkdude/blog/discussions/categories/posts")
(doseq [{:keys [file title date legacy discuss]
:or {discuss discuss-fallback}}
posts]
(let [cache-file (fs/file ".work" (html-file file))
markdown-file (fs/file "posts" file)
stale? (seq (fs/modified-since cache-file
[markdown-file
"posts.edn"
"templates"
"render.clj"
"highlighter.clj"]))
body (if stale?
(let [body (markdown->html markdown-file)]
(spit cache-file body)
body)
(slurp cache-file))
_ (swap! bodies assoc file body)
body (selmer/render post-template {:body body
:title title
:date date
:discuss discuss})
html (selmer/render base-html
{:title title
:body body})
html-file (str/replace file ".md" ".html")]
(spit (fs/file out-dir html-file) html)
(let [legacy-dir (fs/file out-dir (str/replace date "-" "/")
(str/replace file ".md" "")
)]
(when legacy
(fs/create-dirs legacy-dir)
(let [redirect-html (selmer/render"
<html><head>
<meta http-equiv=\"refresh\" content=\"0; URL=/{{new_url}}\" />
</head></html>"
{:new_url html-file})]
(spit (fs/file (fs/file legacy-dir "index.html")) redirect-html))))))
;;;; Generate archive page
(defn post-links []
[:div {:style "width: 600px;"}
[:h1 "Archive"]
[:ul.index
(for [{:keys [file title date preview]} posts
:when (not preview)]
[:li [:span
[:a {:href (str/replace file ".md" ".html")}
title]
" - "
date]])]])
(spit (fs/file out-dir "archive.html")
(selmer/render base-html
{:skip-archive true
:body (hiccup/html (post-links))}))
;;;; Generate index page with last 3 posts
(defn index []
(for [{:keys [file title date preview discuss]
:or {discuss discuss-fallback}} (take 3 posts)
:when (not preview)]
[:div
[:h1 [:a {:href (str/replace file ".md" ".html")}
title]]
(get @bodies file)
[:p "Discuss this post " [:a {:href discuss} "here"] "."]
[:p [:i "Published: " date]]]))
(spit (fs/file out-dir "index.html")
(selmer/render base-html
{:body (hiccup/html {:escape-strings? false} (index))}))
;;;; Generate atom feeds
(xml/alias-uri 'atom "http://www.w3.org/2005/Atom")
(import java.time.format.DateTimeFormatter)
(defn rfc-3339-now []
(let [fmt (DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ssxxx")
now (java.time.ZonedDateTime/now java.time.ZoneOffset/UTC)]
(.format now fmt)))
(defn rfc-3339 [yyyy-MM-dd]
(let [in-fmt (DateTimeFormatter/ofPattern "yyyy-MM-dd")
local-date (java.time.LocalDate/parse yyyy-MM-dd in-fmt)
fmt (DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ssxxx")
now (java.time.ZonedDateTime/of (.atTime local-date 23 59 59) java.time.ZoneOffset/UTC)]
(.format now fmt)))
(def blog-root "https://blog.michielborkent.nl/")
(defn atom-feed
;; validate at https://validator.w3.org/feed/check.cgi
[posts]
(-> (xml/sexp-as-element
[::atom/feed
{:xmlns "http://www.w3.org/2005/Atom"}
[::atom/title "REPL adventures"]
[::atom/link {:href (str blog-root "atom.xml") :rel "self"}]
[::atom/link {:href blog-root}]
[::atom/updated (rfc-3339-now)]
[::atom/id blog-root]
[::atom/author
[::atom/name "PI:NAME:<NAME>END_PI"]]
(for [{:keys [title date file preview]} posts
:when (not preview)
:let [html (str/replace file ".md" ".html")
link (str blog-root html)]]
[::atom/entry
[::atom/id link]
[::atom/link {:href link}]
[::atom/title title]
[::atom/updated (rfc-3339 date)]
[::atom/content {:type "html"}
[:-cdata (get @bodies file)]]])])
xml/indent-str))
(spit (fs/file out-dir "atom.xml") (atom-feed posts))
(spit (fs/file out-dir "planetclojure.xml")
(atom-feed (filter
(fn [post]
(some (:categories post) ["clojure" "clojurescript"]))
posts)))
;; for JVM Clojure:
(defn -main [& _args]
(System/exit 0))
|
[
{
"context": "; Copyright (c) Michael Jerger, Dave Paroulek. All rights reserved.\n; The use an",
"end": 30,
"score": 0.9998461604118347,
"start": 16,
"tag": "NAME",
"value": "Michael Jerger"
},
{
"context": "; Copyright (c) Michael Jerger, Dave Paroulek. All rights reserved.\n; The use and distribution ",
"end": 45,
"score": 0.9998310208320618,
"start": 32,
"tag": "NAME",
"value": "Dave Paroulek"
},
{
"context": " port]\n :or {server-admin-email \"your-name@your-domain.com\"\n port \"80\"}}]\n (into\n []\n (conc",
"end": 3648,
"score": 0.9998652935028076,
"start": 3623,
"tag": "EMAIL",
"value": "your-name@your-domain.com"
},
{
"context": " ssl-module]\n :or {server-admin-email \"your-name@your-domain.com\"\n port \"443\"\n ssl-module :gnu",
"end": 4745,
"score": 0.9991870522499084,
"start": 4720,
"tag": "EMAIL",
"value": "your-name@your-domain.com"
},
{
"context": " opts\n :or {server-admin-email \"your-name@your-domain.com\"\n port \"3000\"}}]]\n (or\n ",
"end": 6719,
"score": 0.9969707131385803,
"start": 6694,
"tag": "EMAIL",
"value": "your-name@your-domain.com"
}
] | main/src/dda/pallet/dda_httpd_crate/infra/vhost/vhost.clj | DomainDrivenArchitecture/dda-httpd-crate | 2 | ; Copyright (c) Michael Jerger, Dave Paroulek. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;; Convenience functions for creating apche vhost config files.
(ns dda.pallet.dda-httpd-crate.infra.vhost.vhost
(:require [clojure.string :as string]
[httpd.crate.common :as common]
[httpd.crate.mod-gnutls :as gnutls]
[httpd.crate.mod-rewrite :as rewrite]))
(defn vhost-server-alias
"Define aliases. For example if your domain-name is example.com, you
might want to pass [\"www.example.com\" \"ftp.example.com\"]"
[& [domain-names]]
(if domain-names
[(apply str "ServerAlias " (interpose " " domain-names))]
[]))
(defn vhost-head
"listening spec may be: x.x.x.x:443 [x6:x6:x6:x6:x6:x6:x6:x6]:443"
[& {:keys [listening-spec
listening-interface
listening-port
domain-name
server-admin-email
aliases]
:or {listening-interface "*"
listening-port "80"}}]
(let [used-server-admin-email
(if server-admin-email
server-admin-email
(str "admin@" domain-name))]
(into
[(if listening-spec
(str "<VirtualHost " listening-spec ">")
(str "<VirtualHost " listening-interface ":" listening-port ">"))]
(common/prefix
" "
(into []
(concat
[(str "ServerName " domain-name)]
(vhost-server-alias aliases)
[(str "ServerAdmin " used-server-admin-email)
""]))))))
(def vhost-tail ["</VirtualHost>"])
(defn vhost-document-root
[& [document-root-path]]
(if document-root-path
[(str "DocumentRoot \"" document-root-path "\"")
""]
[]))
(defn vhost-directory
[file-path & {:keys [directory-options]
:or {directory-options
["Order allow,deny"
"Allow from all"]}}]
(into
[]
(concat
[(str "<Directory \"" file-path "\">")]
(common/prefix
" "
directory-options)
["</Directory>"
""])))
(defn vhost-location
"If path is nil, defaults to \"/\" "
[& {:keys [path
location-options]
:or {path "/"
location-options
["Order allow,deny"
"Allow from all"]}}]
(into []
(concat
[(str "<Location " path ">")]
(common/prefix
" "
location-options)
["</Location>"
""])))
(defn vhost-log
[& {:keys [domain-name
error-name
log-name
log-format]
:or {error-name "error"
log-name "access_log"
log-format "common"}}]
(let [log-prefix (if domain-name
(str domain-name "-")
"")]
[(str "ErrorLog \"/var/log/apache2/" log-prefix error-name "\"")
"LogLevel warn"
(str "CustomLog \"/var/log/apache2/" log-prefix log-name "\" " log-format)
""]))
(defn vhost-conf-default-redirect-to-https-only
"Just redirect http request permanently to https"
[& {:keys [domain-name
aliases
server-admin-email
document-root-path
port]
:or {server-admin-email "your-name@your-domain.com"
port "80"}}]
(into
[]
(concat
(vhost-head :listening-port port
:domain-name domain-name
:server-admin-email server-admin-email
:aliases aliases)
(common/prefix
" "
(into
[]
(concat
(vhost-document-root document-root-path)
(vhost-log :error-name "error.log"
:log-name "access.log"
:log-format "combined")
(rewrite/vhost-rewrite-rules
["RewriteCond %{HTTPS} !on"
"RewriteCond %{REQUEST_URI} !^/\\.well-known/acme-challenge(/.*)?$"
"RewriteRule ^/(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]"]
:use-proxy false))))
vhost-tail)))
(defn vhost-conf-ssl-default
"a https default configuration"
[& {:keys [domain-name
aliases
server-admin-email
document-root-path
port
ssl-module]
:or {server-admin-email "your-name@your-domain.com"
port "443"
ssl-module :gnutls}}]
(into
[]
(concat
(vhost-head :listening-port port
:domain-name domain-name
:server-admin-email server-admin-email
:aliases aliases)
(common/prefix
" "
(into
[]
(concat
(vhost-document-root document-root-path)
(vhost-log :error-name "error.log"
:log-name "ssl-access.log"
:log-format "combined")
(if (= ssl-module :gnutls)
(gnutls/vhost-gnutls domain-name)))))
vhost-tail)))
(defn vhost-conf-default
"Most of my apache vhosts are for java apps. Here's what I usually use."
[domain-name server-admin-email document-root-path aliases port]
(into
[]
(concat
(vhost-head :domain-name domain-name
:server-admin-email server-admin-email
:aliases aliases)
(common/prefix
" "
(into
[]
(concat
(vhost-document-root document-root-path)
(vhost-log :domain-name domain-name)
(vhost-location :path "/")
(vhost-directory document-root-path)
(rewrite/vhost-rewrite-rules
[(str "RewriteRule ^/$ http://localhost:" port "/ [P]")
(str "RewriteRule ^/(.+)$ http://localhost:" port "/$1 [P]")]))))
vhost-tail)))
(defn vhost-conf
"Generate a vhost config. domain-name will be used to name the vhost
conf file as well as log files. If you need to set up complicated
vhost, pass a string of xml to :vhost-xml and you will have full
control over what the vhost file looks like"
[domain-name & [{:keys [server-admin-email document-root-path
vhost-xml aliases port]
:as opts
:or {server-admin-email "your-name@your-domain.com"
port "3000"}}]]
(or
vhost-xml
(string/join
\newline
(vhost-conf-default
domain-name
server-admin-email
document-root-path
aliases port))))
| 23599 | ; Copyright (c) <NAME>, <NAME>. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;; Convenience functions for creating apche vhost config files.
(ns dda.pallet.dda-httpd-crate.infra.vhost.vhost
(:require [clojure.string :as string]
[httpd.crate.common :as common]
[httpd.crate.mod-gnutls :as gnutls]
[httpd.crate.mod-rewrite :as rewrite]))
(defn vhost-server-alias
"Define aliases. For example if your domain-name is example.com, you
might want to pass [\"www.example.com\" \"ftp.example.com\"]"
[& [domain-names]]
(if domain-names
[(apply str "ServerAlias " (interpose " " domain-names))]
[]))
(defn vhost-head
"listening spec may be: x.x.x.x:443 [x6:x6:x6:x6:x6:x6:x6:x6]:443"
[& {:keys [listening-spec
listening-interface
listening-port
domain-name
server-admin-email
aliases]
:or {listening-interface "*"
listening-port "80"}}]
(let [used-server-admin-email
(if server-admin-email
server-admin-email
(str "admin@" domain-name))]
(into
[(if listening-spec
(str "<VirtualHost " listening-spec ">")
(str "<VirtualHost " listening-interface ":" listening-port ">"))]
(common/prefix
" "
(into []
(concat
[(str "ServerName " domain-name)]
(vhost-server-alias aliases)
[(str "ServerAdmin " used-server-admin-email)
""]))))))
(def vhost-tail ["</VirtualHost>"])
(defn vhost-document-root
[& [document-root-path]]
(if document-root-path
[(str "DocumentRoot \"" document-root-path "\"")
""]
[]))
(defn vhost-directory
[file-path & {:keys [directory-options]
:or {directory-options
["Order allow,deny"
"Allow from all"]}}]
(into
[]
(concat
[(str "<Directory \"" file-path "\">")]
(common/prefix
" "
directory-options)
["</Directory>"
""])))
(defn vhost-location
"If path is nil, defaults to \"/\" "
[& {:keys [path
location-options]
:or {path "/"
location-options
["Order allow,deny"
"Allow from all"]}}]
(into []
(concat
[(str "<Location " path ">")]
(common/prefix
" "
location-options)
["</Location>"
""])))
(defn vhost-log
[& {:keys [domain-name
error-name
log-name
log-format]
:or {error-name "error"
log-name "access_log"
log-format "common"}}]
(let [log-prefix (if domain-name
(str domain-name "-")
"")]
[(str "ErrorLog \"/var/log/apache2/" log-prefix error-name "\"")
"LogLevel warn"
(str "CustomLog \"/var/log/apache2/" log-prefix log-name "\" " log-format)
""]))
(defn vhost-conf-default-redirect-to-https-only
"Just redirect http request permanently to https"
[& {:keys [domain-name
aliases
server-admin-email
document-root-path
port]
:or {server-admin-email "<EMAIL>"
port "80"}}]
(into
[]
(concat
(vhost-head :listening-port port
:domain-name domain-name
:server-admin-email server-admin-email
:aliases aliases)
(common/prefix
" "
(into
[]
(concat
(vhost-document-root document-root-path)
(vhost-log :error-name "error.log"
:log-name "access.log"
:log-format "combined")
(rewrite/vhost-rewrite-rules
["RewriteCond %{HTTPS} !on"
"RewriteCond %{REQUEST_URI} !^/\\.well-known/acme-challenge(/.*)?$"
"RewriteRule ^/(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]"]
:use-proxy false))))
vhost-tail)))
(defn vhost-conf-ssl-default
"a https default configuration"
[& {:keys [domain-name
aliases
server-admin-email
document-root-path
port
ssl-module]
:or {server-admin-email "<EMAIL>"
port "443"
ssl-module :gnutls}}]
(into
[]
(concat
(vhost-head :listening-port port
:domain-name domain-name
:server-admin-email server-admin-email
:aliases aliases)
(common/prefix
" "
(into
[]
(concat
(vhost-document-root document-root-path)
(vhost-log :error-name "error.log"
:log-name "ssl-access.log"
:log-format "combined")
(if (= ssl-module :gnutls)
(gnutls/vhost-gnutls domain-name)))))
vhost-tail)))
(defn vhost-conf-default
"Most of my apache vhosts are for java apps. Here's what I usually use."
[domain-name server-admin-email document-root-path aliases port]
(into
[]
(concat
(vhost-head :domain-name domain-name
:server-admin-email server-admin-email
:aliases aliases)
(common/prefix
" "
(into
[]
(concat
(vhost-document-root document-root-path)
(vhost-log :domain-name domain-name)
(vhost-location :path "/")
(vhost-directory document-root-path)
(rewrite/vhost-rewrite-rules
[(str "RewriteRule ^/$ http://localhost:" port "/ [P]")
(str "RewriteRule ^/(.+)$ http://localhost:" port "/$1 [P]")]))))
vhost-tail)))
(defn vhost-conf
"Generate a vhost config. domain-name will be used to name the vhost
conf file as well as log files. If you need to set up complicated
vhost, pass a string of xml to :vhost-xml and you will have full
control over what the vhost file looks like"
[domain-name & [{:keys [server-admin-email document-root-path
vhost-xml aliases port]
:as opts
:or {server-admin-email "<EMAIL>"
port "3000"}}]]
(or
vhost-xml
(string/join
\newline
(vhost-conf-default
domain-name
server-admin-email
document-root-path
aliases port))))
| true | ; Copyright (c) PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;; Convenience functions for creating apche vhost config files.
(ns dda.pallet.dda-httpd-crate.infra.vhost.vhost
(:require [clojure.string :as string]
[httpd.crate.common :as common]
[httpd.crate.mod-gnutls :as gnutls]
[httpd.crate.mod-rewrite :as rewrite]))
(defn vhost-server-alias
"Define aliases. For example if your domain-name is example.com, you
might want to pass [\"www.example.com\" \"ftp.example.com\"]"
[& [domain-names]]
(if domain-names
[(apply str "ServerAlias " (interpose " " domain-names))]
[]))
(defn vhost-head
"listening spec may be: x.x.x.x:443 [x6:x6:x6:x6:x6:x6:x6:x6]:443"
[& {:keys [listening-spec
listening-interface
listening-port
domain-name
server-admin-email
aliases]
:or {listening-interface "*"
listening-port "80"}}]
(let [used-server-admin-email
(if server-admin-email
server-admin-email
(str "admin@" domain-name))]
(into
[(if listening-spec
(str "<VirtualHost " listening-spec ">")
(str "<VirtualHost " listening-interface ":" listening-port ">"))]
(common/prefix
" "
(into []
(concat
[(str "ServerName " domain-name)]
(vhost-server-alias aliases)
[(str "ServerAdmin " used-server-admin-email)
""]))))))
(def vhost-tail ["</VirtualHost>"])
(defn vhost-document-root
[& [document-root-path]]
(if document-root-path
[(str "DocumentRoot \"" document-root-path "\"")
""]
[]))
(defn vhost-directory
[file-path & {:keys [directory-options]
:or {directory-options
["Order allow,deny"
"Allow from all"]}}]
(into
[]
(concat
[(str "<Directory \"" file-path "\">")]
(common/prefix
" "
directory-options)
["</Directory>"
""])))
(defn vhost-location
"If path is nil, defaults to \"/\" "
[& {:keys [path
location-options]
:or {path "/"
location-options
["Order allow,deny"
"Allow from all"]}}]
(into []
(concat
[(str "<Location " path ">")]
(common/prefix
" "
location-options)
["</Location>"
""])))
(defn vhost-log
[& {:keys [domain-name
error-name
log-name
log-format]
:or {error-name "error"
log-name "access_log"
log-format "common"}}]
(let [log-prefix (if domain-name
(str domain-name "-")
"")]
[(str "ErrorLog \"/var/log/apache2/" log-prefix error-name "\"")
"LogLevel warn"
(str "CustomLog \"/var/log/apache2/" log-prefix log-name "\" " log-format)
""]))
(defn vhost-conf-default-redirect-to-https-only
"Just redirect http request permanently to https"
[& {:keys [domain-name
aliases
server-admin-email
document-root-path
port]
:or {server-admin-email "PI:EMAIL:<EMAIL>END_PI"
port "80"}}]
(into
[]
(concat
(vhost-head :listening-port port
:domain-name domain-name
:server-admin-email server-admin-email
:aliases aliases)
(common/prefix
" "
(into
[]
(concat
(vhost-document-root document-root-path)
(vhost-log :error-name "error.log"
:log-name "access.log"
:log-format "combined")
(rewrite/vhost-rewrite-rules
["RewriteCond %{HTTPS} !on"
"RewriteCond %{REQUEST_URI} !^/\\.well-known/acme-challenge(/.*)?$"
"RewriteRule ^/(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]"]
:use-proxy false))))
vhost-tail)))
(defn vhost-conf-ssl-default
"a https default configuration"
[& {:keys [domain-name
aliases
server-admin-email
document-root-path
port
ssl-module]
:or {server-admin-email "PI:EMAIL:<EMAIL>END_PI"
port "443"
ssl-module :gnutls}}]
(into
[]
(concat
(vhost-head :listening-port port
:domain-name domain-name
:server-admin-email server-admin-email
:aliases aliases)
(common/prefix
" "
(into
[]
(concat
(vhost-document-root document-root-path)
(vhost-log :error-name "error.log"
:log-name "ssl-access.log"
:log-format "combined")
(if (= ssl-module :gnutls)
(gnutls/vhost-gnutls domain-name)))))
vhost-tail)))
(defn vhost-conf-default
"Most of my apache vhosts are for java apps. Here's what I usually use."
[domain-name server-admin-email document-root-path aliases port]
(into
[]
(concat
(vhost-head :domain-name domain-name
:server-admin-email server-admin-email
:aliases aliases)
(common/prefix
" "
(into
[]
(concat
(vhost-document-root document-root-path)
(vhost-log :domain-name domain-name)
(vhost-location :path "/")
(vhost-directory document-root-path)
(rewrite/vhost-rewrite-rules
[(str "RewriteRule ^/$ http://localhost:" port "/ [P]")
(str "RewriteRule ^/(.+)$ http://localhost:" port "/$1 [P]")]))))
vhost-tail)))
(defn vhost-conf
"Generate a vhost config. domain-name will be used to name the vhost
conf file as well as log files. If you need to set up complicated
vhost, pass a string of xml to :vhost-xml and you will have full
control over what the vhost file looks like"
[domain-name & [{:keys [server-admin-email document-root-path
vhost-xml aliases port]
:as opts
:or {server-admin-email "PI:EMAIL:<EMAIL>END_PI"
port "3000"}}]]
(or
vhost-xml
(string/join
\newline
(vhost-conf-default
domain-name
server-admin-email
document-root-path
aliases port))))
|
[
{
"context": "url encoded version of that string.\"\n ^{:author \"Chas Emerick\"\n :src \"https://github.com/cemerick/url/blob/m",
"end": 160,
"score": 0.9999006390571594,
"start": 148,
"tag": "NAME",
"value": "Chas Emerick"
}
] | src/chiphat/util.clj | dogonthehorizon/chiphat | 0 | (ns chiphat.util
(:import (java.net URLEncoder)))
(defn url-encode
"Given a string, return a url encoded version of that string."
^{:author "Chas Emerick"
:src "https://github.com/cemerick/url/blob/master/src/cemerick/url.cljx"}
[s]
(some-> s str (URLEncoder/encode "UTF-8") (.replace "+" "%20")))
| 116620 | (ns chiphat.util
(:import (java.net URLEncoder)))
(defn url-encode
"Given a string, return a url encoded version of that string."
^{:author "<NAME>"
:src "https://github.com/cemerick/url/blob/master/src/cemerick/url.cljx"}
[s]
(some-> s str (URLEncoder/encode "UTF-8") (.replace "+" "%20")))
| true | (ns chiphat.util
(:import (java.net URLEncoder)))
(defn url-encode
"Given a string, return a url encoded version of that string."
^{:author "PI:NAME:<NAME>END_PI"
:src "https://github.com/cemerick/url/blob/master/src/cemerick/url.cljx"}
[s]
(some-> s str (URLEncoder/encode "UTF-8") (.replace "+" "%20")))
|
[
{
"context": "amily_name\n :password \"please001!\"\n :password-confirmatio",
"end": 2100,
"score": 0.9993303418159485,
"start": 2091,
"tag": "PASSWORD",
"value": "please001"
},
{
"context": " :password-confirmation \"please001!\"})\n ident (create {:provider provider\n ",
"end": 2164,
"score": 0.999413013458252,
"start": 2155,
"tag": "PASSWORD",
"value": "please001"
}
] | src/clj/clj_money/models/identities.clj | dgknght/clj-money | 5 | (ns clj-money.models.identities
(:refer-clojure :exclude [find])
(:require [clojure.spec.alpha :as s]
[clojure.set :refer [rename-keys]]
[clojure.tools.logging :as log]
[environ.core :refer [env]]
[stowaway.core :refer [tag]]
[stowaway.implicit :as storage :refer [with-storage]]
[dgknght.app-lib.validation :refer [with-validation]]
[clj-money.models :as models]
[clj-money.models.users :as users]))
(s/def ::user-id integer?)
(s/def ::provider #{:google})
(s/def ::provider-id string?)
(s/def ::identity (s/keys :req-un [::user-id ::provider ::provider-id]))
(defn- before-save
[ident]
(tag ident ::models/identity))
(defn- after-read
[ident]
(tag ident ::models/identity))
(defn create
[ident]
(with-storage (env :db)
(with-validation ident ::identity
(-> ident
before-save
storage/create
after-read))))
(defn select
[criteria options]
(with-storage (env :db)
(storage/select (tag criteria ::models/identity)
options)))
(defn find-by
[criteria]
(first (select criteria {:limit 1})))
(defn- identity->user
[ident]
(when ident
(-> ident
(rename-keys {:user-id :id
:user-first-name :first-name
:user-last-name :last-name
:user-email :email})
(dissoc :provider :provider-id))))
(defn- find-by-identity
[provider {:keys [id]}]
(identity->user (find-by
{:provider provider
:provider-id id})))
(defn- find-by-email
[provider {:keys [email id]}]
(when-let [user (users/find-by {:email email})]
(create {:provider provider
:provider-id id
:user-id (:id user)})
user))
(defn- create-from-profile
[provider {:keys [email id given_name family_name]}]
(let [user (users/create {:email email
:first-name given_name
:last-name family_name
:password "please001!"
:password-confirmation "please001!"})
ident (create {:provider provider
:provider-id id
:user-id (:id user)})]
(log/debugf "created user from profile %s" (prn-str user))
(log/debugf "created identity from profile %s" (prn-str ident))
user))
(defn find-or-create-from-profile
[provider profile]
(with-storage (env :db)
(some #(% provider profile)
[find-by-identity
find-by-email
create-from-profile])))
| 22180 | (ns clj-money.models.identities
(:refer-clojure :exclude [find])
(:require [clojure.spec.alpha :as s]
[clojure.set :refer [rename-keys]]
[clojure.tools.logging :as log]
[environ.core :refer [env]]
[stowaway.core :refer [tag]]
[stowaway.implicit :as storage :refer [with-storage]]
[dgknght.app-lib.validation :refer [with-validation]]
[clj-money.models :as models]
[clj-money.models.users :as users]))
(s/def ::user-id integer?)
(s/def ::provider #{:google})
(s/def ::provider-id string?)
(s/def ::identity (s/keys :req-un [::user-id ::provider ::provider-id]))
(defn- before-save
[ident]
(tag ident ::models/identity))
(defn- after-read
[ident]
(tag ident ::models/identity))
(defn create
[ident]
(with-storage (env :db)
(with-validation ident ::identity
(-> ident
before-save
storage/create
after-read))))
(defn select
[criteria options]
(with-storage (env :db)
(storage/select (tag criteria ::models/identity)
options)))
(defn find-by
[criteria]
(first (select criteria {:limit 1})))
(defn- identity->user
[ident]
(when ident
(-> ident
(rename-keys {:user-id :id
:user-first-name :first-name
:user-last-name :last-name
:user-email :email})
(dissoc :provider :provider-id))))
(defn- find-by-identity
[provider {:keys [id]}]
(identity->user (find-by
{:provider provider
:provider-id id})))
(defn- find-by-email
[provider {:keys [email id]}]
(when-let [user (users/find-by {:email email})]
(create {:provider provider
:provider-id id
:user-id (:id user)})
user))
(defn- create-from-profile
[provider {:keys [email id given_name family_name]}]
(let [user (users/create {:email email
:first-name given_name
:last-name family_name
:password "<PASSWORD>!"
:password-confirmation "<PASSWORD>!"})
ident (create {:provider provider
:provider-id id
:user-id (:id user)})]
(log/debugf "created user from profile %s" (prn-str user))
(log/debugf "created identity from profile %s" (prn-str ident))
user))
(defn find-or-create-from-profile
[provider profile]
(with-storage (env :db)
(some #(% provider profile)
[find-by-identity
find-by-email
create-from-profile])))
| true | (ns clj-money.models.identities
(:refer-clojure :exclude [find])
(:require [clojure.spec.alpha :as s]
[clojure.set :refer [rename-keys]]
[clojure.tools.logging :as log]
[environ.core :refer [env]]
[stowaway.core :refer [tag]]
[stowaway.implicit :as storage :refer [with-storage]]
[dgknght.app-lib.validation :refer [with-validation]]
[clj-money.models :as models]
[clj-money.models.users :as users]))
(s/def ::user-id integer?)
(s/def ::provider #{:google})
(s/def ::provider-id string?)
(s/def ::identity (s/keys :req-un [::user-id ::provider ::provider-id]))
(defn- before-save
[ident]
(tag ident ::models/identity))
(defn- after-read
[ident]
(tag ident ::models/identity))
(defn create
[ident]
(with-storage (env :db)
(with-validation ident ::identity
(-> ident
before-save
storage/create
after-read))))
(defn select
[criteria options]
(with-storage (env :db)
(storage/select (tag criteria ::models/identity)
options)))
(defn find-by
[criteria]
(first (select criteria {:limit 1})))
(defn- identity->user
[ident]
(when ident
(-> ident
(rename-keys {:user-id :id
:user-first-name :first-name
:user-last-name :last-name
:user-email :email})
(dissoc :provider :provider-id))))
(defn- find-by-identity
[provider {:keys [id]}]
(identity->user (find-by
{:provider provider
:provider-id id})))
(defn- find-by-email
[provider {:keys [email id]}]
(when-let [user (users/find-by {:email email})]
(create {:provider provider
:provider-id id
:user-id (:id user)})
user))
(defn- create-from-profile
[provider {:keys [email id given_name family_name]}]
(let [user (users/create {:email email
:first-name given_name
:last-name family_name
:password "PI:PASSWORD:<PASSWORD>END_PI!"
:password-confirmation "PI:PASSWORD:<PASSWORD>END_PI!"})
ident (create {:provider provider
:provider-id id
:user-id (:id user)})]
(log/debugf "created user from profile %s" (prn-str user))
(log/debugf "created identity from profile %s" (prn-str ident))
user))
(defn find-or-create-from-profile
[provider profile]
(with-storage (env :db)
(some #(% provider profile)
[find-by-identity
find-by-email
create-from-profile])))
|
[
{
"context": "mir leid\" :back \"I'm sorry\"}\n {:front \"Alles klar\" :back \"Alright\"}}\n :current-deck :starter\n :",
"end": 396,
"score": 0.9848494529724121,
"start": 386,
"tag": "NAME",
"value": "Alles klar"
},
{
"context": "m sorry\"}\n {:front \"Alles klar\" :back \"Alright\"}}\n :current-deck :starter\n :current-card {:f",
"end": 412,
"score": 0.8029338717460632,
"start": 405,
"tag": "NAME",
"value": "Alright"
},
{
"context": ":back \"I'm sorry\"}\n {:front \"Alles klar\" :back \"Alright\"}}\n :one-card-deck #{{:",
"end": 1515,
"score": 0.9646711945533752,
"start": 1505,
"tag": "NAME",
"value": "Alles klar"
},
{
"context": " {:front \"Alles klar\" :back \"Alright\"}}\n :one-card-deck #{{:front \"das Haus\"",
"end": 1531,
"score": 0.8213551044464111,
"start": 1524,
"tag": "NAME",
"value": "Alright"
}
] | test/cljs/cardy/utils.cljs | pianostringquartet/cardy | 0 | (ns cardy.utils
(:require [re-frame.core :as re-frame]))
;; An app-db suitable to test Study and Edit panels.
;; Assumes we've successfully logged in and pulled :decks from external db.
(def edit-and-study-test-db
{:cards #{{:front "Deutsch" :back "German"}
{:front "Genau" :back "Exactly"}
{:front "Es tut mir leid" :back "I'm sorry"}
{:front "Alles klar" :back "Alright"}}
:current-deck :starter
:current-card {:front "Deutsch" :back "German"}
:excluded #{}
:decks {:big-deck-2 #{{:front "aber" :back "but"}
{:front "auch" :back "too, also"}
{:front "als" :back "than (e.g. better than, worse than)"}
{:front "immer" :back "always"}
{:front "mehr" :back "more, further"}
{:front "neben" :back "beside, next to, by, alongside"}
{:front "wie" :back "like, similar to"}
{:front "bald" :back "soon"}
{:front "zusammen" :back "together"}
{:front "iche werde + verb" :back "I will + verb"}
{:front "Stimmt!" :back "Agreed! Right!"}
{:front "Es stimmt" :back "It's true"}}
:starter #{{:front "Deutsch" :back "German"}
{:front "Genau" :back "Exactly"}
{:front "Es tut mir leid" :back "I'm sorry"}
{:front "Alles klar" :back "Alright"}}
:one-card-deck #{{:front "das Haus" :back "house"}}
:two-card-deck #{{:front "das Haus" :back "house"}
{:front "der Hund" :back "dog"}}}})
(re-frame/reg-event-db
::initialize-edit-and-study-test-db
(fn initialize-edit-and-study-test-db [_ _]
edit-and-study-test-db))
| 25547 | (ns cardy.utils
(:require [re-frame.core :as re-frame]))
;; An app-db suitable to test Study and Edit panels.
;; Assumes we've successfully logged in and pulled :decks from external db.
(def edit-and-study-test-db
{:cards #{{:front "Deutsch" :back "German"}
{:front "Genau" :back "Exactly"}
{:front "Es tut mir leid" :back "I'm sorry"}
{:front "<NAME>" :back "<NAME>"}}
:current-deck :starter
:current-card {:front "Deutsch" :back "German"}
:excluded #{}
:decks {:big-deck-2 #{{:front "aber" :back "but"}
{:front "auch" :back "too, also"}
{:front "als" :back "than (e.g. better than, worse than)"}
{:front "immer" :back "always"}
{:front "mehr" :back "more, further"}
{:front "neben" :back "beside, next to, by, alongside"}
{:front "wie" :back "like, similar to"}
{:front "bald" :back "soon"}
{:front "zusammen" :back "together"}
{:front "iche werde + verb" :back "I will + verb"}
{:front "Stimmt!" :back "Agreed! Right!"}
{:front "Es stimmt" :back "It's true"}}
:starter #{{:front "Deutsch" :back "German"}
{:front "Genau" :back "Exactly"}
{:front "Es tut mir leid" :back "I'm sorry"}
{:front "<NAME>" :back "<NAME>"}}
:one-card-deck #{{:front "das Haus" :back "house"}}
:two-card-deck #{{:front "das Haus" :back "house"}
{:front "der Hund" :back "dog"}}}})
(re-frame/reg-event-db
::initialize-edit-and-study-test-db
(fn initialize-edit-and-study-test-db [_ _]
edit-and-study-test-db))
| true | (ns cardy.utils
(:require [re-frame.core :as re-frame]))
;; An app-db suitable to test Study and Edit panels.
;; Assumes we've successfully logged in and pulled :decks from external db.
(def edit-and-study-test-db
{:cards #{{:front "Deutsch" :back "German"}
{:front "Genau" :back "Exactly"}
{:front "Es tut mir leid" :back "I'm sorry"}
{:front "PI:NAME:<NAME>END_PI" :back "PI:NAME:<NAME>END_PI"}}
:current-deck :starter
:current-card {:front "Deutsch" :back "German"}
:excluded #{}
:decks {:big-deck-2 #{{:front "aber" :back "but"}
{:front "auch" :back "too, also"}
{:front "als" :back "than (e.g. better than, worse than)"}
{:front "immer" :back "always"}
{:front "mehr" :back "more, further"}
{:front "neben" :back "beside, next to, by, alongside"}
{:front "wie" :back "like, similar to"}
{:front "bald" :back "soon"}
{:front "zusammen" :back "together"}
{:front "iche werde + verb" :back "I will + verb"}
{:front "Stimmt!" :back "Agreed! Right!"}
{:front "Es stimmt" :back "It's true"}}
:starter #{{:front "Deutsch" :back "German"}
{:front "Genau" :back "Exactly"}
{:front "Es tut mir leid" :back "I'm sorry"}
{:front "PI:NAME:<NAME>END_PI" :back "PI:NAME:<NAME>END_PI"}}
:one-card-deck #{{:front "das Haus" :back "house"}}
:two-card-deck #{{:front "das Haus" :back "house"}
{:front "der Hund" :back "dog"}}}})
(re-frame/reg-event-db
::initialize-edit-and-study-test-db
(fn initialize-edit-and-study-test-db [_ _]
edit-and-study-test-db))
|
[
{
"context": " (:import (java.util UUID)))\n\n(def public-keys {:LYyP2g \"-----BEGIN PUBLIC KEY-----\\n\n ",
"end": 208,
"score": 0.9437412619590759,
"start": 203,
"tag": "KEY",
"value": "LYyP2"
},
{
"context": "rt (java.util UUID)))\n\n(def public-keys {:LYyP2g \"-----BEGIN PUBLIC KEY-----\\n\n ",
"end": 211,
"score": 0.5348644852638245,
"start": 211,
"tag": "KEY",
"value": ""
},
{
"context": "f public-keys {:LYyP2g \"-----BEGIN PUBLIC KEY-----\\n\n MFkwEwYHKoZIzj0CAQYIKo",
"end": 239,
"score": 0.7663409113883972,
"start": 238,
"tag": "KEY",
"value": "n"
},
{
"context": "BEGIN PUBLIC KEY-----\\n\n MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAESlXFFkJ3JxMsXyXNrqzE3ozl/091 3PmNbccLLWfeQFUYtJqGtl8ESuYxRwc/QwZp5Wcl0HCq6GuFDx4/Tk18Ig==\\n\n -----END PUBLIC KEY---",
"end": 394,
"score": 0.9181649088859558,
"start": 267,
"tag": "KEY",
"value": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAESlXFFkJ3JxMsXyXNrqzE3ozl/091 3PmNbccLLWfeQFUYtJqGtl8ESuYxRwc/QwZp5Wcl0HCq6GuFDx4/Tk18Ig==\\n"
},
{
"context": " :b9vTLA \"-----BEGIN PUBLIC KEY-----\\n\n MFkwEwYHKoZIzj0CAQYIKo",
"end": 504,
"score": 0.6911454796791077,
"start": 503,
"tag": "KEY",
"value": "n"
},
{
"context": "BEGIN PUBLIC KEY-----\\n\n MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEqCByTAvci+jRAD7uQSEhTdOs8iA7 14IbcY2L++YzynJZBjS4KhDI9KjNYoZDRqeYV44fkk1eJlr2LpI2o5ybvA==\\n\n -----END PUBLIC KEY---",
"end": 659,
"score": 0.9368425607681274,
"start": 532,
"tag": "KEY",
"value": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEqCByTAvci+jRAD7uQSEhTdOs8iA7 14IbcY2L++YzynJZBjS4KhDI9KjNYoZDRqeYV44fkk1eJlr2LpI2o5ybvA==\\n"
},
{
"context": " :mpf0DA \"-----BEGIN PUBLIC KEY-----\\n\n MFkwEwYHKoZIzj0CAQYIKo",
"end": 770,
"score": 0.7103235125541687,
"start": 769,
"tag": "KEY",
"value": "n"
},
{
"context": "BEGIN PUBLIC KEY-----\\n\n MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfHEdeT3a6KaC1kbwov73ZwB/SiUH EyKQwUUtMCEn0aJBY6PA+Eic24+WqPEtDKG95elao4VxA+Fne36Sgw1tkg==\\n\n -----END PUBLIC KEY---",
"end": 925,
"score": 0.9049654603004456,
"start": 798,
"tag": "KEY",
"value": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfHEdeT3a6KaC1kbwov73ZwB/SiUH EyKQwUUtMCEn0aJBY6PA+Eic24+WqPEtDKG95elao4VxA+Fne36Sgw1tkg==\\n"
},
{
"context": " :use \"sig\",\n :x \"SlXFFkJ3JxMsXyXNrqzE3ozl_0913PmNbccLLWfeQFU\",\n :y \"GLSahrZfBErmMUcHP0MGaeVn",
"end": 1200,
"score": 0.9868952631950378,
"start": 1157,
"tag": "KEY",
"value": "SlXFFkJ3JxMsXyXNrqzE3ozl_0913PmNbccLLWfeQFU"
},
{
"context": "E3ozl_0913PmNbccLLWfeQFU\",\n :y \"GLSahrZfBErmMUcHP0MGaeVnJdBwquhrhQ8eP05NfCI\"})\n(def mpf0DA-jwk {:alg \"ES256\",\n ",
"end": 1263,
"score": 0.8310831189155579,
"start": 1226,
"tag": "KEY",
"value": "GLSahrZfBErmMUcHP0MGaeVnJdBwquhrhQ8eP"
},
{
"context": "hTdOs8iA714IbcY2L--YzynI\",\n :y \"WQY0uCoQyPSozWKGQ0anmFeOH5JNXiZa9i6SNqOcm7w\"})\n\n(defn- wke-url [] (str \"http://wke-\" (UUID/ra",
"end": 1849,
"score": 0.8294400572776794,
"start": 1806,
"tag": "KEY",
"value": "WQY0uCoQyPSozWKGQ0anmFeOH5JNXiZa9i6SNqOcm7w"
},
{
"context": "\"\n (with-redefs [jwk/fetch (fn [_] {:keys [LYyP2g-jwk,\n ",
"end": 2682,
"score": 0.6453207731246948,
"start": 2680,
"tag": "KEY",
"value": "yP"
},
{
"context": "A-jwk]})]\n (is (= (jwk/get-public-key wke \"LYyP2g\")\n (keys/str->public-key (:LYyP2g p",
"end": 2797,
"score": 0.8540223836898804,
"start": 2791,
"tag": "KEY",
"value": "LYyP2g"
},
{
"context": "-jwk]})]\n (is (= (jwk/get-public-key wke \"b9vTLA\")\n (keys/str->public-key (:b9vTLA p",
"end": 3113,
"score": 0.5856270790100098,
"start": 3108,
"tag": "KEY",
"value": "9vTLA"
},
{
"context": "g-jwk]})]\n (is (= (jwk/get-public-key wke \"LYyP2g\")\n (keys/str->public-key (:LYyP2g p",
"end": 3450,
"score": 0.8618842959403992,
"start": 3444,
"tag": "KEY",
"value": "LYyP2g"
},
{
"context": "k]})]\n (is (nil? (jwk/get-public-key wke \"b9vTLA\")))))))\n\n(deftest different-wkes-are-cached-separ",
"end": 3742,
"score": 0.7303105592727661,
"start": 3737,
"tag": "KEY",
"value": "9vTLA"
},
{
"context": "k]})]\n (is (= (jwk/get-public-key (wke-url) \"LYyP2g\")\n (keys/str->public-key (:LYyP2g pub",
"end": 3945,
"score": 0.9891493916511536,
"start": 3939,
"tag": "KEY",
"value": "LYyP2g"
},
{
"context": ")]\n (is (nil? (jwk/get-public-key (wke-url) \"LYyP2g\"))))))\n\n",
"end": 4156,
"score": 0.9823042154312134,
"start": 4150,
"tag": "KEY",
"value": "LYyP2g"
}
] | test/buddy/sign/jwk_cache_tests.clj | insano10/buddy-sign | 0 | (ns buddy.sign.jwk-cache-tests
(:require [clojure.test :refer :all]
[buddy.core.keys :as keys]
[buddy.sign.jwk-cache :as jwk])
(:import (java.util UUID)))
(def public-keys {:LYyP2g "-----BEGIN PUBLIC KEY-----\n
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAESlXFFkJ3JxMsXyXNrqzE3ozl/091 3PmNbccLLWfeQFUYtJqGtl8ESuYxRwc/QwZp5Wcl0HCq6GuFDx4/Tk18Ig==\n
-----END PUBLIC KEY-----",
:b9vTLA "-----BEGIN PUBLIC KEY-----\n
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEqCByTAvci+jRAD7uQSEhTdOs8iA7 14IbcY2L++YzynJZBjS4KhDI9KjNYoZDRqeYV44fkk1eJlr2LpI2o5ybvA==\n
-----END PUBLIC KEY----- ",
:mpf0DA "-----BEGIN PUBLIC KEY-----\n
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfHEdeT3a6KaC1kbwov73ZwB/SiUH EyKQwUUtMCEn0aJBY6PA+Eic24+WqPEtDKG95elao4VxA+Fne36Sgw1tkg==\n
-----END PUBLIC KEY----- "})
(def LYyP2g-jwk {:alg "ES256",
:crv "P-256",
:kid "LYyP2g",
:kty "EC",
:use "sig",
:x "SlXFFkJ3JxMsXyXNrqzE3ozl_0913PmNbccLLWfeQFU",
:y "GLSahrZfBErmMUcHP0MGaeVnJdBwquhrhQ8eP05NfCI"})
(def mpf0DA-jwk {:alg "ES256",
:crv "P-256",
:kid "mpf0DA",
:kty "EC",
:use "sig",
:x "fHEdeT3a6KaC1kbwov73ZwB_SiUHEyKQwUUtMCEn0aI",
:y "QWOjwPhInNuPlqjxLQyhveXpWqOFcQPhZ3t-koMNbZI"})
(def b9vTLA-jwk {:alg "ES256",
:crv "P-256",
:kid "b9vTLA",
:kty "EC",
:use "sig",
:x "qCByTAvci-jRAD7uQSEhTdOs8iA714IbcY2L--YzynI",
:y "WQY0uCoQyPSozWKGQ0anmFeOH5JNXiZa9i6SNqOcm7w"})
(defn- wke-url [] (str "http://wke-" (UUID/randomUUID)))
(use-fixtures :once (fn [f] (with-redefs [jwk/refresh-delay-ms 0] (f))))
(deftest fetch-known-key-from-jwk-cache
(with-redefs [jwk/fetch (fn [_] {:keys [LYyP2g-jwk]})]
(is (= (jwk/get-public-key (wke-url) "LYyP2g")
(keys/str->public-key (:LYyP2g public-keys))))))
(deftest fetch-unknown-key-from-jwk-cache
(with-redefs [jwk/fetch (fn [_] {:keys [LYyP2g-jwk]})]
(is (nil? (jwk/get-public-key (wke-url) "unknown")))))
(deftest no-keys-from-wke-results-in-nil-key
(with-redefs [jwk/fetch (fn [_] "")]
(is (nil? (jwk/get-public-key (wke-url) "unknown")))))
(deftest fetch-newly-rotated-known-key-from-jwk-cache
(let [wke (wke-url)]
(testing "cache starts empty and keys are retrieved"
(with-redefs [jwk/fetch (fn [_] {:keys [LYyP2g-jwk,
mpf0DA-jwk]})]
(is (= (jwk/get-public-key wke "LYyP2g")
(keys/str->public-key (:LYyP2g public-keys))))))
(testing "request for key not in cache causes it to be refreshed from the wke"
(with-redefs [jwk/fetch (fn [_] {:keys [mpf0DA-jwk,
b9vTLA-jwk]})]
(is (= (jwk/get-public-key wke "b9vTLA")
(keys/str->public-key (:b9vTLA public-keys))))))))
(deftest cache-is-not-refreshed-if-it-was-already-refreshed-in-the-last-10-secs
(let [wke (wke-url)]
(testing "cache starts empty and keys are retrieved"
(with-redefs [jwk/fetch (fn [_] {:keys [LYyP2g-jwk]})]
(is (= (jwk/get-public-key wke "LYyP2g")
(keys/str->public-key (:LYyP2g public-keys))))))
(testing "immediate cache miss again does not trigger refresh"
(with-redefs [jwk/refresh-delay-ms 10000
jwk/fetch (fn [_] {:keys [b9vTLA-jwk]})]
(is (nil? (jwk/get-public-key wke "b9vTLA")))))))
(deftest different-wkes-are-cached-separately
(testing "key is retrieved for wke"
(with-redefs [jwk/fetch (fn [_] {:keys [LYyP2g-jwk]})]
(is (= (jwk/get-public-key (wke-url) "LYyP2g")
(keys/str->public-key (:LYyP2g public-keys))))))
(testing "key is not present for different wke"
(with-redefs [jwk/fetch (fn [_] nil)]
(is (nil? (jwk/get-public-key (wke-url) "LYyP2g"))))))
| 42756 | (ns buddy.sign.jwk-cache-tests
(:require [clojure.test :refer :all]
[buddy.core.keys :as keys]
[buddy.sign.jwk-cache :as jwk])
(:import (java.util UUID)))
(def public-keys {:<KEY>g "<KEY>-----BEGIN PUBLIC KEY-----\<KEY>
<KEY>
-----END PUBLIC KEY-----",
:b9vTLA "-----BEGIN PUBLIC KEY-----\<KEY>
<KEY>
-----END PUBLIC KEY----- ",
:mpf0DA "-----BEGIN PUBLIC KEY-----\<KEY>
<KEY>
-----END PUBLIC KEY----- "})
(def LYyP2g-jwk {:alg "ES256",
:crv "P-256",
:kid "LYyP2g",
:kty "EC",
:use "sig",
:x "<KEY>",
:y "<KEY>05NfCI"})
(def mpf0DA-jwk {:alg "ES256",
:crv "P-256",
:kid "mpf0DA",
:kty "EC",
:use "sig",
:x "fHEdeT3a6KaC1kbwov73ZwB_SiUHEyKQwUUtMCEn0aI",
:y "QWOjwPhInNuPlqjxLQyhveXpWqOFcQPhZ3t-koMNbZI"})
(def b9vTLA-jwk {:alg "ES256",
:crv "P-256",
:kid "b9vTLA",
:kty "EC",
:use "sig",
:x "qCByTAvci-jRAD7uQSEhTdOs8iA714IbcY2L--YzynI",
:y "<KEY>"})
(defn- wke-url [] (str "http://wke-" (UUID/randomUUID)))
(use-fixtures :once (fn [f] (with-redefs [jwk/refresh-delay-ms 0] (f))))
(deftest fetch-known-key-from-jwk-cache
(with-redefs [jwk/fetch (fn [_] {:keys [LYyP2g-jwk]})]
(is (= (jwk/get-public-key (wke-url) "LYyP2g")
(keys/str->public-key (:LYyP2g public-keys))))))
(deftest fetch-unknown-key-from-jwk-cache
(with-redefs [jwk/fetch (fn [_] {:keys [LYyP2g-jwk]})]
(is (nil? (jwk/get-public-key (wke-url) "unknown")))))
(deftest no-keys-from-wke-results-in-nil-key
(with-redefs [jwk/fetch (fn [_] "")]
(is (nil? (jwk/get-public-key (wke-url) "unknown")))))
(deftest fetch-newly-rotated-known-key-from-jwk-cache
(let [wke (wke-url)]
(testing "cache starts empty and keys are retrieved"
(with-redefs [jwk/fetch (fn [_] {:keys [LY<KEY>2g-jwk,
mpf0DA-jwk]})]
(is (= (jwk/get-public-key wke "<KEY>")
(keys/str->public-key (:LYyP2g public-keys))))))
(testing "request for key not in cache causes it to be refreshed from the wke"
(with-redefs [jwk/fetch (fn [_] {:keys [mpf0DA-jwk,
b9vTLA-jwk]})]
(is (= (jwk/get-public-key wke "b<KEY>")
(keys/str->public-key (:b9vTLA public-keys))))))))
(deftest cache-is-not-refreshed-if-it-was-already-refreshed-in-the-last-10-secs
(let [wke (wke-url)]
(testing "cache starts empty and keys are retrieved"
(with-redefs [jwk/fetch (fn [_] {:keys [LYyP2g-jwk]})]
(is (= (jwk/get-public-key wke "<KEY>")
(keys/str->public-key (:LYyP2g public-keys))))))
(testing "immediate cache miss again does not trigger refresh"
(with-redefs [jwk/refresh-delay-ms 10000
jwk/fetch (fn [_] {:keys [b9vTLA-jwk]})]
(is (nil? (jwk/get-public-key wke "b<KEY>")))))))
(deftest different-wkes-are-cached-separately
(testing "key is retrieved for wke"
(with-redefs [jwk/fetch (fn [_] {:keys [LYyP2g-jwk]})]
(is (= (jwk/get-public-key (wke-url) "<KEY>")
(keys/str->public-key (:LYyP2g public-keys))))))
(testing "key is not present for different wke"
(with-redefs [jwk/fetch (fn [_] nil)]
(is (nil? (jwk/get-public-key (wke-url) "<KEY>"))))))
| true | (ns buddy.sign.jwk-cache-tests
(:require [clojure.test :refer :all]
[buddy.core.keys :as keys]
[buddy.sign.jwk-cache :as jwk])
(:import (java.util UUID)))
(def public-keys {:PI:KEY:<KEY>END_PIg "PI:KEY:<KEY>END_PI-----BEGIN PUBLIC KEY-----\PI:KEY:<KEY>END_PI
PI:KEY:<KEY>END_PI
-----END PUBLIC KEY-----",
:b9vTLA "-----BEGIN PUBLIC KEY-----\PI:KEY:<KEY>END_PI
PI:KEY:<KEY>END_PI
-----END PUBLIC KEY----- ",
:mpf0DA "-----BEGIN PUBLIC KEY-----\PI:KEY:<KEY>END_PI
PI:KEY:<KEY>END_PI
-----END PUBLIC KEY----- "})
(def LYyP2g-jwk {:alg "ES256",
:crv "P-256",
:kid "LYyP2g",
:kty "EC",
:use "sig",
:x "PI:KEY:<KEY>END_PI",
:y "PI:KEY:<KEY>END_PI05NfCI"})
(def mpf0DA-jwk {:alg "ES256",
:crv "P-256",
:kid "mpf0DA",
:kty "EC",
:use "sig",
:x "fHEdeT3a6KaC1kbwov73ZwB_SiUHEyKQwUUtMCEn0aI",
:y "QWOjwPhInNuPlqjxLQyhveXpWqOFcQPhZ3t-koMNbZI"})
(def b9vTLA-jwk {:alg "ES256",
:crv "P-256",
:kid "b9vTLA",
:kty "EC",
:use "sig",
:x "qCByTAvci-jRAD7uQSEhTdOs8iA714IbcY2L--YzynI",
:y "PI:KEY:<KEY>END_PI"})
(defn- wke-url [] (str "http://wke-" (UUID/randomUUID)))
(use-fixtures :once (fn [f] (with-redefs [jwk/refresh-delay-ms 0] (f))))
(deftest fetch-known-key-from-jwk-cache
(with-redefs [jwk/fetch (fn [_] {:keys [LYyP2g-jwk]})]
(is (= (jwk/get-public-key (wke-url) "LYyP2g")
(keys/str->public-key (:LYyP2g public-keys))))))
(deftest fetch-unknown-key-from-jwk-cache
(with-redefs [jwk/fetch (fn [_] {:keys [LYyP2g-jwk]})]
(is (nil? (jwk/get-public-key (wke-url) "unknown")))))
(deftest no-keys-from-wke-results-in-nil-key
(with-redefs [jwk/fetch (fn [_] "")]
(is (nil? (jwk/get-public-key (wke-url) "unknown")))))
(deftest fetch-newly-rotated-known-key-from-jwk-cache
(let [wke (wke-url)]
(testing "cache starts empty and keys are retrieved"
(with-redefs [jwk/fetch (fn [_] {:keys [LYPI:KEY:<KEY>END_PI2g-jwk,
mpf0DA-jwk]})]
(is (= (jwk/get-public-key wke "PI:KEY:<KEY>END_PI")
(keys/str->public-key (:LYyP2g public-keys))))))
(testing "request for key not in cache causes it to be refreshed from the wke"
(with-redefs [jwk/fetch (fn [_] {:keys [mpf0DA-jwk,
b9vTLA-jwk]})]
(is (= (jwk/get-public-key wke "bPI:KEY:<KEY>END_PI")
(keys/str->public-key (:b9vTLA public-keys))))))))
(deftest cache-is-not-refreshed-if-it-was-already-refreshed-in-the-last-10-secs
(let [wke (wke-url)]
(testing "cache starts empty and keys are retrieved"
(with-redefs [jwk/fetch (fn [_] {:keys [LYyP2g-jwk]})]
(is (= (jwk/get-public-key wke "PI:KEY:<KEY>END_PI")
(keys/str->public-key (:LYyP2g public-keys))))))
(testing "immediate cache miss again does not trigger refresh"
(with-redefs [jwk/refresh-delay-ms 10000
jwk/fetch (fn [_] {:keys [b9vTLA-jwk]})]
(is (nil? (jwk/get-public-key wke "bPI:KEY:<KEY>END_PI")))))))
(deftest different-wkes-are-cached-separately
(testing "key is retrieved for wke"
(with-redefs [jwk/fetch (fn [_] {:keys [LYyP2g-jwk]})]
(is (= (jwk/get-public-key (wke-url) "PI:KEY:<KEY>END_PI")
(keys/str->public-key (:LYyP2g public-keys))))))
(testing "key is not present for different wke"
(with-redefs [jwk/fetch (fn [_] nil)]
(is (nil? (jwk/get-public-key (wke-url) "PI:KEY:<KEY>END_PI"))))))
|
[
{
"context": "iopianOrthodoxHolidayType)))))\n\n\n;; Copyright 2018 Frederic Merizen\n;;\n;; Licensed under the Apache License, Version ",
"end": 14308,
"score": 0.9998756647109985,
"start": 14292,
"tag": "NAME",
"value": "Frederic Merizen"
}
] | src/ferje/config/core.clj | chourave/clojyday | 0 | ;; Copyright and license information at end of file
(ns ferje.config.core
"Represent Jollyday configuration beans as clojure maps"
(:require
[clojure.spec.alpha :as s]
[clojure.string :as string]
[ferje.util :as util])
(:import
(de.jollyday.config
ChristianHoliday ChristianHolidayType ChronologyType Configuration
EthiopianOrthodoxHoliday EthiopianOrthodoxHolidayType Fixed
FixedWeekdayBetweenFixed FixedWeekdayInMonth FixedWeekdayRelativeToFixed
HebrewHoliday HinduHoliday HinduHolidayType Holiday HolidayType Holidays
IslamicHoliday IslamicHolidayType Month MovingCondition
RelativeToEasterSunday RelativeToFixed RelativeToWeekdayInMonth Weekday
When Which With)))
(def months #{:january :february :march :april :may :june
:july :august :september :october :november :december})
(def weekdays #{:monday :tuesday :wednesday :thursday :friday :saturday :sunday})
(def whichs #{:first :second :third :fourth :last})
(def whens #{:before :after})
(def everys #{:every-year :2-years :4-years :5-years :6-years :odd-years :even-years})
(def withs #{:next :previous})
(def chronologies #{:julian :gregorian})
(s/def ::day (s/int-in 1 32))
(s/def ::month months)
(s/def ::weekday weekdays)
(s/def ::which whichs)
(s/def ::when whens)
(s/def ::valid-from int?)
(s/def ::valid-to int?)
(s/def ::every everys)
(s/def ::description-key keyword?)
(s/def ::localized-type #{:official-holiday :unofficial-holiday})
(s/def ::substitute ::weekday)
(s/def ::with withs)
(s/def ::moving-conditions
(s/coll-of
(s/keys :req-un [::substitute ::with ::weekday])))
(s/def ::date
(s/keys :req-un [::month ::day]
:opt-un [::moving-conditions]))
(s/def ::from ::date)
(s/def ::to ::date)
(s/def ::days int?)
(s/def ::description string?)
(s/def ::hierarchy keyword?)
(s/def ::holidays (s/coll-of `holiday))
(s/def ::sub-configurations (s/coll-of ::configuration))
(s/def ::configuration
(s/keys :req-un [::description ::hierarchy ::holidays]
:opt-un [::sub-configurations]))
(defn holiday?
"Is x a Jollyday Holiday configuration object?"
[x]
(instance? Holiday x))
(s/fdef holiday?
:args (s/cat :x any?)
:ret boolean?)
(defn java-collection?
"Is x a Java collection?"
[x]
(instance? java.util.Collection x))
(s/fdef java-collection?
:args (s/cat :x any?)
:ret boolean?)
(defn named?
"Is x a valid argument to the `name` function?"
[x]
(or (instance? clojure.lang.Named x)
(string? x)))
(s/fdef named?
:args (s/cat :x any?)
:ret boolean?)
(s/def ::calendar-name named?)
(defn ->const-name
"Parse a :clojure-keyword to a JAVA_CONSTANT_NAME (as a strig)"
[x]
(-> x name string/upper-case (string/replace #"-" "_")))
(s/fdef ->const-name
:args (s/cat :x named?)
:ret (s/and string? util/uppercase?))
;;
(defmacro ->enum
"Parse a keyword to a value in a Java Enum"
[value enum]
`(-> ~value ->const-name (~(symbol (str enum) "valueOf"))))
(s/fdef ->enum
:args (s/cat :value any? :enum simple-symbol?)
:ret any?)
;;
(s/def ::holiday #{:islamic-holiday
:fixed-weekday
:hindu-holiday
:hebrew-holiday
:fixed-weekday-between-fixed
:fixed-weekday-relative-to-fixed
:relative-to-weekday-in-month
:relative-to-fixed
:relative-to-easter-sunday
:ethiopian-orthodox-holiday
:christian-holiday
:fixed})
(s/def holiday-common
(s/keys :opt-un [::valid-from ::valid-to ::every ::description-key ::localized-type]))
(s/def holiday-tag-common
(s/merge `holiday-common
(s/keys :req-un [::holiday])))
(defn add-moving-conditions!
"Add the moving conditions from a map to a Jollyday Holiday object"
[bean config]
(doto bean
(-> .getMovingCondition
(.addAll (map #(doto (MovingCondition.)
(.setSubstitute (-> % :substitute (->enum Weekday)))
(.setWith (-> % :with (->enum With)))
(.setWeekday (-> % :weekday (->enum Weekday))))
(:moving-conditions config))))))
(s/fdef add-moving-conditions!
:args (s/cat :bean holiday? :config map?)
:ret holiday?
:fn #(identical? (-> % :ret) (-> % :args :bean)))
(defmulti holiday-spec
"Returns the spec for a holiday definition"
:holiday)
(s/def holiday (s/multi-spec holiday-spec :holiday))
(defn set-common-holiday-attributes!
"Set a Jollyday `holiday`object with all those attributes from `config`
that are shared among all holiday types."
[holiday config]
(doto holiday
(.setValidFrom (some-> config :valid-from int))
(.setValidTo (some-> config :valid-to int))
(.setEvery (some-> config :every ->const-name))
(.setLocalizedType (some-> config :localized-type (->enum HolidayType)))
(.setDescriptionPropertiesKey (some-> config :description-key ->const-name))))
(s/fdef set-common-holiday-attributes!
:args (s/cat :bean holiday? :config `holiday-common)
:ret holiday?
:fn #(identical? (-> % :ret) (-> % :args :bean)))
;;
(defmulti ->Holiday
"Create a Jollyday holiday bean from an edn holiday configuration"
:holiday)
(defn add-holidays!
"Add holidays of a given `type` from `all-holidays` collection
to the `holidays` java collection"
[holidays all-holidays type]
(->> all-holidays
(filter #(instance? type %))
(.addAll holidays))
nil)
(s/fdef add-holidays!
:args (s/cat :holidays java-collection?
:all-holidays (s/coll-of holiday?)
:type #(.isAssignableFrom Holiday %))
:ret nil?)
(defmacro dispatch-holidays
"Sort Holiday objects by `types` into the corresponding slots
of a Holidays object."
[holidays & types]
(let [h (gensym "holidays")]
`(let [~h ~holidays]
(doto (Holidays.)
~@(for [t types]
`(-> (~(symbol (str ".get" t))) (add-holidays! ~h ~t)))))))
(s/fdef dispatch-holidays
:args (s/cat :holidays any? :types (s/* simple-symbol?))
:ret any?)
(defn ->Holidays
"Parse a collection of holiday configuration edn into a Jollyday
Holidays configuration bean."
[config]
(let [holidays (map ->Holiday config)]
(doto
(dispatch-holidays holidays
Fixed RelativeToFixed RelativeToWeekdayInMonth
ChristianHoliday IslamicHoliday
FixedWeekdayBetweenFixed FixedWeekdayRelativeToFixed
HinduHoliday HebrewHoliday EthiopianOrthodoxHoliday
RelativeToEasterSunday)
(-> (.getFixedWeekday) (add-holidays! holidays FixedWeekdayInMonth)))))
(s/fdef ->Holidays
:args (s/cat :config ::holidays)
:ret #(instance? Holidays %))
(declare add-sub-configurations!)
(defn ->Configuration
"Parse an edn `config` (top-level or for a subdivision)
into an Jollyday Configuration bean."
[config]
(doto (Configuration.)
(.setDescription (-> config :description))
(.setHierarchy (-> config :hierarchy name))
(.setHolidays (-> config :holidays ->Holidays))
(add-sub-configurations! config)))
(s/fdef ->Configuration
:args (s/cat :config ::configuration)
:ret #(instance? Configuration %))
(defn add-sub-configurations!
"Parse the configurations for geographical subdivisions from the edn `config`
and add them to the Jollyday `configuration` bean"
[configuration config]
(when-let [sub-configurations (some->> config :sub-configurations (map ->Configuration))]
(-> configuration .getSubConfigurations (.addAll sub-configurations))
nil))
(s/fdef add-sub-configurations!
:args (s/cat :configuration #(instance? Configuration %) :config ::configuration)
:ret nil?)
;; Fixed day
(defmethod holiday-spec :fixed [_]
(s/merge
`holiday-tag-common
::date))
(defn ->Fixed
"Create a Jollyday fixed holiday configuration bean from an edn map"
[config]
(doto (Fixed.)
(set-common-holiday-attributes! config)
(.setMonth (-> config :month (->enum Month)))
(.setDay (-> config :day int))
(add-moving-conditions! config)))
(s/fdef ->Fixed
:args (s/cat :config ::date)
:ret #(instance? Fixed %))
(defmethod ->Holiday :fixed
[config]
(->Fixed config))
;; Weekday relative to fixed
(defmethod holiday-spec :relative-to-fixed [_]
(s/merge
`holiday-tag-common
(s/and
(s/keys :req-un [::when ::date] :opt-un [::days ::weekday])
#(some % [:days :weekday]))))
(defmethod ->Holiday :relative-to-fixed
[config]
(doto (RelativeToFixed.)
(set-common-holiday-attributes! config)
(.setWeekday (some-> config :weekday (->enum Weekday)))
(.setWhen (-> config :when (->enum When)))
(.setDate (-> config :date ->Fixed))
(.setDays (some-> config :days int))))
(defmethod holiday-spec :fixed-weekday-between-fixed [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [::weekday ::from ::to])))
(defmethod ->Holiday :fixed-weekday-between-fixed
[config]
(doto (FixedWeekdayBetweenFixed.)
(set-common-holiday-attributes! config)
(.setWeekday (some-> config :weekday (->enum Weekday)))
(.setFrom (-> config :from ->Fixed))
(.setTo (-> config :to ->Fixed))))
;; Weekday in month
(s/def ::fixed-weekday
(s/keys :req-un [::which ::weekday ::month]))
(defmethod holiday-spec :fixed-weekday [_]
(s/merge
`holiday-tag-common
::fixed-weekday))
(defn ->FixedWeekday
[config]
(doto (FixedWeekdayInMonth.)
(set-common-holiday-attributes! config)
(.setWhich (-> config :which (->enum Which)))
(.setWeekday (-> config :weekday (->enum Weekday)))
(.setMonth (-> config :month (->enum Month)))))
(s/fdef ->FixedWeekday
:args (s/cat :config ::fixed-weekday)
:ret #(instance? FixedWeekdayInMonth %))
(defmethod ->Holiday :fixed-weekday
[config]
(->FixedWeekday config))
;; Relative to weekday in month
(defmethod holiday-spec :relative-to-weekday-in-month [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [::weekday ::when ::fixed-weekday])))
(defmethod ->Holiday :relative-to-weekday-in-month
[config]
(doto (RelativeToWeekdayInMonth.)
(set-common-holiday-attributes! config)
(.setWeekday (-> config :weekday (->enum Weekday)))
(.setWhen (-> config :when (->enum When)))
(.setFixedWeekday (-> config :fixed-weekday ->FixedWeekday))))
;; Weekday relative to fixed day
(defmethod holiday-spec :fixed-weekday-relative-to-fixed [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [::which ::weekday ::when ::date])))
(defmethod ->Holiday :fixed-weekday-relative-to-fixed
[config]
(doto (FixedWeekdayRelativeToFixed.)
(set-common-holiday-attributes! config)
(.setWhich (-> config :which (->enum Which)))
(.setWeekday (-> config :weekday (->enum Weekday)))
(.setWhen (-> config :when (->enum When)))
(.setDay (-> config :date ->Fixed))))
;; Christian
(def christian-types
#{:good-friday :easter-monday :ascension-day :whit-monday :corpus-christi
:maundy-thursday :ash-wednesday :mardi-gras :general-prayer-day
:clean-monday :shrove-monday :pentecost :carnival :easter-saturday
:easter-tuesday :sacred-heart :easter :pentecost-monday :whit-sunday})
(s/def :christian/type christian-types)
(s/def ::chronology chronologies)
(defmethod holiday-spec :christian-holiday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [:christian/type] :opt-un [::chronology ::moving-conditions])))
(defmethod ->Holiday :christian-holiday
[config]
(doto (ChristianHoliday.)
(set-common-holiday-attributes! config)
(.setType (-> config :type (->enum ChristianHolidayType)))
(.setChronology (some-> config :chronology (->enum ChronologyType)))
(add-moving-conditions! config)))
(defmethod holiday-spec :relative-to-easter-sunday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [::chronology ::days])))
(defmethod ->Holiday :relative-to-easter-sunday
[config]
(doto (RelativeToEasterSunday.)
(set-common-holiday-attributes! config)
(.setChronology (some-> config :chronology (->enum ChronologyType)))
(.setDays (-> config :days int))))
;; Islamic
(def islamic-types
#{:newyear :aschura :mawlid-an-nabi :lailat-al-miraj :lailat-al-barat
:ramadan :lailat-al-qadr :id-al-fitr :id-ul-adha})
(s/def :islamic/type islamic-types)
(defmethod holiday-spec :islamic-holiday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [:islamic/type])))
(defmethod ->Holiday :islamic-holiday
[config]
(doto (IslamicHoliday.)
(set-common-holiday-attributes! config)
(.setType (-> config :type (->enum IslamicHolidayType)))))
;; Hindu
(def hindu-types
#{:holi})
(s/def :hindu/type hindu-types)
(defmethod holiday-spec :hindu-holiday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [:hindu/type])))
(defmethod ->Holiday :hindu-holiday
[config]
(doto (HinduHoliday.)
(set-common-holiday-attributes! config)
(.setType (-> config :type (->enum HinduHolidayType)))))
;; Hebrew
(def hebrew-types
#{:rosh-hashanah :aseret-yemei-teshuva :yom-kippur :sukkot :shemini-atzeret
:hanukkah :asarah-betevet :tu-bishvat :purim :1-nisan :pesach :sefirah
:lag-baomer :shavout :17-tammuz :tisha-bav :1-elul :rosh-codesh :shabbat
:yom-hashoah :yom-hazikaron :yom-haatzamaut :yom-yerushalaim})
(s/def :hebrew/type hebrew-types)
(defmethod holiday-spec :hebrew-holiday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [:hebrew/type])))
(defmethod ->Holiday :hebrew-holiday
[config]
(doto (HebrewHoliday.)
(set-common-holiday-attributes! config)
(.setType (-> config :type ->const-name))))
;; Ethiopian orthodox
(def ethiopian-orthodox-types
#{:timkat :enkutatash :meskel})
(s/def :ethiopian-orthodox/type ethiopian-orthodox-types)
(defmethod holiday-spec :ethiopian-orthodox-holiday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [:ethiopian-orthodox/type])))
(defmethod ->Holiday :ethiopian-orthodox-holiday
[config]
(doto (EthiopianOrthodoxHoliday.)
(set-common-holiday-attributes! config)
(.setType (-> config :type (->enum EthiopianOrthodoxHolidayType)))))
;; Copyright 2018 Frederic Merizen
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
;; or implied. See the License for the specific language governing
;; permissions and limitations under the License.
| 29975 | ;; Copyright and license information at end of file
(ns ferje.config.core
"Represent Jollyday configuration beans as clojure maps"
(:require
[clojure.spec.alpha :as s]
[clojure.string :as string]
[ferje.util :as util])
(:import
(de.jollyday.config
ChristianHoliday ChristianHolidayType ChronologyType Configuration
EthiopianOrthodoxHoliday EthiopianOrthodoxHolidayType Fixed
FixedWeekdayBetweenFixed FixedWeekdayInMonth FixedWeekdayRelativeToFixed
HebrewHoliday HinduHoliday HinduHolidayType Holiday HolidayType Holidays
IslamicHoliday IslamicHolidayType Month MovingCondition
RelativeToEasterSunday RelativeToFixed RelativeToWeekdayInMonth Weekday
When Which With)))
(def months #{:january :february :march :april :may :june
:july :august :september :october :november :december})
(def weekdays #{:monday :tuesday :wednesday :thursday :friday :saturday :sunday})
(def whichs #{:first :second :third :fourth :last})
(def whens #{:before :after})
(def everys #{:every-year :2-years :4-years :5-years :6-years :odd-years :even-years})
(def withs #{:next :previous})
(def chronologies #{:julian :gregorian})
(s/def ::day (s/int-in 1 32))
(s/def ::month months)
(s/def ::weekday weekdays)
(s/def ::which whichs)
(s/def ::when whens)
(s/def ::valid-from int?)
(s/def ::valid-to int?)
(s/def ::every everys)
(s/def ::description-key keyword?)
(s/def ::localized-type #{:official-holiday :unofficial-holiday})
(s/def ::substitute ::weekday)
(s/def ::with withs)
(s/def ::moving-conditions
(s/coll-of
(s/keys :req-un [::substitute ::with ::weekday])))
(s/def ::date
(s/keys :req-un [::month ::day]
:opt-un [::moving-conditions]))
(s/def ::from ::date)
(s/def ::to ::date)
(s/def ::days int?)
(s/def ::description string?)
(s/def ::hierarchy keyword?)
(s/def ::holidays (s/coll-of `holiday))
(s/def ::sub-configurations (s/coll-of ::configuration))
(s/def ::configuration
(s/keys :req-un [::description ::hierarchy ::holidays]
:opt-un [::sub-configurations]))
(defn holiday?
"Is x a Jollyday Holiday configuration object?"
[x]
(instance? Holiday x))
(s/fdef holiday?
:args (s/cat :x any?)
:ret boolean?)
(defn java-collection?
"Is x a Java collection?"
[x]
(instance? java.util.Collection x))
(s/fdef java-collection?
:args (s/cat :x any?)
:ret boolean?)
(defn named?
"Is x a valid argument to the `name` function?"
[x]
(or (instance? clojure.lang.Named x)
(string? x)))
(s/fdef named?
:args (s/cat :x any?)
:ret boolean?)
(s/def ::calendar-name named?)
(defn ->const-name
"Parse a :clojure-keyword to a JAVA_CONSTANT_NAME (as a strig)"
[x]
(-> x name string/upper-case (string/replace #"-" "_")))
(s/fdef ->const-name
:args (s/cat :x named?)
:ret (s/and string? util/uppercase?))
;;
(defmacro ->enum
"Parse a keyword to a value in a Java Enum"
[value enum]
`(-> ~value ->const-name (~(symbol (str enum) "valueOf"))))
(s/fdef ->enum
:args (s/cat :value any? :enum simple-symbol?)
:ret any?)
;;
(s/def ::holiday #{:islamic-holiday
:fixed-weekday
:hindu-holiday
:hebrew-holiday
:fixed-weekday-between-fixed
:fixed-weekday-relative-to-fixed
:relative-to-weekday-in-month
:relative-to-fixed
:relative-to-easter-sunday
:ethiopian-orthodox-holiday
:christian-holiday
:fixed})
(s/def holiday-common
(s/keys :opt-un [::valid-from ::valid-to ::every ::description-key ::localized-type]))
(s/def holiday-tag-common
(s/merge `holiday-common
(s/keys :req-un [::holiday])))
(defn add-moving-conditions!
"Add the moving conditions from a map to a Jollyday Holiday object"
[bean config]
(doto bean
(-> .getMovingCondition
(.addAll (map #(doto (MovingCondition.)
(.setSubstitute (-> % :substitute (->enum Weekday)))
(.setWith (-> % :with (->enum With)))
(.setWeekday (-> % :weekday (->enum Weekday))))
(:moving-conditions config))))))
(s/fdef add-moving-conditions!
:args (s/cat :bean holiday? :config map?)
:ret holiday?
:fn #(identical? (-> % :ret) (-> % :args :bean)))
(defmulti holiday-spec
"Returns the spec for a holiday definition"
:holiday)
(s/def holiday (s/multi-spec holiday-spec :holiday))
(defn set-common-holiday-attributes!
"Set a Jollyday `holiday`object with all those attributes from `config`
that are shared among all holiday types."
[holiday config]
(doto holiday
(.setValidFrom (some-> config :valid-from int))
(.setValidTo (some-> config :valid-to int))
(.setEvery (some-> config :every ->const-name))
(.setLocalizedType (some-> config :localized-type (->enum HolidayType)))
(.setDescriptionPropertiesKey (some-> config :description-key ->const-name))))
(s/fdef set-common-holiday-attributes!
:args (s/cat :bean holiday? :config `holiday-common)
:ret holiday?
:fn #(identical? (-> % :ret) (-> % :args :bean)))
;;
(defmulti ->Holiday
"Create a Jollyday holiday bean from an edn holiday configuration"
:holiday)
(defn add-holidays!
"Add holidays of a given `type` from `all-holidays` collection
to the `holidays` java collection"
[holidays all-holidays type]
(->> all-holidays
(filter #(instance? type %))
(.addAll holidays))
nil)
(s/fdef add-holidays!
:args (s/cat :holidays java-collection?
:all-holidays (s/coll-of holiday?)
:type #(.isAssignableFrom Holiday %))
:ret nil?)
(defmacro dispatch-holidays
"Sort Holiday objects by `types` into the corresponding slots
of a Holidays object."
[holidays & types]
(let [h (gensym "holidays")]
`(let [~h ~holidays]
(doto (Holidays.)
~@(for [t types]
`(-> (~(symbol (str ".get" t))) (add-holidays! ~h ~t)))))))
(s/fdef dispatch-holidays
:args (s/cat :holidays any? :types (s/* simple-symbol?))
:ret any?)
(defn ->Holidays
"Parse a collection of holiday configuration edn into a Jollyday
Holidays configuration bean."
[config]
(let [holidays (map ->Holiday config)]
(doto
(dispatch-holidays holidays
Fixed RelativeToFixed RelativeToWeekdayInMonth
ChristianHoliday IslamicHoliday
FixedWeekdayBetweenFixed FixedWeekdayRelativeToFixed
HinduHoliday HebrewHoliday EthiopianOrthodoxHoliday
RelativeToEasterSunday)
(-> (.getFixedWeekday) (add-holidays! holidays FixedWeekdayInMonth)))))
(s/fdef ->Holidays
:args (s/cat :config ::holidays)
:ret #(instance? Holidays %))
(declare add-sub-configurations!)
(defn ->Configuration
"Parse an edn `config` (top-level or for a subdivision)
into an Jollyday Configuration bean."
[config]
(doto (Configuration.)
(.setDescription (-> config :description))
(.setHierarchy (-> config :hierarchy name))
(.setHolidays (-> config :holidays ->Holidays))
(add-sub-configurations! config)))
(s/fdef ->Configuration
:args (s/cat :config ::configuration)
:ret #(instance? Configuration %))
(defn add-sub-configurations!
"Parse the configurations for geographical subdivisions from the edn `config`
and add them to the Jollyday `configuration` bean"
[configuration config]
(when-let [sub-configurations (some->> config :sub-configurations (map ->Configuration))]
(-> configuration .getSubConfigurations (.addAll sub-configurations))
nil))
(s/fdef add-sub-configurations!
:args (s/cat :configuration #(instance? Configuration %) :config ::configuration)
:ret nil?)
;; Fixed day
(defmethod holiday-spec :fixed [_]
(s/merge
`holiday-tag-common
::date))
(defn ->Fixed
"Create a Jollyday fixed holiday configuration bean from an edn map"
[config]
(doto (Fixed.)
(set-common-holiday-attributes! config)
(.setMonth (-> config :month (->enum Month)))
(.setDay (-> config :day int))
(add-moving-conditions! config)))
(s/fdef ->Fixed
:args (s/cat :config ::date)
:ret #(instance? Fixed %))
(defmethod ->Holiday :fixed
[config]
(->Fixed config))
;; Weekday relative to fixed
(defmethod holiday-spec :relative-to-fixed [_]
(s/merge
`holiday-tag-common
(s/and
(s/keys :req-un [::when ::date] :opt-un [::days ::weekday])
#(some % [:days :weekday]))))
(defmethod ->Holiday :relative-to-fixed
[config]
(doto (RelativeToFixed.)
(set-common-holiday-attributes! config)
(.setWeekday (some-> config :weekday (->enum Weekday)))
(.setWhen (-> config :when (->enum When)))
(.setDate (-> config :date ->Fixed))
(.setDays (some-> config :days int))))
(defmethod holiday-spec :fixed-weekday-between-fixed [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [::weekday ::from ::to])))
(defmethod ->Holiday :fixed-weekday-between-fixed
[config]
(doto (FixedWeekdayBetweenFixed.)
(set-common-holiday-attributes! config)
(.setWeekday (some-> config :weekday (->enum Weekday)))
(.setFrom (-> config :from ->Fixed))
(.setTo (-> config :to ->Fixed))))
;; Weekday in month
(s/def ::fixed-weekday
(s/keys :req-un [::which ::weekday ::month]))
(defmethod holiday-spec :fixed-weekday [_]
(s/merge
`holiday-tag-common
::fixed-weekday))
(defn ->FixedWeekday
[config]
(doto (FixedWeekdayInMonth.)
(set-common-holiday-attributes! config)
(.setWhich (-> config :which (->enum Which)))
(.setWeekday (-> config :weekday (->enum Weekday)))
(.setMonth (-> config :month (->enum Month)))))
(s/fdef ->FixedWeekday
:args (s/cat :config ::fixed-weekday)
:ret #(instance? FixedWeekdayInMonth %))
(defmethod ->Holiday :fixed-weekday
[config]
(->FixedWeekday config))
;; Relative to weekday in month
(defmethod holiday-spec :relative-to-weekday-in-month [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [::weekday ::when ::fixed-weekday])))
(defmethod ->Holiday :relative-to-weekday-in-month
[config]
(doto (RelativeToWeekdayInMonth.)
(set-common-holiday-attributes! config)
(.setWeekday (-> config :weekday (->enum Weekday)))
(.setWhen (-> config :when (->enum When)))
(.setFixedWeekday (-> config :fixed-weekday ->FixedWeekday))))
;; Weekday relative to fixed day
(defmethod holiday-spec :fixed-weekday-relative-to-fixed [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [::which ::weekday ::when ::date])))
(defmethod ->Holiday :fixed-weekday-relative-to-fixed
[config]
(doto (FixedWeekdayRelativeToFixed.)
(set-common-holiday-attributes! config)
(.setWhich (-> config :which (->enum Which)))
(.setWeekday (-> config :weekday (->enum Weekday)))
(.setWhen (-> config :when (->enum When)))
(.setDay (-> config :date ->Fixed))))
;; Christian
(def christian-types
#{:good-friday :easter-monday :ascension-day :whit-monday :corpus-christi
:maundy-thursday :ash-wednesday :mardi-gras :general-prayer-day
:clean-monday :shrove-monday :pentecost :carnival :easter-saturday
:easter-tuesday :sacred-heart :easter :pentecost-monday :whit-sunday})
(s/def :christian/type christian-types)
(s/def ::chronology chronologies)
(defmethod holiday-spec :christian-holiday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [:christian/type] :opt-un [::chronology ::moving-conditions])))
(defmethod ->Holiday :christian-holiday
[config]
(doto (ChristianHoliday.)
(set-common-holiday-attributes! config)
(.setType (-> config :type (->enum ChristianHolidayType)))
(.setChronology (some-> config :chronology (->enum ChronologyType)))
(add-moving-conditions! config)))
(defmethod holiday-spec :relative-to-easter-sunday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [::chronology ::days])))
(defmethod ->Holiday :relative-to-easter-sunday
[config]
(doto (RelativeToEasterSunday.)
(set-common-holiday-attributes! config)
(.setChronology (some-> config :chronology (->enum ChronologyType)))
(.setDays (-> config :days int))))
;; Islamic
(def islamic-types
#{:newyear :aschura :mawlid-an-nabi :lailat-al-miraj :lailat-al-barat
:ramadan :lailat-al-qadr :id-al-fitr :id-ul-adha})
(s/def :islamic/type islamic-types)
(defmethod holiday-spec :islamic-holiday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [:islamic/type])))
(defmethod ->Holiday :islamic-holiday
[config]
(doto (IslamicHoliday.)
(set-common-holiday-attributes! config)
(.setType (-> config :type (->enum IslamicHolidayType)))))
;; Hindu
(def hindu-types
#{:holi})
(s/def :hindu/type hindu-types)
(defmethod holiday-spec :hindu-holiday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [:hindu/type])))
(defmethod ->Holiday :hindu-holiday
[config]
(doto (HinduHoliday.)
(set-common-holiday-attributes! config)
(.setType (-> config :type (->enum HinduHolidayType)))))
;; Hebrew
(def hebrew-types
#{:rosh-hashanah :aseret-yemei-teshuva :yom-kippur :sukkot :shemini-atzeret
:hanukkah :asarah-betevet :tu-bishvat :purim :1-nisan :pesach :sefirah
:lag-baomer :shavout :17-tammuz :tisha-bav :1-elul :rosh-codesh :shabbat
:yom-hashoah :yom-hazikaron :yom-haatzamaut :yom-yerushalaim})
(s/def :hebrew/type hebrew-types)
(defmethod holiday-spec :hebrew-holiday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [:hebrew/type])))
(defmethod ->Holiday :hebrew-holiday
[config]
(doto (HebrewHoliday.)
(set-common-holiday-attributes! config)
(.setType (-> config :type ->const-name))))
;; Ethiopian orthodox
(def ethiopian-orthodox-types
#{:timkat :enkutatash :meskel})
(s/def :ethiopian-orthodox/type ethiopian-orthodox-types)
(defmethod holiday-spec :ethiopian-orthodox-holiday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [:ethiopian-orthodox/type])))
(defmethod ->Holiday :ethiopian-orthodox-holiday
[config]
(doto (EthiopianOrthodoxHoliday.)
(set-common-holiday-attributes! config)
(.setType (-> config :type (->enum EthiopianOrthodoxHolidayType)))))
;; Copyright 2018 <NAME>
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
;; or implied. See the License for the specific language governing
;; permissions and limitations under the License.
| true | ;; Copyright and license information at end of file
(ns ferje.config.core
"Represent Jollyday configuration beans as clojure maps"
(:require
[clojure.spec.alpha :as s]
[clojure.string :as string]
[ferje.util :as util])
(:import
(de.jollyday.config
ChristianHoliday ChristianHolidayType ChronologyType Configuration
EthiopianOrthodoxHoliday EthiopianOrthodoxHolidayType Fixed
FixedWeekdayBetweenFixed FixedWeekdayInMonth FixedWeekdayRelativeToFixed
HebrewHoliday HinduHoliday HinduHolidayType Holiday HolidayType Holidays
IslamicHoliday IslamicHolidayType Month MovingCondition
RelativeToEasterSunday RelativeToFixed RelativeToWeekdayInMonth Weekday
When Which With)))
(def months #{:january :february :march :april :may :june
:july :august :september :october :november :december})
(def weekdays #{:monday :tuesday :wednesday :thursday :friday :saturday :sunday})
(def whichs #{:first :second :third :fourth :last})
(def whens #{:before :after})
(def everys #{:every-year :2-years :4-years :5-years :6-years :odd-years :even-years})
(def withs #{:next :previous})
(def chronologies #{:julian :gregorian})
(s/def ::day (s/int-in 1 32))
(s/def ::month months)
(s/def ::weekday weekdays)
(s/def ::which whichs)
(s/def ::when whens)
(s/def ::valid-from int?)
(s/def ::valid-to int?)
(s/def ::every everys)
(s/def ::description-key keyword?)
(s/def ::localized-type #{:official-holiday :unofficial-holiday})
(s/def ::substitute ::weekday)
(s/def ::with withs)
(s/def ::moving-conditions
(s/coll-of
(s/keys :req-un [::substitute ::with ::weekday])))
(s/def ::date
(s/keys :req-un [::month ::day]
:opt-un [::moving-conditions]))
(s/def ::from ::date)
(s/def ::to ::date)
(s/def ::days int?)
(s/def ::description string?)
(s/def ::hierarchy keyword?)
(s/def ::holidays (s/coll-of `holiday))
(s/def ::sub-configurations (s/coll-of ::configuration))
(s/def ::configuration
(s/keys :req-un [::description ::hierarchy ::holidays]
:opt-un [::sub-configurations]))
(defn holiday?
"Is x a Jollyday Holiday configuration object?"
[x]
(instance? Holiday x))
(s/fdef holiday?
:args (s/cat :x any?)
:ret boolean?)
(defn java-collection?
"Is x a Java collection?"
[x]
(instance? java.util.Collection x))
(s/fdef java-collection?
:args (s/cat :x any?)
:ret boolean?)
(defn named?
"Is x a valid argument to the `name` function?"
[x]
(or (instance? clojure.lang.Named x)
(string? x)))
(s/fdef named?
:args (s/cat :x any?)
:ret boolean?)
(s/def ::calendar-name named?)
(defn ->const-name
"Parse a :clojure-keyword to a JAVA_CONSTANT_NAME (as a strig)"
[x]
(-> x name string/upper-case (string/replace #"-" "_")))
(s/fdef ->const-name
:args (s/cat :x named?)
:ret (s/and string? util/uppercase?))
;;
(defmacro ->enum
"Parse a keyword to a value in a Java Enum"
[value enum]
`(-> ~value ->const-name (~(symbol (str enum) "valueOf"))))
(s/fdef ->enum
:args (s/cat :value any? :enum simple-symbol?)
:ret any?)
;;
(s/def ::holiday #{:islamic-holiday
:fixed-weekday
:hindu-holiday
:hebrew-holiday
:fixed-weekday-between-fixed
:fixed-weekday-relative-to-fixed
:relative-to-weekday-in-month
:relative-to-fixed
:relative-to-easter-sunday
:ethiopian-orthodox-holiday
:christian-holiday
:fixed})
(s/def holiday-common
(s/keys :opt-un [::valid-from ::valid-to ::every ::description-key ::localized-type]))
(s/def holiday-tag-common
(s/merge `holiday-common
(s/keys :req-un [::holiday])))
(defn add-moving-conditions!
"Add the moving conditions from a map to a Jollyday Holiday object"
[bean config]
(doto bean
(-> .getMovingCondition
(.addAll (map #(doto (MovingCondition.)
(.setSubstitute (-> % :substitute (->enum Weekday)))
(.setWith (-> % :with (->enum With)))
(.setWeekday (-> % :weekday (->enum Weekday))))
(:moving-conditions config))))))
(s/fdef add-moving-conditions!
:args (s/cat :bean holiday? :config map?)
:ret holiday?
:fn #(identical? (-> % :ret) (-> % :args :bean)))
(defmulti holiday-spec
"Returns the spec for a holiday definition"
:holiday)
(s/def holiday (s/multi-spec holiday-spec :holiday))
(defn set-common-holiday-attributes!
"Set a Jollyday `holiday`object with all those attributes from `config`
that are shared among all holiday types."
[holiday config]
(doto holiday
(.setValidFrom (some-> config :valid-from int))
(.setValidTo (some-> config :valid-to int))
(.setEvery (some-> config :every ->const-name))
(.setLocalizedType (some-> config :localized-type (->enum HolidayType)))
(.setDescriptionPropertiesKey (some-> config :description-key ->const-name))))
(s/fdef set-common-holiday-attributes!
:args (s/cat :bean holiday? :config `holiday-common)
:ret holiday?
:fn #(identical? (-> % :ret) (-> % :args :bean)))
;;
(defmulti ->Holiday
"Create a Jollyday holiday bean from an edn holiday configuration"
:holiday)
(defn add-holidays!
"Add holidays of a given `type` from `all-holidays` collection
to the `holidays` java collection"
[holidays all-holidays type]
(->> all-holidays
(filter #(instance? type %))
(.addAll holidays))
nil)
(s/fdef add-holidays!
:args (s/cat :holidays java-collection?
:all-holidays (s/coll-of holiday?)
:type #(.isAssignableFrom Holiday %))
:ret nil?)
(defmacro dispatch-holidays
"Sort Holiday objects by `types` into the corresponding slots
of a Holidays object."
[holidays & types]
(let [h (gensym "holidays")]
`(let [~h ~holidays]
(doto (Holidays.)
~@(for [t types]
`(-> (~(symbol (str ".get" t))) (add-holidays! ~h ~t)))))))
(s/fdef dispatch-holidays
:args (s/cat :holidays any? :types (s/* simple-symbol?))
:ret any?)
(defn ->Holidays
"Parse a collection of holiday configuration edn into a Jollyday
Holidays configuration bean."
[config]
(let [holidays (map ->Holiday config)]
(doto
(dispatch-holidays holidays
Fixed RelativeToFixed RelativeToWeekdayInMonth
ChristianHoliday IslamicHoliday
FixedWeekdayBetweenFixed FixedWeekdayRelativeToFixed
HinduHoliday HebrewHoliday EthiopianOrthodoxHoliday
RelativeToEasterSunday)
(-> (.getFixedWeekday) (add-holidays! holidays FixedWeekdayInMonth)))))
(s/fdef ->Holidays
:args (s/cat :config ::holidays)
:ret #(instance? Holidays %))
(declare add-sub-configurations!)
(defn ->Configuration
"Parse an edn `config` (top-level or for a subdivision)
into an Jollyday Configuration bean."
[config]
(doto (Configuration.)
(.setDescription (-> config :description))
(.setHierarchy (-> config :hierarchy name))
(.setHolidays (-> config :holidays ->Holidays))
(add-sub-configurations! config)))
(s/fdef ->Configuration
:args (s/cat :config ::configuration)
:ret #(instance? Configuration %))
(defn add-sub-configurations!
"Parse the configurations for geographical subdivisions from the edn `config`
and add them to the Jollyday `configuration` bean"
[configuration config]
(when-let [sub-configurations (some->> config :sub-configurations (map ->Configuration))]
(-> configuration .getSubConfigurations (.addAll sub-configurations))
nil))
(s/fdef add-sub-configurations!
:args (s/cat :configuration #(instance? Configuration %) :config ::configuration)
:ret nil?)
;; Fixed day
(defmethod holiday-spec :fixed [_]
(s/merge
`holiday-tag-common
::date))
(defn ->Fixed
"Create a Jollyday fixed holiday configuration bean from an edn map"
[config]
(doto (Fixed.)
(set-common-holiday-attributes! config)
(.setMonth (-> config :month (->enum Month)))
(.setDay (-> config :day int))
(add-moving-conditions! config)))
(s/fdef ->Fixed
:args (s/cat :config ::date)
:ret #(instance? Fixed %))
(defmethod ->Holiday :fixed
[config]
(->Fixed config))
;; Weekday relative to fixed
(defmethod holiday-spec :relative-to-fixed [_]
(s/merge
`holiday-tag-common
(s/and
(s/keys :req-un [::when ::date] :opt-un [::days ::weekday])
#(some % [:days :weekday]))))
(defmethod ->Holiday :relative-to-fixed
[config]
(doto (RelativeToFixed.)
(set-common-holiday-attributes! config)
(.setWeekday (some-> config :weekday (->enum Weekday)))
(.setWhen (-> config :when (->enum When)))
(.setDate (-> config :date ->Fixed))
(.setDays (some-> config :days int))))
(defmethod holiday-spec :fixed-weekday-between-fixed [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [::weekday ::from ::to])))
(defmethod ->Holiday :fixed-weekday-between-fixed
[config]
(doto (FixedWeekdayBetweenFixed.)
(set-common-holiday-attributes! config)
(.setWeekday (some-> config :weekday (->enum Weekday)))
(.setFrom (-> config :from ->Fixed))
(.setTo (-> config :to ->Fixed))))
;; Weekday in month
(s/def ::fixed-weekday
(s/keys :req-un [::which ::weekday ::month]))
(defmethod holiday-spec :fixed-weekday [_]
(s/merge
`holiday-tag-common
::fixed-weekday))
(defn ->FixedWeekday
[config]
(doto (FixedWeekdayInMonth.)
(set-common-holiday-attributes! config)
(.setWhich (-> config :which (->enum Which)))
(.setWeekday (-> config :weekday (->enum Weekday)))
(.setMonth (-> config :month (->enum Month)))))
(s/fdef ->FixedWeekday
:args (s/cat :config ::fixed-weekday)
:ret #(instance? FixedWeekdayInMonth %))
(defmethod ->Holiday :fixed-weekday
[config]
(->FixedWeekday config))
;; Relative to weekday in month
(defmethod holiday-spec :relative-to-weekday-in-month [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [::weekday ::when ::fixed-weekday])))
(defmethod ->Holiday :relative-to-weekday-in-month
[config]
(doto (RelativeToWeekdayInMonth.)
(set-common-holiday-attributes! config)
(.setWeekday (-> config :weekday (->enum Weekday)))
(.setWhen (-> config :when (->enum When)))
(.setFixedWeekday (-> config :fixed-weekday ->FixedWeekday))))
;; Weekday relative to fixed day
(defmethod holiday-spec :fixed-weekday-relative-to-fixed [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [::which ::weekday ::when ::date])))
(defmethod ->Holiday :fixed-weekday-relative-to-fixed
[config]
(doto (FixedWeekdayRelativeToFixed.)
(set-common-holiday-attributes! config)
(.setWhich (-> config :which (->enum Which)))
(.setWeekday (-> config :weekday (->enum Weekday)))
(.setWhen (-> config :when (->enum When)))
(.setDay (-> config :date ->Fixed))))
;; Christian
(def christian-types
#{:good-friday :easter-monday :ascension-day :whit-monday :corpus-christi
:maundy-thursday :ash-wednesday :mardi-gras :general-prayer-day
:clean-monday :shrove-monday :pentecost :carnival :easter-saturday
:easter-tuesday :sacred-heart :easter :pentecost-monday :whit-sunday})
(s/def :christian/type christian-types)
(s/def ::chronology chronologies)
(defmethod holiday-spec :christian-holiday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [:christian/type] :opt-un [::chronology ::moving-conditions])))
(defmethod ->Holiday :christian-holiday
[config]
(doto (ChristianHoliday.)
(set-common-holiday-attributes! config)
(.setType (-> config :type (->enum ChristianHolidayType)))
(.setChronology (some-> config :chronology (->enum ChronologyType)))
(add-moving-conditions! config)))
(defmethod holiday-spec :relative-to-easter-sunday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [::chronology ::days])))
(defmethod ->Holiday :relative-to-easter-sunday
[config]
(doto (RelativeToEasterSunday.)
(set-common-holiday-attributes! config)
(.setChronology (some-> config :chronology (->enum ChronologyType)))
(.setDays (-> config :days int))))
;; Islamic
(def islamic-types
#{:newyear :aschura :mawlid-an-nabi :lailat-al-miraj :lailat-al-barat
:ramadan :lailat-al-qadr :id-al-fitr :id-ul-adha})
(s/def :islamic/type islamic-types)
(defmethod holiday-spec :islamic-holiday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [:islamic/type])))
(defmethod ->Holiday :islamic-holiday
[config]
(doto (IslamicHoliday.)
(set-common-holiday-attributes! config)
(.setType (-> config :type (->enum IslamicHolidayType)))))
;; Hindu
(def hindu-types
#{:holi})
(s/def :hindu/type hindu-types)
(defmethod holiday-spec :hindu-holiday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [:hindu/type])))
(defmethod ->Holiday :hindu-holiday
[config]
(doto (HinduHoliday.)
(set-common-holiday-attributes! config)
(.setType (-> config :type (->enum HinduHolidayType)))))
;; Hebrew
(def hebrew-types
#{:rosh-hashanah :aseret-yemei-teshuva :yom-kippur :sukkot :shemini-atzeret
:hanukkah :asarah-betevet :tu-bishvat :purim :1-nisan :pesach :sefirah
:lag-baomer :shavout :17-tammuz :tisha-bav :1-elul :rosh-codesh :shabbat
:yom-hashoah :yom-hazikaron :yom-haatzamaut :yom-yerushalaim})
(s/def :hebrew/type hebrew-types)
(defmethod holiday-spec :hebrew-holiday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [:hebrew/type])))
(defmethod ->Holiday :hebrew-holiday
[config]
(doto (HebrewHoliday.)
(set-common-holiday-attributes! config)
(.setType (-> config :type ->const-name))))
;; Ethiopian orthodox
(def ethiopian-orthodox-types
#{:timkat :enkutatash :meskel})
(s/def :ethiopian-orthodox/type ethiopian-orthodox-types)
(defmethod holiday-spec :ethiopian-orthodox-holiday [_]
(s/merge
`holiday-tag-common
(s/keys :req-un [:ethiopian-orthodox/type])))
(defmethod ->Holiday :ethiopian-orthodox-holiday
[config]
(doto (EthiopianOrthodoxHoliday.)
(set-common-holiday-attributes! config)
(.setType (-> config :type (->enum EthiopianOrthodoxHolidayType)))))
;; Copyright 2018 PI:NAME:<NAME>END_PI
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
;; or implied. See the License for the specific language governing
;; permissions and limitations under the License.
|
[
{
"context": "sion-template/internal\"\n :username username\n :password password}\n {:",
"end": 761,
"score": 0.978154182434082,
"start": 753,
"tag": "USERNAME",
"value": "username"
},
{
"context": " :username username\n :password password}\n {:keys [status message] :as response} ",
"end": 797,
"score": 0.9985219240188599,
"start": 789,
"tag": "PASSWORD",
"value": "password"
}
] | cimi-tools/src/com/sixsq/slipstream/tools/cli/utils.clj | slipstream/SlipStreamServer | 6 | (ns com.sixsq.slipstream.tools.cli.utils
(:require
[clj-http.client :as http]
[clojure.edn :as edn]
[clojure.string :as str]
[com.sixsq.slipstream.db.serializers.service-config-util :as scu]
[sixsq.slipstream.client.api.authn :as authn]
[sixsq.slipstream.client.api.cimi :as cimi]
[sixsq.slipstream.client.sync :as cimi-sync]
[taoensso.timbre :as log]))
(def ^:dynamic *cimi-client* nil)
(defn cep-url
[endpoint]
(str endpoint "/api/cloud-entry-point"))
(defn create-cimi-client
[cep-url]
(alter-var-root #'*cimi-client* (constantly (cimi-sync/instance cep-url))))
(defn login
[username password]
(when *cimi-client*
(let [creds {:href "session-template/internal"
:username username
:password password}
{:keys [status message] :as response} (authn/login *cimi-client* creds)]
(when (not= 201 status)
(let [msg (cond-> (str "login failed with status (" status ")")
message (str ": " message))]
(log/error msg)
(throw (ex-info msg response)))))))
(defn ss-cfg
[]
(when *cimi-client*
(cimi/get *cimi-client* "configuration/slipstream")))
(defn ss-connectors
[]
(when *cimi-client*
(:connectors (cimi/search *cimi-client* "connectors" {:$last 500}))))
(defn split-creds
"Splits a credentials string formatted as 'username:password' into a tuple
[username password]."
[creds]
(if (string? creds)
(let [[username password] (str/split creds #":")]
[username password])
[nil nil]))
(defn replace-value
[value [pattern replacement]]
(if (string? value)
(str/replace value pattern replacement)
value))
(defn update-val
[modifiers [_ v]]
(reduce replace-value v modifiers))
(defn modify-vals
"Uses the list of modifiers to replace string values in the values at the
first level of the resource map."
[resource modifiers]
(let [convert-fn (partial update-val modifiers)]
(->> resource
(map (juxt first convert-fn))
(into {}))))
(def con-attrs-to-remove
{"ec2" [:securityGroup]
"nuvlabox" [:orchestratorInstanceType :pdiskEndpoint]
"stratuslab" [:messagingQueue :messagingType :messagingEndpoint]
"stratuslabiter" [:messagingQueue :messagingType :messagingEndpoint]})
(defn remove-attrs
"Cleanup of old attributes."
[con]
(if-let [attrs (get con-attrs-to-remove (:cloudServiceType con))]
(apply dissoc con attrs)
con))
(defn ss-cfg-url
[url]
(str url "/api/configuration/slipstream"))
(defn cfg-json
[endpoint-url]
(-> endpoint-url
ss-cfg-url
(http/get {:follow-redirects false
:accept :json})
:body))
(defn cfg-path-url->sc
[endpoint-url]
(cfg-json endpoint-url))
;;
;; file read/write utilities
;;
(defn slurp-edn
[f]
(edn/read-string (slurp f)))
(defn spit-edn
[obj f]
(scu/spit-pprint obj f))
;;
;; resource type utilities
;;
(defn resource-type-from-str
"Returns the base resource type from the string or nil if the type cannot be
determined."
[type-string]
(let [type (some-> type-string
(str/split #"(-template)?/")
first)]
(when-not (str/blank? type)
type)))
(defn resource-type
"Extracts the resource type from a string, resource, or request. Returns nil
if the resource type cannot be obtained."
[v]
(resource-type-from-str
(cond
(string? v) v
(:id v) (:id v)
:else (-> v :body :id))))
;;
;; utilities for dealing with command line args and shell
;;
(defn exit
([]
(exit 0 nil))
([status]
(exit status nil))
([status msg]
(when msg
(if-not (zero? status)
(log/error msg)
(log/info msg)))
(System/exit status)))
(defn success
([]
(exit))
([msg]
(exit 0 msg)))
(defn failure
[& msg]
(exit 1 (str/join msg)))
(defn error-msg
[errors]
(str "The following errors occurred while parsing your command:\n\n"
(str/join \newline errors)))
(defn cli-parse-sets
([m k v]
(cli-parse-sets m k v identity))
([m k v f] (assoc m k (if-let [oldval (get m k)]
(merge oldval (f v))
(hash-set (f v))))))
(defn cli-parse-connectors
[m k v]
(cli-parse-sets m k v))
(defn parse-replacement
"Parses replacement specifications of the form 'm=r' as the two-element
tuple [#'m' 'r']."
[replacement]
(let [[m r] (str/split replacement #"=")]
[(re-pattern m) r]))
(defn cli-parse-modifiers
[m k v]
(cli-parse-sets m k v parse-replacement))
| 72453 | (ns com.sixsq.slipstream.tools.cli.utils
(:require
[clj-http.client :as http]
[clojure.edn :as edn]
[clojure.string :as str]
[com.sixsq.slipstream.db.serializers.service-config-util :as scu]
[sixsq.slipstream.client.api.authn :as authn]
[sixsq.slipstream.client.api.cimi :as cimi]
[sixsq.slipstream.client.sync :as cimi-sync]
[taoensso.timbre :as log]))
(def ^:dynamic *cimi-client* nil)
(defn cep-url
[endpoint]
(str endpoint "/api/cloud-entry-point"))
(defn create-cimi-client
[cep-url]
(alter-var-root #'*cimi-client* (constantly (cimi-sync/instance cep-url))))
(defn login
[username password]
(when *cimi-client*
(let [creds {:href "session-template/internal"
:username username
:password <PASSWORD>}
{:keys [status message] :as response} (authn/login *cimi-client* creds)]
(when (not= 201 status)
(let [msg (cond-> (str "login failed with status (" status ")")
message (str ": " message))]
(log/error msg)
(throw (ex-info msg response)))))))
(defn ss-cfg
[]
(when *cimi-client*
(cimi/get *cimi-client* "configuration/slipstream")))
(defn ss-connectors
[]
(when *cimi-client*
(:connectors (cimi/search *cimi-client* "connectors" {:$last 500}))))
(defn split-creds
"Splits a credentials string formatted as 'username:password' into a tuple
[username password]."
[creds]
(if (string? creds)
(let [[username password] (str/split creds #":")]
[username password])
[nil nil]))
(defn replace-value
[value [pattern replacement]]
(if (string? value)
(str/replace value pattern replacement)
value))
(defn update-val
[modifiers [_ v]]
(reduce replace-value v modifiers))
(defn modify-vals
"Uses the list of modifiers to replace string values in the values at the
first level of the resource map."
[resource modifiers]
(let [convert-fn (partial update-val modifiers)]
(->> resource
(map (juxt first convert-fn))
(into {}))))
(def con-attrs-to-remove
{"ec2" [:securityGroup]
"nuvlabox" [:orchestratorInstanceType :pdiskEndpoint]
"stratuslab" [:messagingQueue :messagingType :messagingEndpoint]
"stratuslabiter" [:messagingQueue :messagingType :messagingEndpoint]})
(defn remove-attrs
"Cleanup of old attributes."
[con]
(if-let [attrs (get con-attrs-to-remove (:cloudServiceType con))]
(apply dissoc con attrs)
con))
(defn ss-cfg-url
[url]
(str url "/api/configuration/slipstream"))
(defn cfg-json
[endpoint-url]
(-> endpoint-url
ss-cfg-url
(http/get {:follow-redirects false
:accept :json})
:body))
(defn cfg-path-url->sc
[endpoint-url]
(cfg-json endpoint-url))
;;
;; file read/write utilities
;;
(defn slurp-edn
[f]
(edn/read-string (slurp f)))
(defn spit-edn
[obj f]
(scu/spit-pprint obj f))
;;
;; resource type utilities
;;
(defn resource-type-from-str
"Returns the base resource type from the string or nil if the type cannot be
determined."
[type-string]
(let [type (some-> type-string
(str/split #"(-template)?/")
first)]
(when-not (str/blank? type)
type)))
(defn resource-type
"Extracts the resource type from a string, resource, or request. Returns nil
if the resource type cannot be obtained."
[v]
(resource-type-from-str
(cond
(string? v) v
(:id v) (:id v)
:else (-> v :body :id))))
;;
;; utilities for dealing with command line args and shell
;;
(defn exit
([]
(exit 0 nil))
([status]
(exit status nil))
([status msg]
(when msg
(if-not (zero? status)
(log/error msg)
(log/info msg)))
(System/exit status)))
(defn success
([]
(exit))
([msg]
(exit 0 msg)))
(defn failure
[& msg]
(exit 1 (str/join msg)))
(defn error-msg
[errors]
(str "The following errors occurred while parsing your command:\n\n"
(str/join \newline errors)))
(defn cli-parse-sets
([m k v]
(cli-parse-sets m k v identity))
([m k v f] (assoc m k (if-let [oldval (get m k)]
(merge oldval (f v))
(hash-set (f v))))))
(defn cli-parse-connectors
[m k v]
(cli-parse-sets m k v))
(defn parse-replacement
"Parses replacement specifications of the form 'm=r' as the two-element
tuple [#'m' 'r']."
[replacement]
(let [[m r] (str/split replacement #"=")]
[(re-pattern m) r]))
(defn cli-parse-modifiers
[m k v]
(cli-parse-sets m k v parse-replacement))
| true | (ns com.sixsq.slipstream.tools.cli.utils
(:require
[clj-http.client :as http]
[clojure.edn :as edn]
[clojure.string :as str]
[com.sixsq.slipstream.db.serializers.service-config-util :as scu]
[sixsq.slipstream.client.api.authn :as authn]
[sixsq.slipstream.client.api.cimi :as cimi]
[sixsq.slipstream.client.sync :as cimi-sync]
[taoensso.timbre :as log]))
(def ^:dynamic *cimi-client* nil)
(defn cep-url
[endpoint]
(str endpoint "/api/cloud-entry-point"))
(defn create-cimi-client
[cep-url]
(alter-var-root #'*cimi-client* (constantly (cimi-sync/instance cep-url))))
(defn login
[username password]
(when *cimi-client*
(let [creds {:href "session-template/internal"
:username username
:password PI:PASSWORD:<PASSWORD>END_PI}
{:keys [status message] :as response} (authn/login *cimi-client* creds)]
(when (not= 201 status)
(let [msg (cond-> (str "login failed with status (" status ")")
message (str ": " message))]
(log/error msg)
(throw (ex-info msg response)))))))
(defn ss-cfg
[]
(when *cimi-client*
(cimi/get *cimi-client* "configuration/slipstream")))
(defn ss-connectors
[]
(when *cimi-client*
(:connectors (cimi/search *cimi-client* "connectors" {:$last 500}))))
(defn split-creds
"Splits a credentials string formatted as 'username:password' into a tuple
[username password]."
[creds]
(if (string? creds)
(let [[username password] (str/split creds #":")]
[username password])
[nil nil]))
(defn replace-value
[value [pattern replacement]]
(if (string? value)
(str/replace value pattern replacement)
value))
(defn update-val
[modifiers [_ v]]
(reduce replace-value v modifiers))
(defn modify-vals
"Uses the list of modifiers to replace string values in the values at the
first level of the resource map."
[resource modifiers]
(let [convert-fn (partial update-val modifiers)]
(->> resource
(map (juxt first convert-fn))
(into {}))))
(def con-attrs-to-remove
{"ec2" [:securityGroup]
"nuvlabox" [:orchestratorInstanceType :pdiskEndpoint]
"stratuslab" [:messagingQueue :messagingType :messagingEndpoint]
"stratuslabiter" [:messagingQueue :messagingType :messagingEndpoint]})
(defn remove-attrs
"Cleanup of old attributes."
[con]
(if-let [attrs (get con-attrs-to-remove (:cloudServiceType con))]
(apply dissoc con attrs)
con))
(defn ss-cfg-url
[url]
(str url "/api/configuration/slipstream"))
(defn cfg-json
[endpoint-url]
(-> endpoint-url
ss-cfg-url
(http/get {:follow-redirects false
:accept :json})
:body))
(defn cfg-path-url->sc
[endpoint-url]
(cfg-json endpoint-url))
;;
;; file read/write utilities
;;
(defn slurp-edn
[f]
(edn/read-string (slurp f)))
(defn spit-edn
[obj f]
(scu/spit-pprint obj f))
;;
;; resource type utilities
;;
(defn resource-type-from-str
"Returns the base resource type from the string or nil if the type cannot be
determined."
[type-string]
(let [type (some-> type-string
(str/split #"(-template)?/")
first)]
(when-not (str/blank? type)
type)))
(defn resource-type
"Extracts the resource type from a string, resource, or request. Returns nil
if the resource type cannot be obtained."
[v]
(resource-type-from-str
(cond
(string? v) v
(:id v) (:id v)
:else (-> v :body :id))))
;;
;; utilities for dealing with command line args and shell
;;
(defn exit
([]
(exit 0 nil))
([status]
(exit status nil))
([status msg]
(when msg
(if-not (zero? status)
(log/error msg)
(log/info msg)))
(System/exit status)))
(defn success
([]
(exit))
([msg]
(exit 0 msg)))
(defn failure
[& msg]
(exit 1 (str/join msg)))
(defn error-msg
[errors]
(str "The following errors occurred while parsing your command:\n\n"
(str/join \newline errors)))
(defn cli-parse-sets
([m k v]
(cli-parse-sets m k v identity))
([m k v f] (assoc m k (if-let [oldval (get m k)]
(merge oldval (f v))
(hash-set (f v))))))
(defn cli-parse-connectors
[m k v]
(cli-parse-sets m k v))
(defn parse-replacement
"Parses replacement specifications of the form 'm=r' as the two-element
tuple [#'m' 'r']."
[replacement]
(let [[m r] (str/split replacement #"=")]
[(re-pattern m) r]))
(defn cli-parse-modifiers
[m k v]
(cli-parse-sets m k v parse-replacement))
|
[
{
"context": " 123\n :senderUsername \"senderUsername\"\n :senderPassword \"sen",
"end": 525,
"score": 0.9995288848876953,
"start": 511,
"tag": "USERNAME",
"value": "senderUsername"
},
{
"context": "ame\"\n :senderPassword \"senderPwd\"\n :senderEmail \"sender",
"end": 581,
"score": 0.9993019104003906,
"start": 572,
"tag": "PASSWORD",
"value": "senderPwd"
},
{
"context": "derPwd\"\n :senderEmail \"sender@domain.com\"\n :senderId \"senderId\"",
"end": 642,
"score": 0.999917209148407,
"start": 625,
"tag": "EMAIL",
"value": "sender@domain.com"
},
{
"context": "omain.com\"\n :senderId \"senderId\"})\n\n(def email-info-for-tests {:recipients \"one@d",
"end": 691,
"score": 0.9540669918060303,
"start": 683,
"tag": "USERNAME",
"value": "senderId"
},
{
"context": "derId\"})\n\n(def email-info-for-tests {:recipients \"one@domain.com\"\n :subject \"subject\"\n ",
"end": 750,
"score": 0.9999090433120728,
"start": 736,
"tag": "EMAIL",
"value": "one@domain.com"
},
{
"context": " :ssl true\n :user \"senderUsername\"\n :pass \"senderPwd",
"end": 998,
"score": 0.9995236396789551,
"start": 984,
"tag": "USERNAME",
"value": "senderUsername"
},
{
"context": "rUsername\"\n :pass \"senderPwd\"})\n\n(def mail-message-for-tests {:from \"sender@do",
"end": 1048,
"score": 0.9992847442626953,
"start": 1039,
"tag": "PASSWORD",
"value": "senderPwd"
},
{
"context": "senderPwd\"})\n\n(def mail-message-for-tests {:from \"sender@domain.com\"\n :to \"one@domain.com",
"end": 1106,
"score": 0.9999178647994995,
"start": 1089,
"tag": "EMAIL",
"value": "sender@domain.com"
},
{
"context": "der@domain.com\"\n :to \"one@domain.com\"\n :subject \"subject\"\n",
"end": 1156,
"score": 0.9999151229858398,
"start": 1142,
"tag": "EMAIL",
"value": "one@domain.com"
}
] | test/mofficer/domain/business/email_business_test.clj | granpanda/mofficer | 1 | (ns mofficer.domain.business.email-business-test
(:use [midje.sweet])
(:require [mofficer.domain.business.user-config-business :as user-config-business]
[mofficer.domain.business.email-business :as email-business]
[mofficer.infrastructure.datastructures.either])
(:import [mofficer.infrastructure.datastructures.either Either]))
(def user-config-for-tests {:emailHost "http://www.gmail.com"
:emailPort 123
:senderUsername "senderUsername"
:senderPassword "senderPwd"
:senderEmail "sender@domain.com"
:senderId "senderId"})
(def email-info-for-tests {:recipients "one@domain.com"
:subject "subject"
:body "Halo!"})
(def mail-connection-for-tests {:host "http://www.gmail.com"
:ssl true
:user "senderUsername"
:pass "senderPwd"})
(def mail-message-for-tests {:from "sender@domain.com"
:to "one@domain.com"
:subject "subject"
:body "Halo!"})
(facts "About the email-business:"
(fact "The get-mail-connection function returns the mail connection required by postal given an user-config"
(email-business/get-mail-connection user-config-for-tests) => mail-connection-for-tests)
(fact "The get-mail-message function returns the mail message required by postal given an email-info"
(email-business/get-mail-message user-config-for-tests email-info-for-tests) => mail-message-for-tests))
| 42828 | (ns mofficer.domain.business.email-business-test
(:use [midje.sweet])
(:require [mofficer.domain.business.user-config-business :as user-config-business]
[mofficer.domain.business.email-business :as email-business]
[mofficer.infrastructure.datastructures.either])
(:import [mofficer.infrastructure.datastructures.either Either]))
(def user-config-for-tests {:emailHost "http://www.gmail.com"
:emailPort 123
:senderUsername "senderUsername"
:senderPassword "<PASSWORD>"
:senderEmail "<EMAIL>"
:senderId "senderId"})
(def email-info-for-tests {:recipients "<EMAIL>"
:subject "subject"
:body "Halo!"})
(def mail-connection-for-tests {:host "http://www.gmail.com"
:ssl true
:user "senderUsername"
:pass "<PASSWORD>"})
(def mail-message-for-tests {:from "<EMAIL>"
:to "<EMAIL>"
:subject "subject"
:body "Halo!"})
(facts "About the email-business:"
(fact "The get-mail-connection function returns the mail connection required by postal given an user-config"
(email-business/get-mail-connection user-config-for-tests) => mail-connection-for-tests)
(fact "The get-mail-message function returns the mail message required by postal given an email-info"
(email-business/get-mail-message user-config-for-tests email-info-for-tests) => mail-message-for-tests))
| true | (ns mofficer.domain.business.email-business-test
(:use [midje.sweet])
(:require [mofficer.domain.business.user-config-business :as user-config-business]
[mofficer.domain.business.email-business :as email-business]
[mofficer.infrastructure.datastructures.either])
(:import [mofficer.infrastructure.datastructures.either Either]))
(def user-config-for-tests {:emailHost "http://www.gmail.com"
:emailPort 123
:senderUsername "senderUsername"
:senderPassword "PI:PASSWORD:<PASSWORD>END_PI"
:senderEmail "PI:EMAIL:<EMAIL>END_PI"
:senderId "senderId"})
(def email-info-for-tests {:recipients "PI:EMAIL:<EMAIL>END_PI"
:subject "subject"
:body "Halo!"})
(def mail-connection-for-tests {:host "http://www.gmail.com"
:ssl true
:user "senderUsername"
:pass "PI:PASSWORD:<PASSWORD>END_PI"})
(def mail-message-for-tests {:from "PI:EMAIL:<EMAIL>END_PI"
:to "PI:EMAIL:<EMAIL>END_PI"
:subject "subject"
:body "Halo!"})
(facts "About the email-business:"
(fact "The get-mail-connection function returns the mail connection required by postal given an user-config"
(email-business/get-mail-connection user-config-for-tests) => mail-connection-for-tests)
(fact "The get-mail-message function returns the mail message required by postal given an email-info"
(email-business/get-mail-message user-config-for-tests email-info-for-tests) => mail-message-for-tests))
|
[
{
"context": "ogin \"login\")\n (is LoginService.user.password \"secret\")))\n\n[[:section {:title \"filters\" :tag \"filters\"}",
"end": 2180,
"score": 0.9994540810585022,
"start": 2174,
"tag": "PASSWORD",
"value": "secret"
}
] | test/cljs/midje_doc/api/test_gyr.cljs | zcaudate-me/gyr | 1 | (ns midje-doc.api.test-gyr
(:require [purnam.test]
[purnam.native]
[midje-doc.api.gyr :as test-app])
(:use-macros [purnam.core :only [f.n def.n obj arr]]
[purnam.test :only [describe is it]]
[gyr.core :only [def.module def.controller def.service]]
[gyr.test :only [describe.ng describe.controller it-uses it-uses-filter it-compiles]]))
[[:chapter {:title "gyr.test" :tag "gyr-test"}]]
[[:section {:title "init" :tag "gyr-init"}]]
"All tests require the following declaration in the namespace. Note that `purnam.test` is required"
(comment
(:require [purnam.test])
(:use-macros [gyr.test :only
[describe.ng it-uses it-compiles it-uses-filter]]))
[[:section {:title "services" :tag "services"}]]
"Angular constants, values, services, factories and providers are all tested the same way: with `describe.ng` and `it-uses`. There are a couple ways of testing out functionality. The easiest is with `:inject`. The definition are from previously defined examples - [constant](#def-constant), [value](#def-value)"
(describe.ng
{:doc "The Meaning of Life"
:module my.app
:inject [MeaningOfLife AnotherMeaningOfLife]}
(it "should be contentious"
(is MeaningOfLife 42)
(is AnotherMeaningOfLife "A Mystery")))
"`:inject` can also be used to bind other values within the modules"
(describe.ng
{:doc "The Meaning of Life"
:module my.app
:inject [[MeaningOfLife ([] "Don't Know")]]}
(it "should be unclear"
(is MeaningOfLife "Don't Know")))
"or to reference other defined services:"
(describe.ng
{:doc "The Meaning of Life"
:module my.app
:inject [[AnotherMeaningOfLife
([MeaningOfLife]
(+ 13 MeaningOfLife))]]}
(it "should be another random number"
(is AnotherMeaningOfLife 55)))
"[services](#def-service) are tested the same way. However this time, we will use `it-uses` to inject them into the test suite. It uses just puts the default"
(describe.ng
{:doc "Login Service"
:module my.app}
(it-uses [LoginService]
(is LoginService.user.login "login")
(is LoginService.user.password "secret")))
[[:section {:title "filters" :tag "filters"}]]
"Filters are dependent on the `$filters` service and so are tested in the following way."
(describe.ng
{:doc "Testing Filters"
:module my.app}
(it-uses [$filter]
(let [r (($filter "range") (arr) 5)]
(is r.length 5)
(is r (arr 0 1 2 3 4)))))
"A convience macro `it-uses-filter` can also be used to achieve the same effect."
(describe.ng
{:doc "Testing Filters"
:module my.app}
(it-uses-filter [range]
(let [r (range (arr) 5)]
(is r.length 5)
(is r (arr 0 1 2 3 4)))))
[[:section {:title "directives" :tag "directives"}]]
"Directives require the `$compile` and `$rootScope` services."
(describe.ng
{:doc "Directives"
:module my.app
:inject [$compile $rootScope]}
(it "should change the html output"
(let [ele (($compile "<div app-welcome>User</div>")
$rootScope)]
;;(js/console.log ele (ele.html))
(is (ele.html) (type "Welome <strong>User</strong>")))))
"For convenience, there is the `it-compiles` macro which hides the implementation details."
(describe.ng
{:doc "Directives"
:module my.app}
(it-compiles [ele "<div app-welcome>User</div>"]
(is (ele.html) (type "Welome <strong>User</strong>"))))
[[:section {:title "controllers" :tag "controllers"}]]
"Controllers require a bit more boilerplate to set up testing. The following is a test for [SimpleCtrl](#def-controller) using describe.ng"
(describe.ng
{:doc "A sample controller for testing purposes"
:module my.app
:inject [[$scope ([$rootScope $controller]
($controller "SimpleCtrl" (obj :$scope ($rootScope.$new))))]]}
(it "should set a message within the $scope"
(is $scope.msg "Hello"))
(it "should be able to change the message within the $scope"
(do ($scope.setMessage "World!")
(is $scope.msg "World!"))
(do ($scope.setMessage "Angular Rocks!")
(is $scope.msg "Angular Rocks!"))))
"`describe.controller` hides all implementation details to make the tests much more clearer to read."
(describe.controller
{:doc "A sample controller for testing purposes"
:module my.app
:controller SimpleCtrl}
(it "should set a message within the $scope"
(is $scope.msg "Hello"))
(it "should be able to change the message within the $scope"
(do ($scope.setMessage "World!")
(is $scope.msg "World!"))
(do ($scope.setMessage "Angular Rocks!")
(is $scope.msg "Angular Rocks!"))))
| 71353 | (ns midje-doc.api.test-gyr
(:require [purnam.test]
[purnam.native]
[midje-doc.api.gyr :as test-app])
(:use-macros [purnam.core :only [f.n def.n obj arr]]
[purnam.test :only [describe is it]]
[gyr.core :only [def.module def.controller def.service]]
[gyr.test :only [describe.ng describe.controller it-uses it-uses-filter it-compiles]]))
[[:chapter {:title "gyr.test" :tag "gyr-test"}]]
[[:section {:title "init" :tag "gyr-init"}]]
"All tests require the following declaration in the namespace. Note that `purnam.test` is required"
(comment
(:require [purnam.test])
(:use-macros [gyr.test :only
[describe.ng it-uses it-compiles it-uses-filter]]))
[[:section {:title "services" :tag "services"}]]
"Angular constants, values, services, factories and providers are all tested the same way: with `describe.ng` and `it-uses`. There are a couple ways of testing out functionality. The easiest is with `:inject`. The definition are from previously defined examples - [constant](#def-constant), [value](#def-value)"
(describe.ng
{:doc "The Meaning of Life"
:module my.app
:inject [MeaningOfLife AnotherMeaningOfLife]}
(it "should be contentious"
(is MeaningOfLife 42)
(is AnotherMeaningOfLife "A Mystery")))
"`:inject` can also be used to bind other values within the modules"
(describe.ng
{:doc "The Meaning of Life"
:module my.app
:inject [[MeaningOfLife ([] "Don't Know")]]}
(it "should be unclear"
(is MeaningOfLife "Don't Know")))
"or to reference other defined services:"
(describe.ng
{:doc "The Meaning of Life"
:module my.app
:inject [[AnotherMeaningOfLife
([MeaningOfLife]
(+ 13 MeaningOfLife))]]}
(it "should be another random number"
(is AnotherMeaningOfLife 55)))
"[services](#def-service) are tested the same way. However this time, we will use `it-uses` to inject them into the test suite. It uses just puts the default"
(describe.ng
{:doc "Login Service"
:module my.app}
(it-uses [LoginService]
(is LoginService.user.login "login")
(is LoginService.user.password "<PASSWORD>")))
[[:section {:title "filters" :tag "filters"}]]
"Filters are dependent on the `$filters` service and so are tested in the following way."
(describe.ng
{:doc "Testing Filters"
:module my.app}
(it-uses [$filter]
(let [r (($filter "range") (arr) 5)]
(is r.length 5)
(is r (arr 0 1 2 3 4)))))
"A convience macro `it-uses-filter` can also be used to achieve the same effect."
(describe.ng
{:doc "Testing Filters"
:module my.app}
(it-uses-filter [range]
(let [r (range (arr) 5)]
(is r.length 5)
(is r (arr 0 1 2 3 4)))))
[[:section {:title "directives" :tag "directives"}]]
"Directives require the `$compile` and `$rootScope` services."
(describe.ng
{:doc "Directives"
:module my.app
:inject [$compile $rootScope]}
(it "should change the html output"
(let [ele (($compile "<div app-welcome>User</div>")
$rootScope)]
;;(js/console.log ele (ele.html))
(is (ele.html) (type "Welome <strong>User</strong>")))))
"For convenience, there is the `it-compiles` macro which hides the implementation details."
(describe.ng
{:doc "Directives"
:module my.app}
(it-compiles [ele "<div app-welcome>User</div>"]
(is (ele.html) (type "Welome <strong>User</strong>"))))
[[:section {:title "controllers" :tag "controllers"}]]
"Controllers require a bit more boilerplate to set up testing. The following is a test for [SimpleCtrl](#def-controller) using describe.ng"
(describe.ng
{:doc "A sample controller for testing purposes"
:module my.app
:inject [[$scope ([$rootScope $controller]
($controller "SimpleCtrl" (obj :$scope ($rootScope.$new))))]]}
(it "should set a message within the $scope"
(is $scope.msg "Hello"))
(it "should be able to change the message within the $scope"
(do ($scope.setMessage "World!")
(is $scope.msg "World!"))
(do ($scope.setMessage "Angular Rocks!")
(is $scope.msg "Angular Rocks!"))))
"`describe.controller` hides all implementation details to make the tests much more clearer to read."
(describe.controller
{:doc "A sample controller for testing purposes"
:module my.app
:controller SimpleCtrl}
(it "should set a message within the $scope"
(is $scope.msg "Hello"))
(it "should be able to change the message within the $scope"
(do ($scope.setMessage "World!")
(is $scope.msg "World!"))
(do ($scope.setMessage "Angular Rocks!")
(is $scope.msg "Angular Rocks!"))))
| true | (ns midje-doc.api.test-gyr
(:require [purnam.test]
[purnam.native]
[midje-doc.api.gyr :as test-app])
(:use-macros [purnam.core :only [f.n def.n obj arr]]
[purnam.test :only [describe is it]]
[gyr.core :only [def.module def.controller def.service]]
[gyr.test :only [describe.ng describe.controller it-uses it-uses-filter it-compiles]]))
[[:chapter {:title "gyr.test" :tag "gyr-test"}]]
[[:section {:title "init" :tag "gyr-init"}]]
"All tests require the following declaration in the namespace. Note that `purnam.test` is required"
(comment
(:require [purnam.test])
(:use-macros [gyr.test :only
[describe.ng it-uses it-compiles it-uses-filter]]))
[[:section {:title "services" :tag "services"}]]
"Angular constants, values, services, factories and providers are all tested the same way: with `describe.ng` and `it-uses`. There are a couple ways of testing out functionality. The easiest is with `:inject`. The definition are from previously defined examples - [constant](#def-constant), [value](#def-value)"
(describe.ng
{:doc "The Meaning of Life"
:module my.app
:inject [MeaningOfLife AnotherMeaningOfLife]}
(it "should be contentious"
(is MeaningOfLife 42)
(is AnotherMeaningOfLife "A Mystery")))
"`:inject` can also be used to bind other values within the modules"
(describe.ng
{:doc "The Meaning of Life"
:module my.app
:inject [[MeaningOfLife ([] "Don't Know")]]}
(it "should be unclear"
(is MeaningOfLife "Don't Know")))
"or to reference other defined services:"
(describe.ng
{:doc "The Meaning of Life"
:module my.app
:inject [[AnotherMeaningOfLife
([MeaningOfLife]
(+ 13 MeaningOfLife))]]}
(it "should be another random number"
(is AnotherMeaningOfLife 55)))
"[services](#def-service) are tested the same way. However this time, we will use `it-uses` to inject them into the test suite. It uses just puts the default"
(describe.ng
{:doc "Login Service"
:module my.app}
(it-uses [LoginService]
(is LoginService.user.login "login")
(is LoginService.user.password "PI:PASSWORD:<PASSWORD>END_PI")))
[[:section {:title "filters" :tag "filters"}]]
"Filters are dependent on the `$filters` service and so are tested in the following way."
(describe.ng
{:doc "Testing Filters"
:module my.app}
(it-uses [$filter]
(let [r (($filter "range") (arr) 5)]
(is r.length 5)
(is r (arr 0 1 2 3 4)))))
"A convience macro `it-uses-filter` can also be used to achieve the same effect."
(describe.ng
{:doc "Testing Filters"
:module my.app}
(it-uses-filter [range]
(let [r (range (arr) 5)]
(is r.length 5)
(is r (arr 0 1 2 3 4)))))
[[:section {:title "directives" :tag "directives"}]]
"Directives require the `$compile` and `$rootScope` services."
(describe.ng
{:doc "Directives"
:module my.app
:inject [$compile $rootScope]}
(it "should change the html output"
(let [ele (($compile "<div app-welcome>User</div>")
$rootScope)]
;;(js/console.log ele (ele.html))
(is (ele.html) (type "Welome <strong>User</strong>")))))
"For convenience, there is the `it-compiles` macro which hides the implementation details."
(describe.ng
{:doc "Directives"
:module my.app}
(it-compiles [ele "<div app-welcome>User</div>"]
(is (ele.html) (type "Welome <strong>User</strong>"))))
[[:section {:title "controllers" :tag "controllers"}]]
"Controllers require a bit more boilerplate to set up testing. The following is a test for [SimpleCtrl](#def-controller) using describe.ng"
(describe.ng
{:doc "A sample controller for testing purposes"
:module my.app
:inject [[$scope ([$rootScope $controller]
($controller "SimpleCtrl" (obj :$scope ($rootScope.$new))))]]}
(it "should set a message within the $scope"
(is $scope.msg "Hello"))
(it "should be able to change the message within the $scope"
(do ($scope.setMessage "World!")
(is $scope.msg "World!"))
(do ($scope.setMessage "Angular Rocks!")
(is $scope.msg "Angular Rocks!"))))
"`describe.controller` hides all implementation details to make the tests much more clearer to read."
(describe.controller
{:doc "A sample controller for testing purposes"
:module my.app
:controller SimpleCtrl}
(it "should set a message within the $scope"
(is $scope.msg "Hello"))
(it "should be able to change the message within the $scope"
(do ($scope.setMessage "World!")
(is $scope.msg "World!"))
(do ($scope.setMessage "Angular Rocks!")
(is $scope.msg "Angular Rocks!"))))
|
[
{
"context": "-------------------\n;; File util.clj\n;; Written by Chris Frisz\n;; \n;; Created 26 Apr 2012\n;; Last modified 20 Oc",
"end": 115,
"score": 0.9998233914375305,
"start": 104,
"tag": "NAME",
"value": "Chris Frisz"
}
] | src/ctco/util.clj | cjfrisz/clojure-tco | 64 | ;;----------------------------------------------------------------------
;; File util.clj
;; Written by Chris Frisz
;;
;; Created 26 Apr 2012
;; Last modified 20 Oct 2012
;;
;; Defines miscellaneous utility functions for use in CTCO. These
;; include:
;; new-var
;; simple-op?
;; serious?
;; trivial?
;; extend-group
;;----------------------------------------------------------------------
(ns ctco.util
(:require [ctco.expr
simple]
[ctco.protocol :as proto])
(:import [ctco.expr.simple
Simple]))
(defn new-var
"Returns a unique variable for use in the TCO compiler either with a given
base symbol or a default base symbol."
([base]
(let [new-var (gensym base)]
(Simple. new-var)))
([]
(let [base "x"]
(new-var base))))
(defn simple-op?
"Predicate returning whether op is a simple, value-returning operator."
[op]
(some #{op}
'(+ - * / mod < <= = >= > and or not
inc dec zero? true? false? nil?
instance? fn? type ref ref-set deref
cons conj with-meta meta)))
(defn serious?
"Given a Clojure TCO expression (as a record type), returns whether the
expression is serious with respect to the Danvy first-order one-pass CPS
transformation."
[expr]
(extends? proto/PCpsSrs (type expr)))
(defn trivial?
"Given a Clojure TCO expression (as a record type), returns whether the
expression is trivial with respect to the Danvy first-order one-pass CPS
transformation."
[expr]
(extends? proto/PCpsTriv (type expr)))
(defmacro extend-multi
"Like extend, but takes a set of types/classes which will all be extended with
the given protocol and method map pairs using the same syntax as defrecord for
protocol function implementations."
[atype* & proto+mmap*]
(loop [proto+mmap* proto+mmap*
fn-map* []
ext-body []]
(if (nil? (seq proto+mmap*))
`(let ~fn-map* ~@(map (fn [a] `(extend ~a ~@ext-body)) atype*))
(let [fst (first proto+mmap*)
nxt (next proto+mmap*)]
(if (list? fst)
(let [map-var (gensym "fn-map")]
(recur nxt
(conj fn-map*
map-var
{(keyword (first fst))
(cons 'fn (next fst))})
(conj ext-body map-var)))
(recur nxt
fn-map*
(conj ext-body fst)))))))
| 102229 | ;;----------------------------------------------------------------------
;; File util.clj
;; Written by <NAME>
;;
;; Created 26 Apr 2012
;; Last modified 20 Oct 2012
;;
;; Defines miscellaneous utility functions for use in CTCO. These
;; include:
;; new-var
;; simple-op?
;; serious?
;; trivial?
;; extend-group
;;----------------------------------------------------------------------
(ns ctco.util
(:require [ctco.expr
simple]
[ctco.protocol :as proto])
(:import [ctco.expr.simple
Simple]))
(defn new-var
"Returns a unique variable for use in the TCO compiler either with a given
base symbol or a default base symbol."
([base]
(let [new-var (gensym base)]
(Simple. new-var)))
([]
(let [base "x"]
(new-var base))))
(defn simple-op?
"Predicate returning whether op is a simple, value-returning operator."
[op]
(some #{op}
'(+ - * / mod < <= = >= > and or not
inc dec zero? true? false? nil?
instance? fn? type ref ref-set deref
cons conj with-meta meta)))
(defn serious?
"Given a Clojure TCO expression (as a record type), returns whether the
expression is serious with respect to the Danvy first-order one-pass CPS
transformation."
[expr]
(extends? proto/PCpsSrs (type expr)))
(defn trivial?
"Given a Clojure TCO expression (as a record type), returns whether the
expression is trivial with respect to the Danvy first-order one-pass CPS
transformation."
[expr]
(extends? proto/PCpsTriv (type expr)))
(defmacro extend-multi
"Like extend, but takes a set of types/classes which will all be extended with
the given protocol and method map pairs using the same syntax as defrecord for
protocol function implementations."
[atype* & proto+mmap*]
(loop [proto+mmap* proto+mmap*
fn-map* []
ext-body []]
(if (nil? (seq proto+mmap*))
`(let ~fn-map* ~@(map (fn [a] `(extend ~a ~@ext-body)) atype*))
(let [fst (first proto+mmap*)
nxt (next proto+mmap*)]
(if (list? fst)
(let [map-var (gensym "fn-map")]
(recur nxt
(conj fn-map*
map-var
{(keyword (first fst))
(cons 'fn (next fst))})
(conj ext-body map-var)))
(recur nxt
fn-map*
(conj ext-body fst)))))))
| true | ;;----------------------------------------------------------------------
;; File util.clj
;; Written by PI:NAME:<NAME>END_PI
;;
;; Created 26 Apr 2012
;; Last modified 20 Oct 2012
;;
;; Defines miscellaneous utility functions for use in CTCO. These
;; include:
;; new-var
;; simple-op?
;; serious?
;; trivial?
;; extend-group
;;----------------------------------------------------------------------
(ns ctco.util
(:require [ctco.expr
simple]
[ctco.protocol :as proto])
(:import [ctco.expr.simple
Simple]))
(defn new-var
"Returns a unique variable for use in the TCO compiler either with a given
base symbol or a default base symbol."
([base]
(let [new-var (gensym base)]
(Simple. new-var)))
([]
(let [base "x"]
(new-var base))))
(defn simple-op?
"Predicate returning whether op is a simple, value-returning operator."
[op]
(some #{op}
'(+ - * / mod < <= = >= > and or not
inc dec zero? true? false? nil?
instance? fn? type ref ref-set deref
cons conj with-meta meta)))
(defn serious?
"Given a Clojure TCO expression (as a record type), returns whether the
expression is serious with respect to the Danvy first-order one-pass CPS
transformation."
[expr]
(extends? proto/PCpsSrs (type expr)))
(defn trivial?
"Given a Clojure TCO expression (as a record type), returns whether the
expression is trivial with respect to the Danvy first-order one-pass CPS
transformation."
[expr]
(extends? proto/PCpsTriv (type expr)))
(defmacro extend-multi
"Like extend, but takes a set of types/classes which will all be extended with
the given protocol and method map pairs using the same syntax as defrecord for
protocol function implementations."
[atype* & proto+mmap*]
(loop [proto+mmap* proto+mmap*
fn-map* []
ext-body []]
(if (nil? (seq proto+mmap*))
`(let ~fn-map* ~@(map (fn [a] `(extend ~a ~@ext-body)) atype*))
(let [fst (first proto+mmap*)
nxt (next proto+mmap*)]
(if (list? fst)
(let [map-var (gensym "fn-map")]
(recur nxt
(conj fn-map*
map-var
{(keyword (first fst))
(cons 'fn (next fst))})
(conj ext-body map-var)))
(recur nxt
fn-map*
(conj ext-body fst)))))))
|
[
{
"context": "-url (ev \"CALDAV_URL\"))\n(def caldav-username (ev \"CALDAV_USERNAME\"))\n(def caldav-password (ev \"CALDAV_PASSWORD\"))\n(",
"end": 320,
"score": 0.9901763796806335,
"start": 305,
"tag": "USERNAME",
"value": "CALDAV_USERNAME"
},
{
"context": "(ev \"CALDAV_USERNAME\"))\n(def caldav-password (ev \"CALDAV_PASSWORD\"))\n(def passphrase (ev \"PASSPHRASE\"))\n",
"end": 365,
"score": 0.9965783953666687,
"start": 350,
"tag": "PASSWORD",
"value": "CALDAV_PASSWORD"
},
{
"context": "word (ev \"CALDAV_PASSWORD\"))\n(def passphrase (ev \"PASSPHRASE\"))\n",
"end": 400,
"score": 0.8578727841377258,
"start": 390,
"tag": "PASSWORD",
"value": "PASSPHRASE"
}
] | src/clojure/caltrack/config.clj | mariogemoll/caltrack | 0 | (ns caltrack.config)
(defn ev [name]
"Returns the environment variable CALTRACK_name or throws an exception."
(or (System/getenv (str "CALTRACK_" name))
(throw (Exception. (str "Environment variable CALTRACK_" name " not set.")))))
(def caldav-url (ev "CALDAV_URL"))
(def caldav-username (ev "CALDAV_USERNAME"))
(def caldav-password (ev "CALDAV_PASSWORD"))
(def passphrase (ev "PASSPHRASE"))
| 106478 | (ns caltrack.config)
(defn ev [name]
"Returns the environment variable CALTRACK_name or throws an exception."
(or (System/getenv (str "CALTRACK_" name))
(throw (Exception. (str "Environment variable CALTRACK_" name " not set.")))))
(def caldav-url (ev "CALDAV_URL"))
(def caldav-username (ev "CALDAV_USERNAME"))
(def caldav-password (ev "<PASSWORD>"))
(def passphrase (ev "<PASSWORD>"))
| true | (ns caltrack.config)
(defn ev [name]
"Returns the environment variable CALTRACK_name or throws an exception."
(or (System/getenv (str "CALTRACK_" name))
(throw (Exception. (str "Environment variable CALTRACK_" name " not set.")))))
(def caldav-url (ev "CALDAV_URL"))
(def caldav-username (ev "CALDAV_USERNAME"))
(def caldav-password (ev "PI:PASSWORD:<PASSWORD>END_PI"))
(def passphrase (ev "PI:PASSWORD:<PASSWORD>END_PI"))
|
[
{
"context": "ter.\n;;;\n;;; Copyright (c) 2015, 2016, 2017, 2020 Pavel Tisnovsky, Red Hat\n;;; All rights reserved.\n;;;\n;;; Redistr",
"end": 133,
"score": 0.9987906813621521,
"start": 118,
"tag": "NAME",
"value": "Pavel Tisnovsky"
},
{
"context": "ULAR PURPOSE ARE\n;;; DISCLAIMED. IN NO EVENT SHALL Pavel Tisnovsky BE LIABLE FOR ANY\n;;; DIRECT, INDIRECT, INCIDENTA",
"end": 1204,
"score": 0.9996294379234314,
"start": 1189,
"tag": "NAME",
"value": "Pavel Tisnovsky"
}
] | test/cloverage_jenkins_reporter/jenkins_api_test.clj | tisnik/cloverage-jenkins-reporter | 0 | ;;;
;;; Statistic about code coverage measured by Cloverage reporter.
;;;
;;; Copyright (c) 2015, 2016, 2017, 2020 Pavel Tisnovsky, Red Hat
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;; * Neither the name of the Red Hat nor the
;;; names of its contributors may be used to endorse or promote products
;;; derived from this software without specific prior written permission.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
;;; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;;; DISCLAIMED. IN NO EVENT SHALL Pavel Tisnovsky BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
;;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
;;; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns cloverage-jenkins-reporter.jenkins-api-test
(:require [clojure.test :refer :all]
[cloverage-jenkins-reporter.jenkins-api :refer :all]))
;
; Common functions used by tests.
;
(defn callable?
"Test if given function-name is bound to the real function."
[function-name]
(clojure.test/function? function-name))
;
; Tests for various defs and functions
;
(deftest test-list-of-all-jobs-url-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/list-of-all-jobs-url definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/list-of-all-jobs-url definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/list-of-all-jobs-url))))
(deftest test-read-list-of-all-jobs-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/read-list-of-all-jobs definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/read-list-of-all-jobs definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/read-list-of-all-jobs))))
(deftest test-read-job-info-as-json-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/read-job-info-as-json definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/read-job-info-as-json definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/read-job-info-as-json))))
(deftest test-read-build-number-for-job-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/read-build-number-for-job definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/read-build-number-for-job definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/read-build-number-for-job))))
(deftest test-encode-spaces-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/encode-spaces definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/encode-spaces definition exists."
(is (callable? 'cloverage-jenkins-reporter.jenkins-api/encode-spaces))))
(deftest test-url-to-file-from-last-build-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/url-to-file-from-last-build definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/url-to-file-from-last-build definition exists."
(is
(callable?
'cloverage-jenkins-reporter.jenkins-api/url-to-file-from-last-build))))
(deftest test-url-to-job-configuration-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/url-to-job-configuration definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/url-to-job-configuration definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/url-to-job-configuration))))
(deftest test-read-file-from-last-build-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/read-file-from-last-build definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/read-file-from-last-build definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/read-file-from-last-build))))
(deftest test-read-job-configuration-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/read-job-configuration definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/read-job-configuration definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/read-job-configuration))))
;
; Actual tests
;
(deftest test-encode-spaces
"Check the jenkins-api/encode-spaces function"
(testing "the jenkins-api/encode-spaces function"
(are [x y] (= x y)
"" (encode-spaces "")
"%20" (encode-spaces " ")
"%20%20" (encode-spaces " ")
"%20%20%20" (encode-spaces " ")
"x%20" (encode-spaces "x ")
"x%20%20" (encode-spaces "x ")
"%20y" (encode-spaces " y")
"%20%20y" (encode-spaces " y")
"x%20y" (encode-spaces "x y")
"x%20y%20z" (encode-spaces "x y z")
"x%20%20%20z" (encode-spaces "x z"))))
(deftest test-encode-spaces-NPE
"Check the function the jenkins-api/encode-spaces"
(testing "the function jenkins-api/encode-spaces"
(is (thrown? NullPointerException (encode-spaces nil)))))
(deftest test-job-name->url-1
"Check the clj-jenkins-api.jenkins-api/job-name->url"
(testing "the clj-jenkins-api.jenkins-api/job-name->url"
(are [x y] (= x y)
"job/" (job-name->url "" "job/" "")
" job/" (job-name->url " " "job/" "")
"jenkins-url/job/" (job-name->url "jenkins-url/" "job/" "")
"jenkins-url:8080/job/" (job-name->url "jenkins-url:8080/" "job/" ""))))
(deftest test-job-name->url-2
"Check the clj-jenkins-api.jenkins-api/job-name->url"
(testing "the clj-jenkins-api.jenkins-api/job-name->url"
(are [x y] (= x y)
"jenkins-url:8080/job/" (job-name->url "jenkins-url:8080/" "job/" "")
"jenkins-url:8080/job/job-name" (job-name->url "jenkins-url:8080/" "job/" "job-name")
"jenkins-url:8080/job/job%20name" (job-name->url "jenkins-url:8080/" "job/" "job name")
"jenkins-url:8080/job/long%20job%20name" (job-name->url "jenkins-url:8080/" "job/" "long job name"))))
(deftest test-job-name->url-not-NPE
"Check the clj-jenkins-api.jenkins-api/job-name->url"
(testing "the clj-jenkins-api.jenkins-api/job-name->url"
(are [x y] (= x y)
"job/" (job-name->url "" "job/" "")
"job/" (job-name->url nil "job/" ""))))
(deftest test-job-name->url-NPE
"Check the clj-jenkins-api.jenkins-api/job-name->url"
(testing "the clj-jenkins-api.jenkins-api/job-name->url"
(is (thrown? NullPointerException (job-name->url "" nil nil)))
(is (thrown? NullPointerException (job-name->url nil nil nil)))))
| 108185 | ;;;
;;; Statistic about code coverage measured by Cloverage reporter.
;;;
;;; Copyright (c) 2015, 2016, 2017, 2020 <NAME>, Red Hat
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;; * Neither the name of the Red Hat nor the
;;; names of its contributors may be used to endorse or promote products
;;; derived from this software without specific prior written permission.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
;;; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;;; DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
;;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
;;; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns cloverage-jenkins-reporter.jenkins-api-test
(:require [clojure.test :refer :all]
[cloverage-jenkins-reporter.jenkins-api :refer :all]))
;
; Common functions used by tests.
;
(defn callable?
"Test if given function-name is bound to the real function."
[function-name]
(clojure.test/function? function-name))
;
; Tests for various defs and functions
;
(deftest test-list-of-all-jobs-url-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/list-of-all-jobs-url definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/list-of-all-jobs-url definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/list-of-all-jobs-url))))
(deftest test-read-list-of-all-jobs-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/read-list-of-all-jobs definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/read-list-of-all-jobs definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/read-list-of-all-jobs))))
(deftest test-read-job-info-as-json-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/read-job-info-as-json definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/read-job-info-as-json definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/read-job-info-as-json))))
(deftest test-read-build-number-for-job-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/read-build-number-for-job definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/read-build-number-for-job definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/read-build-number-for-job))))
(deftest test-encode-spaces-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/encode-spaces definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/encode-spaces definition exists."
(is (callable? 'cloverage-jenkins-reporter.jenkins-api/encode-spaces))))
(deftest test-url-to-file-from-last-build-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/url-to-file-from-last-build definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/url-to-file-from-last-build definition exists."
(is
(callable?
'cloverage-jenkins-reporter.jenkins-api/url-to-file-from-last-build))))
(deftest test-url-to-job-configuration-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/url-to-job-configuration definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/url-to-job-configuration definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/url-to-job-configuration))))
(deftest test-read-file-from-last-build-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/read-file-from-last-build definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/read-file-from-last-build definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/read-file-from-last-build))))
(deftest test-read-job-configuration-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/read-job-configuration definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/read-job-configuration definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/read-job-configuration))))
;
; Actual tests
;
(deftest test-encode-spaces
"Check the jenkins-api/encode-spaces function"
(testing "the jenkins-api/encode-spaces function"
(are [x y] (= x y)
"" (encode-spaces "")
"%20" (encode-spaces " ")
"%20%20" (encode-spaces " ")
"%20%20%20" (encode-spaces " ")
"x%20" (encode-spaces "x ")
"x%20%20" (encode-spaces "x ")
"%20y" (encode-spaces " y")
"%20%20y" (encode-spaces " y")
"x%20y" (encode-spaces "x y")
"x%20y%20z" (encode-spaces "x y z")
"x%20%20%20z" (encode-spaces "x z"))))
(deftest test-encode-spaces-NPE
"Check the function the jenkins-api/encode-spaces"
(testing "the function jenkins-api/encode-spaces"
(is (thrown? NullPointerException (encode-spaces nil)))))
(deftest test-job-name->url-1
"Check the clj-jenkins-api.jenkins-api/job-name->url"
(testing "the clj-jenkins-api.jenkins-api/job-name->url"
(are [x y] (= x y)
"job/" (job-name->url "" "job/" "")
" job/" (job-name->url " " "job/" "")
"jenkins-url/job/" (job-name->url "jenkins-url/" "job/" "")
"jenkins-url:8080/job/" (job-name->url "jenkins-url:8080/" "job/" ""))))
(deftest test-job-name->url-2
"Check the clj-jenkins-api.jenkins-api/job-name->url"
(testing "the clj-jenkins-api.jenkins-api/job-name->url"
(are [x y] (= x y)
"jenkins-url:8080/job/" (job-name->url "jenkins-url:8080/" "job/" "")
"jenkins-url:8080/job/job-name" (job-name->url "jenkins-url:8080/" "job/" "job-name")
"jenkins-url:8080/job/job%20name" (job-name->url "jenkins-url:8080/" "job/" "job name")
"jenkins-url:8080/job/long%20job%20name" (job-name->url "jenkins-url:8080/" "job/" "long job name"))))
(deftest test-job-name->url-not-NPE
"Check the clj-jenkins-api.jenkins-api/job-name->url"
(testing "the clj-jenkins-api.jenkins-api/job-name->url"
(are [x y] (= x y)
"job/" (job-name->url "" "job/" "")
"job/" (job-name->url nil "job/" ""))))
(deftest test-job-name->url-NPE
"Check the clj-jenkins-api.jenkins-api/job-name->url"
(testing "the clj-jenkins-api.jenkins-api/job-name->url"
(is (thrown? NullPointerException (job-name->url "" nil nil)))
(is (thrown? NullPointerException (job-name->url nil nil nil)))))
| true | ;;;
;;; Statistic about code coverage measured by Cloverage reporter.
;;;
;;; Copyright (c) 2015, 2016, 2017, 2020 PI:NAME:<NAME>END_PI, Red Hat
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;; * Neither the name of the Red Hat nor the
;;; names of its contributors may be used to endorse or promote products
;;; derived from this software without specific prior written permission.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
;;; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;;; DISCLAIMED. IN NO EVENT SHALL PI:NAME:<NAME>END_PI BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
;;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
;;; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns cloverage-jenkins-reporter.jenkins-api-test
(:require [clojure.test :refer :all]
[cloverage-jenkins-reporter.jenkins-api :refer :all]))
;
; Common functions used by tests.
;
(defn callable?
"Test if given function-name is bound to the real function."
[function-name]
(clojure.test/function? function-name))
;
; Tests for various defs and functions
;
(deftest test-list-of-all-jobs-url-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/list-of-all-jobs-url definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/list-of-all-jobs-url definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/list-of-all-jobs-url))))
(deftest test-read-list-of-all-jobs-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/read-list-of-all-jobs definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/read-list-of-all-jobs definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/read-list-of-all-jobs))))
(deftest test-read-job-info-as-json-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/read-job-info-as-json definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/read-job-info-as-json definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/read-job-info-as-json))))
(deftest test-read-build-number-for-job-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/read-build-number-for-job definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/read-build-number-for-job definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/read-build-number-for-job))))
(deftest test-encode-spaces-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/encode-spaces definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/encode-spaces definition exists."
(is (callable? 'cloverage-jenkins-reporter.jenkins-api/encode-spaces))))
(deftest test-url-to-file-from-last-build-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/url-to-file-from-last-build definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/url-to-file-from-last-build definition exists."
(is
(callable?
'cloverage-jenkins-reporter.jenkins-api/url-to-file-from-last-build))))
(deftest test-url-to-job-configuration-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/url-to-job-configuration definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/url-to-job-configuration definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/url-to-job-configuration))))
(deftest test-read-file-from-last-build-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/read-file-from-last-build definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/read-file-from-last-build definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/read-file-from-last-build))))
(deftest test-read-job-configuration-existence
"Check that the cloverage-jenkins-reporter.jenkins-api/read-job-configuration definition exists."
(testing
"if the cloverage-jenkins-reporter.jenkins-api/read-job-configuration definition exists."
(is (callable?
'cloverage-jenkins-reporter.jenkins-api/read-job-configuration))))
;
; Actual tests
;
(deftest test-encode-spaces
"Check the jenkins-api/encode-spaces function"
(testing "the jenkins-api/encode-spaces function"
(are [x y] (= x y)
"" (encode-spaces "")
"%20" (encode-spaces " ")
"%20%20" (encode-spaces " ")
"%20%20%20" (encode-spaces " ")
"x%20" (encode-spaces "x ")
"x%20%20" (encode-spaces "x ")
"%20y" (encode-spaces " y")
"%20%20y" (encode-spaces " y")
"x%20y" (encode-spaces "x y")
"x%20y%20z" (encode-spaces "x y z")
"x%20%20%20z" (encode-spaces "x z"))))
(deftest test-encode-spaces-NPE
"Check the function the jenkins-api/encode-spaces"
(testing "the function jenkins-api/encode-spaces"
(is (thrown? NullPointerException (encode-spaces nil)))))
(deftest test-job-name->url-1
"Check the clj-jenkins-api.jenkins-api/job-name->url"
(testing "the clj-jenkins-api.jenkins-api/job-name->url"
(are [x y] (= x y)
"job/" (job-name->url "" "job/" "")
" job/" (job-name->url " " "job/" "")
"jenkins-url/job/" (job-name->url "jenkins-url/" "job/" "")
"jenkins-url:8080/job/" (job-name->url "jenkins-url:8080/" "job/" ""))))
(deftest test-job-name->url-2
"Check the clj-jenkins-api.jenkins-api/job-name->url"
(testing "the clj-jenkins-api.jenkins-api/job-name->url"
(are [x y] (= x y)
"jenkins-url:8080/job/" (job-name->url "jenkins-url:8080/" "job/" "")
"jenkins-url:8080/job/job-name" (job-name->url "jenkins-url:8080/" "job/" "job-name")
"jenkins-url:8080/job/job%20name" (job-name->url "jenkins-url:8080/" "job/" "job name")
"jenkins-url:8080/job/long%20job%20name" (job-name->url "jenkins-url:8080/" "job/" "long job name"))))
(deftest test-job-name->url-not-NPE
"Check the clj-jenkins-api.jenkins-api/job-name->url"
(testing "the clj-jenkins-api.jenkins-api/job-name->url"
(are [x y] (= x y)
"job/" (job-name->url "" "job/" "")
"job/" (job-name->url nil "job/" ""))))
(deftest test-job-name->url-NPE
"Check the clj-jenkins-api.jenkins-api/job-name->url"
(testing "the clj-jenkins-api.jenkins-api/job-name->url"
(is (thrown? NullPointerException (job-name->url "" nil nil)))
(is (thrown? NullPointerException (job-name->url nil nil nil)))))
|
[
{
"context": "re.tools.logging :as log]))\n\n(def bot-name \"Planet Express\")\n(def bot-color \"blue\")\n(def players [{:number 1",
"end": 240,
"score": 0.835563600063324,
"start": 233,
"tag": "USERNAME",
"value": "Express"
},
{
"context": "bot-color \"blue\")\n(def players [{:number 1 :name \"Fry\"}\n {:number 2 :name \"Leela\"}])\n\n(def",
"end": 301,
"score": 0.9994438290596008,
"start": 298,
"tag": "NAME",
"value": "Fry"
},
{
"context": "er 1 :name \"Fry\"}\n {:number 2 :name \"Leela\"}])\n\n(defn server-address [host port]\n (if (= \"0",
"end": 341,
"score": 0.9996145367622375,
"start": 336,
"tag": "NAME",
"value": "Leela"
},
{
"context": "a\"}])\n\n(defn server-address [host port]\n (if (= \"0.0.0.0\" host)\n {:host \"127.0.0.1\" :port port}\n {:h",
"end": 397,
"score": 0.9995894432067871,
"start": 390,
"tag": "IP_ADDRESS",
"value": "0.0.0.0"
},
{
"context": " [host port]\n (if (= \"0.0.0.0\" host)\n {:host \"127.0.0.1\" :port port}\n {:host host :port port}))\n\n(defn",
"end": 426,
"score": 0.9869087934494019,
"start": 417,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " :name bot-name\n :g",
"end": 2003,
"score": 0.9993441104888916,
"start": 1995,
"tag": "USERNAME",
"value": "bot-name"
}
] | src/codecamp2015/bot.clj | jkytomak/clojure-bot | 0 | (ns codecamp2015.bot
(:require [aleph.udp :as udp]
[cheshire.core :as json]
[manifold.stream :as s]
[manifold.deferred :as d]
[clojure.tools.logging :as log]))
(def bot-name "Planet Express")
(def bot-color "blue")
(def players [{:number 1 :name "Fry"}
{:number 2 :name "Leela"}])
(defn server-address [host port]
(if (= "0.0.0.0" host)
{:host "127.0.0.1" :port port}
{:host host :port port}))
(defn parse-udp-msg [msg]
(assoc msg :message (json/parse-string (new String (:message msg) "UTF-8") true)))
(defn send-message [udp-stream server-address connection-id message]
(let [udp-message (->> (assoc message :connection-id connection-id)
(json/generate-string)
(assoc server-address :message))]
(log/debug "Sending message" udp-message)
(s/put! udp-stream udp-message)))
(defn start-game [udp-stream connection-id game-at]
(let [server-address (server-address (:address game-at) (:port game-at))]
(log/info "Connecting to game:" server-address)
(send-message
udp-stream
server-address
connection-id
{:type "join"
:name bot-name
:color bot-color
:game-id (:game-id game-at)
:players players})))
(defn handle-message [udp-stream connection-id udp-msg]
(let [parsed-udp-msg (parse-udp-msg udp-msg)
msg (:message parsed-udp-msg)]
(case (:type msg)
"ping" (send-message udp-stream parsed-udp-msg connection-id {:type "pong"})
"game-at" (start-game udp-stream connection-id msg)
(log/warn "Unhandled msg type" (:type msg) "in message" parsed-udp-msg))))
(defn server-msg-loop [udp-stream connection-id]
(s/consume (partial handle-message udp-stream connection-id) udp-stream))
(defn connect-to-lobby-server [udp-stream game-id server-address]
(send-message udp-stream server-address nil {:type "connect"
:name bot-name
:game-id game-id})
(d/chain
(s/take! udp-stream)
parse-udp-msg
(fn [parsed-udp-msg]
(log/info "Connected to lobby server:" parsed-udp-msg)
(server-msg-loop udp-stream (:connection-id (:message parsed-udp-msg))))))
(defn start-bot [game-id server-host server-port client-port]
(-> (d/chain
(udp/socket {:port client-port :broadcast? false})
(fn [udp-stream]
(log/info "UDP socket opened in port" client-port)
(connect-to-lobby-server udp-stream game-id (server-address server-host server-port))))
(d/catch #(log/error "Unexpected error:" %))))
| 16064 | (ns codecamp2015.bot
(:require [aleph.udp :as udp]
[cheshire.core :as json]
[manifold.stream :as s]
[manifold.deferred :as d]
[clojure.tools.logging :as log]))
(def bot-name "Planet Express")
(def bot-color "blue")
(def players [{:number 1 :name "<NAME>"}
{:number 2 :name "<NAME>"}])
(defn server-address [host port]
(if (= "0.0.0.0" host)
{:host "127.0.0.1" :port port}
{:host host :port port}))
(defn parse-udp-msg [msg]
(assoc msg :message (json/parse-string (new String (:message msg) "UTF-8") true)))
(defn send-message [udp-stream server-address connection-id message]
(let [udp-message (->> (assoc message :connection-id connection-id)
(json/generate-string)
(assoc server-address :message))]
(log/debug "Sending message" udp-message)
(s/put! udp-stream udp-message)))
(defn start-game [udp-stream connection-id game-at]
(let [server-address (server-address (:address game-at) (:port game-at))]
(log/info "Connecting to game:" server-address)
(send-message
udp-stream
server-address
connection-id
{:type "join"
:name bot-name
:color bot-color
:game-id (:game-id game-at)
:players players})))
(defn handle-message [udp-stream connection-id udp-msg]
(let [parsed-udp-msg (parse-udp-msg udp-msg)
msg (:message parsed-udp-msg)]
(case (:type msg)
"ping" (send-message udp-stream parsed-udp-msg connection-id {:type "pong"})
"game-at" (start-game udp-stream connection-id msg)
(log/warn "Unhandled msg type" (:type msg) "in message" parsed-udp-msg))))
(defn server-msg-loop [udp-stream connection-id]
(s/consume (partial handle-message udp-stream connection-id) udp-stream))
(defn connect-to-lobby-server [udp-stream game-id server-address]
(send-message udp-stream server-address nil {:type "connect"
:name bot-name
:game-id game-id})
(d/chain
(s/take! udp-stream)
parse-udp-msg
(fn [parsed-udp-msg]
(log/info "Connected to lobby server:" parsed-udp-msg)
(server-msg-loop udp-stream (:connection-id (:message parsed-udp-msg))))))
(defn start-bot [game-id server-host server-port client-port]
(-> (d/chain
(udp/socket {:port client-port :broadcast? false})
(fn [udp-stream]
(log/info "UDP socket opened in port" client-port)
(connect-to-lobby-server udp-stream game-id (server-address server-host server-port))))
(d/catch #(log/error "Unexpected error:" %))))
| true | (ns codecamp2015.bot
(:require [aleph.udp :as udp]
[cheshire.core :as json]
[manifold.stream :as s]
[manifold.deferred :as d]
[clojure.tools.logging :as log]))
(def bot-name "Planet Express")
(def bot-color "blue")
(def players [{:number 1 :name "PI:NAME:<NAME>END_PI"}
{:number 2 :name "PI:NAME:<NAME>END_PI"}])
(defn server-address [host port]
(if (= "0.0.0.0" host)
{:host "127.0.0.1" :port port}
{:host host :port port}))
(defn parse-udp-msg [msg]
(assoc msg :message (json/parse-string (new String (:message msg) "UTF-8") true)))
(defn send-message [udp-stream server-address connection-id message]
(let [udp-message (->> (assoc message :connection-id connection-id)
(json/generate-string)
(assoc server-address :message))]
(log/debug "Sending message" udp-message)
(s/put! udp-stream udp-message)))
(defn start-game [udp-stream connection-id game-at]
(let [server-address (server-address (:address game-at) (:port game-at))]
(log/info "Connecting to game:" server-address)
(send-message
udp-stream
server-address
connection-id
{:type "join"
:name bot-name
:color bot-color
:game-id (:game-id game-at)
:players players})))
(defn handle-message [udp-stream connection-id udp-msg]
(let [parsed-udp-msg (parse-udp-msg udp-msg)
msg (:message parsed-udp-msg)]
(case (:type msg)
"ping" (send-message udp-stream parsed-udp-msg connection-id {:type "pong"})
"game-at" (start-game udp-stream connection-id msg)
(log/warn "Unhandled msg type" (:type msg) "in message" parsed-udp-msg))))
(defn server-msg-loop [udp-stream connection-id]
(s/consume (partial handle-message udp-stream connection-id) udp-stream))
(defn connect-to-lobby-server [udp-stream game-id server-address]
(send-message udp-stream server-address nil {:type "connect"
:name bot-name
:game-id game-id})
(d/chain
(s/take! udp-stream)
parse-udp-msg
(fn [parsed-udp-msg]
(log/info "Connected to lobby server:" parsed-udp-msg)
(server-msg-loop udp-stream (:connection-id (:message parsed-udp-msg))))))
(defn start-bot [game-id server-host server-port client-port]
(-> (d/chain
(udp/socket {:port client-port :broadcast? false})
(fn [udp-stream]
(log/info "UDP socket opened in port" client-port)
(connect-to-lobby-server udp-stream game-id (server-address server-host server-port))))
(d/catch #(log/error "Unexpected error:" %))))
|
[
{
"context": "user-id\n :name \"user\"\n :email \"user@",
"end": 2360,
"score": 0.9989675879478455,
"start": 2356,
"tag": "USERNAME",
"value": "user"
},
{
"context": "\"user\"\n :email \"user@example.com\"}]}}\n 2 {:workflow {:type :workflow/defau",
"end": 2421,
"score": 0.9999101758003235,
"start": 2405,
"tag": "EMAIL",
"value": "user@example.com"
},
{
"context": "user-id\n :name \"user\"\n :email \"user@",
"end": 2579,
"score": 0.9989908933639526,
"start": 2575,
"tag": "USERNAME",
"value": "user"
},
{
"context": "\"user\"\n :email \"user@example.com\"}]\n :forms [{:form/id 3} {:",
"end": 2640,
"score": 0.9999105334281921,
"start": 2624,
"tag": "EMAIL",
"value": "user@example.com"
},
{
"context": " [{:type :t.form.validation/invalid-user :userid \"deity2\"}]}\n (fail-command application\n ",
"end": 46528,
"score": 0.9716776013374329,
"start": 46522,
"tag": "USERNAME",
"value": "deity2"
},
{
"context": " :application/member {:userid \"somebody\"}}])\n injections {:valid-user? #{\"memb",
"end": 51925,
"score": 0.5570755004882812,
"start": 51921,
"tag": "USERNAME",
"value": "some"
},
{
"context": " injections {:valid-user? #{\"member1\" \"member2\" \"somebody\" applicant-user-id}}]\n (testing \"handler c",
"end": 51995,
"score": 0.5295734405517578,
"start": 51991,
"tag": "USERNAME",
"value": "some"
},
{
"context": "d}\n :secure-token (constantly \"very-secure\")}]\n (testing \"applicant can invite members\"\n ",
"end": 54100,
"score": 0.8072864413261414,
"start": 54089,
"tag": "PASSWORD",
"value": "very-secure"
},
{
"context": " app-id\n :application/member {:name \"Member Applicant 1\"\n :email \"membe",
"end": 54387,
"score": 0.9099285006523132,
"start": 54369,
"tag": "NAME",
"value": "Member Applicant 1"
},
{
"context": "ant 1\"\n :email \"member1@applicants.com\"}\n :invitation/token \"very-secure\"}\n",
"end": 54454,
"score": 0.9999224543571472,
"start": 54432,
"tag": "EMAIL",
"value": "member1@applicants.com"
},
{
"context": "applicants.com\"}\n :invitation/token \"very-secure\"}\n (ok-command application\n ",
"end": 54501,
"score": 0.9779959321022034,
"start": 54490,
"tag": "PASSWORD",
"value": "very-secure"
},
{
"context": "user-id\n :member {:name \"Member Applicant 1\"\n :email \"membe",
"end": 54719,
"score": 0.9254654049873352,
"start": 54701,
"tag": "NAME",
"value": "Member Applicant 1"
},
{
"context": "ant 1\"\n :email \"member1@applicants.com\"}}\n injections))))\n (t",
"end": 54786,
"score": 0.9999232888221741,
"start": 54764,
"tag": "EMAIL",
"value": "member1@applicants.com"
},
{
"context": "pp-id\n :application/member {:name \"Member Applicant 1\"\n :email \"mem",
"end": 55447,
"score": 0.931934654712677,
"start": 55429,
"tag": "NAME",
"value": "Member Applicant 1"
},
{
"context": "t 1\"\n :email \"member1@applicants.com\"}\n :invitation/token \"very-secure\"",
"end": 55516,
"score": 0.9999200701713562,
"start": 55494,
"tag": "EMAIL",
"value": "member1@applicants.com"
},
{
"context": "plicants.com\"}\n :invitation/token \"very-secure\"}\n (ok-command application\n ",
"end": 55565,
"score": 0.9574900269508362,
"start": 55554,
"tag": "PASSWORD",
"value": "very-secure"
},
{
"context": "er-id\n :member {:name \"Member Applicant 1\"\n :email \"mem",
"end": 55789,
"score": 0.9328117370605469,
"start": 55771,
"tag": "NAME",
"value": "Member Applicant 1"
},
{
"context": "t 1\"\n :email \"member1@applicants.com\"}}\n injections)))))\n ",
"end": 55858,
"score": 0.9999212622642517,
"start": 55836,
"tag": "EMAIL",
"value": "member1@applicants.com"
},
{
"context": "ber1\"\n :member {:name \"Member Applicant 1\"\n :email \"mem",
"end": 56213,
"score": 0.9437130093574524,
"start": 56195,
"tag": "NAME",
"value": "Member Applicant 1"
},
{
"context": "t 1\"\n :email \"member1@applicants.com\"}}\n injections))))\n ",
"end": 56282,
"score": 0.9999237656593323,
"start": 56260,
"tag": "EMAIL",
"value": "member1@applicants.com"
},
{
"context": "-id\n :member {:name \"Member Applicant 1\"\n :email \"m",
"end": 56987,
"score": 0.8122426271438599,
"start": 56969,
"tag": "NAME",
"value": "Member Applicant 1"
},
{
"context": "1\"\n :email \"member1@applicants.com\"}}\n injections))))\n ",
"end": 57058,
"score": 0.9999246597290039,
"start": 57036,
"tag": "EMAIL",
"value": "member1@applicants.com"
},
{
"context": "-user-id\n :member {:name \"Member Applicant 1\"\n :email \"member",
"end": 57382,
"score": 0.8361160159111023,
"start": 57364,
"tag": "NAME",
"value": "Member Applicant 1"
},
{
"context": "cant 1\"\n :email \"member1@applicants.com\"}}\n injections))))))\n\n(def",
"end": 57448,
"score": 0.9999231696128845,
"start": 57426,
"tag": "EMAIL",
"value": "member1@applicants.com"
},
{
"context": " :application/member {:name \"Some Body\" :email \"somebody@applicants.com\"}\n ",
"end": 57958,
"score": 0.9647386074066162,
"start": 57949,
"tag": "NAME",
"value": "Some Body"
},
{
"context": " :application/member {:name \"Some Body\" :email \"somebody@applicants.com\"}\n :invitation",
"end": 57991,
"score": 0.9999228119850159,
"start": 57968,
"tag": "EMAIL",
"value": "somebody@applicants.com"
},
{
"context": " \"somebody\"\n :token \"very-secure\"}\n injections))))\n\n (t",
"end": 58604,
"score": 0.590194582939148,
"start": 58598,
"tag": "PASSWORD",
"value": "secure"
},
{
"context": " :application/member {:userid \"somebody\"}}])]\n (is (= {:errors [{:type :t.actions.",
"end": 59126,
"score": 0.99286949634552,
"start": 59118,
"tag": "USERNAME",
"value": "somebody"
},
{
"context": "[{:type :t.actions.errors/already-member :userid \"somebody\" :application-id app-id}]}\n (fail-c",
"end": 59215,
"score": 0.9537234306335449,
"start": 59207,
"tag": "USERNAME",
"value": "somebody"
},
{
"context": "type :t.actions.errors/invalid-token :token \"wrong-token\"}]}\n (fail-command application\n ",
"end": 59631,
"score": 0.616316556930542,
"start": 59631,
"tag": "PASSWORD",
"value": ""
},
{
"context": "omebody\"\n :token \"wrong-token\"}\n injections))))\n\n ",
"end": 59847,
"score": 0.6823017597198486,
"start": 59842,
"tag": "PASSWORD",
"value": "token"
},
{
"context": " :invitation/token \"very-secure\"}])]\n (is (= {:errors [{:type :t.actions.e",
"end": 60328,
"score": 0.7709295153617859,
"start": 60317,
"tag": "PASSWORD",
"value": "very-secure"
},
{
"context": "s [{:type :t.actions.errors/invalid-token :token \"very-secure\"}]}\n (fail-command application\n ",
"end": 60417,
"score": 0.7115028500556946,
"start": 60406,
"tag": "PASSWORD",
"value": "very-secure"
},
{
"context": "\"somebody2\"\n :token \"very-secure\"}\n injections)))))\n\n ",
"end": 60636,
"score": 0.89787358045578,
"start": 60625,
"tag": "PASSWORD",
"value": "very-secure"
},
{
"context": "id app-id\n :invitation/token \"very-secure\"}\n (ok-command application\n ",
"end": 61283,
"score": 0.6841922998428345,
"start": 61277,
"tag": "PASSWORD",
"value": "secure"
},
{
"context": "or \"somebody\"\n :token \"very-secure\"}\n injections))))\n\n ",
"end": 61491,
"score": 0.7479245662689209,
"start": 61480,
"tag": "PASSWORD",
"value": "very-secure"
},
{
"context": "somebody\"\n :token \"very-secure\"}\n injections))))))",
"end": 62227,
"score": 0.8103538155555725,
"start": 62216,
"tag": "PASSWORD",
"value": "very-secure"
},
{
"context": " :application/member {:userid \"somebody\"}}])\n injections {:valid-user? #{\"somebody",
"end": 63000,
"score": 0.9373286366462708,
"start": 62992,
"tag": "USERNAME",
"value": "somebody"
},
{
"context": "pp-id\n :application/member {:userid \"somebody\"}\n :application/comment \"some commen",
"end": 63363,
"score": 0.884246826171875,
"start": 63355,
"tag": "USERNAME",
"value": "somebody"
},
{
"context": "er-id\n :member {:userid \"somebody\"}\n :comment \"some commen",
"end": 63624,
"score": 0.924961268901825,
"start": 63616,
"tag": "USERNAME",
"value": "somebody"
},
{
"context": "mment\n :application/member {:userid \"somebody\"}}\n (ok-command application\n ",
"end": 64019,
"score": 0.8543371558189392,
"start": 64011,
"tag": "USERNAME",
"value": "somebody"
},
{
"context": "er-id\n :member {:userid \"somebody\"}}\n injections))))\n (t",
"end": 64228,
"score": 0.9409011006355286,
"start": 64220,
"tag": "USERNAME",
"value": "somebody"
},
{
"context": "{:errors [{:type :user-not-member :user {:userid \"notamember\"}}]}\n (fail-command application\n ",
"end": 65022,
"score": 0.9879933595657349,
"start": 65012,
"tag": "USERNAME",
"value": "notamember"
},
{
"context": "-id\n :member {:userid \"notamember\"}}\n injections))))\n ",
"end": 65243,
"score": 0.9991719722747803,
"start": 65233,
"tag": "USERNAME",
"value": "notamember"
},
{
"context": " :member {:userid \"somebody\"}}]\n injections",
"end": 65659,
"score": 0.999115526676178,
"start": 65651,
"tag": "USERNAME",
"value": "somebody"
},
{
"context": " :application/member {:name \"Some Body\" :email \"some@body.com\"}\n ",
"end": 66236,
"score": 0.9955390691757202,
"start": 66227,
"tag": "NAME",
"value": "Some Body"
},
{
"context": " :application/member {:name \"Some Body\" :email \"some@body.com\"}\n :invitation",
"end": 66259,
"score": 0.9999120831489563,
"start": 66246,
"tag": "EMAIL",
"value": "some@body.com"
},
{
"context": " :invitation/token \"123456\"}\n {:event/type",
"end": 66323,
"score": 0.9760439991950989,
"start": 66317,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": " app-id\n :application/member {:name \"Some Body\" :email \"some@body.com\"}}\n (ok-comman",
"end": 66888,
"score": 0.9931326508522034,
"start": 66879,
"tag": "NAME",
"value": "Some Body"
},
{
"context": " :application/member {:name \"Some Body\" :email \"some@body.com\"}}\n (ok-command application\n ",
"end": 66911,
"score": 0.9999094009399414,
"start": 66898,
"tag": "EMAIL",
"value": "some@body.com"
},
{
"context": "user-id\n :member {:name \"Some Body\" :email \"some@body.com\"}}\n ",
"end": 67123,
"score": 0.9942319393157959,
"start": 67114,
"tag": "NAME",
"value": "Some Body"
},
{
"context": " :member {:name \"Some Body\" :email \"some@body.com\"}}\n injections))))\n (t",
"end": 67146,
"score": 0.9999102354049683,
"start": 67133,
"tag": "EMAIL",
"value": "some@body.com"
},
{
"context": " app-id\n :application/member {:name \"Some Body\" :email \"some@body.com\"}\n :applicati",
"end": 67461,
"score": 0.9939291477203369,
"start": 67452,
"tag": "NAME",
"value": "Some Body"
},
{
"context": " :application/member {:name \"Some Body\" :email \"some@body.com\"}\n :application/comment \"\"}\n ",
"end": 67484,
"score": 0.9999135136604309,
"start": 67471,
"tag": "EMAIL",
"value": "some@body.com"
},
{
"context": "user-id\n :member {:name \"Some Body\" :email \"some@body.com\"}\n ",
"end": 67732,
"score": 0.9954130053520203,
"start": 67723,
"tag": "NAME",
"value": "Some Body"
},
{
"context": " :member {:name \"Some Body\" :email \"some@body.com\"}\n :comment \"\"}\n ",
"end": 67755,
"score": 0.9999152421951294,
"start": 67742,
"tag": "EMAIL",
"value": "some@body.com"
},
{
"context": "= {:errors [{:type :user-not-member :user {:name \"Not Member\" :email \"not@member.com\"}}]}\n ",
"end": 67954,
"score": 0.8994737267494202,
"start": 67951,
"tag": "NAME",
"value": "Not"
},
{
"context": ":errors [{:type :user-not-member :user {:name \"Not Member\" :email \"not@member.com\"}}]}\n (fail-c",
"end": 67961,
"score": 0.7046138048171997,
"start": 67955,
"tag": "USERNAME",
"value": "Member"
},
{
"context": "user-not-member :user {:name \"Not Member\" :email \"not@member.com\"}}]}\n (fail-command application\n ",
"end": 67985,
"score": 0.9999116063117981,
"start": 67971,
"tag": "EMAIL",
"value": "not@member.com"
},
{
"context": "er-id\n :member {:name \"Not Member\" :email \"not@member.com\"}\n ",
"end": 68199,
"score": 0.7743791937828064,
"start": 68196,
"tag": "NAME",
"value": "Not"
},
{
"context": "id\n :member {:name \"Not Member\" :email \"not@member.com\"}\n ",
"end": 68206,
"score": 0.8455559611320496,
"start": 68200,
"tag": "USERNAME",
"value": "Member"
},
{
"context": " :member {:name \"Not Member\" :email \"not@member.com\"}\n :comment \"\"}\n ",
"end": 68230,
"score": 0.9999090433120728,
"start": 68216,
"tag": "EMAIL",
"value": "not@member.com"
},
{
"context": "ons))))))\n\n(deftest test-review\n (let [reviewer \"reviewer\"\n reviewer2 \"reviewer2\"\n reviewer3 ",
"end": 68366,
"score": 0.9789152145385742,
"start": 68358,
"tag": "USERNAME",
"value": "reviewer"
},
{
"context": "ew\n (let [reviewer \"reviewer\"\n reviewer2 \"reviewer2\"\n reviewer3 \"reviewer3\"\n applicatio",
"end": 68396,
"score": 0.7064406871795654,
"start": 68387,
"tag": "USERNAME",
"value": "reviewer2"
},
{
"context": "\n reviewer2 \"reviewer2\"\n reviewer3 \"reviewer3\"\n application (apply-events nil\n ",
"end": 68426,
"score": 0.5223532319068909,
"start": 68417,
"tag": "USERNAME",
"value": "reviewer3"
},
{
"context": " [{:type :t.form.validation/invalid-user :userid \"invaliduser\"}\n {:type :t.form.validatio",
"end": 69777,
"score": 0.9719278812408447,
"start": 69766,
"tag": "USERNAME",
"value": "invaliduser"
},
{
"context": " {:type :t.form.validation/invalid-user :userid \"invaliduser2\"}]}\n (fail-command application\n ",
"end": 69863,
"score": 0.9368500709533691,
"start": 69851,
"tag": "USERNAME",
"value": "invaliduser2"
},
{
"context": "-user-id\n :reviewers [\"invaliduser\" reviewer \"invaliduser2\"]\n ",
"end": 70080,
"score": 0.9921490550041199,
"start": 70069,
"tag": "USERNAME",
"value": "invaliduser"
},
{
"context": " :reviewers [\"invaliduser\" reviewer \"invaliduser2\"]\n :comment \"\"}\n ",
"end": 70104,
"score": 0.9897996783256531,
"start": 70092,
"tag": "USERNAME",
"value": "invaliduser2"
},
{
"context": "s))))))))\n\n(deftest test-remark\n (let [reviewer \"reviewer\"\n application (apply-events nil\n ",
"end": 74930,
"score": 0.9967849254608154,
"start": 74922,
"tag": "USERNAME",
"value": "reviewer"
},
{
"context": " :attachment/user \"carl\"}}}]\n (testing \"handler can remark\"\n (let",
"end": 76315,
"score": 0.7732852697372437,
"start": 76311,
"tag": "USERNAME",
"value": "carl"
}
] | test/clj/rems/application/test_commands.clj | MalinAhlberg/rems | 0 | (ns rems.application.test-commands
(:require [clojure.test :refer :all]
[rems.application.commands :as commands]
[rems.application.events :as events]
[rems.application.model :as model]
[rems.form-validation :as form-validation]
[rems.permissions :as permissions]
[rems.util :refer [assert-ex getx]])
(:import [clojure.lang ExceptionInfo]
[java.util UUID]
[org.joda.time DateTime]))
(def ^:private test-time (DateTime. 1000))
(def ^:private app-id 123)
(def ^:private new-app-id 456)
(def ^:private new-external-id "2019/66")
(def ^:private applicant-user-id "applicant")
(def ^:private handler-user-id "assistant")
(def ^:private dummy-created-event {:event/type :application.event/created
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/external-id "2000/123"
:application/resources []
:application/licenses []
:application/forms [{:form/id 1}]
:workflow/id 1
:workflow/type :workflow/default})
(def ^:private dummy-licenses
{1 {:id 1
:licensetype "link"
:localizations {:en {:title "en title"
:textcontent "en link"
:attachment-id 1}
:fi {:title "fi title"
:textcontent "fi link"
:attachment-id 2}}}
2 {:id 2
:licensetype "link"
:localizations {:en {:title "en title"
:textcontent "en link"}
:fi {:title "fi title"
:textcontent "fi link"}}}
3 {:id 3
:licensetype "link"
:localizations {:en {:title "en title"
:textcontent "en link"}
:fi {:title "fi title"
:textcontent "fi link"}}}})
(defn- dummy-get-workflow [id]
(getx {1 {:workflow {:type :workflow/default
:handlers [{:userid handler-user-id
:name "user"
:email "user@example.com"}]}}
2 {:workflow {:type :workflow/default
:handlers [{:userid handler-user-id
:name "user"
:email "user@example.com"}]
:forms [{:form/id 3} {:form/id 4}]}}}
id))
(defn- dummy-get-form-template [id]
(getx {1 {:form/id 1
:form/fields [{:field/id "1"
:field/optional true
:field/visible true
:field/type :option
:field/options [{:key "foo" :label "Foo"}
{:key "bar" :label "Bar"}]}
{:field/id "2"
:field/optional false
:field/visibility {:visibility/type :only-if
:visibility/field {:field/id "1"}
:visibility/values ["foo"]}}]}
2 {:form/id 2
:form/fields [{:field/id "1"
:field/optional false}]}
3 {:form/id 3
:form/fields [{:field/id "text"
:field/type :text}
{:field/id "attachment"
:field/type :attachment}]}
4 {:form/id 4
:form/fields [{:field/id "text"
:field/type :text}]}}
id))
(defn- dummy-get-catalogue-item [id]
(when (< id 10000)
(merge {:enabled true :archived false :expired false
:id id :wfid 1 :formid 1}
(getx {1 {:resid "res1"}
2 {:resid "res2"}
3 {:resid "res3"
:formid 2}
4 {:resid "res4"
:wfid 2}
5 {:resid "res5"
:formid 2
:wfid 2}}
id))))
(defn- dummy-get-catalogue-item-licenses [id]
(getx {1 [{:id 1}]
2 [{:id 2}]
3 [{:id 1}
{:id 2}
{:id 3}]
4 []
5 []} id))
(defn- dummy-get-config []
{})
(def allocated-new-ids? (atom false))
(def ^:private injections
{:blacklisted? (constantly false)
:get-workflow dummy-get-workflow
:get-form-template dummy-get-form-template
:get-catalogue-item dummy-get-catalogue-item
:get-catalogue-item-licenses dummy-get-catalogue-item-licenses
:get-config dummy-get-config
:get-license dummy-licenses
:get-user (fn [userid] {:userid userid})
:get-users-with-role (constantly nil)
:get-attachments-for-application (constantly nil)
:allocate-application-ids! (fn [_time]
(reset! allocated-new-ids? true)
{:application/id new-app-id
:application/external-id new-external-id})
:copy-attachment! (fn [_new-app-id attachment-id]
(+ attachment-id 100))})
;; could rework tests to use model/build-application-view instead of this
(defn apply-events [application events]
(events/validate-events events)
(-> (reduce model/application-view application events)
(model/enrich-with-injections injections)))
(defn- set-command-defaults [cmd]
(cond-> cmd
true
(assoc :time test-time)
(not= :application.command/create (:type cmd))
(assoc :application-id app-id)))
(defn- fail-command
([application cmd]
(fail-command application cmd nil))
([application cmd injections]
(let [cmd (set-command-defaults cmd)
result (commands/handle-command cmd application injections)]
(assert-ex (:errors result) {:cmd cmd :result result})
result)))
(defn- ok-command
([application cmd]
(ok-command application cmd nil))
([application cmd injections]
(let [cmd (set-command-defaults cmd)
result (commands/handle-command cmd application injections)]
(assert-ex (not (:errors result)) {:cmd cmd :result result})
(let [events (:events result)]
(events/validate-events events)
;; most tests expect only one event, so this avoids having to wrap the expectation to a list
(if (= 1 (count events))
(first events)
events)))))
(defn- apply-command
([application cmd]
(apply-command application cmd nil))
([application cmd injections]
(apply-events application [(ok-command application cmd injections)])))
(defn- apply-commands
([application commands]
(apply-commands application commands nil))
([application commands injections]
(reduce (fn [app cmd] (apply-command app cmd injections))
application commands)))
;;; Tests
(deftest test-create
(testing "one resource"
(is (= {:event/type :application.event/created
:event/actor applicant-user-id
:event/time (DateTime. 1000)
:application/id new-app-id
:application/external-id new-external-id
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}]
:application/licenses [{:license/id 1}]
:application/forms [{:form/id 1}]
:workflow/id 1
:workflow/type :workflow/default}
(ok-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [1]}
injections))))
(testing "multiple resources"
(is (= {:event/type :application.event/created
:event/actor applicant-user-id
:event/time (DateTime. 1000)
:application/id new-app-id
:application/external-id new-external-id
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}
{:catalogue-item/id 2
:resource/ext-id "res2"}]
:application/licenses [{:license/id 1}
{:license/id 2}]
:application/forms [{:form/id 1}]
:workflow/id 1
:workflow/type :workflow/default}
(ok-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [1 2]}
injections))))
(testing "error: zero catalogue items"
(is (= {:errors [{:type :must-not-be-empty
:key :catalogue-item-ids}]}
(fail-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids []}
injections))))
(testing "error: non-existing catalogue items"
(is (= {:errors [{:type :invalid-catalogue-item
:catalogue-item-id 999999}]}
(fail-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [999999]}
injections))))
(testing "catalogue items with different forms"
(is (= {:event/type :application.event/created
:event/actor applicant-user-id
:event/time (DateTime. 1000)
:application/id new-app-id
:application/external-id new-external-id
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}
{:catalogue-item/id 3
:resource/ext-id "res3"}]
:application/licenses [{:license/id 1}
{:license/id 2}
{:license/id 3}]
:application/forms [{:form/id 1} {:form/id 2}]
:workflow/id 1
:workflow/type :workflow/default}
(ok-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [1 3]}
injections))))
(testing "workflow form, multiple catalogue items with different forms"
(is (= {:event/type :application.event/created
:event/actor applicant-user-id
:event/time (DateTime. 1000)
:application/id new-app-id
:application/external-id new-external-id
:application/resources [{:catalogue-item/id 4 :resource/ext-id "res4"}
{:catalogue-item/id 5 :resource/ext-id "res5"}]
:application/licenses []
:application/forms [{:form/id 3} {:form/id 4} {:form/id 1} {:form/id 2}]
:workflow/id 2
:workflow/type :workflow/default}
(ok-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [4 5]}
injections))))
(testing "error: catalogue items with different workflows"
(is (= {:errors [{:type :unbundlable-catalogue-items
:catalogue-item-ids [1 4]}]}
(fail-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [1 4]}
injections))))
(testing "cannot execute the create command for an existing application"
(reset! allocated-new-ids? false)
(let [application (apply-events nil [dummy-created-event])]
(is (= {:errors [{:type :forbidden}]}
(fail-command application {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [1]}
injections)))
(is (false? @allocated-new-ids?) "should not allocate new IDs"))))
(deftest test-save-draft
(let [application (apply-events nil [dummy-created-event])]
(testing "saves a draft"
(is (= {:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}
(ok-command application
{:type :application.command/save-draft
:actor applicant-user-id
:field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}))))
(testing "saves a draft"
(is (= {:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}
(ok-command application
{:type :application.command/save-draft
:actor applicant-user-id
:field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}))))
(testing "does not save a draft when validations fail"
(is (= {:errors [{:field-id "1", :type :t.form.validation/invalid-value :form-id 1}]}
(fail-command application
{:type :application.command/save-draft
:actor applicant-user-id
:field-values [{:form 1 :field "1" :value "nonexistent_option"}]}))))
(testing "only the applicant can save a draft"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/save-draft
:actor "non-applicant"
:field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]})
(fail-command application
{:type :application.command/save-draft
:actor handler-user-id
:field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}))))
(testing "draft cannot be updated after submitting"
(let [application (apply-events application
[{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/save-draft
:actor applicant-user-id
:field-values [{:form 1 :field "1" :value "bar"}]})))))
(testing "draft can be updated after returning it to applicant"
(let [application (apply-events application
[{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/returned
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment ""}])]
(is (= {:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/field-values [{:form 1 :field "1" :value "bar"}]}
(ok-command application
{:type :application.command/save-draft
:actor applicant-user-id
:field-values [{:form 1 :field "1" :value "bar"}]})))))))
(deftest test-accept-licenses
(let [application (apply-events nil [dummy-created-event])]
(is (= {:event/type :application.event/licenses-accepted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/accepted-licenses #{1 2}}
(ok-command application
{:type :application.command/accept-licenses
:actor applicant-user-id
:accepted-licenses [1 2]})))))
(deftest test-add-licenses
(let [application (apply-events nil [dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(is (= {:event/type :application.event/licenses-added
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "comment"
:application/licenses [{:license/id 1} {:license/id 2}]}
(ok-command application
{:type :application.command/add-licenses
:actor handler-user-id
:comment "comment"
:licenses [1 2]})))
(is (= {:errors [{:type :must-not-be-empty :key :licenses}]}
(fail-command application
{:type :application.command/add-licenses
:actor handler-user-id
:comment "comment"
:licenses []})))))
(deftest test-change-resources
(let [cat-1 1
cat-2-other-license 2
cat-3-other-workflow 3
cat-4-other-form 4
form-1 1
form-2 2
wf-1 1
wf-2 2
license-1 1
license-2 2
application (apply-events nil [dummy-created-event])
submitted-application (apply-events application
[{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
approved-application (apply-events submitted-application
[{:event/type :application.event/approved
:event/time test-time
:event/actor handler-user-id
:application/comment "This is good"
:application/id app-id}])
injections {:get-catalogue-item
{cat-1 {:id cat-1 :resid "res1" :formid form-1 :wfid wf-1}
cat-2-other-license {:id cat-2-other-license :resid "res2" :formid form-1 :wfid wf-1}
cat-3-other-workflow {:id cat-3-other-workflow :resid "res3" :formid form-1 :wfid wf-2}
cat-4-other-form {:id cat-4-other-form :resid "res4" :formid form-2 :wfid wf-1}}
:get-catalogue-item-licenses
{cat-1 [{:id license-1}]
cat-2-other-license [{:id license-2}]
cat-3-other-workflow [{:id license-1}]
cat-4-other-form [{:id license-1}]}}]
(testing "applicant can add resources to a draft application"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/forms [{:form/id 1}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-2-other-license :resource/ext-id "res2"}]
:application/licenses [{:license/id license-1}
{:license/id license-2}]}
(ok-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-1 cat-2-other-license]}
injections))))
(testing "applicant cannot add resources to a submitted application"
(is (= {:errors [{:type :forbidden}]}
(fail-command submitted-application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-1 cat-2-other-license]}
injections))))
(testing "applicant cannot add resources with different workflow"
(is (= {:errors [{:type :unbundlable-catalogue-items
:catalogue-item-ids [cat-1 cat-3-other-workflow]}]}
(fail-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-1 cat-3-other-workflow]}
injections))))
(testing "applicant can add resources with different form"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/forms [{:form/id 1} {:form/id 2}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-4-other-form :resource/ext-id "res4"}]
:application/licenses [{:license/id license-1}]}
(ok-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-1 cat-4-other-form]}
injections))))
(testing "applicant can replace resources"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/forms [{:form/id 1}]
:application/resources [{:catalogue-item/id cat-2-other-license :resource/ext-id "res2"}]
:application/licenses [{:license/id license-2}]}
(ok-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-2-other-license]}
injections))))
(testing "applicant cannot replace resources with different workflow"
(is (= {:errors [{:type :changes-original-workflow :workflow/id wf-1 :ids [wf-2]}]}
(fail-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-3-other-workflow]}
injections))))
(testing "applicant can replace resources with different form"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/forms [{:form/id 2}]
:application/resources [{:catalogue-item/id cat-4-other-form :resource/ext-id "res4"}]
:application/licenses [{:license/id license-1}]}
(ok-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-4-other-form]}
injections))))
(testing "handler can add resources to a submitted application"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "Changed these for you"
:application/forms [{:form/id 1}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-2-other-license :resource/ext-id "res2"}]
:application/licenses [{:license/id license-1}
{:license/id license-2}]}
(ok-command submitted-application
{:type :application.command/change-resources
:actor handler-user-id
:comment "Changed these for you"
:catalogue-item-ids [cat-1 cat-2-other-license]}
injections)))
(testing "- even with a different workflow or form"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "Changed these for you"
:application/forms [{:form/id 1} {:form/id 2}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-3-other-workflow :resource/ext-id "res3"}
{:catalogue-item/id cat-4-other-form :resource/ext-id "res4"}]
:application/licenses [{:license/id license-1}]}
(ok-command submitted-application
{:type :application.command/change-resources
:actor handler-user-id
:comment "Changed these for you"
:catalogue-item-ids [cat-1 cat-3-other-workflow cat-4-other-form]}
injections)))))
(testing "handler can add resources to an approved application"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "Changed these for you"
:application/forms [{:form/id 1}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-2-other-license :resource/ext-id "res2"}]
:application/licenses [{:license/id license-1}
{:license/id license-2}]}
(ok-command approved-application
{:type :application.command/change-resources
:actor handler-user-id
:comment "Changed these for you"
:catalogue-item-ids [cat-1 cat-2-other-license]}
injections)))
(testing "- even with different workflow or form"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "Changed these for you"
:application/forms [{:form/id 1} {:form/id 2}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-3-other-workflow :resource/ext-id "res3"}
{:catalogue-item/id cat-4-other-form :resource/ext-id "res4"}]
:application/licenses [{:license/id license-1}]}
(ok-command approved-application
{:type :application.command/change-resources
:actor handler-user-id
:comment "Changed these for you"
:catalogue-item-ids [cat-1 cat-3-other-workflow cat-4-other-form]}
injections)))))
(testing "the catalogue item must exist"
(is (= {:errors [{:type :invalid-catalogue-item :catalogue-item-id 42}]}
(fail-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [42]}
injections))))
(testing "there must be at least one catalogue item"
(is (= {:errors [{:type :must-not-be-empty :key :catalogue-item-ids}]}
(fail-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids []}))))))
(deftest test-submit
(let [injections {:get-form-template dummy-get-form-template}
created-event {:event/type :application.event/created
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/external-id "2000/123"
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}
{:catalogue-item/id 2
:resource/ext-id "res2"}]
:application/licenses [{:license/id 1}]
:application/forms [{:form/id 1}]
:workflow/id 1
:workflow/type :workflow/default}
draft-saved-event {:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}
licenses-accepted-event {:event/type :application.event/licenses-accepted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/accepted-licenses #{1}}
submit-command {:type :application.command/submit
:actor applicant-user-id}
application-no-licenses (apply-events nil [created-event draft-saved-event])
application (apply-events application-no-licenses [licenses-accepted-event])
created-event2 (assoc created-event :application/forms [{:form/id 1} {:form/id 2}])
draft-saved-event2 (update draft-saved-event :application/field-values conj {:form 2 :field "1" :value "baz"})
application2 (apply-events nil [created-event2 draft-saved-event2 licenses-accepted-event])]
(testing "cannot submit a valid form if licenses are not accepted"
(is (= {:errors [{:type :t.actions.errors/licenses-not-accepted}]}
(fail-command application-no-licenses submit-command injections))))
(testing "can submit a valid form when licenses are accepted"
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(ok-command application submit-command injections))))
(testing "can submit two valid forms when licenses are accepted"
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(ok-command application2 submit-command injections))))
(testing "required fields"
(testing "1st field is optional and empty, 2nd field is required but invisible"
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(-> application
(apply-events [(assoc draft-saved-event :application/field-values [{:form 1 :field "1" :value ""}
{:form 1 :field "2" :value ""}])])
(ok-command submit-command injections)))))
(testing "1st field is given, 2nd field is required and visible but empty"
(is (= {:errors [{:type :t.form.validation/required
:form-id 1
:field-id "2"}]}
(-> application
(apply-events [(assoc draft-saved-event :application/field-values [{:form 1 :field "2" :value ""}])])
(fail-command submit-command injections)))))
(testing "1st field is given, 2nd field is given"
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(-> application
(ok-command submit-command injections)))))
(testing "cannot submit if one of two forms has required fields"
(is (= {:errors [{:field-id "1" :type :t.form.validation/required :form-id 2}]}
(-> application2
(apply-events [(assoc draft-saved-event2 :application/field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}
{:form 2 :field "1" :value ""}])])
(fail-command submit-command injections))))
(is (= {:errors [{:field-id "2" :type :t.form.validation/required :form-id 1}]}
(-> application2
(apply-events [(assoc draft-saved-event2 :application/field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value ""}
{:form 2 :field "1" :value "baz"}])])
(fail-command submit-command injections))))))
(testing "cannot submit draft if catalogue item is disabled"
(let [disabled (assoc-in application [:application/resources 1 :catalogue-item/enabled] false)]
(is (= {:errors [{:type :t.actions.errors/disabled-catalogue-item, :catalogue-item-id 2}]}
(fail-command disabled submit-command injections)))))
(testing "non-applicant cannot submit"
(let [application (apply-events application [(assoc licenses-accepted-event :event/actor "non-applicant")])]
(is (= {:errors [{:type :forbidden}]}
(fail-command application
(assoc submit-command :actor "non-applicant")
injections)))))
(testing "cannot submit twice"
(is (= {:errors [{:type :forbidden}]}
(-> application
(apply-events [{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
(fail-command submit-command injections)))))))
(deftest test-return-resubmit
(testing "return"
(let [application (apply-events nil
[(assoc dummy-created-event
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}])
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
returned-event (ok-command application
{:type :application.command/return
:actor handler-user-id
:comment "ret"})
submit-injections {:get-form-template dummy-get-form-template}
submit-command {:type :application.command/submit
:actor applicant-user-id}]
(is (= {:event/type :application.event/returned
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "ret"}
returned-event))
(testing "resubmit"
(let [returned (apply-events application [returned-event])]
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(ok-command returned submit-command submit-injections)))
(testing "succeeds even when catalogue item is disabled"
(let [disabled (assoc-in returned [:application/resources 0 :catalogue-item/enabled] false)]
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(ok-command disabled submit-command submit-injections))))))))))
(deftest test-assign-external-id
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(testing "handler can assign id"
(is (= {:event/type :application.event/external-id-assigned
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/external-id "ext123"}
(ok-command application
{:type :application.command/assign-external-id
:actor handler-user-id
:external-id "ext123"}))))
(testing "applicant can't assign id"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/assign-external-id
:actor applicant-user-id
:external-id "ext123"}))))))
(deftest test-approve-or-reject
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(testing "approved successfully"
(is (= {:event/type :application.event/approved
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "fine"}
(ok-command application
{:type :application.command/approve
:actor handler-user-id
:comment "fine"}))))
(testing "approved with end-date"
(is (= {:event/type :application.event/approved
:event/time test-time
:event/actor handler-user-id
:entitlement/end (DateTime. 1234)
:application/id app-id
:application/comment "fine"}
(ok-command application
{:type :application.command/approve
:actor handler-user-id
:entitlement-end (DateTime. 1234)
:comment "fine"}))))
(testing "rejected successfully"
(is (= {:event/type :application.event/rejected
:application/comment "bad"
:event/time test-time
:event/actor handler-user-id
:application/id app-id}
(ok-command application
{:type :application.command/reject
:actor handler-user-id
:comment "bad"}))))))
(deftest test-close
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/approved
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment ""}])]
(testing "handler can close approved application"
(is (= {:event/type :application.event/closed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "outdated"}
(ok-command application
{:type :application.command/close
:actor handler-user-id
:comment "outdated"})))))
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/returned
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment ""}])]
(testing "applicant can close returned application"
(is (= {:event/type :application.event/closed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/comment "outdated"}
(ok-command application
{:type :application.command/close
:actor applicant-user-id
:comment "outdated"}))))
(testing "handler can close returned application"
(is (= {:event/type :application.event/closed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "outdated"}
(ok-command application
{:type :application.command/close
:actor handler-user-id
:comment "outdated"}))))))
(deftest test-revoke
(let [application (apply-events nil [dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/approved
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment ""}])]
(is (= {:event/type :application.event/revoked
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "license violated"}
(ok-command application
{:type :application.command/revoke
:actor handler-user-id
:comment "license violated"}
injections)))))
(deftest test-decision
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
injections {:valid-user? #{"deity"}}]
(testing "required :valid-user? injection"
(is (= {:errors [{:type :missing-injection :injection :valid-user?}]}
(fail-command application
{:type :application.command/request-decision
:actor handler-user-id
:deciders ["deity"]
:comment "pls"}
{}))))
(testing "decider must be a valid user"
(is (= {:errors [{:type :t.form.validation/invalid-user :userid "deity2"}]}
(fail-command application
{:type :application.command/request-decision
:actor handler-user-id
:deciders ["deity2"]
:comment "pls"}
injections))))
(testing "deciding before ::request-decision should fail"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/decide
:actor "deity"
:decision :approved
:comment "pls"}
injections))))
(let [event (ok-command application
{:type :application.command/request-decision
:actor handler-user-id
:deciders ["deity"]
:comment ""}
injections)
request-id (:application/request-id event)
requested (apply-events application [event])]
(testing "decision requested successfully"
(is (instance? UUID request-id))
(is (= {:event/type :application.event/decision-requested
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/request-id request-id
:application/deciders ["deity"]
:application/comment ""}
event)))
(testing "only the requested user can decide"
(is (= {:errors [{:type :forbidden}]}
(fail-command requested
{:type :application.command/decide
:actor "deity2"
:decision :approved
:comment ""}
injections))))
(let [event (ok-command requested
{:type :application.command/decide
:actor "deity"
:decision :approved
:comment ""}
injections)
approved (apply-events requested [event])]
(testing "decided approved successfully"
(is (= {:event/type :application.event/decided
:event/time test-time
:event/actor "deity"
:application/id app-id
:application/request-id request-id
:application/decision :approved
:application/comment ""}
event)))
(testing "cannot approve twice"
(is (= {:errors [{:type :forbidden}]}
(fail-command approved
{:type :application.command/decide
:actor "deity"
:decision :approved
:comment ""}
injections)))))
(let [event (ok-command requested
{:type :application.command/decide
:actor "deity"
:decision :rejected
:comment ""}
injections)
rejected (apply-events requested [event])]
(testing "decided rejected successfully"
(is (= {:event/type :application.event/decided
:event/time test-time
:event/actor "deity"
:application/id app-id
:application/request-id request-id
:application/decision :rejected
:application/comment ""}
event)))
(testing "cannot reject twice"
(is (= {:errors [{:type :forbidden}]}
(fail-command rejected
{:type :application.command/decide
:actor "deity"
:decision :rejected
:comment ""}
injections)))))
(testing "other decisions are not possible"
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Value does not match schema"
(fail-command requested
{:type :application.command/decide
:actor "deity"
:decision :foobar
:comment ""}
injections)))))))
(deftest test-add-member
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/member-added
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:userid "somebody"}}])
injections {:valid-user? #{"member1" "member2" "somebody" applicant-user-id}}]
(testing "handler can add members"
(is (= {:event/type :application.event/member-added
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/member {:userid "member1"}}
(ok-command application
{:type :application.command/add-member
:actor handler-user-id
:member {:userid "member1"}}
injections))))
(testing "only handler can add members"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/add-member
:actor applicant-user-id
:member {:userid "member1"}}
injections)
(fail-command application
{:type :application.command/add-member
:actor "member1"
:member {:userid "member2"}}
injections))))
(testing "only valid users can be added"
(is (= {:errors [{:type :t.form.validation/invalid-user :userid "member3"}]}
(fail-command application
{:type :application.command/add-member
:actor handler-user-id
:member {:userid "member3"}}
injections))))
(testing "added members can see the application"
(is (-> (apply-commands application
[{:type :application.command/add-member
:actor handler-user-id
:member {:userid "member1"}}]
injections)
(model/see-application? "member1"))))))
(deftest test-invite-member
(let [application (apply-events nil [dummy-created-event])
injections {:valid-user? #{"somebody" applicant-user-id}
:secure-token (constantly "very-secure")}]
(testing "applicant can invite members"
(is (= {:event/type :application.event/member-invited
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:name "Member Applicant 1"
:email "member1@applicants.com"}
:invitation/token "very-secure"}
(ok-command application
{:type :application.command/invite-member
:actor applicant-user-id
:member {:name "Member Applicant 1"
:email "member1@applicants.com"}}
injections))))
(testing "handler can invite members"
(let [application (apply-events application [{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(is (= {:event/type :application.event/member-invited
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/member {:name "Member Applicant 1"
:email "member1@applicants.com"}
:invitation/token "very-secure"}
(ok-command application
{:type :application.command/invite-member
:actor handler-user-id
:member {:name "Member Applicant 1"
:email "member1@applicants.com"}}
injections)))))
(testing "other users cannot invite members"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/invite-member
:actor "member1"
:member {:name "Member Applicant 1"
:email "member1@applicants.com"}}
injections))))
(let [submitted (apply-events application
[{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(testing "applicant can't invite members to submitted application"
(is (= {:errors [{:type :forbidden}]}
(fail-command submitted
{:type :application.command/invite-member
:actor applicant-user-id
:member {:name "Member Applicant 1"
:email "member1@applicants.com"}}
injections))))
(testing "handler can invite members to submitted application"
(is (ok-command submitted
{:type :application.command/invite-member
:actor handler-user-id
:member {:name "Member Applicant 1"
:email "member1@applicants.com"}}
injections))))))
(deftest test-accept-invitation
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/member-invited
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:name "Some Body" :email "somebody@applicants.com"}
:invitation/token "very-secure"}])
injections {:valid-user? #{"somebody" "somebody2" applicant-user-id}}]
(testing "invited member can join draft"
(is (= {:event/type :application.event/member-joined
:event/time test-time
:event/actor "somebody"
:application/id app-id
:invitation/token "very-secure"}
(ok-command application
{:type :application.command/accept-invitation
:actor "somebody"
:token "very-secure"}
injections))))
(testing "invited member can't join if they are already a member"
(let [application (apply-events application
[{:event/type :application.event/member-added
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:userid "somebody"}}])]
(is (= {:errors [{:type :t.actions.errors/already-member :userid "somebody" :application-id app-id}]}
(fail-command application
{:type :application.command/accept-invitation
:actor "somebody"
:token "very-secure"}
injections)))))
(testing "invalid token can't be used to join"
(is (= {:errors [{:type :t.actions.errors/invalid-token :token "wrong-token"}]}
(fail-command application
{:type :application.command/accept-invitation
:actor "somebody"
:token "wrong-token"}
injections))))
(testing "token can't be used twice"
(let [application (apply-events application
[{:event/type :application.event/member-joined
:event/time test-time
:event/actor "somebody"
:application/id app-id
:invitation/token "very-secure"}])]
(is (= {:errors [{:type :t.actions.errors/invalid-token :token "very-secure"}]}
(fail-command application
{:type :application.command/accept-invitation
:actor "somebody2"
:token "very-secure"}
injections)))))
(let [submitted (apply-events application
[{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(testing "invited member can join submitted application"
(is (= {:event/type :application.event/member-joined
:event/actor "somebody"
:event/time test-time
:application/id app-id
:invitation/token "very-secure"}
(ok-command application
{:type :application.command/accept-invitation
:actor "somebody"
:token "very-secure"}
injections))))
(let [closed (apply-events submitted
[{:event/type :application.event/closed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/comment ""}])]
(testing "invited member can't join a closed application"
(is (= {:errors [{:type :forbidden}]}
(fail-command closed
{:type :application.command/accept-invitation
:actor "somebody"
:token "very-secure"}
injections))))))))
(deftest test-remove-member
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/member-added
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/member {:userid "somebody"}}])
injections {:valid-user? #{"somebody" applicant-user-id handler-user-id}}]
(testing "applicant can remove members"
(is (= {:event/type :application.event/member-removed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:userid "somebody"}
:application/comment "some comment"}
(ok-command application
{:type :application.command/remove-member
:actor applicant-user-id
:member {:userid "somebody"}
:comment "some comment"}
injections))))
(testing "handler can remove members"
(is (= {:event/type :application.event/member-removed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
;; NB no comment
:application/member {:userid "somebody"}}
(ok-command application
{:type :application.command/remove-member
:actor handler-user-id
:member {:userid "somebody"}}
injections))))
(testing "applicant cannot be removed"
(is (= {:errors [{:type :cannot-remove-applicant}]}
(fail-command application
{:type :application.command/remove-member
:actor applicant-user-id
:member {:userid applicant-user-id}}
injections)
(fail-command application
{:type :application.command/remove-member
:actor handler-user-id
:member {:userid applicant-user-id}}
injections))))
(testing "non-members cannot be removed"
(is (= {:errors [{:type :user-not-member :user {:userid "notamember"}}]}
(fail-command application
{:type :application.command/remove-member
:actor handler-user-id
:member {:userid "notamember"}}
injections))))
(testing "removed members cannot see the application"
(is (-> application
(model/see-application? "somebody")))
(is (not (-> application
(apply-commands [{:type :application.command/remove-member
:actor applicant-user-id
:member {:userid "somebody"}}]
injections)
(model/see-application? "somebody")))))))
(deftest test-uninvite-member
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/member-invited
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:name "Some Body" :email "some@body.com"}
:invitation/token "123456"}
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
injections {}]
(testing "uninvite member by applicant"
(is (= {:event/type :application.event/member-uninvited
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:name "Some Body" :email "some@body.com"}}
(ok-command application
{:type :application.command/uninvite-member
:actor applicant-user-id
:member {:name "Some Body" :email "some@body.com"}}
injections))))
(testing "uninvite member by handler"
(is (= {:event/type :application.event/member-uninvited
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/member {:name "Some Body" :email "some@body.com"}
:application/comment ""}
(ok-command application
{:type :application.command/uninvite-member
:actor handler-user-id
:member {:name "Some Body" :email "some@body.com"}
:comment ""}
injections))))
(testing "only invited members can be uninvited"
(is (= {:errors [{:type :user-not-member :user {:name "Not Member" :email "not@member.com"}}]}
(fail-command application
{:type :application.command/uninvite-member
:actor handler-user-id
:member {:name "Not Member" :email "not@member.com"}
:comment ""}
injections))))))
(deftest test-review
(let [reviewer "reviewer"
reviewer2 "reviewer2"
reviewer3 "reviewer3"
application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
injections {:valid-user? #{reviewer reviewer2 reviewer3}}]
(testing "required :valid-user? injection"
(is (= {:errors [{:type :missing-injection :injection :valid-user?}]}
(fail-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers [reviewer]
:comment ""}
{}))))
(testing "reviewers must not be empty"
(is (= {:errors [{:type :must-not-be-empty :key :reviewers}]}
(fail-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers []
:comment ""}
{}))))
(testing "reviewers must be a valid users"
(is (= {:errors [{:type :t.form.validation/invalid-user :userid "invaliduser"}
{:type :t.form.validation/invalid-user :userid "invaliduser2"}]}
(fail-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers ["invaliduser" reviewer "invaliduser2"]
:comment ""}
injections))))
(testing "reviewing before ::request-review should fail"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/review
:actor reviewer
:comment ""}
injections))))
(let [event-1 (ok-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers [reviewer reviewer2]
:comment ""}
injections)
request-id-1 (:application/request-id event-1)
application (apply-events application [event-1])
;; Make a new request that should partly override previous
event-2 (ok-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers [reviewer]
:comment ""}
injections)
request-id-2 (:application/request-id event-2)
application (apply-events application [event-2])]
(testing "review requested successfully"
(is (instance? UUID request-id-1))
(is (= {:event/type :application.event/review-requested
:application/request-id request-id-1
:application/reviewers [reviewer reviewer2]
:application/comment ""
:event/time test-time
:event/actor handler-user-id
:application/id app-id}
event-1))
(is (instance? UUID request-id-2))
(is (= {:event/type :application.event/review-requested
:application/request-id request-id-2
:application/reviewers [reviewer]
:application/comment ""
:event/time test-time
:event/actor handler-user-id
:application/id app-id}
event-2)))
(testing "only the requested reviewer can review"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/review
:actor reviewer3
:comment "..."}
injections))))
(testing "reviews are linked to different requests"
(is (= request-id-2
(:application/request-id
(ok-command application
{:type :application.command/review
:actor reviewer
:comment "..."}
injections))))
(is (= request-id-1
(:application/request-id
(ok-command application
{:type :application.command/review
:actor reviewer2
:comment "..."}
injections)))))
(let [event (ok-command application
{:type :application.command/review
:actor reviewer
:comment "..."}
injections)
application (apply-events application [event])]
(testing "reviewed succesfully"
(is (= {:event/type :application.event/reviewed
:event/time test-time
:event/actor reviewer
:application/id app-id
:application/request-id request-id-2
:application/comment "..."}
event)))
(testing "cannot review twice"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/review
:actor reviewer
:comment "..."}
injections))))
(testing "other reviewer can still review"
(is (= {:event/type :application.event/reviewed
:event/time test-time
:event/actor reviewer2
:application/id app-id
:application/request-id request-id-1
:application/comment "..."}
(ok-command application
{:type :application.command/review
:actor reviewer2
:comment "..."}
injections))))))))
(deftest test-remark
(let [reviewer "reviewer"
application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
valid-attachment-id 1234
wrong-application-attachment-id 1235
wrong-user-attachment-id 1236
unknown-attachment-id 1237
injections {:valid-user? #{reviewer}
:get-attachment-metadata
{valid-attachment-id {:application/id (:application/id application)
:attachment/id valid-attachment-id
:attachment/user handler-user-id}
wrong-application-attachment-id {:application/id (inc (:application/id application))
:attachment/id wrong-application-attachment-id
:attachment/user handler-user-id}
wrong-user-attachment-id {:application/id (:application/id application)
:attachment/id wrong-user-attachment-id
:attachment/user "carl"}}}]
(testing "handler can remark"
(let [event (ok-command application
{:type :application.command/remark
:actor handler-user-id
:comment "handler's remark"
:attachments [{:attachment/id valid-attachment-id}]
:public false}
injections)
application (apply-events application [event])]
(is (= {:event/type :application.event/remarked
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "handler's remark"
:application/public false
:event/attachments [{:attachment/id valid-attachment-id}]}
event))))
(testing "invalid attachments"
(is (= {:errors [{:type :invalid-attachments
:attachments [wrong-application-attachment-id wrong-user-attachment-id unknown-attachment-id]}]}
(fail-command application
{:type :application.command/remark
:actor handler-user-id
:comment "handler's remark"
:attachments [{:attachment/id valid-attachment-id}
{:attachment/id wrong-application-attachment-id}
{:attachment/id wrong-user-attachment-id}
{:attachment/id unknown-attachment-id}]
:public false}
injections))))
(testing "applicants cannot remark"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/remark
:actor applicant-user-id
:comment ""
:public false}
injections))))
(testing "reviewer cannot remark before becoming reviewer"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/remark
:actor reviewer
:comment ""
:public false}
injections))))
(let [event-1 (ok-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers [reviewer]
:comment ""}
injections)
application (apply-events application [event-1])
event-2 (ok-command application
{:type :application.command/remark
:actor reviewer
:comment "first remark"
:public false}
injections)
application (apply-events application [event-2])]
(testing "reviewer can remark before"
(is (= {:event/type :application.event/remarked
:event/time test-time
:event/actor reviewer
:application/id app-id
:application/comment "first remark"
:application/public false}
event-2))
(let [event-1 (ok-command application
{:type :application.command/review
:actor reviewer
:comment "..."}
injections)
application (apply-events application [event-1])
event-2 (ok-command application
{:type :application.command/remark
:actor reviewer
:comment "second remark"
:public false}
injections)
application (apply-events application [event-2])]
(testing "and after reviewing"
(is (= {:event/type :application.event/remarked
:event/time test-time
:event/actor reviewer
:application/id app-id
:application/comment "second remark"
:application/public false}
event-2))))))))
(deftest test-copy-as-new
(let [created-event {:event/type :application.event/created
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/external-id "2018/55"
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}
{:catalogue-item/id 2
:resource/ext-id "res2"}]
:application/licenses []
:application/forms [{:form/id 3}]
:workflow/id 1
:workflow/type :workflow/default}
application (apply-events nil [created-event
{:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/field-values [{:form 3 :field "text" :value "1"}
{:form 3 :field "attachment" :value "2"}]}])]
(testing "creates a new application with the same form answers"
(is (= [{:event/type :application.event/created
:event/time test-time
:event/actor applicant-user-id
:application/id new-app-id
:application/external-id new-external-id
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}
{:catalogue-item/id 2
:resource/ext-id "res2"}]
:application/licenses [{:license/id 1} {:license/id 2}]
:application/forms [{:form/id 1}]
:workflow/id 1
:workflow/type :workflow/default}
{:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id new-app-id
:application/field-values [{:form 3 :field "text" :value "1"}
{:form 3 :field "attachment" :value "102"}]}
{:event/type :application.event/copied-from
:event/time test-time
:event/actor applicant-user-id
:application/id new-app-id
:application/copied-from {:application/id app-id
:application/external-id "2018/55"}}
{:event/type :application.event/copied-to
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/copied-to {:application/id new-app-id
:application/external-id new-external-id}}]
(ok-command application
{:type :application.command/copy-as-new
:actor applicant-user-id}
injections))))))
(deftest test-delete
(let [draft-application (apply-events nil [dummy-created-event])
submitted-application (apply-events draft-application [{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(testing "forbidden"
(is (= {:errors [{:type :forbidden}]} (fail-command draft-application
{:type :application.command/delete
:actor handler-user-id}
injections)))
(is (= {:errors [{:type :forbidden}]} (fail-command submitted-application
{:type :application.command/delete
:actor applicant-user-id}
injections))))
(testing "success"
(is (= {:event/type :application.event/deleted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(ok-command draft-application
{:type :application.command/delete
:actor applicant-user-id}
injections))))))
(deftest test-handle-command
(let [application (model/application-view nil {:event/type :application.event/created
:event/actor "applicant"
:workflow/type :workflow/default})
command {:application-id 123 :time (DateTime. 1000)
:type :application.command/save-draft
:field-values []
:actor "applicant"}]
(testing "executes command when user is authorized"
(is (not (:errors (commands/handle-command command application {})))))
(testing "fails when command fails validation"
(is (thrown-with-msg? ExceptionInfo #"Value does not match schema"
(commands/handle-command (assoc command :time 3) application {}))))
(testing "fails when user is not authorized"
;; the permission checks should happen before executing the command handler
;; and only depend on the roles and permissions
(let [application (permissions/remove-role-from-user application :applicant "applicant")
result (commands/handle-command command application {})]
(is (= {:errors [{:type :forbidden}]} result))))))
| 27493 | (ns rems.application.test-commands
(:require [clojure.test :refer :all]
[rems.application.commands :as commands]
[rems.application.events :as events]
[rems.application.model :as model]
[rems.form-validation :as form-validation]
[rems.permissions :as permissions]
[rems.util :refer [assert-ex getx]])
(:import [clojure.lang ExceptionInfo]
[java.util UUID]
[org.joda.time DateTime]))
(def ^:private test-time (DateTime. 1000))
(def ^:private app-id 123)
(def ^:private new-app-id 456)
(def ^:private new-external-id "2019/66")
(def ^:private applicant-user-id "applicant")
(def ^:private handler-user-id "assistant")
(def ^:private dummy-created-event {:event/type :application.event/created
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/external-id "2000/123"
:application/resources []
:application/licenses []
:application/forms [{:form/id 1}]
:workflow/id 1
:workflow/type :workflow/default})
(def ^:private dummy-licenses
{1 {:id 1
:licensetype "link"
:localizations {:en {:title "en title"
:textcontent "en link"
:attachment-id 1}
:fi {:title "fi title"
:textcontent "fi link"
:attachment-id 2}}}
2 {:id 2
:licensetype "link"
:localizations {:en {:title "en title"
:textcontent "en link"}
:fi {:title "fi title"
:textcontent "fi link"}}}
3 {:id 3
:licensetype "link"
:localizations {:en {:title "en title"
:textcontent "en link"}
:fi {:title "fi title"
:textcontent "fi link"}}}})
(defn- dummy-get-workflow [id]
(getx {1 {:workflow {:type :workflow/default
:handlers [{:userid handler-user-id
:name "user"
:email "<EMAIL>"}]}}
2 {:workflow {:type :workflow/default
:handlers [{:userid handler-user-id
:name "user"
:email "<EMAIL>"}]
:forms [{:form/id 3} {:form/id 4}]}}}
id))
(defn- dummy-get-form-template [id]
(getx {1 {:form/id 1
:form/fields [{:field/id "1"
:field/optional true
:field/visible true
:field/type :option
:field/options [{:key "foo" :label "Foo"}
{:key "bar" :label "Bar"}]}
{:field/id "2"
:field/optional false
:field/visibility {:visibility/type :only-if
:visibility/field {:field/id "1"}
:visibility/values ["foo"]}}]}
2 {:form/id 2
:form/fields [{:field/id "1"
:field/optional false}]}
3 {:form/id 3
:form/fields [{:field/id "text"
:field/type :text}
{:field/id "attachment"
:field/type :attachment}]}
4 {:form/id 4
:form/fields [{:field/id "text"
:field/type :text}]}}
id))
(defn- dummy-get-catalogue-item [id]
(when (< id 10000)
(merge {:enabled true :archived false :expired false
:id id :wfid 1 :formid 1}
(getx {1 {:resid "res1"}
2 {:resid "res2"}
3 {:resid "res3"
:formid 2}
4 {:resid "res4"
:wfid 2}
5 {:resid "res5"
:formid 2
:wfid 2}}
id))))
(defn- dummy-get-catalogue-item-licenses [id]
(getx {1 [{:id 1}]
2 [{:id 2}]
3 [{:id 1}
{:id 2}
{:id 3}]
4 []
5 []} id))
(defn- dummy-get-config []
{})
(def allocated-new-ids? (atom false))
(def ^:private injections
{:blacklisted? (constantly false)
:get-workflow dummy-get-workflow
:get-form-template dummy-get-form-template
:get-catalogue-item dummy-get-catalogue-item
:get-catalogue-item-licenses dummy-get-catalogue-item-licenses
:get-config dummy-get-config
:get-license dummy-licenses
:get-user (fn [userid] {:userid userid})
:get-users-with-role (constantly nil)
:get-attachments-for-application (constantly nil)
:allocate-application-ids! (fn [_time]
(reset! allocated-new-ids? true)
{:application/id new-app-id
:application/external-id new-external-id})
:copy-attachment! (fn [_new-app-id attachment-id]
(+ attachment-id 100))})
;; could rework tests to use model/build-application-view instead of this
(defn apply-events [application events]
(events/validate-events events)
(-> (reduce model/application-view application events)
(model/enrich-with-injections injections)))
(defn- set-command-defaults [cmd]
(cond-> cmd
true
(assoc :time test-time)
(not= :application.command/create (:type cmd))
(assoc :application-id app-id)))
(defn- fail-command
([application cmd]
(fail-command application cmd nil))
([application cmd injections]
(let [cmd (set-command-defaults cmd)
result (commands/handle-command cmd application injections)]
(assert-ex (:errors result) {:cmd cmd :result result})
result)))
(defn- ok-command
([application cmd]
(ok-command application cmd nil))
([application cmd injections]
(let [cmd (set-command-defaults cmd)
result (commands/handle-command cmd application injections)]
(assert-ex (not (:errors result)) {:cmd cmd :result result})
(let [events (:events result)]
(events/validate-events events)
;; most tests expect only one event, so this avoids having to wrap the expectation to a list
(if (= 1 (count events))
(first events)
events)))))
(defn- apply-command
([application cmd]
(apply-command application cmd nil))
([application cmd injections]
(apply-events application [(ok-command application cmd injections)])))
(defn- apply-commands
([application commands]
(apply-commands application commands nil))
([application commands injections]
(reduce (fn [app cmd] (apply-command app cmd injections))
application commands)))
;;; Tests
(deftest test-create
(testing "one resource"
(is (= {:event/type :application.event/created
:event/actor applicant-user-id
:event/time (DateTime. 1000)
:application/id new-app-id
:application/external-id new-external-id
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}]
:application/licenses [{:license/id 1}]
:application/forms [{:form/id 1}]
:workflow/id 1
:workflow/type :workflow/default}
(ok-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [1]}
injections))))
(testing "multiple resources"
(is (= {:event/type :application.event/created
:event/actor applicant-user-id
:event/time (DateTime. 1000)
:application/id new-app-id
:application/external-id new-external-id
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}
{:catalogue-item/id 2
:resource/ext-id "res2"}]
:application/licenses [{:license/id 1}
{:license/id 2}]
:application/forms [{:form/id 1}]
:workflow/id 1
:workflow/type :workflow/default}
(ok-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [1 2]}
injections))))
(testing "error: zero catalogue items"
(is (= {:errors [{:type :must-not-be-empty
:key :catalogue-item-ids}]}
(fail-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids []}
injections))))
(testing "error: non-existing catalogue items"
(is (= {:errors [{:type :invalid-catalogue-item
:catalogue-item-id 999999}]}
(fail-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [999999]}
injections))))
(testing "catalogue items with different forms"
(is (= {:event/type :application.event/created
:event/actor applicant-user-id
:event/time (DateTime. 1000)
:application/id new-app-id
:application/external-id new-external-id
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}
{:catalogue-item/id 3
:resource/ext-id "res3"}]
:application/licenses [{:license/id 1}
{:license/id 2}
{:license/id 3}]
:application/forms [{:form/id 1} {:form/id 2}]
:workflow/id 1
:workflow/type :workflow/default}
(ok-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [1 3]}
injections))))
(testing "workflow form, multiple catalogue items with different forms"
(is (= {:event/type :application.event/created
:event/actor applicant-user-id
:event/time (DateTime. 1000)
:application/id new-app-id
:application/external-id new-external-id
:application/resources [{:catalogue-item/id 4 :resource/ext-id "res4"}
{:catalogue-item/id 5 :resource/ext-id "res5"}]
:application/licenses []
:application/forms [{:form/id 3} {:form/id 4} {:form/id 1} {:form/id 2}]
:workflow/id 2
:workflow/type :workflow/default}
(ok-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [4 5]}
injections))))
(testing "error: catalogue items with different workflows"
(is (= {:errors [{:type :unbundlable-catalogue-items
:catalogue-item-ids [1 4]}]}
(fail-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [1 4]}
injections))))
(testing "cannot execute the create command for an existing application"
(reset! allocated-new-ids? false)
(let [application (apply-events nil [dummy-created-event])]
(is (= {:errors [{:type :forbidden}]}
(fail-command application {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [1]}
injections)))
(is (false? @allocated-new-ids?) "should not allocate new IDs"))))
(deftest test-save-draft
(let [application (apply-events nil [dummy-created-event])]
(testing "saves a draft"
(is (= {:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}
(ok-command application
{:type :application.command/save-draft
:actor applicant-user-id
:field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}))))
(testing "saves a draft"
(is (= {:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}
(ok-command application
{:type :application.command/save-draft
:actor applicant-user-id
:field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}))))
(testing "does not save a draft when validations fail"
(is (= {:errors [{:field-id "1", :type :t.form.validation/invalid-value :form-id 1}]}
(fail-command application
{:type :application.command/save-draft
:actor applicant-user-id
:field-values [{:form 1 :field "1" :value "nonexistent_option"}]}))))
(testing "only the applicant can save a draft"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/save-draft
:actor "non-applicant"
:field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]})
(fail-command application
{:type :application.command/save-draft
:actor handler-user-id
:field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}))))
(testing "draft cannot be updated after submitting"
(let [application (apply-events application
[{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/save-draft
:actor applicant-user-id
:field-values [{:form 1 :field "1" :value "bar"}]})))))
(testing "draft can be updated after returning it to applicant"
(let [application (apply-events application
[{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/returned
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment ""}])]
(is (= {:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/field-values [{:form 1 :field "1" :value "bar"}]}
(ok-command application
{:type :application.command/save-draft
:actor applicant-user-id
:field-values [{:form 1 :field "1" :value "bar"}]})))))))
(deftest test-accept-licenses
(let [application (apply-events nil [dummy-created-event])]
(is (= {:event/type :application.event/licenses-accepted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/accepted-licenses #{1 2}}
(ok-command application
{:type :application.command/accept-licenses
:actor applicant-user-id
:accepted-licenses [1 2]})))))
(deftest test-add-licenses
(let [application (apply-events nil [dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(is (= {:event/type :application.event/licenses-added
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "comment"
:application/licenses [{:license/id 1} {:license/id 2}]}
(ok-command application
{:type :application.command/add-licenses
:actor handler-user-id
:comment "comment"
:licenses [1 2]})))
(is (= {:errors [{:type :must-not-be-empty :key :licenses}]}
(fail-command application
{:type :application.command/add-licenses
:actor handler-user-id
:comment "comment"
:licenses []})))))
(deftest test-change-resources
(let [cat-1 1
cat-2-other-license 2
cat-3-other-workflow 3
cat-4-other-form 4
form-1 1
form-2 2
wf-1 1
wf-2 2
license-1 1
license-2 2
application (apply-events nil [dummy-created-event])
submitted-application (apply-events application
[{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
approved-application (apply-events submitted-application
[{:event/type :application.event/approved
:event/time test-time
:event/actor handler-user-id
:application/comment "This is good"
:application/id app-id}])
injections {:get-catalogue-item
{cat-1 {:id cat-1 :resid "res1" :formid form-1 :wfid wf-1}
cat-2-other-license {:id cat-2-other-license :resid "res2" :formid form-1 :wfid wf-1}
cat-3-other-workflow {:id cat-3-other-workflow :resid "res3" :formid form-1 :wfid wf-2}
cat-4-other-form {:id cat-4-other-form :resid "res4" :formid form-2 :wfid wf-1}}
:get-catalogue-item-licenses
{cat-1 [{:id license-1}]
cat-2-other-license [{:id license-2}]
cat-3-other-workflow [{:id license-1}]
cat-4-other-form [{:id license-1}]}}]
(testing "applicant can add resources to a draft application"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/forms [{:form/id 1}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-2-other-license :resource/ext-id "res2"}]
:application/licenses [{:license/id license-1}
{:license/id license-2}]}
(ok-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-1 cat-2-other-license]}
injections))))
(testing "applicant cannot add resources to a submitted application"
(is (= {:errors [{:type :forbidden}]}
(fail-command submitted-application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-1 cat-2-other-license]}
injections))))
(testing "applicant cannot add resources with different workflow"
(is (= {:errors [{:type :unbundlable-catalogue-items
:catalogue-item-ids [cat-1 cat-3-other-workflow]}]}
(fail-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-1 cat-3-other-workflow]}
injections))))
(testing "applicant can add resources with different form"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/forms [{:form/id 1} {:form/id 2}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-4-other-form :resource/ext-id "res4"}]
:application/licenses [{:license/id license-1}]}
(ok-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-1 cat-4-other-form]}
injections))))
(testing "applicant can replace resources"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/forms [{:form/id 1}]
:application/resources [{:catalogue-item/id cat-2-other-license :resource/ext-id "res2"}]
:application/licenses [{:license/id license-2}]}
(ok-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-2-other-license]}
injections))))
(testing "applicant cannot replace resources with different workflow"
(is (= {:errors [{:type :changes-original-workflow :workflow/id wf-1 :ids [wf-2]}]}
(fail-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-3-other-workflow]}
injections))))
(testing "applicant can replace resources with different form"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/forms [{:form/id 2}]
:application/resources [{:catalogue-item/id cat-4-other-form :resource/ext-id "res4"}]
:application/licenses [{:license/id license-1}]}
(ok-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-4-other-form]}
injections))))
(testing "handler can add resources to a submitted application"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "Changed these for you"
:application/forms [{:form/id 1}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-2-other-license :resource/ext-id "res2"}]
:application/licenses [{:license/id license-1}
{:license/id license-2}]}
(ok-command submitted-application
{:type :application.command/change-resources
:actor handler-user-id
:comment "Changed these for you"
:catalogue-item-ids [cat-1 cat-2-other-license]}
injections)))
(testing "- even with a different workflow or form"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "Changed these for you"
:application/forms [{:form/id 1} {:form/id 2}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-3-other-workflow :resource/ext-id "res3"}
{:catalogue-item/id cat-4-other-form :resource/ext-id "res4"}]
:application/licenses [{:license/id license-1}]}
(ok-command submitted-application
{:type :application.command/change-resources
:actor handler-user-id
:comment "Changed these for you"
:catalogue-item-ids [cat-1 cat-3-other-workflow cat-4-other-form]}
injections)))))
(testing "handler can add resources to an approved application"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "Changed these for you"
:application/forms [{:form/id 1}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-2-other-license :resource/ext-id "res2"}]
:application/licenses [{:license/id license-1}
{:license/id license-2}]}
(ok-command approved-application
{:type :application.command/change-resources
:actor handler-user-id
:comment "Changed these for you"
:catalogue-item-ids [cat-1 cat-2-other-license]}
injections)))
(testing "- even with different workflow or form"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "Changed these for you"
:application/forms [{:form/id 1} {:form/id 2}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-3-other-workflow :resource/ext-id "res3"}
{:catalogue-item/id cat-4-other-form :resource/ext-id "res4"}]
:application/licenses [{:license/id license-1}]}
(ok-command approved-application
{:type :application.command/change-resources
:actor handler-user-id
:comment "Changed these for you"
:catalogue-item-ids [cat-1 cat-3-other-workflow cat-4-other-form]}
injections)))))
(testing "the catalogue item must exist"
(is (= {:errors [{:type :invalid-catalogue-item :catalogue-item-id 42}]}
(fail-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [42]}
injections))))
(testing "there must be at least one catalogue item"
(is (= {:errors [{:type :must-not-be-empty :key :catalogue-item-ids}]}
(fail-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids []}))))))
(deftest test-submit
(let [injections {:get-form-template dummy-get-form-template}
created-event {:event/type :application.event/created
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/external-id "2000/123"
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}
{:catalogue-item/id 2
:resource/ext-id "res2"}]
:application/licenses [{:license/id 1}]
:application/forms [{:form/id 1}]
:workflow/id 1
:workflow/type :workflow/default}
draft-saved-event {:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}
licenses-accepted-event {:event/type :application.event/licenses-accepted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/accepted-licenses #{1}}
submit-command {:type :application.command/submit
:actor applicant-user-id}
application-no-licenses (apply-events nil [created-event draft-saved-event])
application (apply-events application-no-licenses [licenses-accepted-event])
created-event2 (assoc created-event :application/forms [{:form/id 1} {:form/id 2}])
draft-saved-event2 (update draft-saved-event :application/field-values conj {:form 2 :field "1" :value "baz"})
application2 (apply-events nil [created-event2 draft-saved-event2 licenses-accepted-event])]
(testing "cannot submit a valid form if licenses are not accepted"
(is (= {:errors [{:type :t.actions.errors/licenses-not-accepted}]}
(fail-command application-no-licenses submit-command injections))))
(testing "can submit a valid form when licenses are accepted"
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(ok-command application submit-command injections))))
(testing "can submit two valid forms when licenses are accepted"
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(ok-command application2 submit-command injections))))
(testing "required fields"
(testing "1st field is optional and empty, 2nd field is required but invisible"
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(-> application
(apply-events [(assoc draft-saved-event :application/field-values [{:form 1 :field "1" :value ""}
{:form 1 :field "2" :value ""}])])
(ok-command submit-command injections)))))
(testing "1st field is given, 2nd field is required and visible but empty"
(is (= {:errors [{:type :t.form.validation/required
:form-id 1
:field-id "2"}]}
(-> application
(apply-events [(assoc draft-saved-event :application/field-values [{:form 1 :field "2" :value ""}])])
(fail-command submit-command injections)))))
(testing "1st field is given, 2nd field is given"
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(-> application
(ok-command submit-command injections)))))
(testing "cannot submit if one of two forms has required fields"
(is (= {:errors [{:field-id "1" :type :t.form.validation/required :form-id 2}]}
(-> application2
(apply-events [(assoc draft-saved-event2 :application/field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}
{:form 2 :field "1" :value ""}])])
(fail-command submit-command injections))))
(is (= {:errors [{:field-id "2" :type :t.form.validation/required :form-id 1}]}
(-> application2
(apply-events [(assoc draft-saved-event2 :application/field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value ""}
{:form 2 :field "1" :value "baz"}])])
(fail-command submit-command injections))))))
(testing "cannot submit draft if catalogue item is disabled"
(let [disabled (assoc-in application [:application/resources 1 :catalogue-item/enabled] false)]
(is (= {:errors [{:type :t.actions.errors/disabled-catalogue-item, :catalogue-item-id 2}]}
(fail-command disabled submit-command injections)))))
(testing "non-applicant cannot submit"
(let [application (apply-events application [(assoc licenses-accepted-event :event/actor "non-applicant")])]
(is (= {:errors [{:type :forbidden}]}
(fail-command application
(assoc submit-command :actor "non-applicant")
injections)))))
(testing "cannot submit twice"
(is (= {:errors [{:type :forbidden}]}
(-> application
(apply-events [{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
(fail-command submit-command injections)))))))
(deftest test-return-resubmit
(testing "return"
(let [application (apply-events nil
[(assoc dummy-created-event
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}])
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
returned-event (ok-command application
{:type :application.command/return
:actor handler-user-id
:comment "ret"})
submit-injections {:get-form-template dummy-get-form-template}
submit-command {:type :application.command/submit
:actor applicant-user-id}]
(is (= {:event/type :application.event/returned
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "ret"}
returned-event))
(testing "resubmit"
(let [returned (apply-events application [returned-event])]
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(ok-command returned submit-command submit-injections)))
(testing "succeeds even when catalogue item is disabled"
(let [disabled (assoc-in returned [:application/resources 0 :catalogue-item/enabled] false)]
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(ok-command disabled submit-command submit-injections))))))))))
(deftest test-assign-external-id
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(testing "handler can assign id"
(is (= {:event/type :application.event/external-id-assigned
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/external-id "ext123"}
(ok-command application
{:type :application.command/assign-external-id
:actor handler-user-id
:external-id "ext123"}))))
(testing "applicant can't assign id"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/assign-external-id
:actor applicant-user-id
:external-id "ext123"}))))))
(deftest test-approve-or-reject
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(testing "approved successfully"
(is (= {:event/type :application.event/approved
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "fine"}
(ok-command application
{:type :application.command/approve
:actor handler-user-id
:comment "fine"}))))
(testing "approved with end-date"
(is (= {:event/type :application.event/approved
:event/time test-time
:event/actor handler-user-id
:entitlement/end (DateTime. 1234)
:application/id app-id
:application/comment "fine"}
(ok-command application
{:type :application.command/approve
:actor handler-user-id
:entitlement-end (DateTime. 1234)
:comment "fine"}))))
(testing "rejected successfully"
(is (= {:event/type :application.event/rejected
:application/comment "bad"
:event/time test-time
:event/actor handler-user-id
:application/id app-id}
(ok-command application
{:type :application.command/reject
:actor handler-user-id
:comment "bad"}))))))
(deftest test-close
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/approved
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment ""}])]
(testing "handler can close approved application"
(is (= {:event/type :application.event/closed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "outdated"}
(ok-command application
{:type :application.command/close
:actor handler-user-id
:comment "outdated"})))))
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/returned
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment ""}])]
(testing "applicant can close returned application"
(is (= {:event/type :application.event/closed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/comment "outdated"}
(ok-command application
{:type :application.command/close
:actor applicant-user-id
:comment "outdated"}))))
(testing "handler can close returned application"
(is (= {:event/type :application.event/closed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "outdated"}
(ok-command application
{:type :application.command/close
:actor handler-user-id
:comment "outdated"}))))))
(deftest test-revoke
(let [application (apply-events nil [dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/approved
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment ""}])]
(is (= {:event/type :application.event/revoked
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "license violated"}
(ok-command application
{:type :application.command/revoke
:actor handler-user-id
:comment "license violated"}
injections)))))
(deftest test-decision
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
injections {:valid-user? #{"deity"}}]
(testing "required :valid-user? injection"
(is (= {:errors [{:type :missing-injection :injection :valid-user?}]}
(fail-command application
{:type :application.command/request-decision
:actor handler-user-id
:deciders ["deity"]
:comment "pls"}
{}))))
(testing "decider must be a valid user"
(is (= {:errors [{:type :t.form.validation/invalid-user :userid "deity2"}]}
(fail-command application
{:type :application.command/request-decision
:actor handler-user-id
:deciders ["deity2"]
:comment "pls"}
injections))))
(testing "deciding before ::request-decision should fail"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/decide
:actor "deity"
:decision :approved
:comment "pls"}
injections))))
(let [event (ok-command application
{:type :application.command/request-decision
:actor handler-user-id
:deciders ["deity"]
:comment ""}
injections)
request-id (:application/request-id event)
requested (apply-events application [event])]
(testing "decision requested successfully"
(is (instance? UUID request-id))
(is (= {:event/type :application.event/decision-requested
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/request-id request-id
:application/deciders ["deity"]
:application/comment ""}
event)))
(testing "only the requested user can decide"
(is (= {:errors [{:type :forbidden}]}
(fail-command requested
{:type :application.command/decide
:actor "deity2"
:decision :approved
:comment ""}
injections))))
(let [event (ok-command requested
{:type :application.command/decide
:actor "deity"
:decision :approved
:comment ""}
injections)
approved (apply-events requested [event])]
(testing "decided approved successfully"
(is (= {:event/type :application.event/decided
:event/time test-time
:event/actor "deity"
:application/id app-id
:application/request-id request-id
:application/decision :approved
:application/comment ""}
event)))
(testing "cannot approve twice"
(is (= {:errors [{:type :forbidden}]}
(fail-command approved
{:type :application.command/decide
:actor "deity"
:decision :approved
:comment ""}
injections)))))
(let [event (ok-command requested
{:type :application.command/decide
:actor "deity"
:decision :rejected
:comment ""}
injections)
rejected (apply-events requested [event])]
(testing "decided rejected successfully"
(is (= {:event/type :application.event/decided
:event/time test-time
:event/actor "deity"
:application/id app-id
:application/request-id request-id
:application/decision :rejected
:application/comment ""}
event)))
(testing "cannot reject twice"
(is (= {:errors [{:type :forbidden}]}
(fail-command rejected
{:type :application.command/decide
:actor "deity"
:decision :rejected
:comment ""}
injections)))))
(testing "other decisions are not possible"
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Value does not match schema"
(fail-command requested
{:type :application.command/decide
:actor "deity"
:decision :foobar
:comment ""}
injections)))))))
(deftest test-add-member
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/member-added
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:userid "somebody"}}])
injections {:valid-user? #{"member1" "member2" "somebody" applicant-user-id}}]
(testing "handler can add members"
(is (= {:event/type :application.event/member-added
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/member {:userid "member1"}}
(ok-command application
{:type :application.command/add-member
:actor handler-user-id
:member {:userid "member1"}}
injections))))
(testing "only handler can add members"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/add-member
:actor applicant-user-id
:member {:userid "member1"}}
injections)
(fail-command application
{:type :application.command/add-member
:actor "member1"
:member {:userid "member2"}}
injections))))
(testing "only valid users can be added"
(is (= {:errors [{:type :t.form.validation/invalid-user :userid "member3"}]}
(fail-command application
{:type :application.command/add-member
:actor handler-user-id
:member {:userid "member3"}}
injections))))
(testing "added members can see the application"
(is (-> (apply-commands application
[{:type :application.command/add-member
:actor handler-user-id
:member {:userid "member1"}}]
injections)
(model/see-application? "member1"))))))
(deftest test-invite-member
(let [application (apply-events nil [dummy-created-event])
injections {:valid-user? #{"somebody" applicant-user-id}
:secure-token (constantly "<PASSWORD>")}]
(testing "applicant can invite members"
(is (= {:event/type :application.event/member-invited
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:name "<NAME>"
:email "<EMAIL>"}
:invitation/token "<PASSWORD>"}
(ok-command application
{:type :application.command/invite-member
:actor applicant-user-id
:member {:name "<NAME>"
:email "<EMAIL>"}}
injections))))
(testing "handler can invite members"
(let [application (apply-events application [{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(is (= {:event/type :application.event/member-invited
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/member {:name "<NAME>"
:email "<EMAIL>"}
:invitation/token "<PASSWORD>"}
(ok-command application
{:type :application.command/invite-member
:actor handler-user-id
:member {:name "<NAME>"
:email "<EMAIL>"}}
injections)))))
(testing "other users cannot invite members"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/invite-member
:actor "member1"
:member {:name "<NAME>"
:email "<EMAIL>"}}
injections))))
(let [submitted (apply-events application
[{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(testing "applicant can't invite members to submitted application"
(is (= {:errors [{:type :forbidden}]}
(fail-command submitted
{:type :application.command/invite-member
:actor applicant-user-id
:member {:name "<NAME>"
:email "<EMAIL>"}}
injections))))
(testing "handler can invite members to submitted application"
(is (ok-command submitted
{:type :application.command/invite-member
:actor handler-user-id
:member {:name "<NAME>"
:email "<EMAIL>"}}
injections))))))
(deftest test-accept-invitation
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/member-invited
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:name "<NAME>" :email "<EMAIL>"}
:invitation/token "very-secure"}])
injections {:valid-user? #{"somebody" "somebody2" applicant-user-id}}]
(testing "invited member can join draft"
(is (= {:event/type :application.event/member-joined
:event/time test-time
:event/actor "somebody"
:application/id app-id
:invitation/token "very-secure"}
(ok-command application
{:type :application.command/accept-invitation
:actor "somebody"
:token "very-<PASSWORD>"}
injections))))
(testing "invited member can't join if they are already a member"
(let [application (apply-events application
[{:event/type :application.event/member-added
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:userid "somebody"}}])]
(is (= {:errors [{:type :t.actions.errors/already-member :userid "somebody" :application-id app-id}]}
(fail-command application
{:type :application.command/accept-invitation
:actor "somebody"
:token "very-secure"}
injections)))))
(testing "invalid token can't be used to join"
(is (= {:errors [{:type :t.actions.errors/invalid-token :token "wrong<PASSWORD>-token"}]}
(fail-command application
{:type :application.command/accept-invitation
:actor "somebody"
:token "wrong-<PASSWORD>"}
injections))))
(testing "token can't be used twice"
(let [application (apply-events application
[{:event/type :application.event/member-joined
:event/time test-time
:event/actor "somebody"
:application/id app-id
:invitation/token "<PASSWORD>"}])]
(is (= {:errors [{:type :t.actions.errors/invalid-token :token "<PASSWORD>"}]}
(fail-command application
{:type :application.command/accept-invitation
:actor "somebody2"
:token "<PASSWORD>"}
injections)))))
(let [submitted (apply-events application
[{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(testing "invited member can join submitted application"
(is (= {:event/type :application.event/member-joined
:event/actor "somebody"
:event/time test-time
:application/id app-id
:invitation/token "very-<PASSWORD>"}
(ok-command application
{:type :application.command/accept-invitation
:actor "somebody"
:token "<PASSWORD>"}
injections))))
(let [closed (apply-events submitted
[{:event/type :application.event/closed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/comment ""}])]
(testing "invited member can't join a closed application"
(is (= {:errors [{:type :forbidden}]}
(fail-command closed
{:type :application.command/accept-invitation
:actor "somebody"
:token "<PASSWORD>"}
injections))))))))
(deftest test-remove-member
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/member-added
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/member {:userid "somebody"}}])
injections {:valid-user? #{"somebody" applicant-user-id handler-user-id}}]
(testing "applicant can remove members"
(is (= {:event/type :application.event/member-removed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:userid "somebody"}
:application/comment "some comment"}
(ok-command application
{:type :application.command/remove-member
:actor applicant-user-id
:member {:userid "somebody"}
:comment "some comment"}
injections))))
(testing "handler can remove members"
(is (= {:event/type :application.event/member-removed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
;; NB no comment
:application/member {:userid "somebody"}}
(ok-command application
{:type :application.command/remove-member
:actor handler-user-id
:member {:userid "somebody"}}
injections))))
(testing "applicant cannot be removed"
(is (= {:errors [{:type :cannot-remove-applicant}]}
(fail-command application
{:type :application.command/remove-member
:actor applicant-user-id
:member {:userid applicant-user-id}}
injections)
(fail-command application
{:type :application.command/remove-member
:actor handler-user-id
:member {:userid applicant-user-id}}
injections))))
(testing "non-members cannot be removed"
(is (= {:errors [{:type :user-not-member :user {:userid "notamember"}}]}
(fail-command application
{:type :application.command/remove-member
:actor handler-user-id
:member {:userid "notamember"}}
injections))))
(testing "removed members cannot see the application"
(is (-> application
(model/see-application? "somebody")))
(is (not (-> application
(apply-commands [{:type :application.command/remove-member
:actor applicant-user-id
:member {:userid "somebody"}}]
injections)
(model/see-application? "somebody")))))))
(deftest test-uninvite-member
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/member-invited
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:name "<NAME>" :email "<EMAIL>"}
:invitation/token "<PASSWORD>"}
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
injections {}]
(testing "uninvite member by applicant"
(is (= {:event/type :application.event/member-uninvited
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:name "<NAME>" :email "<EMAIL>"}}
(ok-command application
{:type :application.command/uninvite-member
:actor applicant-user-id
:member {:name "<NAME>" :email "<EMAIL>"}}
injections))))
(testing "uninvite member by handler"
(is (= {:event/type :application.event/member-uninvited
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/member {:name "<NAME>" :email "<EMAIL>"}
:application/comment ""}
(ok-command application
{:type :application.command/uninvite-member
:actor handler-user-id
:member {:name "<NAME>" :email "<EMAIL>"}
:comment ""}
injections))))
(testing "only invited members can be uninvited"
(is (= {:errors [{:type :user-not-member :user {:name "<NAME> Member" :email "<EMAIL>"}}]}
(fail-command application
{:type :application.command/uninvite-member
:actor handler-user-id
:member {:name "<NAME> Member" :email "<EMAIL>"}
:comment ""}
injections))))))
(deftest test-review
(let [reviewer "reviewer"
reviewer2 "reviewer2"
reviewer3 "reviewer3"
application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
injections {:valid-user? #{reviewer reviewer2 reviewer3}}]
(testing "required :valid-user? injection"
(is (= {:errors [{:type :missing-injection :injection :valid-user?}]}
(fail-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers [reviewer]
:comment ""}
{}))))
(testing "reviewers must not be empty"
(is (= {:errors [{:type :must-not-be-empty :key :reviewers}]}
(fail-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers []
:comment ""}
{}))))
(testing "reviewers must be a valid users"
(is (= {:errors [{:type :t.form.validation/invalid-user :userid "invaliduser"}
{:type :t.form.validation/invalid-user :userid "invaliduser2"}]}
(fail-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers ["invaliduser" reviewer "invaliduser2"]
:comment ""}
injections))))
(testing "reviewing before ::request-review should fail"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/review
:actor reviewer
:comment ""}
injections))))
(let [event-1 (ok-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers [reviewer reviewer2]
:comment ""}
injections)
request-id-1 (:application/request-id event-1)
application (apply-events application [event-1])
;; Make a new request that should partly override previous
event-2 (ok-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers [reviewer]
:comment ""}
injections)
request-id-2 (:application/request-id event-2)
application (apply-events application [event-2])]
(testing "review requested successfully"
(is (instance? UUID request-id-1))
(is (= {:event/type :application.event/review-requested
:application/request-id request-id-1
:application/reviewers [reviewer reviewer2]
:application/comment ""
:event/time test-time
:event/actor handler-user-id
:application/id app-id}
event-1))
(is (instance? UUID request-id-2))
(is (= {:event/type :application.event/review-requested
:application/request-id request-id-2
:application/reviewers [reviewer]
:application/comment ""
:event/time test-time
:event/actor handler-user-id
:application/id app-id}
event-2)))
(testing "only the requested reviewer can review"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/review
:actor reviewer3
:comment "..."}
injections))))
(testing "reviews are linked to different requests"
(is (= request-id-2
(:application/request-id
(ok-command application
{:type :application.command/review
:actor reviewer
:comment "..."}
injections))))
(is (= request-id-1
(:application/request-id
(ok-command application
{:type :application.command/review
:actor reviewer2
:comment "..."}
injections)))))
(let [event (ok-command application
{:type :application.command/review
:actor reviewer
:comment "..."}
injections)
application (apply-events application [event])]
(testing "reviewed succesfully"
(is (= {:event/type :application.event/reviewed
:event/time test-time
:event/actor reviewer
:application/id app-id
:application/request-id request-id-2
:application/comment "..."}
event)))
(testing "cannot review twice"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/review
:actor reviewer
:comment "..."}
injections))))
(testing "other reviewer can still review"
(is (= {:event/type :application.event/reviewed
:event/time test-time
:event/actor reviewer2
:application/id app-id
:application/request-id request-id-1
:application/comment "..."}
(ok-command application
{:type :application.command/review
:actor reviewer2
:comment "..."}
injections))))))))
(deftest test-remark
(let [reviewer "reviewer"
application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
valid-attachment-id 1234
wrong-application-attachment-id 1235
wrong-user-attachment-id 1236
unknown-attachment-id 1237
injections {:valid-user? #{reviewer}
:get-attachment-metadata
{valid-attachment-id {:application/id (:application/id application)
:attachment/id valid-attachment-id
:attachment/user handler-user-id}
wrong-application-attachment-id {:application/id (inc (:application/id application))
:attachment/id wrong-application-attachment-id
:attachment/user handler-user-id}
wrong-user-attachment-id {:application/id (:application/id application)
:attachment/id wrong-user-attachment-id
:attachment/user "carl"}}}]
(testing "handler can remark"
(let [event (ok-command application
{:type :application.command/remark
:actor handler-user-id
:comment "handler's remark"
:attachments [{:attachment/id valid-attachment-id}]
:public false}
injections)
application (apply-events application [event])]
(is (= {:event/type :application.event/remarked
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "handler's remark"
:application/public false
:event/attachments [{:attachment/id valid-attachment-id}]}
event))))
(testing "invalid attachments"
(is (= {:errors [{:type :invalid-attachments
:attachments [wrong-application-attachment-id wrong-user-attachment-id unknown-attachment-id]}]}
(fail-command application
{:type :application.command/remark
:actor handler-user-id
:comment "handler's remark"
:attachments [{:attachment/id valid-attachment-id}
{:attachment/id wrong-application-attachment-id}
{:attachment/id wrong-user-attachment-id}
{:attachment/id unknown-attachment-id}]
:public false}
injections))))
(testing "applicants cannot remark"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/remark
:actor applicant-user-id
:comment ""
:public false}
injections))))
(testing "reviewer cannot remark before becoming reviewer"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/remark
:actor reviewer
:comment ""
:public false}
injections))))
(let [event-1 (ok-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers [reviewer]
:comment ""}
injections)
application (apply-events application [event-1])
event-2 (ok-command application
{:type :application.command/remark
:actor reviewer
:comment "first remark"
:public false}
injections)
application (apply-events application [event-2])]
(testing "reviewer can remark before"
(is (= {:event/type :application.event/remarked
:event/time test-time
:event/actor reviewer
:application/id app-id
:application/comment "first remark"
:application/public false}
event-2))
(let [event-1 (ok-command application
{:type :application.command/review
:actor reviewer
:comment "..."}
injections)
application (apply-events application [event-1])
event-2 (ok-command application
{:type :application.command/remark
:actor reviewer
:comment "second remark"
:public false}
injections)
application (apply-events application [event-2])]
(testing "and after reviewing"
(is (= {:event/type :application.event/remarked
:event/time test-time
:event/actor reviewer
:application/id app-id
:application/comment "second remark"
:application/public false}
event-2))))))))
(deftest test-copy-as-new
(let [created-event {:event/type :application.event/created
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/external-id "2018/55"
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}
{:catalogue-item/id 2
:resource/ext-id "res2"}]
:application/licenses []
:application/forms [{:form/id 3}]
:workflow/id 1
:workflow/type :workflow/default}
application (apply-events nil [created-event
{:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/field-values [{:form 3 :field "text" :value "1"}
{:form 3 :field "attachment" :value "2"}]}])]
(testing "creates a new application with the same form answers"
(is (= [{:event/type :application.event/created
:event/time test-time
:event/actor applicant-user-id
:application/id new-app-id
:application/external-id new-external-id
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}
{:catalogue-item/id 2
:resource/ext-id "res2"}]
:application/licenses [{:license/id 1} {:license/id 2}]
:application/forms [{:form/id 1}]
:workflow/id 1
:workflow/type :workflow/default}
{:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id new-app-id
:application/field-values [{:form 3 :field "text" :value "1"}
{:form 3 :field "attachment" :value "102"}]}
{:event/type :application.event/copied-from
:event/time test-time
:event/actor applicant-user-id
:application/id new-app-id
:application/copied-from {:application/id app-id
:application/external-id "2018/55"}}
{:event/type :application.event/copied-to
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/copied-to {:application/id new-app-id
:application/external-id new-external-id}}]
(ok-command application
{:type :application.command/copy-as-new
:actor applicant-user-id}
injections))))))
(deftest test-delete
(let [draft-application (apply-events nil [dummy-created-event])
submitted-application (apply-events draft-application [{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(testing "forbidden"
(is (= {:errors [{:type :forbidden}]} (fail-command draft-application
{:type :application.command/delete
:actor handler-user-id}
injections)))
(is (= {:errors [{:type :forbidden}]} (fail-command submitted-application
{:type :application.command/delete
:actor applicant-user-id}
injections))))
(testing "success"
(is (= {:event/type :application.event/deleted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(ok-command draft-application
{:type :application.command/delete
:actor applicant-user-id}
injections))))))
(deftest test-handle-command
(let [application (model/application-view nil {:event/type :application.event/created
:event/actor "applicant"
:workflow/type :workflow/default})
command {:application-id 123 :time (DateTime. 1000)
:type :application.command/save-draft
:field-values []
:actor "applicant"}]
(testing "executes command when user is authorized"
(is (not (:errors (commands/handle-command command application {})))))
(testing "fails when command fails validation"
(is (thrown-with-msg? ExceptionInfo #"Value does not match schema"
(commands/handle-command (assoc command :time 3) application {}))))
(testing "fails when user is not authorized"
;; the permission checks should happen before executing the command handler
;; and only depend on the roles and permissions
(let [application (permissions/remove-role-from-user application :applicant "applicant")
result (commands/handle-command command application {})]
(is (= {:errors [{:type :forbidden}]} result))))))
| true | (ns rems.application.test-commands
(:require [clojure.test :refer :all]
[rems.application.commands :as commands]
[rems.application.events :as events]
[rems.application.model :as model]
[rems.form-validation :as form-validation]
[rems.permissions :as permissions]
[rems.util :refer [assert-ex getx]])
(:import [clojure.lang ExceptionInfo]
[java.util UUID]
[org.joda.time DateTime]))
(def ^:private test-time (DateTime. 1000))
(def ^:private app-id 123)
(def ^:private new-app-id 456)
(def ^:private new-external-id "2019/66")
(def ^:private applicant-user-id "applicant")
(def ^:private handler-user-id "assistant")
(def ^:private dummy-created-event {:event/type :application.event/created
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/external-id "2000/123"
:application/resources []
:application/licenses []
:application/forms [{:form/id 1}]
:workflow/id 1
:workflow/type :workflow/default})
(def ^:private dummy-licenses
{1 {:id 1
:licensetype "link"
:localizations {:en {:title "en title"
:textcontent "en link"
:attachment-id 1}
:fi {:title "fi title"
:textcontent "fi link"
:attachment-id 2}}}
2 {:id 2
:licensetype "link"
:localizations {:en {:title "en title"
:textcontent "en link"}
:fi {:title "fi title"
:textcontent "fi link"}}}
3 {:id 3
:licensetype "link"
:localizations {:en {:title "en title"
:textcontent "en link"}
:fi {:title "fi title"
:textcontent "fi link"}}}})
(defn- dummy-get-workflow [id]
(getx {1 {:workflow {:type :workflow/default
:handlers [{:userid handler-user-id
:name "user"
:email "PI:EMAIL:<EMAIL>END_PI"}]}}
2 {:workflow {:type :workflow/default
:handlers [{:userid handler-user-id
:name "user"
:email "PI:EMAIL:<EMAIL>END_PI"}]
:forms [{:form/id 3} {:form/id 4}]}}}
id))
(defn- dummy-get-form-template [id]
(getx {1 {:form/id 1
:form/fields [{:field/id "1"
:field/optional true
:field/visible true
:field/type :option
:field/options [{:key "foo" :label "Foo"}
{:key "bar" :label "Bar"}]}
{:field/id "2"
:field/optional false
:field/visibility {:visibility/type :only-if
:visibility/field {:field/id "1"}
:visibility/values ["foo"]}}]}
2 {:form/id 2
:form/fields [{:field/id "1"
:field/optional false}]}
3 {:form/id 3
:form/fields [{:field/id "text"
:field/type :text}
{:field/id "attachment"
:field/type :attachment}]}
4 {:form/id 4
:form/fields [{:field/id "text"
:field/type :text}]}}
id))
(defn- dummy-get-catalogue-item [id]
(when (< id 10000)
(merge {:enabled true :archived false :expired false
:id id :wfid 1 :formid 1}
(getx {1 {:resid "res1"}
2 {:resid "res2"}
3 {:resid "res3"
:formid 2}
4 {:resid "res4"
:wfid 2}
5 {:resid "res5"
:formid 2
:wfid 2}}
id))))
(defn- dummy-get-catalogue-item-licenses [id]
(getx {1 [{:id 1}]
2 [{:id 2}]
3 [{:id 1}
{:id 2}
{:id 3}]
4 []
5 []} id))
(defn- dummy-get-config []
{})
(def allocated-new-ids? (atom false))
(def ^:private injections
{:blacklisted? (constantly false)
:get-workflow dummy-get-workflow
:get-form-template dummy-get-form-template
:get-catalogue-item dummy-get-catalogue-item
:get-catalogue-item-licenses dummy-get-catalogue-item-licenses
:get-config dummy-get-config
:get-license dummy-licenses
:get-user (fn [userid] {:userid userid})
:get-users-with-role (constantly nil)
:get-attachments-for-application (constantly nil)
:allocate-application-ids! (fn [_time]
(reset! allocated-new-ids? true)
{:application/id new-app-id
:application/external-id new-external-id})
:copy-attachment! (fn [_new-app-id attachment-id]
(+ attachment-id 100))})
;; could rework tests to use model/build-application-view instead of this
(defn apply-events [application events]
(events/validate-events events)
(-> (reduce model/application-view application events)
(model/enrich-with-injections injections)))
(defn- set-command-defaults [cmd]
(cond-> cmd
true
(assoc :time test-time)
(not= :application.command/create (:type cmd))
(assoc :application-id app-id)))
(defn- fail-command
([application cmd]
(fail-command application cmd nil))
([application cmd injections]
(let [cmd (set-command-defaults cmd)
result (commands/handle-command cmd application injections)]
(assert-ex (:errors result) {:cmd cmd :result result})
result)))
(defn- ok-command
([application cmd]
(ok-command application cmd nil))
([application cmd injections]
(let [cmd (set-command-defaults cmd)
result (commands/handle-command cmd application injections)]
(assert-ex (not (:errors result)) {:cmd cmd :result result})
(let [events (:events result)]
(events/validate-events events)
;; most tests expect only one event, so this avoids having to wrap the expectation to a list
(if (= 1 (count events))
(first events)
events)))))
(defn- apply-command
([application cmd]
(apply-command application cmd nil))
([application cmd injections]
(apply-events application [(ok-command application cmd injections)])))
(defn- apply-commands
([application commands]
(apply-commands application commands nil))
([application commands injections]
(reduce (fn [app cmd] (apply-command app cmd injections))
application commands)))
;;; Tests
(deftest test-create
(testing "one resource"
(is (= {:event/type :application.event/created
:event/actor applicant-user-id
:event/time (DateTime. 1000)
:application/id new-app-id
:application/external-id new-external-id
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}]
:application/licenses [{:license/id 1}]
:application/forms [{:form/id 1}]
:workflow/id 1
:workflow/type :workflow/default}
(ok-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [1]}
injections))))
(testing "multiple resources"
(is (= {:event/type :application.event/created
:event/actor applicant-user-id
:event/time (DateTime. 1000)
:application/id new-app-id
:application/external-id new-external-id
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}
{:catalogue-item/id 2
:resource/ext-id "res2"}]
:application/licenses [{:license/id 1}
{:license/id 2}]
:application/forms [{:form/id 1}]
:workflow/id 1
:workflow/type :workflow/default}
(ok-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [1 2]}
injections))))
(testing "error: zero catalogue items"
(is (= {:errors [{:type :must-not-be-empty
:key :catalogue-item-ids}]}
(fail-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids []}
injections))))
(testing "error: non-existing catalogue items"
(is (= {:errors [{:type :invalid-catalogue-item
:catalogue-item-id 999999}]}
(fail-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [999999]}
injections))))
(testing "catalogue items with different forms"
(is (= {:event/type :application.event/created
:event/actor applicant-user-id
:event/time (DateTime. 1000)
:application/id new-app-id
:application/external-id new-external-id
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}
{:catalogue-item/id 3
:resource/ext-id "res3"}]
:application/licenses [{:license/id 1}
{:license/id 2}
{:license/id 3}]
:application/forms [{:form/id 1} {:form/id 2}]
:workflow/id 1
:workflow/type :workflow/default}
(ok-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [1 3]}
injections))))
(testing "workflow form, multiple catalogue items with different forms"
(is (= {:event/type :application.event/created
:event/actor applicant-user-id
:event/time (DateTime. 1000)
:application/id new-app-id
:application/external-id new-external-id
:application/resources [{:catalogue-item/id 4 :resource/ext-id "res4"}
{:catalogue-item/id 5 :resource/ext-id "res5"}]
:application/licenses []
:application/forms [{:form/id 3} {:form/id 4} {:form/id 1} {:form/id 2}]
:workflow/id 2
:workflow/type :workflow/default}
(ok-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [4 5]}
injections))))
(testing "error: catalogue items with different workflows"
(is (= {:errors [{:type :unbundlable-catalogue-items
:catalogue-item-ids [1 4]}]}
(fail-command nil {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [1 4]}
injections))))
(testing "cannot execute the create command for an existing application"
(reset! allocated-new-ids? false)
(let [application (apply-events nil [dummy-created-event])]
(is (= {:errors [{:type :forbidden}]}
(fail-command application {:type :application.command/create
:actor applicant-user-id
:catalogue-item-ids [1]}
injections)))
(is (false? @allocated-new-ids?) "should not allocate new IDs"))))
(deftest test-save-draft
(let [application (apply-events nil [dummy-created-event])]
(testing "saves a draft"
(is (= {:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}
(ok-command application
{:type :application.command/save-draft
:actor applicant-user-id
:field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}))))
(testing "saves a draft"
(is (= {:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}
(ok-command application
{:type :application.command/save-draft
:actor applicant-user-id
:field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}))))
(testing "does not save a draft when validations fail"
(is (= {:errors [{:field-id "1", :type :t.form.validation/invalid-value :form-id 1}]}
(fail-command application
{:type :application.command/save-draft
:actor applicant-user-id
:field-values [{:form 1 :field "1" :value "nonexistent_option"}]}))))
(testing "only the applicant can save a draft"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/save-draft
:actor "non-applicant"
:field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]})
(fail-command application
{:type :application.command/save-draft
:actor handler-user-id
:field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}))))
(testing "draft cannot be updated after submitting"
(let [application (apply-events application
[{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/save-draft
:actor applicant-user-id
:field-values [{:form 1 :field "1" :value "bar"}]})))))
(testing "draft can be updated after returning it to applicant"
(let [application (apply-events application
[{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/returned
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment ""}])]
(is (= {:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/field-values [{:form 1 :field "1" :value "bar"}]}
(ok-command application
{:type :application.command/save-draft
:actor applicant-user-id
:field-values [{:form 1 :field "1" :value "bar"}]})))))))
(deftest test-accept-licenses
(let [application (apply-events nil [dummy-created-event])]
(is (= {:event/type :application.event/licenses-accepted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/accepted-licenses #{1 2}}
(ok-command application
{:type :application.command/accept-licenses
:actor applicant-user-id
:accepted-licenses [1 2]})))))
(deftest test-add-licenses
(let [application (apply-events nil [dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(is (= {:event/type :application.event/licenses-added
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "comment"
:application/licenses [{:license/id 1} {:license/id 2}]}
(ok-command application
{:type :application.command/add-licenses
:actor handler-user-id
:comment "comment"
:licenses [1 2]})))
(is (= {:errors [{:type :must-not-be-empty :key :licenses}]}
(fail-command application
{:type :application.command/add-licenses
:actor handler-user-id
:comment "comment"
:licenses []})))))
(deftest test-change-resources
(let [cat-1 1
cat-2-other-license 2
cat-3-other-workflow 3
cat-4-other-form 4
form-1 1
form-2 2
wf-1 1
wf-2 2
license-1 1
license-2 2
application (apply-events nil [dummy-created-event])
submitted-application (apply-events application
[{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
approved-application (apply-events submitted-application
[{:event/type :application.event/approved
:event/time test-time
:event/actor handler-user-id
:application/comment "This is good"
:application/id app-id}])
injections {:get-catalogue-item
{cat-1 {:id cat-1 :resid "res1" :formid form-1 :wfid wf-1}
cat-2-other-license {:id cat-2-other-license :resid "res2" :formid form-1 :wfid wf-1}
cat-3-other-workflow {:id cat-3-other-workflow :resid "res3" :formid form-1 :wfid wf-2}
cat-4-other-form {:id cat-4-other-form :resid "res4" :formid form-2 :wfid wf-1}}
:get-catalogue-item-licenses
{cat-1 [{:id license-1}]
cat-2-other-license [{:id license-2}]
cat-3-other-workflow [{:id license-1}]
cat-4-other-form [{:id license-1}]}}]
(testing "applicant can add resources to a draft application"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/forms [{:form/id 1}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-2-other-license :resource/ext-id "res2"}]
:application/licenses [{:license/id license-1}
{:license/id license-2}]}
(ok-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-1 cat-2-other-license]}
injections))))
(testing "applicant cannot add resources to a submitted application"
(is (= {:errors [{:type :forbidden}]}
(fail-command submitted-application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-1 cat-2-other-license]}
injections))))
(testing "applicant cannot add resources with different workflow"
(is (= {:errors [{:type :unbundlable-catalogue-items
:catalogue-item-ids [cat-1 cat-3-other-workflow]}]}
(fail-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-1 cat-3-other-workflow]}
injections))))
(testing "applicant can add resources with different form"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/forms [{:form/id 1} {:form/id 2}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-4-other-form :resource/ext-id "res4"}]
:application/licenses [{:license/id license-1}]}
(ok-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-1 cat-4-other-form]}
injections))))
(testing "applicant can replace resources"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/forms [{:form/id 1}]
:application/resources [{:catalogue-item/id cat-2-other-license :resource/ext-id "res2"}]
:application/licenses [{:license/id license-2}]}
(ok-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-2-other-license]}
injections))))
(testing "applicant cannot replace resources with different workflow"
(is (= {:errors [{:type :changes-original-workflow :workflow/id wf-1 :ids [wf-2]}]}
(fail-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-3-other-workflow]}
injections))))
(testing "applicant can replace resources with different form"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/forms [{:form/id 2}]
:application/resources [{:catalogue-item/id cat-4-other-form :resource/ext-id "res4"}]
:application/licenses [{:license/id license-1}]}
(ok-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [cat-4-other-form]}
injections))))
(testing "handler can add resources to a submitted application"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "Changed these for you"
:application/forms [{:form/id 1}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-2-other-license :resource/ext-id "res2"}]
:application/licenses [{:license/id license-1}
{:license/id license-2}]}
(ok-command submitted-application
{:type :application.command/change-resources
:actor handler-user-id
:comment "Changed these for you"
:catalogue-item-ids [cat-1 cat-2-other-license]}
injections)))
(testing "- even with a different workflow or form"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "Changed these for you"
:application/forms [{:form/id 1} {:form/id 2}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-3-other-workflow :resource/ext-id "res3"}
{:catalogue-item/id cat-4-other-form :resource/ext-id "res4"}]
:application/licenses [{:license/id license-1}]}
(ok-command submitted-application
{:type :application.command/change-resources
:actor handler-user-id
:comment "Changed these for you"
:catalogue-item-ids [cat-1 cat-3-other-workflow cat-4-other-form]}
injections)))))
(testing "handler can add resources to an approved application"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "Changed these for you"
:application/forms [{:form/id 1}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-2-other-license :resource/ext-id "res2"}]
:application/licenses [{:license/id license-1}
{:license/id license-2}]}
(ok-command approved-application
{:type :application.command/change-resources
:actor handler-user-id
:comment "Changed these for you"
:catalogue-item-ids [cat-1 cat-2-other-license]}
injections)))
(testing "- even with different workflow or form"
(is (= {:event/type :application.event/resources-changed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "Changed these for you"
:application/forms [{:form/id 1} {:form/id 2}]
:application/resources [{:catalogue-item/id cat-1 :resource/ext-id "res1"}
{:catalogue-item/id cat-3-other-workflow :resource/ext-id "res3"}
{:catalogue-item/id cat-4-other-form :resource/ext-id "res4"}]
:application/licenses [{:license/id license-1}]}
(ok-command approved-application
{:type :application.command/change-resources
:actor handler-user-id
:comment "Changed these for you"
:catalogue-item-ids [cat-1 cat-3-other-workflow cat-4-other-form]}
injections)))))
(testing "the catalogue item must exist"
(is (= {:errors [{:type :invalid-catalogue-item :catalogue-item-id 42}]}
(fail-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids [42]}
injections))))
(testing "there must be at least one catalogue item"
(is (= {:errors [{:type :must-not-be-empty :key :catalogue-item-ids}]}
(fail-command application
{:type :application.command/change-resources
:actor applicant-user-id
:catalogue-item-ids []}))))))
(deftest test-submit
(let [injections {:get-form-template dummy-get-form-template}
created-event {:event/type :application.event/created
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/external-id "2000/123"
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}
{:catalogue-item/id 2
:resource/ext-id "res2"}]
:application/licenses [{:license/id 1}]
:application/forms [{:form/id 1}]
:workflow/id 1
:workflow/type :workflow/default}
draft-saved-event {:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}]}
licenses-accepted-event {:event/type :application.event/licenses-accepted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/accepted-licenses #{1}}
submit-command {:type :application.command/submit
:actor applicant-user-id}
application-no-licenses (apply-events nil [created-event draft-saved-event])
application (apply-events application-no-licenses [licenses-accepted-event])
created-event2 (assoc created-event :application/forms [{:form/id 1} {:form/id 2}])
draft-saved-event2 (update draft-saved-event :application/field-values conj {:form 2 :field "1" :value "baz"})
application2 (apply-events nil [created-event2 draft-saved-event2 licenses-accepted-event])]
(testing "cannot submit a valid form if licenses are not accepted"
(is (= {:errors [{:type :t.actions.errors/licenses-not-accepted}]}
(fail-command application-no-licenses submit-command injections))))
(testing "can submit a valid form when licenses are accepted"
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(ok-command application submit-command injections))))
(testing "can submit two valid forms when licenses are accepted"
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(ok-command application2 submit-command injections))))
(testing "required fields"
(testing "1st field is optional and empty, 2nd field is required but invisible"
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(-> application
(apply-events [(assoc draft-saved-event :application/field-values [{:form 1 :field "1" :value ""}
{:form 1 :field "2" :value ""}])])
(ok-command submit-command injections)))))
(testing "1st field is given, 2nd field is required and visible but empty"
(is (= {:errors [{:type :t.form.validation/required
:form-id 1
:field-id "2"}]}
(-> application
(apply-events [(assoc draft-saved-event :application/field-values [{:form 1 :field "2" :value ""}])])
(fail-command submit-command injections)))))
(testing "1st field is given, 2nd field is given"
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(-> application
(ok-command submit-command injections)))))
(testing "cannot submit if one of two forms has required fields"
(is (= {:errors [{:field-id "1" :type :t.form.validation/required :form-id 2}]}
(-> application2
(apply-events [(assoc draft-saved-event2 :application/field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value "bar"}
{:form 2 :field "1" :value ""}])])
(fail-command submit-command injections))))
(is (= {:errors [{:field-id "2" :type :t.form.validation/required :form-id 1}]}
(-> application2
(apply-events [(assoc draft-saved-event2 :application/field-values [{:form 1 :field "1" :value "foo"}
{:form 1 :field "2" :value ""}
{:form 2 :field "1" :value "baz"}])])
(fail-command submit-command injections))))))
(testing "cannot submit draft if catalogue item is disabled"
(let [disabled (assoc-in application [:application/resources 1 :catalogue-item/enabled] false)]
(is (= {:errors [{:type :t.actions.errors/disabled-catalogue-item, :catalogue-item-id 2}]}
(fail-command disabled submit-command injections)))))
(testing "non-applicant cannot submit"
(let [application (apply-events application [(assoc licenses-accepted-event :event/actor "non-applicant")])]
(is (= {:errors [{:type :forbidden}]}
(fail-command application
(assoc submit-command :actor "non-applicant")
injections)))))
(testing "cannot submit twice"
(is (= {:errors [{:type :forbidden}]}
(-> application
(apply-events [{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
(fail-command submit-command injections)))))))
(deftest test-return-resubmit
(testing "return"
(let [application (apply-events nil
[(assoc dummy-created-event
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}])
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
returned-event (ok-command application
{:type :application.command/return
:actor handler-user-id
:comment "ret"})
submit-injections {:get-form-template dummy-get-form-template}
submit-command {:type :application.command/submit
:actor applicant-user-id}]
(is (= {:event/type :application.event/returned
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "ret"}
returned-event))
(testing "resubmit"
(let [returned (apply-events application [returned-event])]
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(ok-command returned submit-command submit-injections)))
(testing "succeeds even when catalogue item is disabled"
(let [disabled (assoc-in returned [:application/resources 0 :catalogue-item/enabled] false)]
(is (= {:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(ok-command disabled submit-command submit-injections))))))))))
(deftest test-assign-external-id
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(testing "handler can assign id"
(is (= {:event/type :application.event/external-id-assigned
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/external-id "ext123"}
(ok-command application
{:type :application.command/assign-external-id
:actor handler-user-id
:external-id "ext123"}))))
(testing "applicant can't assign id"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/assign-external-id
:actor applicant-user-id
:external-id "ext123"}))))))
(deftest test-approve-or-reject
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(testing "approved successfully"
(is (= {:event/type :application.event/approved
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "fine"}
(ok-command application
{:type :application.command/approve
:actor handler-user-id
:comment "fine"}))))
(testing "approved with end-date"
(is (= {:event/type :application.event/approved
:event/time test-time
:event/actor handler-user-id
:entitlement/end (DateTime. 1234)
:application/id app-id
:application/comment "fine"}
(ok-command application
{:type :application.command/approve
:actor handler-user-id
:entitlement-end (DateTime. 1234)
:comment "fine"}))))
(testing "rejected successfully"
(is (= {:event/type :application.event/rejected
:application/comment "bad"
:event/time test-time
:event/actor handler-user-id
:application/id app-id}
(ok-command application
{:type :application.command/reject
:actor handler-user-id
:comment "bad"}))))))
(deftest test-close
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/approved
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment ""}])]
(testing "handler can close approved application"
(is (= {:event/type :application.event/closed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "outdated"}
(ok-command application
{:type :application.command/close
:actor handler-user-id
:comment "outdated"})))))
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/returned
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment ""}])]
(testing "applicant can close returned application"
(is (= {:event/type :application.event/closed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/comment "outdated"}
(ok-command application
{:type :application.command/close
:actor applicant-user-id
:comment "outdated"}))))
(testing "handler can close returned application"
(is (= {:event/type :application.event/closed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "outdated"}
(ok-command application
{:type :application.command/close
:actor handler-user-id
:comment "outdated"}))))))
(deftest test-revoke
(let [application (apply-events nil [dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/approved
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment ""}])]
(is (= {:event/type :application.event/revoked
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "license violated"}
(ok-command application
{:type :application.command/revoke
:actor handler-user-id
:comment "license violated"}
injections)))))
(deftest test-decision
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
injections {:valid-user? #{"deity"}}]
(testing "required :valid-user? injection"
(is (= {:errors [{:type :missing-injection :injection :valid-user?}]}
(fail-command application
{:type :application.command/request-decision
:actor handler-user-id
:deciders ["deity"]
:comment "pls"}
{}))))
(testing "decider must be a valid user"
(is (= {:errors [{:type :t.form.validation/invalid-user :userid "deity2"}]}
(fail-command application
{:type :application.command/request-decision
:actor handler-user-id
:deciders ["deity2"]
:comment "pls"}
injections))))
(testing "deciding before ::request-decision should fail"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/decide
:actor "deity"
:decision :approved
:comment "pls"}
injections))))
(let [event (ok-command application
{:type :application.command/request-decision
:actor handler-user-id
:deciders ["deity"]
:comment ""}
injections)
request-id (:application/request-id event)
requested (apply-events application [event])]
(testing "decision requested successfully"
(is (instance? UUID request-id))
(is (= {:event/type :application.event/decision-requested
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/request-id request-id
:application/deciders ["deity"]
:application/comment ""}
event)))
(testing "only the requested user can decide"
(is (= {:errors [{:type :forbidden}]}
(fail-command requested
{:type :application.command/decide
:actor "deity2"
:decision :approved
:comment ""}
injections))))
(let [event (ok-command requested
{:type :application.command/decide
:actor "deity"
:decision :approved
:comment ""}
injections)
approved (apply-events requested [event])]
(testing "decided approved successfully"
(is (= {:event/type :application.event/decided
:event/time test-time
:event/actor "deity"
:application/id app-id
:application/request-id request-id
:application/decision :approved
:application/comment ""}
event)))
(testing "cannot approve twice"
(is (= {:errors [{:type :forbidden}]}
(fail-command approved
{:type :application.command/decide
:actor "deity"
:decision :approved
:comment ""}
injections)))))
(let [event (ok-command requested
{:type :application.command/decide
:actor "deity"
:decision :rejected
:comment ""}
injections)
rejected (apply-events requested [event])]
(testing "decided rejected successfully"
(is (= {:event/type :application.event/decided
:event/time test-time
:event/actor "deity"
:application/id app-id
:application/request-id request-id
:application/decision :rejected
:application/comment ""}
event)))
(testing "cannot reject twice"
(is (= {:errors [{:type :forbidden}]}
(fail-command rejected
{:type :application.command/decide
:actor "deity"
:decision :rejected
:comment ""}
injections)))))
(testing "other decisions are not possible"
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Value does not match schema"
(fail-command requested
{:type :application.command/decide
:actor "deity"
:decision :foobar
:comment ""}
injections)))))))
(deftest test-add-member
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/member-added
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:userid "somebody"}}])
injections {:valid-user? #{"member1" "member2" "somebody" applicant-user-id}}]
(testing "handler can add members"
(is (= {:event/type :application.event/member-added
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/member {:userid "member1"}}
(ok-command application
{:type :application.command/add-member
:actor handler-user-id
:member {:userid "member1"}}
injections))))
(testing "only handler can add members"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/add-member
:actor applicant-user-id
:member {:userid "member1"}}
injections)
(fail-command application
{:type :application.command/add-member
:actor "member1"
:member {:userid "member2"}}
injections))))
(testing "only valid users can be added"
(is (= {:errors [{:type :t.form.validation/invalid-user :userid "member3"}]}
(fail-command application
{:type :application.command/add-member
:actor handler-user-id
:member {:userid "member3"}}
injections))))
(testing "added members can see the application"
(is (-> (apply-commands application
[{:type :application.command/add-member
:actor handler-user-id
:member {:userid "member1"}}]
injections)
(model/see-application? "member1"))))))
(deftest test-invite-member
(let [application (apply-events nil [dummy-created-event])
injections {:valid-user? #{"somebody" applicant-user-id}
:secure-token (constantly "PI:PASSWORD:<PASSWORD>END_PI")}]
(testing "applicant can invite members"
(is (= {:event/type :application.event/member-invited
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"}
:invitation/token "PI:PASSWORD:<PASSWORD>END_PI"}
(ok-command application
{:type :application.command/invite-member
:actor applicant-user-id
:member {:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"}}
injections))))
(testing "handler can invite members"
(let [application (apply-events application [{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(is (= {:event/type :application.event/member-invited
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/member {:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"}
:invitation/token "PI:PASSWORD:<PASSWORD>END_PI"}
(ok-command application
{:type :application.command/invite-member
:actor handler-user-id
:member {:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"}}
injections)))))
(testing "other users cannot invite members"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/invite-member
:actor "member1"
:member {:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"}}
injections))))
(let [submitted (apply-events application
[{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(testing "applicant can't invite members to submitted application"
(is (= {:errors [{:type :forbidden}]}
(fail-command submitted
{:type :application.command/invite-member
:actor applicant-user-id
:member {:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"}}
injections))))
(testing "handler can invite members to submitted application"
(is (ok-command submitted
{:type :application.command/invite-member
:actor handler-user-id
:member {:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"}}
injections))))))
(deftest test-accept-invitation
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/member-invited
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}
:invitation/token "very-secure"}])
injections {:valid-user? #{"somebody" "somebody2" applicant-user-id}}]
(testing "invited member can join draft"
(is (= {:event/type :application.event/member-joined
:event/time test-time
:event/actor "somebody"
:application/id app-id
:invitation/token "very-secure"}
(ok-command application
{:type :application.command/accept-invitation
:actor "somebody"
:token "very-PI:PASSWORD:<PASSWORD>END_PI"}
injections))))
(testing "invited member can't join if they are already a member"
(let [application (apply-events application
[{:event/type :application.event/member-added
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:userid "somebody"}}])]
(is (= {:errors [{:type :t.actions.errors/already-member :userid "somebody" :application-id app-id}]}
(fail-command application
{:type :application.command/accept-invitation
:actor "somebody"
:token "very-secure"}
injections)))))
(testing "invalid token can't be used to join"
(is (= {:errors [{:type :t.actions.errors/invalid-token :token "wrongPI:PASSWORD:<PASSWORD>END_PI-token"}]}
(fail-command application
{:type :application.command/accept-invitation
:actor "somebody"
:token "wrong-PI:PASSWORD:<PASSWORD>END_PI"}
injections))))
(testing "token can't be used twice"
(let [application (apply-events application
[{:event/type :application.event/member-joined
:event/time test-time
:event/actor "somebody"
:application/id app-id
:invitation/token "PI:PASSWORD:<PASSWORD>END_PI"}])]
(is (= {:errors [{:type :t.actions.errors/invalid-token :token "PI:PASSWORD:<PASSWORD>END_PI"}]}
(fail-command application
{:type :application.command/accept-invitation
:actor "somebody2"
:token "PI:PASSWORD:<PASSWORD>END_PI"}
injections)))))
(let [submitted (apply-events application
[{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(testing "invited member can join submitted application"
(is (= {:event/type :application.event/member-joined
:event/actor "somebody"
:event/time test-time
:application/id app-id
:invitation/token "very-PI:PASSWORD:<PASSWORD>END_PI"}
(ok-command application
{:type :application.command/accept-invitation
:actor "somebody"
:token "PI:PASSWORD:<PASSWORD>END_PI"}
injections))))
(let [closed (apply-events submitted
[{:event/type :application.event/closed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/comment ""}])]
(testing "invited member can't join a closed application"
(is (= {:errors [{:type :forbidden}]}
(fail-command closed
{:type :application.command/accept-invitation
:actor "somebody"
:token "PI:PASSWORD:<PASSWORD>END_PI"}
injections))))))))
(deftest test-remove-member
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
{:event/type :application.event/member-added
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/member {:userid "somebody"}}])
injections {:valid-user? #{"somebody" applicant-user-id handler-user-id}}]
(testing "applicant can remove members"
(is (= {:event/type :application.event/member-removed
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:userid "somebody"}
:application/comment "some comment"}
(ok-command application
{:type :application.command/remove-member
:actor applicant-user-id
:member {:userid "somebody"}
:comment "some comment"}
injections))))
(testing "handler can remove members"
(is (= {:event/type :application.event/member-removed
:event/time test-time
:event/actor handler-user-id
:application/id app-id
;; NB no comment
:application/member {:userid "somebody"}}
(ok-command application
{:type :application.command/remove-member
:actor handler-user-id
:member {:userid "somebody"}}
injections))))
(testing "applicant cannot be removed"
(is (= {:errors [{:type :cannot-remove-applicant}]}
(fail-command application
{:type :application.command/remove-member
:actor applicant-user-id
:member {:userid applicant-user-id}}
injections)
(fail-command application
{:type :application.command/remove-member
:actor handler-user-id
:member {:userid applicant-user-id}}
injections))))
(testing "non-members cannot be removed"
(is (= {:errors [{:type :user-not-member :user {:userid "notamember"}}]}
(fail-command application
{:type :application.command/remove-member
:actor handler-user-id
:member {:userid "notamember"}}
injections))))
(testing "removed members cannot see the application"
(is (-> application
(model/see-application? "somebody")))
(is (not (-> application
(apply-commands [{:type :application.command/remove-member
:actor applicant-user-id
:member {:userid "somebody"}}]
injections)
(model/see-application? "somebody")))))))
(deftest test-uninvite-member
(let [application (apply-events nil
[dummy-created-event
{:event/type :application.event/member-invited
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}
:invitation/token "PI:PASSWORD:<PASSWORD>END_PI"}
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
injections {}]
(testing "uninvite member by applicant"
(is (= {:event/type :application.event/member-uninvited
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/member {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}}
(ok-command application
{:type :application.command/uninvite-member
:actor applicant-user-id
:member {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}}
injections))))
(testing "uninvite member by handler"
(is (= {:event/type :application.event/member-uninvited
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/member {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}
:application/comment ""}
(ok-command application
{:type :application.command/uninvite-member
:actor handler-user-id
:member {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}
:comment ""}
injections))))
(testing "only invited members can be uninvited"
(is (= {:errors [{:type :user-not-member :user {:name "PI:NAME:<NAME>END_PI Member" :email "PI:EMAIL:<EMAIL>END_PI"}}]}
(fail-command application
{:type :application.command/uninvite-member
:actor handler-user-id
:member {:name "PI:NAME:<NAME>END_PI Member" :email "PI:EMAIL:<EMAIL>END_PI"}
:comment ""}
injections))))))
(deftest test-review
(let [reviewer "reviewer"
reviewer2 "reviewer2"
reviewer3 "reviewer3"
application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
injections {:valid-user? #{reviewer reviewer2 reviewer3}}]
(testing "required :valid-user? injection"
(is (= {:errors [{:type :missing-injection :injection :valid-user?}]}
(fail-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers [reviewer]
:comment ""}
{}))))
(testing "reviewers must not be empty"
(is (= {:errors [{:type :must-not-be-empty :key :reviewers}]}
(fail-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers []
:comment ""}
{}))))
(testing "reviewers must be a valid users"
(is (= {:errors [{:type :t.form.validation/invalid-user :userid "invaliduser"}
{:type :t.form.validation/invalid-user :userid "invaliduser2"}]}
(fail-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers ["invaliduser" reviewer "invaliduser2"]
:comment ""}
injections))))
(testing "reviewing before ::request-review should fail"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/review
:actor reviewer
:comment ""}
injections))))
(let [event-1 (ok-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers [reviewer reviewer2]
:comment ""}
injections)
request-id-1 (:application/request-id event-1)
application (apply-events application [event-1])
;; Make a new request that should partly override previous
event-2 (ok-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers [reviewer]
:comment ""}
injections)
request-id-2 (:application/request-id event-2)
application (apply-events application [event-2])]
(testing "review requested successfully"
(is (instance? UUID request-id-1))
(is (= {:event/type :application.event/review-requested
:application/request-id request-id-1
:application/reviewers [reviewer reviewer2]
:application/comment ""
:event/time test-time
:event/actor handler-user-id
:application/id app-id}
event-1))
(is (instance? UUID request-id-2))
(is (= {:event/type :application.event/review-requested
:application/request-id request-id-2
:application/reviewers [reviewer]
:application/comment ""
:event/time test-time
:event/actor handler-user-id
:application/id app-id}
event-2)))
(testing "only the requested reviewer can review"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/review
:actor reviewer3
:comment "..."}
injections))))
(testing "reviews are linked to different requests"
(is (= request-id-2
(:application/request-id
(ok-command application
{:type :application.command/review
:actor reviewer
:comment "..."}
injections))))
(is (= request-id-1
(:application/request-id
(ok-command application
{:type :application.command/review
:actor reviewer2
:comment "..."}
injections)))))
(let [event (ok-command application
{:type :application.command/review
:actor reviewer
:comment "..."}
injections)
application (apply-events application [event])]
(testing "reviewed succesfully"
(is (= {:event/type :application.event/reviewed
:event/time test-time
:event/actor reviewer
:application/id app-id
:application/request-id request-id-2
:application/comment "..."}
event)))
(testing "cannot review twice"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/review
:actor reviewer
:comment "..."}
injections))))
(testing "other reviewer can still review"
(is (= {:event/type :application.event/reviewed
:event/time test-time
:event/actor reviewer2
:application/id app-id
:application/request-id request-id-1
:application/comment "..."}
(ok-command application
{:type :application.command/review
:actor reviewer2
:comment "..."}
injections))))))))
(deftest test-remark
(let [reviewer "reviewer"
application (apply-events nil
[dummy-created-event
{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])
valid-attachment-id 1234
wrong-application-attachment-id 1235
wrong-user-attachment-id 1236
unknown-attachment-id 1237
injections {:valid-user? #{reviewer}
:get-attachment-metadata
{valid-attachment-id {:application/id (:application/id application)
:attachment/id valid-attachment-id
:attachment/user handler-user-id}
wrong-application-attachment-id {:application/id (inc (:application/id application))
:attachment/id wrong-application-attachment-id
:attachment/user handler-user-id}
wrong-user-attachment-id {:application/id (:application/id application)
:attachment/id wrong-user-attachment-id
:attachment/user "carl"}}}]
(testing "handler can remark"
(let [event (ok-command application
{:type :application.command/remark
:actor handler-user-id
:comment "handler's remark"
:attachments [{:attachment/id valid-attachment-id}]
:public false}
injections)
application (apply-events application [event])]
(is (= {:event/type :application.event/remarked
:event/time test-time
:event/actor handler-user-id
:application/id app-id
:application/comment "handler's remark"
:application/public false
:event/attachments [{:attachment/id valid-attachment-id}]}
event))))
(testing "invalid attachments"
(is (= {:errors [{:type :invalid-attachments
:attachments [wrong-application-attachment-id wrong-user-attachment-id unknown-attachment-id]}]}
(fail-command application
{:type :application.command/remark
:actor handler-user-id
:comment "handler's remark"
:attachments [{:attachment/id valid-attachment-id}
{:attachment/id wrong-application-attachment-id}
{:attachment/id wrong-user-attachment-id}
{:attachment/id unknown-attachment-id}]
:public false}
injections))))
(testing "applicants cannot remark"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/remark
:actor applicant-user-id
:comment ""
:public false}
injections))))
(testing "reviewer cannot remark before becoming reviewer"
(is (= {:errors [{:type :forbidden}]}
(fail-command application
{:type :application.command/remark
:actor reviewer
:comment ""
:public false}
injections))))
(let [event-1 (ok-command application
{:type :application.command/request-review
:actor handler-user-id
:reviewers [reviewer]
:comment ""}
injections)
application (apply-events application [event-1])
event-2 (ok-command application
{:type :application.command/remark
:actor reviewer
:comment "first remark"
:public false}
injections)
application (apply-events application [event-2])]
(testing "reviewer can remark before"
(is (= {:event/type :application.event/remarked
:event/time test-time
:event/actor reviewer
:application/id app-id
:application/comment "first remark"
:application/public false}
event-2))
(let [event-1 (ok-command application
{:type :application.command/review
:actor reviewer
:comment "..."}
injections)
application (apply-events application [event-1])
event-2 (ok-command application
{:type :application.command/remark
:actor reviewer
:comment "second remark"
:public false}
injections)
application (apply-events application [event-2])]
(testing "and after reviewing"
(is (= {:event/type :application.event/remarked
:event/time test-time
:event/actor reviewer
:application/id app-id
:application/comment "second remark"
:application/public false}
event-2))))))))
(deftest test-copy-as-new
(let [created-event {:event/type :application.event/created
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/external-id "2018/55"
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}
{:catalogue-item/id 2
:resource/ext-id "res2"}]
:application/licenses []
:application/forms [{:form/id 3}]
:workflow/id 1
:workflow/type :workflow/default}
application (apply-events nil [created-event
{:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/field-values [{:form 3 :field "text" :value "1"}
{:form 3 :field "attachment" :value "2"}]}])]
(testing "creates a new application with the same form answers"
(is (= [{:event/type :application.event/created
:event/time test-time
:event/actor applicant-user-id
:application/id new-app-id
:application/external-id new-external-id
:application/resources [{:catalogue-item/id 1
:resource/ext-id "res1"}
{:catalogue-item/id 2
:resource/ext-id "res2"}]
:application/licenses [{:license/id 1} {:license/id 2}]
:application/forms [{:form/id 1}]
:workflow/id 1
:workflow/type :workflow/default}
{:event/type :application.event/draft-saved
:event/time test-time
:event/actor applicant-user-id
:application/id new-app-id
:application/field-values [{:form 3 :field "text" :value "1"}
{:form 3 :field "attachment" :value "102"}]}
{:event/type :application.event/copied-from
:event/time test-time
:event/actor applicant-user-id
:application/id new-app-id
:application/copied-from {:application/id app-id
:application/external-id "2018/55"}}
{:event/type :application.event/copied-to
:event/time test-time
:event/actor applicant-user-id
:application/id app-id
:application/copied-to {:application/id new-app-id
:application/external-id new-external-id}}]
(ok-command application
{:type :application.command/copy-as-new
:actor applicant-user-id}
injections))))))
(deftest test-delete
(let [draft-application (apply-events nil [dummy-created-event])
submitted-application (apply-events draft-application [{:event/type :application.event/submitted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}])]
(testing "forbidden"
(is (= {:errors [{:type :forbidden}]} (fail-command draft-application
{:type :application.command/delete
:actor handler-user-id}
injections)))
(is (= {:errors [{:type :forbidden}]} (fail-command submitted-application
{:type :application.command/delete
:actor applicant-user-id}
injections))))
(testing "success"
(is (= {:event/type :application.event/deleted
:event/time test-time
:event/actor applicant-user-id
:application/id app-id}
(ok-command draft-application
{:type :application.command/delete
:actor applicant-user-id}
injections))))))
(deftest test-handle-command
(let [application (model/application-view nil {:event/type :application.event/created
:event/actor "applicant"
:workflow/type :workflow/default})
command {:application-id 123 :time (DateTime. 1000)
:type :application.command/save-draft
:field-values []
:actor "applicant"}]
(testing "executes command when user is authorized"
(is (not (:errors (commands/handle-command command application {})))))
(testing "fails when command fails validation"
(is (thrown-with-msg? ExceptionInfo #"Value does not match schema"
(commands/handle-command (assoc command :time 3) application {}))))
(testing "fails when user is not authorized"
;; the permission checks should happen before executing the command handler
;; and only depend on the roles and permissions
(let [application (permissions/remove-role-from-user application :applicant "applicant")
result (commands/handle-command command application {})]
(is (= {:errors [{:type :forbidden}]} result))))))
|
[
{
"context": ";; Copyright (c) 2015-2018 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redi",
"end": 40,
"score": 0.9998840093612671,
"start": 27,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": ";; Copyright (c) 2015-2018 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redistribution and",
"end": 54,
"score": 0.9999321699142456,
"start": 42,
"tag": "EMAIL",
"value": "niwi@niwi.nz"
}
] | src/octet/util.cljc | digital-dj-tools/octet | 88 | ;; Copyright (c) 2015-2018 Andrey Antukh <niwi@niwi.nz>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice, this
;; list of conditions and the following disclaimer.
;;
;; * Redistributions in binary form must reproduce the above copyright notice,
;; this list of conditions and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns octet.util
(:require [clojure.string :as str :refer [join]]
[octet.buffer :as bfr])
#?(:clj (:import java.util.Arrays)))
(defmacro defalias
[sym sym2]
`(do
(def ~sym ~sym2)
(alter-meta! (var ~sym) merge (dissoc (meta (var ~sym2)) :name))))
(defn assoc-ordered [a-map key val & rest]
"assoc into an array-map, keeping insertion order. The normal clojure
assoc function switches to hash maps on maps > size 10 and loses insertion order"
(let [kvs (interleave (concat (keys a-map) (list key))
(concat (vals a-map) (list val)))
ret (apply array-map kvs)]
(if rest
(if (next rest)
(recur ret (first rest) (second rest) (nnext rest))
(throw (ex-info "assoc-ordered expects even number of arguments after map/vector, found odd number" {})))
ret)))
;; --- Hexdumps
#?(:clj
(defn bytes->hex
"converts a byte array to a hex string"
[^bytes bytes]
(let [[f & r] bytes
fh (fn [_ b]
(let [h (Integer/toHexString (bit-and b 0xFF))]
(if (<= 0 b 15) (str "0" h) h)))]
(join (reductions fh (fh 0 f) r)))))
#?(:clj
(defn byte->ascii
"convert a byte to 'printable' ascii where possible, otherwise ."
[byte]
(if (<= 32 (bit-and byte 0xFF) 127) (char byte) \.)))
#?(:clj
(defn- bytes->ascii [^bytes bytes]
"returns a 16-per-line printable ascii view of the bytes"
(->> bytes
(map byte->ascii)
(partition 16 16 " ")
(map join))))
#?(:clj
(defn- format-hex-line [^String hex-line]
"formats a 'line' (32 hex chars) of hex output"
(->> hex-line
(partition-all 4)
(map join)
(split-at 4)
(map #(join " " %))
(join " "))))
#?(:clj
(defn- bytes->hexdump [^bytes bytes]
"formats a byte array to a sequence of formatted hex lines"
(->> bytes
bytes->hex
(partition 32 32 (join (repeat 32 " ")))
(map format-hex-line))))
#?(:clj
(defn- copy-bytes [bytes offset size]
"utility function - copy bytes, return new byte array"
(let [size (if (nil? size) (alength bytes) size)]
(if (and (= 0 offset) (= (alength bytes) size))
bytes ; short circuit
(java.util.Arrays/copyOfRange bytes
offset
(+ offset size))))))
#?(:clj
(defn get-dump-bytes
"utility function - return byte array from offset offset and with
size size for nio ByteBuffer, netty ByteBuf, byte array, and String"
[x offset size]
(cond
(and (satisfies? octet.buffer/IBufferBytes x)
(satisfies? octet.buffer/IBufferLimit x))
(let [size (if (nil? size) (octet.buffer/get-capacity x) size)]
(octet.buffer/read-bytes x offset size))
(instance? (type (byte-array 0)) x)
(copy-bytes x offset size)
(instance? String x)
(copy-bytes (.getBytes x) offset size))))
; Example usage of hex-dump
;
;(hex-dump (byte-array (range 200)))
; --------------------------------------------------------------------
;|00000000: 0001 0203 0405 0607 0809 0a0b 0c0d 0e0f ................|
;|00000010: 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f ................|
;|00000020: 2021 2223 2425 2627 2829 2a2b 2c2d 2e2f !"#$%&'()*+,-./|
;|00000030: 3031 3233 3435 3637 3839 3a3b 3c3d 3e3f 0123456789:;<=>?|
;|00000040: 4041 4243 4445 4647 4849 4a4b 4c4d 4e4f @ABCDEFGHIJKLMNO|
;|00000050: 5051 5253 5455 5657 5859 5a5b 5c5d 5e5f PQRSTUVWXYZ[\]^_|
;|00000060: 6061 6263 6465 6667 6869 6a6b 6c6d 6e6f `abcdefghijklmno|
;|00000070: 7071 7273 7475 7677 7879 7a7b 7c7d 7e7f pqrstuvwxyz{|}~|
;|00000080: 8081 8283 8485 8687 8889 8a8b 8c8d 8e8f ................|
;|00000090: 9091 9293 9495 9697 9899 9a9b 9c9d 9e9f ................|
;|000000a0: a0a1 a2a3 a4a5 a6a7 a8a9 aaab acad aeaf ................|
;|000000b0: b0b1 b2b3 b4b5 b6b7 b8b9 babb bcbd bebf ................|
;|000000c0: c0c1 c2c3 c4c5 c6c7 ........ |
; --------------------------------------------------------------------
#?(:clj
(defn hex-dump
"Create hex dump. Accepts byte array, java.nio.ByteBuffer,
io.netty.buffer.ByteBuf, or String as first argument. Offset will
start the dump from an offset in the byte array, size will limit
the number of bytes dumped, and frames will print a frame around
the dump if true. Set print to true to print the dump on stdout
(default) or false to return it as a string. Example call:
(hex-dump (byte-array (range 200)) :print false)"
[x & {:keys [offset size print frame]
:or {offset 0
print true
frame true}}]
{:pre [(not (nil? x))]}
(let [bytes (get-dump-bytes x offset size)
size (if (nil? size) (alength bytes) size)
dump (bytes->hexdump bytes)
ascii (bytes->ascii bytes)
offs (map #(format "%08x" %)
(range offset (+ offset size 16) 16))
header (str " " (join (repeat 68 "-")))
border (if frame "|" "")
lines (map #(str border %1 ": " %2 " " %3 border) offs dump ascii)
lines (if frame (concat [header] lines [header]) lines)
result (join \newline lines)]
(if print (println result) result))))
| 7003 | ;; Copyright (c) 2015-2018 <NAME> <<EMAIL>>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice, this
;; list of conditions and the following disclaimer.
;;
;; * Redistributions in binary form must reproduce the above copyright notice,
;; this list of conditions and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns octet.util
(:require [clojure.string :as str :refer [join]]
[octet.buffer :as bfr])
#?(:clj (:import java.util.Arrays)))
(defmacro defalias
[sym sym2]
`(do
(def ~sym ~sym2)
(alter-meta! (var ~sym) merge (dissoc (meta (var ~sym2)) :name))))
(defn assoc-ordered [a-map key val & rest]
"assoc into an array-map, keeping insertion order. The normal clojure
assoc function switches to hash maps on maps > size 10 and loses insertion order"
(let [kvs (interleave (concat (keys a-map) (list key))
(concat (vals a-map) (list val)))
ret (apply array-map kvs)]
(if rest
(if (next rest)
(recur ret (first rest) (second rest) (nnext rest))
(throw (ex-info "assoc-ordered expects even number of arguments after map/vector, found odd number" {})))
ret)))
;; --- Hexdumps
#?(:clj
(defn bytes->hex
"converts a byte array to a hex string"
[^bytes bytes]
(let [[f & r] bytes
fh (fn [_ b]
(let [h (Integer/toHexString (bit-and b 0xFF))]
(if (<= 0 b 15) (str "0" h) h)))]
(join (reductions fh (fh 0 f) r)))))
#?(:clj
(defn byte->ascii
"convert a byte to 'printable' ascii where possible, otherwise ."
[byte]
(if (<= 32 (bit-and byte 0xFF) 127) (char byte) \.)))
#?(:clj
(defn- bytes->ascii [^bytes bytes]
"returns a 16-per-line printable ascii view of the bytes"
(->> bytes
(map byte->ascii)
(partition 16 16 " ")
(map join))))
#?(:clj
(defn- format-hex-line [^String hex-line]
"formats a 'line' (32 hex chars) of hex output"
(->> hex-line
(partition-all 4)
(map join)
(split-at 4)
(map #(join " " %))
(join " "))))
#?(:clj
(defn- bytes->hexdump [^bytes bytes]
"formats a byte array to a sequence of formatted hex lines"
(->> bytes
bytes->hex
(partition 32 32 (join (repeat 32 " ")))
(map format-hex-line))))
#?(:clj
(defn- copy-bytes [bytes offset size]
"utility function - copy bytes, return new byte array"
(let [size (if (nil? size) (alength bytes) size)]
(if (and (= 0 offset) (= (alength bytes) size))
bytes ; short circuit
(java.util.Arrays/copyOfRange bytes
offset
(+ offset size))))))
#?(:clj
(defn get-dump-bytes
"utility function - return byte array from offset offset and with
size size for nio ByteBuffer, netty ByteBuf, byte array, and String"
[x offset size]
(cond
(and (satisfies? octet.buffer/IBufferBytes x)
(satisfies? octet.buffer/IBufferLimit x))
(let [size (if (nil? size) (octet.buffer/get-capacity x) size)]
(octet.buffer/read-bytes x offset size))
(instance? (type (byte-array 0)) x)
(copy-bytes x offset size)
(instance? String x)
(copy-bytes (.getBytes x) offset size))))
; Example usage of hex-dump
;
;(hex-dump (byte-array (range 200)))
; --------------------------------------------------------------------
;|00000000: 0001 0203 0405 0607 0809 0a0b 0c0d 0e0f ................|
;|00000010: 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f ................|
;|00000020: 2021 2223 2425 2627 2829 2a2b 2c2d 2e2f !"#$%&'()*+,-./|
;|00000030: 3031 3233 3435 3637 3839 3a3b 3c3d 3e3f 0123456789:;<=>?|
;|00000040: 4041 4243 4445 4647 4849 4a4b 4c4d 4e4f @ABCDEFGHIJKLMNO|
;|00000050: 5051 5253 5455 5657 5859 5a5b 5c5d 5e5f PQRSTUVWXYZ[\]^_|
;|00000060: 6061 6263 6465 6667 6869 6a6b 6c6d 6e6f `abcdefghijklmno|
;|00000070: 7071 7273 7475 7677 7879 7a7b 7c7d 7e7f pqrstuvwxyz{|}~|
;|00000080: 8081 8283 8485 8687 8889 8a8b 8c8d 8e8f ................|
;|00000090: 9091 9293 9495 9697 9899 9a9b 9c9d 9e9f ................|
;|000000a0: a0a1 a2a3 a4a5 a6a7 a8a9 aaab acad aeaf ................|
;|000000b0: b0b1 b2b3 b4b5 b6b7 b8b9 babb bcbd bebf ................|
;|000000c0: c0c1 c2c3 c4c5 c6c7 ........ |
; --------------------------------------------------------------------
#?(:clj
(defn hex-dump
"Create hex dump. Accepts byte array, java.nio.ByteBuffer,
io.netty.buffer.ByteBuf, or String as first argument. Offset will
start the dump from an offset in the byte array, size will limit
the number of bytes dumped, and frames will print a frame around
the dump if true. Set print to true to print the dump on stdout
(default) or false to return it as a string. Example call:
(hex-dump (byte-array (range 200)) :print false)"
[x & {:keys [offset size print frame]
:or {offset 0
print true
frame true}}]
{:pre [(not (nil? x))]}
(let [bytes (get-dump-bytes x offset size)
size (if (nil? size) (alength bytes) size)
dump (bytes->hexdump bytes)
ascii (bytes->ascii bytes)
offs (map #(format "%08x" %)
(range offset (+ offset size 16) 16))
header (str " " (join (repeat 68 "-")))
border (if frame "|" "")
lines (map #(str border %1 ": " %2 " " %3 border) offs dump ascii)
lines (if frame (concat [header] lines [header]) lines)
result (join \newline lines)]
(if print (println result) result))))
| true | ;; Copyright (c) 2015-2018 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice, this
;; list of conditions and the following disclaimer.
;;
;; * Redistributions in binary form must reproduce the above copyright notice,
;; this list of conditions and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns octet.util
(:require [clojure.string :as str :refer [join]]
[octet.buffer :as bfr])
#?(:clj (:import java.util.Arrays)))
(defmacro defalias
[sym sym2]
`(do
(def ~sym ~sym2)
(alter-meta! (var ~sym) merge (dissoc (meta (var ~sym2)) :name))))
(defn assoc-ordered [a-map key val & rest]
"assoc into an array-map, keeping insertion order. The normal clojure
assoc function switches to hash maps on maps > size 10 and loses insertion order"
(let [kvs (interleave (concat (keys a-map) (list key))
(concat (vals a-map) (list val)))
ret (apply array-map kvs)]
(if rest
(if (next rest)
(recur ret (first rest) (second rest) (nnext rest))
(throw (ex-info "assoc-ordered expects even number of arguments after map/vector, found odd number" {})))
ret)))
;; --- Hexdumps
#?(:clj
(defn bytes->hex
"converts a byte array to a hex string"
[^bytes bytes]
(let [[f & r] bytes
fh (fn [_ b]
(let [h (Integer/toHexString (bit-and b 0xFF))]
(if (<= 0 b 15) (str "0" h) h)))]
(join (reductions fh (fh 0 f) r)))))
#?(:clj
(defn byte->ascii
"convert a byte to 'printable' ascii where possible, otherwise ."
[byte]
(if (<= 32 (bit-and byte 0xFF) 127) (char byte) \.)))
#?(:clj
(defn- bytes->ascii [^bytes bytes]
"returns a 16-per-line printable ascii view of the bytes"
(->> bytes
(map byte->ascii)
(partition 16 16 " ")
(map join))))
#?(:clj
(defn- format-hex-line [^String hex-line]
"formats a 'line' (32 hex chars) of hex output"
(->> hex-line
(partition-all 4)
(map join)
(split-at 4)
(map #(join " " %))
(join " "))))
#?(:clj
(defn- bytes->hexdump [^bytes bytes]
"formats a byte array to a sequence of formatted hex lines"
(->> bytes
bytes->hex
(partition 32 32 (join (repeat 32 " ")))
(map format-hex-line))))
#?(:clj
(defn- copy-bytes [bytes offset size]
"utility function - copy bytes, return new byte array"
(let [size (if (nil? size) (alength bytes) size)]
(if (and (= 0 offset) (= (alength bytes) size))
bytes ; short circuit
(java.util.Arrays/copyOfRange bytes
offset
(+ offset size))))))
#?(:clj
(defn get-dump-bytes
"utility function - return byte array from offset offset and with
size size for nio ByteBuffer, netty ByteBuf, byte array, and String"
[x offset size]
(cond
(and (satisfies? octet.buffer/IBufferBytes x)
(satisfies? octet.buffer/IBufferLimit x))
(let [size (if (nil? size) (octet.buffer/get-capacity x) size)]
(octet.buffer/read-bytes x offset size))
(instance? (type (byte-array 0)) x)
(copy-bytes x offset size)
(instance? String x)
(copy-bytes (.getBytes x) offset size))))
; Example usage of hex-dump
;
;(hex-dump (byte-array (range 200)))
; --------------------------------------------------------------------
;|00000000: 0001 0203 0405 0607 0809 0a0b 0c0d 0e0f ................|
;|00000010: 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f ................|
;|00000020: 2021 2223 2425 2627 2829 2a2b 2c2d 2e2f !"#$%&'()*+,-./|
;|00000030: 3031 3233 3435 3637 3839 3a3b 3c3d 3e3f 0123456789:;<=>?|
;|00000040: 4041 4243 4445 4647 4849 4a4b 4c4d 4e4f @ABCDEFGHIJKLMNO|
;|00000050: 5051 5253 5455 5657 5859 5a5b 5c5d 5e5f PQRSTUVWXYZ[\]^_|
;|00000060: 6061 6263 6465 6667 6869 6a6b 6c6d 6e6f `abcdefghijklmno|
;|00000070: 7071 7273 7475 7677 7879 7a7b 7c7d 7e7f pqrstuvwxyz{|}~|
;|00000080: 8081 8283 8485 8687 8889 8a8b 8c8d 8e8f ................|
;|00000090: 9091 9293 9495 9697 9899 9a9b 9c9d 9e9f ................|
;|000000a0: a0a1 a2a3 a4a5 a6a7 a8a9 aaab acad aeaf ................|
;|000000b0: b0b1 b2b3 b4b5 b6b7 b8b9 babb bcbd bebf ................|
;|000000c0: c0c1 c2c3 c4c5 c6c7 ........ |
; --------------------------------------------------------------------
#?(:clj
(defn hex-dump
"Create hex dump. Accepts byte array, java.nio.ByteBuffer,
io.netty.buffer.ByteBuf, or String as first argument. Offset will
start the dump from an offset in the byte array, size will limit
the number of bytes dumped, and frames will print a frame around
the dump if true. Set print to true to print the dump on stdout
(default) or false to return it as a string. Example call:
(hex-dump (byte-array (range 200)) :print false)"
[x & {:keys [offset size print frame]
:or {offset 0
print true
frame true}}]
{:pre [(not (nil? x))]}
(let [bytes (get-dump-bytes x offset size)
size (if (nil? size) (alength bytes) size)
dump (bytes->hexdump bytes)
ascii (bytes->ascii bytes)
offs (map #(format "%08x" %)
(range offset (+ offset size 16) 16))
header (str " " (join (repeat 68 "-")))
border (if frame "|" "")
lines (map #(str border %1 ": " %2 " " %3 border) offs dump ascii)
lines (if frame (concat [header] lines [header]) lines)
result (join \newline lines)]
(if print (println result) result))))
|
[
{
"context": "; Copyright (c) 2010-2021 Haifeng Li. All rights reserved.\n;\n; Smile is free softwar",
"end": 38,
"score": 0.9998396635055542,
"start": 28,
"tag": "NAME",
"value": "Haifeng Li"
},
{
"context": "onflicts with smile.classifictation.\"\n {:author \"Haifeng Li\"}\n (:require [smile.io :refer :all]\n ",
"end": 912,
"score": 0.9998552799224854,
"start": 902,
"tag": "NAME",
"value": "Haifeng Li"
}
] | clojure/src/smile/ai.clj | takanori-ugai/smile | 0 | ; Copyright (c) 2010-2021 Haifeng Li. All rights reserved.
;
; Smile is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; Smile is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with Smile. If not, see <https://www.gnu.org/licenses/>.
(ns smile.ai
"Main namespace for REPL, referring to all public vars of
other namespaces except that smile.regression :as regression
to avoid name conflicts with smile.classifictation."
{:author "Haifeng Li"}
(:require [smile.io :refer :all]
[smile.classification :refer :all]
[smile.regression :as regression]
[smile.clustering :refer :all]
[smile.manifold :refer :all]))
| 87195 | ; Copyright (c) 2010-2021 <NAME>. All rights reserved.
;
; Smile is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; Smile is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with Smile. If not, see <https://www.gnu.org/licenses/>.
(ns smile.ai
"Main namespace for REPL, referring to all public vars of
other namespaces except that smile.regression :as regression
to avoid name conflicts with smile.classifictation."
{:author "<NAME>"}
(:require [smile.io :refer :all]
[smile.classification :refer :all]
[smile.regression :as regression]
[smile.clustering :refer :all]
[smile.manifold :refer :all]))
| true | ; Copyright (c) 2010-2021 PI:NAME:<NAME>END_PI. All rights reserved.
;
; Smile is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; Smile is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with Smile. If not, see <https://www.gnu.org/licenses/>.
(ns smile.ai
"Main namespace for REPL, referring to all public vars of
other namespaces except that smile.regression :as regression
to avoid name conflicts with smile.classifictation."
{:author "PI:NAME:<NAME>END_PI"}
(:require [smile.io :refer :all]
[smile.classification :refer :all]
[smile.regression :as regression]
[smile.clustering :refer :all]
[smile.manifold :refer :all]))
|
[
{
"context": ";\n; Copyright 2019 Peter Monks\n;\n; Licensed under the Apache License, Version 2.",
"end": 30,
"score": 0.9996774792671204,
"start": 19,
"tag": "NAME",
"value": "Peter Monks"
},
{
"context": "aders (merge {\"User-Agent\" \"com.github.pmonks/clojars-dependencies\"}\n ",
"end": 3966,
"score": 0.6577998399734497,
"start": 3961,
"tag": "USERNAME",
"value": "monks"
},
{
"context": "upport for rsync in 2019 - see https://github.com/clojars/clojars-web/issues/735\n(comment\n(defn rsync\n [& ",
"end": 5185,
"score": 0.9996011257171631,
"start": 5178,
"tag": "USERNAME",
"value": "clojars"
}
] | src/clojars_dependencies/core.clj | pmonks/clojars-dependencies | 0 | ;
; Copyright 2019 Peter Monks
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; SPDX-License-Identifier: Apache-2.0
(ns clojars-dependencies.core
(:require [clojure.string :as s]
[clojure.java.io :as io]
[clojure.xml :as xml]
[clojure.zip :as zip]
[clojure.edn :as edn]
[clojure.data.zip.xml :as zip-xml]
[hato.client :as hc]
[version-clj.core :as ver]))
(def clojars-repo "https://repo.clojars.org")
(def all-poms-list "all-poms.txt")
(def metadata-ext ".meta.edn")
(defonce http-client (hc/build-http-client {:connect-timeout 10000
:redirect-policy :always}))
(defn- encode-url-path
"Encodes a URL path (but NOT a query string)."
[url-path]
(-> url-path
(s/replace "%" "%25")
(s/replace " " "%20")
(s/replace "!" "%21")
(s/replace "#" "%23")
(s/replace "$" "%24")
(s/replace "&" "%26")
(s/replace "'" "%27")
(s/replace "(" "%28")
(s/replace ")" "%29")
(s/replace "*" "%2A")
(s/replace "+" "%2B")
(s/replace "," "%2C")
; (s/replace "/" "%2F")
(s/replace ":" "%3A")
(s/replace ";" "%3B")
(s/replace "=" "%3D")
(s/replace "?" "%3F")
(s/replace "@" "%40")
(s/replace "[" "%5B")
(s/replace "]" "%5D")))
(defn- write-file-and-meta!
"Writes the given response to the given file-path, including metadata."
[target file-path {:keys [headers body]}]
(let [filename (str target "/" file-path)
etag (s/trim (get headers "etag" "")) ; Note: for some reason etag values returned by Clojars include quotes...
last-modified (s/trim (get headers "last-modified" ""))]
(io/make-parents filename) ; Ensure parent directories exist
(spit filename body) ; Write content
(spit (str filename metadata-ext) ; Write metadata
(pr-str (merge {}
(when-not (s/blank? etag) {:etag etag})
(when-not (s/blank? last-modified) {:last-modified last-modified})))))
nil)
(defn- try-n-times
"Try f up to n times, with optional sleep in between - adapted from https://ericnormand.me/article/try-three-times"
([f n] (try-n-times f n 0))
([f n sleep-ms]
(if (zero? (dec n))
(f)
(try
(f)
(catch Throwable _
(when (pos? sleep-ms) (Thread/sleep sleep-ms))
(try-n-times f (dec n)))))))
(defmacro ^:private try3sleep1
[& body]
`(try-n-times (fn [] ~@body) 3 1000))
(defn download-file-from-clojars!
"Downloads a single file (identified by file-path) from Clojars, to the specific target directory. Does nothing if the given file hasn't changed (as per ETag / If-None-Match). Returns true if the file was downloaded."
[target file-path]
(let [metadata-file (io/file (str target "/" file-path metadata-ext))
etag (when (.exists metadata-file) (with-open [r (io/reader metadata-file)] (:etag (edn/read (java.io.PushbackReader. r)))))
clojars-url (str clojars-repo "/" (encode-url-path file-path))
response (hc/get clojars-url
{:http-client http-client
:throw-exceptions? false
:headers (merge {"User-Agent" "com.github.pmonks/clojars-dependencies"}
(when etag {"If-None-Match" etag}))})]
(case (:status response)
200 (do (write-file-and-meta! target file-path response) true)
304 false
410 false ; Not sure why, but Clojars returns 410s for some of the POMs it lists in the "All POMs list"...
:else (throw (ex-info (str "Unexpected status returned by Clojars: " (:status response)) response)))))
; Note: doesn't support deletion (though Clojars itself may not allow deletion anyway? 🤔)
(defn sync-clojars-poms!
"Syncs all POMs from Clojars to the target directory. Returns true if there were changes, false if not."
[target]
; First, get the list of all poms
(try3sleep1 (download-file-from-clojars! target all-poms-list))
; Second, spin through the list, downloading all poms
(let [all-poms-file (str target "/" all-poms-list)
all-pom-paths (map #(s/replace-first % "./" "") (with-open [r (io/reader all-poms-file)] (doall (line-seq r))))]
(doall (pmap #(try3sleep1 (download-file-from-clojars! target %)) all-pom-paths))
true)
false)
; Note: clojars dropped support for rsync in 2019 - see https://github.com/clojars/clojars-web/issues/735
(comment
(defn rsync
[& args]
(let [exit-code (-> (ProcessBuilder. ^java.util.List (cons "rsync" args))
(.inheritIO)
(.start)
(.waitFor))]
(when-not (= 0 exit-code)
(throw (Exception. "rsync failed - see stderr for details")))))
(defn rsync-poms
[source target]
(rsync "-zarv" "--prune-empty-dirs" "--delete" "--include=*/" "--include=*.pom" "--exclude=*" source target))
)
(defn cljgav
"Parses a POM XML element containing a Maven GAV, and returns it in Leiningen format: [\"[groupId/]artifactId\" \"versionStr\"]."
[root]
(let [group-id (zip-xml/xml1-> root :groupId zip-xml/text)
artifact-id (zip-xml/xml1-> root :artifactId zip-xml/text)
version (str (zip-xml/xml1-> root :version zip-xml/text))]
(when-not (s/blank? artifact-id)
(when-not (s/blank? group-id)
[(str group-id "/" artifact-id) version]
[artifact-id version]))))
(defn parse-pom-file
"Parses a single POM file (a java.io.File) into the structure: [projectCljGAV [dependencyCljGAVs, ...]] (see cljgav for the format of each CLJGAV)."
[^java.io.File pom-file]
(try
; We do all of this because some of the POMs in Clojars are invalid in ways that are trivial to fix (leading whitespace, BOM, invalid UTF-8 byte sequences)
(let [xml-decoder (doto (.newDecoder java.nio.charset.StandardCharsets/UTF_8)
(.onMalformedInput java.nio.charset.CodingErrorAction/REPLACE)
(.onUnmappableCharacter java.nio.charset.CodingErrorAction/REPLACE))
xml-is (org.owasp.dependencycheck.xml.XmlInputStream. ; Strip leading whitespace, BOM, etc.
(org.apache.commons.io.input.ReaderInputStream. ; Convert reader back to UTF-8 encoded InputStream (*blech*)
(java.io.InputStreamReader. (io/input-stream pom-file) xml-decoder) ; Replace invalid UTF-8 byte sequences into a reader
java.nio.charset.StandardCharsets/UTF_8))
root (zip/xml-zip (xml/parse xml-is))
project-gav (cljgav root)
dependency-gavs (seq (remove nil? (map cljgav (zip-xml/xml-> root :dependencies :dependency))))]
(when project-gav
[project-gav dependency-gavs]))
(catch Exception e
(print (str "⚠️ Unable to parse POM " (.getName pom-file) ": " e "\n"))
(flush))))
(defn parse-pom-files
"Parses all POM files in the given directory, and returns a sequence of parsed POMs (see parse-pom-file for the format of each entry in the sequence)."
[poms-directory]
(let [pom-files (filter #(and (.endsWith (.getName ^java.io.File %) ".pom")
(.canRead ^java.io.File %)
(not (.isDirectory ^java.io.File %)))
(file-seq (io/file poms-directory)))]
(remove nil? (pmap parse-pom-file pom-files))))
(defn latest-project-versions
"Filters out all but the latest version of each project (based on how version-clj compares Maven version strings)."
[parsed-pom-files]
(let [grouped-projects (group-by #(first (first %)) parsed-pom-files)]
(pmap #(last (sort-by (fn [p] (second (first p))) ver/version-compare (second %))) grouped-projects)))
(defn dependencies
"Returns a sequence of dependency pairs, in [fromCljGAV toCljGAV] format."
[latest-project-versions]
(let [version-numbers-elided (pmap #(vec [(first (first %)) (map first (second %))]) latest-project-versions)]
(for [project version-numbers-elided
from [(first project)]
to (second project)]
[from to])))
| 122159 | ;
; Copyright 2019 <NAME>
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; SPDX-License-Identifier: Apache-2.0
(ns clojars-dependencies.core
(:require [clojure.string :as s]
[clojure.java.io :as io]
[clojure.xml :as xml]
[clojure.zip :as zip]
[clojure.edn :as edn]
[clojure.data.zip.xml :as zip-xml]
[hato.client :as hc]
[version-clj.core :as ver]))
(def clojars-repo "https://repo.clojars.org")
(def all-poms-list "all-poms.txt")
(def metadata-ext ".meta.edn")
(defonce http-client (hc/build-http-client {:connect-timeout 10000
:redirect-policy :always}))
(defn- encode-url-path
"Encodes a URL path (but NOT a query string)."
[url-path]
(-> url-path
(s/replace "%" "%25")
(s/replace " " "%20")
(s/replace "!" "%21")
(s/replace "#" "%23")
(s/replace "$" "%24")
(s/replace "&" "%26")
(s/replace "'" "%27")
(s/replace "(" "%28")
(s/replace ")" "%29")
(s/replace "*" "%2A")
(s/replace "+" "%2B")
(s/replace "," "%2C")
; (s/replace "/" "%2F")
(s/replace ":" "%3A")
(s/replace ";" "%3B")
(s/replace "=" "%3D")
(s/replace "?" "%3F")
(s/replace "@" "%40")
(s/replace "[" "%5B")
(s/replace "]" "%5D")))
(defn- write-file-and-meta!
"Writes the given response to the given file-path, including metadata."
[target file-path {:keys [headers body]}]
(let [filename (str target "/" file-path)
etag (s/trim (get headers "etag" "")) ; Note: for some reason etag values returned by Clojars include quotes...
last-modified (s/trim (get headers "last-modified" ""))]
(io/make-parents filename) ; Ensure parent directories exist
(spit filename body) ; Write content
(spit (str filename metadata-ext) ; Write metadata
(pr-str (merge {}
(when-not (s/blank? etag) {:etag etag})
(when-not (s/blank? last-modified) {:last-modified last-modified})))))
nil)
(defn- try-n-times
"Try f up to n times, with optional sleep in between - adapted from https://ericnormand.me/article/try-three-times"
([f n] (try-n-times f n 0))
([f n sleep-ms]
(if (zero? (dec n))
(f)
(try
(f)
(catch Throwable _
(when (pos? sleep-ms) (Thread/sleep sleep-ms))
(try-n-times f (dec n)))))))
(defmacro ^:private try3sleep1
[& body]
`(try-n-times (fn [] ~@body) 3 1000))
(defn download-file-from-clojars!
"Downloads a single file (identified by file-path) from Clojars, to the specific target directory. Does nothing if the given file hasn't changed (as per ETag / If-None-Match). Returns true if the file was downloaded."
[target file-path]
(let [metadata-file (io/file (str target "/" file-path metadata-ext))
etag (when (.exists metadata-file) (with-open [r (io/reader metadata-file)] (:etag (edn/read (java.io.PushbackReader. r)))))
clojars-url (str clojars-repo "/" (encode-url-path file-path))
response (hc/get clojars-url
{:http-client http-client
:throw-exceptions? false
:headers (merge {"User-Agent" "com.github.pmonks/clojars-dependencies"}
(when etag {"If-None-Match" etag}))})]
(case (:status response)
200 (do (write-file-and-meta! target file-path response) true)
304 false
410 false ; Not sure why, but Clojars returns 410s for some of the POMs it lists in the "All POMs list"...
:else (throw (ex-info (str "Unexpected status returned by Clojars: " (:status response)) response)))))
; Note: doesn't support deletion (though Clojars itself may not allow deletion anyway? 🤔)
(defn sync-clojars-poms!
"Syncs all POMs from Clojars to the target directory. Returns true if there were changes, false if not."
[target]
; First, get the list of all poms
(try3sleep1 (download-file-from-clojars! target all-poms-list))
; Second, spin through the list, downloading all poms
(let [all-poms-file (str target "/" all-poms-list)
all-pom-paths (map #(s/replace-first % "./" "") (with-open [r (io/reader all-poms-file)] (doall (line-seq r))))]
(doall (pmap #(try3sleep1 (download-file-from-clojars! target %)) all-pom-paths))
true)
false)
; Note: clojars dropped support for rsync in 2019 - see https://github.com/clojars/clojars-web/issues/735
(comment
(defn rsync
[& args]
(let [exit-code (-> (ProcessBuilder. ^java.util.List (cons "rsync" args))
(.inheritIO)
(.start)
(.waitFor))]
(when-not (= 0 exit-code)
(throw (Exception. "rsync failed - see stderr for details")))))
(defn rsync-poms
[source target]
(rsync "-zarv" "--prune-empty-dirs" "--delete" "--include=*/" "--include=*.pom" "--exclude=*" source target))
)
(defn cljgav
"Parses a POM XML element containing a Maven GAV, and returns it in Leiningen format: [\"[groupId/]artifactId\" \"versionStr\"]."
[root]
(let [group-id (zip-xml/xml1-> root :groupId zip-xml/text)
artifact-id (zip-xml/xml1-> root :artifactId zip-xml/text)
version (str (zip-xml/xml1-> root :version zip-xml/text))]
(when-not (s/blank? artifact-id)
(when-not (s/blank? group-id)
[(str group-id "/" artifact-id) version]
[artifact-id version]))))
(defn parse-pom-file
"Parses a single POM file (a java.io.File) into the structure: [projectCljGAV [dependencyCljGAVs, ...]] (see cljgav for the format of each CLJGAV)."
[^java.io.File pom-file]
(try
; We do all of this because some of the POMs in Clojars are invalid in ways that are trivial to fix (leading whitespace, BOM, invalid UTF-8 byte sequences)
(let [xml-decoder (doto (.newDecoder java.nio.charset.StandardCharsets/UTF_8)
(.onMalformedInput java.nio.charset.CodingErrorAction/REPLACE)
(.onUnmappableCharacter java.nio.charset.CodingErrorAction/REPLACE))
xml-is (org.owasp.dependencycheck.xml.XmlInputStream. ; Strip leading whitespace, BOM, etc.
(org.apache.commons.io.input.ReaderInputStream. ; Convert reader back to UTF-8 encoded InputStream (*blech*)
(java.io.InputStreamReader. (io/input-stream pom-file) xml-decoder) ; Replace invalid UTF-8 byte sequences into a reader
java.nio.charset.StandardCharsets/UTF_8))
root (zip/xml-zip (xml/parse xml-is))
project-gav (cljgav root)
dependency-gavs (seq (remove nil? (map cljgav (zip-xml/xml-> root :dependencies :dependency))))]
(when project-gav
[project-gav dependency-gavs]))
(catch Exception e
(print (str "⚠️ Unable to parse POM " (.getName pom-file) ": " e "\n"))
(flush))))
(defn parse-pom-files
"Parses all POM files in the given directory, and returns a sequence of parsed POMs (see parse-pom-file for the format of each entry in the sequence)."
[poms-directory]
(let [pom-files (filter #(and (.endsWith (.getName ^java.io.File %) ".pom")
(.canRead ^java.io.File %)
(not (.isDirectory ^java.io.File %)))
(file-seq (io/file poms-directory)))]
(remove nil? (pmap parse-pom-file pom-files))))
(defn latest-project-versions
"Filters out all but the latest version of each project (based on how version-clj compares Maven version strings)."
[parsed-pom-files]
(let [grouped-projects (group-by #(first (first %)) parsed-pom-files)]
(pmap #(last (sort-by (fn [p] (second (first p))) ver/version-compare (second %))) grouped-projects)))
(defn dependencies
"Returns a sequence of dependency pairs, in [fromCljGAV toCljGAV] format."
[latest-project-versions]
(let [version-numbers-elided (pmap #(vec [(first (first %)) (map first (second %))]) latest-project-versions)]
(for [project version-numbers-elided
from [(first project)]
to (second project)]
[from to])))
| true | ;
; Copyright 2019 PI:NAME:<NAME>END_PI
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; SPDX-License-Identifier: Apache-2.0
(ns clojars-dependencies.core
(:require [clojure.string :as s]
[clojure.java.io :as io]
[clojure.xml :as xml]
[clojure.zip :as zip]
[clojure.edn :as edn]
[clojure.data.zip.xml :as zip-xml]
[hato.client :as hc]
[version-clj.core :as ver]))
(def clojars-repo "https://repo.clojars.org")
(def all-poms-list "all-poms.txt")
(def metadata-ext ".meta.edn")
(defonce http-client (hc/build-http-client {:connect-timeout 10000
:redirect-policy :always}))
(defn- encode-url-path
"Encodes a URL path (but NOT a query string)."
[url-path]
(-> url-path
(s/replace "%" "%25")
(s/replace " " "%20")
(s/replace "!" "%21")
(s/replace "#" "%23")
(s/replace "$" "%24")
(s/replace "&" "%26")
(s/replace "'" "%27")
(s/replace "(" "%28")
(s/replace ")" "%29")
(s/replace "*" "%2A")
(s/replace "+" "%2B")
(s/replace "," "%2C")
; (s/replace "/" "%2F")
(s/replace ":" "%3A")
(s/replace ";" "%3B")
(s/replace "=" "%3D")
(s/replace "?" "%3F")
(s/replace "@" "%40")
(s/replace "[" "%5B")
(s/replace "]" "%5D")))
(defn- write-file-and-meta!
"Writes the given response to the given file-path, including metadata."
[target file-path {:keys [headers body]}]
(let [filename (str target "/" file-path)
etag (s/trim (get headers "etag" "")) ; Note: for some reason etag values returned by Clojars include quotes...
last-modified (s/trim (get headers "last-modified" ""))]
(io/make-parents filename) ; Ensure parent directories exist
(spit filename body) ; Write content
(spit (str filename metadata-ext) ; Write metadata
(pr-str (merge {}
(when-not (s/blank? etag) {:etag etag})
(when-not (s/blank? last-modified) {:last-modified last-modified})))))
nil)
(defn- try-n-times
"Try f up to n times, with optional sleep in between - adapted from https://ericnormand.me/article/try-three-times"
([f n] (try-n-times f n 0))
([f n sleep-ms]
(if (zero? (dec n))
(f)
(try
(f)
(catch Throwable _
(when (pos? sleep-ms) (Thread/sleep sleep-ms))
(try-n-times f (dec n)))))))
(defmacro ^:private try3sleep1
[& body]
`(try-n-times (fn [] ~@body) 3 1000))
(defn download-file-from-clojars!
"Downloads a single file (identified by file-path) from Clojars, to the specific target directory. Does nothing if the given file hasn't changed (as per ETag / If-None-Match). Returns true if the file was downloaded."
[target file-path]
(let [metadata-file (io/file (str target "/" file-path metadata-ext))
etag (when (.exists metadata-file) (with-open [r (io/reader metadata-file)] (:etag (edn/read (java.io.PushbackReader. r)))))
clojars-url (str clojars-repo "/" (encode-url-path file-path))
response (hc/get clojars-url
{:http-client http-client
:throw-exceptions? false
:headers (merge {"User-Agent" "com.github.pmonks/clojars-dependencies"}
(when etag {"If-None-Match" etag}))})]
(case (:status response)
200 (do (write-file-and-meta! target file-path response) true)
304 false
410 false ; Not sure why, but Clojars returns 410s for some of the POMs it lists in the "All POMs list"...
:else (throw (ex-info (str "Unexpected status returned by Clojars: " (:status response)) response)))))
; Note: doesn't support deletion (though Clojars itself may not allow deletion anyway? 🤔)
(defn sync-clojars-poms!
"Syncs all POMs from Clojars to the target directory. Returns true if there were changes, false if not."
[target]
; First, get the list of all poms
(try3sleep1 (download-file-from-clojars! target all-poms-list))
; Second, spin through the list, downloading all poms
(let [all-poms-file (str target "/" all-poms-list)
all-pom-paths (map #(s/replace-first % "./" "") (with-open [r (io/reader all-poms-file)] (doall (line-seq r))))]
(doall (pmap #(try3sleep1 (download-file-from-clojars! target %)) all-pom-paths))
true)
false)
; Note: clojars dropped support for rsync in 2019 - see https://github.com/clojars/clojars-web/issues/735
(comment
(defn rsync
[& args]
(let [exit-code (-> (ProcessBuilder. ^java.util.List (cons "rsync" args))
(.inheritIO)
(.start)
(.waitFor))]
(when-not (= 0 exit-code)
(throw (Exception. "rsync failed - see stderr for details")))))
(defn rsync-poms
[source target]
(rsync "-zarv" "--prune-empty-dirs" "--delete" "--include=*/" "--include=*.pom" "--exclude=*" source target))
)
(defn cljgav
"Parses a POM XML element containing a Maven GAV, and returns it in Leiningen format: [\"[groupId/]artifactId\" \"versionStr\"]."
[root]
(let [group-id (zip-xml/xml1-> root :groupId zip-xml/text)
artifact-id (zip-xml/xml1-> root :artifactId zip-xml/text)
version (str (zip-xml/xml1-> root :version zip-xml/text))]
(when-not (s/blank? artifact-id)
(when-not (s/blank? group-id)
[(str group-id "/" artifact-id) version]
[artifact-id version]))))
(defn parse-pom-file
"Parses a single POM file (a java.io.File) into the structure: [projectCljGAV [dependencyCljGAVs, ...]] (see cljgav for the format of each CLJGAV)."
[^java.io.File pom-file]
(try
; We do all of this because some of the POMs in Clojars are invalid in ways that are trivial to fix (leading whitespace, BOM, invalid UTF-8 byte sequences)
(let [xml-decoder (doto (.newDecoder java.nio.charset.StandardCharsets/UTF_8)
(.onMalformedInput java.nio.charset.CodingErrorAction/REPLACE)
(.onUnmappableCharacter java.nio.charset.CodingErrorAction/REPLACE))
xml-is (org.owasp.dependencycheck.xml.XmlInputStream. ; Strip leading whitespace, BOM, etc.
(org.apache.commons.io.input.ReaderInputStream. ; Convert reader back to UTF-8 encoded InputStream (*blech*)
(java.io.InputStreamReader. (io/input-stream pom-file) xml-decoder) ; Replace invalid UTF-8 byte sequences into a reader
java.nio.charset.StandardCharsets/UTF_8))
root (zip/xml-zip (xml/parse xml-is))
project-gav (cljgav root)
dependency-gavs (seq (remove nil? (map cljgav (zip-xml/xml-> root :dependencies :dependency))))]
(when project-gav
[project-gav dependency-gavs]))
(catch Exception e
(print (str "⚠️ Unable to parse POM " (.getName pom-file) ": " e "\n"))
(flush))))
(defn parse-pom-files
"Parses all POM files in the given directory, and returns a sequence of parsed POMs (see parse-pom-file for the format of each entry in the sequence)."
[poms-directory]
(let [pom-files (filter #(and (.endsWith (.getName ^java.io.File %) ".pom")
(.canRead ^java.io.File %)
(not (.isDirectory ^java.io.File %)))
(file-seq (io/file poms-directory)))]
(remove nil? (pmap parse-pom-file pom-files))))
(defn latest-project-versions
"Filters out all but the latest version of each project (based on how version-clj compares Maven version strings)."
[parsed-pom-files]
(let [grouped-projects (group-by #(first (first %)) parsed-pom-files)]
(pmap #(last (sort-by (fn [p] (second (first p))) ver/version-compare (second %))) grouped-projects)))
(defn dependencies
"Returns a sequence of dependency pairs, in [fromCljGAV toCljGAV] format."
[latest-project-versions]
(let [version-numbers-elided (pmap #(vec [(first (first %)) (map first (second %))]) latest-project-versions)]
(for [project version-numbers-elided
from [(first project)]
to (second project)]
[from to])))
|
[
{
"context": "cher-fn]\n (let [p (promise)\n key (uuid)]\n (on-sync-event path\n ",
"end": 5194,
"score": 0.49563828110694885,
"start": 5190,
"tag": "KEY",
"value": "uuid"
}
] | src/overtone/sc/machinery/server/comms.clj | ABaldwinHunter/overtone | 1 | (ns overtone.sc.machinery.server.comms
(:use [overtone.sc.machinery.server osc-validator]
[overtone.libs event counters]
[overtone.helpers.lib :only [uuid deref!]])
(:require [overtone.config.log :as log]))
(defonce osc-debug* (atom false))
(defonce server-osc-peer* (ref nil))
;; The base handler for receiving osc messages just forwards the message on
;; as an event using the osc path as the event key.
(on-sync-event [:overtone :osc-msg-received]
(fn [{{path :path args :args} :msg}]
(when @osc-debug*
(println "Receiving: " path args))
(event path :path path :args args))
::osc-receiver)
(defn- massage-numerical-args
"Massage numerical args to the form SC would like them. Currently this
just casts all Longs to Integers and Doubles to Floats."
[argv]
(mapv (fn [arg]
(cond (instance? Long arg)
(Integer. arg)
(instance? Double arg)
(Float. arg)
:else
arg))
argv))
(defn server-snd
"Sends an OSC message to the server. If the message path is a known
scsynth path, then the types of the arguments will be checked
according to what scsynth is expecting. Automatically converts any
args which are longs to ints and doubles to floats.
(server-snd \"/foo\" 1 2.0 \"eggs\")"
[path & args]
(let [args (massage-numerical-args (vec args))]
(log/debug (str "Sending: " path ", args: " (into [] args)))
(when @osc-debug*
(println "Sending: " path args))
(apply validated-snd @server-osc-peer* path args)))
(defn on-server-sync
"Registers the handler to be executed when all the osc messages
generated by executing the action-fn have completed. Returns result
of action-fn."
[action-fn handler-fn]
(let [id (next-id ::server-sync-id)
key (uuid)]
(on-event "/synced"
(fn [msg] (when (= id (first (:args msg)))
(handler-fn)
:overtone/remove-handler))
key)
(let [res (action-fn)]
(server-snd "/sync" id)
res)))
(defn server-sync
"Send a sync message to the server with the specified id. Server will
reply with a synced message when all incoming messages up to the sync
message have been handled. See with-server-sync and on-server-sync for
more typical usage."
[id]
(server-snd "/sync" id))
(defn with-server-self-sync
"Blocks the current thread until the action-fn explicitly sends a
server sync. The action-fn is assumed to have one argument which will
be the unique sync id. This is useful when the action-fn is itself
asynchronous yet you wish to synchronise with its completion. The
action-fn can sync using the fn server-sync. Returns the result of
action-fn
Throws an exception if the sync doesn't complete. By specifying an
optional error-msg, you can communicate back to the user through the
timeout exception the cause of the exception. Typical error-msg values
start with \"whilst...\" i.e. \"whilst creating group foo\"."
([action-fn] (with-server-self-sync action-fn ""))
([action-fn error-msg]
(let [id (next-id ::server-sync-id)
prom (promise)
key (uuid)]
(oneshot-event "/synced"
(fn [msg] (when (= id (first (:args msg)))
(deliver prom true)))
key)
(let [res (action-fn id)]
(deref! prom (str "attempting to self-synchronise with the server " error-msg))
res))))
(defn with-server-sync
"Blocks current thread until all osc messages in action-fn have
completed. Returns result of action-fn.
Throws an exception if the sync doesn't complete. By specifying an
optional error-msg, you can communicate back to the user through the
timeout exception the cause of the exception. Typical error-msg values
start with \"whilst...\" i.e. \"whilst creating group foo\""
([action-fn] (with-server-sync action-fn ""))
([action-fn error-msg]
(let [id (next-id ::server-sync-id)
prom (promise)
key (uuid)]
(on-event "/synced"
(fn [msg] (when (= id (first (:args msg)))
(deliver prom true)
:overtone/remove-handler))
key)
(let [res (action-fn)]
(server-snd "/sync" id)
(deref! prom (str "attempting to synchronise with the server " error-msg))
res))))
(defn server-recv
"Register your intent to wait for a message associated with given path
to be received from the server. Returns a promise that will contain
the message once it has been received. Does not block current
thread (this only happens once you try and look inside the promise and
the reply has not yet been received).
If an optional matcher-fn is specified, will only deliver the promise
when the matcher-fn returns true. The matcher-fn should accept one arg
which is the incoming event info."
([path] (server-recv path nil))
([path matcher-fn]
(let [p (promise)
key (uuid)]
(on-sync-event path
(fn [info]
(when (or (nil? matcher-fn)
(matcher-fn info))
(deliver p info)
:overtone/remove-handler))
key)
p)))
| 28423 | (ns overtone.sc.machinery.server.comms
(:use [overtone.sc.machinery.server osc-validator]
[overtone.libs event counters]
[overtone.helpers.lib :only [uuid deref!]])
(:require [overtone.config.log :as log]))
(defonce osc-debug* (atom false))
(defonce server-osc-peer* (ref nil))
;; The base handler for receiving osc messages just forwards the message on
;; as an event using the osc path as the event key.
(on-sync-event [:overtone :osc-msg-received]
(fn [{{path :path args :args} :msg}]
(when @osc-debug*
(println "Receiving: " path args))
(event path :path path :args args))
::osc-receiver)
(defn- massage-numerical-args
"Massage numerical args to the form SC would like them. Currently this
just casts all Longs to Integers and Doubles to Floats."
[argv]
(mapv (fn [arg]
(cond (instance? Long arg)
(Integer. arg)
(instance? Double arg)
(Float. arg)
:else
arg))
argv))
(defn server-snd
"Sends an OSC message to the server. If the message path is a known
scsynth path, then the types of the arguments will be checked
according to what scsynth is expecting. Automatically converts any
args which are longs to ints and doubles to floats.
(server-snd \"/foo\" 1 2.0 \"eggs\")"
[path & args]
(let [args (massage-numerical-args (vec args))]
(log/debug (str "Sending: " path ", args: " (into [] args)))
(when @osc-debug*
(println "Sending: " path args))
(apply validated-snd @server-osc-peer* path args)))
(defn on-server-sync
"Registers the handler to be executed when all the osc messages
generated by executing the action-fn have completed. Returns result
of action-fn."
[action-fn handler-fn]
(let [id (next-id ::server-sync-id)
key (uuid)]
(on-event "/synced"
(fn [msg] (when (= id (first (:args msg)))
(handler-fn)
:overtone/remove-handler))
key)
(let [res (action-fn)]
(server-snd "/sync" id)
res)))
(defn server-sync
"Send a sync message to the server with the specified id. Server will
reply with a synced message when all incoming messages up to the sync
message have been handled. See with-server-sync and on-server-sync for
more typical usage."
[id]
(server-snd "/sync" id))
(defn with-server-self-sync
"Blocks the current thread until the action-fn explicitly sends a
server sync. The action-fn is assumed to have one argument which will
be the unique sync id. This is useful when the action-fn is itself
asynchronous yet you wish to synchronise with its completion. The
action-fn can sync using the fn server-sync. Returns the result of
action-fn
Throws an exception if the sync doesn't complete. By specifying an
optional error-msg, you can communicate back to the user through the
timeout exception the cause of the exception. Typical error-msg values
start with \"whilst...\" i.e. \"whilst creating group foo\"."
([action-fn] (with-server-self-sync action-fn ""))
([action-fn error-msg]
(let [id (next-id ::server-sync-id)
prom (promise)
key (uuid)]
(oneshot-event "/synced"
(fn [msg] (when (= id (first (:args msg)))
(deliver prom true)))
key)
(let [res (action-fn id)]
(deref! prom (str "attempting to self-synchronise with the server " error-msg))
res))))
(defn with-server-sync
"Blocks current thread until all osc messages in action-fn have
completed. Returns result of action-fn.
Throws an exception if the sync doesn't complete. By specifying an
optional error-msg, you can communicate back to the user through the
timeout exception the cause of the exception. Typical error-msg values
start with \"whilst...\" i.e. \"whilst creating group foo\""
([action-fn] (with-server-sync action-fn ""))
([action-fn error-msg]
(let [id (next-id ::server-sync-id)
prom (promise)
key (uuid)]
(on-event "/synced"
(fn [msg] (when (= id (first (:args msg)))
(deliver prom true)
:overtone/remove-handler))
key)
(let [res (action-fn)]
(server-snd "/sync" id)
(deref! prom (str "attempting to synchronise with the server " error-msg))
res))))
(defn server-recv
"Register your intent to wait for a message associated with given path
to be received from the server. Returns a promise that will contain
the message once it has been received. Does not block current
thread (this only happens once you try and look inside the promise and
the reply has not yet been received).
If an optional matcher-fn is specified, will only deliver the promise
when the matcher-fn returns true. The matcher-fn should accept one arg
which is the incoming event info."
([path] (server-recv path nil))
([path matcher-fn]
(let [p (promise)
key (<KEY>)]
(on-sync-event path
(fn [info]
(when (or (nil? matcher-fn)
(matcher-fn info))
(deliver p info)
:overtone/remove-handler))
key)
p)))
| true | (ns overtone.sc.machinery.server.comms
(:use [overtone.sc.machinery.server osc-validator]
[overtone.libs event counters]
[overtone.helpers.lib :only [uuid deref!]])
(:require [overtone.config.log :as log]))
(defonce osc-debug* (atom false))
(defonce server-osc-peer* (ref nil))
;; The base handler for receiving osc messages just forwards the message on
;; as an event using the osc path as the event key.
(on-sync-event [:overtone :osc-msg-received]
(fn [{{path :path args :args} :msg}]
(when @osc-debug*
(println "Receiving: " path args))
(event path :path path :args args))
::osc-receiver)
(defn- massage-numerical-args
"Massage numerical args to the form SC would like them. Currently this
just casts all Longs to Integers and Doubles to Floats."
[argv]
(mapv (fn [arg]
(cond (instance? Long arg)
(Integer. arg)
(instance? Double arg)
(Float. arg)
:else
arg))
argv))
(defn server-snd
"Sends an OSC message to the server. If the message path is a known
scsynth path, then the types of the arguments will be checked
according to what scsynth is expecting. Automatically converts any
args which are longs to ints and doubles to floats.
(server-snd \"/foo\" 1 2.0 \"eggs\")"
[path & args]
(let [args (massage-numerical-args (vec args))]
(log/debug (str "Sending: " path ", args: " (into [] args)))
(when @osc-debug*
(println "Sending: " path args))
(apply validated-snd @server-osc-peer* path args)))
(defn on-server-sync
"Registers the handler to be executed when all the osc messages
generated by executing the action-fn have completed. Returns result
of action-fn."
[action-fn handler-fn]
(let [id (next-id ::server-sync-id)
key (uuid)]
(on-event "/synced"
(fn [msg] (when (= id (first (:args msg)))
(handler-fn)
:overtone/remove-handler))
key)
(let [res (action-fn)]
(server-snd "/sync" id)
res)))
(defn server-sync
"Send a sync message to the server with the specified id. Server will
reply with a synced message when all incoming messages up to the sync
message have been handled. See with-server-sync and on-server-sync for
more typical usage."
[id]
(server-snd "/sync" id))
(defn with-server-self-sync
"Blocks the current thread until the action-fn explicitly sends a
server sync. The action-fn is assumed to have one argument which will
be the unique sync id. This is useful when the action-fn is itself
asynchronous yet you wish to synchronise with its completion. The
action-fn can sync using the fn server-sync. Returns the result of
action-fn
Throws an exception if the sync doesn't complete. By specifying an
optional error-msg, you can communicate back to the user through the
timeout exception the cause of the exception. Typical error-msg values
start with \"whilst...\" i.e. \"whilst creating group foo\"."
([action-fn] (with-server-self-sync action-fn ""))
([action-fn error-msg]
(let [id (next-id ::server-sync-id)
prom (promise)
key (uuid)]
(oneshot-event "/synced"
(fn [msg] (when (= id (first (:args msg)))
(deliver prom true)))
key)
(let [res (action-fn id)]
(deref! prom (str "attempting to self-synchronise with the server " error-msg))
res))))
(defn with-server-sync
"Blocks current thread until all osc messages in action-fn have
completed. Returns result of action-fn.
Throws an exception if the sync doesn't complete. By specifying an
optional error-msg, you can communicate back to the user through the
timeout exception the cause of the exception. Typical error-msg values
start with \"whilst...\" i.e. \"whilst creating group foo\""
([action-fn] (with-server-sync action-fn ""))
([action-fn error-msg]
(let [id (next-id ::server-sync-id)
prom (promise)
key (uuid)]
(on-event "/synced"
(fn [msg] (when (= id (first (:args msg)))
(deliver prom true)
:overtone/remove-handler))
key)
(let [res (action-fn)]
(server-snd "/sync" id)
(deref! prom (str "attempting to synchronise with the server " error-msg))
res))))
(defn server-recv
"Register your intent to wait for a message associated with given path
to be received from the server. Returns a promise that will contain
the message once it has been received. Does not block current
thread (this only happens once you try and look inside the promise and
the reply has not yet been received).
If an optional matcher-fn is specified, will only deliver the promise
when the matcher-fn returns true. The matcher-fn should accept one arg
which is the incoming event info."
([path] (server-recv path nil))
([path matcher-fn]
(let [p (promise)
key (PI:KEY:<KEY>END_PI)]
(on-sync-event path
(fn [info]
(when (or (nil? matcher-fn)
(matcher-fn info))
(deliver p info)
:overtone/remove-handler))
key)
p)))
|
[
{
"context": "maire\"\n [(= __\n (group-by :id [{:id 1 :name \"Bob\"}\n {:id 2 :name \"Mike\"}\n ",
"end": 584,
"score": 0.9997190237045288,
"start": 581,
"tag": "NAME",
"value": "Bob"
},
{
"context": " 1 :name \"Bob\"}\n {:id 2 :name \"Mike\"}\n {:id 1 :last-name \"Smith\"}]",
"end": 625,
"score": 0.9994447231292725,
"start": 621,
"tag": "NAME",
"value": "Mike"
},
{
"context": "me \"Mike\"}\n {:id 1 :last-name \"Smith\"}]))] {1 [{:name \"Bob\" :id 1}\n ",
"end": 672,
"score": 0.9997100830078125,
"start": 667,
"tag": "NAME",
"value": "Smith"
},
{
"context": " {:id 1 :last-name \"Smith\"}]))] {1 [{:name \"Bob\" :id 1}\n ",
"end": 694,
"score": 0.9995750784873962,
"start": 691,
"tag": "NAME",
"value": "Bob"
},
{
"context": " {:last-name \"Smith\" :id 1}]\n ",
"end": 776,
"score": 0.999688982963562,
"start": 771,
"tag": "NAME",
"value": "Smith"
},
{
"context": " 2 [{:name \"Mike\" :id 2}]})\n\n\n(exercice\n\n \"Mais soyez prudent lor",
"end": 853,
"score": 0.9996124505996704,
"start": 849,
"tag": "NAME",
"value": "Mike"
},
{
"context": " lorsque vous groupe par clé non requise\"\n [(= {\"Bob\" [{:name \"Bob\" :id 1}]\n \"Mike\" [{:name \"Mik",
"end": 952,
"score": 0.8976539969444275,
"start": 949,
"tag": "NAME",
"value": "Bob"
},
{
"context": "groupe par clé non requise\"\n [(= {\"Bob\" [{:name \"Bob\" :id 1}]\n \"Mike\" [{:name \"Mike\" :id 2}]\n ",
"end": 966,
"score": 0.9994263648986816,
"start": 963,
"tag": "NAME",
"value": "Bob"
},
{
"context": "quise\"\n [(= {\"Bob\" [{:name \"Bob\" :id 1}]\n \"Mike\" [{:name \"Mike\" :id 2}]\n __ [{:last-name \"S",
"end": 988,
"score": 0.9859884977340698,
"start": 984,
"tag": "NAME",
"value": "Mike"
},
{
"context": "Bob\" [{:name \"Bob\" :id 1}]\n \"Mike\" [{:name \"Mike\" :id 2}]\n __ [{:last-name \"Smith\" :id 1}]}\n",
"end": 1003,
"score": 0.9995591640472412,
"start": 999,
"tag": "NAME",
"value": "Mike"
},
{
"context": "e\" [{:name \"Mike\" :id 2}]\n __ [{:last-name \"Smith\" :id 1}]}\n (group-by :name [{:id 1 :name \"Bob",
"end": 1042,
"score": 0.9993102550506592,
"start": 1037,
"tag": "NAME",
"value": "Smith"
},
{
"context": "ith\" :id 1}]}\n (group-by :name [{:id 1 :name \"Bob\"}\n {:id 2 :name \"Mike\"}\n ",
"end": 1092,
"score": 0.9997484087944031,
"start": 1089,
"tag": "NAME",
"value": "Bob"
},
{
"context": " :name \"Bob\"}\n {:id 2 :name \"Mike\"}\n {:id 1 :last-name \"Smith\"",
"end": 1135,
"score": 0.9996047616004944,
"start": 1131,
"tag": "NAME",
"value": "Mike"
},
{
"context": " \"Mike\"}\n {:id 1 :last-name \"Smith\"}]))] nil)\n\n\n(exercice\n\"Le vrai pouvoir de group-",
"end": 1184,
"score": 0.9997341632843018,
"start": 1179,
"tag": "NAME",
"value": "Smith"
},
{
"context": ":bad %) :naughty-list :nice-list)\n [{:name \"Jimmy\" :bad true}\n {:name \"Jack\" :bad false}\n ",
"end": 1368,
"score": 0.9993757605552673,
"start": 1363,
"tag": "NAME",
"value": "Jimmy"
},
{
"context": " [{:name \"Jimmy\" :bad true}\n {:name \"Jack\" :bad false}\n {:name \"Joe\" :bad true}]))] ",
"end": 1401,
"score": 0.9997605681419373,
"start": 1397,
"tag": "NAME",
"value": "Jack"
},
{
"context": " {:name \"Jack\" :bad false}\n {:name \"Joe\" :bad true}]))] {:naughty-list [{:name \"Jimmy\" :b",
"end": 1434,
"score": 0.9994829893112183,
"start": 1431,
"tag": "NAME",
"value": "Joe"
},
{
"context": "name \"Joe\" :bad true}]))] {:naughty-list [{:name \"Jimmy\" :bad true}\n ",
"end": 1480,
"score": 0.9996734857559204,
"start": 1475,
"tag": "NAME",
"value": "Jimmy"
},
{
"context": " {:name \"Joe\" :bad true}]\n ",
"end": 1556,
"score": 0.9996528029441833,
"start": 1553,
"tag": "NAME",
"value": "Joe"
},
{
"context": " :nice-list [{:name \"Jack\" :bad false}]})\n",
"end": 1631,
"score": 0.9997878670692444,
"start": 1627,
"tag": "NAME",
"value": "Jack"
}
] | src/clj/exercices/21_group_by.clj | univalence/introclojure | 0 | (defn get-odds-and-evens [coll]
(let [{odds true evens false} (group-by __ coll)]
[odds evens]))
(exercice
"Pour classer une collection par une fonction, utilisez group-by."
[(= __ (group-by count ["hello" "world" "foo" "bar"]))] odd?)
(exercice
"Vous pouvez simuler filtre + retirer en une seule passe"
[(= (get-odds-and-evens [1 2 3 4 5])
((juxt filter remove) odd? [1 2 3 4 5])
[[1 3 5] [2 4]])] {5 ["hello" "world"] 3 ["foo" "bar"]})
(exercice
"Vous pouvez également regrouper par une clé primaire"
[(= __
(group-by :id [{:id 1 :name "Bob"}
{:id 2 :name "Mike"}
{:id 1 :last-name "Smith"}]))] {1 [{:name "Bob" :id 1}
{:last-name "Smith" :id 1}]
2 [{:name "Mike" :id 2}]})
(exercice
"Mais soyez prudent lorsque vous groupe par clé non requise"
[(= {"Bob" [{:name "Bob" :id 1}]
"Mike" [{:name "Mike" :id 2}]
__ [{:last-name "Smith" :id 1}]}
(group-by :name [{:id 1 :name "Bob"}
{:id 2 :name "Mike"}
{:id 1 :last-name "Smith"}]))] nil)
(exercice
"Le vrai pouvoir de group-by est délivré via des fonctions personnalisées"
[(= __
(group-by #(if (:bad %) :naughty-list :nice-list)
[{:name "Jimmy" :bad true}
{:name "Jack" :bad false}
{:name "Joe" :bad true}]))] {:naughty-list [{:name "Jimmy" :bad true}
{:name "Joe" :bad true}]
:nice-list [{:name "Jack" :bad false}]})
| 57686 | (defn get-odds-and-evens [coll]
(let [{odds true evens false} (group-by __ coll)]
[odds evens]))
(exercice
"Pour classer une collection par une fonction, utilisez group-by."
[(= __ (group-by count ["hello" "world" "foo" "bar"]))] odd?)
(exercice
"Vous pouvez simuler filtre + retirer en une seule passe"
[(= (get-odds-and-evens [1 2 3 4 5])
((juxt filter remove) odd? [1 2 3 4 5])
[[1 3 5] [2 4]])] {5 ["hello" "world"] 3 ["foo" "bar"]})
(exercice
"Vous pouvez également regrouper par une clé primaire"
[(= __
(group-by :id [{:id 1 :name "<NAME>"}
{:id 2 :name "<NAME>"}
{:id 1 :last-name "<NAME>"}]))] {1 [{:name "<NAME>" :id 1}
{:last-name "<NAME>" :id 1}]
2 [{:name "<NAME>" :id 2}]})
(exercice
"Mais soyez prudent lorsque vous groupe par clé non requise"
[(= {"<NAME>" [{:name "<NAME>" :id 1}]
"<NAME>" [{:name "<NAME>" :id 2}]
__ [{:last-name "<NAME>" :id 1}]}
(group-by :name [{:id 1 :name "<NAME>"}
{:id 2 :name "<NAME>"}
{:id 1 :last-name "<NAME>"}]))] nil)
(exercice
"Le vrai pouvoir de group-by est délivré via des fonctions personnalisées"
[(= __
(group-by #(if (:bad %) :naughty-list :nice-list)
[{:name "<NAME>" :bad true}
{:name "<NAME>" :bad false}
{:name "<NAME>" :bad true}]))] {:naughty-list [{:name "<NAME>" :bad true}
{:name "<NAME>" :bad true}]
:nice-list [{:name "<NAME>" :bad false}]})
| true | (defn get-odds-and-evens [coll]
(let [{odds true evens false} (group-by __ coll)]
[odds evens]))
(exercice
"Pour classer une collection par une fonction, utilisez group-by."
[(= __ (group-by count ["hello" "world" "foo" "bar"]))] odd?)
(exercice
"Vous pouvez simuler filtre + retirer en une seule passe"
[(= (get-odds-and-evens [1 2 3 4 5])
((juxt filter remove) odd? [1 2 3 4 5])
[[1 3 5] [2 4]])] {5 ["hello" "world"] 3 ["foo" "bar"]})
(exercice
"Vous pouvez également regrouper par une clé primaire"
[(= __
(group-by :id [{:id 1 :name "PI:NAME:<NAME>END_PI"}
{:id 2 :name "PI:NAME:<NAME>END_PI"}
{:id 1 :last-name "PI:NAME:<NAME>END_PI"}]))] {1 [{:name "PI:NAME:<NAME>END_PI" :id 1}
{:last-name "PI:NAME:<NAME>END_PI" :id 1}]
2 [{:name "PI:NAME:<NAME>END_PI" :id 2}]})
(exercice
"Mais soyez prudent lorsque vous groupe par clé non requise"
[(= {"PI:NAME:<NAME>END_PI" [{:name "PI:NAME:<NAME>END_PI" :id 1}]
"PI:NAME:<NAME>END_PI" [{:name "PI:NAME:<NAME>END_PI" :id 2}]
__ [{:last-name "PI:NAME:<NAME>END_PI" :id 1}]}
(group-by :name [{:id 1 :name "PI:NAME:<NAME>END_PI"}
{:id 2 :name "PI:NAME:<NAME>END_PI"}
{:id 1 :last-name "PI:NAME:<NAME>END_PI"}]))] nil)
(exercice
"Le vrai pouvoir de group-by est délivré via des fonctions personnalisées"
[(= __
(group-by #(if (:bad %) :naughty-list :nice-list)
[{:name "PI:NAME:<NAME>END_PI" :bad true}
{:name "PI:NAME:<NAME>END_PI" :bad false}
{:name "PI:NAME:<NAME>END_PI" :bad true}]))] {:naughty-list [{:name "PI:NAME:<NAME>END_PI" :bad true}
{:name "PI:NAME:<NAME>END_PI" :bad true}]
:nice-list [{:name "PI:NAME:<NAME>END_PI" :bad false}]})
|
[
{
"context": "\n\n; *update-in* function\n(def by-author\n {:name \"Jane Austen\"\n :book {:title \"Emma\" :copies 1000}})\n\n; (upda",
"end": 473,
"score": 0.9998703002929688,
"start": 462,
"tag": "NAME",
"value": "Jane Austen"
},
{
"context": "author\n {:name \"Jane Austen\"\n :book {:title \"Emma\" :copies 1000}})\n\n; (update-in [m ks f & args]) ;",
"end": 497,
"score": 0.8151413798332214,
"start": 495,
"tag": "NAME",
"value": "ma"
}
] | cljlrn/src/learn/collections.clj | lenkite/learn | 0 | (ns learn.collections)
; Various map functions
; *update* function
; updates a value in map, takes m(map, k(key) and f(function) as arguments followed by optional args)
; f is a function that will take in old value and args and return the new value.
; update will return a new map
(def book {:title "Emma" :copies 1000})
; (update [m k f & args])
(update book :copies inc) ;= {:title "Emma", :copies 1001}
; *update-in* function
(def by-author
{:name "Jane Austen"
:book {:title "Emma" :copies 1000}})
; (update-in [m ks f & args]) ; update-in takes in key-sequence vector instead
; of plain key. creates levels if they don't exit
(update-in by-author [:book :copies] inc)
; *assoc-in* function
; associates a new value in a map for a given key sequence
; (assoc-in [m ks v])
; Example using Ring and Jetty.
; In Ring requests and responses are maps. A handler is a function that takes a
; request map and returns a response map
(defn handler [ request]
{:status 200
:headers {"Content-Type" "text/html"}
:body "Hello from your web-app"})
; you can start web-app by passing the handler function to rings run-jetty
;(defn -main [] (jetty/run-jetty handler {:port 8080}))
; ring apps use middleware which are functions that take a handler function (and other arguments) as
; parameters and return a new handler function. Can be used to layer
; additional features onto handlers
(defn log [msg value]
"Logs message and value. Returns the value"
(println msg value) value)
(defn wrap-log
"Returns a middlware function that logs the response"
[msg handler]
(fn [request]
(log msg (handler request))))
(defn wrap-content-type
"Middlware function that Returns a function that sets the response content type"
[handler content-type]
(fn [request]
(assoc-in (handler request) [:headers "Content-Type"] content-type))) ;assoc-in will create levels if they don't exist
| 121669 | (ns learn.collections)
; Various map functions
; *update* function
; updates a value in map, takes m(map, k(key) and f(function) as arguments followed by optional args)
; f is a function that will take in old value and args and return the new value.
; update will return a new map
(def book {:title "Emma" :copies 1000})
; (update [m k f & args])
(update book :copies inc) ;= {:title "Emma", :copies 1001}
; *update-in* function
(def by-author
{:name "<NAME>"
:book {:title "Em<NAME>" :copies 1000}})
; (update-in [m ks f & args]) ; update-in takes in key-sequence vector instead
; of plain key. creates levels if they don't exit
(update-in by-author [:book :copies] inc)
; *assoc-in* function
; associates a new value in a map for a given key sequence
; (assoc-in [m ks v])
; Example using Ring and Jetty.
; In Ring requests and responses are maps. A handler is a function that takes a
; request map and returns a response map
(defn handler [ request]
{:status 200
:headers {"Content-Type" "text/html"}
:body "Hello from your web-app"})
; you can start web-app by passing the handler function to rings run-jetty
;(defn -main [] (jetty/run-jetty handler {:port 8080}))
; ring apps use middleware which are functions that take a handler function (and other arguments) as
; parameters and return a new handler function. Can be used to layer
; additional features onto handlers
(defn log [msg value]
"Logs message and value. Returns the value"
(println msg value) value)
(defn wrap-log
"Returns a middlware function that logs the response"
[msg handler]
(fn [request]
(log msg (handler request))))
(defn wrap-content-type
"Middlware function that Returns a function that sets the response content type"
[handler content-type]
(fn [request]
(assoc-in (handler request) [:headers "Content-Type"] content-type))) ;assoc-in will create levels if they don't exist
| true | (ns learn.collections)
; Various map functions
; *update* function
; updates a value in map, takes m(map, k(key) and f(function) as arguments followed by optional args)
; f is a function that will take in old value and args and return the new value.
; update will return a new map
(def book {:title "Emma" :copies 1000})
; (update [m k f & args])
(update book :copies inc) ;= {:title "Emma", :copies 1001}
; *update-in* function
(def by-author
{:name "PI:NAME:<NAME>END_PI"
:book {:title "EmPI:NAME:<NAME>END_PI" :copies 1000}})
; (update-in [m ks f & args]) ; update-in takes in key-sequence vector instead
; of plain key. creates levels if they don't exit
(update-in by-author [:book :copies] inc)
; *assoc-in* function
; associates a new value in a map for a given key sequence
; (assoc-in [m ks v])
; Example using Ring and Jetty.
; In Ring requests and responses are maps. A handler is a function that takes a
; request map and returns a response map
(defn handler [ request]
{:status 200
:headers {"Content-Type" "text/html"}
:body "Hello from your web-app"})
; you can start web-app by passing the handler function to rings run-jetty
;(defn -main [] (jetty/run-jetty handler {:port 8080}))
; ring apps use middleware which are functions that take a handler function (and other arguments) as
; parameters and return a new handler function. Can be used to layer
; additional features onto handlers
(defn log [msg value]
"Logs message and value. Returns the value"
(println msg value) value)
(defn wrap-log
"Returns a middlware function that logs the response"
[msg handler]
(fn [request]
(log msg (handler request))))
(defn wrap-content-type
"Middlware function that Returns a function that sets the response content type"
[handler content-type]
(fn [request]
(assoc-in (handler request) [:headers "Content-Type"] content-type))) ;assoc-in will create levels if they don't exist
|
[
{
"context": "t/name name\n :password/hashed-value password\n :password/salt password_salt\n ",
"end": 3578,
"score": 0.943924069404602,
"start": 3570,
"tag": "PASSWORD",
"value": "password"
}
] | src/sql/com/example/components/database_queries.clj | somanythings/fulcro-rad-demo | 60 | (ns com.example.components.database-queries
(:require
[com.fulcrologic.rad.database-adapters.sql :as sql]
[com.fulcrologic.rad.database-adapters.sql.query :as query]
[next.jdbc.sql :as jdbc]
[taoensso.timbre :as log]))
(defn add-namespace [nspc k] (keyword nspc (name k)))
(defn get-all-accounts
[env query-params]
(let [data-source (get-in env [::sql/connection-pools :production])
show-inactive? (:show-inactive? query-params)
sql (str "SELECT id FROM account" (when-not show-inactive? " WHERE active = true"))
rows (mapv #(hash-map :account/id (:id %)) (jdbc/query data-source [sql] {:builder-fn query/row-builder}))]
rows))
(defn get-all-items
[env {:category/keys [id]}]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params (if id
["SELECT id FROM item WHERE category = ?" (log/spy :info id)]
["SELECT id FROM item"])
rows (mapv #(hash-map :item/id (:id %)) (jdbc/query data-source query-params {:builder-fn query/row-builder}))]
rows))
(defn get-customer-invoices [env {:account/keys [id]}]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params (if id
["SELECT id FROM invoice INNER JOIN account ON account.id = invoice.customer WHERE account.id = ?" id]
nil)
rows (if query-params
(mapv #(hash-map :invoice/id (:id %)) (jdbc/query data-source query-params {:builder-fn query/row-builder}))
[])]
rows))
(defn get-all-invoices
[env _]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params ["SELECT id FROM invoice"]
rows (mapv #(hash-map :invoice/id (:id %)) (jdbc/query data-source query-params {:builder-fn query/row-builder}))]
rows))
(defn get-invoice-customer-id
[env invoice-id]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params ["SELECT account.id FROM account INNER JOIN invoice on invoice.customer = account.id WHERE invoice.id = ?" invoice-id]]
(-> (jdbc/query data-source query-params {:builder-fn query/row-builder})
first
:id)))
(defn get-all-categories
[env _]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params ["SELECT id FROM category"]
rows (mapv #(hash-map :category/id (:id %)) (jdbc/query data-source query-params {:builder-fn query/row-builder}))]
rows))
(defn get-line-item-category [env line-item-id]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params [(str
"SELECT item.category FROM item "
"INNER JOIN line_item ON line_item.item = item.id "
"WHERE line_item.id = ?") line-item-id]]
(:category (first (jdbc/query data-source query-params {:builder-fn query/row-builder})))))
(defn get-login-info
"Get the account name, time zone, and password info via a username (email)."
[env username]
(let [data-source (get-in env [::sql/connection-pools :production])
rows (jdbc/query data-source ["SELECT name, password, password_salt, password_iterations FROM account WHERE email = ?" username] {:builder-fn query/row-builder})
{:keys [name password password_salt password_iterations]} (first rows)]
(when name
{:account/name name
:password/hashed-value password
:password/salt password_salt
:password/iterations password_iterations})))
| 87571 | (ns com.example.components.database-queries
(:require
[com.fulcrologic.rad.database-adapters.sql :as sql]
[com.fulcrologic.rad.database-adapters.sql.query :as query]
[next.jdbc.sql :as jdbc]
[taoensso.timbre :as log]))
(defn add-namespace [nspc k] (keyword nspc (name k)))
(defn get-all-accounts
[env query-params]
(let [data-source (get-in env [::sql/connection-pools :production])
show-inactive? (:show-inactive? query-params)
sql (str "SELECT id FROM account" (when-not show-inactive? " WHERE active = true"))
rows (mapv #(hash-map :account/id (:id %)) (jdbc/query data-source [sql] {:builder-fn query/row-builder}))]
rows))
(defn get-all-items
[env {:category/keys [id]}]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params (if id
["SELECT id FROM item WHERE category = ?" (log/spy :info id)]
["SELECT id FROM item"])
rows (mapv #(hash-map :item/id (:id %)) (jdbc/query data-source query-params {:builder-fn query/row-builder}))]
rows))
(defn get-customer-invoices [env {:account/keys [id]}]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params (if id
["SELECT id FROM invoice INNER JOIN account ON account.id = invoice.customer WHERE account.id = ?" id]
nil)
rows (if query-params
(mapv #(hash-map :invoice/id (:id %)) (jdbc/query data-source query-params {:builder-fn query/row-builder}))
[])]
rows))
(defn get-all-invoices
[env _]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params ["SELECT id FROM invoice"]
rows (mapv #(hash-map :invoice/id (:id %)) (jdbc/query data-source query-params {:builder-fn query/row-builder}))]
rows))
(defn get-invoice-customer-id
[env invoice-id]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params ["SELECT account.id FROM account INNER JOIN invoice on invoice.customer = account.id WHERE invoice.id = ?" invoice-id]]
(-> (jdbc/query data-source query-params {:builder-fn query/row-builder})
first
:id)))
(defn get-all-categories
[env _]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params ["SELECT id FROM category"]
rows (mapv #(hash-map :category/id (:id %)) (jdbc/query data-source query-params {:builder-fn query/row-builder}))]
rows))
(defn get-line-item-category [env line-item-id]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params [(str
"SELECT item.category FROM item "
"INNER JOIN line_item ON line_item.item = item.id "
"WHERE line_item.id = ?") line-item-id]]
(:category (first (jdbc/query data-source query-params {:builder-fn query/row-builder})))))
(defn get-login-info
"Get the account name, time zone, and password info via a username (email)."
[env username]
(let [data-source (get-in env [::sql/connection-pools :production])
rows (jdbc/query data-source ["SELECT name, password, password_salt, password_iterations FROM account WHERE email = ?" username] {:builder-fn query/row-builder})
{:keys [name password password_salt password_iterations]} (first rows)]
(when name
{:account/name name
:password/hashed-value <PASSWORD>
:password/salt password_salt
:password/iterations password_iterations})))
| true | (ns com.example.components.database-queries
(:require
[com.fulcrologic.rad.database-adapters.sql :as sql]
[com.fulcrologic.rad.database-adapters.sql.query :as query]
[next.jdbc.sql :as jdbc]
[taoensso.timbre :as log]))
(defn add-namespace [nspc k] (keyword nspc (name k)))
(defn get-all-accounts
[env query-params]
(let [data-source (get-in env [::sql/connection-pools :production])
show-inactive? (:show-inactive? query-params)
sql (str "SELECT id FROM account" (when-not show-inactive? " WHERE active = true"))
rows (mapv #(hash-map :account/id (:id %)) (jdbc/query data-source [sql] {:builder-fn query/row-builder}))]
rows))
(defn get-all-items
[env {:category/keys [id]}]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params (if id
["SELECT id FROM item WHERE category = ?" (log/spy :info id)]
["SELECT id FROM item"])
rows (mapv #(hash-map :item/id (:id %)) (jdbc/query data-source query-params {:builder-fn query/row-builder}))]
rows))
(defn get-customer-invoices [env {:account/keys [id]}]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params (if id
["SELECT id FROM invoice INNER JOIN account ON account.id = invoice.customer WHERE account.id = ?" id]
nil)
rows (if query-params
(mapv #(hash-map :invoice/id (:id %)) (jdbc/query data-source query-params {:builder-fn query/row-builder}))
[])]
rows))
(defn get-all-invoices
[env _]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params ["SELECT id FROM invoice"]
rows (mapv #(hash-map :invoice/id (:id %)) (jdbc/query data-source query-params {:builder-fn query/row-builder}))]
rows))
(defn get-invoice-customer-id
[env invoice-id]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params ["SELECT account.id FROM account INNER JOIN invoice on invoice.customer = account.id WHERE invoice.id = ?" invoice-id]]
(-> (jdbc/query data-source query-params {:builder-fn query/row-builder})
first
:id)))
(defn get-all-categories
[env _]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params ["SELECT id FROM category"]
rows (mapv #(hash-map :category/id (:id %)) (jdbc/query data-source query-params {:builder-fn query/row-builder}))]
rows))
(defn get-line-item-category [env line-item-id]
(let [data-source (get-in env [::sql/connection-pools :production])
query-params [(str
"SELECT item.category FROM item "
"INNER JOIN line_item ON line_item.item = item.id "
"WHERE line_item.id = ?") line-item-id]]
(:category (first (jdbc/query data-source query-params {:builder-fn query/row-builder})))))
(defn get-login-info
"Get the account name, time zone, and password info via a username (email)."
[env username]
(let [data-source (get-in env [::sql/connection-pools :production])
rows (jdbc/query data-source ["SELECT name, password, password_salt, password_iterations FROM account WHERE email = ?" username] {:builder-fn query/row-builder})
{:keys [name password password_salt password_iterations]} (first rows)]
(when name
{:account/name name
:password/hashed-value PI:PASSWORD:<PASSWORD>END_PI
:password/salt password_salt
:password/iterations password_iterations})))
|
[
{
"context": "nd! conn {:from from\n :to \"alice@example.com\"\n :subject \"hello\"\n ",
"end": 1027,
"score": 0.999858021736145,
"start": 1010,
"tag": "EMAIL",
"value": "alice@example.com"
},
{
"context": "= [\"hello\"] (:subject headers)))\n (t/is (= [\"alice@example.com\"] (:to headers)))\n (t/is (h/tarayo-user-agen",
"end": 1907,
"score": 0.9999240636825562,
"start": 1890,
"tag": "EMAIL",
"value": "alice@example.com"
},
{
"context": "-server)]\n (core/send! conn {:from from :to \"alice@example.com\" :subject \"hello\"\n :body \"",
"end": 2218,
"score": 0.999919056892395,
"start": 2201,
"tag": "EMAIL",
"value": "alice@example.com"
},
{
"context": "-server)]\n (core/send! conn {:from from :to \"alice@example.com\" :subject \"hello\" :body \"world\"})\n (core/sen",
"end": 2797,
"score": 0.9999208450317383,
"start": 2780,
"tag": "EMAIL",
"value": "alice@example.com"
},
{
"context": "\"world\"})\n (core/send! conn {:from from :to \"bob@example.com\" :subject \"foo\" :body \"bar\"}))\n (let [resp (fi",
"end": 2887,
"score": 0.9999202489852905,
"start": 2872,
"tag": "EMAIL",
"value": "bob@example.com"
},
{
"context": "p) (count (:items resp))))\n (t/is (= [{:to [\"bob@example.com\"] :subject [\"foo\"]}\n {:to [\"alice@",
"end": 3053,
"score": 0.9999213218688965,
"start": 3038,
"tag": "EMAIL",
"value": "bob@example.com"
},
{
"context": "le.com\"] :subject [\"foo\"]}\n {:to [\"alice@example.com\"] :subject [\"hello\"]}]\n (->> (:item",
"end": 3114,
"score": 0.9999204874038696,
"start": 3097,
"tag": "EMAIL",
"value": "alice@example.com"
},
{
"context": "-server)]\n (core/send! conn {:from from :to \"alice@example.com\" :subject \"hello\"\n :body [",
"end": 3483,
"score": 0.9999216198921204,
"start": 3466,
"tag": "EMAIL",
"value": "alice@example.com"
},
{
"context": "-server)]\n (core/send! conn {:from from :to \"alice@example.com\" :subject \"hello\"\n :multip",
"end": 4729,
"score": 0.9999216198921204,
"start": 4712,
"tag": "EMAIL",
"value": "alice@example.com"
}
] | integration/test/tarayo/integration/send_test.clj | toyokumo/tarayo | 34 | (ns tarayo.integration.send-test
(:require
[camel-snake-kebab.core :as csk]
[clojure.data.json :as json]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.test :as t]
[org.httpkit.client :as http]
[tarayo.core :as core]
[tarayo.test-helper :as h])
(:import
java.util.Calendar))
(def ^:private mailhog-server
{:host "localhost" :port 1025})
(def ^:private mailhog-search-api-endpoint
(format "http://%s:8025/api/v2/search" (:host mailhog-server)))
(def ^:private ^Calendar now
(doto (Calendar/getInstance)
(.set 2112 (dec 9) 3)))
(defn- find-mail-by-from
[from-address]
(let [resp @(http/get mailhog-search-api-endpoint
{:query-params {:kind "from" :query from-address}})]
(json/read-str (:body resp) :key-fn (comp keyword csk/->kebab-case))))
(t/deftest send-text-mail-test
(let [from (h/random-address)]
(with-open [conn (core/connect mailhog-server)]
(core/send! conn {:from from
:to "alice@example.com"
:subject "hello"
:body "world"
:charset "UTF-8"
:date (.getTime now)}))
(let [resp (find-mail-by-from from)
item (get-in resp [:items 0])
headers (some-> item (get-in [:content :headers]))]
(t/is (= 1 (:total resp)))
(t/is (= 1 (count (:to item))))
(t/is (= {:mailbox "alice" :domain "example.com"}
(-> item :to first (select-keys [:mailbox :domain]))))
(t/is (= ["UTF-8"] (:charset headers)))
(t/is (= ["text/plain; charset=UTF-8"] (:content-type headers)))
(t/is (str/starts-with? (first (:date headers)) "Sat, 3 Sep 2112 "))
(t/is (= [from] (:from headers)))
(t/is (h/tarayo-message-id? (:message-id headers)))
(t/is (= ["hello"] (:subject headers)))
(t/is (= ["alice@example.com"] (:to headers)))
(t/is (h/tarayo-user-agent? (:user-agent headers)))
(t/is (= "world" (get-in item [:content :body]))))))
(t/deftest send-html-mail-test
(let [from (h/random-address)]
(with-open [conn (core/connect mailhog-server)]
(core/send! conn {:from from :to "alice@example.com" :subject "hello"
:body "<h1>world</h1>" :content-type "text/html"}))
(let [resp (find-mail-by-from from)
item (get-in resp [:items 0])]
(t/is (= 1 (:total resp)))
(t/is (= ["text/html; charset=utf-8"]
(get-in item [:content :headers :content-type])))
(t/is (= "<h1>world</h1>" (get-in item [:content :body]))))))
(t/deftest send-several-mails-in-one-session-test
(let [from (h/random-address)]
(with-open [conn (core/connect mailhog-server)]
(core/send! conn {:from from :to "alice@example.com" :subject "hello" :body "world"})
(core/send! conn {:from from :to "bob@example.com" :subject "foo" :body "bar"}))
(let [resp (find-mail-by-from from)]
(t/is (= 2 (:total resp) (count (:items resp))))
(t/is (= [{:to ["bob@example.com"] :subject ["foo"]}
{:to ["alice@example.com"] :subject ["hello"]}]
(->> (:items resp)
(map #(-> % :content :headers (select-keys [:to :subject])))
(sort-by :subject)))))))
(t/deftest send-multipart-mixed-mail-test
(let [from (h/random-address)]
(with-open [conn (core/connect mailhog-server)]
(core/send! conn {:from from :to "alice@example.com" :subject "hello"
:body [{:content-type "text/plain" :content "world"}
{:content (io/file "project.clj")}]}))
(let [resp (find-mail-by-from from)
item (get-in resp [:items 0])
mime-parts (->> (get-in item [:mime :parts])
;; NOTE: mailhog contains blank part
drop-last)]
(t/is (= 1 (:total resp)))
(t/is (= 2 (count mime-parts)))
(t/is (str/starts-with? (get-in item [:content :headers :content-type 0])
"multipart/mixed; "))
(let [{:keys [headers body]} (first mime-parts)]
(t/is (= ["text/plain; charset=utf-8"]
(:content-type headers)))
(t/is (= "world" body)))
(let [{:keys [headers body]} (second mime-parts)]
(t/is (= ["text/x-clojure"] (:content-type headers)))
(t/is (= ["attachment; filename=project.clj"] (:content-disposition headers)))
(t/is (and (string? body) (not (str/blank? body))))))))
(t/deftest send-multipart-alternative-mail-test
(let [from (h/random-address)]
(with-open [conn (core/connect mailhog-server)]
(core/send! conn {:from from :to "alice@example.com" :subject "hello"
:multipart "alternative"
:body [{:content-type "text/plain" :content "world"}
{:content-type "text/html" :content "<p>world</p>"}]}))
(let [resp (find-mail-by-from from)
item (get-in resp [:items 0])
;; NOTE: mailhog contains blank part
mime-parts (drop-last (get-in item [:mime :parts]))]
(t/is (= 1 (:total resp)))
(t/is (= 2 (count mime-parts)))
(t/is (str/starts-with? (get-in item [:content :headers :content-type 0])
"multipart/alternative; "))
(let [{:keys [headers body]} (first mime-parts)]
(t/is (= ["text/plain; charset=utf-8"] (:content-type headers)))
(t/is (= "world" body)))
(let [{:keys [headers body]} (second mime-parts)]
(t/is (= ["text/html; charset=utf-8"] (:content-type headers)))
(t/is (= "<p>world</p>" body))))))
| 117370 | (ns tarayo.integration.send-test
(:require
[camel-snake-kebab.core :as csk]
[clojure.data.json :as json]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.test :as t]
[org.httpkit.client :as http]
[tarayo.core :as core]
[tarayo.test-helper :as h])
(:import
java.util.Calendar))
(def ^:private mailhog-server
{:host "localhost" :port 1025})
(def ^:private mailhog-search-api-endpoint
(format "http://%s:8025/api/v2/search" (:host mailhog-server)))
(def ^:private ^Calendar now
(doto (Calendar/getInstance)
(.set 2112 (dec 9) 3)))
(defn- find-mail-by-from
[from-address]
(let [resp @(http/get mailhog-search-api-endpoint
{:query-params {:kind "from" :query from-address}})]
(json/read-str (:body resp) :key-fn (comp keyword csk/->kebab-case))))
(t/deftest send-text-mail-test
(let [from (h/random-address)]
(with-open [conn (core/connect mailhog-server)]
(core/send! conn {:from from
:to "<EMAIL>"
:subject "hello"
:body "world"
:charset "UTF-8"
:date (.getTime now)}))
(let [resp (find-mail-by-from from)
item (get-in resp [:items 0])
headers (some-> item (get-in [:content :headers]))]
(t/is (= 1 (:total resp)))
(t/is (= 1 (count (:to item))))
(t/is (= {:mailbox "alice" :domain "example.com"}
(-> item :to first (select-keys [:mailbox :domain]))))
(t/is (= ["UTF-8"] (:charset headers)))
(t/is (= ["text/plain; charset=UTF-8"] (:content-type headers)))
(t/is (str/starts-with? (first (:date headers)) "Sat, 3 Sep 2112 "))
(t/is (= [from] (:from headers)))
(t/is (h/tarayo-message-id? (:message-id headers)))
(t/is (= ["hello"] (:subject headers)))
(t/is (= ["<EMAIL>"] (:to headers)))
(t/is (h/tarayo-user-agent? (:user-agent headers)))
(t/is (= "world" (get-in item [:content :body]))))))
(t/deftest send-html-mail-test
(let [from (h/random-address)]
(with-open [conn (core/connect mailhog-server)]
(core/send! conn {:from from :to "<EMAIL>" :subject "hello"
:body "<h1>world</h1>" :content-type "text/html"}))
(let [resp (find-mail-by-from from)
item (get-in resp [:items 0])]
(t/is (= 1 (:total resp)))
(t/is (= ["text/html; charset=utf-8"]
(get-in item [:content :headers :content-type])))
(t/is (= "<h1>world</h1>" (get-in item [:content :body]))))))
(t/deftest send-several-mails-in-one-session-test
(let [from (h/random-address)]
(with-open [conn (core/connect mailhog-server)]
(core/send! conn {:from from :to "<EMAIL>" :subject "hello" :body "world"})
(core/send! conn {:from from :to "<EMAIL>" :subject "foo" :body "bar"}))
(let [resp (find-mail-by-from from)]
(t/is (= 2 (:total resp) (count (:items resp))))
(t/is (= [{:to ["<EMAIL>"] :subject ["foo"]}
{:to ["<EMAIL>"] :subject ["hello"]}]
(->> (:items resp)
(map #(-> % :content :headers (select-keys [:to :subject])))
(sort-by :subject)))))))
(t/deftest send-multipart-mixed-mail-test
(let [from (h/random-address)]
(with-open [conn (core/connect mailhog-server)]
(core/send! conn {:from from :to "<EMAIL>" :subject "hello"
:body [{:content-type "text/plain" :content "world"}
{:content (io/file "project.clj")}]}))
(let [resp (find-mail-by-from from)
item (get-in resp [:items 0])
mime-parts (->> (get-in item [:mime :parts])
;; NOTE: mailhog contains blank part
drop-last)]
(t/is (= 1 (:total resp)))
(t/is (= 2 (count mime-parts)))
(t/is (str/starts-with? (get-in item [:content :headers :content-type 0])
"multipart/mixed; "))
(let [{:keys [headers body]} (first mime-parts)]
(t/is (= ["text/plain; charset=utf-8"]
(:content-type headers)))
(t/is (= "world" body)))
(let [{:keys [headers body]} (second mime-parts)]
(t/is (= ["text/x-clojure"] (:content-type headers)))
(t/is (= ["attachment; filename=project.clj"] (:content-disposition headers)))
(t/is (and (string? body) (not (str/blank? body))))))))
(t/deftest send-multipart-alternative-mail-test
(let [from (h/random-address)]
(with-open [conn (core/connect mailhog-server)]
(core/send! conn {:from from :to "<EMAIL>" :subject "hello"
:multipart "alternative"
:body [{:content-type "text/plain" :content "world"}
{:content-type "text/html" :content "<p>world</p>"}]}))
(let [resp (find-mail-by-from from)
item (get-in resp [:items 0])
;; NOTE: mailhog contains blank part
mime-parts (drop-last (get-in item [:mime :parts]))]
(t/is (= 1 (:total resp)))
(t/is (= 2 (count mime-parts)))
(t/is (str/starts-with? (get-in item [:content :headers :content-type 0])
"multipart/alternative; "))
(let [{:keys [headers body]} (first mime-parts)]
(t/is (= ["text/plain; charset=utf-8"] (:content-type headers)))
(t/is (= "world" body)))
(let [{:keys [headers body]} (second mime-parts)]
(t/is (= ["text/html; charset=utf-8"] (:content-type headers)))
(t/is (= "<p>world</p>" body))))))
| true | (ns tarayo.integration.send-test
(:require
[camel-snake-kebab.core :as csk]
[clojure.data.json :as json]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.test :as t]
[org.httpkit.client :as http]
[tarayo.core :as core]
[tarayo.test-helper :as h])
(:import
java.util.Calendar))
(def ^:private mailhog-server
{:host "localhost" :port 1025})
(def ^:private mailhog-search-api-endpoint
(format "http://%s:8025/api/v2/search" (:host mailhog-server)))
(def ^:private ^Calendar now
(doto (Calendar/getInstance)
(.set 2112 (dec 9) 3)))
(defn- find-mail-by-from
[from-address]
(let [resp @(http/get mailhog-search-api-endpoint
{:query-params {:kind "from" :query from-address}})]
(json/read-str (:body resp) :key-fn (comp keyword csk/->kebab-case))))
(t/deftest send-text-mail-test
(let [from (h/random-address)]
(with-open [conn (core/connect mailhog-server)]
(core/send! conn {:from from
:to "PI:EMAIL:<EMAIL>END_PI"
:subject "hello"
:body "world"
:charset "UTF-8"
:date (.getTime now)}))
(let [resp (find-mail-by-from from)
item (get-in resp [:items 0])
headers (some-> item (get-in [:content :headers]))]
(t/is (= 1 (:total resp)))
(t/is (= 1 (count (:to item))))
(t/is (= {:mailbox "alice" :domain "example.com"}
(-> item :to first (select-keys [:mailbox :domain]))))
(t/is (= ["UTF-8"] (:charset headers)))
(t/is (= ["text/plain; charset=UTF-8"] (:content-type headers)))
(t/is (str/starts-with? (first (:date headers)) "Sat, 3 Sep 2112 "))
(t/is (= [from] (:from headers)))
(t/is (h/tarayo-message-id? (:message-id headers)))
(t/is (= ["hello"] (:subject headers)))
(t/is (= ["PI:EMAIL:<EMAIL>END_PI"] (:to headers)))
(t/is (h/tarayo-user-agent? (:user-agent headers)))
(t/is (= "world" (get-in item [:content :body]))))))
(t/deftest send-html-mail-test
(let [from (h/random-address)]
(with-open [conn (core/connect mailhog-server)]
(core/send! conn {:from from :to "PI:EMAIL:<EMAIL>END_PI" :subject "hello"
:body "<h1>world</h1>" :content-type "text/html"}))
(let [resp (find-mail-by-from from)
item (get-in resp [:items 0])]
(t/is (= 1 (:total resp)))
(t/is (= ["text/html; charset=utf-8"]
(get-in item [:content :headers :content-type])))
(t/is (= "<h1>world</h1>" (get-in item [:content :body]))))))
(t/deftest send-several-mails-in-one-session-test
(let [from (h/random-address)]
(with-open [conn (core/connect mailhog-server)]
(core/send! conn {:from from :to "PI:EMAIL:<EMAIL>END_PI" :subject "hello" :body "world"})
(core/send! conn {:from from :to "PI:EMAIL:<EMAIL>END_PI" :subject "foo" :body "bar"}))
(let [resp (find-mail-by-from from)]
(t/is (= 2 (:total resp) (count (:items resp))))
(t/is (= [{:to ["PI:EMAIL:<EMAIL>END_PI"] :subject ["foo"]}
{:to ["PI:EMAIL:<EMAIL>END_PI"] :subject ["hello"]}]
(->> (:items resp)
(map #(-> % :content :headers (select-keys [:to :subject])))
(sort-by :subject)))))))
(t/deftest send-multipart-mixed-mail-test
(let [from (h/random-address)]
(with-open [conn (core/connect mailhog-server)]
(core/send! conn {:from from :to "PI:EMAIL:<EMAIL>END_PI" :subject "hello"
:body [{:content-type "text/plain" :content "world"}
{:content (io/file "project.clj")}]}))
(let [resp (find-mail-by-from from)
item (get-in resp [:items 0])
mime-parts (->> (get-in item [:mime :parts])
;; NOTE: mailhog contains blank part
drop-last)]
(t/is (= 1 (:total resp)))
(t/is (= 2 (count mime-parts)))
(t/is (str/starts-with? (get-in item [:content :headers :content-type 0])
"multipart/mixed; "))
(let [{:keys [headers body]} (first mime-parts)]
(t/is (= ["text/plain; charset=utf-8"]
(:content-type headers)))
(t/is (= "world" body)))
(let [{:keys [headers body]} (second mime-parts)]
(t/is (= ["text/x-clojure"] (:content-type headers)))
(t/is (= ["attachment; filename=project.clj"] (:content-disposition headers)))
(t/is (and (string? body) (not (str/blank? body))))))))
(t/deftest send-multipart-alternative-mail-test
(let [from (h/random-address)]
(with-open [conn (core/connect mailhog-server)]
(core/send! conn {:from from :to "PI:EMAIL:<EMAIL>END_PI" :subject "hello"
:multipart "alternative"
:body [{:content-type "text/plain" :content "world"}
{:content-type "text/html" :content "<p>world</p>"}]}))
(let [resp (find-mail-by-from from)
item (get-in resp [:items 0])
;; NOTE: mailhog contains blank part
mime-parts (drop-last (get-in item [:mime :parts]))]
(t/is (= 1 (:total resp)))
(t/is (= 2 (count mime-parts)))
(t/is (str/starts-with? (get-in item [:content :headers :content-type 0])
"multipart/alternative; "))
(let [{:keys [headers body]} (first mime-parts)]
(t/is (= ["text/plain; charset=utf-8"] (:content-type headers)))
(t/is (= "world" body)))
(let [{:keys [headers body]} (second mime-parts)]
(t/is (= ["text/html; charset=utf-8"] (:content-type headers)))
(t/is (= "<p>world</p>" body))))))
|
[
{
"context": "(ns ^{:author \"Tunde Ashafa\"}\n test-clutch\n (:require (com.ashafa.clutch\n ",
"end": 27,
"score": 0.9998500943183899,
"start": 15,
"tag": "NAME",
"value": "Tunde Ashafa"
},
{
"context": " (assoc (utils/url \"localhost\")\n; :username \"username\"\n; :password \"password\")\n(def test-host (or (",
"end": 673,
"score": 0.9407066702842712,
"start": 665,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ost\")\n; :username \"username\"\n; :password \"password\")\n(def test-host (or (System/getenv \"clutch_url\")",
"end": 700,
"score": 0.9993979930877686,
"start": 692,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " resources-path \"test\")\n\n(def test-docs [{:name \"John Smith\"\n :email \"john.smith@test.com\"\n ",
"end": 1228,
"score": 0.9996874332427979,
"start": 1218,
"tag": "NAME",
"value": "John Smith"
},
{
"context": "cs [{:name \"John Smith\"\n :email \"john.smith@test.com\"\n :score 65}\n {:na",
"end": 1274,
"score": 0.9999271631240845,
"start": 1255,
"tag": "EMAIL",
"value": "john.smith@test.com"
},
{
"context": " :score 65}\n {:name \"Jane Thompson\"\n :email \"jane.thompson@test.com\"",
"end": 1342,
"score": 0.9998846054077148,
"start": 1329,
"tag": "NAME",
"value": "Jane Thompson"
},
{
"context": " {:name \"Jane Thompson\"\n :email \"jane.thompson@test.com\"\n :score 98}\n {:na",
"end": 1391,
"score": 0.9999281167984009,
"start": 1369,
"tag": "EMAIL",
"value": "jane.thompson@test.com"
},
{
"context": " :score 98}\n {:name \"Robert Jones\"\n :email \"robert.jones@example.co",
"end": 1458,
"score": 0.9998922348022461,
"start": 1446,
"tag": "NAME",
"value": "Robert Jones"
},
{
"context": " {:name \"Robert Jones\"\n :email \"robert.jones@example.com\"\n :score 80}\n {:na",
"end": 1509,
"score": 0.9999295473098755,
"start": 1485,
"tag": "EMAIL",
"value": "robert.jones@example.com"
},
{
"context": " :score 80}\n {:name \"Sarah Parker\"\n :email \"sarah.parker@example.co",
"end": 1576,
"score": 0.9998913407325745,
"start": 1564,
"tag": "NAME",
"value": "Sarah Parker"
},
{
"context": " {:name \"Sarah Parker\"\n :email \"sarah.parker@example.com\"\n :score 59}])\n\n(def ^{:private t",
"end": 1627,
"score": 0.9999307990074158,
"start": 1603,
"tag": "EMAIL",
"value": "sarah.parker@example.com"
},
{
"context": "ment :_id))]\n (are [x y z] (= x y z)\n \"Robert Jones\" (created-document :name) (fetched-document :name",
"end": 5343,
"score": 0.9998178482055664,
"start": 5331,
"tag": "NAME",
"value": "Robert Jones"
},
{
"context": "ocument :name) (fetched-document :name)\n \"robert.jones@example.com\" (created-document :email) (fetched-document :ema",
"end": 5429,
"score": 0.9999222755432129,
"start": 5405,
"tag": "EMAIL",
"value": "robert.jones@example.com"
},
{
"context": "-document))]\n (are [x y z] (= x y z)\n \"Robert Jones\" (created-document :name) (fetched-document :name",
"end": 5902,
"score": 0.9979435205459595,
"start": 5890,
"tag": "NAME",
"value": "Robert Jones"
},
{
"context": "ocument :name) (fetched-document :name)\n \"robert.jones@example.com\" (created-document :email) (fetched-document :ema",
"end": 5988,
"score": 0.9999240636825562,
"start": 5964,
"tag": "EMAIL",
"value": "robert.jones@example.com"
},
{
"context": "]\n (update-document (get-document id) {:email \"test@example.com\"})\n (is (= \"test@example.com\" (:email (get-doc",
"end": 6787,
"score": 0.9999227523803711,
"start": 6771,
"tag": "EMAIL",
"value": "test@example.com"
},
{
"context": "ment id) {:email \"test@example.com\"})\n (is (= \"test@example.com\" (:email (get-document id)))))\n (testing \"no upd",
"end": 6819,
"score": 0.9999232292175293,
"start": 6803,
"tag": "EMAIL",
"value": "test@example.com"
},
{
"context": "update-document (merge (get-document id) {:email \"test@example.com\"}))\n (is (= \"test@example.com\" (:email (get-",
"end": 7011,
"score": 0.9999237060546875,
"start": 6995,
"tag": "EMAIL",
"value": "test@example.com"
},
{
"context": "t id) {:email \"test@example.com\"}))\n (is (= \"test@example.com\" (:email (get-document id)))))))\n\n(defdbtest upda",
"end": 7046,
"score": 0.9999229311943054,
"start": 7030,
"tag": "EMAIL",
"value": "test@example.com"
},
{
"context": " all-documents-ascending)\n (are [name] (= \"Sarah Parker\" name)\n (-> all-documents-descending firs",
"end": 9567,
"score": 0.9997139573097229,
"start": 9555,
"tag": "NAME",
"value": "Sarah Parker"
},
{
"context": "cuments-matching-keys all-documents]\n (is (= [\"John Smith\" \"Jane Thompson\"]\n (map #(-> % :doc :na",
"end": 9987,
"score": 0.9998236894607544,
"start": 9977,
"tag": "NAME",
"value": "John Smith"
},
{
"context": "ing-keys all-documents]\n (is (= [\"John Smith\" \"Jane Thompson\"]\n (map #(-> % :doc :name) all-document",
"end": 10003,
"score": 0.9998725056648254,
"start": 9990,
"tag": "NAME",
"value": "Jane Thompson"
}
] | test/test_clutch.clj | jalpedersen/clutch | 0 | (ns ^{:author "Tunde Ashafa"}
test-clutch
(:require (com.ashafa.clutch
[http-client :as http-client]
[utils :as utils])
[clojure.string :as str]
[clojure.java.io :as io])
(:use com.ashafa.clutch
[cemerick.url :only (url)]
[slingshot.slingshot :only (throw+ try+)]
clojure.set
clojure.test)
(:import (java.io File ByteArrayInputStream FileInputStream ByteArrayOutputStream)
(java.net URL))
(:refer-clojure :exclude (conj! assoc! dissoc!)))
; Can be e.g.
; "https://username:password@account.cloudant.com" or
; (assoc (utils/url "localhost")
; :username "username"
; :password "password")
(def test-host (or (System/getenv "clutch_url") "http://localhost:5984"))
;;Make sure that the "out" directory exists (otherwise, constants_table.js is not generated)
(.mkdir (java.io.File. "out"))
(println "Testing using Clojure" *clojure-version*
"on Java" (System/getProperty "java.version")
"=>>" (-> test-host url (assoc :username nil :password nil) str))
(println "CouchDB server info:" (couchdb-info-with-db (-> test-host url str)))
(def resources-path "test")
(def test-docs [{:name "John Smith"
:email "john.smith@test.com"
:score 65}
{:name "Jane Thompson"
:email "jane.thompson@test.com"
:score 98}
{:name "Robert Jones"
:email "robert.jones@example.com"
:score 80}
{:name "Sarah Parker"
:email "sarah.parker@example.com"
:score 59}])
(def ^{:private true} to-byte-array @#'com.ashafa.clutch/to-byte-array)
(declare ^{:dynamic true} *test-database*)
(defn test-database-name
[test-name]
(str "test-db-" (str/replace (str test-name) #"[^$]+\$([^@]+)@.*" "$1")))
(defn test-database-url
[db-name]
(utils/url (utils/url test-host) db-name))
(defmacro defdbtest [name & body]
`(deftest ~name
(binding [*test-database* (get-database-with-db (test-database-url (test-database-name ~name)))]
(try
(with-db *test-database* ~@body)
(finally
(delete-database-with-db *test-database*))))))
(deftest check-couchdb-connection
(is (= "Welcome" (:couchdb (couchdb-info-with-db (test-database-url nil))))))
(deftest get-list-check-and-delete-database
(let [name "clutch_test_db"
url (test-database-url name)
*test-database* (get-database-with-db url)]
(is (= name (:db_name *test-database*)))
(is ((set (all-databases-with-db url)) name))
(is (= name (:db_name (database-info-with-db url))))
(is (:ok (delete-database-with-db url)))
(is (nil? ((set (all-databases-with-db url)) name)))))
(deftest database-name-escaping
(let [name (test-database-name "foo_$()+-/bar")
url (test-database-url name)]
(try
(let [dbinfo (get-database-with-db url)]
(is (= name (:db_name dbinfo))))
(put-document-with-db url {:_id "a" :b 0})
(is (= 0 (:b (get-document-with-db url "a"))))
(delete-document-with-db url (get-document-with-db url "a"))
(is (nil? (get-document-with-db url "a")))
(finally
(delete-database-with-db url)))))
(defn- valid-id-charcode?
[code]
(cond
; c.c.json doesn't cope well with the responses provided when CR or LF are included
(#{10 13} code) false
; D800–DFFF only used in surrogate pairs, invalid anywhere else (couch chokes on them)
(and (>= code 0xd800) (<= code 0xdfff)) false
(> code @#'com.ashafa.clutch/highest-supported-charcode) false
:else true))
; create a document containing each of the 65K chars in unicode BMP.
; this ensures that utils/id-encode is doing what it should and that we aren't screwing up
; encoding issues generally (which are easy regressions to introduce)
(defdbtest test-docid-encoding
; doing a lot of requests here -- the test is crazy-slow if delayed_commit=false,
; so let's use the iron we've got
(doseq [x (range 0xffff)
:when (valid-id-charcode? x)
:let [id (str "a" (char x)) ; doc ids can't start with _, so prefix everything
id-desc (str x " " id)]]
(try
(is (= id (:_id (put-document {:_id id}))) id-desc)
(let [doc (get-document id)]
(is (= {} (dissoc-meta doc)))
(delete-document doc)
(is (nil? (get-document id))))
(catch Exception e
(is false (str "Error for " id-desc ": " (.getMessage e)))))))
(defdbtest create-a-document
(let [document (put-document (first test-docs))]
(are [k] (contains? document k)
:_id :_rev)))
(defdbtest create-a-document-with-id
(let [document (put-document (first test-docs) :id "my_id")]
(is (= "my_id" (document :_id)))))
(defdbtest test-exists
(put-document {:_id "foo" :a 5})
(is (not (document-exists? "bar")))
(is (document-exists? "foo")))
(defrecord Foo [a])
(defdbtest create-with-record
(let [rec (put-document (Foo. "bar") :id "docid")]
(is (instance? Foo rec)))
(is (= "bar" (-> "docid" get-document :a))))
(defdbtest get-a-document
(let [created-document (put-document (nth test-docs 2))
fetched-document (get-document (created-document :_id))]
(are [x y z] (= x y z)
"Robert Jones" (created-document :name) (fetched-document :name)
"robert.jones@example.com" (created-document :email) (fetched-document :email)
80 (created-document :score) (fetched-document :score))))
(defdbtest get-a-document-revision
(let [created-document (put-document (nth test-docs 2))
updated-doc (update-document (assoc created-document :newentry 1))
fetched-document (get-document (:_id created-document)
:rev (:_rev created-document))]
(are [x y z] (= x y z)
"Robert Jones" (created-document :name) (fetched-document :name)
"robert.jones@example.com" (created-document :email) (fetched-document :email)
80 (:score created-document) (:score fetched-document)
nil (:newentry created-document) (:newentry fetched-document))
(is (= 1 (:newentry updated-doc)))))
(defmacro failing-request
[expected-status & body]
`(binding [http-client/*response* nil]
(try+
~@body
(assert false)
(catch identity ex#
(is (== ~expected-status (:status ex#)))
(is (map? http-client/*response*))))))
(defdbtest verify-response-code-access
(put-document (first test-docs) :id "some_id")
(failing-request 409 (put-document (first test-docs) :id "some_id")))
(defdbtest update-a-document
(let [id (:_id (put-document (nth test-docs 3)))]
(update-document (get-document id) {:email "test@example.com"})
(is (= "test@example.com" (:email (get-document id)))))
(testing "no update map or fn"
(let [id (:_id (put-document (nth test-docs 3)))]
(update-document (merge (get-document id) {:email "test@example.com"}))
(is (= "test@example.com" (:email (get-document id)))))))
(defdbtest update-a-document-with-a-function
(let [id (:_id (put-document (nth test-docs 2)))]
(update-document (get-document id) update-in [:score] + 3)
(is (= 83 (:score (get-document id))))))
(defdbtest update-with-updated-map
(-> (nth test-docs 2)
(put-document :id "docid")
(assoc :a "bar")
update-document)
(is (= "bar" (-> "docid" get-document :a))))
(defdbtest update-with-record
(let [rec (-> (Foo. "bar")
(merge (put-document {} :id "docid"))
update-document)]
(is (instance? Foo rec)))
(is (= "bar" (-> "docid" get-document :a))))
(defdbtest delete-a-document
(put-document (second test-docs) :id "my_id")
(is (get-document "my_id"))
(is (true? (:ok (delete-document (get-document "my_id")))))
(is (nil? (get-document "my_id"))))
(defdbtest copy-a-document
(let [doc (put-document (first test-docs) :id "src")]
(copy-document "src" "dst")
(copy-document doc "dst2")
(is (= (dissoc-meta doc)
(-> "dst" get-document dissoc-meta)
(-> "dst2" get-document dissoc-meta)))))
(defdbtest copy-document-overwrite
(let [doc (put-document (first test-docs) :id "src")
overwrite (put-document (second test-docs) :id "overwrite")]
(copy-document doc overwrite)
(is (= (dissoc-meta doc) (dissoc-meta (get-document "overwrite"))))))
(defdbtest copy-document-attachments
(let [doc (put-document (first test-docs) :id "src")
file (File. (str resources-path "/couchdb.png"))
doc (put-attachment doc file :filename :image)
doc (-> doc :id get-document)]
(copy-document "src" "dest")
(let [copy (get-document "dest")
copied-attachment (get-attachment copy :image)]
(is (= (dissoc-meta doc) (dissoc-meta copy)))
(is (= (-> file to-byte-array seq)
(-> copied-attachment to-byte-array seq))))))
(defdbtest copy-document-fail-overwrite
(put-document (first test-docs) :id "src")
(put-document (second test-docs) :id "overwrite")
(failing-request 409 (copy-document "src" "overwrite")))
(defdbtest get-all-documents-with-query-parameters
(bulk-update test-docs)
(let [all-documents-descending (all-documents {:include_docs true :descending true})
all-documents-ascending (all-documents {:include_docs true :descending false})]
(are [results] (= 4 (:total_rows (meta results)))
all-documents-descending
all-documents-ascending)
(are [name] (= "Sarah Parker" name)
(-> all-documents-descending first :doc :name)
(-> all-documents-ascending last :doc :name))))
(defdbtest get-all-documents-with-post-keys
(doseq [[n x] (keep-indexed vector test-docs)]
(put-document x :id (str (inc n))))
(let [all-documents (all-documents {:include_docs true} {:keys ["1" "2"]})
all-documents-matching-keys all-documents]
(is (= ["John Smith" "Jane Thompson"]
(map #(-> % :doc :name) all-documents-matching-keys)))
(is (= 4 (:total_rows (meta all-documents))))))
(defdbtest bulk-update-new-documents
(bulk-update test-docs)
(is (= 4 (:total_rows (meta (all-documents))))))
(defdbtest bulk-update-documents
(bulk-update test-docs)
(bulk-update (->> (all-documents {:include_docs true})
(map :doc)
(map #(assoc % :updated true))))
(is (every? true? (map #(-> % :doc :updated) (all-documents {:include_docs true})))))
(defdbtest inline-attachments
(let [clojure-img-file (str resources-path "/clojure.png")
couchdb-img-file (str resources-path "/couchdb.png")
couch-filename :couchdb.png
bytes-filename :couchdbbytes.png
created-document (put-document (nth test-docs 3)
:attachments [clojure-img-file
{:data (to-byte-array (FileInputStream. couchdb-img-file))
:data-length (-> couchdb-img-file File. .length)
:filename bytes-filename :mime-type "image/png"}
{:data (FileInputStream. couchdb-img-file)
:data-length (-> couchdb-img-file File. .length)
:filename couch-filename :mime-type "image/png"}])
fetched-document (get-document (created-document :_id))]
(are [attachment-keys] (= #{:clojure.png couch-filename bytes-filename} attachment-keys)
(set (keys (created-document :_attachments)))
(set (keys (fetched-document :_attachments))))
(are [doc file-key] (= "image/png" (-> doc :_attachments file-key :content_type))
created-document :clojure.png
fetched-document :clojure.png
created-document couch-filename
fetched-document couch-filename
created-document bytes-filename
fetched-document bytes-filename)
(are [path file-key] (= (.length (File. path)) (-> fetched-document :_attachments file-key :length))
clojure-img-file :clojure.png
couchdb-img-file couch-filename
couchdb-img-file bytes-filename)))
#_(defdbtest standalone-attachments
(let [document (put-document (first test-docs))
path (str resources-path "/couchdb.png")
filename-with-space (keyword "couchdb - image2")
updated-document-meta (put-attachment document path :filename :couchdb-image)
updated-document-meta (put-attachment (assoc document :_rev (:rev updated-document-meta))
(FileInputStream. path)
:filename filename-with-space
:mime-type "image/png"
:data-length (-> path File. .length))
updated-document-meta (put-attachment (assoc document :_rev (:rev updated-document-meta))
(to-byte-array (FileInputStream. path))
:filename :bytes-image :mime-type "image/png"
:data-length (-> path File. .length))
_ (.println System/out (pr-str (String.
(com.ashafa.clutch.http-client/couchdb-request :get
(-> (cemerick.url/url *test-database* (updated-document-meta :id))
(assoc :query {:attachments true}
:as :byte-array)))
"UTF-8")))
_ (do (flush) (Thread/sleep 5000))
#_#_document-with-attachments (get-document (updated-document-meta :id) :attachments true)]
#_((is (= #{:couchdb-image filename-with-space :bytes-image} (set (keys (:_attachments document-with-attachments)))))
(is (= "image/png" (-> document-with-attachments :_attachments :couchdb-image :content_type)))
(is (contains? (-> document-with-attachments :_attachments :couchdb-image) :data))
(is (= (-> document-with-attachments :_attachments :couchdb-image (select-keys [:data :content_type :length]))
(-> document-with-attachments :_attachments filename-with-space (select-keys [:data :content_type :length]))
(-> document-with-attachments :_attachments :bytes-image (select-keys [:data :content_type :length]))))
(is (thrown? IllegalArgumentException (put-attachment document (Object.))))
(is (thrown? IllegalArgumentException (put-attachment document (ByteArrayInputStream. (make-array Byte/TYPE 0))))))))
(defdbtest stream-attachments
(let [document (put-document (nth test-docs 3))
updated-document-meta (put-attachment document (str resources-path "/couchdb.png")
:filename :couchdb-image
:mime-type "other/mimetype")
document-with-attachments (get-document (updated-document-meta :id))
data (to-byte-array (java.io.File. (str resources-path "/couchdb.png")))]
(is (= "other/mimetype" (-> document-with-attachments :_attachments :couchdb-image :content_type)))
(is (= (seq data) (-> (get-attachment document-with-attachments :couchdb-image) to-byte-array seq)))))
(deftest replicate-a-database
(let [source (url test-host "source_test_db")
target (url test-host "target_test_db")]
(try
(get-database-with-db source)
(get-database-with-db target)
(bulk-update-with-db source test-docs)
(replicate-database-with-db source target)
(is (= 4 (:total_rows (meta (all-documents-with-db target)))))
(finally
(delete-database-with-db source)
(delete-database-with-db target)))))
(defn report-change
[description & forms]
(doseq [result forms]
(println (str "Testing changes: '" description "'") (if result "passed" "failed"))))
(defn check-id-changes-test
[description change-meta]
(if-not (:last_seq change-meta)
(report-change description
(is (= (:id change-meta) "target-id")))))
(defn check-seq-changes-test
[description change-meta]
(if-not (:last_seq change-meta)
(report-change description
(is (= (:seq change-meta) 1)))))
(defn check-delete-changes-test
[description change-meta]
(if (:deleted change-meta)
(report-change description
(is (= (:id change-meta) "target-id"))
(is (= (:seq change-meta) 5)))))
(deftest direct-db-config-usage
(let [db (test-database-url "direct-db-config-usage")]
(try
(create-database-with-db db)
(let [doc (put-document-with-db db (first test-docs) :id "foo")]
(update-document-with-db db doc {:a 5})
(is (= (assoc (first test-docs) :a 5) (dissoc-meta (get-document-with-db db "foo")))))
(finally
(delete-database-with-db db)))))
(deftest multiple-binding-levels
(let [db1 (test-database-url "multiple-binding-levels")
db2 (test-database-url "multiple-binding-levels2")]
(with-db db1
(try
(is (= "multiple-binding-levels" (:db_name (get-database))))
(put-document {} :id "1")
(with-db db2
(try
(is (= "multiple-binding-levels2" (:db_name (get-database))))
(is (nil? (get-document "1")))
(let [doc (put-document {} :id "2")]
(update-document doc {:a 5})
(is (= {:a 5} (dissoc-meta (get-document "2")))))
(finally
(delete-database))))
(is (nil? (get-document "2")))
(finally
(delete-database))))))
| 6415 | (ns ^{:author "<NAME>"}
test-clutch
(:require (com.ashafa.clutch
[http-client :as http-client]
[utils :as utils])
[clojure.string :as str]
[clojure.java.io :as io])
(:use com.ashafa.clutch
[cemerick.url :only (url)]
[slingshot.slingshot :only (throw+ try+)]
clojure.set
clojure.test)
(:import (java.io File ByteArrayInputStream FileInputStream ByteArrayOutputStream)
(java.net URL))
(:refer-clojure :exclude (conj! assoc! dissoc!)))
; Can be e.g.
; "https://username:password@account.cloudant.com" or
; (assoc (utils/url "localhost")
; :username "username"
; :password "<PASSWORD>")
(def test-host (or (System/getenv "clutch_url") "http://localhost:5984"))
;;Make sure that the "out" directory exists (otherwise, constants_table.js is not generated)
(.mkdir (java.io.File. "out"))
(println "Testing using Clojure" *clojure-version*
"on Java" (System/getProperty "java.version")
"=>>" (-> test-host url (assoc :username nil :password nil) str))
(println "CouchDB server info:" (couchdb-info-with-db (-> test-host url str)))
(def resources-path "test")
(def test-docs [{:name "<NAME>"
:email "<EMAIL>"
:score 65}
{:name "<NAME>"
:email "<EMAIL>"
:score 98}
{:name "<NAME>"
:email "<EMAIL>"
:score 80}
{:name "<NAME>"
:email "<EMAIL>"
:score 59}])
(def ^{:private true} to-byte-array @#'com.ashafa.clutch/to-byte-array)
(declare ^{:dynamic true} *test-database*)
(defn test-database-name
[test-name]
(str "test-db-" (str/replace (str test-name) #"[^$]+\$([^@]+)@.*" "$1")))
(defn test-database-url
[db-name]
(utils/url (utils/url test-host) db-name))
(defmacro defdbtest [name & body]
`(deftest ~name
(binding [*test-database* (get-database-with-db (test-database-url (test-database-name ~name)))]
(try
(with-db *test-database* ~@body)
(finally
(delete-database-with-db *test-database*))))))
(deftest check-couchdb-connection
(is (= "Welcome" (:couchdb (couchdb-info-with-db (test-database-url nil))))))
(deftest get-list-check-and-delete-database
(let [name "clutch_test_db"
url (test-database-url name)
*test-database* (get-database-with-db url)]
(is (= name (:db_name *test-database*)))
(is ((set (all-databases-with-db url)) name))
(is (= name (:db_name (database-info-with-db url))))
(is (:ok (delete-database-with-db url)))
(is (nil? ((set (all-databases-with-db url)) name)))))
(deftest database-name-escaping
(let [name (test-database-name "foo_$()+-/bar")
url (test-database-url name)]
(try
(let [dbinfo (get-database-with-db url)]
(is (= name (:db_name dbinfo))))
(put-document-with-db url {:_id "a" :b 0})
(is (= 0 (:b (get-document-with-db url "a"))))
(delete-document-with-db url (get-document-with-db url "a"))
(is (nil? (get-document-with-db url "a")))
(finally
(delete-database-with-db url)))))
(defn- valid-id-charcode?
[code]
(cond
; c.c.json doesn't cope well with the responses provided when CR or LF are included
(#{10 13} code) false
; D800–DFFF only used in surrogate pairs, invalid anywhere else (couch chokes on them)
(and (>= code 0xd800) (<= code 0xdfff)) false
(> code @#'com.ashafa.clutch/highest-supported-charcode) false
:else true))
; create a document containing each of the 65K chars in unicode BMP.
; this ensures that utils/id-encode is doing what it should and that we aren't screwing up
; encoding issues generally (which are easy regressions to introduce)
(defdbtest test-docid-encoding
; doing a lot of requests here -- the test is crazy-slow if delayed_commit=false,
; so let's use the iron we've got
(doseq [x (range 0xffff)
:when (valid-id-charcode? x)
:let [id (str "a" (char x)) ; doc ids can't start with _, so prefix everything
id-desc (str x " " id)]]
(try
(is (= id (:_id (put-document {:_id id}))) id-desc)
(let [doc (get-document id)]
(is (= {} (dissoc-meta doc)))
(delete-document doc)
(is (nil? (get-document id))))
(catch Exception e
(is false (str "Error for " id-desc ": " (.getMessage e)))))))
(defdbtest create-a-document
(let [document (put-document (first test-docs))]
(are [k] (contains? document k)
:_id :_rev)))
(defdbtest create-a-document-with-id
(let [document (put-document (first test-docs) :id "my_id")]
(is (= "my_id" (document :_id)))))
(defdbtest test-exists
(put-document {:_id "foo" :a 5})
(is (not (document-exists? "bar")))
(is (document-exists? "foo")))
(defrecord Foo [a])
(defdbtest create-with-record
(let [rec (put-document (Foo. "bar") :id "docid")]
(is (instance? Foo rec)))
(is (= "bar" (-> "docid" get-document :a))))
(defdbtest get-a-document
(let [created-document (put-document (nth test-docs 2))
fetched-document (get-document (created-document :_id))]
(are [x y z] (= x y z)
"<NAME>" (created-document :name) (fetched-document :name)
"<EMAIL>" (created-document :email) (fetched-document :email)
80 (created-document :score) (fetched-document :score))))
(defdbtest get-a-document-revision
(let [created-document (put-document (nth test-docs 2))
updated-doc (update-document (assoc created-document :newentry 1))
fetched-document (get-document (:_id created-document)
:rev (:_rev created-document))]
(are [x y z] (= x y z)
"<NAME>" (created-document :name) (fetched-document :name)
"<EMAIL>" (created-document :email) (fetched-document :email)
80 (:score created-document) (:score fetched-document)
nil (:newentry created-document) (:newentry fetched-document))
(is (= 1 (:newentry updated-doc)))))
(defmacro failing-request
[expected-status & body]
`(binding [http-client/*response* nil]
(try+
~@body
(assert false)
(catch identity ex#
(is (== ~expected-status (:status ex#)))
(is (map? http-client/*response*))))))
(defdbtest verify-response-code-access
(put-document (first test-docs) :id "some_id")
(failing-request 409 (put-document (first test-docs) :id "some_id")))
(defdbtest update-a-document
(let [id (:_id (put-document (nth test-docs 3)))]
(update-document (get-document id) {:email "<EMAIL>"})
(is (= "<EMAIL>" (:email (get-document id)))))
(testing "no update map or fn"
(let [id (:_id (put-document (nth test-docs 3)))]
(update-document (merge (get-document id) {:email "<EMAIL>"}))
(is (= "<EMAIL>" (:email (get-document id)))))))
(defdbtest update-a-document-with-a-function
(let [id (:_id (put-document (nth test-docs 2)))]
(update-document (get-document id) update-in [:score] + 3)
(is (= 83 (:score (get-document id))))))
(defdbtest update-with-updated-map
(-> (nth test-docs 2)
(put-document :id "docid")
(assoc :a "bar")
update-document)
(is (= "bar" (-> "docid" get-document :a))))
(defdbtest update-with-record
(let [rec (-> (Foo. "bar")
(merge (put-document {} :id "docid"))
update-document)]
(is (instance? Foo rec)))
(is (= "bar" (-> "docid" get-document :a))))
(defdbtest delete-a-document
(put-document (second test-docs) :id "my_id")
(is (get-document "my_id"))
(is (true? (:ok (delete-document (get-document "my_id")))))
(is (nil? (get-document "my_id"))))
(defdbtest copy-a-document
(let [doc (put-document (first test-docs) :id "src")]
(copy-document "src" "dst")
(copy-document doc "dst2")
(is (= (dissoc-meta doc)
(-> "dst" get-document dissoc-meta)
(-> "dst2" get-document dissoc-meta)))))
(defdbtest copy-document-overwrite
(let [doc (put-document (first test-docs) :id "src")
overwrite (put-document (second test-docs) :id "overwrite")]
(copy-document doc overwrite)
(is (= (dissoc-meta doc) (dissoc-meta (get-document "overwrite"))))))
(defdbtest copy-document-attachments
(let [doc (put-document (first test-docs) :id "src")
file (File. (str resources-path "/couchdb.png"))
doc (put-attachment doc file :filename :image)
doc (-> doc :id get-document)]
(copy-document "src" "dest")
(let [copy (get-document "dest")
copied-attachment (get-attachment copy :image)]
(is (= (dissoc-meta doc) (dissoc-meta copy)))
(is (= (-> file to-byte-array seq)
(-> copied-attachment to-byte-array seq))))))
(defdbtest copy-document-fail-overwrite
(put-document (first test-docs) :id "src")
(put-document (second test-docs) :id "overwrite")
(failing-request 409 (copy-document "src" "overwrite")))
(defdbtest get-all-documents-with-query-parameters
(bulk-update test-docs)
(let [all-documents-descending (all-documents {:include_docs true :descending true})
all-documents-ascending (all-documents {:include_docs true :descending false})]
(are [results] (= 4 (:total_rows (meta results)))
all-documents-descending
all-documents-ascending)
(are [name] (= "<NAME>" name)
(-> all-documents-descending first :doc :name)
(-> all-documents-ascending last :doc :name))))
(defdbtest get-all-documents-with-post-keys
(doseq [[n x] (keep-indexed vector test-docs)]
(put-document x :id (str (inc n))))
(let [all-documents (all-documents {:include_docs true} {:keys ["1" "2"]})
all-documents-matching-keys all-documents]
(is (= ["<NAME>" "<NAME>"]
(map #(-> % :doc :name) all-documents-matching-keys)))
(is (= 4 (:total_rows (meta all-documents))))))
(defdbtest bulk-update-new-documents
(bulk-update test-docs)
(is (= 4 (:total_rows (meta (all-documents))))))
(defdbtest bulk-update-documents
(bulk-update test-docs)
(bulk-update (->> (all-documents {:include_docs true})
(map :doc)
(map #(assoc % :updated true))))
(is (every? true? (map #(-> % :doc :updated) (all-documents {:include_docs true})))))
(defdbtest inline-attachments
(let [clojure-img-file (str resources-path "/clojure.png")
couchdb-img-file (str resources-path "/couchdb.png")
couch-filename :couchdb.png
bytes-filename :couchdbbytes.png
created-document (put-document (nth test-docs 3)
:attachments [clojure-img-file
{:data (to-byte-array (FileInputStream. couchdb-img-file))
:data-length (-> couchdb-img-file File. .length)
:filename bytes-filename :mime-type "image/png"}
{:data (FileInputStream. couchdb-img-file)
:data-length (-> couchdb-img-file File. .length)
:filename couch-filename :mime-type "image/png"}])
fetched-document (get-document (created-document :_id))]
(are [attachment-keys] (= #{:clojure.png couch-filename bytes-filename} attachment-keys)
(set (keys (created-document :_attachments)))
(set (keys (fetched-document :_attachments))))
(are [doc file-key] (= "image/png" (-> doc :_attachments file-key :content_type))
created-document :clojure.png
fetched-document :clojure.png
created-document couch-filename
fetched-document couch-filename
created-document bytes-filename
fetched-document bytes-filename)
(are [path file-key] (= (.length (File. path)) (-> fetched-document :_attachments file-key :length))
clojure-img-file :clojure.png
couchdb-img-file couch-filename
couchdb-img-file bytes-filename)))
#_(defdbtest standalone-attachments
(let [document (put-document (first test-docs))
path (str resources-path "/couchdb.png")
filename-with-space (keyword "couchdb - image2")
updated-document-meta (put-attachment document path :filename :couchdb-image)
updated-document-meta (put-attachment (assoc document :_rev (:rev updated-document-meta))
(FileInputStream. path)
:filename filename-with-space
:mime-type "image/png"
:data-length (-> path File. .length))
updated-document-meta (put-attachment (assoc document :_rev (:rev updated-document-meta))
(to-byte-array (FileInputStream. path))
:filename :bytes-image :mime-type "image/png"
:data-length (-> path File. .length))
_ (.println System/out (pr-str (String.
(com.ashafa.clutch.http-client/couchdb-request :get
(-> (cemerick.url/url *test-database* (updated-document-meta :id))
(assoc :query {:attachments true}
:as :byte-array)))
"UTF-8")))
_ (do (flush) (Thread/sleep 5000))
#_#_document-with-attachments (get-document (updated-document-meta :id) :attachments true)]
#_((is (= #{:couchdb-image filename-with-space :bytes-image} (set (keys (:_attachments document-with-attachments)))))
(is (= "image/png" (-> document-with-attachments :_attachments :couchdb-image :content_type)))
(is (contains? (-> document-with-attachments :_attachments :couchdb-image) :data))
(is (= (-> document-with-attachments :_attachments :couchdb-image (select-keys [:data :content_type :length]))
(-> document-with-attachments :_attachments filename-with-space (select-keys [:data :content_type :length]))
(-> document-with-attachments :_attachments :bytes-image (select-keys [:data :content_type :length]))))
(is (thrown? IllegalArgumentException (put-attachment document (Object.))))
(is (thrown? IllegalArgumentException (put-attachment document (ByteArrayInputStream. (make-array Byte/TYPE 0))))))))
(defdbtest stream-attachments
(let [document (put-document (nth test-docs 3))
updated-document-meta (put-attachment document (str resources-path "/couchdb.png")
:filename :couchdb-image
:mime-type "other/mimetype")
document-with-attachments (get-document (updated-document-meta :id))
data (to-byte-array (java.io.File. (str resources-path "/couchdb.png")))]
(is (= "other/mimetype" (-> document-with-attachments :_attachments :couchdb-image :content_type)))
(is (= (seq data) (-> (get-attachment document-with-attachments :couchdb-image) to-byte-array seq)))))
(deftest replicate-a-database
(let [source (url test-host "source_test_db")
target (url test-host "target_test_db")]
(try
(get-database-with-db source)
(get-database-with-db target)
(bulk-update-with-db source test-docs)
(replicate-database-with-db source target)
(is (= 4 (:total_rows (meta (all-documents-with-db target)))))
(finally
(delete-database-with-db source)
(delete-database-with-db target)))))
(defn report-change
[description & forms]
(doseq [result forms]
(println (str "Testing changes: '" description "'") (if result "passed" "failed"))))
(defn check-id-changes-test
[description change-meta]
(if-not (:last_seq change-meta)
(report-change description
(is (= (:id change-meta) "target-id")))))
(defn check-seq-changes-test
[description change-meta]
(if-not (:last_seq change-meta)
(report-change description
(is (= (:seq change-meta) 1)))))
(defn check-delete-changes-test
[description change-meta]
(if (:deleted change-meta)
(report-change description
(is (= (:id change-meta) "target-id"))
(is (= (:seq change-meta) 5)))))
(deftest direct-db-config-usage
(let [db (test-database-url "direct-db-config-usage")]
(try
(create-database-with-db db)
(let [doc (put-document-with-db db (first test-docs) :id "foo")]
(update-document-with-db db doc {:a 5})
(is (= (assoc (first test-docs) :a 5) (dissoc-meta (get-document-with-db db "foo")))))
(finally
(delete-database-with-db db)))))
(deftest multiple-binding-levels
(let [db1 (test-database-url "multiple-binding-levels")
db2 (test-database-url "multiple-binding-levels2")]
(with-db db1
(try
(is (= "multiple-binding-levels" (:db_name (get-database))))
(put-document {} :id "1")
(with-db db2
(try
(is (= "multiple-binding-levels2" (:db_name (get-database))))
(is (nil? (get-document "1")))
(let [doc (put-document {} :id "2")]
(update-document doc {:a 5})
(is (= {:a 5} (dissoc-meta (get-document "2")))))
(finally
(delete-database))))
(is (nil? (get-document "2")))
(finally
(delete-database))))))
| true | (ns ^{:author "PI:NAME:<NAME>END_PI"}
test-clutch
(:require (com.ashafa.clutch
[http-client :as http-client]
[utils :as utils])
[clojure.string :as str]
[clojure.java.io :as io])
(:use com.ashafa.clutch
[cemerick.url :only (url)]
[slingshot.slingshot :only (throw+ try+)]
clojure.set
clojure.test)
(:import (java.io File ByteArrayInputStream FileInputStream ByteArrayOutputStream)
(java.net URL))
(:refer-clojure :exclude (conj! assoc! dissoc!)))
; Can be e.g.
; "https://username:password@account.cloudant.com" or
; (assoc (utils/url "localhost")
; :username "username"
; :password "PI:PASSWORD:<PASSWORD>END_PI")
(def test-host (or (System/getenv "clutch_url") "http://localhost:5984"))
;;Make sure that the "out" directory exists (otherwise, constants_table.js is not generated)
(.mkdir (java.io.File. "out"))
(println "Testing using Clojure" *clojure-version*
"on Java" (System/getProperty "java.version")
"=>>" (-> test-host url (assoc :username nil :password nil) str))
(println "CouchDB server info:" (couchdb-info-with-db (-> test-host url str)))
(def resources-path "test")
(def test-docs [{:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:score 65}
{:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:score 98}
{:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:score 80}
{:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:score 59}])
(def ^{:private true} to-byte-array @#'com.ashafa.clutch/to-byte-array)
(declare ^{:dynamic true} *test-database*)
(defn test-database-name
[test-name]
(str "test-db-" (str/replace (str test-name) #"[^$]+\$([^@]+)@.*" "$1")))
(defn test-database-url
[db-name]
(utils/url (utils/url test-host) db-name))
(defmacro defdbtest [name & body]
`(deftest ~name
(binding [*test-database* (get-database-with-db (test-database-url (test-database-name ~name)))]
(try
(with-db *test-database* ~@body)
(finally
(delete-database-with-db *test-database*))))))
(deftest check-couchdb-connection
(is (= "Welcome" (:couchdb (couchdb-info-with-db (test-database-url nil))))))
(deftest get-list-check-and-delete-database
(let [name "clutch_test_db"
url (test-database-url name)
*test-database* (get-database-with-db url)]
(is (= name (:db_name *test-database*)))
(is ((set (all-databases-with-db url)) name))
(is (= name (:db_name (database-info-with-db url))))
(is (:ok (delete-database-with-db url)))
(is (nil? ((set (all-databases-with-db url)) name)))))
(deftest database-name-escaping
(let [name (test-database-name "foo_$()+-/bar")
url (test-database-url name)]
(try
(let [dbinfo (get-database-with-db url)]
(is (= name (:db_name dbinfo))))
(put-document-with-db url {:_id "a" :b 0})
(is (= 0 (:b (get-document-with-db url "a"))))
(delete-document-with-db url (get-document-with-db url "a"))
(is (nil? (get-document-with-db url "a")))
(finally
(delete-database-with-db url)))))
(defn- valid-id-charcode?
[code]
(cond
; c.c.json doesn't cope well with the responses provided when CR or LF are included
(#{10 13} code) false
; D800–DFFF only used in surrogate pairs, invalid anywhere else (couch chokes on them)
(and (>= code 0xd800) (<= code 0xdfff)) false
(> code @#'com.ashafa.clutch/highest-supported-charcode) false
:else true))
; create a document containing each of the 65K chars in unicode BMP.
; this ensures that utils/id-encode is doing what it should and that we aren't screwing up
; encoding issues generally (which are easy regressions to introduce)
(defdbtest test-docid-encoding
; doing a lot of requests here -- the test is crazy-slow if delayed_commit=false,
; so let's use the iron we've got
(doseq [x (range 0xffff)
:when (valid-id-charcode? x)
:let [id (str "a" (char x)) ; doc ids can't start with _, so prefix everything
id-desc (str x " " id)]]
(try
(is (= id (:_id (put-document {:_id id}))) id-desc)
(let [doc (get-document id)]
(is (= {} (dissoc-meta doc)))
(delete-document doc)
(is (nil? (get-document id))))
(catch Exception e
(is false (str "Error for " id-desc ": " (.getMessage e)))))))
(defdbtest create-a-document
(let [document (put-document (first test-docs))]
(are [k] (contains? document k)
:_id :_rev)))
(defdbtest create-a-document-with-id
(let [document (put-document (first test-docs) :id "my_id")]
(is (= "my_id" (document :_id)))))
(defdbtest test-exists
(put-document {:_id "foo" :a 5})
(is (not (document-exists? "bar")))
(is (document-exists? "foo")))
(defrecord Foo [a])
(defdbtest create-with-record
(let [rec (put-document (Foo. "bar") :id "docid")]
(is (instance? Foo rec)))
(is (= "bar" (-> "docid" get-document :a))))
(defdbtest get-a-document
(let [created-document (put-document (nth test-docs 2))
fetched-document (get-document (created-document :_id))]
(are [x y z] (= x y z)
"PI:NAME:<NAME>END_PI" (created-document :name) (fetched-document :name)
"PI:EMAIL:<EMAIL>END_PI" (created-document :email) (fetched-document :email)
80 (created-document :score) (fetched-document :score))))
(defdbtest get-a-document-revision
(let [created-document (put-document (nth test-docs 2))
updated-doc (update-document (assoc created-document :newentry 1))
fetched-document (get-document (:_id created-document)
:rev (:_rev created-document))]
(are [x y z] (= x y z)
"PI:NAME:<NAME>END_PI" (created-document :name) (fetched-document :name)
"PI:EMAIL:<EMAIL>END_PI" (created-document :email) (fetched-document :email)
80 (:score created-document) (:score fetched-document)
nil (:newentry created-document) (:newentry fetched-document))
(is (= 1 (:newentry updated-doc)))))
(defmacro failing-request
[expected-status & body]
`(binding [http-client/*response* nil]
(try+
~@body
(assert false)
(catch identity ex#
(is (== ~expected-status (:status ex#)))
(is (map? http-client/*response*))))))
(defdbtest verify-response-code-access
(put-document (first test-docs) :id "some_id")
(failing-request 409 (put-document (first test-docs) :id "some_id")))
(defdbtest update-a-document
(let [id (:_id (put-document (nth test-docs 3)))]
(update-document (get-document id) {:email "PI:EMAIL:<EMAIL>END_PI"})
(is (= "PI:EMAIL:<EMAIL>END_PI" (:email (get-document id)))))
(testing "no update map or fn"
(let [id (:_id (put-document (nth test-docs 3)))]
(update-document (merge (get-document id) {:email "PI:EMAIL:<EMAIL>END_PI"}))
(is (= "PI:EMAIL:<EMAIL>END_PI" (:email (get-document id)))))))
(defdbtest update-a-document-with-a-function
(let [id (:_id (put-document (nth test-docs 2)))]
(update-document (get-document id) update-in [:score] + 3)
(is (= 83 (:score (get-document id))))))
(defdbtest update-with-updated-map
(-> (nth test-docs 2)
(put-document :id "docid")
(assoc :a "bar")
update-document)
(is (= "bar" (-> "docid" get-document :a))))
(defdbtest update-with-record
(let [rec (-> (Foo. "bar")
(merge (put-document {} :id "docid"))
update-document)]
(is (instance? Foo rec)))
(is (= "bar" (-> "docid" get-document :a))))
(defdbtest delete-a-document
(put-document (second test-docs) :id "my_id")
(is (get-document "my_id"))
(is (true? (:ok (delete-document (get-document "my_id")))))
(is (nil? (get-document "my_id"))))
(defdbtest copy-a-document
(let [doc (put-document (first test-docs) :id "src")]
(copy-document "src" "dst")
(copy-document doc "dst2")
(is (= (dissoc-meta doc)
(-> "dst" get-document dissoc-meta)
(-> "dst2" get-document dissoc-meta)))))
(defdbtest copy-document-overwrite
(let [doc (put-document (first test-docs) :id "src")
overwrite (put-document (second test-docs) :id "overwrite")]
(copy-document doc overwrite)
(is (= (dissoc-meta doc) (dissoc-meta (get-document "overwrite"))))))
(defdbtest copy-document-attachments
(let [doc (put-document (first test-docs) :id "src")
file (File. (str resources-path "/couchdb.png"))
doc (put-attachment doc file :filename :image)
doc (-> doc :id get-document)]
(copy-document "src" "dest")
(let [copy (get-document "dest")
copied-attachment (get-attachment copy :image)]
(is (= (dissoc-meta doc) (dissoc-meta copy)))
(is (= (-> file to-byte-array seq)
(-> copied-attachment to-byte-array seq))))))
(defdbtest copy-document-fail-overwrite
(put-document (first test-docs) :id "src")
(put-document (second test-docs) :id "overwrite")
(failing-request 409 (copy-document "src" "overwrite")))
(defdbtest get-all-documents-with-query-parameters
(bulk-update test-docs)
(let [all-documents-descending (all-documents {:include_docs true :descending true})
all-documents-ascending (all-documents {:include_docs true :descending false})]
(are [results] (= 4 (:total_rows (meta results)))
all-documents-descending
all-documents-ascending)
(are [name] (= "PI:NAME:<NAME>END_PI" name)
(-> all-documents-descending first :doc :name)
(-> all-documents-ascending last :doc :name))))
(defdbtest get-all-documents-with-post-keys
(doseq [[n x] (keep-indexed vector test-docs)]
(put-document x :id (str (inc n))))
(let [all-documents (all-documents {:include_docs true} {:keys ["1" "2"]})
all-documents-matching-keys all-documents]
(is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]
(map #(-> % :doc :name) all-documents-matching-keys)))
(is (= 4 (:total_rows (meta all-documents))))))
(defdbtest bulk-update-new-documents
(bulk-update test-docs)
(is (= 4 (:total_rows (meta (all-documents))))))
(defdbtest bulk-update-documents
(bulk-update test-docs)
(bulk-update (->> (all-documents {:include_docs true})
(map :doc)
(map #(assoc % :updated true))))
(is (every? true? (map #(-> % :doc :updated) (all-documents {:include_docs true})))))
(defdbtest inline-attachments
(let [clojure-img-file (str resources-path "/clojure.png")
couchdb-img-file (str resources-path "/couchdb.png")
couch-filename :couchdb.png
bytes-filename :couchdbbytes.png
created-document (put-document (nth test-docs 3)
:attachments [clojure-img-file
{:data (to-byte-array (FileInputStream. couchdb-img-file))
:data-length (-> couchdb-img-file File. .length)
:filename bytes-filename :mime-type "image/png"}
{:data (FileInputStream. couchdb-img-file)
:data-length (-> couchdb-img-file File. .length)
:filename couch-filename :mime-type "image/png"}])
fetched-document (get-document (created-document :_id))]
(are [attachment-keys] (= #{:clojure.png couch-filename bytes-filename} attachment-keys)
(set (keys (created-document :_attachments)))
(set (keys (fetched-document :_attachments))))
(are [doc file-key] (= "image/png" (-> doc :_attachments file-key :content_type))
created-document :clojure.png
fetched-document :clojure.png
created-document couch-filename
fetched-document couch-filename
created-document bytes-filename
fetched-document bytes-filename)
(are [path file-key] (= (.length (File. path)) (-> fetched-document :_attachments file-key :length))
clojure-img-file :clojure.png
couchdb-img-file couch-filename
couchdb-img-file bytes-filename)))
#_(defdbtest standalone-attachments
(let [document (put-document (first test-docs))
path (str resources-path "/couchdb.png")
filename-with-space (keyword "couchdb - image2")
updated-document-meta (put-attachment document path :filename :couchdb-image)
updated-document-meta (put-attachment (assoc document :_rev (:rev updated-document-meta))
(FileInputStream. path)
:filename filename-with-space
:mime-type "image/png"
:data-length (-> path File. .length))
updated-document-meta (put-attachment (assoc document :_rev (:rev updated-document-meta))
(to-byte-array (FileInputStream. path))
:filename :bytes-image :mime-type "image/png"
:data-length (-> path File. .length))
_ (.println System/out (pr-str (String.
(com.ashafa.clutch.http-client/couchdb-request :get
(-> (cemerick.url/url *test-database* (updated-document-meta :id))
(assoc :query {:attachments true}
:as :byte-array)))
"UTF-8")))
_ (do (flush) (Thread/sleep 5000))
#_#_document-with-attachments (get-document (updated-document-meta :id) :attachments true)]
#_((is (= #{:couchdb-image filename-with-space :bytes-image} (set (keys (:_attachments document-with-attachments)))))
(is (= "image/png" (-> document-with-attachments :_attachments :couchdb-image :content_type)))
(is (contains? (-> document-with-attachments :_attachments :couchdb-image) :data))
(is (= (-> document-with-attachments :_attachments :couchdb-image (select-keys [:data :content_type :length]))
(-> document-with-attachments :_attachments filename-with-space (select-keys [:data :content_type :length]))
(-> document-with-attachments :_attachments :bytes-image (select-keys [:data :content_type :length]))))
(is (thrown? IllegalArgumentException (put-attachment document (Object.))))
(is (thrown? IllegalArgumentException (put-attachment document (ByteArrayInputStream. (make-array Byte/TYPE 0))))))))
(defdbtest stream-attachments
(let [document (put-document (nth test-docs 3))
updated-document-meta (put-attachment document (str resources-path "/couchdb.png")
:filename :couchdb-image
:mime-type "other/mimetype")
document-with-attachments (get-document (updated-document-meta :id))
data (to-byte-array (java.io.File. (str resources-path "/couchdb.png")))]
(is (= "other/mimetype" (-> document-with-attachments :_attachments :couchdb-image :content_type)))
(is (= (seq data) (-> (get-attachment document-with-attachments :couchdb-image) to-byte-array seq)))))
(deftest replicate-a-database
(let [source (url test-host "source_test_db")
target (url test-host "target_test_db")]
(try
(get-database-with-db source)
(get-database-with-db target)
(bulk-update-with-db source test-docs)
(replicate-database-with-db source target)
(is (= 4 (:total_rows (meta (all-documents-with-db target)))))
(finally
(delete-database-with-db source)
(delete-database-with-db target)))))
(defn report-change
[description & forms]
(doseq [result forms]
(println (str "Testing changes: '" description "'") (if result "passed" "failed"))))
(defn check-id-changes-test
[description change-meta]
(if-not (:last_seq change-meta)
(report-change description
(is (= (:id change-meta) "target-id")))))
(defn check-seq-changes-test
[description change-meta]
(if-not (:last_seq change-meta)
(report-change description
(is (= (:seq change-meta) 1)))))
(defn check-delete-changes-test
[description change-meta]
(if (:deleted change-meta)
(report-change description
(is (= (:id change-meta) "target-id"))
(is (= (:seq change-meta) 5)))))
(deftest direct-db-config-usage
(let [db (test-database-url "direct-db-config-usage")]
(try
(create-database-with-db db)
(let [doc (put-document-with-db db (first test-docs) :id "foo")]
(update-document-with-db db doc {:a 5})
(is (= (assoc (first test-docs) :a 5) (dissoc-meta (get-document-with-db db "foo")))))
(finally
(delete-database-with-db db)))))
(deftest multiple-binding-levels
(let [db1 (test-database-url "multiple-binding-levels")
db2 (test-database-url "multiple-binding-levels2")]
(with-db db1
(try
(is (= "multiple-binding-levels" (:db_name (get-database))))
(put-document {} :id "1")
(with-db db2
(try
(is (= "multiple-binding-levels2" (:db_name (get-database))))
(is (nil? (get-document "1")))
(let [doc (put-document {} :id "2")]
(update-document doc {:a 5})
(is (= {:a 5} (dissoc-meta (get-document "2")))))
(finally
(delete-database))))
(is (nil? (get-document "2")))
(finally
(delete-database))))))
|
[
{
"context": "c 22 :period \"1\"\n :scorer {:player \"Connor McDavid\" :season-total 11}\n :assists [{:pla",
"end": 6909,
"score": 0.9998857378959656,
"start": 6895,
"tag": "NAME",
"value": "Connor McDavid"
},
{
"context": "ason-total 11}\n :assists [{:player \"Jordan Eberle\" :season-total 19}]}\n {:team \"BUF\" :",
"end": 6977,
"score": 0.999872088432312,
"start": 6964,
"tag": "NAME",
"value": "Jordan Eberle"
},
{
"context": "ec 6 :period \"3\"\n :scorer {:player \"Cal O'Reilly\" :season-total 1}\n :assists [{:play",
"end": 7097,
"score": 0.9998860359191895,
"start": 7085,
"tag": "NAME",
"value": "Cal O'Reilly"
},
{
"context": "eason-total 1}\n :assists [{:player \"Sam Reinhart\" :season-total 11}\n {:pla",
"end": 7163,
"score": 0.9998689889907837,
"start": 7151,
"tag": "NAME",
"value": "Sam Reinhart"
},
{
"context": "ason-total 11}\n {:player \"Mark Pysyk\" :season-total 5}]}\n {:team \"EDM\" :m",
"end": 7228,
"score": 0.9998676180839539,
"start": 7218,
"tag": "NAME",
"value": "Mark Pysyk"
},
{
"context": " 48 :period \"OT\"\n :scorer {:player \"Connor McDavid\" :season-total 12}\n :assists []}]\n ",
"end": 7351,
"score": 0.9998709559440613,
"start": 7337,
"tag": "NAME",
"value": "Connor McDavid"
},
{
"context": "c 36 :period \"1\"\n :scorer {:player \"Dmitrij Jaskin\" :season-total 4}\n :assists [{:play",
"end": 7958,
"score": 0.9998522400856018,
"start": 7944,
"tag": "NAME",
"value": "Dmitrij Jaskin"
},
{
"context": "eason-total 4}\n :assists [{:player \"Jaden Schwartz\" :season-total 7}\n {:play",
"end": 8026,
"score": 0.9998615384101868,
"start": 8012,
"tag": "NAME",
"value": "Jaden Schwartz"
},
{
"context": "eason-total 7}\n {:player \"Alex Pietrangelo\" :season-total 22}]}\n {:team \"STL\" :",
"end": 8096,
"score": 0.9998893141746521,
"start": 8080,
"tag": "NAME",
"value": "Alex Pietrangelo"
},
{
"context": "c 53 :period \"1\"\n :scorer {:player \"Jaden Schwartz\" :season-total 5}\n :assists [{:play",
"end": 8220,
"score": 0.9998601675033569,
"start": 8206,
"tag": "NAME",
"value": "Jaden Schwartz"
},
{
"context": "eason-total 5}\n :assists [{:player \"David Backes\" :season-total 19}\n {:pla",
"end": 8286,
"score": 0.9998822212219238,
"start": 8274,
"tag": "NAME",
"value": "David Backes"
},
{
"context": "ason-total 19}\n {:player \"Kevin Shattenkirk\" :season-total 22}]}\n {:team \"STL\" :",
"end": 8358,
"score": 0.9998883008956909,
"start": 8341,
"tag": "NAME",
"value": "Kevin Shattenkirk"
},
{
"context": "c 38 :period \"2\"\n :scorer {:player \"Vladimir Tarasenko\" :season-total 30}\n :assists [{:pla",
"end": 8486,
"score": 0.999848484992981,
"start": 8468,
"tag": "NAME",
"value": "Vladimir Tarasenko"
},
{
"context": "ason-total 30}\n :assists [{:player \"Kevin Shattenkirk\" :season-total 23}\n {:pla",
"end": 8558,
"score": 0.9998899102210999,
"start": 8541,
"tag": "NAME",
"value": "Kevin Shattenkirk"
},
{
"context": "ason-total 23}\n {:player \"Jaden Schwartz\" :season-total 8}]}\n {:team \"OTT\" :m",
"end": 8627,
"score": 0.9998695254325867,
"start": 8613,
"tag": "NAME",
"value": "Jaden Schwartz"
},
{
"context": "c 32 :period \"2\"\n :scorer {:player \"Ryan Dzingel\" :season-total 2}\n :assists [{:play",
"end": 8748,
"score": 0.999881386756897,
"start": 8736,
"tag": "NAME",
"value": "Ryan Dzingel"
},
{
"context": "eason-total 2}\n :assists [{:player \"Dion Phaneuf\" :season-total 27}\n {:pla",
"end": 8814,
"score": 0.9998624920845032,
"start": 8802,
"tag": "NAME",
"value": "Dion Phaneuf"
},
{
"context": "ason-total 27}\n {:player \"Mika Zibanejad\" :season-total 26}]}\n {:team \"OTT\" :",
"end": 8883,
"score": 0.9998855590820312,
"start": 8869,
"tag": "NAME",
"value": "Mika Zibanejad"
},
{
"context": "c 19 :period \"3\"\n :scorer {:player \"Jean-Gabriel Pageau\" :season-total 15}\n :assists [{:pla",
"end": 9012,
"score": 0.9998782873153687,
"start": 8993,
"tag": "NAME",
"value": "Jean-Gabriel Pageau"
},
{
"context": "ason-total 15}\n :assists [{:player \"Mark Stone\" :season-total 30}\n {:pla",
"end": 9077,
"score": 0.9998614192008972,
"start": 9067,
"tag": "NAME",
"value": "Mark Stone"
},
{
"context": "ason-total 30}\n {:player \"Erik Karlsson\" :season-total 57}]}\n {:team \"OTT\" :",
"end": 9145,
"score": 0.9998651742935181,
"start": 9132,
"tag": "NAME",
"value": "Erik Karlsson"
},
{
"context": "c 59 :period \"3\"\n :scorer {:player \"Jean-Gabriel Pageau\" :season-total 16}\n :assists [{:pla",
"end": 9274,
"score": 0.9998739957809448,
"start": 9255,
"tag": "NAME",
"value": "Jean-Gabriel Pageau"
},
{
"context": "ason-total 16}\n :assists [{:player \"Bobby Ryan\" :season-total 27}\n {:pla",
"end": 9339,
"score": 0.9998805522918701,
"start": 9329,
"tag": "NAME",
"value": "Bobby Ryan"
},
{
"context": "ason-total 27}\n {:player \"Zack Smith\" :season-total 7}]}\n {:team \"STL\" :p",
"end": 9404,
"score": 0.9998645186424255,
"start": 9394,
"tag": "NAME",
"value": "Zack Smith"
},
{
"context": " {:team \"STL\" :period \"SO\" :scorer {:player \"Patrik Berglund\"}}]\n goals) \"Parsed goals\")))\n\n (tes",
"end": 9498,
"score": 0.9998759031295776,
"start": 9483,
"tag": "NAME",
"value": "Patrik Berglund"
},
{
"context": "ec 4 :period \"4\"\n :scorer {:player \"David Backes\" :season-total 1}\n :assists [{:play",
"end": 10046,
"score": 0.9998692870140076,
"start": 10034,
"tag": "NAME",
"value": "David Backes"
},
{
"context": "eason-total 1}\n :assists [{:player \"Jay Bouwmeester\" :season-total 1}\n {:play",
"end": 10115,
"score": 0.9998883008956909,
"start": 10100,
"tag": "NAME",
"value": "Jay Bouwmeester"
},
{
"context": "eason-total 1}\n {:player \"Alex Pietrangelo\" :season-total 1}]}]\n (:goals game)) ",
"end": 10185,
"score": 0.9998887181282043,
"start": 10169,
"tag": "NAME",
"value": "Alex Pietrangelo"
}
] | test/nhl_score_api/fetchers/nhlstats/game_scores_test.clj | peruukki/nhl-score-api | 44 | (ns nhl-score-api.fetchers.nhlstats.game-scores-test
(:require [clojure.test :refer :all]
[nhl-score-api.fetchers.nhlstats.game-scores :refer :all]
[nhl-score-api.fetchers.nhlstats.transformer :refer [get-latest-games]]
[nhl-score-api.fetchers.nhlstats.resources :as resources]
[nhl-score-api.utils :refer [fmap-vals]]))
(deftest game-scores-parsing-scores
(testing "Parsing scores with games finished in overtime and in shootout"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))]
(is (= 9
(count games)) "Parsed game count")
(is (= [4 3 5 7 3 5 9 8 5]
(map #(count (:goals %)) games)) "Parsed goal count")
(is (= [{:away {:abbreviation "CAR" :id 12 :location-name "Carolina" :short-name "Carolina" :team-name "Hurricanes"}
:home {:abbreviation "NJD" :id 1 :location-name "New Jersey" :short-name "New Jersey" :team-name "Devils"}}
{:away {:abbreviation "CGY" :id 20 :location-name "Calgary" :short-name "Calgary" :team-name "Flames"}
:home {:abbreviation "BOS" :id 6 :location-name "Boston" :short-name "Boston" :team-name "Bruins"}}
{:away {:abbreviation "PIT" :id 5 :location-name "Pittsburgh" :short-name "Pittsburgh" :team-name "Penguins"}
:home {:abbreviation "WSH" :id 15 :location-name "Washington" :short-name "Washington" :team-name "Capitals"}}
{:away {:abbreviation "STL" :id 19 :location-name "St. Louis" :short-name "St Louis" :team-name "Blues"}
:home {:abbreviation "OTT" :id 9 :location-name "Ottawa" :short-name "Ottawa" :team-name "Senators"}}
{:away {:abbreviation "EDM" :id 22 :location-name "Edmonton" :short-name "Edmonton" :team-name "Oilers"}
:home {:abbreviation "BUF" :id 7 :location-name "Buffalo" :short-name "Buffalo" :team-name "Sabres"}}
{:away {:abbreviation "FLA" :id 13 :location-name "Florida" :short-name "Florida" :team-name "Panthers"}
:home {:abbreviation "WPG" :id 52 :location-name "Winnipeg" :short-name "Winnipeg" :team-name "Jets"}}
{:away {:abbreviation "COL" :id 21 :location-name "Colorado" :short-name "Colorado" :team-name "Avalanche"}
:home {:abbreviation "MIN" :id 30 :location-name "Minnesota" :short-name "Minnesota" :team-name "Wild"}}
{:away {:abbreviation "DAL" :id 25 :location-name "Dallas" :short-name "Dallas" :team-name "Stars"}
:home {:abbreviation "NSH" :id 18 :location-name "Nashville" :short-name "Nashville" :team-name "Predators"}}
{:away {:abbreviation "NYI" :id 2 :location-name "New York" :short-name "NY Islanders" :team-name "Islanders"}
:home {:abbreviation "VAN" :id 23 :location-name "Vancouver" :short-name "Vancouver" :team-name "Canucks"}}]
(map :teams games)) "Parsed teams")
(is (= [{"CAR" 3 "NJD" 1} {"CGY" 1 "BOS" 2} {"PIT" 2 "WSH" 3} {"STL" 4 "OTT" 3 :shootout true}
{"EDM" 2 "BUF" 1 :overtime true} {"FLA" 3 "WPG" 2} {"COL" 3 "MIN" 6} {"DAL" 3 "NSH" 5}
{"NYI" 3 "VAN" 2}]
(map :scores games)) "Parsed scores")
(is (= [false]
(distinct (map #(contains? % :playoff-series) games))))))
(testing "Parsing scores with games finished, on-going and not yet started"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-in-live-preview-and-final-states)
(:records resources/standings)))]
(is (= 7
(count games)) "Parsed game count")
(is (= 1
(count (filter #(= (:state (:status %)) "FINAL") games))) "Parsed finished game count")
(is (= 2
(count (filter #(= (:state (:status %)) "LIVE") games))) "Parsed on-going game count")
(is (= 3
(count (filter #(= (:state (:status %)) "PREVIEW") games))) "Parsed not started game count")
(is (= 1
(count (filter #(= (:state (:status %)) "POSTPONED") games))) "Parsed postponed game count")
(is (= [5 2 5 0 0 0 0]
(map #(count (:goals %)) games)) "Parsed goal count")
(is (= [{:away {:abbreviation "WSH" :id 15 :location-name "Washington" :short-name "Washington" :team-name "Capitals"}
:home {:abbreviation "CHI" :id 16 :location-name "Chicago" :short-name "Chicago" :team-name "Blackhawks"}}
{:away {:abbreviation "FLA" :id 13 :location-name "Florida" :short-name "Florida" :team-name "Panthers"}
:home {:abbreviation "MIN" :id 30 :location-name "Minnesota" :short-name "Minnesota" :team-name "Wild"}}
{:away {:abbreviation "STL" :id 19 :location-name "St. Louis" :short-name "St Louis" :team-name "Blues"}
:home {:abbreviation "CAR" :id 12 :location-name "Carolina" :short-name "Carolina" :team-name "Hurricanes"}}
{:away {:abbreviation "TBL" :id 14 :location-name "Tampa Bay" :short-name "Tampa Bay" :team-name "Lightning"}
:home {:abbreviation "BOS" :id 6 :location-name "Boston" :short-name "Boston" :team-name "Bruins"}}
{:away {:abbreviation "SJS" :id 28 :location-name "San Jose" :short-name "San Jose" :team-name "Sharks"}
:home {:abbreviation "VAN" :id 23 :location-name "Vancouver" :short-name "Vancouver" :team-name "Canucks"}}
{:away {:abbreviation "LAK" :id 26 :location-name "Los Angeles" :short-name "Los Angeles" :team-name "Kings"}
:home {:abbreviation "ANA" :id 24 :location-name "Anaheim" :short-name "Anaheim" :team-name "Ducks"}}
{:away {:abbreviation "NYI" :id 2 :location-name "New York" :short-name "NY Islanders" :team-name "Islanders"}
:home {:abbreviation "EDM" :id 22 :location-name "Edmonton" :short-name "Edmonton" :team-name "Oilers"}}]
(map :teams games)) "Parsed teams")
(is (= [{"WSH" 2 "CHI" 3} {"FLA" 1 "MIN" 1} {"STL" 3 "CAR" 2}
{"TBL" 0 "BOS" 0} {"SJS" 0 "VAN" 0} {"LAK" 0 "ANA" 0} {"NYI" 0 "EDM" 0}]
(map :scores games)) "Parsed scores")
(is (= [false]
(distinct (map #(contains? % :playoff-series) games)))))))
(deftest game-scores-parsing-games
(testing "Parsing game with goals in regulation and overtime"
(let [game (nth
(:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
4)
goals (:goals game)]
(is (= [{:team "EDM" :min 0 :sec 22 :period "1"
:scorer {:player "Connor McDavid" :season-total 11}
:assists [{:player "Jordan Eberle" :season-total 19}]}
{:team "BUF" :min 9 :sec 6 :period "3"
:scorer {:player "Cal O'Reilly" :season-total 1}
:assists [{:player "Sam Reinhart" :season-total 11}
{:player "Mark Pysyk" :season-total 5}]}
{:team "EDM" :min 3 :sec 48 :period "OT"
:scorer {:player "Connor McDavid" :season-total 12}
:assists []}]
goals) "Parsed goals")))
(testing "Parsing game with goals in regulation and shootout"
(let [game (nth
(:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
3)
goals (map #(dissoc % :strength) (:goals game))] ; 'strength' field has its own test
(is (= [{:team "STL" :min 3 :sec 36 :period "1"
:scorer {:player "Dmitrij Jaskin" :season-total 4}
:assists [{:player "Jaden Schwartz" :season-total 7}
{:player "Alex Pietrangelo" :season-total 22}]}
{:team "STL" :min 12 :sec 53 :period "1"
:scorer {:player "Jaden Schwartz" :season-total 5}
:assists [{:player "David Backes" :season-total 19}
{:player "Kevin Shattenkirk" :season-total 22}]}
{:team "STL" :min 10 :sec 38 :period "2"
:scorer {:player "Vladimir Tarasenko" :season-total 30}
:assists [{:player "Kevin Shattenkirk" :season-total 23}
{:player "Jaden Schwartz" :season-total 8}]}
{:team "OTT" :min 12 :sec 32 :period "2"
:scorer {:player "Ryan Dzingel" :season-total 2}
:assists [{:player "Dion Phaneuf" :season-total 27}
{:player "Mika Zibanejad" :season-total 26}]}
{:team "OTT" :min 17 :sec 19 :period "3"
:scorer {:player "Jean-Gabriel Pageau" :season-total 15}
:assists [{:player "Mark Stone" :season-total 30}
{:player "Erik Karlsson" :season-total 57}]}
{:team "OTT" :min 19 :sec 59 :period "3"
:scorer {:player "Jean-Gabriel Pageau" :season-total 16}
:assists [{:player "Bobby Ryan" :season-total 27}
{:player "Zack Smith" :season-total 7}]}
{:team "STL" :period "SO" :scorer {:player "Patrik Berglund"}}]
goals) "Parsed goals")))
(testing "Parsing game with goal in playoff overtime"
(let [game (nth
(:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-in-regulation-and-overtime)
(:records resources/standings)))
2)]
(is (= {"CHI" 0 "STL" 1 :overtime true}
(:scores game)) "Parsed scores")
(is (= [{:team "STL" :min 9 :sec 4 :period "4"
:scorer {:player "David Backes" :season-total 1}
:assists [{:player "Jay Bouwmeester" :season-total 1}
{:player "Alex Pietrangelo" :season-total 1}]}]
(:goals game)) "Parsed goals")))
(testing "Parsing empty net goal information"
(let [game (nth
(:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-in-regulation-and-overtime)
(:records resources/standings)))
1)
goals (:goals game)]
(is (= [false]
(distinct (map #(contains? % :empty-net) (drop-last goals))))
"All goals but the last one have no :empty-net field")
(is (= true
(:empty-net (last goals)))
"Last goal has :empty-net field set to true")))
(testing "Parsing goal strength (even / power play / short handed) information"
(let [game (nth
(:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-in-regulation-and-overtime)
(:records resources/standings)))
1)
goals (:goals game)]
(is (= [nil nil "PPG" "SHG" "PPG" nil nil]
(map #(:strength %) goals))
"Parsed goal strengths")
(is (= [false false true true true false false]
(map #(contains? % :strength) goals))
"Even strength goals don't contain :strength field"))))
(deftest game-scores-parsing-game-statuses
(testing "Parsing games' statuses"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-in-live-preview-and-final-states)
(:records resources/standings)))
statuses (map #(:status %) games)]
(is (= [{:state "FINAL"}
{:state "LIVE"
:progress {:current-period 3,
:current-period-ordinal "3rd",
:current-period-time-remaining {:pretty "08:58" :min 8 :sec 58}}}
{:state "LIVE"
:progress {:current-period 3,
:current-period-ordinal "3rd",
:current-period-time-remaining {:pretty "END" :min 0 :sec 0}}}
{:state "PREVIEW"}
{:state "PREVIEW"}
{:state "PREVIEW"}
{:state "POSTPONED"}]
statuses) "Parsed game statuses"))))
(deftest game-scores-parsing-game-start-times
(testing "Parsing games' start times"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-in-live-preview-and-final-states)
(:records resources/standings)))
start-times (map #(:start-time %) games)]
(is (= ["2016-02-28T17:30:00Z"
"2016-02-28T20:00:00Z"
"2016-02-28T20:00:00Z"
"2016-02-28T23:30:00Z"
"2016-02-29T00:00:00Z"
"2016-02-29T02:00:00Z"
"2016-02-29T02:30:00Z"]
start-times) "Parsed game start times"))))
(deftest game-scores-parsing-team-records
(testing "Parsing teams' pre-game regular season records"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
records (map #(:records (:pre-game-stats %)) games)]
(is (= 9
(count records)) "Parsed pre-game regular season records count")
(is (= [{"CAR" {:wins 28 :losses 26 :ot 10} "NJD" {:wins 30 :losses 26 :ot 7}}
{"CGY" {:wins 26 :losses 32 :ot 4} "BOS" {:wins 34 :losses 23 :ot 6}}
{"PIT" {:wins 32 :losses 21 :ot 8} "WSH" {:wins 45 :losses 12 :ot 4}}
{"STL" {:wins 36 :losses 20 :ot 9} "OTT" {:wins 30 :losses 27 :ot 6}}
{"EDM" {:wins 23 :losses 34 :ot 7} "BUF" {:wins 25 :losses 31 :ot 7}}
{"FLA" {:wins 35 :losses 19 :ot 8} "WPG" {:wins 26 :losses 31 :ot 4}}
{"COL" {:wins 32 :losses 28 :ot 4} "MIN" {:wins 28 :losses 25 :ot 10}}
{"DAL" {:wins 38 :losses 19 :ot 7} "NSH" {:wins 31 :losses 21 :ot 11}}
{"NYI" {:wins 33 :losses 20 :ot 7} "VAN" {:wins 24 :losses 25 :ot 12}}]
records) "Parsed pre-game regular season records")))
(testing "Parsing teams' current regular season records"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
records (map #(:records (:current-stats %)) games)]
(is (= 9
(count records)) "Parsed current regular season records count")
(is (= [{"CAR" {:wins 29 :losses 26 :ot 10} "NJD" {:wins 30 :losses 27 :ot 7}}
{"CGY" {:wins 26 :losses 33 :ot 4} "BOS" {:wins 35 :losses 23 :ot 6}}
{"PIT" {:wins 32 :losses 22 :ot 8} "WSH" {:wins 46 :losses 12 :ot 4}}
{"STL" {:wins 37 :losses 20 :ot 9} "OTT" {:wins 30 :losses 27 :ot 7}}
{"EDM" {:wins 24 :losses 34 :ot 7} "BUF" {:wins 25 :losses 31 :ot 8}}
{"FLA" {:wins 36 :losses 19 :ot 8} "WPG" {:wins 26 :losses 32 :ot 4}}
{"COL" {:wins 32 :losses 29 :ot 4} "MIN" {:wins 29 :losses 25 :ot 10}}
{"DAL" {:wins 38 :losses 20 :ot 7} "NSH" {:wins 32 :losses 21 :ot 11}}
{"NYI" {:wins 34 :losses 20 :ot 7} "VAN" {:wins 24 :losses 26 :ot 12}}]
records) "Parsed current regular season records"))))
(deftest game-scores-parsing-team-streaks
(testing "Parsing teams' current streaks"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
streaks (map #(:streaks (:current-stats %)) games)]
(is (= 9
(count streaks)) "Parsed streaks count")
(is (= [{"CAR" {:type "WINS" :count 3} "NJD" {:type "LOSSES" :count 1}}
{"CGY" {:type "LOSSES" :count 1} "BOS" {:type "WINS" :count 1}}
{"PIT" {:type "WINS" :count 1} "WSH" {:type "OT" :count 1}}
{"STL" {:type "WINS" :count 1} "OTT" {:type "LOSSES" :count 2}}
{"EDM" {:type "LOSSES" :count 1} "BUF" {:type "WINS" :count 1}}
{"FLA" {:type "WINS" :count 2} "WPG" {:type "WINS" :count 4}}
{"COL" {:type "WINS" :count 1} "MIN" {:type "WINS" :count 1}}
{"DAL" {:type "LOSSES" :count 3} "NSH" {:type "WINS" :count 3}}
{"NYI" {:type "OT" :count 2} "VAN" {:type "WINS" :count 1}}]
streaks) "Parsed streaks"))))
(deftest game-scores-parsing-team-ranks
(testing "Parsing teams' division and league ranks for regular season games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
pre-game-stats-standings (map #(:standings (:pre-game-stats %)) games)
current-stats-standings (map #(:standings (:current-stats %)) games)
ranks (map
#(fmap-vals (fn [team-stats] (select-keys team-stats [:division-rank :league-rank])) %)
current-stats-standings)]
(is (= (repeat 9 nil) pre-game-stats-standings) "Pre-game standings should not exist")
(is (= [{"CAR" {:division-rank "4" :league-rank "9"} "NJD" {:division-rank "8" :league-rank "26"}}
{"CGY" {:division-rank "4" :league-rank "19"} "BOS" {:division-rank "1" :league-rank "1"}}
{"PIT" {:division-rank "3" :league-rank "7"} "WSH" {:division-rank "1" :league-rank "5"}}
{"STL" {:division-rank "1" :league-rank "2"} "OTT" {:division-rank "7" :league-rank "30"}}
{"EDM" {:division-rank "2" :league-rank "12"} "BUF" {:division-rank "6" :league-rank "25"}}
{"FLA" {:division-rank "4" :league-rank "15"} "WPG" {:division-rank "5" :league-rank "20"}}
{"COL" {:division-rank "2" :league-rank "3"} "MIN" {:division-rank "6" :league-rank "21"}}
{"DAL" {:division-rank "3" :league-rank "10"} "NSH" {:division-rank "4" :league-rank "16"}}
{"NYI" {:division-rank "5" :league-rank "11"} "VAN" {:division-rank "3" :league-rank "17"}}]
ranks) "Parsed current stats division and league ranks")))
(testing "Parsing teams' division and league ranks for playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-in-regulation-and-overtime)
(:records resources/standings)))
pre-game-stats-standings (map #(:standings (:pre-game-stats %)) games)
current-stats-standings (map #(:standings (:current-stats %)) games)
ranks (map
#(fmap-vals (fn [team-stats] (select-keys team-stats [:division-rank :league-rank])) %)
current-stats-standings)]
(is (= pre-game-stats-standings current-stats-standings) "Parsed standings, pre-game vs. current stats")
(is (= [{"DET" {:division-rank "8" :league-rank "31"} "TBL" {:division-rank "2" :league-rank "4"}}
{"NYR" {:division-rank "7" :league-rank "18"} "PIT" {:division-rank "3" :league-rank "7"}}
{"CHI" {:division-rank "7" :league-rank "23"} "STL" {:division-rank "1" :league-rank "2"}}]
ranks) "Parsed current stats division and league ranks"))))
; TODO: Enable this again when "normal" playoff spot logic is resumed
(deftest ^:skip game-scores-parsing-team-points-from-playoff-spot
(testing "Parsing teams' points from playoff spot"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings-playoff-spots-per-division-5-3-4-4)))
standings (map #(:standings (:current-stats %)) games)
points-from-playoff-spot (map
#(fmap-vals (fn [team-stats] (select-keys team-stats [:points-from-playoff-spot])) %)
standings)]
(is (= 9
(count points-from-playoff-spot)) "Parsed points from playoff spot count")
; The test standings are:
;
; Eastern conference Western conference
;
; Metropolitan Central
; 1 WSH 79 pts 1 STL 74 pts
; 2 PIT 76 pts 2 DAL 73 pts
; 3 NYI 72 pts 3 COL 72 pts
; 4 CBJ 71 pts, 1st wild card 4 NSH 65 pts, 2nd wild card
; 5 PHI 71 pts, 2nd wild card ------------
; ------------ 5 WPG 63 pts
; 6 CAR 69 pts, 1st out of the playoffs 6 MIN 61 pts
; 7 NYR 64 pts 7 CHI 60 pts
; 8 NJD 52 pts
;
; Atlantic Pacific
; 1 BOS 84 pts 1 VAN 69 pts
; 2 TBL 83 pts 2 EDM 68 pts
; 3 TOR 70 pts 3 VGK 68 pts
; ------------ 4 CGY 66 pts, 1st wild card
; 4 FLA 66 pts ------------
; 5 MTL 62 pts 5 ARI 64 pts, 1st out of the playoffs
; 6 BUF 60 pts 6 SJS 56 pts
; 7 OTT 49 pts 7 ANA 53 pts
; 8 DET 32 pts 8 LAK 47 pts
(is (= [{"CAR" {:points-from-playoff-spot "-2"} "NJD" {:points-from-playoff-spot "-19"}}
{"CGY" {:points-from-playoff-spot "+2"} "BOS" {:points-from-playoff-spot "+18"}}
{"PIT" {:points-from-playoff-spot "+7"} "WSH" {:points-from-playoff-spot "+10"}}
{"STL" {:points-from-playoff-spot "+10"} "OTT" {:points-from-playoff-spot "-21"}}
{"EDM" {:points-from-playoff-spot "+4"} "BUF" {:points-from-playoff-spot "-10"}}
{"FLA" {:points-from-playoff-spot "-4"} "WPG" {:points-from-playoff-spot "-2"}}
{"COL" {:points-from-playoff-spot "+8"} "MIN" {:points-from-playoff-spot "-4"}}
{"DAL" {:points-from-playoff-spot "+9"} "NSH" {:points-from-playoff-spot "+1"}}
{"NYI" {:points-from-playoff-spot "+3"} "VAN" {:points-from-playoff-spot "+5"}}]
points-from-playoff-spot) "Parsed points from playoff spot"))))
(deftest game-scores-parsing-team-playoff-records
(testing "Parsing teams' pre-game playoff records when teams have no OT loss values in their records"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-live-finished-with-1st-games)
(:records resources/standings)))
records (map #(:records (:pre-game-stats %)) games)]
(is (= 5
(count records)) "Parsed pre-game playoff records count")
(is (= [{"NJD" {:wins 0 :losses 0} "TBL" {:wins 0 :losses 0}}
{"TOR" {:wins 0 :losses 0} "BOS" {:wins 0 :losses 0}}
{"CBJ" {:wins 0 :losses 0} "WSH" {:wins 0 :losses 0}}
{"COL" {:wins 0 :losses 0} "NSH" {:wins 0 :losses 0}}
{"SJS" {:wins 0 :losses 0} "ANA" {:wins 0 :losses 0}}]
records) "Parsed pre-game playoff records")))
(testing "Parsing teams' pre-game playoff records when teams have OT loss values in their records"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-with-ot-losses-in-records)
(:records resources/standings)))
records (map #(:records (:pre-game-stats %)) games)]
(is (= 5
(count records)) "Parsed pre-game playoff records count")
(is (= [{"CAR" {:wins 0 :losses 0 :ot 0} "NYR" {:wins 0 :losses 0 :ot 0}}
{"CHI" {:wins 0 :losses 0 :ot 0} "EDM" {:wins 0 :losses 0 :ot 0}}
{"FLA" {:wins 0 :losses 0 :ot 0} "NYI" {:wins 0 :losses 0 :ot 0}}
{"MTL" {:wins 0 :losses 0 :ot 0} "PIT" {:wins 0 :losses 0 :ot 0}}
{"CGY" {:wins 0 :losses 0 :ot 0} "WPG" {:wins 0 :losses 0 :ot 0}}]
records) "Parsed pre-game playoff records")))
(testing "Parsing teams' current playoff records"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-live-finished-with-1st-games)
(:records resources/standings)))
records (map #(:records (:current-stats %)) games)]
(is (= 5
(count records)) "Parsed current playoff records count")
(is (= [{"NJD" {:wins 0 :losses 1} "TBL" {:wins 1 :losses 0}}
{"TOR" {:wins 0 :losses 1} "BOS" {:wins 1 :losses 0}}
{"CBJ" {:wins 1 :losses 0} "WSH" {:wins 0 :losses 1}}
{"COL" {:wins 0 :losses 0} "NSH" {:wins 0 :losses 0}}
{"SJS" {:wins 0 :losses 0} "ANA" {:wins 0 :losses 0}}]
records) "Parsed current playoff records"))))
(deftest game-scores-parsing-playoff-series
(testing "Parsing pre-game playoff series wins from playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-with-2nd-games)
(:records resources/standings)))
playoff-series (map #(:playoff-series (:pre-game-stats %)) games)
wins (map :wins playoff-series)]
(is (= [{"DET" 0 "TBL" 1} {"NYI" 1 "FLA" 0} {"CHI" 0 "STL" 1} {"NSH" 0 "ANA" 0}]
wins) "Parsed pre-game playoff series wins")))
(testing "Parsing current playoff series wins from playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-with-2nd-games)
(:records resources/standings)))
playoff-series (map #(:playoff-series (:current-stats %)) games)
wins (map :wins playoff-series)]
(is (= [{"DET" 0 "TBL" 2} {"NYI" 1 "FLA" 1} {"CHI" 1 "STL" 1} {"NSH" 1 "ANA" 0}]
wins) "Parsed current playoff series wins")))
(testing "Parsing pre-game playoff series wins from first playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-live-finished-with-1st-games)
(:records resources/standings)))
playoff-series (map #(:playoff-series (:pre-game-stats %)) games)
wins (map :wins playoff-series)]
(is (= [{"NJD" 0 "TBL" 0} ; finished & up to date
{"TOR" 0 "BOS" 0} ; finished & up to date
{"CBJ" 0 "WSH" 0} ; finished & current game missing from seriesRecord
{"COL" 0 "NSH" 0} ; in-progress & up to date
{"SJS" 0 "ANA" 0}] ; in-progress & current game included in seriesRecord
wins) "Parsed pre-game playoff series wins")))
(testing "Parsing current playoff series wins from first playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-live-finished-with-1st-games)
(:records resources/standings)))
playoff-series (map #(:playoff-series (:current-stats %)) games)
wins (map :wins playoff-series)]
(is (= [{"NJD" 0 "TBL" 1} ; finished & up to date
{"TOR" 0 "BOS" 1} ; finished & up to date
{"CBJ" 1 "WSH" 0} ; finished & current game missing from seriesRecord
{"COL" 0 "NSH" 0} ; in-progress & up to date
{"SJS" 0 "ANA" 0}] ; in-progress & current game included in seriesRecord
wins) "Parsed current playoff series wins")))
(testing "Parsing playoff rounds from playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-live-finished-with-1st-games)
(:records resources/standings)))
pre-game-stats-playoff-series (map #(:playoff-series (:pre-game-stats %)) games)
current-stats-playoff-series (map #(:playoff-series (:current-stats %)) games)
pre-game-stats-rounds (map :round pre-game-stats-playoff-series)
current-stats-rounds (map :round current-stats-playoff-series)]
(is (= [1 1 1 1 1]
pre-game-stats-rounds) "Parsed pre-game stats playoff rounds")
(is (= [1 1 1 1 1]
current-stats-rounds) "Parsed current stats playoff rounds"))))
(deftest game-scores-pre-game-stats
(testing "Not including teams' pre-game stats"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)
false))]
(is (= [false]
(distinct (map #(contains? % :pre-game-stats) games)))
"Pre-game stats are not included"))))
(deftest game-scores-validation
(testing "Validating valid game with goals"
(let [game (first (:games
(parse-game-scores
(get-latest-games resources/games-in-live-preview-and-final-states)
(:records resources/standings))))]
(is (= (contains? game :errors) false) "No validation errors")))
(testing "Validating valid game without goals"
(let [game (nth (:games
(parse-game-scores
(get-latest-games resources/games-in-live-preview-and-final-states)
(:records resources/standings)))
3)]
(is (= (contains? game :errors) false) "No validation errors")))
(testing "Validating valid non-finished game with multiple shootout goals"
(let [game (nth (:games
(parse-game-scores
(get-latest-games resources/games-for-validation-testing)
(:records resources/standings)))
4)]
(is (= (contains? game :errors) false) "No validation errors")))
(testing "Validating valid finished game with multiple shootout goals"
(let [game (nth (:games
(parse-game-scores
(get-latest-games resources/games-for-validation-testing)
(:records resources/standings)))
3)]
(is (= (contains? game :errors) false) "No validation errors")))
(testing "Validating game missing all goals"
(let [game (first (:games
(parse-game-scores
(get-latest-games resources/games-for-validation-testing)
(:records resources/standings))))]
(is (= (contains? game :errors) true) "Contains validation errors")
(is (= [{:error :MISSING-ALL-GOALS}]
(:errors game)) "Errors contain 'missing all goals' error")))
(testing "Validating game missing one goal"
(let [game (second (:games
(parse-game-scores
(get-latest-games resources/games-for-validation-testing)
(:records resources/standings))))]
(is (= (contains? game :errors) true) "Contains validation errors")
(is (= [{:error :SCORE-AND-GOAL-COUNT-MISMATCH :details {:goal-count 4 :score-count 5}}]
(:errors game)) "Errors contain expected 'score and goal count mismatch' error")))
(testing "Validating game having one goal too many"
(let [game (nth (:games
(parse-game-scores
(get-latest-games resources/games-for-validation-testing)
(:records resources/standings)))
2)]
(is (= (contains? game :errors) true) "Contains validation errors")
(is (= [{:error :SCORE-AND-GOAL-COUNT-MISMATCH :details {:goal-count 5 :score-count 3}}]
(:errors game)) "Errors contain expected 'score and goal count mismatch' error"))))
| 11535 | (ns nhl-score-api.fetchers.nhlstats.game-scores-test
(:require [clojure.test :refer :all]
[nhl-score-api.fetchers.nhlstats.game-scores :refer :all]
[nhl-score-api.fetchers.nhlstats.transformer :refer [get-latest-games]]
[nhl-score-api.fetchers.nhlstats.resources :as resources]
[nhl-score-api.utils :refer [fmap-vals]]))
(deftest game-scores-parsing-scores
(testing "Parsing scores with games finished in overtime and in shootout"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))]
(is (= 9
(count games)) "Parsed game count")
(is (= [4 3 5 7 3 5 9 8 5]
(map #(count (:goals %)) games)) "Parsed goal count")
(is (= [{:away {:abbreviation "CAR" :id 12 :location-name "Carolina" :short-name "Carolina" :team-name "Hurricanes"}
:home {:abbreviation "NJD" :id 1 :location-name "New Jersey" :short-name "New Jersey" :team-name "Devils"}}
{:away {:abbreviation "CGY" :id 20 :location-name "Calgary" :short-name "Calgary" :team-name "Flames"}
:home {:abbreviation "BOS" :id 6 :location-name "Boston" :short-name "Boston" :team-name "Bruins"}}
{:away {:abbreviation "PIT" :id 5 :location-name "Pittsburgh" :short-name "Pittsburgh" :team-name "Penguins"}
:home {:abbreviation "WSH" :id 15 :location-name "Washington" :short-name "Washington" :team-name "Capitals"}}
{:away {:abbreviation "STL" :id 19 :location-name "St. Louis" :short-name "St Louis" :team-name "Blues"}
:home {:abbreviation "OTT" :id 9 :location-name "Ottawa" :short-name "Ottawa" :team-name "Senators"}}
{:away {:abbreviation "EDM" :id 22 :location-name "Edmonton" :short-name "Edmonton" :team-name "Oilers"}
:home {:abbreviation "BUF" :id 7 :location-name "Buffalo" :short-name "Buffalo" :team-name "Sabres"}}
{:away {:abbreviation "FLA" :id 13 :location-name "Florida" :short-name "Florida" :team-name "Panthers"}
:home {:abbreviation "WPG" :id 52 :location-name "Winnipeg" :short-name "Winnipeg" :team-name "Jets"}}
{:away {:abbreviation "COL" :id 21 :location-name "Colorado" :short-name "Colorado" :team-name "Avalanche"}
:home {:abbreviation "MIN" :id 30 :location-name "Minnesota" :short-name "Minnesota" :team-name "Wild"}}
{:away {:abbreviation "DAL" :id 25 :location-name "Dallas" :short-name "Dallas" :team-name "Stars"}
:home {:abbreviation "NSH" :id 18 :location-name "Nashville" :short-name "Nashville" :team-name "Predators"}}
{:away {:abbreviation "NYI" :id 2 :location-name "New York" :short-name "NY Islanders" :team-name "Islanders"}
:home {:abbreviation "VAN" :id 23 :location-name "Vancouver" :short-name "Vancouver" :team-name "Canucks"}}]
(map :teams games)) "Parsed teams")
(is (= [{"CAR" 3 "NJD" 1} {"CGY" 1 "BOS" 2} {"PIT" 2 "WSH" 3} {"STL" 4 "OTT" 3 :shootout true}
{"EDM" 2 "BUF" 1 :overtime true} {"FLA" 3 "WPG" 2} {"COL" 3 "MIN" 6} {"DAL" 3 "NSH" 5}
{"NYI" 3 "VAN" 2}]
(map :scores games)) "Parsed scores")
(is (= [false]
(distinct (map #(contains? % :playoff-series) games))))))
(testing "Parsing scores with games finished, on-going and not yet started"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-in-live-preview-and-final-states)
(:records resources/standings)))]
(is (= 7
(count games)) "Parsed game count")
(is (= 1
(count (filter #(= (:state (:status %)) "FINAL") games))) "Parsed finished game count")
(is (= 2
(count (filter #(= (:state (:status %)) "LIVE") games))) "Parsed on-going game count")
(is (= 3
(count (filter #(= (:state (:status %)) "PREVIEW") games))) "Parsed not started game count")
(is (= 1
(count (filter #(= (:state (:status %)) "POSTPONED") games))) "Parsed postponed game count")
(is (= [5 2 5 0 0 0 0]
(map #(count (:goals %)) games)) "Parsed goal count")
(is (= [{:away {:abbreviation "WSH" :id 15 :location-name "Washington" :short-name "Washington" :team-name "Capitals"}
:home {:abbreviation "CHI" :id 16 :location-name "Chicago" :short-name "Chicago" :team-name "Blackhawks"}}
{:away {:abbreviation "FLA" :id 13 :location-name "Florida" :short-name "Florida" :team-name "Panthers"}
:home {:abbreviation "MIN" :id 30 :location-name "Minnesota" :short-name "Minnesota" :team-name "Wild"}}
{:away {:abbreviation "STL" :id 19 :location-name "St. Louis" :short-name "St Louis" :team-name "Blues"}
:home {:abbreviation "CAR" :id 12 :location-name "Carolina" :short-name "Carolina" :team-name "Hurricanes"}}
{:away {:abbreviation "TBL" :id 14 :location-name "Tampa Bay" :short-name "Tampa Bay" :team-name "Lightning"}
:home {:abbreviation "BOS" :id 6 :location-name "Boston" :short-name "Boston" :team-name "Bruins"}}
{:away {:abbreviation "SJS" :id 28 :location-name "San Jose" :short-name "San Jose" :team-name "Sharks"}
:home {:abbreviation "VAN" :id 23 :location-name "Vancouver" :short-name "Vancouver" :team-name "Canucks"}}
{:away {:abbreviation "LAK" :id 26 :location-name "Los Angeles" :short-name "Los Angeles" :team-name "Kings"}
:home {:abbreviation "ANA" :id 24 :location-name "Anaheim" :short-name "Anaheim" :team-name "Ducks"}}
{:away {:abbreviation "NYI" :id 2 :location-name "New York" :short-name "NY Islanders" :team-name "Islanders"}
:home {:abbreviation "EDM" :id 22 :location-name "Edmonton" :short-name "Edmonton" :team-name "Oilers"}}]
(map :teams games)) "Parsed teams")
(is (= [{"WSH" 2 "CHI" 3} {"FLA" 1 "MIN" 1} {"STL" 3 "CAR" 2}
{"TBL" 0 "BOS" 0} {"SJS" 0 "VAN" 0} {"LAK" 0 "ANA" 0} {"NYI" 0 "EDM" 0}]
(map :scores games)) "Parsed scores")
(is (= [false]
(distinct (map #(contains? % :playoff-series) games)))))))
(deftest game-scores-parsing-games
(testing "Parsing game with goals in regulation and overtime"
(let [game (nth
(:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
4)
goals (:goals game)]
(is (= [{:team "EDM" :min 0 :sec 22 :period "1"
:scorer {:player "<NAME>" :season-total 11}
:assists [{:player "<NAME>" :season-total 19}]}
{:team "BUF" :min 9 :sec 6 :period "3"
:scorer {:player "<NAME>" :season-total 1}
:assists [{:player "<NAME>" :season-total 11}
{:player "<NAME>" :season-total 5}]}
{:team "EDM" :min 3 :sec 48 :period "OT"
:scorer {:player "<NAME>" :season-total 12}
:assists []}]
goals) "Parsed goals")))
(testing "Parsing game with goals in regulation and shootout"
(let [game (nth
(:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
3)
goals (map #(dissoc % :strength) (:goals game))] ; 'strength' field has its own test
(is (= [{:team "STL" :min 3 :sec 36 :period "1"
:scorer {:player "<NAME>" :season-total 4}
:assists [{:player "<NAME>" :season-total 7}
{:player "<NAME>" :season-total 22}]}
{:team "STL" :min 12 :sec 53 :period "1"
:scorer {:player "<NAME>" :season-total 5}
:assists [{:player "<NAME>" :season-total 19}
{:player "<NAME>" :season-total 22}]}
{:team "STL" :min 10 :sec 38 :period "2"
:scorer {:player "<NAME>" :season-total 30}
:assists [{:player "<NAME>" :season-total 23}
{:player "<NAME>" :season-total 8}]}
{:team "OTT" :min 12 :sec 32 :period "2"
:scorer {:player "<NAME>" :season-total 2}
:assists [{:player "<NAME>" :season-total 27}
{:player "<NAME>" :season-total 26}]}
{:team "OTT" :min 17 :sec 19 :period "3"
:scorer {:player "<NAME>" :season-total 15}
:assists [{:player "<NAME>" :season-total 30}
{:player "<NAME>" :season-total 57}]}
{:team "OTT" :min 19 :sec 59 :period "3"
:scorer {:player "<NAME>" :season-total 16}
:assists [{:player "<NAME>" :season-total 27}
{:player "<NAME>" :season-total 7}]}
{:team "STL" :period "SO" :scorer {:player "<NAME>"}}]
goals) "Parsed goals")))
(testing "Parsing game with goal in playoff overtime"
(let [game (nth
(:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-in-regulation-and-overtime)
(:records resources/standings)))
2)]
(is (= {"CHI" 0 "STL" 1 :overtime true}
(:scores game)) "Parsed scores")
(is (= [{:team "STL" :min 9 :sec 4 :period "4"
:scorer {:player "<NAME>" :season-total 1}
:assists [{:player "<NAME>" :season-total 1}
{:player "<NAME>" :season-total 1}]}]
(:goals game)) "Parsed goals")))
(testing "Parsing empty net goal information"
(let [game (nth
(:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-in-regulation-and-overtime)
(:records resources/standings)))
1)
goals (:goals game)]
(is (= [false]
(distinct (map #(contains? % :empty-net) (drop-last goals))))
"All goals but the last one have no :empty-net field")
(is (= true
(:empty-net (last goals)))
"Last goal has :empty-net field set to true")))
(testing "Parsing goal strength (even / power play / short handed) information"
(let [game (nth
(:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-in-regulation-and-overtime)
(:records resources/standings)))
1)
goals (:goals game)]
(is (= [nil nil "PPG" "SHG" "PPG" nil nil]
(map #(:strength %) goals))
"Parsed goal strengths")
(is (= [false false true true true false false]
(map #(contains? % :strength) goals))
"Even strength goals don't contain :strength field"))))
(deftest game-scores-parsing-game-statuses
(testing "Parsing games' statuses"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-in-live-preview-and-final-states)
(:records resources/standings)))
statuses (map #(:status %) games)]
(is (= [{:state "FINAL"}
{:state "LIVE"
:progress {:current-period 3,
:current-period-ordinal "3rd",
:current-period-time-remaining {:pretty "08:58" :min 8 :sec 58}}}
{:state "LIVE"
:progress {:current-period 3,
:current-period-ordinal "3rd",
:current-period-time-remaining {:pretty "END" :min 0 :sec 0}}}
{:state "PREVIEW"}
{:state "PREVIEW"}
{:state "PREVIEW"}
{:state "POSTPONED"}]
statuses) "Parsed game statuses"))))
(deftest game-scores-parsing-game-start-times
(testing "Parsing games' start times"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-in-live-preview-and-final-states)
(:records resources/standings)))
start-times (map #(:start-time %) games)]
(is (= ["2016-02-28T17:30:00Z"
"2016-02-28T20:00:00Z"
"2016-02-28T20:00:00Z"
"2016-02-28T23:30:00Z"
"2016-02-29T00:00:00Z"
"2016-02-29T02:00:00Z"
"2016-02-29T02:30:00Z"]
start-times) "Parsed game start times"))))
(deftest game-scores-parsing-team-records
(testing "Parsing teams' pre-game regular season records"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
records (map #(:records (:pre-game-stats %)) games)]
(is (= 9
(count records)) "Parsed pre-game regular season records count")
(is (= [{"CAR" {:wins 28 :losses 26 :ot 10} "NJD" {:wins 30 :losses 26 :ot 7}}
{"CGY" {:wins 26 :losses 32 :ot 4} "BOS" {:wins 34 :losses 23 :ot 6}}
{"PIT" {:wins 32 :losses 21 :ot 8} "WSH" {:wins 45 :losses 12 :ot 4}}
{"STL" {:wins 36 :losses 20 :ot 9} "OTT" {:wins 30 :losses 27 :ot 6}}
{"EDM" {:wins 23 :losses 34 :ot 7} "BUF" {:wins 25 :losses 31 :ot 7}}
{"FLA" {:wins 35 :losses 19 :ot 8} "WPG" {:wins 26 :losses 31 :ot 4}}
{"COL" {:wins 32 :losses 28 :ot 4} "MIN" {:wins 28 :losses 25 :ot 10}}
{"DAL" {:wins 38 :losses 19 :ot 7} "NSH" {:wins 31 :losses 21 :ot 11}}
{"NYI" {:wins 33 :losses 20 :ot 7} "VAN" {:wins 24 :losses 25 :ot 12}}]
records) "Parsed pre-game regular season records")))
(testing "Parsing teams' current regular season records"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
records (map #(:records (:current-stats %)) games)]
(is (= 9
(count records)) "Parsed current regular season records count")
(is (= [{"CAR" {:wins 29 :losses 26 :ot 10} "NJD" {:wins 30 :losses 27 :ot 7}}
{"CGY" {:wins 26 :losses 33 :ot 4} "BOS" {:wins 35 :losses 23 :ot 6}}
{"PIT" {:wins 32 :losses 22 :ot 8} "WSH" {:wins 46 :losses 12 :ot 4}}
{"STL" {:wins 37 :losses 20 :ot 9} "OTT" {:wins 30 :losses 27 :ot 7}}
{"EDM" {:wins 24 :losses 34 :ot 7} "BUF" {:wins 25 :losses 31 :ot 8}}
{"FLA" {:wins 36 :losses 19 :ot 8} "WPG" {:wins 26 :losses 32 :ot 4}}
{"COL" {:wins 32 :losses 29 :ot 4} "MIN" {:wins 29 :losses 25 :ot 10}}
{"DAL" {:wins 38 :losses 20 :ot 7} "NSH" {:wins 32 :losses 21 :ot 11}}
{"NYI" {:wins 34 :losses 20 :ot 7} "VAN" {:wins 24 :losses 26 :ot 12}}]
records) "Parsed current regular season records"))))
(deftest game-scores-parsing-team-streaks
(testing "Parsing teams' current streaks"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
streaks (map #(:streaks (:current-stats %)) games)]
(is (= 9
(count streaks)) "Parsed streaks count")
(is (= [{"CAR" {:type "WINS" :count 3} "NJD" {:type "LOSSES" :count 1}}
{"CGY" {:type "LOSSES" :count 1} "BOS" {:type "WINS" :count 1}}
{"PIT" {:type "WINS" :count 1} "WSH" {:type "OT" :count 1}}
{"STL" {:type "WINS" :count 1} "OTT" {:type "LOSSES" :count 2}}
{"EDM" {:type "LOSSES" :count 1} "BUF" {:type "WINS" :count 1}}
{"FLA" {:type "WINS" :count 2} "WPG" {:type "WINS" :count 4}}
{"COL" {:type "WINS" :count 1} "MIN" {:type "WINS" :count 1}}
{"DAL" {:type "LOSSES" :count 3} "NSH" {:type "WINS" :count 3}}
{"NYI" {:type "OT" :count 2} "VAN" {:type "WINS" :count 1}}]
streaks) "Parsed streaks"))))
(deftest game-scores-parsing-team-ranks
(testing "Parsing teams' division and league ranks for regular season games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
pre-game-stats-standings (map #(:standings (:pre-game-stats %)) games)
current-stats-standings (map #(:standings (:current-stats %)) games)
ranks (map
#(fmap-vals (fn [team-stats] (select-keys team-stats [:division-rank :league-rank])) %)
current-stats-standings)]
(is (= (repeat 9 nil) pre-game-stats-standings) "Pre-game standings should not exist")
(is (= [{"CAR" {:division-rank "4" :league-rank "9"} "NJD" {:division-rank "8" :league-rank "26"}}
{"CGY" {:division-rank "4" :league-rank "19"} "BOS" {:division-rank "1" :league-rank "1"}}
{"PIT" {:division-rank "3" :league-rank "7"} "WSH" {:division-rank "1" :league-rank "5"}}
{"STL" {:division-rank "1" :league-rank "2"} "OTT" {:division-rank "7" :league-rank "30"}}
{"EDM" {:division-rank "2" :league-rank "12"} "BUF" {:division-rank "6" :league-rank "25"}}
{"FLA" {:division-rank "4" :league-rank "15"} "WPG" {:division-rank "5" :league-rank "20"}}
{"COL" {:division-rank "2" :league-rank "3"} "MIN" {:division-rank "6" :league-rank "21"}}
{"DAL" {:division-rank "3" :league-rank "10"} "NSH" {:division-rank "4" :league-rank "16"}}
{"NYI" {:division-rank "5" :league-rank "11"} "VAN" {:division-rank "3" :league-rank "17"}}]
ranks) "Parsed current stats division and league ranks")))
(testing "Parsing teams' division and league ranks for playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-in-regulation-and-overtime)
(:records resources/standings)))
pre-game-stats-standings (map #(:standings (:pre-game-stats %)) games)
current-stats-standings (map #(:standings (:current-stats %)) games)
ranks (map
#(fmap-vals (fn [team-stats] (select-keys team-stats [:division-rank :league-rank])) %)
current-stats-standings)]
(is (= pre-game-stats-standings current-stats-standings) "Parsed standings, pre-game vs. current stats")
(is (= [{"DET" {:division-rank "8" :league-rank "31"} "TBL" {:division-rank "2" :league-rank "4"}}
{"NYR" {:division-rank "7" :league-rank "18"} "PIT" {:division-rank "3" :league-rank "7"}}
{"CHI" {:division-rank "7" :league-rank "23"} "STL" {:division-rank "1" :league-rank "2"}}]
ranks) "Parsed current stats division and league ranks"))))
; TODO: Enable this again when "normal" playoff spot logic is resumed
(deftest ^:skip game-scores-parsing-team-points-from-playoff-spot
(testing "Parsing teams' points from playoff spot"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings-playoff-spots-per-division-5-3-4-4)))
standings (map #(:standings (:current-stats %)) games)
points-from-playoff-spot (map
#(fmap-vals (fn [team-stats] (select-keys team-stats [:points-from-playoff-spot])) %)
standings)]
(is (= 9
(count points-from-playoff-spot)) "Parsed points from playoff spot count")
; The test standings are:
;
; Eastern conference Western conference
;
; Metropolitan Central
; 1 WSH 79 pts 1 STL 74 pts
; 2 PIT 76 pts 2 DAL 73 pts
; 3 NYI 72 pts 3 COL 72 pts
; 4 CBJ 71 pts, 1st wild card 4 NSH 65 pts, 2nd wild card
; 5 PHI 71 pts, 2nd wild card ------------
; ------------ 5 WPG 63 pts
; 6 CAR 69 pts, 1st out of the playoffs 6 MIN 61 pts
; 7 NYR 64 pts 7 CHI 60 pts
; 8 NJD 52 pts
;
; Atlantic Pacific
; 1 BOS 84 pts 1 VAN 69 pts
; 2 TBL 83 pts 2 EDM 68 pts
; 3 TOR 70 pts 3 VGK 68 pts
; ------------ 4 CGY 66 pts, 1st wild card
; 4 FLA 66 pts ------------
; 5 MTL 62 pts 5 ARI 64 pts, 1st out of the playoffs
; 6 BUF 60 pts 6 SJS 56 pts
; 7 OTT 49 pts 7 ANA 53 pts
; 8 DET 32 pts 8 LAK 47 pts
(is (= [{"CAR" {:points-from-playoff-spot "-2"} "NJD" {:points-from-playoff-spot "-19"}}
{"CGY" {:points-from-playoff-spot "+2"} "BOS" {:points-from-playoff-spot "+18"}}
{"PIT" {:points-from-playoff-spot "+7"} "WSH" {:points-from-playoff-spot "+10"}}
{"STL" {:points-from-playoff-spot "+10"} "OTT" {:points-from-playoff-spot "-21"}}
{"EDM" {:points-from-playoff-spot "+4"} "BUF" {:points-from-playoff-spot "-10"}}
{"FLA" {:points-from-playoff-spot "-4"} "WPG" {:points-from-playoff-spot "-2"}}
{"COL" {:points-from-playoff-spot "+8"} "MIN" {:points-from-playoff-spot "-4"}}
{"DAL" {:points-from-playoff-spot "+9"} "NSH" {:points-from-playoff-spot "+1"}}
{"NYI" {:points-from-playoff-spot "+3"} "VAN" {:points-from-playoff-spot "+5"}}]
points-from-playoff-spot) "Parsed points from playoff spot"))))
(deftest game-scores-parsing-team-playoff-records
(testing "Parsing teams' pre-game playoff records when teams have no OT loss values in their records"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-live-finished-with-1st-games)
(:records resources/standings)))
records (map #(:records (:pre-game-stats %)) games)]
(is (= 5
(count records)) "Parsed pre-game playoff records count")
(is (= [{"NJD" {:wins 0 :losses 0} "TBL" {:wins 0 :losses 0}}
{"TOR" {:wins 0 :losses 0} "BOS" {:wins 0 :losses 0}}
{"CBJ" {:wins 0 :losses 0} "WSH" {:wins 0 :losses 0}}
{"COL" {:wins 0 :losses 0} "NSH" {:wins 0 :losses 0}}
{"SJS" {:wins 0 :losses 0} "ANA" {:wins 0 :losses 0}}]
records) "Parsed pre-game playoff records")))
(testing "Parsing teams' pre-game playoff records when teams have OT loss values in their records"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-with-ot-losses-in-records)
(:records resources/standings)))
records (map #(:records (:pre-game-stats %)) games)]
(is (= 5
(count records)) "Parsed pre-game playoff records count")
(is (= [{"CAR" {:wins 0 :losses 0 :ot 0} "NYR" {:wins 0 :losses 0 :ot 0}}
{"CHI" {:wins 0 :losses 0 :ot 0} "EDM" {:wins 0 :losses 0 :ot 0}}
{"FLA" {:wins 0 :losses 0 :ot 0} "NYI" {:wins 0 :losses 0 :ot 0}}
{"MTL" {:wins 0 :losses 0 :ot 0} "PIT" {:wins 0 :losses 0 :ot 0}}
{"CGY" {:wins 0 :losses 0 :ot 0} "WPG" {:wins 0 :losses 0 :ot 0}}]
records) "Parsed pre-game playoff records")))
(testing "Parsing teams' current playoff records"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-live-finished-with-1st-games)
(:records resources/standings)))
records (map #(:records (:current-stats %)) games)]
(is (= 5
(count records)) "Parsed current playoff records count")
(is (= [{"NJD" {:wins 0 :losses 1} "TBL" {:wins 1 :losses 0}}
{"TOR" {:wins 0 :losses 1} "BOS" {:wins 1 :losses 0}}
{"CBJ" {:wins 1 :losses 0} "WSH" {:wins 0 :losses 1}}
{"COL" {:wins 0 :losses 0} "NSH" {:wins 0 :losses 0}}
{"SJS" {:wins 0 :losses 0} "ANA" {:wins 0 :losses 0}}]
records) "Parsed current playoff records"))))
(deftest game-scores-parsing-playoff-series
(testing "Parsing pre-game playoff series wins from playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-with-2nd-games)
(:records resources/standings)))
playoff-series (map #(:playoff-series (:pre-game-stats %)) games)
wins (map :wins playoff-series)]
(is (= [{"DET" 0 "TBL" 1} {"NYI" 1 "FLA" 0} {"CHI" 0 "STL" 1} {"NSH" 0 "ANA" 0}]
wins) "Parsed pre-game playoff series wins")))
(testing "Parsing current playoff series wins from playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-with-2nd-games)
(:records resources/standings)))
playoff-series (map #(:playoff-series (:current-stats %)) games)
wins (map :wins playoff-series)]
(is (= [{"DET" 0 "TBL" 2} {"NYI" 1 "FLA" 1} {"CHI" 1 "STL" 1} {"NSH" 1 "ANA" 0}]
wins) "Parsed current playoff series wins")))
(testing "Parsing pre-game playoff series wins from first playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-live-finished-with-1st-games)
(:records resources/standings)))
playoff-series (map #(:playoff-series (:pre-game-stats %)) games)
wins (map :wins playoff-series)]
(is (= [{"NJD" 0 "TBL" 0} ; finished & up to date
{"TOR" 0 "BOS" 0} ; finished & up to date
{"CBJ" 0 "WSH" 0} ; finished & current game missing from seriesRecord
{"COL" 0 "NSH" 0} ; in-progress & up to date
{"SJS" 0 "ANA" 0}] ; in-progress & current game included in seriesRecord
wins) "Parsed pre-game playoff series wins")))
(testing "Parsing current playoff series wins from first playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-live-finished-with-1st-games)
(:records resources/standings)))
playoff-series (map #(:playoff-series (:current-stats %)) games)
wins (map :wins playoff-series)]
(is (= [{"NJD" 0 "TBL" 1} ; finished & up to date
{"TOR" 0 "BOS" 1} ; finished & up to date
{"CBJ" 1 "WSH" 0} ; finished & current game missing from seriesRecord
{"COL" 0 "NSH" 0} ; in-progress & up to date
{"SJS" 0 "ANA" 0}] ; in-progress & current game included in seriesRecord
wins) "Parsed current playoff series wins")))
(testing "Parsing playoff rounds from playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-live-finished-with-1st-games)
(:records resources/standings)))
pre-game-stats-playoff-series (map #(:playoff-series (:pre-game-stats %)) games)
current-stats-playoff-series (map #(:playoff-series (:current-stats %)) games)
pre-game-stats-rounds (map :round pre-game-stats-playoff-series)
current-stats-rounds (map :round current-stats-playoff-series)]
(is (= [1 1 1 1 1]
pre-game-stats-rounds) "Parsed pre-game stats playoff rounds")
(is (= [1 1 1 1 1]
current-stats-rounds) "Parsed current stats playoff rounds"))))
(deftest game-scores-pre-game-stats
(testing "Not including teams' pre-game stats"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)
false))]
(is (= [false]
(distinct (map #(contains? % :pre-game-stats) games)))
"Pre-game stats are not included"))))
(deftest game-scores-validation
(testing "Validating valid game with goals"
(let [game (first (:games
(parse-game-scores
(get-latest-games resources/games-in-live-preview-and-final-states)
(:records resources/standings))))]
(is (= (contains? game :errors) false) "No validation errors")))
(testing "Validating valid game without goals"
(let [game (nth (:games
(parse-game-scores
(get-latest-games resources/games-in-live-preview-and-final-states)
(:records resources/standings)))
3)]
(is (= (contains? game :errors) false) "No validation errors")))
(testing "Validating valid non-finished game with multiple shootout goals"
(let [game (nth (:games
(parse-game-scores
(get-latest-games resources/games-for-validation-testing)
(:records resources/standings)))
4)]
(is (= (contains? game :errors) false) "No validation errors")))
(testing "Validating valid finished game with multiple shootout goals"
(let [game (nth (:games
(parse-game-scores
(get-latest-games resources/games-for-validation-testing)
(:records resources/standings)))
3)]
(is (= (contains? game :errors) false) "No validation errors")))
(testing "Validating game missing all goals"
(let [game (first (:games
(parse-game-scores
(get-latest-games resources/games-for-validation-testing)
(:records resources/standings))))]
(is (= (contains? game :errors) true) "Contains validation errors")
(is (= [{:error :MISSING-ALL-GOALS}]
(:errors game)) "Errors contain 'missing all goals' error")))
(testing "Validating game missing one goal"
(let [game (second (:games
(parse-game-scores
(get-latest-games resources/games-for-validation-testing)
(:records resources/standings))))]
(is (= (contains? game :errors) true) "Contains validation errors")
(is (= [{:error :SCORE-AND-GOAL-COUNT-MISMATCH :details {:goal-count 4 :score-count 5}}]
(:errors game)) "Errors contain expected 'score and goal count mismatch' error")))
(testing "Validating game having one goal too many"
(let [game (nth (:games
(parse-game-scores
(get-latest-games resources/games-for-validation-testing)
(:records resources/standings)))
2)]
(is (= (contains? game :errors) true) "Contains validation errors")
(is (= [{:error :SCORE-AND-GOAL-COUNT-MISMATCH :details {:goal-count 5 :score-count 3}}]
(:errors game)) "Errors contain expected 'score and goal count mismatch' error"))))
| true | (ns nhl-score-api.fetchers.nhlstats.game-scores-test
(:require [clojure.test :refer :all]
[nhl-score-api.fetchers.nhlstats.game-scores :refer :all]
[nhl-score-api.fetchers.nhlstats.transformer :refer [get-latest-games]]
[nhl-score-api.fetchers.nhlstats.resources :as resources]
[nhl-score-api.utils :refer [fmap-vals]]))
(deftest game-scores-parsing-scores
(testing "Parsing scores with games finished in overtime and in shootout"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))]
(is (= 9
(count games)) "Parsed game count")
(is (= [4 3 5 7 3 5 9 8 5]
(map #(count (:goals %)) games)) "Parsed goal count")
(is (= [{:away {:abbreviation "CAR" :id 12 :location-name "Carolina" :short-name "Carolina" :team-name "Hurricanes"}
:home {:abbreviation "NJD" :id 1 :location-name "New Jersey" :short-name "New Jersey" :team-name "Devils"}}
{:away {:abbreviation "CGY" :id 20 :location-name "Calgary" :short-name "Calgary" :team-name "Flames"}
:home {:abbreviation "BOS" :id 6 :location-name "Boston" :short-name "Boston" :team-name "Bruins"}}
{:away {:abbreviation "PIT" :id 5 :location-name "Pittsburgh" :short-name "Pittsburgh" :team-name "Penguins"}
:home {:abbreviation "WSH" :id 15 :location-name "Washington" :short-name "Washington" :team-name "Capitals"}}
{:away {:abbreviation "STL" :id 19 :location-name "St. Louis" :short-name "St Louis" :team-name "Blues"}
:home {:abbreviation "OTT" :id 9 :location-name "Ottawa" :short-name "Ottawa" :team-name "Senators"}}
{:away {:abbreviation "EDM" :id 22 :location-name "Edmonton" :short-name "Edmonton" :team-name "Oilers"}
:home {:abbreviation "BUF" :id 7 :location-name "Buffalo" :short-name "Buffalo" :team-name "Sabres"}}
{:away {:abbreviation "FLA" :id 13 :location-name "Florida" :short-name "Florida" :team-name "Panthers"}
:home {:abbreviation "WPG" :id 52 :location-name "Winnipeg" :short-name "Winnipeg" :team-name "Jets"}}
{:away {:abbreviation "COL" :id 21 :location-name "Colorado" :short-name "Colorado" :team-name "Avalanche"}
:home {:abbreviation "MIN" :id 30 :location-name "Minnesota" :short-name "Minnesota" :team-name "Wild"}}
{:away {:abbreviation "DAL" :id 25 :location-name "Dallas" :short-name "Dallas" :team-name "Stars"}
:home {:abbreviation "NSH" :id 18 :location-name "Nashville" :short-name "Nashville" :team-name "Predators"}}
{:away {:abbreviation "NYI" :id 2 :location-name "New York" :short-name "NY Islanders" :team-name "Islanders"}
:home {:abbreviation "VAN" :id 23 :location-name "Vancouver" :short-name "Vancouver" :team-name "Canucks"}}]
(map :teams games)) "Parsed teams")
(is (= [{"CAR" 3 "NJD" 1} {"CGY" 1 "BOS" 2} {"PIT" 2 "WSH" 3} {"STL" 4 "OTT" 3 :shootout true}
{"EDM" 2 "BUF" 1 :overtime true} {"FLA" 3 "WPG" 2} {"COL" 3 "MIN" 6} {"DAL" 3 "NSH" 5}
{"NYI" 3 "VAN" 2}]
(map :scores games)) "Parsed scores")
(is (= [false]
(distinct (map #(contains? % :playoff-series) games))))))
(testing "Parsing scores with games finished, on-going and not yet started"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-in-live-preview-and-final-states)
(:records resources/standings)))]
(is (= 7
(count games)) "Parsed game count")
(is (= 1
(count (filter #(= (:state (:status %)) "FINAL") games))) "Parsed finished game count")
(is (= 2
(count (filter #(= (:state (:status %)) "LIVE") games))) "Parsed on-going game count")
(is (= 3
(count (filter #(= (:state (:status %)) "PREVIEW") games))) "Parsed not started game count")
(is (= 1
(count (filter #(= (:state (:status %)) "POSTPONED") games))) "Parsed postponed game count")
(is (= [5 2 5 0 0 0 0]
(map #(count (:goals %)) games)) "Parsed goal count")
(is (= [{:away {:abbreviation "WSH" :id 15 :location-name "Washington" :short-name "Washington" :team-name "Capitals"}
:home {:abbreviation "CHI" :id 16 :location-name "Chicago" :short-name "Chicago" :team-name "Blackhawks"}}
{:away {:abbreviation "FLA" :id 13 :location-name "Florida" :short-name "Florida" :team-name "Panthers"}
:home {:abbreviation "MIN" :id 30 :location-name "Minnesota" :short-name "Minnesota" :team-name "Wild"}}
{:away {:abbreviation "STL" :id 19 :location-name "St. Louis" :short-name "St Louis" :team-name "Blues"}
:home {:abbreviation "CAR" :id 12 :location-name "Carolina" :short-name "Carolina" :team-name "Hurricanes"}}
{:away {:abbreviation "TBL" :id 14 :location-name "Tampa Bay" :short-name "Tampa Bay" :team-name "Lightning"}
:home {:abbreviation "BOS" :id 6 :location-name "Boston" :short-name "Boston" :team-name "Bruins"}}
{:away {:abbreviation "SJS" :id 28 :location-name "San Jose" :short-name "San Jose" :team-name "Sharks"}
:home {:abbreviation "VAN" :id 23 :location-name "Vancouver" :short-name "Vancouver" :team-name "Canucks"}}
{:away {:abbreviation "LAK" :id 26 :location-name "Los Angeles" :short-name "Los Angeles" :team-name "Kings"}
:home {:abbreviation "ANA" :id 24 :location-name "Anaheim" :short-name "Anaheim" :team-name "Ducks"}}
{:away {:abbreviation "NYI" :id 2 :location-name "New York" :short-name "NY Islanders" :team-name "Islanders"}
:home {:abbreviation "EDM" :id 22 :location-name "Edmonton" :short-name "Edmonton" :team-name "Oilers"}}]
(map :teams games)) "Parsed teams")
(is (= [{"WSH" 2 "CHI" 3} {"FLA" 1 "MIN" 1} {"STL" 3 "CAR" 2}
{"TBL" 0 "BOS" 0} {"SJS" 0 "VAN" 0} {"LAK" 0 "ANA" 0} {"NYI" 0 "EDM" 0}]
(map :scores games)) "Parsed scores")
(is (= [false]
(distinct (map #(contains? % :playoff-series) games)))))))
(deftest game-scores-parsing-games
(testing "Parsing game with goals in regulation and overtime"
(let [game (nth
(:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
4)
goals (:goals game)]
(is (= [{:team "EDM" :min 0 :sec 22 :period "1"
:scorer {:player "PI:NAME:<NAME>END_PI" :season-total 11}
:assists [{:player "PI:NAME:<NAME>END_PI" :season-total 19}]}
{:team "BUF" :min 9 :sec 6 :period "3"
:scorer {:player "PI:NAME:<NAME>END_PI" :season-total 1}
:assists [{:player "PI:NAME:<NAME>END_PI" :season-total 11}
{:player "PI:NAME:<NAME>END_PI" :season-total 5}]}
{:team "EDM" :min 3 :sec 48 :period "OT"
:scorer {:player "PI:NAME:<NAME>END_PI" :season-total 12}
:assists []}]
goals) "Parsed goals")))
(testing "Parsing game with goals in regulation and shootout"
(let [game (nth
(:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
3)
goals (map #(dissoc % :strength) (:goals game))] ; 'strength' field has its own test
(is (= [{:team "STL" :min 3 :sec 36 :period "1"
:scorer {:player "PI:NAME:<NAME>END_PI" :season-total 4}
:assists [{:player "PI:NAME:<NAME>END_PI" :season-total 7}
{:player "PI:NAME:<NAME>END_PI" :season-total 22}]}
{:team "STL" :min 12 :sec 53 :period "1"
:scorer {:player "PI:NAME:<NAME>END_PI" :season-total 5}
:assists [{:player "PI:NAME:<NAME>END_PI" :season-total 19}
{:player "PI:NAME:<NAME>END_PI" :season-total 22}]}
{:team "STL" :min 10 :sec 38 :period "2"
:scorer {:player "PI:NAME:<NAME>END_PI" :season-total 30}
:assists [{:player "PI:NAME:<NAME>END_PI" :season-total 23}
{:player "PI:NAME:<NAME>END_PI" :season-total 8}]}
{:team "OTT" :min 12 :sec 32 :period "2"
:scorer {:player "PI:NAME:<NAME>END_PI" :season-total 2}
:assists [{:player "PI:NAME:<NAME>END_PI" :season-total 27}
{:player "PI:NAME:<NAME>END_PI" :season-total 26}]}
{:team "OTT" :min 17 :sec 19 :period "3"
:scorer {:player "PI:NAME:<NAME>END_PI" :season-total 15}
:assists [{:player "PI:NAME:<NAME>END_PI" :season-total 30}
{:player "PI:NAME:<NAME>END_PI" :season-total 57}]}
{:team "OTT" :min 19 :sec 59 :period "3"
:scorer {:player "PI:NAME:<NAME>END_PI" :season-total 16}
:assists [{:player "PI:NAME:<NAME>END_PI" :season-total 27}
{:player "PI:NAME:<NAME>END_PI" :season-total 7}]}
{:team "STL" :period "SO" :scorer {:player "PI:NAME:<NAME>END_PI"}}]
goals) "Parsed goals")))
(testing "Parsing game with goal in playoff overtime"
(let [game (nth
(:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-in-regulation-and-overtime)
(:records resources/standings)))
2)]
(is (= {"CHI" 0 "STL" 1 :overtime true}
(:scores game)) "Parsed scores")
(is (= [{:team "STL" :min 9 :sec 4 :period "4"
:scorer {:player "PI:NAME:<NAME>END_PI" :season-total 1}
:assists [{:player "PI:NAME:<NAME>END_PI" :season-total 1}
{:player "PI:NAME:<NAME>END_PI" :season-total 1}]}]
(:goals game)) "Parsed goals")))
(testing "Parsing empty net goal information"
(let [game (nth
(:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-in-regulation-and-overtime)
(:records resources/standings)))
1)
goals (:goals game)]
(is (= [false]
(distinct (map #(contains? % :empty-net) (drop-last goals))))
"All goals but the last one have no :empty-net field")
(is (= true
(:empty-net (last goals)))
"Last goal has :empty-net field set to true")))
(testing "Parsing goal strength (even / power play / short handed) information"
(let [game (nth
(:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-in-regulation-and-overtime)
(:records resources/standings)))
1)
goals (:goals game)]
(is (= [nil nil "PPG" "SHG" "PPG" nil nil]
(map #(:strength %) goals))
"Parsed goal strengths")
(is (= [false false true true true false false]
(map #(contains? % :strength) goals))
"Even strength goals don't contain :strength field"))))
(deftest game-scores-parsing-game-statuses
(testing "Parsing games' statuses"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-in-live-preview-and-final-states)
(:records resources/standings)))
statuses (map #(:status %) games)]
(is (= [{:state "FINAL"}
{:state "LIVE"
:progress {:current-period 3,
:current-period-ordinal "3rd",
:current-period-time-remaining {:pretty "08:58" :min 8 :sec 58}}}
{:state "LIVE"
:progress {:current-period 3,
:current-period-ordinal "3rd",
:current-period-time-remaining {:pretty "END" :min 0 :sec 0}}}
{:state "PREVIEW"}
{:state "PREVIEW"}
{:state "PREVIEW"}
{:state "POSTPONED"}]
statuses) "Parsed game statuses"))))
(deftest game-scores-parsing-game-start-times
(testing "Parsing games' start times"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-in-live-preview-and-final-states)
(:records resources/standings)))
start-times (map #(:start-time %) games)]
(is (= ["2016-02-28T17:30:00Z"
"2016-02-28T20:00:00Z"
"2016-02-28T20:00:00Z"
"2016-02-28T23:30:00Z"
"2016-02-29T00:00:00Z"
"2016-02-29T02:00:00Z"
"2016-02-29T02:30:00Z"]
start-times) "Parsed game start times"))))
(deftest game-scores-parsing-team-records
(testing "Parsing teams' pre-game regular season records"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
records (map #(:records (:pre-game-stats %)) games)]
(is (= 9
(count records)) "Parsed pre-game regular season records count")
(is (= [{"CAR" {:wins 28 :losses 26 :ot 10} "NJD" {:wins 30 :losses 26 :ot 7}}
{"CGY" {:wins 26 :losses 32 :ot 4} "BOS" {:wins 34 :losses 23 :ot 6}}
{"PIT" {:wins 32 :losses 21 :ot 8} "WSH" {:wins 45 :losses 12 :ot 4}}
{"STL" {:wins 36 :losses 20 :ot 9} "OTT" {:wins 30 :losses 27 :ot 6}}
{"EDM" {:wins 23 :losses 34 :ot 7} "BUF" {:wins 25 :losses 31 :ot 7}}
{"FLA" {:wins 35 :losses 19 :ot 8} "WPG" {:wins 26 :losses 31 :ot 4}}
{"COL" {:wins 32 :losses 28 :ot 4} "MIN" {:wins 28 :losses 25 :ot 10}}
{"DAL" {:wins 38 :losses 19 :ot 7} "NSH" {:wins 31 :losses 21 :ot 11}}
{"NYI" {:wins 33 :losses 20 :ot 7} "VAN" {:wins 24 :losses 25 :ot 12}}]
records) "Parsed pre-game regular season records")))
(testing "Parsing teams' current regular season records"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
records (map #(:records (:current-stats %)) games)]
(is (= 9
(count records)) "Parsed current regular season records count")
(is (= [{"CAR" {:wins 29 :losses 26 :ot 10} "NJD" {:wins 30 :losses 27 :ot 7}}
{"CGY" {:wins 26 :losses 33 :ot 4} "BOS" {:wins 35 :losses 23 :ot 6}}
{"PIT" {:wins 32 :losses 22 :ot 8} "WSH" {:wins 46 :losses 12 :ot 4}}
{"STL" {:wins 37 :losses 20 :ot 9} "OTT" {:wins 30 :losses 27 :ot 7}}
{"EDM" {:wins 24 :losses 34 :ot 7} "BUF" {:wins 25 :losses 31 :ot 8}}
{"FLA" {:wins 36 :losses 19 :ot 8} "WPG" {:wins 26 :losses 32 :ot 4}}
{"COL" {:wins 32 :losses 29 :ot 4} "MIN" {:wins 29 :losses 25 :ot 10}}
{"DAL" {:wins 38 :losses 20 :ot 7} "NSH" {:wins 32 :losses 21 :ot 11}}
{"NYI" {:wins 34 :losses 20 :ot 7} "VAN" {:wins 24 :losses 26 :ot 12}}]
records) "Parsed current regular season records"))))
(deftest game-scores-parsing-team-streaks
(testing "Parsing teams' current streaks"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
streaks (map #(:streaks (:current-stats %)) games)]
(is (= 9
(count streaks)) "Parsed streaks count")
(is (= [{"CAR" {:type "WINS" :count 3} "NJD" {:type "LOSSES" :count 1}}
{"CGY" {:type "LOSSES" :count 1} "BOS" {:type "WINS" :count 1}}
{"PIT" {:type "WINS" :count 1} "WSH" {:type "OT" :count 1}}
{"STL" {:type "WINS" :count 1} "OTT" {:type "LOSSES" :count 2}}
{"EDM" {:type "LOSSES" :count 1} "BUF" {:type "WINS" :count 1}}
{"FLA" {:type "WINS" :count 2} "WPG" {:type "WINS" :count 4}}
{"COL" {:type "WINS" :count 1} "MIN" {:type "WINS" :count 1}}
{"DAL" {:type "LOSSES" :count 3} "NSH" {:type "WINS" :count 3}}
{"NYI" {:type "OT" :count 2} "VAN" {:type "WINS" :count 1}}]
streaks) "Parsed streaks"))))
(deftest game-scores-parsing-team-ranks
(testing "Parsing teams' division and league ranks for regular season games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)))
pre-game-stats-standings (map #(:standings (:pre-game-stats %)) games)
current-stats-standings (map #(:standings (:current-stats %)) games)
ranks (map
#(fmap-vals (fn [team-stats] (select-keys team-stats [:division-rank :league-rank])) %)
current-stats-standings)]
(is (= (repeat 9 nil) pre-game-stats-standings) "Pre-game standings should not exist")
(is (= [{"CAR" {:division-rank "4" :league-rank "9"} "NJD" {:division-rank "8" :league-rank "26"}}
{"CGY" {:division-rank "4" :league-rank "19"} "BOS" {:division-rank "1" :league-rank "1"}}
{"PIT" {:division-rank "3" :league-rank "7"} "WSH" {:division-rank "1" :league-rank "5"}}
{"STL" {:division-rank "1" :league-rank "2"} "OTT" {:division-rank "7" :league-rank "30"}}
{"EDM" {:division-rank "2" :league-rank "12"} "BUF" {:division-rank "6" :league-rank "25"}}
{"FLA" {:division-rank "4" :league-rank "15"} "WPG" {:division-rank "5" :league-rank "20"}}
{"COL" {:division-rank "2" :league-rank "3"} "MIN" {:division-rank "6" :league-rank "21"}}
{"DAL" {:division-rank "3" :league-rank "10"} "NSH" {:division-rank "4" :league-rank "16"}}
{"NYI" {:division-rank "5" :league-rank "11"} "VAN" {:division-rank "3" :league-rank "17"}}]
ranks) "Parsed current stats division and league ranks")))
(testing "Parsing teams' division and league ranks for playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-in-regulation-and-overtime)
(:records resources/standings)))
pre-game-stats-standings (map #(:standings (:pre-game-stats %)) games)
current-stats-standings (map #(:standings (:current-stats %)) games)
ranks (map
#(fmap-vals (fn [team-stats] (select-keys team-stats [:division-rank :league-rank])) %)
current-stats-standings)]
(is (= pre-game-stats-standings current-stats-standings) "Parsed standings, pre-game vs. current stats")
(is (= [{"DET" {:division-rank "8" :league-rank "31"} "TBL" {:division-rank "2" :league-rank "4"}}
{"NYR" {:division-rank "7" :league-rank "18"} "PIT" {:division-rank "3" :league-rank "7"}}
{"CHI" {:division-rank "7" :league-rank "23"} "STL" {:division-rank "1" :league-rank "2"}}]
ranks) "Parsed current stats division and league ranks"))))
; TODO: Enable this again when "normal" playoff spot logic is resumed
(deftest ^:skip game-scores-parsing-team-points-from-playoff-spot
(testing "Parsing teams' points from playoff spot"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings-playoff-spots-per-division-5-3-4-4)))
standings (map #(:standings (:current-stats %)) games)
points-from-playoff-spot (map
#(fmap-vals (fn [team-stats] (select-keys team-stats [:points-from-playoff-spot])) %)
standings)]
(is (= 9
(count points-from-playoff-spot)) "Parsed points from playoff spot count")
; The test standings are:
;
; Eastern conference Western conference
;
; Metropolitan Central
; 1 WSH 79 pts 1 STL 74 pts
; 2 PIT 76 pts 2 DAL 73 pts
; 3 NYI 72 pts 3 COL 72 pts
; 4 CBJ 71 pts, 1st wild card 4 NSH 65 pts, 2nd wild card
; 5 PHI 71 pts, 2nd wild card ------------
; ------------ 5 WPG 63 pts
; 6 CAR 69 pts, 1st out of the playoffs 6 MIN 61 pts
; 7 NYR 64 pts 7 CHI 60 pts
; 8 NJD 52 pts
;
; Atlantic Pacific
; 1 BOS 84 pts 1 VAN 69 pts
; 2 TBL 83 pts 2 EDM 68 pts
; 3 TOR 70 pts 3 VGK 68 pts
; ------------ 4 CGY 66 pts, 1st wild card
; 4 FLA 66 pts ------------
; 5 MTL 62 pts 5 ARI 64 pts, 1st out of the playoffs
; 6 BUF 60 pts 6 SJS 56 pts
; 7 OTT 49 pts 7 ANA 53 pts
; 8 DET 32 pts 8 LAK 47 pts
(is (= [{"CAR" {:points-from-playoff-spot "-2"} "NJD" {:points-from-playoff-spot "-19"}}
{"CGY" {:points-from-playoff-spot "+2"} "BOS" {:points-from-playoff-spot "+18"}}
{"PIT" {:points-from-playoff-spot "+7"} "WSH" {:points-from-playoff-spot "+10"}}
{"STL" {:points-from-playoff-spot "+10"} "OTT" {:points-from-playoff-spot "-21"}}
{"EDM" {:points-from-playoff-spot "+4"} "BUF" {:points-from-playoff-spot "-10"}}
{"FLA" {:points-from-playoff-spot "-4"} "WPG" {:points-from-playoff-spot "-2"}}
{"COL" {:points-from-playoff-spot "+8"} "MIN" {:points-from-playoff-spot "-4"}}
{"DAL" {:points-from-playoff-spot "+9"} "NSH" {:points-from-playoff-spot "+1"}}
{"NYI" {:points-from-playoff-spot "+3"} "VAN" {:points-from-playoff-spot "+5"}}]
points-from-playoff-spot) "Parsed points from playoff spot"))))
(deftest game-scores-parsing-team-playoff-records
(testing "Parsing teams' pre-game playoff records when teams have no OT loss values in their records"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-live-finished-with-1st-games)
(:records resources/standings)))
records (map #(:records (:pre-game-stats %)) games)]
(is (= 5
(count records)) "Parsed pre-game playoff records count")
(is (= [{"NJD" {:wins 0 :losses 0} "TBL" {:wins 0 :losses 0}}
{"TOR" {:wins 0 :losses 0} "BOS" {:wins 0 :losses 0}}
{"CBJ" {:wins 0 :losses 0} "WSH" {:wins 0 :losses 0}}
{"COL" {:wins 0 :losses 0} "NSH" {:wins 0 :losses 0}}
{"SJS" {:wins 0 :losses 0} "ANA" {:wins 0 :losses 0}}]
records) "Parsed pre-game playoff records")))
(testing "Parsing teams' pre-game playoff records when teams have OT loss values in their records"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-with-ot-losses-in-records)
(:records resources/standings)))
records (map #(:records (:pre-game-stats %)) games)]
(is (= 5
(count records)) "Parsed pre-game playoff records count")
(is (= [{"CAR" {:wins 0 :losses 0 :ot 0} "NYR" {:wins 0 :losses 0 :ot 0}}
{"CHI" {:wins 0 :losses 0 :ot 0} "EDM" {:wins 0 :losses 0 :ot 0}}
{"FLA" {:wins 0 :losses 0 :ot 0} "NYI" {:wins 0 :losses 0 :ot 0}}
{"MTL" {:wins 0 :losses 0 :ot 0} "PIT" {:wins 0 :losses 0 :ot 0}}
{"CGY" {:wins 0 :losses 0 :ot 0} "WPG" {:wins 0 :losses 0 :ot 0}}]
records) "Parsed pre-game playoff records")))
(testing "Parsing teams' current playoff records"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-live-finished-with-1st-games)
(:records resources/standings)))
records (map #(:records (:current-stats %)) games)]
(is (= 5
(count records)) "Parsed current playoff records count")
(is (= [{"NJD" {:wins 0 :losses 1} "TBL" {:wins 1 :losses 0}}
{"TOR" {:wins 0 :losses 1} "BOS" {:wins 1 :losses 0}}
{"CBJ" {:wins 1 :losses 0} "WSH" {:wins 0 :losses 1}}
{"COL" {:wins 0 :losses 0} "NSH" {:wins 0 :losses 0}}
{"SJS" {:wins 0 :losses 0} "ANA" {:wins 0 :losses 0}}]
records) "Parsed current playoff records"))))
(deftest game-scores-parsing-playoff-series
(testing "Parsing pre-game playoff series wins from playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-with-2nd-games)
(:records resources/standings)))
playoff-series (map #(:playoff-series (:pre-game-stats %)) games)
wins (map :wins playoff-series)]
(is (= [{"DET" 0 "TBL" 1} {"NYI" 1 "FLA" 0} {"CHI" 0 "STL" 1} {"NSH" 0 "ANA" 0}]
wins) "Parsed pre-game playoff series wins")))
(testing "Parsing current playoff series wins from playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-finished-with-2nd-games)
(:records resources/standings)))
playoff-series (map #(:playoff-series (:current-stats %)) games)
wins (map :wins playoff-series)]
(is (= [{"DET" 0 "TBL" 2} {"NYI" 1 "FLA" 1} {"CHI" 1 "STL" 1} {"NSH" 1 "ANA" 0}]
wins) "Parsed current playoff series wins")))
(testing "Parsing pre-game playoff series wins from first playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-live-finished-with-1st-games)
(:records resources/standings)))
playoff-series (map #(:playoff-series (:pre-game-stats %)) games)
wins (map :wins playoff-series)]
(is (= [{"NJD" 0 "TBL" 0} ; finished & up to date
{"TOR" 0 "BOS" 0} ; finished & up to date
{"CBJ" 0 "WSH" 0} ; finished & current game missing from seriesRecord
{"COL" 0 "NSH" 0} ; in-progress & up to date
{"SJS" 0 "ANA" 0}] ; in-progress & current game included in seriesRecord
wins) "Parsed pre-game playoff series wins")))
(testing "Parsing current playoff series wins from first playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-live-finished-with-1st-games)
(:records resources/standings)))
playoff-series (map #(:playoff-series (:current-stats %)) games)
wins (map :wins playoff-series)]
(is (= [{"NJD" 0 "TBL" 1} ; finished & up to date
{"TOR" 0 "BOS" 1} ; finished & up to date
{"CBJ" 1 "WSH" 0} ; finished & current game missing from seriesRecord
{"COL" 0 "NSH" 0} ; in-progress & up to date
{"SJS" 0 "ANA" 0}] ; in-progress & current game included in seriesRecord
wins) "Parsed current playoff series wins")))
(testing "Parsing playoff rounds from playoff games"
(let [games (:games
(parse-game-scores
(get-latest-games resources/playoff-games-live-finished-with-1st-games)
(:records resources/standings)))
pre-game-stats-playoff-series (map #(:playoff-series (:pre-game-stats %)) games)
current-stats-playoff-series (map #(:playoff-series (:current-stats %)) games)
pre-game-stats-rounds (map :round pre-game-stats-playoff-series)
current-stats-rounds (map :round current-stats-playoff-series)]
(is (= [1 1 1 1 1]
pre-game-stats-rounds) "Parsed pre-game stats playoff rounds")
(is (= [1 1 1 1 1]
current-stats-rounds) "Parsed current stats playoff rounds"))))
(deftest game-scores-pre-game-stats
(testing "Not including teams' pre-game stats"
(let [games (:games
(parse-game-scores
(get-latest-games resources/games-finished-in-regulation-overtime-and-shootout)
(:records resources/standings)
false))]
(is (= [false]
(distinct (map #(contains? % :pre-game-stats) games)))
"Pre-game stats are not included"))))
(deftest game-scores-validation
(testing "Validating valid game with goals"
(let [game (first (:games
(parse-game-scores
(get-latest-games resources/games-in-live-preview-and-final-states)
(:records resources/standings))))]
(is (= (contains? game :errors) false) "No validation errors")))
(testing "Validating valid game without goals"
(let [game (nth (:games
(parse-game-scores
(get-latest-games resources/games-in-live-preview-and-final-states)
(:records resources/standings)))
3)]
(is (= (contains? game :errors) false) "No validation errors")))
(testing "Validating valid non-finished game with multiple shootout goals"
(let [game (nth (:games
(parse-game-scores
(get-latest-games resources/games-for-validation-testing)
(:records resources/standings)))
4)]
(is (= (contains? game :errors) false) "No validation errors")))
(testing "Validating valid finished game with multiple shootout goals"
(let [game (nth (:games
(parse-game-scores
(get-latest-games resources/games-for-validation-testing)
(:records resources/standings)))
3)]
(is (= (contains? game :errors) false) "No validation errors")))
(testing "Validating game missing all goals"
(let [game (first (:games
(parse-game-scores
(get-latest-games resources/games-for-validation-testing)
(:records resources/standings))))]
(is (= (contains? game :errors) true) "Contains validation errors")
(is (= [{:error :MISSING-ALL-GOALS}]
(:errors game)) "Errors contain 'missing all goals' error")))
(testing "Validating game missing one goal"
(let [game (second (:games
(parse-game-scores
(get-latest-games resources/games-for-validation-testing)
(:records resources/standings))))]
(is (= (contains? game :errors) true) "Contains validation errors")
(is (= [{:error :SCORE-AND-GOAL-COUNT-MISMATCH :details {:goal-count 4 :score-count 5}}]
(:errors game)) "Errors contain expected 'score and goal count mismatch' error")))
(testing "Validating game having one goal too many"
(let [game (nth (:games
(parse-game-scores
(get-latest-games resources/games-for-validation-testing)
(:records resources/standings)))
2)]
(is (= (contains? game :errors) true) "Contains validation errors")
(is (= [{:error :SCORE-AND-GOAL-COUNT-MISMATCH :details {:goal-count 5 :score-count 3}}]
(:errors game)) "Errors contain expected 'score and goal count mismatch' error"))))
|
[
{
"context": " :b true})))\n (is (= [(key/parse \"807B00810102C8\")\n {:z :foo}]\n (record/encod",
"end": 1938,
"score": 0.9874712228775024,
"start": 1924,
"tag": "KEY",
"value": "807B00810102C8"
},
{
"context": "icoder\n nil\n [(key/parse \"807B\")\n {:a \"abc\", :b true}])))\n (is (",
"end": 2401,
"score": 0.9268919229507446,
"start": 2397,
"tag": "KEY",
"value": "807B"
},
{
"context": "r)\n [:x :y]\n [(key/parse \"807B00810102C8\")\n {:z :foo}])))))\n\n\n(deftest family",
"end": 2703,
"score": 0.9928449392318726,
"start": 2689,
"tag": "KEY",
"value": "807B00810102C8"
}
] | lib/core/test/merkle_db/record_test.clj | greglook/merkle-db | 47 | (ns merkle-db.record-test
(:require
[clojure.spec.alpha :as s]
[clojure.test :refer :all]
[merkle-db.key :as key]
[merkle-db.record :as record]
[merkle-db.test-utils]))
(deftest record-specs
(testing "id fields"
(is (invalid? ::record/id-field nil))
(is (invalid? ::record/id-field #{:a}))
(is (invalid? ::record/id-field []))
(is (valid? ::record/id-field :id))
(is (valid? ::record/id-field [:a]))
(is (valid? ::record/id-field [:a :b :c]))
(is (invalid? ::record/id-field [:a :a])
"no duplicates")
(is (invalid? ::record/id-field [#{:foo} :bar nil])
"elements must be valid field keys"))
(testing "record data"
(is (invalid? ::record/data nil))
(is (invalid? ::record/data []))
(is (valid? ::record/data {}))
(is (valid? ::record/data {:foo true, :bar "---", :baz 123})))
(testing "family maps"
(is (invalid? ::record/families nil))
(is (invalid? ::record/families []))
(is (valid? ::record/families {}))
(is (valid? ::record/families {:bc #{:b :c}}))
(is (valid? ::record/families {:bc #{:b :c}, :ad #{:a :d}}))
(is (invalid? ::record/families {"foo" #{:a}}))
(is (invalid? ::record/families {:qualified/family #{:a}}))
(is (invalid? ::record/families {:not-a-set [:a]}))
(is (invalid? ::record/families {:bc #{:b :c}, :cd #{:c :d}}))))
(deftest entry-encoding
(testing "id projection"
(is (= 123 (record/project-id nil {::record/id 123}))
"field defaults to ::record/id")
(is (= "xyz" (record/project-id :id {:id "xyz"})))
(is (= [123 "abc"] (record/project-id [:a :b] {:a 123, :b "abc"}))))
(testing "encoding"
(is (= [(key/parse "807B")
{:a "abc", :b true}]
(record/encode-entry
key/integer-lexicoder
nil
{::record/id 123
:a "abc"
:b true})))
(is (= [(key/parse "807B00810102C8")
{:z :foo}]
(record/encode-entry
(key/tuple-lexicoder
key/integer-lexicoder
key/integer-lexicoder)
[:x :y]
{:x 123
:y 456
:z :foo}))))
(testing "decoding"
(is (= {::record/id 123
:a "abc"
:b true}
(record/decode-entry
key/integer-lexicoder
nil
[(key/parse "807B")
{:a "abc", :b true}])))
(is (= {:x 123
:y 456
:z :foo}
(record/decode-entry
(key/tuple-lexicoder
key/integer-lexicoder
key/integer-lexicoder)
[:x :y]
[(key/parse "807B00810102C8")
{:z :foo}])))))
(deftest family-grouping
(let [k0 (key/create [0])
r0 {}
k1 (key/create [1])
r1 {:a 5, :x true}
k2 (key/create [2])
r2 {:b 7, :y false}]
(is (= {} (record/split-data {} [])))
(is (= {:base [[k0 {}]]}
(record/split-data {} [[k0 {}]])))
(is (= {:base [[k0 {}]
[k1 {:x true}]
[k2 {:y false}]]
:ab [[k0 nil]
[k1 {:a 5}]
[k2 {:b 7}]]}
(record/split-data {:ab #{:a :b}} [[k0 r0] [k1 r1] [k2 r2]])))))
| 29511 | (ns merkle-db.record-test
(:require
[clojure.spec.alpha :as s]
[clojure.test :refer :all]
[merkle-db.key :as key]
[merkle-db.record :as record]
[merkle-db.test-utils]))
(deftest record-specs
(testing "id fields"
(is (invalid? ::record/id-field nil))
(is (invalid? ::record/id-field #{:a}))
(is (invalid? ::record/id-field []))
(is (valid? ::record/id-field :id))
(is (valid? ::record/id-field [:a]))
(is (valid? ::record/id-field [:a :b :c]))
(is (invalid? ::record/id-field [:a :a])
"no duplicates")
(is (invalid? ::record/id-field [#{:foo} :bar nil])
"elements must be valid field keys"))
(testing "record data"
(is (invalid? ::record/data nil))
(is (invalid? ::record/data []))
(is (valid? ::record/data {}))
(is (valid? ::record/data {:foo true, :bar "---", :baz 123})))
(testing "family maps"
(is (invalid? ::record/families nil))
(is (invalid? ::record/families []))
(is (valid? ::record/families {}))
(is (valid? ::record/families {:bc #{:b :c}}))
(is (valid? ::record/families {:bc #{:b :c}, :ad #{:a :d}}))
(is (invalid? ::record/families {"foo" #{:a}}))
(is (invalid? ::record/families {:qualified/family #{:a}}))
(is (invalid? ::record/families {:not-a-set [:a]}))
(is (invalid? ::record/families {:bc #{:b :c}, :cd #{:c :d}}))))
(deftest entry-encoding
(testing "id projection"
(is (= 123 (record/project-id nil {::record/id 123}))
"field defaults to ::record/id")
(is (= "xyz" (record/project-id :id {:id "xyz"})))
(is (= [123 "abc"] (record/project-id [:a :b] {:a 123, :b "abc"}))))
(testing "encoding"
(is (= [(key/parse "807B")
{:a "abc", :b true}]
(record/encode-entry
key/integer-lexicoder
nil
{::record/id 123
:a "abc"
:b true})))
(is (= [(key/parse "<KEY>")
{:z :foo}]
(record/encode-entry
(key/tuple-lexicoder
key/integer-lexicoder
key/integer-lexicoder)
[:x :y]
{:x 123
:y 456
:z :foo}))))
(testing "decoding"
(is (= {::record/id 123
:a "abc"
:b true}
(record/decode-entry
key/integer-lexicoder
nil
[(key/parse "<KEY>")
{:a "abc", :b true}])))
(is (= {:x 123
:y 456
:z :foo}
(record/decode-entry
(key/tuple-lexicoder
key/integer-lexicoder
key/integer-lexicoder)
[:x :y]
[(key/parse "<KEY>")
{:z :foo}])))))
(deftest family-grouping
(let [k0 (key/create [0])
r0 {}
k1 (key/create [1])
r1 {:a 5, :x true}
k2 (key/create [2])
r2 {:b 7, :y false}]
(is (= {} (record/split-data {} [])))
(is (= {:base [[k0 {}]]}
(record/split-data {} [[k0 {}]])))
(is (= {:base [[k0 {}]
[k1 {:x true}]
[k2 {:y false}]]
:ab [[k0 nil]
[k1 {:a 5}]
[k2 {:b 7}]]}
(record/split-data {:ab #{:a :b}} [[k0 r0] [k1 r1] [k2 r2]])))))
| true | (ns merkle-db.record-test
(:require
[clojure.spec.alpha :as s]
[clojure.test :refer :all]
[merkle-db.key :as key]
[merkle-db.record :as record]
[merkle-db.test-utils]))
(deftest record-specs
(testing "id fields"
(is (invalid? ::record/id-field nil))
(is (invalid? ::record/id-field #{:a}))
(is (invalid? ::record/id-field []))
(is (valid? ::record/id-field :id))
(is (valid? ::record/id-field [:a]))
(is (valid? ::record/id-field [:a :b :c]))
(is (invalid? ::record/id-field [:a :a])
"no duplicates")
(is (invalid? ::record/id-field [#{:foo} :bar nil])
"elements must be valid field keys"))
(testing "record data"
(is (invalid? ::record/data nil))
(is (invalid? ::record/data []))
(is (valid? ::record/data {}))
(is (valid? ::record/data {:foo true, :bar "---", :baz 123})))
(testing "family maps"
(is (invalid? ::record/families nil))
(is (invalid? ::record/families []))
(is (valid? ::record/families {}))
(is (valid? ::record/families {:bc #{:b :c}}))
(is (valid? ::record/families {:bc #{:b :c}, :ad #{:a :d}}))
(is (invalid? ::record/families {"foo" #{:a}}))
(is (invalid? ::record/families {:qualified/family #{:a}}))
(is (invalid? ::record/families {:not-a-set [:a]}))
(is (invalid? ::record/families {:bc #{:b :c}, :cd #{:c :d}}))))
(deftest entry-encoding
(testing "id projection"
(is (= 123 (record/project-id nil {::record/id 123}))
"field defaults to ::record/id")
(is (= "xyz" (record/project-id :id {:id "xyz"})))
(is (= [123 "abc"] (record/project-id [:a :b] {:a 123, :b "abc"}))))
(testing "encoding"
(is (= [(key/parse "807B")
{:a "abc", :b true}]
(record/encode-entry
key/integer-lexicoder
nil
{::record/id 123
:a "abc"
:b true})))
(is (= [(key/parse "PI:KEY:<KEY>END_PI")
{:z :foo}]
(record/encode-entry
(key/tuple-lexicoder
key/integer-lexicoder
key/integer-lexicoder)
[:x :y]
{:x 123
:y 456
:z :foo}))))
(testing "decoding"
(is (= {::record/id 123
:a "abc"
:b true}
(record/decode-entry
key/integer-lexicoder
nil
[(key/parse "PI:KEY:<KEY>END_PI")
{:a "abc", :b true}])))
(is (= {:x 123
:y 456
:z :foo}
(record/decode-entry
(key/tuple-lexicoder
key/integer-lexicoder
key/integer-lexicoder)
[:x :y]
[(key/parse "PI:KEY:<KEY>END_PI")
{:z :foo}])))))
(deftest family-grouping
(let [k0 (key/create [0])
r0 {}
k1 (key/create [1])
r1 {:a 5, :x true}
k2 (key/create [2])
r2 {:b 7, :y false}]
(is (= {} (record/split-data {} [])))
(is (= {:base [[k0 {}]]}
(record/split-data {} [[k0 {}]])))
(is (= {:base [[k0 {}]
[k1 {:x true}]
[k2 {:y false}]]
:ab [[k0 nil]
[k1 {:a 5}]
[k2 {:b 7}]]}
(record/split-data {:ab #{:a :b}} [[k0 r0] [k1 r1] [k2 r2]])))))
|
[
{
"context": "et of attributes\"\n [username {:userid \"developer@uu.id\"\n :email \"developer@example",
"end": 2898,
"score": 0.9998936653137207,
"start": 2883,
"tag": "EMAIL",
"value": "developer@uu.id"
},
{
"context": " \"developer@uu.id\"\n :email \"developer@example.com\"\n :name \"Deve Loper\"}])\n ",
"end": 2952,
"score": 0.9999209642410278,
"start": 2931,
"tag": "EMAIL",
"value": "developer@example.com"
},
{
"context": "eloper@example.com\"\n :name \"Deve Loper\"}])\n (example \"fallback to userid\"\n ",
"end": 2994,
"score": 0.9995934367179871,
"start": 2984,
"tag": "NAME",
"value": "Deve Loper"
},
{
"context": "llback to userid\"\n [username {:userid \"developer@uu.id\"\n :email \"developer@example",
"end": 3079,
"score": 0.9999110102653503,
"start": 3064,
"tag": "EMAIL",
"value": "developer@uu.id"
},
{
"context": " \"developer@uu.id\"\n :email \"developer@example.com\"}])\n (example \"empty attributes\"\n [u",
"end": 3133,
"score": 0.9999138116836548,
"start": 3112,
"tag": "EMAIL",
"value": "developer@example.com"
},
{
"context": "ed-user status\"\n [attributes {:userid \"developer@uu.id\"\n :email \"developer@uu.id",
"end": 3340,
"score": 0.9999109506607056,
"start": 3325,
"tag": "EMAIL",
"value": "developer@uu.id"
},
{
"context": "developer@uu.id\"\n :email \"developer@uu.id\"\n :name \"Deve Loper\"\n ",
"end": 3390,
"score": 0.9998943209648132,
"start": 3375,
"tag": "EMAIL",
"value": "developer@uu.id"
},
{
"context": "\"developer@uu.id\"\n :name \"Deve Loper\"\n :notification-email \"no",
"end": 3434,
"score": 0.9997055530548096,
"start": 3424,
"tag": "NAME",
"value": "Deve Loper"
},
{
"context": "er\"\n :notification-email \"notification@example.com\"\n :organizations [{:organ",
"end": 3506,
"score": 0.9999173283576965,
"start": 3482,
"tag": "EMAIL",
"value": "notification@example.com"
},
{
"context": "ed-user status\"\n [attributes {:userid \"invited@memeber.com\"\n :email \"invited@memeber",
"end": 3916,
"score": 0.9998851418495178,
"start": 3897,
"tag": "EMAIL",
"value": "invited@memeber.com"
},
{
"context": "ted@memeber.com\"\n :email \"invited@memeber.com\"\n :name \"Invited Mamber\"\n",
"end": 3970,
"score": 0.9998997449874878,
"start": 3951,
"tag": "EMAIL",
"value": "invited@memeber.com"
},
{
"context": "ited@memeber.com\"\n :name \"Invited Mamber\"\n :notification-email \"in",
"end": 4018,
"score": 0.9960095286369324,
"start": 4004,
"tag": "NAME",
"value": "Invited Mamber"
},
{
"context": "er\"\n :notification-email \"invited@memeber.com\"\n :organizations []}\n ",
"end": 4085,
"score": 0.9999059438705444,
"start": 4066,
"tag": "EMAIL",
"value": "invited@memeber.com"
},
{
"context": "ed-user status\"\n [attributes {:userid \"developer@uu.id\"\n :email \"developer@uu.id",
"end": 4274,
"score": 0.999925434589386,
"start": 4259,
"tag": "EMAIL",
"value": "developer@uu.id"
},
{
"context": "developer@uu.id\"\n :email \"developer@uu.id\"\n :organizations [{:organ",
"end": 4324,
"score": 0.9999248385429382,
"start": 4309,
"tag": "EMAIL",
"value": "developer@uu.id"
},
{
"context": "ted-user status\"\n [attributes {:email \"developer@uu.id\"\n :organizations [{:organ",
"end": 4581,
"score": 0.9999268651008606,
"start": 4566,
"tag": "EMAIL",
"value": "developer@uu.id"
}
] | src/cljs/rems/user.cljs | ossilva/rems | 31 | (ns rems.user
(:require [clojure.string :as str]
[re-frame.core :as rf]
[rems.atoms :refer [info-field readonly-checkbox]]
[rems.common.application-util :refer [get-member-name]]
[rems.common.util :refer [index-by]]
[rems.guide-util :refer [component-info example]]
[rems.text :refer [text localized]]))
(defn username
"A rems.atoms/info-field with the name of the user."
[attributes]
(when-let [name (get-member-name attributes)]
[info-field (text :t.applicant-info/name) name {:inline? true}]))
(defn attributes
"A div with a rems.atoms/info-field for every user attribute in the given attributes.
Accepts
- attributes: map, user attributes
- invited-user? : boolean, if user is invited, shows different email string"
[attributes invited-user?]
(let [language @(rf/subscribe [:language])
organization-by-id @(rf/subscribe [:organization-by-id])
organization-name-if-known (fn [organization]
(if-let [known-organization (organization-by-id (:organization/id organization))] ; comes from idp, maybe unknown
(get-in known-organization [:organization/short-name language])
(:organization/id organization)))
other-attributes (dissoc attributes :name :userid :email :organizations :notification-email :researcher-status-by)
extra-attributes (index-by [:attribute] (:oidc-extra-attributes @(rf/subscribe [:rems.config/config])))]
(into [:div.user-attributes
(when-let [user-id (:userid attributes)]
[info-field (text :t.applicant-info/username) user-id {:inline? true}])
(when-let [mail (:notification-email attributes)]
[info-field (text :t.applicant-info/notification-email) mail {:inline? true}])
(when-let [mail (:email attributes)]
(if invited-user?
[info-field (text :t.applicant-info/email) mail {:inline? true}]
[info-field (text :t.applicant-info/email-idp) mail {:inline? true}]))
(when-let [organizations (seq (:organizations attributes))]
[info-field (text :t.applicant-info/organization) (str/join ", " (map organization-name-if-known organizations)) {:inline? true}])
(when (#{"so" "system"} (:researcher-status-by attributes))
[info-field (text :t.applicant-info/researcher-status) [readonly-checkbox {:value true}] {:inline? true}])]
(for [[k v] other-attributes]
(let [title (or (localized (get-in extra-attributes [(name k) :name]))
k)]
[info-field title v {:inline? true}])))))
(defn guide []
[:div
(component-info username)
(example "full set of attributes"
[username {:userid "developer@uu.id"
:email "developer@example.com"
:name "Deve Loper"}])
(example "fallback to userid"
[username {:userid "developer@uu.id"
:email "developer@example.com"}])
(example "empty attributes"
[username {}])
(component-info attributes)
(example "full set of attributes, false invited-user status"
[attributes {:userid "developer@uu.id"
:email "developer@uu.id"
:name "Deve Loper"
:notification-email "notification@example.com"
:organizations [{:organization/id "Testers"} {:organization/id "Users"}]
:address "Testikatu 1, 00100 Helsinki"
:researcher-status-by "so"
:nickname "The Dev"}
false])
(example "invited memeber set of attributes, true invited-user status"
[attributes {:userid "invited@memeber.com"
:email "invited@memeber.com"
:name "Invited Mamber"
:notification-email "invited@memeber.com"
:organizations []}
true])
(example "invalid value for researcher status, no invited-user status"
[attributes {:userid "developer@uu.id"
:email "developer@uu.id"
:organizations [{:organization/id "Testers"} {:organization/id "Users"}]
:researcher-status-by :dac}])
(example "less attributes, no invited-user status"
[attributes {:email "developer@uu.id"
:organizations [{:organization/id "Testers"} {:organization/id "Users"}]}])
(example "empty attributes, no invited-user status"
[attributes {}])])
| 122291 | (ns rems.user
(:require [clojure.string :as str]
[re-frame.core :as rf]
[rems.atoms :refer [info-field readonly-checkbox]]
[rems.common.application-util :refer [get-member-name]]
[rems.common.util :refer [index-by]]
[rems.guide-util :refer [component-info example]]
[rems.text :refer [text localized]]))
(defn username
"A rems.atoms/info-field with the name of the user."
[attributes]
(when-let [name (get-member-name attributes)]
[info-field (text :t.applicant-info/name) name {:inline? true}]))
(defn attributes
"A div with a rems.atoms/info-field for every user attribute in the given attributes.
Accepts
- attributes: map, user attributes
- invited-user? : boolean, if user is invited, shows different email string"
[attributes invited-user?]
(let [language @(rf/subscribe [:language])
organization-by-id @(rf/subscribe [:organization-by-id])
organization-name-if-known (fn [organization]
(if-let [known-organization (organization-by-id (:organization/id organization))] ; comes from idp, maybe unknown
(get-in known-organization [:organization/short-name language])
(:organization/id organization)))
other-attributes (dissoc attributes :name :userid :email :organizations :notification-email :researcher-status-by)
extra-attributes (index-by [:attribute] (:oidc-extra-attributes @(rf/subscribe [:rems.config/config])))]
(into [:div.user-attributes
(when-let [user-id (:userid attributes)]
[info-field (text :t.applicant-info/username) user-id {:inline? true}])
(when-let [mail (:notification-email attributes)]
[info-field (text :t.applicant-info/notification-email) mail {:inline? true}])
(when-let [mail (:email attributes)]
(if invited-user?
[info-field (text :t.applicant-info/email) mail {:inline? true}]
[info-field (text :t.applicant-info/email-idp) mail {:inline? true}]))
(when-let [organizations (seq (:organizations attributes))]
[info-field (text :t.applicant-info/organization) (str/join ", " (map organization-name-if-known organizations)) {:inline? true}])
(when (#{"so" "system"} (:researcher-status-by attributes))
[info-field (text :t.applicant-info/researcher-status) [readonly-checkbox {:value true}] {:inline? true}])]
(for [[k v] other-attributes]
(let [title (or (localized (get-in extra-attributes [(name k) :name]))
k)]
[info-field title v {:inline? true}])))))
(defn guide []
[:div
(component-info username)
(example "full set of attributes"
[username {:userid "<EMAIL>"
:email "<EMAIL>"
:name "<NAME>"}])
(example "fallback to userid"
[username {:userid "<EMAIL>"
:email "<EMAIL>"}])
(example "empty attributes"
[username {}])
(component-info attributes)
(example "full set of attributes, false invited-user status"
[attributes {:userid "<EMAIL>"
:email "<EMAIL>"
:name "<NAME>"
:notification-email "<EMAIL>"
:organizations [{:organization/id "Testers"} {:organization/id "Users"}]
:address "Testikatu 1, 00100 Helsinki"
:researcher-status-by "so"
:nickname "The Dev"}
false])
(example "invited memeber set of attributes, true invited-user status"
[attributes {:userid "<EMAIL>"
:email "<EMAIL>"
:name "<NAME>"
:notification-email "<EMAIL>"
:organizations []}
true])
(example "invalid value for researcher status, no invited-user status"
[attributes {:userid "<EMAIL>"
:email "<EMAIL>"
:organizations [{:organization/id "Testers"} {:organization/id "Users"}]
:researcher-status-by :dac}])
(example "less attributes, no invited-user status"
[attributes {:email "<EMAIL>"
:organizations [{:organization/id "Testers"} {:organization/id "Users"}]}])
(example "empty attributes, no invited-user status"
[attributes {}])])
| true | (ns rems.user
(:require [clojure.string :as str]
[re-frame.core :as rf]
[rems.atoms :refer [info-field readonly-checkbox]]
[rems.common.application-util :refer [get-member-name]]
[rems.common.util :refer [index-by]]
[rems.guide-util :refer [component-info example]]
[rems.text :refer [text localized]]))
(defn username
"A rems.atoms/info-field with the name of the user."
[attributes]
(when-let [name (get-member-name attributes)]
[info-field (text :t.applicant-info/name) name {:inline? true}]))
(defn attributes
"A div with a rems.atoms/info-field for every user attribute in the given attributes.
Accepts
- attributes: map, user attributes
- invited-user? : boolean, if user is invited, shows different email string"
[attributes invited-user?]
(let [language @(rf/subscribe [:language])
organization-by-id @(rf/subscribe [:organization-by-id])
organization-name-if-known (fn [organization]
(if-let [known-organization (organization-by-id (:organization/id organization))] ; comes from idp, maybe unknown
(get-in known-organization [:organization/short-name language])
(:organization/id organization)))
other-attributes (dissoc attributes :name :userid :email :organizations :notification-email :researcher-status-by)
extra-attributes (index-by [:attribute] (:oidc-extra-attributes @(rf/subscribe [:rems.config/config])))]
(into [:div.user-attributes
(when-let [user-id (:userid attributes)]
[info-field (text :t.applicant-info/username) user-id {:inline? true}])
(when-let [mail (:notification-email attributes)]
[info-field (text :t.applicant-info/notification-email) mail {:inline? true}])
(when-let [mail (:email attributes)]
(if invited-user?
[info-field (text :t.applicant-info/email) mail {:inline? true}]
[info-field (text :t.applicant-info/email-idp) mail {:inline? true}]))
(when-let [organizations (seq (:organizations attributes))]
[info-field (text :t.applicant-info/organization) (str/join ", " (map organization-name-if-known organizations)) {:inline? true}])
(when (#{"so" "system"} (:researcher-status-by attributes))
[info-field (text :t.applicant-info/researcher-status) [readonly-checkbox {:value true}] {:inline? true}])]
(for [[k v] other-attributes]
(let [title (or (localized (get-in extra-attributes [(name k) :name]))
k)]
[info-field title v {:inline? true}])))))
(defn guide []
[:div
(component-info username)
(example "full set of attributes"
[username {:userid "PI:EMAIL:<EMAIL>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:name "PI:NAME:<NAME>END_PI"}])
(example "fallback to userid"
[username {:userid "PI:EMAIL:<EMAIL>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"}])
(example "empty attributes"
[username {}])
(component-info attributes)
(example "full set of attributes, false invited-user status"
[attributes {:userid "PI:EMAIL:<EMAIL>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:name "PI:NAME:<NAME>END_PI"
:notification-email "PI:EMAIL:<EMAIL>END_PI"
:organizations [{:organization/id "Testers"} {:organization/id "Users"}]
:address "Testikatu 1, 00100 Helsinki"
:researcher-status-by "so"
:nickname "The Dev"}
false])
(example "invited memeber set of attributes, true invited-user status"
[attributes {:userid "PI:EMAIL:<EMAIL>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:name "PI:NAME:<NAME>END_PI"
:notification-email "PI:EMAIL:<EMAIL>END_PI"
:organizations []}
true])
(example "invalid value for researcher status, no invited-user status"
[attributes {:userid "PI:EMAIL:<EMAIL>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:organizations [{:organization/id "Testers"} {:organization/id "Users"}]
:researcher-status-by :dac}])
(example "less attributes, no invited-user status"
[attributes {:email "PI:EMAIL:<EMAIL>END_PI"
:organizations [{:organization/id "Testers"} {:organization/id "Users"}]}])
(example "empty attributes, no invited-user status"
[attributes {}])])
|
[
{
"context": ".\n [#\"(?i)morgens|(in der )?früh|vor ?mittags?|am morgen\"]\n (assoc (interval (hour 3 false) (hour 12",
"end": 11787,
"score": 0.5886578559875488,
"start": 11786,
"tag": "NAME",
"value": "m"
}
] | resources/languages/de/rules/time.clj | irvingflores/duckling | 0 | (
;; generic
"intersect"
[(dim :time #(not (:latent %))) (dim :time #(not (:latent %)))] ; sequence of two tokens with a time dimension
(intersect %1 %2)
; same thing, with "of" in between like "Sunday of last week"
"intersect by 'of', 'from', 's"
[(dim :time #(not (:latent %))) #"(?i)von|der|im" (dim :time #(not (:latent %)))] ; sequence of two tokens with a time fn
(intersect %1 %3)
; mostly for January 12, 2005
; this is a separate rule, because commas separate very specific tokens
; so we want this rule's classifier to learn this
"intersect by ','"
[(dim :time #(not (:latent %))) #"," (dim :time #(not (:latent %)))] ; sequence of two tokens with a time fn
(intersect %1 %3)
"on <date>" ; on Wed, March 23
[#"(?i)am" (dim :time)]
%2 ; does NOT dissoc latent
"on a named-day" ; on a sunday
[#"(?i)an einem" {:form :day-of-week}]
%2 ; does NOT dissoc latent
;;;;;;;;;;;;;;;;;;;
;; Named things
"named-day"
#"(?i)montags?|mo\.?"
(day-of-week 1)
"named-day"
#"(?i)die?nstags?|di\.?"
(day-of-week 2)
"named-day"
#"(?i)mittwochs?|mi\.?"
(day-of-week 3)
"named-day"
#"(?i)donn?erstags?|do\.?"
(day-of-week 4)
"named-day"
#"(?i)freitags?|fr\.?"
(day-of-week 5)
"named-day"
#"(?i)samstags?|sa\.?"
(day-of-week 6)
"named-day"
#"(?i)sonntags?|so\.?"
(day-of-week 7)
"named-month"
#"(?i)januar|jan\.?"
(month 1)
"named-month"
#"(?i)februar|feb\.?"
(month 2)
"named-month"
#"(?i)märz|mär\.?"
(month 3)
"named-month"
#"(?i)april|apr\.?"
(month 4)
"named-month"
#"(?i)mai"
(month 5)
"named-month"
#"(?i)juni|jun\.?"
(month 6)
"named-month"
#"(?i)juli|jul\.?"
(month 7)
"named-month"
#"(?i)august|aug\.?"
(month 8)
"named-month"
#"(?i)september|sept?\.?"
(month 9)
"named-month"
#"(?i)oktober|oct\.?"
(month 10)
"named-month"
#"(?i)november|nov\.?"
(month 11)
"named-month"
#"(?i)dezember|dez\.?"
(month 12)
; Holiday TODO: check online holidays
; or define dynamic rule (last thursday of october..)
"christmas"
#"(?i)weih?nacht(en|stag)?"
(month-day 12 25)
"christmas eve"
#"(?i)heilig(er)? abend"
(month-day 12 24)
"new year's eve"
#"(?i)silvester"
(month-day 12 31)
"new year's day"
#"(?i)neujahr(s?tag)?"
(month-day 1 1)
"valentine's day"
#"(?i)valentin'?stag"
(month-day 2 14)
"Tag der Deutschen Einheit"
#"(?i)tag (der)? deutsc?hen? einheit"
(month-day 10 3)
"Österreichischer Nationalfeiertag"
#"(österreichischer?)? nationalfeiertag|national feiertag"
(month-day 10 26)
"Schweizer Bundesfeiertag"
#"(?i)schweiz(er)? (bundes)?feiertag|bundes feiertag"
(month-day 8 1)
"Father's Day";third Sunday of June
#"(?i)vatt?ertag|vatt?er (tag)?"
(intersect (day-of-week 7) (month 6) (cycle-nth-after :week 2 (month-day 6 1)))
"Mother's Day";second Sunday in May.
#"(?i)mutt?ertag|mutt?er (tag)?"
(intersect (day-of-week 7) (month 5) (cycle-nth-after :week 1 (month-day 5 1)))
"halloween day"
#"(?i)hall?owe?en?"
(month-day 10 31)
"Allerheiligen"
#"(?i)allerheiligen?|aller heiligen?"
(month-day 11 1)
"Nikolaus"
#"(?i)nikolaus(tag)?|nikolaus tag|nikolo"
(month-day 12 6)
"absorption of , after named day"
[{:form :day-of-week} #","]
%1
"now"
#"(?i)(genau)? ?jetzt|diesen moment|in diesem moment|gerade eben"
(cycle-nth :second 0)
"today"
#"(?i)heute|(um diese zeit|zu dieser zeit|um diesen zeitpunkt|zu diesem zeitpunkt)"
(cycle-nth :day 0)
"tomorrow"
#"(?i)morgen"
(cycle-nth :day 1)
"after tomorrow"
#"(?i)übermorgen"
(cycle-nth :day 2)
"yesterday"
#"(?i)gestern"
(cycle-nth :day -1)
"before yesterday"
#"(?i)vorgestern"
(cycle-nth :day -2)
"EOM|End of month"
#"(?i)(das )?ende des monats?"
(cycle-nth :month 1)
"EOY|End of year"
#"(?i)(das )?(EOY|jahr(es)? ?ende|ende (des )?jahr(es)?)"
(cycle-nth :year 1)
;;
;; This, Next, Last
;; assumed to be strictly in the future:
;; "this Monday" => next week if today in Monday
"this|next <day-of-week>"
[#"(?i)diese(n|r)|kommenden|nächsten" {:form :day-of-week}]
(pred-nth-not-immediate %2 0)
;; for other preds, it can be immediate:
;; "this month" => now is part of it
; See also: cycles in en.cycles.clj
"this <time>"
[#"(?i)diese(n|r|s)?|(im )?laufenden" (dim :time)]
(pred-nth %2 0)
"next <time>"
[#"(?i)nächsten?|nächstes|kommenden?|kommendes" (dim :time)]
(pred-nth-not-immediate %2 0)
"last <time>"
[#"(?i)letzten?|letztes" (dim :time)]
(pred-nth %2 -1)
"after next <time>"
[#"(?i)übernächsten?|über ?nächstes?" (dim :time)]
(pred-nth-not-immediate %2 1)
"<time> after next"
[ (dim :time) #"(?i)nach dem nächsten"]
(pred-nth-not-immediate %1 1)
"<time> before last"
[#"(?i)vorletzten?|vor ?letztes?" (dim :time)]
(pred-nth %2 -2)
"last <day-of-week> of <time>"
[#"(?i)letzte(r|n|s)?" {:form :day-of-week} #"(?i)um|im" (dim :time)];Check me OF
(pred-last-of %2 %4)
"last <cycle> of <time>"
[#"(?i)letzte(r|n|s)?" (dim :cycle) #"(?i)um|im" (dim :time)];Check me OF
(cycle-last-of %2 %4)
; Ordinals
"nth <time> of <time>"
[(dim :ordinal) (dim :time) #"(?i)im" (dim :time)];Check me OF
(pred-nth (intersect %4 %2) (dec (:value %1)))
"nth <time> of <time>"
[#"(?i)der|die|das" (dim :ordinal) (dim :time) #"(?i)im" (dim :time)];Check me OF
(pred-nth (intersect %5 %3) (dec (:value %2)))
"nth <time> after <time>"
[(dim :ordinal) (dim :time) #"(?i)nach" (dim :time)];CHeck me
(pred-nth-after %2 %4 (dec (:value %1)))
"nth <time> after <time>"
[#"(?i)der|das" (dim :ordinal) (dim :time) #"(?i)nach" (dim :time)];Check me
(pred-nth-after %3 %5 (dec (:value %2)))
; Years
; Between 1000 and 2100 we assume it's a year
; Outside of this, it's safer to consider it's latent
"year"
(integer 1000 2100)
(year (:value %1))
"year (latent)"
(integer -10000 999)
(assoc (year (:value %1)) :latent true)
"year (latent)"
(integer 2101 10000)
(assoc (year (:value %1)) :latent true)
; Day of month appears in the following context:
; - the nth
; - March nth
; - nth of March
; - mm/dd (and other numerical formats like yyyy-mm-dd etc.)
; In general we are flexible and accept both ordinals (3rd) and numbers (3)
"the <day-of-month> (ordinal)" ; this one is not latent
[#"(?i)der" (dim :ordinal #(<= 1 (:value %) 31))]
(day-of-month (:value %2))
"<day-of-month> (ordinal)" ; this one is latent
[(dim :ordinal #(<= 1 (:value %) 31))]
(assoc (day-of-month (:value %1)) :latent true)
"the <day-of-month> (non ordinal)" ; this one is latent
[#"(?i)der" (integer 1 31)]
(assoc (day-of-month (:value %2)) :latent true)
"<named-month> <day-of-month> (ordinal)" ; march 12th
[{:form :month} (dim :ordinal #(<= 1 (:value %) 31))]
(intersect %1 (day-of-month (:value %2)))
"<named-month> <day-of-month> (non ordinal)" ; march 12
[{:form :month} (integer 1 31)]
(intersect %1 (day-of-month (:value %2)))
"<day-of-month> (non ordinal) of <named-month>"
[(integer 1 31) #"(?i)vom|von" {:form :month}];Check me DO WE NEED THIS
(intersect %3 (day-of-month (:value %1)))
"<day-of-month> (non ordinal) <named-month>" ; 12 mars
[(integer 1 31) {:form :month}]
(intersect %2 (day-of-month (:value %1)))
"<day-of-month>(ordinal) <named-month>" ; 12nd mars
[(dim :ordinal #(<= 1 (:value %) 31)) {:form :month}]
(intersect %2 (day-of-month (:value %1)))
"<day-of-month>(ordinal) <named-month> year" ; 12nd mars 12
[(dim :ordinal #(<= 1 (:value %) 31)) {:form :month} #"(\d{2,4})"]
(intersect %2 (day-of-month (:value %1)) (year (Integer/parseInt(first (:groups %3)))))
"the ides of <named-month>" ; the ides of march 13th for most months, but on the 15th for March, May, July, and October
[#"(?i)die iden (des?)" {:form :month}]
(intersect %2 (day-of-month (if (#{3 5 7 10} (:month %2)) 15 13)))
; Hours and minutes (absolute time)
;
; Assumptions:
; - 0 is midnight
; - 1..11 is ambiguous am or pm
; - 12 is noon (whereas in English it is ambiguous)
; - 13..23 is pm
"time-of-day (latent)"
(integer 0 23)
(assoc (hour (:value %1) (< (:value %1) 12)) :latent true)
"<time-of-day> o'clock"
[#(:full-hour %) #"(?i)uhr|h"]
(dissoc %1 :latent)
"at <time-of-day>" ; absorption
[#"(?i)um|@" {:form :time-of-day}]
(dissoc %2 :latent)
"hh:mm"
#"(?i)((?:[01]?\d)|(?:2[0-3]))[:.]([0-5]\d)"
(hour-minute (Integer/parseInt (first (:groups %1)))
(Integer/parseInt (second (:groups %1)))
false)
"hhmm (military)"
#"(?i)((?:[01]?\d)|(?:2[0-3]))([0-5]\d)"
(-> (hour-minute (Integer/parseInt (first (:groups %1)))
(Integer/parseInt (second (:groups %1)))
false) ; not a 12-hour clock)
(assoc :latent true))
"hhmm (military) am|pm" ; hh only from 00 to 12
[#"(?i)((?:1[012]|0?\d))([0-5]\d)" #"(?i)([ap])\.?m?\.?"]
; (-> (hour-minute (Integer/parseInt (first (:groups %1)))
; (Integer/parseInt (second (:groups %1)))
; false) ; not a 12-hour clock)
; (assoc :latent true))
(let [[p meridiem] (if (= "a" (-> %2 :groups first .toLowerCase))
[[(hour 0) (hour 12) false] :am]
[[(hour 12) (hour 0) false] :pm])]
(-> (intersect
(hour-minute (Integer/parseInt (first (:groups %1)))
(Integer/parseInt (second (:groups %1)))
true)
(apply interval p))
(assoc :form :time-of-day)))
"<time-of-day> am|pm"
[{:form :time-of-day} #"(?i)([ap])(\s|\.)?m?\.?"];Check me DO WE NEED THIS
;; TODO set_am fn in helpers => add :ampm field
(let [[p meridiem] (if (= "a" (-> %2 :groups first .toLowerCase))
[[(hour 0) (hour 12) false] :am]
[[(hour 12) (hour 0) false] :pm])]
(-> (intersect %1 (apply interval p))
(assoc :form :time-of-day)))
"noon"
#"(?i)mittags?|zwölf (uhr)?"
(hour 12 false)
"midnight|EOD|end of day"
#"(?i)mitternacht|EOD|tagesende|ende (des)? tag(es)?"
(hour 0 false)
"quarter (relative minutes)"
#"(?i)vie?rtel"
{:relative-minutes 15}
"half (relative minutes)"
#"halbe?"
{:relative-minutes 30}
"number (as relative minutes)"
(integer 1 59)
{:relative-minutes (:value %1)}
"<hour-of-day> <integer> (as relative minutes)"
[(dim :time :full-hour) #(:relative-minutes %)]
(hour-relativemin (:full-hour %1) (:relative-minutes %2) true)
"relative minutes to|till|before <integer> (hour-of-day)"
[#(:relative-minutes %) #"(?i)vor" (dim :time :full-hour)]
(hour-relativemin (:full-hour %3) (- (:relative-minutes %1)) true)
"relative minutes after|past <integer> (hour-of-day)"
[#(:relative-minutes %) #"(?i)nach" (dim :time :full-hour)]
(hour-relativemin (:full-hour %3) (:relative-minutes %1) true)
"half <integer> (german style hour-of-day)"
[#"halb" (dim :time :full-hour)];Check me CHANGE CODE TO MATCH GERMAN USAGE
(hour-relativemin (:full-hour %2) -30 true)
; Formatted dates and times
"mm/dd/yyyy"
#"([012]?\d|30|31)\.(0?\d|10|11|12)\.(\d{2,4})"
(parse-dmy (first (:groups %1)) (second (:groups %1)) (nth (:groups %1) 2) true)
"yyyy-mm-dd"
#"(\d{2,4})-(0?\d|10|11|12)-([012]?\d|30|31)"
(parse-dmy (nth (:groups %1) 2) (second (:groups %1)) (first (:groups %1)) true)
"mm/dd"
#"([012]?\d|30|31)\.(0?\d|10|11|12)\."
(parse-dmy (first (:groups %1)) (second (:groups %1)) nil true)
; Part of day (morning, evening...). They are intervals.
"morning" ;; TODO "3am this morning" won't work since morning starts at 4...
[#"(?i)morgens|(in der )?früh|vor ?mittags?|am morgen"]
(assoc (interval (hour 3 false) (hour 12 false) false) :form :part-of-day :latent true)
"afternoon"
[#"(?i)nach ?mittags?"]
(assoc (interval (hour 12 false) (hour 19 false) false) :form :part-of-day :latent true)
"evening"
[#"(?i)abends?"]
(assoc (interval (hour 18 false) (hour 0 false) false) :form :part-of-day :latent true)
"night"
[#"(?i)nachts?"]
(assoc (interval (hour 0 false) (hour 4 false) false) :form :part-of-day :latent true)
"lunch"
[#"(?i)(am |zu )?mittags?"]
(assoc (interval (hour 12 false) (hour 14 false) false) :form :part-of-day :latent true)
"in|during the <part-of-day>" ;; removes latent
[#"(?i)(in|an|am|wäh?rend)( der| dem| des)?" {:form :part-of-day}]
(dissoc %2 :latent)
"this <part-of-day>"
[#"(?i)diesen?|dieses|heute" {:form :part-of-day}]
(assoc (intersect (cycle-nth :day 0) %2) :form :part-of-day) ;; removes :latent
"tonight"
#"(?i)heute? (am)? abends?"
(assoc (intersect (cycle-nth :day 0)
(interval (hour 18 false) (hour 0 false) false))
:form :part-of-day) ; no :latent
"after lunch"
#"(?i)nach dem mittagessen|nachmittags?"
(assoc (intersect (cycle-nth :day 0)
(interval (hour 13 false) (hour 17 false) false))
:form :part-of-day) ; no :latent
"after work"
#"(?i)nach (der)? arbeit|(am)? feier ?abend"
(assoc (intersect (cycle-nth :day 0)
(interval (hour 17 false) (hour 21 false) false))
:form :part-of-day) ; no :latent
"<time> <part-of-day>" ; since "morning" "evening" etc. are latent, general time+time is blocked
[(dim :time) {:form :part-of-day}]
(intersect %2 %1)
"<part-of-day> of <time>" ; since "morning" "evening" etc. are latent, general time+time is blocked
[{:form :part-of-day} #"(?i)des|von|vom|am" (dim :time)];Check me
(intersect %1 %3)
; Other intervals: week-end, seasons
"week-end" ; from Friday 6pm to Sunday midnight
#"(?i)wochen ?ende?"
(interval (intersect (day-of-week 5) (hour 18 false))
(intersect (day-of-week 1) (hour 0 false))
false)
"season"
#"(?i)sommer" ;could be smarter and take the exact hour into account... also some years the day can change
(interval (month-day 6 21) (month-day 9 23) false)
"season"
#"(?i)herbst"
(interval (month-day 9 23) (month-day 12 21) false)
"season"
#"(?i)winter"
(interval (month-day 12 21) (month-day 3 20) false)
"season"
#"(?i)frühling|frühjahr"
(interval (month-day 3 20) (month-day 6 21) false)
; Time zones
"timezone"
#"(?i)(YEKT|YEKST|YAPT|YAKT|YAKST|WT|WST|WITA|WIT|WIB|WGT|WGST|WFT|WEZ|WET|WESZ|WEST|WAT|WAST|VUT|VLAT|VLAST|VET|UZT|UYT|UYST|UTC|ULAT|TVT|TMT|TLT|TKT|TJT|TFT|TAHT|SST|SRT|SGT|SCT|SBT|SAST|SAMT|RET|PYT|PYST|PWT|PT|PST|PONT|PMST|PMDT|PKT|PHT|PHOT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|NCT|MYT|MVT|MUT|MST|MSK|MSD|MMT|MHT|MEZ|MESZ|MDT|MAWT|MART|MAGT|MAGST|LINT|LHST|LHDT|KUYT|KST|KRAT|KRAST|KGT|JST|IST|IRST|IRKT|IRKST|IRDT|IOT|IDT|ICT|HOVT|HNY|HNT|HNR|HNP|HNE|HNC|HNA|HLV|HKT|HAY|HAT|HAST|HAR|HAP|HAE|HADT|HAC|HAA|GYT|GST|GMT|GILT|GFT|GET|GAMT|GALT|FNT|FKT|FKST|FJT|FJST|ET|EST|EGT|EGST|EET|EEST|EDT|ECT|EAT|EAST|EASST|DAVT|ChST|CXT|CVT|CST|COT|CLT|CLST|CKT|CHAST|CHADT|CET|CEST|CDT|CCT|CAT|CAST|BTT|BST|BRT|BRST|BOT|BNT|AZT|AZST|AZOT|AZOST|AWST|AWDT|AST|ART|AQTT|ANAT|ANAST|AMT|AMST|ALMT|AKST|AKDT|AFT|AEST|AEDT|ADT|ACST|ACDT)"
{:dim :timezone
:value (-> %1 :groups first .toUpperCase)}
"<time> timezone"
[(dim :time) (dim :timezone)]
(set-timezone %1 (:value %2))
; Precision
; FIXME
; - should be applied to all dims not just time-of-day
;- shouldn't remove latency, except maybe -ish
"<time-of-day> approximately" ; 7ish
[{:form :time-of-day} #"(?i)(um )?zirka|ungefähr|etwa"]
(-> %1
(dissoc :latent)
(merge {:precision "approximate"}));Check me NO TRANSLATION NECESSARY
"<time-of-day> sharp" ; sharp
[{:form :time-of-day} #"(?i)genau|exakt|pünktlich|punkt( um)?"]
(-> %1
(dissoc :latent)
(merge {:precision "exact"}));Check me NO TRANSLATION NECESSARY
"about <time-of-day>" ; about
[#"(?i)(um )?zirka|ungefähr|etwa" {:form :time-of-day}]
(-> %2
(dissoc :latent)
(merge {:precision "approximate"}));Check me NO TRANSLATION NECESSARY
"exactly <time-of-day>" ; sharp
[#"(?i)genau|exakt|pünktlich|punkt( um)?" {:form :time-of-day}]
(-> %2
(dissoc :latent)
(merge {:precision "exact"}));Check me NO TRANSLATION NECESSARY
; Intervals
"<month> dd-dd (interval)"
[ #"([012]?\d|30|31)(ter|\.)?" #"\-|bis" #"([012]?\d|30|31)(ter|\.)?" {:form :month}]
(interval (intersect %4 (day-of-month (Integer/parseInt (-> %1 :groups first))))
(intersect %4 (day-of-month (Integer/parseInt (-> %3 :groups first))))
true)
; Blocked for :latent time. May need to accept certain latents only, like hours
"<datetime> - <datetime> (interval)"
[(dim :time #(not (:latent %))) #"\-|bis" (dim :time #(not (:latent %)))]
(interval %1 %3 true)
"from <datetime> - <datetime> (interval)"
[#"(?i)vo[nm]" (dim :time) #"\-|bis" (dim :time)]
(interval %2 %4 true)
"between <datetime> and <datetime> (interval)"
[#"(?i)zwischen" (dim :time) #"und" (dim :time)]
(interval %2 %4 true)
; Specific for time-of-day, to help resolve ambiguities
"<time-of-day> - <time-of-day> (interval)"
[#(and (= :time-of-day (:form %)) (not (:latent %))) #"\-|bis" {:form :time-of-day}] ; Prevent set alarm 1 to 5pm
(interval %1 %3 true)
"from <time-of-day> - <time-of-day> (interval)"
[#"(?i)(von|nach|ab|frühestens (um)?)" {:form :time-of-day} #"((noch|aber|jedoch)? vor)|\-|bis" {:form :time-of-day}]
(interval %2 %4 true)
"between <time-of-day> and <time-of-day> (interval)"
[#"(?i)zwischen" {:form :time-of-day} #"und" {:form :time-of-day}]
(interval %2 %4 true)
; Specific for within duration... Would need to be reworked
"within <duration>"
[#"(?i)binnen|innerhalb( von)?" (dim :duration)]
(interval (cycle-nth :second 0) (in-duration (:value %2)) false)
"by the end of <time>"; in this case take the end of the time (by the end of next week = by the end of next sunday)
[#"(?i)bis (zum)? ende (von)?|(noch)? vor" (dim :time)];Check me CODE OK?
(interval (cycle-nth :second 0) %2 true)
; One-sided Intervals
"until <time-of-day>"
[#"(?i)vor|bis( zu[rm]?)?" (dim :time)]
(merge %2 {:direction :before})
"after <time-of-day>"
[#"(?i)nach" (dim :time)]
(merge %2 {:direction :after}))
; ;; In this special case, the upper limit is exclusive
; "<hour-of-day> - <hour-of-day> (interval)"
; [{:form :time-of-day} #"-|to|th?ru|through|until" #(and (= :time-of-day (:form %))
; (not (:latent %)))]
; (interval %1 %3 :exclusive)
; "from <hour-of-day> - <hour-of-day> (interval)"
; [#"(?i)from" {:form :time-of-day} #"-|to|th?ru|through|until" #(and (= :time-of-day (:form %))
; (not (:latent %)))]
; (interval %2 %4 :exclusive)
; "time => time2 (experiment)"
; (dim :time)
; (assoc %1 :dim :time2)
| 122786 | (
;; generic
"intersect"
[(dim :time #(not (:latent %))) (dim :time #(not (:latent %)))] ; sequence of two tokens with a time dimension
(intersect %1 %2)
; same thing, with "of" in between like "Sunday of last week"
"intersect by 'of', 'from', 's"
[(dim :time #(not (:latent %))) #"(?i)von|der|im" (dim :time #(not (:latent %)))] ; sequence of two tokens with a time fn
(intersect %1 %3)
; mostly for January 12, 2005
; this is a separate rule, because commas separate very specific tokens
; so we want this rule's classifier to learn this
"intersect by ','"
[(dim :time #(not (:latent %))) #"," (dim :time #(not (:latent %)))] ; sequence of two tokens with a time fn
(intersect %1 %3)
"on <date>" ; on Wed, March 23
[#"(?i)am" (dim :time)]
%2 ; does NOT dissoc latent
"on a named-day" ; on a sunday
[#"(?i)an einem" {:form :day-of-week}]
%2 ; does NOT dissoc latent
;;;;;;;;;;;;;;;;;;;
;; Named things
"named-day"
#"(?i)montags?|mo\.?"
(day-of-week 1)
"named-day"
#"(?i)die?nstags?|di\.?"
(day-of-week 2)
"named-day"
#"(?i)mittwochs?|mi\.?"
(day-of-week 3)
"named-day"
#"(?i)donn?erstags?|do\.?"
(day-of-week 4)
"named-day"
#"(?i)freitags?|fr\.?"
(day-of-week 5)
"named-day"
#"(?i)samstags?|sa\.?"
(day-of-week 6)
"named-day"
#"(?i)sonntags?|so\.?"
(day-of-week 7)
"named-month"
#"(?i)januar|jan\.?"
(month 1)
"named-month"
#"(?i)februar|feb\.?"
(month 2)
"named-month"
#"(?i)märz|mär\.?"
(month 3)
"named-month"
#"(?i)april|apr\.?"
(month 4)
"named-month"
#"(?i)mai"
(month 5)
"named-month"
#"(?i)juni|jun\.?"
(month 6)
"named-month"
#"(?i)juli|jul\.?"
(month 7)
"named-month"
#"(?i)august|aug\.?"
(month 8)
"named-month"
#"(?i)september|sept?\.?"
(month 9)
"named-month"
#"(?i)oktober|oct\.?"
(month 10)
"named-month"
#"(?i)november|nov\.?"
(month 11)
"named-month"
#"(?i)dezember|dez\.?"
(month 12)
; Holiday TODO: check online holidays
; or define dynamic rule (last thursday of october..)
"christmas"
#"(?i)weih?nacht(en|stag)?"
(month-day 12 25)
"christmas eve"
#"(?i)heilig(er)? abend"
(month-day 12 24)
"new year's eve"
#"(?i)silvester"
(month-day 12 31)
"new year's day"
#"(?i)neujahr(s?tag)?"
(month-day 1 1)
"valentine's day"
#"(?i)valentin'?stag"
(month-day 2 14)
"Tag der Deutschen Einheit"
#"(?i)tag (der)? deutsc?hen? einheit"
(month-day 10 3)
"Österreichischer Nationalfeiertag"
#"(österreichischer?)? nationalfeiertag|national feiertag"
(month-day 10 26)
"Schweizer Bundesfeiertag"
#"(?i)schweiz(er)? (bundes)?feiertag|bundes feiertag"
(month-day 8 1)
"Father's Day";third Sunday of June
#"(?i)vatt?ertag|vatt?er (tag)?"
(intersect (day-of-week 7) (month 6) (cycle-nth-after :week 2 (month-day 6 1)))
"Mother's Day";second Sunday in May.
#"(?i)mutt?ertag|mutt?er (tag)?"
(intersect (day-of-week 7) (month 5) (cycle-nth-after :week 1 (month-day 5 1)))
"halloween day"
#"(?i)hall?owe?en?"
(month-day 10 31)
"Allerheiligen"
#"(?i)allerheiligen?|aller heiligen?"
(month-day 11 1)
"Nikolaus"
#"(?i)nikolaus(tag)?|nikolaus tag|nikolo"
(month-day 12 6)
"absorption of , after named day"
[{:form :day-of-week} #","]
%1
"now"
#"(?i)(genau)? ?jetzt|diesen moment|in diesem moment|gerade eben"
(cycle-nth :second 0)
"today"
#"(?i)heute|(um diese zeit|zu dieser zeit|um diesen zeitpunkt|zu diesem zeitpunkt)"
(cycle-nth :day 0)
"tomorrow"
#"(?i)morgen"
(cycle-nth :day 1)
"after tomorrow"
#"(?i)übermorgen"
(cycle-nth :day 2)
"yesterday"
#"(?i)gestern"
(cycle-nth :day -1)
"before yesterday"
#"(?i)vorgestern"
(cycle-nth :day -2)
"EOM|End of month"
#"(?i)(das )?ende des monats?"
(cycle-nth :month 1)
"EOY|End of year"
#"(?i)(das )?(EOY|jahr(es)? ?ende|ende (des )?jahr(es)?)"
(cycle-nth :year 1)
;;
;; This, Next, Last
;; assumed to be strictly in the future:
;; "this Monday" => next week if today in Monday
"this|next <day-of-week>"
[#"(?i)diese(n|r)|kommenden|nächsten" {:form :day-of-week}]
(pred-nth-not-immediate %2 0)
;; for other preds, it can be immediate:
;; "this month" => now is part of it
; See also: cycles in en.cycles.clj
"this <time>"
[#"(?i)diese(n|r|s)?|(im )?laufenden" (dim :time)]
(pred-nth %2 0)
"next <time>"
[#"(?i)nächsten?|nächstes|kommenden?|kommendes" (dim :time)]
(pred-nth-not-immediate %2 0)
"last <time>"
[#"(?i)letzten?|letztes" (dim :time)]
(pred-nth %2 -1)
"after next <time>"
[#"(?i)übernächsten?|über ?nächstes?" (dim :time)]
(pred-nth-not-immediate %2 1)
"<time> after next"
[ (dim :time) #"(?i)nach dem nächsten"]
(pred-nth-not-immediate %1 1)
"<time> before last"
[#"(?i)vorletzten?|vor ?letztes?" (dim :time)]
(pred-nth %2 -2)
"last <day-of-week> of <time>"
[#"(?i)letzte(r|n|s)?" {:form :day-of-week} #"(?i)um|im" (dim :time)];Check me OF
(pred-last-of %2 %4)
"last <cycle> of <time>"
[#"(?i)letzte(r|n|s)?" (dim :cycle) #"(?i)um|im" (dim :time)];Check me OF
(cycle-last-of %2 %4)
; Ordinals
"nth <time> of <time>"
[(dim :ordinal) (dim :time) #"(?i)im" (dim :time)];Check me OF
(pred-nth (intersect %4 %2) (dec (:value %1)))
"nth <time> of <time>"
[#"(?i)der|die|das" (dim :ordinal) (dim :time) #"(?i)im" (dim :time)];Check me OF
(pred-nth (intersect %5 %3) (dec (:value %2)))
"nth <time> after <time>"
[(dim :ordinal) (dim :time) #"(?i)nach" (dim :time)];CHeck me
(pred-nth-after %2 %4 (dec (:value %1)))
"nth <time> after <time>"
[#"(?i)der|das" (dim :ordinal) (dim :time) #"(?i)nach" (dim :time)];Check me
(pred-nth-after %3 %5 (dec (:value %2)))
; Years
; Between 1000 and 2100 we assume it's a year
; Outside of this, it's safer to consider it's latent
"year"
(integer 1000 2100)
(year (:value %1))
"year (latent)"
(integer -10000 999)
(assoc (year (:value %1)) :latent true)
"year (latent)"
(integer 2101 10000)
(assoc (year (:value %1)) :latent true)
; Day of month appears in the following context:
; - the nth
; - March nth
; - nth of March
; - mm/dd (and other numerical formats like yyyy-mm-dd etc.)
; In general we are flexible and accept both ordinals (3rd) and numbers (3)
"the <day-of-month> (ordinal)" ; this one is not latent
[#"(?i)der" (dim :ordinal #(<= 1 (:value %) 31))]
(day-of-month (:value %2))
"<day-of-month> (ordinal)" ; this one is latent
[(dim :ordinal #(<= 1 (:value %) 31))]
(assoc (day-of-month (:value %1)) :latent true)
"the <day-of-month> (non ordinal)" ; this one is latent
[#"(?i)der" (integer 1 31)]
(assoc (day-of-month (:value %2)) :latent true)
"<named-month> <day-of-month> (ordinal)" ; march 12th
[{:form :month} (dim :ordinal #(<= 1 (:value %) 31))]
(intersect %1 (day-of-month (:value %2)))
"<named-month> <day-of-month> (non ordinal)" ; march 12
[{:form :month} (integer 1 31)]
(intersect %1 (day-of-month (:value %2)))
"<day-of-month> (non ordinal) of <named-month>"
[(integer 1 31) #"(?i)vom|von" {:form :month}];Check me DO WE NEED THIS
(intersect %3 (day-of-month (:value %1)))
"<day-of-month> (non ordinal) <named-month>" ; 12 mars
[(integer 1 31) {:form :month}]
(intersect %2 (day-of-month (:value %1)))
"<day-of-month>(ordinal) <named-month>" ; 12nd mars
[(dim :ordinal #(<= 1 (:value %) 31)) {:form :month}]
(intersect %2 (day-of-month (:value %1)))
"<day-of-month>(ordinal) <named-month> year" ; 12nd mars 12
[(dim :ordinal #(<= 1 (:value %) 31)) {:form :month} #"(\d{2,4})"]
(intersect %2 (day-of-month (:value %1)) (year (Integer/parseInt(first (:groups %3)))))
"the ides of <named-month>" ; the ides of march 13th for most months, but on the 15th for March, May, July, and October
[#"(?i)die iden (des?)" {:form :month}]
(intersect %2 (day-of-month (if (#{3 5 7 10} (:month %2)) 15 13)))
; Hours and minutes (absolute time)
;
; Assumptions:
; - 0 is midnight
; - 1..11 is ambiguous am or pm
; - 12 is noon (whereas in English it is ambiguous)
; - 13..23 is pm
"time-of-day (latent)"
(integer 0 23)
(assoc (hour (:value %1) (< (:value %1) 12)) :latent true)
"<time-of-day> o'clock"
[#(:full-hour %) #"(?i)uhr|h"]
(dissoc %1 :latent)
"at <time-of-day>" ; absorption
[#"(?i)um|@" {:form :time-of-day}]
(dissoc %2 :latent)
"hh:mm"
#"(?i)((?:[01]?\d)|(?:2[0-3]))[:.]([0-5]\d)"
(hour-minute (Integer/parseInt (first (:groups %1)))
(Integer/parseInt (second (:groups %1)))
false)
"hhmm (military)"
#"(?i)((?:[01]?\d)|(?:2[0-3]))([0-5]\d)"
(-> (hour-minute (Integer/parseInt (first (:groups %1)))
(Integer/parseInt (second (:groups %1)))
false) ; not a 12-hour clock)
(assoc :latent true))
"hhmm (military) am|pm" ; hh only from 00 to 12
[#"(?i)((?:1[012]|0?\d))([0-5]\d)" #"(?i)([ap])\.?m?\.?"]
; (-> (hour-minute (Integer/parseInt (first (:groups %1)))
; (Integer/parseInt (second (:groups %1)))
; false) ; not a 12-hour clock)
; (assoc :latent true))
(let [[p meridiem] (if (= "a" (-> %2 :groups first .toLowerCase))
[[(hour 0) (hour 12) false] :am]
[[(hour 12) (hour 0) false] :pm])]
(-> (intersect
(hour-minute (Integer/parseInt (first (:groups %1)))
(Integer/parseInt (second (:groups %1)))
true)
(apply interval p))
(assoc :form :time-of-day)))
"<time-of-day> am|pm"
[{:form :time-of-day} #"(?i)([ap])(\s|\.)?m?\.?"];Check me DO WE NEED THIS
;; TODO set_am fn in helpers => add :ampm field
(let [[p meridiem] (if (= "a" (-> %2 :groups first .toLowerCase))
[[(hour 0) (hour 12) false] :am]
[[(hour 12) (hour 0) false] :pm])]
(-> (intersect %1 (apply interval p))
(assoc :form :time-of-day)))
"noon"
#"(?i)mittags?|zwölf (uhr)?"
(hour 12 false)
"midnight|EOD|end of day"
#"(?i)mitternacht|EOD|tagesende|ende (des)? tag(es)?"
(hour 0 false)
"quarter (relative minutes)"
#"(?i)vie?rtel"
{:relative-minutes 15}
"half (relative minutes)"
#"halbe?"
{:relative-minutes 30}
"number (as relative minutes)"
(integer 1 59)
{:relative-minutes (:value %1)}
"<hour-of-day> <integer> (as relative minutes)"
[(dim :time :full-hour) #(:relative-minutes %)]
(hour-relativemin (:full-hour %1) (:relative-minutes %2) true)
"relative minutes to|till|before <integer> (hour-of-day)"
[#(:relative-minutes %) #"(?i)vor" (dim :time :full-hour)]
(hour-relativemin (:full-hour %3) (- (:relative-minutes %1)) true)
"relative minutes after|past <integer> (hour-of-day)"
[#(:relative-minutes %) #"(?i)nach" (dim :time :full-hour)]
(hour-relativemin (:full-hour %3) (:relative-minutes %1) true)
"half <integer> (german style hour-of-day)"
[#"halb" (dim :time :full-hour)];Check me CHANGE CODE TO MATCH GERMAN USAGE
(hour-relativemin (:full-hour %2) -30 true)
; Formatted dates and times
"mm/dd/yyyy"
#"([012]?\d|30|31)\.(0?\d|10|11|12)\.(\d{2,4})"
(parse-dmy (first (:groups %1)) (second (:groups %1)) (nth (:groups %1) 2) true)
"yyyy-mm-dd"
#"(\d{2,4})-(0?\d|10|11|12)-([012]?\d|30|31)"
(parse-dmy (nth (:groups %1) 2) (second (:groups %1)) (first (:groups %1)) true)
"mm/dd"
#"([012]?\d|30|31)\.(0?\d|10|11|12)\."
(parse-dmy (first (:groups %1)) (second (:groups %1)) nil true)
; Part of day (morning, evening...). They are intervals.
"morning" ;; TODO "3am this morning" won't work since morning starts at 4...
[#"(?i)morgens|(in der )?früh|vor ?mittags?|am <NAME>orgen"]
(assoc (interval (hour 3 false) (hour 12 false) false) :form :part-of-day :latent true)
"afternoon"
[#"(?i)nach ?mittags?"]
(assoc (interval (hour 12 false) (hour 19 false) false) :form :part-of-day :latent true)
"evening"
[#"(?i)abends?"]
(assoc (interval (hour 18 false) (hour 0 false) false) :form :part-of-day :latent true)
"night"
[#"(?i)nachts?"]
(assoc (interval (hour 0 false) (hour 4 false) false) :form :part-of-day :latent true)
"lunch"
[#"(?i)(am |zu )?mittags?"]
(assoc (interval (hour 12 false) (hour 14 false) false) :form :part-of-day :latent true)
"in|during the <part-of-day>" ;; removes latent
[#"(?i)(in|an|am|wäh?rend)( der| dem| des)?" {:form :part-of-day}]
(dissoc %2 :latent)
"this <part-of-day>"
[#"(?i)diesen?|dieses|heute" {:form :part-of-day}]
(assoc (intersect (cycle-nth :day 0) %2) :form :part-of-day) ;; removes :latent
"tonight"
#"(?i)heute? (am)? abends?"
(assoc (intersect (cycle-nth :day 0)
(interval (hour 18 false) (hour 0 false) false))
:form :part-of-day) ; no :latent
"after lunch"
#"(?i)nach dem mittagessen|nachmittags?"
(assoc (intersect (cycle-nth :day 0)
(interval (hour 13 false) (hour 17 false) false))
:form :part-of-day) ; no :latent
"after work"
#"(?i)nach (der)? arbeit|(am)? feier ?abend"
(assoc (intersect (cycle-nth :day 0)
(interval (hour 17 false) (hour 21 false) false))
:form :part-of-day) ; no :latent
"<time> <part-of-day>" ; since "morning" "evening" etc. are latent, general time+time is blocked
[(dim :time) {:form :part-of-day}]
(intersect %2 %1)
"<part-of-day> of <time>" ; since "morning" "evening" etc. are latent, general time+time is blocked
[{:form :part-of-day} #"(?i)des|von|vom|am" (dim :time)];Check me
(intersect %1 %3)
; Other intervals: week-end, seasons
"week-end" ; from Friday 6pm to Sunday midnight
#"(?i)wochen ?ende?"
(interval (intersect (day-of-week 5) (hour 18 false))
(intersect (day-of-week 1) (hour 0 false))
false)
"season"
#"(?i)sommer" ;could be smarter and take the exact hour into account... also some years the day can change
(interval (month-day 6 21) (month-day 9 23) false)
"season"
#"(?i)herbst"
(interval (month-day 9 23) (month-day 12 21) false)
"season"
#"(?i)winter"
(interval (month-day 12 21) (month-day 3 20) false)
"season"
#"(?i)frühling|frühjahr"
(interval (month-day 3 20) (month-day 6 21) false)
; Time zones
"timezone"
#"(?i)(YEKT|YEKST|YAPT|YAKT|YAKST|WT|WST|WITA|WIT|WIB|WGT|WGST|WFT|WEZ|WET|WESZ|WEST|WAT|WAST|VUT|VLAT|VLAST|VET|UZT|UYT|UYST|UTC|ULAT|TVT|TMT|TLT|TKT|TJT|TFT|TAHT|SST|SRT|SGT|SCT|SBT|SAST|SAMT|RET|PYT|PYST|PWT|PT|PST|PONT|PMST|PMDT|PKT|PHT|PHOT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|NCT|MYT|MVT|MUT|MST|MSK|MSD|MMT|MHT|MEZ|MESZ|MDT|MAWT|MART|MAGT|MAGST|LINT|LHST|LHDT|KUYT|KST|KRAT|KRAST|KGT|JST|IST|IRST|IRKT|IRKST|IRDT|IOT|IDT|ICT|HOVT|HNY|HNT|HNR|HNP|HNE|HNC|HNA|HLV|HKT|HAY|HAT|HAST|HAR|HAP|HAE|HADT|HAC|HAA|GYT|GST|GMT|GILT|GFT|GET|GAMT|GALT|FNT|FKT|FKST|FJT|FJST|ET|EST|EGT|EGST|EET|EEST|EDT|ECT|EAT|EAST|EASST|DAVT|ChST|CXT|CVT|CST|COT|CLT|CLST|CKT|CHAST|CHADT|CET|CEST|CDT|CCT|CAT|CAST|BTT|BST|BRT|BRST|BOT|BNT|AZT|AZST|AZOT|AZOST|AWST|AWDT|AST|ART|AQTT|ANAT|ANAST|AMT|AMST|ALMT|AKST|AKDT|AFT|AEST|AEDT|ADT|ACST|ACDT)"
{:dim :timezone
:value (-> %1 :groups first .toUpperCase)}
"<time> timezone"
[(dim :time) (dim :timezone)]
(set-timezone %1 (:value %2))
; Precision
; FIXME
; - should be applied to all dims not just time-of-day
;- shouldn't remove latency, except maybe -ish
"<time-of-day> approximately" ; 7ish
[{:form :time-of-day} #"(?i)(um )?zirka|ungefähr|etwa"]
(-> %1
(dissoc :latent)
(merge {:precision "approximate"}));Check me NO TRANSLATION NECESSARY
"<time-of-day> sharp" ; sharp
[{:form :time-of-day} #"(?i)genau|exakt|pünktlich|punkt( um)?"]
(-> %1
(dissoc :latent)
(merge {:precision "exact"}));Check me NO TRANSLATION NECESSARY
"about <time-of-day>" ; about
[#"(?i)(um )?zirka|ungefähr|etwa" {:form :time-of-day}]
(-> %2
(dissoc :latent)
(merge {:precision "approximate"}));Check me NO TRANSLATION NECESSARY
"exactly <time-of-day>" ; sharp
[#"(?i)genau|exakt|pünktlich|punkt( um)?" {:form :time-of-day}]
(-> %2
(dissoc :latent)
(merge {:precision "exact"}));Check me NO TRANSLATION NECESSARY
; Intervals
"<month> dd-dd (interval)"
[ #"([012]?\d|30|31)(ter|\.)?" #"\-|bis" #"([012]?\d|30|31)(ter|\.)?" {:form :month}]
(interval (intersect %4 (day-of-month (Integer/parseInt (-> %1 :groups first))))
(intersect %4 (day-of-month (Integer/parseInt (-> %3 :groups first))))
true)
; Blocked for :latent time. May need to accept certain latents only, like hours
"<datetime> - <datetime> (interval)"
[(dim :time #(not (:latent %))) #"\-|bis" (dim :time #(not (:latent %)))]
(interval %1 %3 true)
"from <datetime> - <datetime> (interval)"
[#"(?i)vo[nm]" (dim :time) #"\-|bis" (dim :time)]
(interval %2 %4 true)
"between <datetime> and <datetime> (interval)"
[#"(?i)zwischen" (dim :time) #"und" (dim :time)]
(interval %2 %4 true)
; Specific for time-of-day, to help resolve ambiguities
"<time-of-day> - <time-of-day> (interval)"
[#(and (= :time-of-day (:form %)) (not (:latent %))) #"\-|bis" {:form :time-of-day}] ; Prevent set alarm 1 to 5pm
(interval %1 %3 true)
"from <time-of-day> - <time-of-day> (interval)"
[#"(?i)(von|nach|ab|frühestens (um)?)" {:form :time-of-day} #"((noch|aber|jedoch)? vor)|\-|bis" {:form :time-of-day}]
(interval %2 %4 true)
"between <time-of-day> and <time-of-day> (interval)"
[#"(?i)zwischen" {:form :time-of-day} #"und" {:form :time-of-day}]
(interval %2 %4 true)
; Specific for within duration... Would need to be reworked
"within <duration>"
[#"(?i)binnen|innerhalb( von)?" (dim :duration)]
(interval (cycle-nth :second 0) (in-duration (:value %2)) false)
"by the end of <time>"; in this case take the end of the time (by the end of next week = by the end of next sunday)
[#"(?i)bis (zum)? ende (von)?|(noch)? vor" (dim :time)];Check me CODE OK?
(interval (cycle-nth :second 0) %2 true)
; One-sided Intervals
"until <time-of-day>"
[#"(?i)vor|bis( zu[rm]?)?" (dim :time)]
(merge %2 {:direction :before})
"after <time-of-day>"
[#"(?i)nach" (dim :time)]
(merge %2 {:direction :after}))
; ;; In this special case, the upper limit is exclusive
; "<hour-of-day> - <hour-of-day> (interval)"
; [{:form :time-of-day} #"-|to|th?ru|through|until" #(and (= :time-of-day (:form %))
; (not (:latent %)))]
; (interval %1 %3 :exclusive)
; "from <hour-of-day> - <hour-of-day> (interval)"
; [#"(?i)from" {:form :time-of-day} #"-|to|th?ru|through|until" #(and (= :time-of-day (:form %))
; (not (:latent %)))]
; (interval %2 %4 :exclusive)
; "time => time2 (experiment)"
; (dim :time)
; (assoc %1 :dim :time2)
| true | (
;; generic
"intersect"
[(dim :time #(not (:latent %))) (dim :time #(not (:latent %)))] ; sequence of two tokens with a time dimension
(intersect %1 %2)
; same thing, with "of" in between like "Sunday of last week"
"intersect by 'of', 'from', 's"
[(dim :time #(not (:latent %))) #"(?i)von|der|im" (dim :time #(not (:latent %)))] ; sequence of two tokens with a time fn
(intersect %1 %3)
; mostly for January 12, 2005
; this is a separate rule, because commas separate very specific tokens
; so we want this rule's classifier to learn this
"intersect by ','"
[(dim :time #(not (:latent %))) #"," (dim :time #(not (:latent %)))] ; sequence of two tokens with a time fn
(intersect %1 %3)
"on <date>" ; on Wed, March 23
[#"(?i)am" (dim :time)]
%2 ; does NOT dissoc latent
"on a named-day" ; on a sunday
[#"(?i)an einem" {:form :day-of-week}]
%2 ; does NOT dissoc latent
;;;;;;;;;;;;;;;;;;;
;; Named things
"named-day"
#"(?i)montags?|mo\.?"
(day-of-week 1)
"named-day"
#"(?i)die?nstags?|di\.?"
(day-of-week 2)
"named-day"
#"(?i)mittwochs?|mi\.?"
(day-of-week 3)
"named-day"
#"(?i)donn?erstags?|do\.?"
(day-of-week 4)
"named-day"
#"(?i)freitags?|fr\.?"
(day-of-week 5)
"named-day"
#"(?i)samstags?|sa\.?"
(day-of-week 6)
"named-day"
#"(?i)sonntags?|so\.?"
(day-of-week 7)
"named-month"
#"(?i)januar|jan\.?"
(month 1)
"named-month"
#"(?i)februar|feb\.?"
(month 2)
"named-month"
#"(?i)märz|mär\.?"
(month 3)
"named-month"
#"(?i)april|apr\.?"
(month 4)
"named-month"
#"(?i)mai"
(month 5)
"named-month"
#"(?i)juni|jun\.?"
(month 6)
"named-month"
#"(?i)juli|jul\.?"
(month 7)
"named-month"
#"(?i)august|aug\.?"
(month 8)
"named-month"
#"(?i)september|sept?\.?"
(month 9)
"named-month"
#"(?i)oktober|oct\.?"
(month 10)
"named-month"
#"(?i)november|nov\.?"
(month 11)
"named-month"
#"(?i)dezember|dez\.?"
(month 12)
; Holiday TODO: check online holidays
; or define dynamic rule (last thursday of october..)
"christmas"
#"(?i)weih?nacht(en|stag)?"
(month-day 12 25)
"christmas eve"
#"(?i)heilig(er)? abend"
(month-day 12 24)
"new year's eve"
#"(?i)silvester"
(month-day 12 31)
"new year's day"
#"(?i)neujahr(s?tag)?"
(month-day 1 1)
"valentine's day"
#"(?i)valentin'?stag"
(month-day 2 14)
"Tag der Deutschen Einheit"
#"(?i)tag (der)? deutsc?hen? einheit"
(month-day 10 3)
"Österreichischer Nationalfeiertag"
#"(österreichischer?)? nationalfeiertag|national feiertag"
(month-day 10 26)
"Schweizer Bundesfeiertag"
#"(?i)schweiz(er)? (bundes)?feiertag|bundes feiertag"
(month-day 8 1)
"Father's Day";third Sunday of June
#"(?i)vatt?ertag|vatt?er (tag)?"
(intersect (day-of-week 7) (month 6) (cycle-nth-after :week 2 (month-day 6 1)))
"Mother's Day";second Sunday in May.
#"(?i)mutt?ertag|mutt?er (tag)?"
(intersect (day-of-week 7) (month 5) (cycle-nth-after :week 1 (month-day 5 1)))
"halloween day"
#"(?i)hall?owe?en?"
(month-day 10 31)
"Allerheiligen"
#"(?i)allerheiligen?|aller heiligen?"
(month-day 11 1)
"Nikolaus"
#"(?i)nikolaus(tag)?|nikolaus tag|nikolo"
(month-day 12 6)
"absorption of , after named day"
[{:form :day-of-week} #","]
%1
"now"
#"(?i)(genau)? ?jetzt|diesen moment|in diesem moment|gerade eben"
(cycle-nth :second 0)
"today"
#"(?i)heute|(um diese zeit|zu dieser zeit|um diesen zeitpunkt|zu diesem zeitpunkt)"
(cycle-nth :day 0)
"tomorrow"
#"(?i)morgen"
(cycle-nth :day 1)
"after tomorrow"
#"(?i)übermorgen"
(cycle-nth :day 2)
"yesterday"
#"(?i)gestern"
(cycle-nth :day -1)
"before yesterday"
#"(?i)vorgestern"
(cycle-nth :day -2)
"EOM|End of month"
#"(?i)(das )?ende des monats?"
(cycle-nth :month 1)
"EOY|End of year"
#"(?i)(das )?(EOY|jahr(es)? ?ende|ende (des )?jahr(es)?)"
(cycle-nth :year 1)
;;
;; This, Next, Last
;; assumed to be strictly in the future:
;; "this Monday" => next week if today in Monday
"this|next <day-of-week>"
[#"(?i)diese(n|r)|kommenden|nächsten" {:form :day-of-week}]
(pred-nth-not-immediate %2 0)
;; for other preds, it can be immediate:
;; "this month" => now is part of it
; See also: cycles in en.cycles.clj
"this <time>"
[#"(?i)diese(n|r|s)?|(im )?laufenden" (dim :time)]
(pred-nth %2 0)
"next <time>"
[#"(?i)nächsten?|nächstes|kommenden?|kommendes" (dim :time)]
(pred-nth-not-immediate %2 0)
"last <time>"
[#"(?i)letzten?|letztes" (dim :time)]
(pred-nth %2 -1)
"after next <time>"
[#"(?i)übernächsten?|über ?nächstes?" (dim :time)]
(pred-nth-not-immediate %2 1)
"<time> after next"
[ (dim :time) #"(?i)nach dem nächsten"]
(pred-nth-not-immediate %1 1)
"<time> before last"
[#"(?i)vorletzten?|vor ?letztes?" (dim :time)]
(pred-nth %2 -2)
"last <day-of-week> of <time>"
[#"(?i)letzte(r|n|s)?" {:form :day-of-week} #"(?i)um|im" (dim :time)];Check me OF
(pred-last-of %2 %4)
"last <cycle> of <time>"
[#"(?i)letzte(r|n|s)?" (dim :cycle) #"(?i)um|im" (dim :time)];Check me OF
(cycle-last-of %2 %4)
; Ordinals
"nth <time> of <time>"
[(dim :ordinal) (dim :time) #"(?i)im" (dim :time)];Check me OF
(pred-nth (intersect %4 %2) (dec (:value %1)))
"nth <time> of <time>"
[#"(?i)der|die|das" (dim :ordinal) (dim :time) #"(?i)im" (dim :time)];Check me OF
(pred-nth (intersect %5 %3) (dec (:value %2)))
"nth <time> after <time>"
[(dim :ordinal) (dim :time) #"(?i)nach" (dim :time)];CHeck me
(pred-nth-after %2 %4 (dec (:value %1)))
"nth <time> after <time>"
[#"(?i)der|das" (dim :ordinal) (dim :time) #"(?i)nach" (dim :time)];Check me
(pred-nth-after %3 %5 (dec (:value %2)))
; Years
; Between 1000 and 2100 we assume it's a year
; Outside of this, it's safer to consider it's latent
"year"
(integer 1000 2100)
(year (:value %1))
"year (latent)"
(integer -10000 999)
(assoc (year (:value %1)) :latent true)
"year (latent)"
(integer 2101 10000)
(assoc (year (:value %1)) :latent true)
; Day of month appears in the following context:
; - the nth
; - March nth
; - nth of March
; - mm/dd (and other numerical formats like yyyy-mm-dd etc.)
; In general we are flexible and accept both ordinals (3rd) and numbers (3)
"the <day-of-month> (ordinal)" ; this one is not latent
[#"(?i)der" (dim :ordinal #(<= 1 (:value %) 31))]
(day-of-month (:value %2))
"<day-of-month> (ordinal)" ; this one is latent
[(dim :ordinal #(<= 1 (:value %) 31))]
(assoc (day-of-month (:value %1)) :latent true)
"the <day-of-month> (non ordinal)" ; this one is latent
[#"(?i)der" (integer 1 31)]
(assoc (day-of-month (:value %2)) :latent true)
"<named-month> <day-of-month> (ordinal)" ; march 12th
[{:form :month} (dim :ordinal #(<= 1 (:value %) 31))]
(intersect %1 (day-of-month (:value %2)))
"<named-month> <day-of-month> (non ordinal)" ; march 12
[{:form :month} (integer 1 31)]
(intersect %1 (day-of-month (:value %2)))
"<day-of-month> (non ordinal) of <named-month>"
[(integer 1 31) #"(?i)vom|von" {:form :month}];Check me DO WE NEED THIS
(intersect %3 (day-of-month (:value %1)))
"<day-of-month> (non ordinal) <named-month>" ; 12 mars
[(integer 1 31) {:form :month}]
(intersect %2 (day-of-month (:value %1)))
"<day-of-month>(ordinal) <named-month>" ; 12nd mars
[(dim :ordinal #(<= 1 (:value %) 31)) {:form :month}]
(intersect %2 (day-of-month (:value %1)))
"<day-of-month>(ordinal) <named-month> year" ; 12nd mars 12
[(dim :ordinal #(<= 1 (:value %) 31)) {:form :month} #"(\d{2,4})"]
(intersect %2 (day-of-month (:value %1)) (year (Integer/parseInt(first (:groups %3)))))
"the ides of <named-month>" ; the ides of march 13th for most months, but on the 15th for March, May, July, and October
[#"(?i)die iden (des?)" {:form :month}]
(intersect %2 (day-of-month (if (#{3 5 7 10} (:month %2)) 15 13)))
; Hours and minutes (absolute time)
;
; Assumptions:
; - 0 is midnight
; - 1..11 is ambiguous am or pm
; - 12 is noon (whereas in English it is ambiguous)
; - 13..23 is pm
"time-of-day (latent)"
(integer 0 23)
(assoc (hour (:value %1) (< (:value %1) 12)) :latent true)
"<time-of-day> o'clock"
[#(:full-hour %) #"(?i)uhr|h"]
(dissoc %1 :latent)
"at <time-of-day>" ; absorption
[#"(?i)um|@" {:form :time-of-day}]
(dissoc %2 :latent)
"hh:mm"
#"(?i)((?:[01]?\d)|(?:2[0-3]))[:.]([0-5]\d)"
(hour-minute (Integer/parseInt (first (:groups %1)))
(Integer/parseInt (second (:groups %1)))
false)
"hhmm (military)"
#"(?i)((?:[01]?\d)|(?:2[0-3]))([0-5]\d)"
(-> (hour-minute (Integer/parseInt (first (:groups %1)))
(Integer/parseInt (second (:groups %1)))
false) ; not a 12-hour clock)
(assoc :latent true))
"hhmm (military) am|pm" ; hh only from 00 to 12
[#"(?i)((?:1[012]|0?\d))([0-5]\d)" #"(?i)([ap])\.?m?\.?"]
; (-> (hour-minute (Integer/parseInt (first (:groups %1)))
; (Integer/parseInt (second (:groups %1)))
; false) ; not a 12-hour clock)
; (assoc :latent true))
(let [[p meridiem] (if (= "a" (-> %2 :groups first .toLowerCase))
[[(hour 0) (hour 12) false] :am]
[[(hour 12) (hour 0) false] :pm])]
(-> (intersect
(hour-minute (Integer/parseInt (first (:groups %1)))
(Integer/parseInt (second (:groups %1)))
true)
(apply interval p))
(assoc :form :time-of-day)))
"<time-of-day> am|pm"
[{:form :time-of-day} #"(?i)([ap])(\s|\.)?m?\.?"];Check me DO WE NEED THIS
;; TODO set_am fn in helpers => add :ampm field
(let [[p meridiem] (if (= "a" (-> %2 :groups first .toLowerCase))
[[(hour 0) (hour 12) false] :am]
[[(hour 12) (hour 0) false] :pm])]
(-> (intersect %1 (apply interval p))
(assoc :form :time-of-day)))
"noon"
#"(?i)mittags?|zwölf (uhr)?"
(hour 12 false)
"midnight|EOD|end of day"
#"(?i)mitternacht|EOD|tagesende|ende (des)? tag(es)?"
(hour 0 false)
"quarter (relative minutes)"
#"(?i)vie?rtel"
{:relative-minutes 15}
"half (relative minutes)"
#"halbe?"
{:relative-minutes 30}
"number (as relative minutes)"
(integer 1 59)
{:relative-minutes (:value %1)}
"<hour-of-day> <integer> (as relative minutes)"
[(dim :time :full-hour) #(:relative-minutes %)]
(hour-relativemin (:full-hour %1) (:relative-minutes %2) true)
"relative minutes to|till|before <integer> (hour-of-day)"
[#(:relative-minutes %) #"(?i)vor" (dim :time :full-hour)]
(hour-relativemin (:full-hour %3) (- (:relative-minutes %1)) true)
"relative minutes after|past <integer> (hour-of-day)"
[#(:relative-minutes %) #"(?i)nach" (dim :time :full-hour)]
(hour-relativemin (:full-hour %3) (:relative-minutes %1) true)
"half <integer> (german style hour-of-day)"
[#"halb" (dim :time :full-hour)];Check me CHANGE CODE TO MATCH GERMAN USAGE
(hour-relativemin (:full-hour %2) -30 true)
; Formatted dates and times
"mm/dd/yyyy"
#"([012]?\d|30|31)\.(0?\d|10|11|12)\.(\d{2,4})"
(parse-dmy (first (:groups %1)) (second (:groups %1)) (nth (:groups %1) 2) true)
"yyyy-mm-dd"
#"(\d{2,4})-(0?\d|10|11|12)-([012]?\d|30|31)"
(parse-dmy (nth (:groups %1) 2) (second (:groups %1)) (first (:groups %1)) true)
"mm/dd"
#"([012]?\d|30|31)\.(0?\d|10|11|12)\."
(parse-dmy (first (:groups %1)) (second (:groups %1)) nil true)
; Part of day (morning, evening...). They are intervals.
"morning" ;; TODO "3am this morning" won't work since morning starts at 4...
[#"(?i)morgens|(in der )?früh|vor ?mittags?|am PI:NAME:<NAME>END_PIorgen"]
(assoc (interval (hour 3 false) (hour 12 false) false) :form :part-of-day :latent true)
"afternoon"
[#"(?i)nach ?mittags?"]
(assoc (interval (hour 12 false) (hour 19 false) false) :form :part-of-day :latent true)
"evening"
[#"(?i)abends?"]
(assoc (interval (hour 18 false) (hour 0 false) false) :form :part-of-day :latent true)
"night"
[#"(?i)nachts?"]
(assoc (interval (hour 0 false) (hour 4 false) false) :form :part-of-day :latent true)
"lunch"
[#"(?i)(am |zu )?mittags?"]
(assoc (interval (hour 12 false) (hour 14 false) false) :form :part-of-day :latent true)
"in|during the <part-of-day>" ;; removes latent
[#"(?i)(in|an|am|wäh?rend)( der| dem| des)?" {:form :part-of-day}]
(dissoc %2 :latent)
"this <part-of-day>"
[#"(?i)diesen?|dieses|heute" {:form :part-of-day}]
(assoc (intersect (cycle-nth :day 0) %2) :form :part-of-day) ;; removes :latent
"tonight"
#"(?i)heute? (am)? abends?"
(assoc (intersect (cycle-nth :day 0)
(interval (hour 18 false) (hour 0 false) false))
:form :part-of-day) ; no :latent
"after lunch"
#"(?i)nach dem mittagessen|nachmittags?"
(assoc (intersect (cycle-nth :day 0)
(interval (hour 13 false) (hour 17 false) false))
:form :part-of-day) ; no :latent
"after work"
#"(?i)nach (der)? arbeit|(am)? feier ?abend"
(assoc (intersect (cycle-nth :day 0)
(interval (hour 17 false) (hour 21 false) false))
:form :part-of-day) ; no :latent
"<time> <part-of-day>" ; since "morning" "evening" etc. are latent, general time+time is blocked
[(dim :time) {:form :part-of-day}]
(intersect %2 %1)
"<part-of-day> of <time>" ; since "morning" "evening" etc. are latent, general time+time is blocked
[{:form :part-of-day} #"(?i)des|von|vom|am" (dim :time)];Check me
(intersect %1 %3)
; Other intervals: week-end, seasons
"week-end" ; from Friday 6pm to Sunday midnight
#"(?i)wochen ?ende?"
(interval (intersect (day-of-week 5) (hour 18 false))
(intersect (day-of-week 1) (hour 0 false))
false)
"season"
#"(?i)sommer" ;could be smarter and take the exact hour into account... also some years the day can change
(interval (month-day 6 21) (month-day 9 23) false)
"season"
#"(?i)herbst"
(interval (month-day 9 23) (month-day 12 21) false)
"season"
#"(?i)winter"
(interval (month-day 12 21) (month-day 3 20) false)
"season"
#"(?i)frühling|frühjahr"
(interval (month-day 3 20) (month-day 6 21) false)
; Time zones
"timezone"
#"(?i)(YEKT|YEKST|YAPT|YAKT|YAKST|WT|WST|WITA|WIT|WIB|WGT|WGST|WFT|WEZ|WET|WESZ|WEST|WAT|WAST|VUT|VLAT|VLAST|VET|UZT|UYT|UYST|UTC|ULAT|TVT|TMT|TLT|TKT|TJT|TFT|TAHT|SST|SRT|SGT|SCT|SBT|SAST|SAMT|RET|PYT|PYST|PWT|PT|PST|PONT|PMST|PMDT|PKT|PHT|PHOT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|NCT|MYT|MVT|MUT|MST|MSK|MSD|MMT|MHT|MEZ|MESZ|MDT|MAWT|MART|MAGT|MAGST|LINT|LHST|LHDT|KUYT|KST|KRAT|KRAST|KGT|JST|IST|IRST|IRKT|IRKST|IRDT|IOT|IDT|ICT|HOVT|HNY|HNT|HNR|HNP|HNE|HNC|HNA|HLV|HKT|HAY|HAT|HAST|HAR|HAP|HAE|HADT|HAC|HAA|GYT|GST|GMT|GILT|GFT|GET|GAMT|GALT|FNT|FKT|FKST|FJT|FJST|ET|EST|EGT|EGST|EET|EEST|EDT|ECT|EAT|EAST|EASST|DAVT|ChST|CXT|CVT|CST|COT|CLT|CLST|CKT|CHAST|CHADT|CET|CEST|CDT|CCT|CAT|CAST|BTT|BST|BRT|BRST|BOT|BNT|AZT|AZST|AZOT|AZOST|AWST|AWDT|AST|ART|AQTT|ANAT|ANAST|AMT|AMST|ALMT|AKST|AKDT|AFT|AEST|AEDT|ADT|ACST|ACDT)"
{:dim :timezone
:value (-> %1 :groups first .toUpperCase)}
"<time> timezone"
[(dim :time) (dim :timezone)]
(set-timezone %1 (:value %2))
; Precision
; FIXME
; - should be applied to all dims not just time-of-day
;- shouldn't remove latency, except maybe -ish
"<time-of-day> approximately" ; 7ish
[{:form :time-of-day} #"(?i)(um )?zirka|ungefähr|etwa"]
(-> %1
(dissoc :latent)
(merge {:precision "approximate"}));Check me NO TRANSLATION NECESSARY
"<time-of-day> sharp" ; sharp
[{:form :time-of-day} #"(?i)genau|exakt|pünktlich|punkt( um)?"]
(-> %1
(dissoc :latent)
(merge {:precision "exact"}));Check me NO TRANSLATION NECESSARY
"about <time-of-day>" ; about
[#"(?i)(um )?zirka|ungefähr|etwa" {:form :time-of-day}]
(-> %2
(dissoc :latent)
(merge {:precision "approximate"}));Check me NO TRANSLATION NECESSARY
"exactly <time-of-day>" ; sharp
[#"(?i)genau|exakt|pünktlich|punkt( um)?" {:form :time-of-day}]
(-> %2
(dissoc :latent)
(merge {:precision "exact"}));Check me NO TRANSLATION NECESSARY
; Intervals
"<month> dd-dd (interval)"
[ #"([012]?\d|30|31)(ter|\.)?" #"\-|bis" #"([012]?\d|30|31)(ter|\.)?" {:form :month}]
(interval (intersect %4 (day-of-month (Integer/parseInt (-> %1 :groups first))))
(intersect %4 (day-of-month (Integer/parseInt (-> %3 :groups first))))
true)
; Blocked for :latent time. May need to accept certain latents only, like hours
"<datetime> - <datetime> (interval)"
[(dim :time #(not (:latent %))) #"\-|bis" (dim :time #(not (:latent %)))]
(interval %1 %3 true)
"from <datetime> - <datetime> (interval)"
[#"(?i)vo[nm]" (dim :time) #"\-|bis" (dim :time)]
(interval %2 %4 true)
"between <datetime> and <datetime> (interval)"
[#"(?i)zwischen" (dim :time) #"und" (dim :time)]
(interval %2 %4 true)
; Specific for time-of-day, to help resolve ambiguities
"<time-of-day> - <time-of-day> (interval)"
[#(and (= :time-of-day (:form %)) (not (:latent %))) #"\-|bis" {:form :time-of-day}] ; Prevent set alarm 1 to 5pm
(interval %1 %3 true)
"from <time-of-day> - <time-of-day> (interval)"
[#"(?i)(von|nach|ab|frühestens (um)?)" {:form :time-of-day} #"((noch|aber|jedoch)? vor)|\-|bis" {:form :time-of-day}]
(interval %2 %4 true)
"between <time-of-day> and <time-of-day> (interval)"
[#"(?i)zwischen" {:form :time-of-day} #"und" {:form :time-of-day}]
(interval %2 %4 true)
; Specific for within duration... Would need to be reworked
"within <duration>"
[#"(?i)binnen|innerhalb( von)?" (dim :duration)]
(interval (cycle-nth :second 0) (in-duration (:value %2)) false)
"by the end of <time>"; in this case take the end of the time (by the end of next week = by the end of next sunday)
[#"(?i)bis (zum)? ende (von)?|(noch)? vor" (dim :time)];Check me CODE OK?
(interval (cycle-nth :second 0) %2 true)
; One-sided Intervals
"until <time-of-day>"
[#"(?i)vor|bis( zu[rm]?)?" (dim :time)]
(merge %2 {:direction :before})
"after <time-of-day>"
[#"(?i)nach" (dim :time)]
(merge %2 {:direction :after}))
; ;; In this special case, the upper limit is exclusive
; "<hour-of-day> - <hour-of-day> (interval)"
; [{:form :time-of-day} #"-|to|th?ru|through|until" #(and (= :time-of-day (:form %))
; (not (:latent %)))]
; (interval %1 %3 :exclusive)
; "from <hour-of-day> - <hour-of-day> (interval)"
; [#"(?i)from" {:form :time-of-day} #"-|to|th?ru|through|until" #(and (= :time-of-day (:form %))
; (not (:latent %)))]
; (interval %2 %4 :exclusive)
; "time => time2 (experiment)"
; (dim :time)
; (assoc %1 :dim :time2)
|
[
{
"context": ";;;;;;;;;;;;;;;;;;;\n\n(def linen-data {:ugen-name \"Linen\"\n :rates [:kr]\n :",
"end": 16734,
"score": 0.9003832340240479,
"start": 16729,
"tag": "NAME",
"value": "Linen"
}
] | src/synchrotron/ugens.cljs | brianfay/synchrotron | 0 | (ns synchrotron.ugens
(:require [synchrotron.ugen :as ugen :refer [abstract-ugen]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Binary Ops
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def binary-op-ugen-data {:ugen-name "BinaryOpUGen"
:rates [:ar :kr :demand :ir]
:inputs [:a nil :b nil]
:num-outputs 1})
;;TODO infer calculation-rate from ugen inputs (but I'm not sure which rate should get preference if two different rates are given)
(def add (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 0)))
(def add:ar (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 0)))
(def add:kr (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :kr :special-index 0)))
(def sub (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 1)))
(def sub:ar (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 1)))
(def sub:kr (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :kr :special-index 1)))
(def mul (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 2)))
(def mul:ar (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 2)))
(def mul:kr (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :kr :special-index 2)))
(def div (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 4)));;float division
(def div:ar (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 4)));;float division
(def div:kr (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :kr :special-index 4)));;float division
(def eq (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 6)))
(def eq:ar (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 6)))
(def eq:kr (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :kr :special-index 6)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Buffer IO
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;num-channels is actually a concept of "MultiOutUgen" and so this doesn't work
(def buf-rd-data {:ugen-name "BufRd"
:rates [:ar :kr]
:inputs [:num-channels 1 :buf-num 0 :phase 0 :loop 0 :interpolation 2]
;;sclang has a variable called argsNamesInputsOffsets, which you can set to 2 to NOT send the first input to scsynth.
;;it's very confusing.
:treat-num-channels-as-input false
:num-outputs :variadic})
(def buf-rd (partial abstract-ugen buf-rd-data))
(def buf-rd:ar (partial abstract-ugen (assoc buf-rd-data :calculation-rate :ar)))
(def buf-rd:kr (partial abstract-ugen (assoc buf-rd-data :calculation-rate :kr)))
(def buf-wr-data {:ugen-name "BufWr"
:rates [:ar :kr]
:inputs [:input-array nil :buf-num 0 :phase 0 :loop 1]
:num-outputs 1})
(def buf-wr (partial abstract-ugen buf-wr-data))
(def buf-wr:ar (partial abstract-ugen (assoc buf-wr-data :calculation-rate :ar)))
(def buf-wr:kr (partial abstract-ugen (assoc buf-wr-data :calculation-rate :kr)))
(def record-buf-data {:ugen-name "RecordBuf"
:rates [:ar :kr]
;;TODO: would need to actually explode input-array out into multiple inputs to get this working with multi-channel buffers
:inputs [:buf-num 0 :offset 0 :rec-level 1 :pre-level 0 :run 1 :loop 1 :trigger 1 :done-action 0 :input-array nil]
:num-outputs 1})
(def record-buf (partial abstract-ugen record-buf-data))
(def record-buf:ar (partial abstract-ugen (assoc record-buf-data :calculation-rate :ar)))
(def record-buf:kr (partial abstract-ugen (assoc record-buf-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Delays
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def delay-n-data {:ugen-name "DelayN"
:rates [:ar :kr]
:inputs [:in 0 :max-delay-time 0.2 :delay-time 0.2]
:num-outputs 1})
(def delay-n (partial abstract-ugen delay-n-data))
(def delay-n:ar (partial abstract-ugen (assoc delay-n-data :calculation-rate :ar)))
(def delay-n:kr (partial abstract-ugen (assoc delay-n-data :calculation-rate :kr)))
(def comb-n-data {:ugen-name "CombN"
:rates [:ar :kr]
:inputs [:in 0 :max-delay-time 0.2 :delay-time 0.2 :decay-time 1]
:num-outputs 1})
(def comb-n (partial abstract-ugen comb-n-data))
(def comb-n:ar (partial abstract-ugen (assoc comb-n-data :calculation-rate :ar)))
(def comb-n:kr (partial abstract-ugen (assoc comb-n-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; IO
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def out-data {:ugen-name "Out"
:rates [:ar :kr]
:inputs [:bus 0 :channels-array nil]
:num-outputs 0})
(def out (partial abstract-ugen out-data))
(def out:ar (partial abstract-ugen (assoc out-data :calculation-rate :ar)))
(def out:kr (partial abstract-ugen (assoc out-data :calculation-rate :kr)))
(def replace-out-data {:ugen-name "ReplaceOut"
:rates [:ar :kr]
:inputs [:bus 0 :channels-array nil]
:num-outputs 0})
(def replace-out (partial abstract-ugen replace-out-data))
(def replace-out:ar (partial abstract-ugen (assoc replace-out-data :calculation-rate :ar)))
(def replace-out:kr (partial abstract-ugen (assoc replace-out-data :calculation-rate :kr)))
(def in-data {:ugen-name "In"
:rates [:ar :kr]
:inputs [:bus 0 :num-channels 1]
:num-outputs :variadic})
(def in (partial abstract-ugen in-data))
(def in:ar (partial abstract-ugen (assoc in-data :calculation-rate :ar)))
(def in:kr (partial abstract-ugen (assoc in-data :calcutaion-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Info
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def info-ugen-base {:rates [:ir]
:inputs nil
:num-outputs 1})
(def sample-rate-data (assoc info-ugen-base :ugen-name "SampleRate"))
(def sample-rate (partial abstract-ugen sample-rate-data))
(def sample-rate:ir (partial abstract-ugen (assoc sample-rate-data :calculation-rate :ir)))
(def sample-dur-data (assoc info-ugen-base :ugen-name "SampleDur"))
(def sample-dur (partial abstract-ugen sample-dur-data))
(def sample-dur:ir (partial abstract-ugen (assoc sample-dur-data :calculation-rate :ir)))
(def radians-per-sample-data (assoc info-ugen-base :ugen-name "RadiansPerSample"))
(def radians-per-sample (partial abstract-ugen radians-per-sample-data))
(def radians-per-sample:ir (partial abstract-ugen (assoc radians-per-sample-data :calculation-rate :ir)))
(def block-size-data (assoc info-ugen-base :ugen-name "BlockSize"))
(def block-size (partial abstract-ugen block-size-data))
(def block-size:ir (partial abstract-ugen (assoc block-size-data :calculation-rate :ir)))
(def control-rate-data (assoc info-ugen-base :ugen-name "ControlRate"))
(def control-rate (partial abstract-ugen control-rate-data))
(def control-rate:ir (partial abstract-ugen (assoc control-rate-data :calculation-rate :ir)))
(def control-dur-data (assoc info-ugen-base :ugen-name "ControlDur"))
(def control-dur (partial abstract-ugen control-dur-data))
(def control-dur:ir (partial abstract-ugen (assoc control-dur-data :calculation-rate :ir)))
(def subsample-offset-data (assoc info-ugen-base :ugen-name "SubsampleOffset"))
(def subsample-offset (partial abstract-ugen subsample-offset-data))
(def subsample-offset:ir (partial abstract-ugen (assoc subsample-offset-data :calculation-rate :ir)))
(def num-output-buses-data (assoc info-ugen-base :ugen-name "NumOutputBuses"))
(def num-output-buses (partial abstract-ugen num-output-buses-data))
(def num-output-buses:ir (partial abstract-ugen (assoc num-output-buses-data :calculation-rate :ir)))
(def num-input-buses-data (assoc info-ugen-base :ugen-name "NumInputBuses"))
(def num-input-buses (partial abstract-ugen num-input-buses-data))
(def num-input-buses:ir (partial abstract-ugen (assoc num-input-buses-data :calculation-rate :ir)))
(def num-audio-buses-data (assoc info-ugen-base :ugen-name "NumAudioBuses"))
(def num-audio-buses (partial abstract-ugen num-audio-buses-data))
(def num-audio-buses:ir (partial abstract-ugen (assoc num-audio-buses-data :calculation-rate :ir)))
(def num-control-buses-data (assoc info-ugen-base :ugen-name "NumControlBuses"))
(def num-control-buses (partial abstract-ugen num-control-buses-data))
(def num-control-buses:ir (partial abstract-ugen (assoc num-control-buses-data :calculation-rate :ir)))
(def num-buffers-data (assoc info-ugen-base :ugen-name "NumBuffers"))
(def num-buffers (partial abstract-ugen num-buffers-data))
(def num-buffers:ir (partial abstract-ugen (assoc num-buffers-data :calculation-rate :ir)))
(def node-id-data (assoc info-ugen-base :ugen-name "NodeID"))
(def node-id (partial abstract-ugen node-id-data))
(def node-id:ir (partial abstract-ugen (assoc node-id-data :calculation-rate :ir)))
(def num-running-synths-data (assoc info-ugen-base :ugen-name "NodeID" :inputs [:kr :ir]))
(def num-running-synths (partial abstract-ugen num-running-synths-data))
(def num-running-synths:kr (partial abstract-ugen num-running-synths-data :calculation-rate :kr))
(def num-running-synths:ir (partial abstract-ugen num-running-synths-data :calculation-rate :ir))
(def buf-info-ugen-base {:rates [:kr :ir]
:inputs [:bufnum 0]
:num-outputs 1})
(def buf-sample-rate-data (assoc buf-info-ugen-base :ugen-name "BufSampleRate"))
(def buf-sample-rate (partial abstract-ugen buf-sample-rate-data))
(def buf-sample-rate:kr (partial abstract-ugen (assoc buf-sample-rate-data :calculation-rate :kr)))
(def buf-sample-rate:ir (partial abstract-ugen (assoc buf-sample-rate-data :calculation-rate :ir)))
(def buf-rate-scale-data (assoc buf-info-ugen-base :ugen-name "BufRateScale"))
(def buf-rate-scale (partial abstract-ugen buf-rate-scale-data))
(def buf-rate-scale:kr (partial abstract-ugen (assoc buf-rate-scale-data :calculation-rate :kr)))
(def buf-rate-scale:ir (partial abstract-ugen (assoc buf-rate-scale-data :calculation-rate :ir)))
(def buf-frames-data (assoc buf-info-ugen-base :ugen-name "BufFrames"))
(def buf-frames (partial abstract-ugen buf-frames-data))
(def buf-frames:kr (partial abstract-ugen (assoc buf-frames-data :calculation-rate :kr)))
(def buf-frames:ir (partial abstract-ugen (assoc buf-frames-data :calculation-rate :ir)))
(def buf-samples-data (assoc buf-info-ugen-base :ugen-name "BufSamples"))
(def buf-samples (partial abstract-ugen buf-samples-data))
(def buf-samples:kr (partial abstract-ugen (assoc buf-samples-data :calculation-rate :kr)))
(def buf-samples:ir (partial abstract-ugen (assoc buf-samples-data :calculation-rate :ir)))
(def buf-dur-data (assoc buf-info-ugen-base :ugen-name "BufDur"))
(def buf-dur (partial abstract-ugen buf-dur-data))
(def buf-dur:kr (partial abstract-ugen (assoc buf-dur-data :calculation-rate :kr)))
(def buf-dur:ir (partial abstract-ugen (assoc buf-dur-data :calculation-rate :ir)))
(def buf-channels-data (assoc buf-info-ugen-base :ugen-name "BufChannels"))
(def buf-channels (partial abstract-ugen buf-channels-data))
(def buf-channels:kr (partial abstract-ugen (assoc buf-channels-data :calculation-rate :kr)))
(def buf-channels:ir (partial abstract-ugen (assoc buf-channels-data :calculation-rate :ir)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Line
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def line-data {:ugen-name "Line"
:rates [:ar :kr]
:inputs [:start 0.0 :end 1.0 :dur 1.0 :done-action 0]
:num-outputs 1})
(def line (partial abstract-ugen line-data))
(def line:ar (partial abstract-ugen (assoc line-data :calculation-rate :ar)))
(def line:kr (partial abstract-ugen (assoc line-data :calculation-rate :kr)))
(def x-line-data {:ugen-name "XLine"
:rates [:ar :kr]
:inputs [:start 1.0 :end 2.0 :dur 1.0 :done-action 0]
:num-outputs 1})
(def x-line (partial abstract-ugen x-line-data))
(def x-line:ar (partial abstract-ugen (assoc x-line-data :calculation-rate :ar)))
(def x-line:kr (partial abstract-ugen (assoc x-line-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Noise
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def lf-noise-data {:rates [:ar :kr]
:inputs [:freq 500]
:num-outputs 1})
(def lf-noise-0 (partial abstract-ugen (assoc lf-noise-data :ugen-name "LFNoise0")))
(def lf-noise-0:ar (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise0"
:calculation-rate :ar)))
(def lf-noise-0:kr (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise0"
:calculation-rate :kr)))
(def lf-noise-1 (partial abstract-ugen (assoc lf-noise-data :ugen-name "LFNoise1")))
(def lf-noise-1:ar (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise1"
:calculation-rate :ar)))
(def lf-noise-1:kr (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise1"
:calculation-rate :kr)))
(def lf-noise-2 (partial abstract-ugen (assoc lf-noise-data :ugen-name "LFNoise2")))
(def lf-noise-2:ar (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise2"
:calculation-rate :ar)))
(def lf-noise-2:kr (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise2"
:calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Osc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def sin-osc-data {:ugen-name "SinOsc"
:rates [:ar :kr]
:inputs [:freq 440 :phase 0]
:num-outputs 1})
(def sin-osc (partial abstract-ugen sin-osc-data))
(def sin-osc:ar (partial abstract-ugen (assoc sin-osc-data :calculation-rate :ar)))
(def sin-osc:kr (partial abstract-ugen (assoc sin-osc-data :calculation-rate :kr)))
(def impulse-data {:ugen-name "Impulse"
:rates [:ar :kr]
:inputs [:freq 440 :phase 0]
:num-outputs 1})
(def impulse (partial abstract-ugen impulse-data))
(def impulse:ar (partial abstract-ugen (assoc impulse-data :calculation-rate :ar)))
(def impulse:kr (partial abstract-ugen (assoc impulse-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Pan
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def pan2-data {:ugen-name "Pan2"
:rates [:ar :kr]
:inputs [:in nil :pos 0 :level 1]
:num-outputs 2})
(def pan2 (partial abstract-ugen pan2-data))
(def pan2:ar (partial abstract-ugen (assoc pan2-data :calculation-rate :ar)))
(def pan2:kr (partial abstract-ugen (assoc pan2-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Trig
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def send-trig-data {:ugen-name "SendTrig"
:rates [:ar :kr]
:inputs [:in 0 :id 0 :value 0]
:num-outputs 0})
(def send-trig (partial abstract-ugen send-trig-data))
(def send-trig:ar (partial abstract-ugen (assoc send-trig-data :calculation-rate :ar)))
(def send-trig:kr (partial abstract-ugen (assoc send-trig-data :calculation-rate :kr)))
(def phasor-data {:ugen-name "Phasor"
:rates [:ar :kr]
:inputs [:trig 0 :rate 1 :start 0 :end 1 :reset-pos 0]
:num-outputs 1})
(def phasor (partial abstract-ugen phasor-data))
(def phasor:ar (partial abstract-ugen (assoc phasor-data :calculation-rate :ar)))
(def phasor:kr (partial abstract-ugen (assoc phasor-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Envelope
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def linen-data {:ugen-name "Linen"
:rates [:kr]
:inputs [:gate 1 :attack-time 0.01 :sus-level 1 :release-time 1.0 :done-action 0]
:num-outputs 1})
(def linen (partial abstract-ugen linen-data))
(def linen:kr (partial abstract-ugen (assoc linen-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Bela
;; WARNING -- these will only work on the Bela fork of SuperCollider
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def multiplex-analog-in-data {:ugen-name "MultiplexAnalogIn"
:rates [:ar :kr]
:inputs [:analog-pin 0 :mux-channel 0]
:num-outputs 1})
(def multiplex-analog-in (partial abstract-ugen multiplex-analog-in-data))
(def multiplex-analog-in:ar (partial abstract-ugen (assoc multiplex-analog-in-data :calculation-rate :ar)))
(def multiplex-analog-in:kr (partial abstract-ugen (assoc multiplex-analog-in-data :calculation-rate :kr)))
(def analog-in-data {:ugen-name "AnalogIn"
:rates [:ar :kr]
:inputs [:analog-pin 0]
:num-outputs 1})
(def analog-in (partial abstract-ugen analog-in-data))
(def analog-in:ar (partial abstract-ugen (assoc analog-in-data :calculation-rate :ar)))
(def analog-in:kr (partial abstract-ugen (assoc analog-in-data :calculation-rate :kr)))
(def analog-out-data {:ugen-name "AnalogOut"
:rates [:ar :kr]
:inputs [:analog-pin 0]
:num-outputs 0});;TODO test - reference implementation no-ops writeOutputSpecs, probably need something like that
(def analog-out (partial abstract-ugen analog-out-data))
(def analog-out:ar (partial abstract-ugen (assoc analog-out-data :calculation-rate :ar)))
(def analog-out:kr (partial abstract-ugen (assoc analog-out-data :calculation-rate :kr)))
(def digital-in-data {:ugen-name "DigitalIn"
:rates [:ar :kr]
:inputs [:digital-pin 0]
:num-outputs 1})
(def digital-in (partial abstract-ugen digital-in-data))
(def digital-in:ar (partial abstract-ugen (assoc digital-in-data :calculation-rate :ar)))
(def digital-in:kr (partial abstract-ugen (assoc digital-in-data :calculation-rate :kr)))
(def digital-out-data {:ugen-name "DigitalOut"
:rates [:ar :kr]
:inputs [:digital-pin 0]
:num-outputs 0});;TODO test - reference implementation no-ops writeOutputSpecs, probably need something like that
(def digital-out (partial abstract-ugen digital-out-data))
(def digital-out:ar (partial abstract-ugen (assoc digital-out-data :calculation-rate :ar)))
(def digital-out:kr (partial abstract-ugen (assoc digital-out-data :calculation-rate :kr)))
(def digital-io-data {:ugen-name "DigitalIO"
:rates [:ar :kr]
:inputs [:digital-pin 0 :output 0 :pin-mode 0]
:num-outputs 1})
(def digital-io (partial abstract-ugen digital-io-data))
(def digital-io:ar (partial abstract-ugen (assoc digital-io-data :calculation-rate :ar)))
(def digital-io:kr (partial abstract-ugen (assoc digital-io-data :calculation-rate :ar)))
| 113701 | (ns synchrotron.ugens
(:require [synchrotron.ugen :as ugen :refer [abstract-ugen]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Binary Ops
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def binary-op-ugen-data {:ugen-name "BinaryOpUGen"
:rates [:ar :kr :demand :ir]
:inputs [:a nil :b nil]
:num-outputs 1})
;;TODO infer calculation-rate from ugen inputs (but I'm not sure which rate should get preference if two different rates are given)
(def add (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 0)))
(def add:ar (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 0)))
(def add:kr (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :kr :special-index 0)))
(def sub (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 1)))
(def sub:ar (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 1)))
(def sub:kr (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :kr :special-index 1)))
(def mul (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 2)))
(def mul:ar (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 2)))
(def mul:kr (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :kr :special-index 2)))
(def div (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 4)));;float division
(def div:ar (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 4)));;float division
(def div:kr (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :kr :special-index 4)));;float division
(def eq (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 6)))
(def eq:ar (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 6)))
(def eq:kr (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :kr :special-index 6)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Buffer IO
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;num-channels is actually a concept of "MultiOutUgen" and so this doesn't work
(def buf-rd-data {:ugen-name "BufRd"
:rates [:ar :kr]
:inputs [:num-channels 1 :buf-num 0 :phase 0 :loop 0 :interpolation 2]
;;sclang has a variable called argsNamesInputsOffsets, which you can set to 2 to NOT send the first input to scsynth.
;;it's very confusing.
:treat-num-channels-as-input false
:num-outputs :variadic})
(def buf-rd (partial abstract-ugen buf-rd-data))
(def buf-rd:ar (partial abstract-ugen (assoc buf-rd-data :calculation-rate :ar)))
(def buf-rd:kr (partial abstract-ugen (assoc buf-rd-data :calculation-rate :kr)))
(def buf-wr-data {:ugen-name "BufWr"
:rates [:ar :kr]
:inputs [:input-array nil :buf-num 0 :phase 0 :loop 1]
:num-outputs 1})
(def buf-wr (partial abstract-ugen buf-wr-data))
(def buf-wr:ar (partial abstract-ugen (assoc buf-wr-data :calculation-rate :ar)))
(def buf-wr:kr (partial abstract-ugen (assoc buf-wr-data :calculation-rate :kr)))
(def record-buf-data {:ugen-name "RecordBuf"
:rates [:ar :kr]
;;TODO: would need to actually explode input-array out into multiple inputs to get this working with multi-channel buffers
:inputs [:buf-num 0 :offset 0 :rec-level 1 :pre-level 0 :run 1 :loop 1 :trigger 1 :done-action 0 :input-array nil]
:num-outputs 1})
(def record-buf (partial abstract-ugen record-buf-data))
(def record-buf:ar (partial abstract-ugen (assoc record-buf-data :calculation-rate :ar)))
(def record-buf:kr (partial abstract-ugen (assoc record-buf-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Delays
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def delay-n-data {:ugen-name "DelayN"
:rates [:ar :kr]
:inputs [:in 0 :max-delay-time 0.2 :delay-time 0.2]
:num-outputs 1})
(def delay-n (partial abstract-ugen delay-n-data))
(def delay-n:ar (partial abstract-ugen (assoc delay-n-data :calculation-rate :ar)))
(def delay-n:kr (partial abstract-ugen (assoc delay-n-data :calculation-rate :kr)))
(def comb-n-data {:ugen-name "CombN"
:rates [:ar :kr]
:inputs [:in 0 :max-delay-time 0.2 :delay-time 0.2 :decay-time 1]
:num-outputs 1})
(def comb-n (partial abstract-ugen comb-n-data))
(def comb-n:ar (partial abstract-ugen (assoc comb-n-data :calculation-rate :ar)))
(def comb-n:kr (partial abstract-ugen (assoc comb-n-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; IO
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def out-data {:ugen-name "Out"
:rates [:ar :kr]
:inputs [:bus 0 :channels-array nil]
:num-outputs 0})
(def out (partial abstract-ugen out-data))
(def out:ar (partial abstract-ugen (assoc out-data :calculation-rate :ar)))
(def out:kr (partial abstract-ugen (assoc out-data :calculation-rate :kr)))
(def replace-out-data {:ugen-name "ReplaceOut"
:rates [:ar :kr]
:inputs [:bus 0 :channels-array nil]
:num-outputs 0})
(def replace-out (partial abstract-ugen replace-out-data))
(def replace-out:ar (partial abstract-ugen (assoc replace-out-data :calculation-rate :ar)))
(def replace-out:kr (partial abstract-ugen (assoc replace-out-data :calculation-rate :kr)))
(def in-data {:ugen-name "In"
:rates [:ar :kr]
:inputs [:bus 0 :num-channels 1]
:num-outputs :variadic})
(def in (partial abstract-ugen in-data))
(def in:ar (partial abstract-ugen (assoc in-data :calculation-rate :ar)))
(def in:kr (partial abstract-ugen (assoc in-data :calcutaion-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Info
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def info-ugen-base {:rates [:ir]
:inputs nil
:num-outputs 1})
(def sample-rate-data (assoc info-ugen-base :ugen-name "SampleRate"))
(def sample-rate (partial abstract-ugen sample-rate-data))
(def sample-rate:ir (partial abstract-ugen (assoc sample-rate-data :calculation-rate :ir)))
(def sample-dur-data (assoc info-ugen-base :ugen-name "SampleDur"))
(def sample-dur (partial abstract-ugen sample-dur-data))
(def sample-dur:ir (partial abstract-ugen (assoc sample-dur-data :calculation-rate :ir)))
(def radians-per-sample-data (assoc info-ugen-base :ugen-name "RadiansPerSample"))
(def radians-per-sample (partial abstract-ugen radians-per-sample-data))
(def radians-per-sample:ir (partial abstract-ugen (assoc radians-per-sample-data :calculation-rate :ir)))
(def block-size-data (assoc info-ugen-base :ugen-name "BlockSize"))
(def block-size (partial abstract-ugen block-size-data))
(def block-size:ir (partial abstract-ugen (assoc block-size-data :calculation-rate :ir)))
(def control-rate-data (assoc info-ugen-base :ugen-name "ControlRate"))
(def control-rate (partial abstract-ugen control-rate-data))
(def control-rate:ir (partial abstract-ugen (assoc control-rate-data :calculation-rate :ir)))
(def control-dur-data (assoc info-ugen-base :ugen-name "ControlDur"))
(def control-dur (partial abstract-ugen control-dur-data))
(def control-dur:ir (partial abstract-ugen (assoc control-dur-data :calculation-rate :ir)))
(def subsample-offset-data (assoc info-ugen-base :ugen-name "SubsampleOffset"))
(def subsample-offset (partial abstract-ugen subsample-offset-data))
(def subsample-offset:ir (partial abstract-ugen (assoc subsample-offset-data :calculation-rate :ir)))
(def num-output-buses-data (assoc info-ugen-base :ugen-name "NumOutputBuses"))
(def num-output-buses (partial abstract-ugen num-output-buses-data))
(def num-output-buses:ir (partial abstract-ugen (assoc num-output-buses-data :calculation-rate :ir)))
(def num-input-buses-data (assoc info-ugen-base :ugen-name "NumInputBuses"))
(def num-input-buses (partial abstract-ugen num-input-buses-data))
(def num-input-buses:ir (partial abstract-ugen (assoc num-input-buses-data :calculation-rate :ir)))
(def num-audio-buses-data (assoc info-ugen-base :ugen-name "NumAudioBuses"))
(def num-audio-buses (partial abstract-ugen num-audio-buses-data))
(def num-audio-buses:ir (partial abstract-ugen (assoc num-audio-buses-data :calculation-rate :ir)))
(def num-control-buses-data (assoc info-ugen-base :ugen-name "NumControlBuses"))
(def num-control-buses (partial abstract-ugen num-control-buses-data))
(def num-control-buses:ir (partial abstract-ugen (assoc num-control-buses-data :calculation-rate :ir)))
(def num-buffers-data (assoc info-ugen-base :ugen-name "NumBuffers"))
(def num-buffers (partial abstract-ugen num-buffers-data))
(def num-buffers:ir (partial abstract-ugen (assoc num-buffers-data :calculation-rate :ir)))
(def node-id-data (assoc info-ugen-base :ugen-name "NodeID"))
(def node-id (partial abstract-ugen node-id-data))
(def node-id:ir (partial abstract-ugen (assoc node-id-data :calculation-rate :ir)))
(def num-running-synths-data (assoc info-ugen-base :ugen-name "NodeID" :inputs [:kr :ir]))
(def num-running-synths (partial abstract-ugen num-running-synths-data))
(def num-running-synths:kr (partial abstract-ugen num-running-synths-data :calculation-rate :kr))
(def num-running-synths:ir (partial abstract-ugen num-running-synths-data :calculation-rate :ir))
(def buf-info-ugen-base {:rates [:kr :ir]
:inputs [:bufnum 0]
:num-outputs 1})
(def buf-sample-rate-data (assoc buf-info-ugen-base :ugen-name "BufSampleRate"))
(def buf-sample-rate (partial abstract-ugen buf-sample-rate-data))
(def buf-sample-rate:kr (partial abstract-ugen (assoc buf-sample-rate-data :calculation-rate :kr)))
(def buf-sample-rate:ir (partial abstract-ugen (assoc buf-sample-rate-data :calculation-rate :ir)))
(def buf-rate-scale-data (assoc buf-info-ugen-base :ugen-name "BufRateScale"))
(def buf-rate-scale (partial abstract-ugen buf-rate-scale-data))
(def buf-rate-scale:kr (partial abstract-ugen (assoc buf-rate-scale-data :calculation-rate :kr)))
(def buf-rate-scale:ir (partial abstract-ugen (assoc buf-rate-scale-data :calculation-rate :ir)))
(def buf-frames-data (assoc buf-info-ugen-base :ugen-name "BufFrames"))
(def buf-frames (partial abstract-ugen buf-frames-data))
(def buf-frames:kr (partial abstract-ugen (assoc buf-frames-data :calculation-rate :kr)))
(def buf-frames:ir (partial abstract-ugen (assoc buf-frames-data :calculation-rate :ir)))
(def buf-samples-data (assoc buf-info-ugen-base :ugen-name "BufSamples"))
(def buf-samples (partial abstract-ugen buf-samples-data))
(def buf-samples:kr (partial abstract-ugen (assoc buf-samples-data :calculation-rate :kr)))
(def buf-samples:ir (partial abstract-ugen (assoc buf-samples-data :calculation-rate :ir)))
(def buf-dur-data (assoc buf-info-ugen-base :ugen-name "BufDur"))
(def buf-dur (partial abstract-ugen buf-dur-data))
(def buf-dur:kr (partial abstract-ugen (assoc buf-dur-data :calculation-rate :kr)))
(def buf-dur:ir (partial abstract-ugen (assoc buf-dur-data :calculation-rate :ir)))
(def buf-channels-data (assoc buf-info-ugen-base :ugen-name "BufChannels"))
(def buf-channels (partial abstract-ugen buf-channels-data))
(def buf-channels:kr (partial abstract-ugen (assoc buf-channels-data :calculation-rate :kr)))
(def buf-channels:ir (partial abstract-ugen (assoc buf-channels-data :calculation-rate :ir)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Line
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def line-data {:ugen-name "Line"
:rates [:ar :kr]
:inputs [:start 0.0 :end 1.0 :dur 1.0 :done-action 0]
:num-outputs 1})
(def line (partial abstract-ugen line-data))
(def line:ar (partial abstract-ugen (assoc line-data :calculation-rate :ar)))
(def line:kr (partial abstract-ugen (assoc line-data :calculation-rate :kr)))
(def x-line-data {:ugen-name "XLine"
:rates [:ar :kr]
:inputs [:start 1.0 :end 2.0 :dur 1.0 :done-action 0]
:num-outputs 1})
(def x-line (partial abstract-ugen x-line-data))
(def x-line:ar (partial abstract-ugen (assoc x-line-data :calculation-rate :ar)))
(def x-line:kr (partial abstract-ugen (assoc x-line-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Noise
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def lf-noise-data {:rates [:ar :kr]
:inputs [:freq 500]
:num-outputs 1})
(def lf-noise-0 (partial abstract-ugen (assoc lf-noise-data :ugen-name "LFNoise0")))
(def lf-noise-0:ar (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise0"
:calculation-rate :ar)))
(def lf-noise-0:kr (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise0"
:calculation-rate :kr)))
(def lf-noise-1 (partial abstract-ugen (assoc lf-noise-data :ugen-name "LFNoise1")))
(def lf-noise-1:ar (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise1"
:calculation-rate :ar)))
(def lf-noise-1:kr (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise1"
:calculation-rate :kr)))
(def lf-noise-2 (partial abstract-ugen (assoc lf-noise-data :ugen-name "LFNoise2")))
(def lf-noise-2:ar (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise2"
:calculation-rate :ar)))
(def lf-noise-2:kr (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise2"
:calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Osc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def sin-osc-data {:ugen-name "SinOsc"
:rates [:ar :kr]
:inputs [:freq 440 :phase 0]
:num-outputs 1})
(def sin-osc (partial abstract-ugen sin-osc-data))
(def sin-osc:ar (partial abstract-ugen (assoc sin-osc-data :calculation-rate :ar)))
(def sin-osc:kr (partial abstract-ugen (assoc sin-osc-data :calculation-rate :kr)))
(def impulse-data {:ugen-name "Impulse"
:rates [:ar :kr]
:inputs [:freq 440 :phase 0]
:num-outputs 1})
(def impulse (partial abstract-ugen impulse-data))
(def impulse:ar (partial abstract-ugen (assoc impulse-data :calculation-rate :ar)))
(def impulse:kr (partial abstract-ugen (assoc impulse-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Pan
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def pan2-data {:ugen-name "Pan2"
:rates [:ar :kr]
:inputs [:in nil :pos 0 :level 1]
:num-outputs 2})
(def pan2 (partial abstract-ugen pan2-data))
(def pan2:ar (partial abstract-ugen (assoc pan2-data :calculation-rate :ar)))
(def pan2:kr (partial abstract-ugen (assoc pan2-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Trig
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def send-trig-data {:ugen-name "SendTrig"
:rates [:ar :kr]
:inputs [:in 0 :id 0 :value 0]
:num-outputs 0})
(def send-trig (partial abstract-ugen send-trig-data))
(def send-trig:ar (partial abstract-ugen (assoc send-trig-data :calculation-rate :ar)))
(def send-trig:kr (partial abstract-ugen (assoc send-trig-data :calculation-rate :kr)))
(def phasor-data {:ugen-name "Phasor"
:rates [:ar :kr]
:inputs [:trig 0 :rate 1 :start 0 :end 1 :reset-pos 0]
:num-outputs 1})
(def phasor (partial abstract-ugen phasor-data))
(def phasor:ar (partial abstract-ugen (assoc phasor-data :calculation-rate :ar)))
(def phasor:kr (partial abstract-ugen (assoc phasor-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Envelope
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def linen-data {:ugen-name "<NAME>"
:rates [:kr]
:inputs [:gate 1 :attack-time 0.01 :sus-level 1 :release-time 1.0 :done-action 0]
:num-outputs 1})
(def linen (partial abstract-ugen linen-data))
(def linen:kr (partial abstract-ugen (assoc linen-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Bela
;; WARNING -- these will only work on the Bela fork of SuperCollider
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def multiplex-analog-in-data {:ugen-name "MultiplexAnalogIn"
:rates [:ar :kr]
:inputs [:analog-pin 0 :mux-channel 0]
:num-outputs 1})
(def multiplex-analog-in (partial abstract-ugen multiplex-analog-in-data))
(def multiplex-analog-in:ar (partial abstract-ugen (assoc multiplex-analog-in-data :calculation-rate :ar)))
(def multiplex-analog-in:kr (partial abstract-ugen (assoc multiplex-analog-in-data :calculation-rate :kr)))
(def analog-in-data {:ugen-name "AnalogIn"
:rates [:ar :kr]
:inputs [:analog-pin 0]
:num-outputs 1})
(def analog-in (partial abstract-ugen analog-in-data))
(def analog-in:ar (partial abstract-ugen (assoc analog-in-data :calculation-rate :ar)))
(def analog-in:kr (partial abstract-ugen (assoc analog-in-data :calculation-rate :kr)))
(def analog-out-data {:ugen-name "AnalogOut"
:rates [:ar :kr]
:inputs [:analog-pin 0]
:num-outputs 0});;TODO test - reference implementation no-ops writeOutputSpecs, probably need something like that
(def analog-out (partial abstract-ugen analog-out-data))
(def analog-out:ar (partial abstract-ugen (assoc analog-out-data :calculation-rate :ar)))
(def analog-out:kr (partial abstract-ugen (assoc analog-out-data :calculation-rate :kr)))
(def digital-in-data {:ugen-name "DigitalIn"
:rates [:ar :kr]
:inputs [:digital-pin 0]
:num-outputs 1})
(def digital-in (partial abstract-ugen digital-in-data))
(def digital-in:ar (partial abstract-ugen (assoc digital-in-data :calculation-rate :ar)))
(def digital-in:kr (partial abstract-ugen (assoc digital-in-data :calculation-rate :kr)))
(def digital-out-data {:ugen-name "DigitalOut"
:rates [:ar :kr]
:inputs [:digital-pin 0]
:num-outputs 0});;TODO test - reference implementation no-ops writeOutputSpecs, probably need something like that
(def digital-out (partial abstract-ugen digital-out-data))
(def digital-out:ar (partial abstract-ugen (assoc digital-out-data :calculation-rate :ar)))
(def digital-out:kr (partial abstract-ugen (assoc digital-out-data :calculation-rate :kr)))
(def digital-io-data {:ugen-name "DigitalIO"
:rates [:ar :kr]
:inputs [:digital-pin 0 :output 0 :pin-mode 0]
:num-outputs 1})
(def digital-io (partial abstract-ugen digital-io-data))
(def digital-io:ar (partial abstract-ugen (assoc digital-io-data :calculation-rate :ar)))
(def digital-io:kr (partial abstract-ugen (assoc digital-io-data :calculation-rate :ar)))
| true | (ns synchrotron.ugens
(:require [synchrotron.ugen :as ugen :refer [abstract-ugen]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Binary Ops
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def binary-op-ugen-data {:ugen-name "BinaryOpUGen"
:rates [:ar :kr :demand :ir]
:inputs [:a nil :b nil]
:num-outputs 1})
;;TODO infer calculation-rate from ugen inputs (but I'm not sure which rate should get preference if two different rates are given)
(def add (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 0)))
(def add:ar (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 0)))
(def add:kr (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :kr :special-index 0)))
(def sub (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 1)))
(def sub:ar (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 1)))
(def sub:kr (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :kr :special-index 1)))
(def mul (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 2)))
(def mul:ar (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 2)))
(def mul:kr (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :kr :special-index 2)))
(def div (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 4)));;float division
(def div:ar (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 4)));;float division
(def div:kr (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :kr :special-index 4)));;float division
(def eq (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 6)))
(def eq:ar (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :ar :special-index 6)))
(def eq:kr (partial abstract-ugen (assoc binary-op-ugen-data :calculation-rate :kr :special-index 6)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Buffer IO
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;num-channels is actually a concept of "MultiOutUgen" and so this doesn't work
(def buf-rd-data {:ugen-name "BufRd"
:rates [:ar :kr]
:inputs [:num-channels 1 :buf-num 0 :phase 0 :loop 0 :interpolation 2]
;;sclang has a variable called argsNamesInputsOffsets, which you can set to 2 to NOT send the first input to scsynth.
;;it's very confusing.
:treat-num-channels-as-input false
:num-outputs :variadic})
(def buf-rd (partial abstract-ugen buf-rd-data))
(def buf-rd:ar (partial abstract-ugen (assoc buf-rd-data :calculation-rate :ar)))
(def buf-rd:kr (partial abstract-ugen (assoc buf-rd-data :calculation-rate :kr)))
(def buf-wr-data {:ugen-name "BufWr"
:rates [:ar :kr]
:inputs [:input-array nil :buf-num 0 :phase 0 :loop 1]
:num-outputs 1})
(def buf-wr (partial abstract-ugen buf-wr-data))
(def buf-wr:ar (partial abstract-ugen (assoc buf-wr-data :calculation-rate :ar)))
(def buf-wr:kr (partial abstract-ugen (assoc buf-wr-data :calculation-rate :kr)))
(def record-buf-data {:ugen-name "RecordBuf"
:rates [:ar :kr]
;;TODO: would need to actually explode input-array out into multiple inputs to get this working with multi-channel buffers
:inputs [:buf-num 0 :offset 0 :rec-level 1 :pre-level 0 :run 1 :loop 1 :trigger 1 :done-action 0 :input-array nil]
:num-outputs 1})
(def record-buf (partial abstract-ugen record-buf-data))
(def record-buf:ar (partial abstract-ugen (assoc record-buf-data :calculation-rate :ar)))
(def record-buf:kr (partial abstract-ugen (assoc record-buf-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Delays
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def delay-n-data {:ugen-name "DelayN"
:rates [:ar :kr]
:inputs [:in 0 :max-delay-time 0.2 :delay-time 0.2]
:num-outputs 1})
(def delay-n (partial abstract-ugen delay-n-data))
(def delay-n:ar (partial abstract-ugen (assoc delay-n-data :calculation-rate :ar)))
(def delay-n:kr (partial abstract-ugen (assoc delay-n-data :calculation-rate :kr)))
(def comb-n-data {:ugen-name "CombN"
:rates [:ar :kr]
:inputs [:in 0 :max-delay-time 0.2 :delay-time 0.2 :decay-time 1]
:num-outputs 1})
(def comb-n (partial abstract-ugen comb-n-data))
(def comb-n:ar (partial abstract-ugen (assoc comb-n-data :calculation-rate :ar)))
(def comb-n:kr (partial abstract-ugen (assoc comb-n-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; IO
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def out-data {:ugen-name "Out"
:rates [:ar :kr]
:inputs [:bus 0 :channels-array nil]
:num-outputs 0})
(def out (partial abstract-ugen out-data))
(def out:ar (partial abstract-ugen (assoc out-data :calculation-rate :ar)))
(def out:kr (partial abstract-ugen (assoc out-data :calculation-rate :kr)))
(def replace-out-data {:ugen-name "ReplaceOut"
:rates [:ar :kr]
:inputs [:bus 0 :channels-array nil]
:num-outputs 0})
(def replace-out (partial abstract-ugen replace-out-data))
(def replace-out:ar (partial abstract-ugen (assoc replace-out-data :calculation-rate :ar)))
(def replace-out:kr (partial abstract-ugen (assoc replace-out-data :calculation-rate :kr)))
(def in-data {:ugen-name "In"
:rates [:ar :kr]
:inputs [:bus 0 :num-channels 1]
:num-outputs :variadic})
(def in (partial abstract-ugen in-data))
(def in:ar (partial abstract-ugen (assoc in-data :calculation-rate :ar)))
(def in:kr (partial abstract-ugen (assoc in-data :calcutaion-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Info
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def info-ugen-base {:rates [:ir]
:inputs nil
:num-outputs 1})
(def sample-rate-data (assoc info-ugen-base :ugen-name "SampleRate"))
(def sample-rate (partial abstract-ugen sample-rate-data))
(def sample-rate:ir (partial abstract-ugen (assoc sample-rate-data :calculation-rate :ir)))
(def sample-dur-data (assoc info-ugen-base :ugen-name "SampleDur"))
(def sample-dur (partial abstract-ugen sample-dur-data))
(def sample-dur:ir (partial abstract-ugen (assoc sample-dur-data :calculation-rate :ir)))
(def radians-per-sample-data (assoc info-ugen-base :ugen-name "RadiansPerSample"))
(def radians-per-sample (partial abstract-ugen radians-per-sample-data))
(def radians-per-sample:ir (partial abstract-ugen (assoc radians-per-sample-data :calculation-rate :ir)))
(def block-size-data (assoc info-ugen-base :ugen-name "BlockSize"))
(def block-size (partial abstract-ugen block-size-data))
(def block-size:ir (partial abstract-ugen (assoc block-size-data :calculation-rate :ir)))
(def control-rate-data (assoc info-ugen-base :ugen-name "ControlRate"))
(def control-rate (partial abstract-ugen control-rate-data))
(def control-rate:ir (partial abstract-ugen (assoc control-rate-data :calculation-rate :ir)))
(def control-dur-data (assoc info-ugen-base :ugen-name "ControlDur"))
(def control-dur (partial abstract-ugen control-dur-data))
(def control-dur:ir (partial abstract-ugen (assoc control-dur-data :calculation-rate :ir)))
(def subsample-offset-data (assoc info-ugen-base :ugen-name "SubsampleOffset"))
(def subsample-offset (partial abstract-ugen subsample-offset-data))
(def subsample-offset:ir (partial abstract-ugen (assoc subsample-offset-data :calculation-rate :ir)))
(def num-output-buses-data (assoc info-ugen-base :ugen-name "NumOutputBuses"))
(def num-output-buses (partial abstract-ugen num-output-buses-data))
(def num-output-buses:ir (partial abstract-ugen (assoc num-output-buses-data :calculation-rate :ir)))
(def num-input-buses-data (assoc info-ugen-base :ugen-name "NumInputBuses"))
(def num-input-buses (partial abstract-ugen num-input-buses-data))
(def num-input-buses:ir (partial abstract-ugen (assoc num-input-buses-data :calculation-rate :ir)))
(def num-audio-buses-data (assoc info-ugen-base :ugen-name "NumAudioBuses"))
(def num-audio-buses (partial abstract-ugen num-audio-buses-data))
(def num-audio-buses:ir (partial abstract-ugen (assoc num-audio-buses-data :calculation-rate :ir)))
(def num-control-buses-data (assoc info-ugen-base :ugen-name "NumControlBuses"))
(def num-control-buses (partial abstract-ugen num-control-buses-data))
(def num-control-buses:ir (partial abstract-ugen (assoc num-control-buses-data :calculation-rate :ir)))
(def num-buffers-data (assoc info-ugen-base :ugen-name "NumBuffers"))
(def num-buffers (partial abstract-ugen num-buffers-data))
(def num-buffers:ir (partial abstract-ugen (assoc num-buffers-data :calculation-rate :ir)))
(def node-id-data (assoc info-ugen-base :ugen-name "NodeID"))
(def node-id (partial abstract-ugen node-id-data))
(def node-id:ir (partial abstract-ugen (assoc node-id-data :calculation-rate :ir)))
(def num-running-synths-data (assoc info-ugen-base :ugen-name "NodeID" :inputs [:kr :ir]))
(def num-running-synths (partial abstract-ugen num-running-synths-data))
(def num-running-synths:kr (partial abstract-ugen num-running-synths-data :calculation-rate :kr))
(def num-running-synths:ir (partial abstract-ugen num-running-synths-data :calculation-rate :ir))
(def buf-info-ugen-base {:rates [:kr :ir]
:inputs [:bufnum 0]
:num-outputs 1})
(def buf-sample-rate-data (assoc buf-info-ugen-base :ugen-name "BufSampleRate"))
(def buf-sample-rate (partial abstract-ugen buf-sample-rate-data))
(def buf-sample-rate:kr (partial abstract-ugen (assoc buf-sample-rate-data :calculation-rate :kr)))
(def buf-sample-rate:ir (partial abstract-ugen (assoc buf-sample-rate-data :calculation-rate :ir)))
(def buf-rate-scale-data (assoc buf-info-ugen-base :ugen-name "BufRateScale"))
(def buf-rate-scale (partial abstract-ugen buf-rate-scale-data))
(def buf-rate-scale:kr (partial abstract-ugen (assoc buf-rate-scale-data :calculation-rate :kr)))
(def buf-rate-scale:ir (partial abstract-ugen (assoc buf-rate-scale-data :calculation-rate :ir)))
(def buf-frames-data (assoc buf-info-ugen-base :ugen-name "BufFrames"))
(def buf-frames (partial abstract-ugen buf-frames-data))
(def buf-frames:kr (partial abstract-ugen (assoc buf-frames-data :calculation-rate :kr)))
(def buf-frames:ir (partial abstract-ugen (assoc buf-frames-data :calculation-rate :ir)))
(def buf-samples-data (assoc buf-info-ugen-base :ugen-name "BufSamples"))
(def buf-samples (partial abstract-ugen buf-samples-data))
(def buf-samples:kr (partial abstract-ugen (assoc buf-samples-data :calculation-rate :kr)))
(def buf-samples:ir (partial abstract-ugen (assoc buf-samples-data :calculation-rate :ir)))
(def buf-dur-data (assoc buf-info-ugen-base :ugen-name "BufDur"))
(def buf-dur (partial abstract-ugen buf-dur-data))
(def buf-dur:kr (partial abstract-ugen (assoc buf-dur-data :calculation-rate :kr)))
(def buf-dur:ir (partial abstract-ugen (assoc buf-dur-data :calculation-rate :ir)))
(def buf-channels-data (assoc buf-info-ugen-base :ugen-name "BufChannels"))
(def buf-channels (partial abstract-ugen buf-channels-data))
(def buf-channels:kr (partial abstract-ugen (assoc buf-channels-data :calculation-rate :kr)))
(def buf-channels:ir (partial abstract-ugen (assoc buf-channels-data :calculation-rate :ir)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Line
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def line-data {:ugen-name "Line"
:rates [:ar :kr]
:inputs [:start 0.0 :end 1.0 :dur 1.0 :done-action 0]
:num-outputs 1})
(def line (partial abstract-ugen line-data))
(def line:ar (partial abstract-ugen (assoc line-data :calculation-rate :ar)))
(def line:kr (partial abstract-ugen (assoc line-data :calculation-rate :kr)))
(def x-line-data {:ugen-name "XLine"
:rates [:ar :kr]
:inputs [:start 1.0 :end 2.0 :dur 1.0 :done-action 0]
:num-outputs 1})
(def x-line (partial abstract-ugen x-line-data))
(def x-line:ar (partial abstract-ugen (assoc x-line-data :calculation-rate :ar)))
(def x-line:kr (partial abstract-ugen (assoc x-line-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Noise
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def lf-noise-data {:rates [:ar :kr]
:inputs [:freq 500]
:num-outputs 1})
(def lf-noise-0 (partial abstract-ugen (assoc lf-noise-data :ugen-name "LFNoise0")))
(def lf-noise-0:ar (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise0"
:calculation-rate :ar)))
(def lf-noise-0:kr (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise0"
:calculation-rate :kr)))
(def lf-noise-1 (partial abstract-ugen (assoc lf-noise-data :ugen-name "LFNoise1")))
(def lf-noise-1:ar (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise1"
:calculation-rate :ar)))
(def lf-noise-1:kr (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise1"
:calculation-rate :kr)))
(def lf-noise-2 (partial abstract-ugen (assoc lf-noise-data :ugen-name "LFNoise2")))
(def lf-noise-2:ar (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise2"
:calculation-rate :ar)))
(def lf-noise-2:kr (partial abstract-ugen (assoc lf-noise-data
:ugen-name "LFNoise2"
:calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Osc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def sin-osc-data {:ugen-name "SinOsc"
:rates [:ar :kr]
:inputs [:freq 440 :phase 0]
:num-outputs 1})
(def sin-osc (partial abstract-ugen sin-osc-data))
(def sin-osc:ar (partial abstract-ugen (assoc sin-osc-data :calculation-rate :ar)))
(def sin-osc:kr (partial abstract-ugen (assoc sin-osc-data :calculation-rate :kr)))
(def impulse-data {:ugen-name "Impulse"
:rates [:ar :kr]
:inputs [:freq 440 :phase 0]
:num-outputs 1})
(def impulse (partial abstract-ugen impulse-data))
(def impulse:ar (partial abstract-ugen (assoc impulse-data :calculation-rate :ar)))
(def impulse:kr (partial abstract-ugen (assoc impulse-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Pan
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def pan2-data {:ugen-name "Pan2"
:rates [:ar :kr]
:inputs [:in nil :pos 0 :level 1]
:num-outputs 2})
(def pan2 (partial abstract-ugen pan2-data))
(def pan2:ar (partial abstract-ugen (assoc pan2-data :calculation-rate :ar)))
(def pan2:kr (partial abstract-ugen (assoc pan2-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Trig
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def send-trig-data {:ugen-name "SendTrig"
:rates [:ar :kr]
:inputs [:in 0 :id 0 :value 0]
:num-outputs 0})
(def send-trig (partial abstract-ugen send-trig-data))
(def send-trig:ar (partial abstract-ugen (assoc send-trig-data :calculation-rate :ar)))
(def send-trig:kr (partial abstract-ugen (assoc send-trig-data :calculation-rate :kr)))
(def phasor-data {:ugen-name "Phasor"
:rates [:ar :kr]
:inputs [:trig 0 :rate 1 :start 0 :end 1 :reset-pos 0]
:num-outputs 1})
(def phasor (partial abstract-ugen phasor-data))
(def phasor:ar (partial abstract-ugen (assoc phasor-data :calculation-rate :ar)))
(def phasor:kr (partial abstract-ugen (assoc phasor-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Envelope
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def linen-data {:ugen-name "PI:NAME:<NAME>END_PI"
:rates [:kr]
:inputs [:gate 1 :attack-time 0.01 :sus-level 1 :release-time 1.0 :done-action 0]
:num-outputs 1})
(def linen (partial abstract-ugen linen-data))
(def linen:kr (partial abstract-ugen (assoc linen-data :calculation-rate :kr)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Bela
;; WARNING -- these will only work on the Bela fork of SuperCollider
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def multiplex-analog-in-data {:ugen-name "MultiplexAnalogIn"
:rates [:ar :kr]
:inputs [:analog-pin 0 :mux-channel 0]
:num-outputs 1})
(def multiplex-analog-in (partial abstract-ugen multiplex-analog-in-data))
(def multiplex-analog-in:ar (partial abstract-ugen (assoc multiplex-analog-in-data :calculation-rate :ar)))
(def multiplex-analog-in:kr (partial abstract-ugen (assoc multiplex-analog-in-data :calculation-rate :kr)))
(def analog-in-data {:ugen-name "AnalogIn"
:rates [:ar :kr]
:inputs [:analog-pin 0]
:num-outputs 1})
(def analog-in (partial abstract-ugen analog-in-data))
(def analog-in:ar (partial abstract-ugen (assoc analog-in-data :calculation-rate :ar)))
(def analog-in:kr (partial abstract-ugen (assoc analog-in-data :calculation-rate :kr)))
(def analog-out-data {:ugen-name "AnalogOut"
:rates [:ar :kr]
:inputs [:analog-pin 0]
:num-outputs 0});;TODO test - reference implementation no-ops writeOutputSpecs, probably need something like that
(def analog-out (partial abstract-ugen analog-out-data))
(def analog-out:ar (partial abstract-ugen (assoc analog-out-data :calculation-rate :ar)))
(def analog-out:kr (partial abstract-ugen (assoc analog-out-data :calculation-rate :kr)))
(def digital-in-data {:ugen-name "DigitalIn"
:rates [:ar :kr]
:inputs [:digital-pin 0]
:num-outputs 1})
(def digital-in (partial abstract-ugen digital-in-data))
(def digital-in:ar (partial abstract-ugen (assoc digital-in-data :calculation-rate :ar)))
(def digital-in:kr (partial abstract-ugen (assoc digital-in-data :calculation-rate :kr)))
(def digital-out-data {:ugen-name "DigitalOut"
:rates [:ar :kr]
:inputs [:digital-pin 0]
:num-outputs 0});;TODO test - reference implementation no-ops writeOutputSpecs, probably need something like that
(def digital-out (partial abstract-ugen digital-out-data))
(def digital-out:ar (partial abstract-ugen (assoc digital-out-data :calculation-rate :ar)))
(def digital-out:kr (partial abstract-ugen (assoc digital-out-data :calculation-rate :kr)))
(def digital-io-data {:ugen-name "DigitalIO"
:rates [:ar :kr]
:inputs [:digital-pin 0 :output 0 :pin-mode 0]
:num-outputs 1})
(def digital-io (partial abstract-ugen digital-io-data))
(def digital-io:ar (partial abstract-ugen (assoc digital-io-data :calculation-rate :ar)))
(def digital-io:kr (partial abstract-ugen (assoc digital-io-data :calculation-rate :ar)))
|
[
{
"context": ";; Copyright © 2015-2019 Esko Luontola\n;; This software is released under the Apache Lic",
"end": 38,
"score": 0.9998834729194641,
"start": 25,
"tag": "NAME",
"value": "Esko Luontola"
}
] | test/territory_bro/region_test.clj | JessRoberts/territory_assistant | 0 | ;; Copyright © 2015-2019 Esko Luontola
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.region-test
(:require [clojure.java.jdbc :as jdbc]
[clojure.test :refer :all]
[territory-bro.congregation :as congregation]
[territory-bro.db :as db]
[territory-bro.fixtures :refer [db-fixture event-actor-fixture]]
[territory-bro.projections :as projections]
[territory-bro.region :as region]
[territory-bro.testdata :as testdata]))
(use-fixtures :once (join-fixtures [db-fixture event-actor-fixture]))
(deftest regions-test
(db/with-db [conn {}]
(jdbc/db-set-rollback-only! conn)
(let [cong-id (congregation/create-congregation! conn "the name")
_ (congregation/use-schema conn (projections/current-state conn) cong-id)]
(testing "create & list congregation boundaries"
(let [id (region/create-congregation-boundary! conn testdata/wkt-multi-polygon)]
(is (= [{:region/id id
:region/location testdata/wkt-multi-polygon}]
(region/get-congregation-boundaries conn)))))
(testing "create & list subregions"
(let [id (region/create-subregion! conn "the name" testdata/wkt-multi-polygon)]
(is (= [{:region/id id
:region/name "the name"
:region/location testdata/wkt-multi-polygon}]
(region/get-subregions conn)))))
(testing "create & list card minimap viewports"
(let [id (region/create-card-minimap-viewport! conn testdata/wkt-polygon)]
(is (= [{:region/id id
:region/location testdata/wkt-polygon}]
(region/get-card-minimap-viewports conn))))))))
| 41734 | ;; Copyright © 2015-2019 <NAME>
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.region-test
(:require [clojure.java.jdbc :as jdbc]
[clojure.test :refer :all]
[territory-bro.congregation :as congregation]
[territory-bro.db :as db]
[territory-bro.fixtures :refer [db-fixture event-actor-fixture]]
[territory-bro.projections :as projections]
[territory-bro.region :as region]
[territory-bro.testdata :as testdata]))
(use-fixtures :once (join-fixtures [db-fixture event-actor-fixture]))
(deftest regions-test
(db/with-db [conn {}]
(jdbc/db-set-rollback-only! conn)
(let [cong-id (congregation/create-congregation! conn "the name")
_ (congregation/use-schema conn (projections/current-state conn) cong-id)]
(testing "create & list congregation boundaries"
(let [id (region/create-congregation-boundary! conn testdata/wkt-multi-polygon)]
(is (= [{:region/id id
:region/location testdata/wkt-multi-polygon}]
(region/get-congregation-boundaries conn)))))
(testing "create & list subregions"
(let [id (region/create-subregion! conn "the name" testdata/wkt-multi-polygon)]
(is (= [{:region/id id
:region/name "the name"
:region/location testdata/wkt-multi-polygon}]
(region/get-subregions conn)))))
(testing "create & list card minimap viewports"
(let [id (region/create-card-minimap-viewport! conn testdata/wkt-polygon)]
(is (= [{:region/id id
:region/location testdata/wkt-polygon}]
(region/get-card-minimap-viewports conn))))))))
| true | ;; Copyright © 2015-2019 PI:NAME:<NAME>END_PI
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.region-test
(:require [clojure.java.jdbc :as jdbc]
[clojure.test :refer :all]
[territory-bro.congregation :as congregation]
[territory-bro.db :as db]
[territory-bro.fixtures :refer [db-fixture event-actor-fixture]]
[territory-bro.projections :as projections]
[territory-bro.region :as region]
[territory-bro.testdata :as testdata]))
(use-fixtures :once (join-fixtures [db-fixture event-actor-fixture]))
(deftest regions-test
(db/with-db [conn {}]
(jdbc/db-set-rollback-only! conn)
(let [cong-id (congregation/create-congregation! conn "the name")
_ (congregation/use-schema conn (projections/current-state conn) cong-id)]
(testing "create & list congregation boundaries"
(let [id (region/create-congregation-boundary! conn testdata/wkt-multi-polygon)]
(is (= [{:region/id id
:region/location testdata/wkt-multi-polygon}]
(region/get-congregation-boundaries conn)))))
(testing "create & list subregions"
(let [id (region/create-subregion! conn "the name" testdata/wkt-multi-polygon)]
(is (= [{:region/id id
:region/name "the name"
:region/location testdata/wkt-multi-polygon}]
(region/get-subregions conn)))))
(testing "create & list card minimap viewports"
(let [id (region/create-card-minimap-viewport! conn testdata/wkt-polygon)]
(is (= [{:region/id id
:region/location testdata/wkt-polygon}]
(region/get-card-minimap-viewports conn))))))))
|
[
{
"context": " :else [ScriptLoader\n {:key \"igv\"\n :on-error #(swap! state assoc",
"end": 2497,
"score": 0.6432588696479797,
"start": 2494,
"tag": "KEY",
"value": "igv"
}
] | src/cljs/main/broadfcui/page/workspace/analysis/igv.cljs | ssyms/firecloud-ui | 26 | (ns broadfcui.page.workspace.analysis.igv
(:require
[dmohs.react :as react]
[clojure.string :as string]
[broadfcui.common :as common]
[broadfcui.common.style :as style]
[broadfcui.components.script-loader :refer [ScriptLoader]]
[broadfcui.endpoints :as endpoints]
[broadfcui.utils :as utils]
[broadfcui.utils.ajax :as ajax]
[broadfcui.utils.user :as user]
))
(defn- options [tracks token]
(clj->js
{
;; TODO: should we set hg38 as the default?
:genome "hg19"
:oauthToken token
:tracks (map-indexed (fn [index {:keys [track-url index-url]}]
(let [track-filename (first (string/split track-url #"[\#\?]")) ;; remove any querystring or hash
file-extension (string/lower-case (last (string/split track-filename ".")))]
{:name (str "Track " (inc index))
;; NB: IGV knows how to infer the track type from its url - but this doesn't work for sourceType="gcs"
;; so we will set the track type explicitly.
:sourceType "gcs"
:type (case file-extension
"bam" "alignment"
"bed" "annotation"
"vcf" "variant")
:url track-url
:indexURL (when (string? @index-url) @index-url)
;; NB: we'd love to skip setting indexURL and set indexed=true instead, which allows IGV to search
;; for indexes by naming convention, similar (but more lazily-loaded than) our track selector modal.
;; However, IGV's naming convention only supports (filename + ".bai"), e.g. my.bam.bai, whereas
;; sometimes we also want (filename.replace(".bam", ".bai")), e.g. my.bai.
;; So, we have keep our own track selector with index-finder.
}))
tracks)}))
(react/defc IGVContainer
{
:render
(fn [{:keys [this state]}]
(let [{:keys [deps-loaded? error?]} @state]
[:div {}
[:div {:ref "container" :data-test-id "igv-container"}]
(cond
error? (style/create-server-error-message "Unable to load IGV.")
:else [ScriptLoader
{:key "igv"
:on-error #(swap! state assoc :error? true)
:on-load #(do
(swap! state assoc :igv-loaded? true)
(this :refresh))
:path "https://igv.org/web/release/2.0.1/dist/igv.min.js"}])]))
:component-did-update
(fn [{:keys [props state prev-props this]}]
(when (and (not= (:tracks props) (:tracks prev-props)) (:igv-loaded? @state))
(this :refresh)))
:refresh
(fn [{:keys [props refs]}]
;; .createBrowser returns a Promise that we should be using to add/remove tracks. For now, we do it brute-force:
;; empty the container, then create a new IGV browser each time we change tracks.
(set! (.-innerHTML (@refs "container")) "")
(let [tracks (:tracks props)]
(if (empty? tracks)
;; if the user hasn't specified any tracks, render the IGV shell without getting a pet token
(.createBrowser js/igv (@refs "container") (options [] ""))
;; when the user DOES have tracks, get a token for the user's pet, then pass that token into the IGV tracks.
(endpoints/call-ajax-sam
{:endpoint (endpoints/pet-token (get-in props [:workspace-id :namespace]))
:payload common/storage-scopes
:headers ajax/content-type=json
:on-done
(fn [{:keys [success? raw-response]}]
(if success?
;; Sam endpoint returns a quoted token; dequote it.
(let [pet-token (utils/dequote raw-response)]
(.createBrowser js/igv (@refs "container") (options (:tracks props) pet-token)))
;; TODO: better error display
(js/alert raw-response)))}))))})
| 30164 | (ns broadfcui.page.workspace.analysis.igv
(:require
[dmohs.react :as react]
[clojure.string :as string]
[broadfcui.common :as common]
[broadfcui.common.style :as style]
[broadfcui.components.script-loader :refer [ScriptLoader]]
[broadfcui.endpoints :as endpoints]
[broadfcui.utils :as utils]
[broadfcui.utils.ajax :as ajax]
[broadfcui.utils.user :as user]
))
(defn- options [tracks token]
(clj->js
{
;; TODO: should we set hg38 as the default?
:genome "hg19"
:oauthToken token
:tracks (map-indexed (fn [index {:keys [track-url index-url]}]
(let [track-filename (first (string/split track-url #"[\#\?]")) ;; remove any querystring or hash
file-extension (string/lower-case (last (string/split track-filename ".")))]
{:name (str "Track " (inc index))
;; NB: IGV knows how to infer the track type from its url - but this doesn't work for sourceType="gcs"
;; so we will set the track type explicitly.
:sourceType "gcs"
:type (case file-extension
"bam" "alignment"
"bed" "annotation"
"vcf" "variant")
:url track-url
:indexURL (when (string? @index-url) @index-url)
;; NB: we'd love to skip setting indexURL and set indexed=true instead, which allows IGV to search
;; for indexes by naming convention, similar (but more lazily-loaded than) our track selector modal.
;; However, IGV's naming convention only supports (filename + ".bai"), e.g. my.bam.bai, whereas
;; sometimes we also want (filename.replace(".bam", ".bai")), e.g. my.bai.
;; So, we have keep our own track selector with index-finder.
}))
tracks)}))
(react/defc IGVContainer
{
:render
(fn [{:keys [this state]}]
(let [{:keys [deps-loaded? error?]} @state]
[:div {}
[:div {:ref "container" :data-test-id "igv-container"}]
(cond
error? (style/create-server-error-message "Unable to load IGV.")
:else [ScriptLoader
{:key "<KEY>"
:on-error #(swap! state assoc :error? true)
:on-load #(do
(swap! state assoc :igv-loaded? true)
(this :refresh))
:path "https://igv.org/web/release/2.0.1/dist/igv.min.js"}])]))
:component-did-update
(fn [{:keys [props state prev-props this]}]
(when (and (not= (:tracks props) (:tracks prev-props)) (:igv-loaded? @state))
(this :refresh)))
:refresh
(fn [{:keys [props refs]}]
;; .createBrowser returns a Promise that we should be using to add/remove tracks. For now, we do it brute-force:
;; empty the container, then create a new IGV browser each time we change tracks.
(set! (.-innerHTML (@refs "container")) "")
(let [tracks (:tracks props)]
(if (empty? tracks)
;; if the user hasn't specified any tracks, render the IGV shell without getting a pet token
(.createBrowser js/igv (@refs "container") (options [] ""))
;; when the user DOES have tracks, get a token for the user's pet, then pass that token into the IGV tracks.
(endpoints/call-ajax-sam
{:endpoint (endpoints/pet-token (get-in props [:workspace-id :namespace]))
:payload common/storage-scopes
:headers ajax/content-type=json
:on-done
(fn [{:keys [success? raw-response]}]
(if success?
;; Sam endpoint returns a quoted token; dequote it.
(let [pet-token (utils/dequote raw-response)]
(.createBrowser js/igv (@refs "container") (options (:tracks props) pet-token)))
;; TODO: better error display
(js/alert raw-response)))}))))})
| true | (ns broadfcui.page.workspace.analysis.igv
(:require
[dmohs.react :as react]
[clojure.string :as string]
[broadfcui.common :as common]
[broadfcui.common.style :as style]
[broadfcui.components.script-loader :refer [ScriptLoader]]
[broadfcui.endpoints :as endpoints]
[broadfcui.utils :as utils]
[broadfcui.utils.ajax :as ajax]
[broadfcui.utils.user :as user]
))
(defn- options [tracks token]
(clj->js
{
;; TODO: should we set hg38 as the default?
:genome "hg19"
:oauthToken token
:tracks (map-indexed (fn [index {:keys [track-url index-url]}]
(let [track-filename (first (string/split track-url #"[\#\?]")) ;; remove any querystring or hash
file-extension (string/lower-case (last (string/split track-filename ".")))]
{:name (str "Track " (inc index))
;; NB: IGV knows how to infer the track type from its url - but this doesn't work for sourceType="gcs"
;; so we will set the track type explicitly.
:sourceType "gcs"
:type (case file-extension
"bam" "alignment"
"bed" "annotation"
"vcf" "variant")
:url track-url
:indexURL (when (string? @index-url) @index-url)
;; NB: we'd love to skip setting indexURL and set indexed=true instead, which allows IGV to search
;; for indexes by naming convention, similar (but more lazily-loaded than) our track selector modal.
;; However, IGV's naming convention only supports (filename + ".bai"), e.g. my.bam.bai, whereas
;; sometimes we also want (filename.replace(".bam", ".bai")), e.g. my.bai.
;; So, we have keep our own track selector with index-finder.
}))
tracks)}))
(react/defc IGVContainer
{
:render
(fn [{:keys [this state]}]
(let [{:keys [deps-loaded? error?]} @state]
[:div {}
[:div {:ref "container" :data-test-id "igv-container"}]
(cond
error? (style/create-server-error-message "Unable to load IGV.")
:else [ScriptLoader
{:key "PI:KEY:<KEY>END_PI"
:on-error #(swap! state assoc :error? true)
:on-load #(do
(swap! state assoc :igv-loaded? true)
(this :refresh))
:path "https://igv.org/web/release/2.0.1/dist/igv.min.js"}])]))
:component-did-update
(fn [{:keys [props state prev-props this]}]
(when (and (not= (:tracks props) (:tracks prev-props)) (:igv-loaded? @state))
(this :refresh)))
:refresh
(fn [{:keys [props refs]}]
;; .createBrowser returns a Promise that we should be using to add/remove tracks. For now, we do it brute-force:
;; empty the container, then create a new IGV browser each time we change tracks.
(set! (.-innerHTML (@refs "container")) "")
(let [tracks (:tracks props)]
(if (empty? tracks)
;; if the user hasn't specified any tracks, render the IGV shell without getting a pet token
(.createBrowser js/igv (@refs "container") (options [] ""))
;; when the user DOES have tracks, get a token for the user's pet, then pass that token into the IGV tracks.
(endpoints/call-ajax-sam
{:endpoint (endpoints/pet-token (get-in props [:workspace-id :namespace]))
:payload common/storage-scopes
:headers ajax/content-type=json
:on-done
(fn [{:keys [success? raw-response]}]
(if success?
;; Sam endpoint returns a quoted token; dequote it.
(let [pet-token (utils/dequote raw-response)]
(.createBrowser js/igv (@refs "container") (options (:tracks props) pet-token)))
;; TODO: better error display
(js/alert raw-response)))}))))})
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.999812662601471,
"start": 96,
"tag": "NAME",
"value": "Ragnar Svensson"
},
{
"context": "-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold License version 1.0 ",
"end": 129,
"score": 0.9998272061347961,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
},
{
"context": "uffer (->pos-4f-uv-2f 2)\n vertex-1 [100.0 101.0 102.0 103.0 150.0 151.0]\n vertex-2 ",
"end": 3389,
"score": 0.5915542840957642,
"start": 3388,
"tag": "IP_ADDRESS",
"value": "0"
},
{
"context": " (->pos-4f-uv-2f 2)\n vertex-1 [100.0 101.0 102.0 103.0 150.0 151.0]\n vertex-2 [2",
"end": 3397,
"score": 0.7716546654701233,
"start": 3393,
"tag": "IP_ADDRESS",
"value": "01.0"
},
{
"context": "103.0 150.0 151.0]\n vertex-2 [200.0 201.0 202.0 203.0 250.0 251.0]]\n (apply pos-4f-uv-2",
"end": 3455,
"score": 0.6807080507278442,
"start": 3454,
"tag": "IP_ADDRESS",
"value": "1"
}
] | editor/test/editor/gl/vertex2_test.clj | cmarincia/defold | 0 | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 Ragnar Svensson, Christian Murray
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.gl.vertex2-test
(:require [clojure.test :refer :all]
[support.test-support :refer [array=]]
[editor.buffers :as b]
[editor.gl.vertex2 :as v])
(:import [java.nio ByteBuffer]
[com.google.protobuf ByteString]
[editor.gl.vertex2 VertexBuffer]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(defn- contents-of ^bytes
[^VertexBuffer vb]
(let [bb (.asReadOnlyBuffer ^ByteBuffer (.buf vb))
arr (byte-array (.limit bb))]
(.rewind bb)
(.get bb arr)
arr))
(defn- print-buffer
[b cols]
(let [fmt (clojure.string/join " " (repeat cols "%02X "))
rows (partition cols (seq (contents-of b)))]
(doseq [r rows]
(println (apply format fmt r)))))
(v/defvertex pos-1b
(vec1.byte position))
(v/defvertex pos-2b
(vec2.byte position))
(v/defvertex pos-2s
(vec2.short position))
(deftest vertex-contains-correct-data
(let [vertex-buffer (->pos-1b 1)]
(pos-1b-put! vertex-buffer 42)
(testing "what goes in comes out"
(is (= 1 (count vertex-buffer)))
(is (array= (byte-array [42])
(contents-of vertex-buffer))))
(testing "once flipped, the data is still there"
(let [final (v/flip! vertex-buffer)]
(is (= 1 (count final)))
(is (array= (byte-array [42])
(contents-of final)))))))
(defn- laid-out-as [def into-seq expected-vec]
(let [ctor (symbol (str "->" (:name def)))
dims (reduce + (map :components (:attributes def)))
buf ((ns-resolve 'editor.gl.vertex2-test ctor) (/ (count into-seq) ^long dims))
put! (ns-resolve 'editor.gl.vertex2-test (symbol (str (:name def) "-put!")))]
(doseq [x (partition dims into-seq)]
(apply put! buf x))
(array= (byte-array expected-vec) (contents-of buf))))
(deftest vertex-constructor
(is (thrown? AssertionError (->pos-1b 1 :invalid-usage))))
(deftest memory-layouts
(is (laid-out-as pos-1b (range 10)
[0 1 2 3 4 5 6 7 8 9]))
(is (laid-out-as pos-2b (range 20)
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]))
(is (laid-out-as pos-2s (range 20)
[0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 10 0 11 0 12 0 13 0 14 0 15 0 16 0 17 0 18 0 19 0])))
(deftest attributes-compiled-correctly
(is (= [{:components 1, :type :byte, :name "position", :normalized? false}] (:attributes pos-1b))))
(v/defvertex pos-4f-uv-2f
(vec4.float position)
(vec2.float texcoord))
(deftest two-vertex-contains-correct-data
(let [vertex-buffer (->pos-4f-uv-2f 2)
vertex-1 [100.0 101.0 102.0 103.0 150.0 151.0]
vertex-2 [200.0 201.0 202.0 203.0 250.0 251.0]]
(apply pos-4f-uv-2f-put! vertex-buffer vertex-1)
(is (= 1 (count vertex-buffer)))
(apply pos-4f-uv-2f-put! vertex-buffer vertex-2)
(is (= 2 (count vertex-buffer)))))
| 33129 | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 <NAME>, <NAME>
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.gl.vertex2-test
(:require [clojure.test :refer :all]
[support.test-support :refer [array=]]
[editor.buffers :as b]
[editor.gl.vertex2 :as v])
(:import [java.nio ByteBuffer]
[com.google.protobuf ByteString]
[editor.gl.vertex2 VertexBuffer]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(defn- contents-of ^bytes
[^VertexBuffer vb]
(let [bb (.asReadOnlyBuffer ^ByteBuffer (.buf vb))
arr (byte-array (.limit bb))]
(.rewind bb)
(.get bb arr)
arr))
(defn- print-buffer
[b cols]
(let [fmt (clojure.string/join " " (repeat cols "%02X "))
rows (partition cols (seq (contents-of b)))]
(doseq [r rows]
(println (apply format fmt r)))))
(v/defvertex pos-1b
(vec1.byte position))
(v/defvertex pos-2b
(vec2.byte position))
(v/defvertex pos-2s
(vec2.short position))
(deftest vertex-contains-correct-data
(let [vertex-buffer (->pos-1b 1)]
(pos-1b-put! vertex-buffer 42)
(testing "what goes in comes out"
(is (= 1 (count vertex-buffer)))
(is (array= (byte-array [42])
(contents-of vertex-buffer))))
(testing "once flipped, the data is still there"
(let [final (v/flip! vertex-buffer)]
(is (= 1 (count final)))
(is (array= (byte-array [42])
(contents-of final)))))))
(defn- laid-out-as [def into-seq expected-vec]
(let [ctor (symbol (str "->" (:name def)))
dims (reduce + (map :components (:attributes def)))
buf ((ns-resolve 'editor.gl.vertex2-test ctor) (/ (count into-seq) ^long dims))
put! (ns-resolve 'editor.gl.vertex2-test (symbol (str (:name def) "-put!")))]
(doseq [x (partition dims into-seq)]
(apply put! buf x))
(array= (byte-array expected-vec) (contents-of buf))))
(deftest vertex-constructor
(is (thrown? AssertionError (->pos-1b 1 :invalid-usage))))
(deftest memory-layouts
(is (laid-out-as pos-1b (range 10)
[0 1 2 3 4 5 6 7 8 9]))
(is (laid-out-as pos-2b (range 20)
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]))
(is (laid-out-as pos-2s (range 20)
[0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 10 0 11 0 12 0 13 0 14 0 15 0 16 0 17 0 18 0 19 0])))
(deftest attributes-compiled-correctly
(is (= [{:components 1, :type :byte, :name "position", :normalized? false}] (:attributes pos-1b))))
(v/defvertex pos-4f-uv-2f
(vec4.float position)
(vec2.float texcoord))
(deftest two-vertex-contains-correct-data
(let [vertex-buffer (->pos-4f-uv-2f 2)
vertex-1 [100.0 101.0 102.0 103.0 150.0 151.0]
vertex-2 [200.0 201.0 202.0 203.0 250.0 251.0]]
(apply pos-4f-uv-2f-put! vertex-buffer vertex-1)
(is (= 1 (count vertex-buffer)))
(apply pos-4f-uv-2f-put! vertex-buffer vertex-2)
(is (= 2 (count vertex-buffer)))))
| true | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.gl.vertex2-test
(:require [clojure.test :refer :all]
[support.test-support :refer [array=]]
[editor.buffers :as b]
[editor.gl.vertex2 :as v])
(:import [java.nio ByteBuffer]
[com.google.protobuf ByteString]
[editor.gl.vertex2 VertexBuffer]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(defn- contents-of ^bytes
[^VertexBuffer vb]
(let [bb (.asReadOnlyBuffer ^ByteBuffer (.buf vb))
arr (byte-array (.limit bb))]
(.rewind bb)
(.get bb arr)
arr))
(defn- print-buffer
[b cols]
(let [fmt (clojure.string/join " " (repeat cols "%02X "))
rows (partition cols (seq (contents-of b)))]
(doseq [r rows]
(println (apply format fmt r)))))
(v/defvertex pos-1b
(vec1.byte position))
(v/defvertex pos-2b
(vec2.byte position))
(v/defvertex pos-2s
(vec2.short position))
(deftest vertex-contains-correct-data
(let [vertex-buffer (->pos-1b 1)]
(pos-1b-put! vertex-buffer 42)
(testing "what goes in comes out"
(is (= 1 (count vertex-buffer)))
(is (array= (byte-array [42])
(contents-of vertex-buffer))))
(testing "once flipped, the data is still there"
(let [final (v/flip! vertex-buffer)]
(is (= 1 (count final)))
(is (array= (byte-array [42])
(contents-of final)))))))
(defn- laid-out-as [def into-seq expected-vec]
(let [ctor (symbol (str "->" (:name def)))
dims (reduce + (map :components (:attributes def)))
buf ((ns-resolve 'editor.gl.vertex2-test ctor) (/ (count into-seq) ^long dims))
put! (ns-resolve 'editor.gl.vertex2-test (symbol (str (:name def) "-put!")))]
(doseq [x (partition dims into-seq)]
(apply put! buf x))
(array= (byte-array expected-vec) (contents-of buf))))
(deftest vertex-constructor
(is (thrown? AssertionError (->pos-1b 1 :invalid-usage))))
(deftest memory-layouts
(is (laid-out-as pos-1b (range 10)
[0 1 2 3 4 5 6 7 8 9]))
(is (laid-out-as pos-2b (range 20)
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]))
(is (laid-out-as pos-2s (range 20)
[0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 10 0 11 0 12 0 13 0 14 0 15 0 16 0 17 0 18 0 19 0])))
(deftest attributes-compiled-correctly
(is (= [{:components 1, :type :byte, :name "position", :normalized? false}] (:attributes pos-1b))))
(v/defvertex pos-4f-uv-2f
(vec4.float position)
(vec2.float texcoord))
(deftest two-vertex-contains-correct-data
(let [vertex-buffer (->pos-4f-uv-2f 2)
vertex-1 [100.0 101.0 102.0 103.0 150.0 151.0]
vertex-2 [200.0 201.0 202.0 203.0 250.0 251.0]]
(apply pos-4f-uv-2f-put! vertex-buffer vertex-1)
(is (= 1 (count vertex-buffer)))
(apply pos-4f-uv-2f-put! vertex-buffer vertex-2)
(is (= 2 (count vertex-buffer)))))
|
[
{
"context": "inds the invoice for the given id\"\n (let [key \"foo/bar.pdf\"\n {id :id} (inv/create {:storage-key key",
"end": 1303,
"score": 0.9589325785636902,
"start": 1292,
"tag": "KEY",
"value": "foo/bar.pdf"
},
{
"context": " after the attachment is uploaded\"\n (let [key \"foo/bar.pdf\"\n {id :id} (inv/create {:storage-key key",
"end": 1690,
"score": 0.9602185487747192,
"start": 1679,
"tag": "KEY",
"value": "foo/bar.pdf"
},
{
"context": "g (org/store {:name \"filenso\"})\n names [\"Flipkart\" \"Harvest\" \"Cognitect\"]]\n (doall (map #(inv/",
"end": 2030,
"score": 0.5807803273200989,
"start": 2022,
"tag": "NAME",
"value": "Flipkart"
},
{
"context": "date-invoice\n (let [{id :id} (inv/create {:name \"Name\"})]\n (testing \"changes the requested attrs and",
"end": 3347,
"score": 0.9752713441848755,
"start": 3343,
"tag": "NAME",
"value": "Name"
},
{
"context": " inv/states)\n _ (inv/update id {:name \"New Name\"})\n {:keys [name status]} (inv/lookup ",
"end": 3511,
"score": 0.8267127275466919,
"start": 3503,
"tag": "NAME",
"value": "New Name"
},
{
"context": "me status]} (inv/lookup id)]\n (is (= name \"New Name\"))\n (is (= status e-status))))))\n\n(de",
"end": 3590,
"score": 0.9157480001449585,
"start": 3587,
"tag": "NAME",
"value": "New"
},
{
"context": " it again\"\n (let [{id :id} (inv/create {:name \"Deleter Deleteson\"})\n before-removal (inv/lookup id)\n ",
"end": 3802,
"score": 0.9936941862106323,
"start": 3785,
"tag": "NAME",
"value": "Deleter Deleteson"
},
{
"context": " :organization-name \"filenso\"}) :id)\n result3 (dissoc (inv/next-and",
"end": 5229,
"score": 0.9988767504692078,
"start": 5222,
"tag": "NAME",
"value": "filenso"
}
] | test/kulu_backend/invoices/model_test.clj | vkrmis/kulu-backend | 3 | (ns kulu-backend.invoices.model-test
(:require [clojure.test :refer :all]
[conjure.core :refer :all]
[kulu-backend.db :as db]
[kulu-backend.invoices.messaging :as inv-msg]
[kulu-backend.invoices.model :as inv]
[kulu-backend.organizations.model :as org]
[kulu-backend.invoices.search :as inv-search]
[kulu-backend.test-helper :refer :all]
[kulu-backend.config :as cfg]))
(use-fixtures :each isolate-db)
(use-fixtures :once set-test-env)
(deftest create-invoice
(testing "creates an invoice record"
(let [count-before (inv/size {})
inv (inv/create {:name "foobar"})]
(is (= (+ 1 count-before)
(inv/size inv)))))
(testing "generates an id and persist the invoice"
(let [expected-name "Flipkart"
{:keys [id name]} (inv/create {:name expected-name})]
(is ((comp not empty?) (str id)))
(is (= expected-name name))))
(testing "newly created invoice should be in uploaded state"
(let [n "Flipkart"
expected-state (:submitted inv/states)
{:keys [id status]} (inv/create {:name n})]
(is (= status expected-state)))))
(deftest lookup-invoice
(testing "finds the invoice for the given id"
(let [key "foo/bar.pdf"
{id :id} (inv/create {:storage-key key})]
(is (= key (:storage-key (inv/lookup id))))))
(testing "returns nil if there is invoice for the given id"
(let [non-existent-id #uuid "fb857379-1b66-4499-b705-08ec68601c6c"]
(is (nil? (inv/lookup non-existent-id)))))
(testing "adds the attachment URL after the attachment is uploaded"
(let [key "foo/bar.pdf"
{id :id} (inv/create {:storage-key key})
_ (inv/update id {:name "Invoice #1"})
attachment-url (:attachment-url (inv/lookup id))]
(is ((comp not nil?) attachment-url)))))
(deftest get-invoices
(testing "fetches all the invoices"
(let [org (org/store {:name "filenso"})
names ["Flipkart" "Harvest" "Cognitect"]]
(doall (map #(inv/create {:name %1 :organization-name "filenso"})
names))
(let [result-names (map :name (inv/all {:organization-name "filenso"}))]
(is (= (sort names)
(sort result-names)))))))
(deftest get-invoices-pagination
(testing "paginates the results"
(let [org (org/store {:name "filenso"})]
(doseq [d (range 1 9)]
(->> d
(format "%02d")
(str "2014-08-")
(java.sql.Date/valueOf)
(hash-map :organization-name "filenso" :name (str d) :date)
(inv/create)))
(let [per-page 3
page-1-names (map :name (inv/all {:page 1 :per-page per-page :organization-name "filenso"}))
page-2-names (map :name (inv/all {:page 2 :per-page per-page :organization-name "filenso"}))
page-3-names (map :name (inv/all {:page 3 :per-page per-page :organization-name "filenso"}))
page-4-names (map :name (inv/all {:page 4 :per-page per-page :organization-name "filenso"}))]
(is (= (map str [8 7 6]) page-1-names))
(is (= (map str [5 4 3]) page-2-names))
(is (= (map str [2 1]) page-3-names))
(is (= [] page-4-names))))))
(deftest update-invoice
(let [{id :id} (inv/create {:name "Name"})]
(testing "changes the requested attrs and status of the invoice"
(let [e-status (:submitted inv/states)
_ (inv/update id {:name "New Name"})
{:keys [name status]} (inv/lookup id)]
(is (= name "New Name"))
(is (= status e-status))))))
(deftest delete-invoice
(testing "create invoice, look for it, delete it, make sure we dont find it again"
(let [{id :id} (inv/create {:name "Deleter Deleteson"})
before-removal (inv/lookup id)
_ (inv/delete! id)
after-removal (inv/lookup id)]
(is (not (nil? id)))
(is (not (= before-removal after-removal)))
(is (map? before-removal))
(is (nil? after-removal)))))
(deftest next-and-prev-invoice
(testing "find the next and prev invoices for a given invoice within an organizations"
(let [{org1-id :id} (org/store {:name "filenso"})
{org2-id :id} (org/store {:name "flipcar"})
{inv1-id :id} (inv/create {:organization-name "flipcar"})
{inv2-id :id} (inv/create {:organization-name "filenso"})
{inv3-id :id} (inv/create {:organization-name "flipcar"})
{inv4-id :id} (inv/create {:organization-name "filenso"})
{inv5-id :id} (inv/create {:organization-name "flipcar"})
{inv6-id :id} (inv/create {:organization-name "filenso"})]
(let [result1 (dissoc (inv/next-and-prev-invoices inv1-id {:order "created_at"
:direction "desc"
:organization-name "flipcar"}) :id)
result2 (dissoc (inv/next-and-prev-invoices inv2-id {:order "created_at"
:direction "desc"
:organization-name "filenso"}) :id)
result3 (dissoc (inv/next-and-prev-invoices inv3-id {:order "created_at"
:direction "desc"
:organization-name "flipcar"}) :id)
result4 (dissoc (inv/next-and-prev-invoices inv4-id {:order "created_at"
:direction "desc"
:organization-name "filenso"}) :id)]
(is (= {:next-item-id nil :prev-item-id inv3-id} result1))
(is (= {:next-item-id nil :prev-item-id inv4-id} result2))
(is (= {:next-item-id inv1-id :prev-item-id inv5-id} result3))
(is (= {:next-item-id inv2-id :prev-item-id inv6-id} result4))))))
| 40737 | (ns kulu-backend.invoices.model-test
(:require [clojure.test :refer :all]
[conjure.core :refer :all]
[kulu-backend.db :as db]
[kulu-backend.invoices.messaging :as inv-msg]
[kulu-backend.invoices.model :as inv]
[kulu-backend.organizations.model :as org]
[kulu-backend.invoices.search :as inv-search]
[kulu-backend.test-helper :refer :all]
[kulu-backend.config :as cfg]))
(use-fixtures :each isolate-db)
(use-fixtures :once set-test-env)
(deftest create-invoice
(testing "creates an invoice record"
(let [count-before (inv/size {})
inv (inv/create {:name "foobar"})]
(is (= (+ 1 count-before)
(inv/size inv)))))
(testing "generates an id and persist the invoice"
(let [expected-name "Flipkart"
{:keys [id name]} (inv/create {:name expected-name})]
(is ((comp not empty?) (str id)))
(is (= expected-name name))))
(testing "newly created invoice should be in uploaded state"
(let [n "Flipkart"
expected-state (:submitted inv/states)
{:keys [id status]} (inv/create {:name n})]
(is (= status expected-state)))))
(deftest lookup-invoice
(testing "finds the invoice for the given id"
(let [key "<KEY>"
{id :id} (inv/create {:storage-key key})]
(is (= key (:storage-key (inv/lookup id))))))
(testing "returns nil if there is invoice for the given id"
(let [non-existent-id #uuid "fb857379-1b66-4499-b705-08ec68601c6c"]
(is (nil? (inv/lookup non-existent-id)))))
(testing "adds the attachment URL after the attachment is uploaded"
(let [key "<KEY>"
{id :id} (inv/create {:storage-key key})
_ (inv/update id {:name "Invoice #1"})
attachment-url (:attachment-url (inv/lookup id))]
(is ((comp not nil?) attachment-url)))))
(deftest get-invoices
(testing "fetches all the invoices"
(let [org (org/store {:name "filenso"})
names ["<NAME>" "Harvest" "Cognitect"]]
(doall (map #(inv/create {:name %1 :organization-name "filenso"})
names))
(let [result-names (map :name (inv/all {:organization-name "filenso"}))]
(is (= (sort names)
(sort result-names)))))))
(deftest get-invoices-pagination
(testing "paginates the results"
(let [org (org/store {:name "filenso"})]
(doseq [d (range 1 9)]
(->> d
(format "%02d")
(str "2014-08-")
(java.sql.Date/valueOf)
(hash-map :organization-name "filenso" :name (str d) :date)
(inv/create)))
(let [per-page 3
page-1-names (map :name (inv/all {:page 1 :per-page per-page :organization-name "filenso"}))
page-2-names (map :name (inv/all {:page 2 :per-page per-page :organization-name "filenso"}))
page-3-names (map :name (inv/all {:page 3 :per-page per-page :organization-name "filenso"}))
page-4-names (map :name (inv/all {:page 4 :per-page per-page :organization-name "filenso"}))]
(is (= (map str [8 7 6]) page-1-names))
(is (= (map str [5 4 3]) page-2-names))
(is (= (map str [2 1]) page-3-names))
(is (= [] page-4-names))))))
(deftest update-invoice
(let [{id :id} (inv/create {:name "<NAME>"})]
(testing "changes the requested attrs and status of the invoice"
(let [e-status (:submitted inv/states)
_ (inv/update id {:name "<NAME>"})
{:keys [name status]} (inv/lookup id)]
(is (= name "<NAME> Name"))
(is (= status e-status))))))
(deftest delete-invoice
(testing "create invoice, look for it, delete it, make sure we dont find it again"
(let [{id :id} (inv/create {:name "<NAME>"})
before-removal (inv/lookup id)
_ (inv/delete! id)
after-removal (inv/lookup id)]
(is (not (nil? id)))
(is (not (= before-removal after-removal)))
(is (map? before-removal))
(is (nil? after-removal)))))
(deftest next-and-prev-invoice
(testing "find the next and prev invoices for a given invoice within an organizations"
(let [{org1-id :id} (org/store {:name "filenso"})
{org2-id :id} (org/store {:name "flipcar"})
{inv1-id :id} (inv/create {:organization-name "flipcar"})
{inv2-id :id} (inv/create {:organization-name "filenso"})
{inv3-id :id} (inv/create {:organization-name "flipcar"})
{inv4-id :id} (inv/create {:organization-name "filenso"})
{inv5-id :id} (inv/create {:organization-name "flipcar"})
{inv6-id :id} (inv/create {:organization-name "filenso"})]
(let [result1 (dissoc (inv/next-and-prev-invoices inv1-id {:order "created_at"
:direction "desc"
:organization-name "flipcar"}) :id)
result2 (dissoc (inv/next-and-prev-invoices inv2-id {:order "created_at"
:direction "desc"
:organization-name "<NAME>"}) :id)
result3 (dissoc (inv/next-and-prev-invoices inv3-id {:order "created_at"
:direction "desc"
:organization-name "flipcar"}) :id)
result4 (dissoc (inv/next-and-prev-invoices inv4-id {:order "created_at"
:direction "desc"
:organization-name "filenso"}) :id)]
(is (= {:next-item-id nil :prev-item-id inv3-id} result1))
(is (= {:next-item-id nil :prev-item-id inv4-id} result2))
(is (= {:next-item-id inv1-id :prev-item-id inv5-id} result3))
(is (= {:next-item-id inv2-id :prev-item-id inv6-id} result4))))))
| true | (ns kulu-backend.invoices.model-test
(:require [clojure.test :refer :all]
[conjure.core :refer :all]
[kulu-backend.db :as db]
[kulu-backend.invoices.messaging :as inv-msg]
[kulu-backend.invoices.model :as inv]
[kulu-backend.organizations.model :as org]
[kulu-backend.invoices.search :as inv-search]
[kulu-backend.test-helper :refer :all]
[kulu-backend.config :as cfg]))
(use-fixtures :each isolate-db)
(use-fixtures :once set-test-env)
(deftest create-invoice
(testing "creates an invoice record"
(let [count-before (inv/size {})
inv (inv/create {:name "foobar"})]
(is (= (+ 1 count-before)
(inv/size inv)))))
(testing "generates an id and persist the invoice"
(let [expected-name "Flipkart"
{:keys [id name]} (inv/create {:name expected-name})]
(is ((comp not empty?) (str id)))
(is (= expected-name name))))
(testing "newly created invoice should be in uploaded state"
(let [n "Flipkart"
expected-state (:submitted inv/states)
{:keys [id status]} (inv/create {:name n})]
(is (= status expected-state)))))
(deftest lookup-invoice
(testing "finds the invoice for the given id"
(let [key "PI:KEY:<KEY>END_PI"
{id :id} (inv/create {:storage-key key})]
(is (= key (:storage-key (inv/lookup id))))))
(testing "returns nil if there is invoice for the given id"
(let [non-existent-id #uuid "fb857379-1b66-4499-b705-08ec68601c6c"]
(is (nil? (inv/lookup non-existent-id)))))
(testing "adds the attachment URL after the attachment is uploaded"
(let [key "PI:KEY:<KEY>END_PI"
{id :id} (inv/create {:storage-key key})
_ (inv/update id {:name "Invoice #1"})
attachment-url (:attachment-url (inv/lookup id))]
(is ((comp not nil?) attachment-url)))))
(deftest get-invoices
(testing "fetches all the invoices"
(let [org (org/store {:name "filenso"})
names ["PI:NAME:<NAME>END_PI" "Harvest" "Cognitect"]]
(doall (map #(inv/create {:name %1 :organization-name "filenso"})
names))
(let [result-names (map :name (inv/all {:organization-name "filenso"}))]
(is (= (sort names)
(sort result-names)))))))
(deftest get-invoices-pagination
(testing "paginates the results"
(let [org (org/store {:name "filenso"})]
(doseq [d (range 1 9)]
(->> d
(format "%02d")
(str "2014-08-")
(java.sql.Date/valueOf)
(hash-map :organization-name "filenso" :name (str d) :date)
(inv/create)))
(let [per-page 3
page-1-names (map :name (inv/all {:page 1 :per-page per-page :organization-name "filenso"}))
page-2-names (map :name (inv/all {:page 2 :per-page per-page :organization-name "filenso"}))
page-3-names (map :name (inv/all {:page 3 :per-page per-page :organization-name "filenso"}))
page-4-names (map :name (inv/all {:page 4 :per-page per-page :organization-name "filenso"}))]
(is (= (map str [8 7 6]) page-1-names))
(is (= (map str [5 4 3]) page-2-names))
(is (= (map str [2 1]) page-3-names))
(is (= [] page-4-names))))))
(deftest update-invoice
(let [{id :id} (inv/create {:name "PI:NAME:<NAME>END_PI"})]
(testing "changes the requested attrs and status of the invoice"
(let [e-status (:submitted inv/states)
_ (inv/update id {:name "PI:NAME:<NAME>END_PI"})
{:keys [name status]} (inv/lookup id)]
(is (= name "PI:NAME:<NAME>END_PI Name"))
(is (= status e-status))))))
(deftest delete-invoice
(testing "create invoice, look for it, delete it, make sure we dont find it again"
(let [{id :id} (inv/create {:name "PI:NAME:<NAME>END_PI"})
before-removal (inv/lookup id)
_ (inv/delete! id)
after-removal (inv/lookup id)]
(is (not (nil? id)))
(is (not (= before-removal after-removal)))
(is (map? before-removal))
(is (nil? after-removal)))))
(deftest next-and-prev-invoice
(testing "find the next and prev invoices for a given invoice within an organizations"
(let [{org1-id :id} (org/store {:name "filenso"})
{org2-id :id} (org/store {:name "flipcar"})
{inv1-id :id} (inv/create {:organization-name "flipcar"})
{inv2-id :id} (inv/create {:organization-name "filenso"})
{inv3-id :id} (inv/create {:organization-name "flipcar"})
{inv4-id :id} (inv/create {:organization-name "filenso"})
{inv5-id :id} (inv/create {:organization-name "flipcar"})
{inv6-id :id} (inv/create {:organization-name "filenso"})]
(let [result1 (dissoc (inv/next-and-prev-invoices inv1-id {:order "created_at"
:direction "desc"
:organization-name "flipcar"}) :id)
result2 (dissoc (inv/next-and-prev-invoices inv2-id {:order "created_at"
:direction "desc"
:organization-name "PI:NAME:<NAME>END_PI"}) :id)
result3 (dissoc (inv/next-and-prev-invoices inv3-id {:order "created_at"
:direction "desc"
:organization-name "flipcar"}) :id)
result4 (dissoc (inv/next-and-prev-invoices inv4-id {:order "created_at"
:direction "desc"
:organization-name "filenso"}) :id)]
(is (= {:next-item-id nil :prev-item-id inv3-id} result1))
(is (= {:next-item-id nil :prev-item-id inv4-id} result2))
(is (= {:next-item-id inv1-id :prev-item-id inv5-id} result3))
(is (= {:next-item-id inv2-id :prev-item-id inv6-id} result4))))))
|
[
{
"context": "ind :namespace\n :children\n [{:name \"some-test\"\n :range {:start {:line 1 :character 0}\n",
"end": 1421,
"score": 0.998712956905365,
"start": 1412,
"tag": "USERNAME",
"value": "some-test"
},
{
"context": "}}\n :kind :testing}\n {:name \"bar baz\"\n :range {:start {:line 4 :character 2",
"end": 1957,
"score": 0.8714629411697388,
"start": 1950,
"tag": "NAME",
"value": "bar baz"
},
{
"context": "esting\n :children\n [{:name \"qux\"\n :range {:start {:line 5 :character",
"end": 2242,
"score": 0.5047480463981628,
"start": 2239,
"tag": "NAME",
"value": "qux"
},
{
"context": " :kind :testing}\n {:name \"last one\"\n :range {:start {:line 6 :character",
"end": 2521,
"score": 0.9140734672546387,
"start": 2513,
"tag": "NAME",
"value": "last one"
}
] | lib/test/clojure_lsp/feature/test_tree_test.clj | ccidral/clojure-lsp | 0 | (ns clojure-lsp.feature.test-tree-test
(:require
[clojure-lsp.db :as db]
[clojure-lsp.feature.test-tree :as f.test-tree]
[clojure-lsp.test-helper :as h]
[clojure.test :refer [deftest is testing]]))
(h/reset-db-after-test)
(deftest tree-test
(testing "without test tree client capability"
(swap! db/db assoc-in [:client-capabilities :experimental :testTree] false)
(is (not (f.test-tree/tree "file:///a.clj" db/db))))
(testing "valid test tree"
(swap! db/db assoc-in [:client-capabilities :experimental :testTree] true)
(h/load-code-and-locs (h/code "(ns foo.bar (:require [clojure.test :refer :all]))"
"(deftest some-test"
" (testing \"foo\""
" (+ 1 2))"
" (testing \"bar baz\""
" (testing \"qux\" 123)"
" (testing \"last one\""
" (+ 2 3)))"
")"))
(h/assert-submap
{:uri "file:///a.clj"
:tree
{:name "foo.bar"
:range {:start {:line 0 :character 0}
:end {:line 0 :character 11}}
:name-range {:start {:line 0 :character 4}
:end {:line 0 :character 11}}
:kind :namespace
:children
[{:name "some-test"
:range {:start {:line 1 :character 0}
:end {:line 8 :character 1}}
:name-range {:start {:line 1 :character 9}
:end {:line 1 :character 18}}
:kind :deftest
:children
[{:name "foo"
:range {:start {:line 2 :character 2}
:end {:line 3 :character 12}}
:name-range {:start {:line 2 :character 3}
:end {:line 2 :character 10}}
:kind :testing}
{:name "bar baz"
:range {:start {:line 4 :character 2}
:end {:line 7 :character 15}}
:name-range {:start {:line 4 :character 3}
:end {:line 4 :character 10}}
:kind :testing
:children
[{:name "qux"
:range {:start {:line 5 :character 4}
:end {:line 5 :character 23}}
:name-range {:start {:line 5 :character 5}
:end {:line 5 :character 12}}
:kind :testing}
{:name "last one"
:range {:start {:line 6 :character 4}
:end {:line 7 :character 14}}
:name-range {:start {:line 6 :character 5}
:end {:line 6 :character 12}}
:kind :testing}]}]}]}}
(f.test-tree/tree "file:///a.clj" db/db))))
| 69358 | (ns clojure-lsp.feature.test-tree-test
(:require
[clojure-lsp.db :as db]
[clojure-lsp.feature.test-tree :as f.test-tree]
[clojure-lsp.test-helper :as h]
[clojure.test :refer [deftest is testing]]))
(h/reset-db-after-test)
(deftest tree-test
(testing "without test tree client capability"
(swap! db/db assoc-in [:client-capabilities :experimental :testTree] false)
(is (not (f.test-tree/tree "file:///a.clj" db/db))))
(testing "valid test tree"
(swap! db/db assoc-in [:client-capabilities :experimental :testTree] true)
(h/load-code-and-locs (h/code "(ns foo.bar (:require [clojure.test :refer :all]))"
"(deftest some-test"
" (testing \"foo\""
" (+ 1 2))"
" (testing \"bar baz\""
" (testing \"qux\" 123)"
" (testing \"last one\""
" (+ 2 3)))"
")"))
(h/assert-submap
{:uri "file:///a.clj"
:tree
{:name "foo.bar"
:range {:start {:line 0 :character 0}
:end {:line 0 :character 11}}
:name-range {:start {:line 0 :character 4}
:end {:line 0 :character 11}}
:kind :namespace
:children
[{:name "some-test"
:range {:start {:line 1 :character 0}
:end {:line 8 :character 1}}
:name-range {:start {:line 1 :character 9}
:end {:line 1 :character 18}}
:kind :deftest
:children
[{:name "foo"
:range {:start {:line 2 :character 2}
:end {:line 3 :character 12}}
:name-range {:start {:line 2 :character 3}
:end {:line 2 :character 10}}
:kind :testing}
{:name "<NAME>"
:range {:start {:line 4 :character 2}
:end {:line 7 :character 15}}
:name-range {:start {:line 4 :character 3}
:end {:line 4 :character 10}}
:kind :testing
:children
[{:name "<NAME>"
:range {:start {:line 5 :character 4}
:end {:line 5 :character 23}}
:name-range {:start {:line 5 :character 5}
:end {:line 5 :character 12}}
:kind :testing}
{:name "<NAME>"
:range {:start {:line 6 :character 4}
:end {:line 7 :character 14}}
:name-range {:start {:line 6 :character 5}
:end {:line 6 :character 12}}
:kind :testing}]}]}]}}
(f.test-tree/tree "file:///a.clj" db/db))))
| true | (ns clojure-lsp.feature.test-tree-test
(:require
[clojure-lsp.db :as db]
[clojure-lsp.feature.test-tree :as f.test-tree]
[clojure-lsp.test-helper :as h]
[clojure.test :refer [deftest is testing]]))
(h/reset-db-after-test)
(deftest tree-test
(testing "without test tree client capability"
(swap! db/db assoc-in [:client-capabilities :experimental :testTree] false)
(is (not (f.test-tree/tree "file:///a.clj" db/db))))
(testing "valid test tree"
(swap! db/db assoc-in [:client-capabilities :experimental :testTree] true)
(h/load-code-and-locs (h/code "(ns foo.bar (:require [clojure.test :refer :all]))"
"(deftest some-test"
" (testing \"foo\""
" (+ 1 2))"
" (testing \"bar baz\""
" (testing \"qux\" 123)"
" (testing \"last one\""
" (+ 2 3)))"
")"))
(h/assert-submap
{:uri "file:///a.clj"
:tree
{:name "foo.bar"
:range {:start {:line 0 :character 0}
:end {:line 0 :character 11}}
:name-range {:start {:line 0 :character 4}
:end {:line 0 :character 11}}
:kind :namespace
:children
[{:name "some-test"
:range {:start {:line 1 :character 0}
:end {:line 8 :character 1}}
:name-range {:start {:line 1 :character 9}
:end {:line 1 :character 18}}
:kind :deftest
:children
[{:name "foo"
:range {:start {:line 2 :character 2}
:end {:line 3 :character 12}}
:name-range {:start {:line 2 :character 3}
:end {:line 2 :character 10}}
:kind :testing}
{:name "PI:NAME:<NAME>END_PI"
:range {:start {:line 4 :character 2}
:end {:line 7 :character 15}}
:name-range {:start {:line 4 :character 3}
:end {:line 4 :character 10}}
:kind :testing
:children
[{:name "PI:NAME:<NAME>END_PI"
:range {:start {:line 5 :character 4}
:end {:line 5 :character 23}}
:name-range {:start {:line 5 :character 5}
:end {:line 5 :character 12}}
:kind :testing}
{:name "PI:NAME:<NAME>END_PI"
:range {:start {:line 6 :character 4}
:end {:line 7 :character 14}}
:name-range {:start {:line 6 :character 5}
:end {:line 6 :character 12}}
:kind :testing}]}]}]}}
(f.test-tree/tree "file:///a.clj" db/db))))
|
[
{
"context": ";; Copyright (c) 2020-2021 Saidone\n\n(ns kugelmass.pages.life.life-utils)\n\n;; random ",
"end": 34,
"score": 0.9989199042320251,
"start": 27,
"tag": "NAME",
"value": "Saidone"
}
] | src/cljs/kugelmass/pages/life/life_utils.cljs | saidone75/kugelmass | 0 | ;; Copyright (c) 2020-2021 Saidone
(ns kugelmass.pages.life.life-utils)
;; random boolean ~75% false
(defn- random-bool []
(if (> (rand-int 4) 2)
true
false))
;; init board
(defn init-game [w h]
(vec (doall (take (* w h) (repeatedly random-bool)))))
;; calculate vector index from coords
(defn- compute-index [[x y] w]
(+ x (* y w)))
;; get neighbours of a cell
(defn- neighbours [n w h]
(let [x (mod n w) y (quot n w)]
(map
#(compute-index % w)
(drop 1 (for [x [x (mod (inc x) w) (mod (dec x) w)]
y [y (mod (inc y) h) (mod (dec y) h)]]
(vector x y))))))
;; get alive neighbours count
(defn- count-alive-neighbours [n board]
(let [{w :w h :h board :board} board]
(reduce
#(if (nth board %2)
(inc %1)
%1)
0
(neighbours n w h))))
;; compute next generation of board
(defn compute-next-gen [board]
(reduce
#(let [alive-neighbours (count-alive-neighbours (count %1) board)]
(if %2
(cond
(< alive-neighbours 2) (conj %1 false)
(and (> alive-neighbours 1) (< alive-neighbours 4)) (conj %1 true)
(> alive-neighbours 3) (conj %1 false))
(if (= alive-neighbours 3)
(conj %1 true)
(conj %1 false))))
[]
(:board board)))
| 90569 | ;; Copyright (c) 2020-2021 <NAME>
(ns kugelmass.pages.life.life-utils)
;; random boolean ~75% false
(defn- random-bool []
(if (> (rand-int 4) 2)
true
false))
;; init board
(defn init-game [w h]
(vec (doall (take (* w h) (repeatedly random-bool)))))
;; calculate vector index from coords
(defn- compute-index [[x y] w]
(+ x (* y w)))
;; get neighbours of a cell
(defn- neighbours [n w h]
(let [x (mod n w) y (quot n w)]
(map
#(compute-index % w)
(drop 1 (for [x [x (mod (inc x) w) (mod (dec x) w)]
y [y (mod (inc y) h) (mod (dec y) h)]]
(vector x y))))))
;; get alive neighbours count
(defn- count-alive-neighbours [n board]
(let [{w :w h :h board :board} board]
(reduce
#(if (nth board %2)
(inc %1)
%1)
0
(neighbours n w h))))
;; compute next generation of board
(defn compute-next-gen [board]
(reduce
#(let [alive-neighbours (count-alive-neighbours (count %1) board)]
(if %2
(cond
(< alive-neighbours 2) (conj %1 false)
(and (> alive-neighbours 1) (< alive-neighbours 4)) (conj %1 true)
(> alive-neighbours 3) (conj %1 false))
(if (= alive-neighbours 3)
(conj %1 true)
(conj %1 false))))
[]
(:board board)))
| true | ;; Copyright (c) 2020-2021 PI:NAME:<NAME>END_PI
(ns kugelmass.pages.life.life-utils)
;; random boolean ~75% false
(defn- random-bool []
(if (> (rand-int 4) 2)
true
false))
;; init board
(defn init-game [w h]
(vec (doall (take (* w h) (repeatedly random-bool)))))
;; calculate vector index from coords
(defn- compute-index [[x y] w]
(+ x (* y w)))
;; get neighbours of a cell
(defn- neighbours [n w h]
(let [x (mod n w) y (quot n w)]
(map
#(compute-index % w)
(drop 1 (for [x [x (mod (inc x) w) (mod (dec x) w)]
y [y (mod (inc y) h) (mod (dec y) h)]]
(vector x y))))))
;; get alive neighbours count
(defn- count-alive-neighbours [n board]
(let [{w :w h :h board :board} board]
(reduce
#(if (nth board %2)
(inc %1)
%1)
0
(neighbours n w h))))
;; compute next generation of board
(defn compute-next-gen [board]
(reduce
#(let [alive-neighbours (count-alive-neighbours (count %1) board)]
(if %2
(cond
(< alive-neighbours 2) (conj %1 false)
(and (> alive-neighbours 1) (< alive-neighbours 4)) (conj %1 true)
(> alive-neighbours 3) (conj %1 false))
(if (= alive-neighbours 3)
(conj %1 true)
(conj %1 false))))
[]
(:board board)))
|
[
{
"context": "and conceptually acts as a separate process.\n;;\n;; Isaiah Peng <issaria@gmail.com>\n;;\n\n(defrecord Client [n]\n R",
"end": 549,
"score": 0.9998687505722046,
"start": 538,
"tag": "NAME",
"value": "Isaiah Peng"
},
{
"context": "ly acts as a separate process.\n;;\n;; Isaiah Peng <issaria@gmail.com>\n;;\n\n(defrecord Client [n]\n Runnable\n (run [thi",
"end": 568,
"score": 0.9999261498451233,
"start": 551,
"tag": "EMAIL",
"value": "issaria@gmail.com"
}
] | docs/zeroMQ-guide2/examples/Clojure/lruqueue.clj | krattai/noo-ebs | 2 | (ns lruqueue
(:refer-clojure :exclude [send])
(:require [zhelpers :as mq])
(:import [org.zeromq ZMQ$Poller]))
;;
;; Least-recently used (LRU) queue device
;; Clients and workers are shown here in-process
;;
;; While this example runs in a single process, that is just to make
;; it easier to start and stop the example. Each thread has its own
;; context and conceptually acts as a separate process.
;;
;; Isaiah Peng <issaria@gmail.com>
;;
(defrecord Client [n]
Runnable
(run [this]
(let [cntx (mq/context 1)
client (mq/socket cntx mq/req)]
(mq/set-id client n)
(mq/connect client "ipc://frontend.ipc")
(mq/send client "HELLO")
(println (format "Client: %s" (mq/recv-str client)))
(.close client)
(.term cntx))))
(defrecord Worker [n]
Runnable
(run [this]
(let [cnt (mq/context 1)
worker (mq/socket cnt mq/req)]
(mq/set-id worker n)
(mq/connect worker "ipc://backend.ipc")
(mq/send worker "READY")
(while true
(let [address (mq/recv-str worker)
_ (mq/recv worker)
request (mq/recv-str worker)]
(println (format "Worker: %s" request))
(mq/send-more worker address)
(mq/send-more worker "")
(mq/send worker "OK")))
(.close worker)
(.term cnt))))
(def worker-nbr 3)
(def client-nbr 10)
(defn -main []
(let [ctx (mq/context 1)
frontend (mq/socket ctx mq/router)
backend (mq/socket ctx mq/router)]
(mq/bind frontend "ipc://frontend.ipc")
(mq/bind backend "ipc://backend.ipc")
(dotimes [i client-nbr]
(-> i Client. Thread. .start))
(dotimes [i worker-nbr]
(-> i Worker. Thread. .start)
;; Logic of LRU loop
;; - Poll backend always, frontend only if 1+ worker ready
;; - If worker replies, queue worker as ready and forward reply
;; to client if necessary
;; - If client requests, pop next worker and send request to it
;;
;; Queue of available workers
(let [available-workers (atom 0)
worker-queue (atom clojure.lang.PersistentQueue/EMPTY)
items (.poller ctx 2)]
(while (not (.isInterrupted (Thread/currentThread)))
(dotimes [i client-nbr]
(.register items backend ZMQ$Poller/POLLIN)
(.register items frontend ZMQ$Poller/POLLIN)
(.poll items)
;; Handle worker activity on background
(if (.pollin items 0)
;; Queue worker address for LRU routing
(swap! worker-queue #(conj % (mq/recv-str backend)))
(let [_ (mq/recv backend) client-addr (mq/recv-str backend)]
(if (not= "READY" client-addr)
(let [_ (mq/recv backend) reply (mq/recv-str backend)]
(mq/send-more frontend client-addr)
(mq/send-more frontend "")
(mq/send frontend reply)))))
(if (.pollin items 1)
(let [client-addr (mq/recv-str frontend)
_ (mq/recv frontend)
request (mq/recv-str frontend)
worker-addr (peek @worker-queue)]
(swap! worker-queue pop)
(mq/send-more backend worker-addr)
(mq/send-more backend "")
(mq/send-more backend client-addr)
(mq/send-more backend "")
(mq/send backend request)))))
(.close frontend)
(.close backend)
(.term ctx)))))
| 62116 | (ns lruqueue
(:refer-clojure :exclude [send])
(:require [zhelpers :as mq])
(:import [org.zeromq ZMQ$Poller]))
;;
;; Least-recently used (LRU) queue device
;; Clients and workers are shown here in-process
;;
;; While this example runs in a single process, that is just to make
;; it easier to start and stop the example. Each thread has its own
;; context and conceptually acts as a separate process.
;;
;; <NAME> <<EMAIL>>
;;
(defrecord Client [n]
Runnable
(run [this]
(let [cntx (mq/context 1)
client (mq/socket cntx mq/req)]
(mq/set-id client n)
(mq/connect client "ipc://frontend.ipc")
(mq/send client "HELLO")
(println (format "Client: %s" (mq/recv-str client)))
(.close client)
(.term cntx))))
(defrecord Worker [n]
Runnable
(run [this]
(let [cnt (mq/context 1)
worker (mq/socket cnt mq/req)]
(mq/set-id worker n)
(mq/connect worker "ipc://backend.ipc")
(mq/send worker "READY")
(while true
(let [address (mq/recv-str worker)
_ (mq/recv worker)
request (mq/recv-str worker)]
(println (format "Worker: %s" request))
(mq/send-more worker address)
(mq/send-more worker "")
(mq/send worker "OK")))
(.close worker)
(.term cnt))))
(def worker-nbr 3)
(def client-nbr 10)
(defn -main []
(let [ctx (mq/context 1)
frontend (mq/socket ctx mq/router)
backend (mq/socket ctx mq/router)]
(mq/bind frontend "ipc://frontend.ipc")
(mq/bind backend "ipc://backend.ipc")
(dotimes [i client-nbr]
(-> i Client. Thread. .start))
(dotimes [i worker-nbr]
(-> i Worker. Thread. .start)
;; Logic of LRU loop
;; - Poll backend always, frontend only if 1+ worker ready
;; - If worker replies, queue worker as ready and forward reply
;; to client if necessary
;; - If client requests, pop next worker and send request to it
;;
;; Queue of available workers
(let [available-workers (atom 0)
worker-queue (atom clojure.lang.PersistentQueue/EMPTY)
items (.poller ctx 2)]
(while (not (.isInterrupted (Thread/currentThread)))
(dotimes [i client-nbr]
(.register items backend ZMQ$Poller/POLLIN)
(.register items frontend ZMQ$Poller/POLLIN)
(.poll items)
;; Handle worker activity on background
(if (.pollin items 0)
;; Queue worker address for LRU routing
(swap! worker-queue #(conj % (mq/recv-str backend)))
(let [_ (mq/recv backend) client-addr (mq/recv-str backend)]
(if (not= "READY" client-addr)
(let [_ (mq/recv backend) reply (mq/recv-str backend)]
(mq/send-more frontend client-addr)
(mq/send-more frontend "")
(mq/send frontend reply)))))
(if (.pollin items 1)
(let [client-addr (mq/recv-str frontend)
_ (mq/recv frontend)
request (mq/recv-str frontend)
worker-addr (peek @worker-queue)]
(swap! worker-queue pop)
(mq/send-more backend worker-addr)
(mq/send-more backend "")
(mq/send-more backend client-addr)
(mq/send-more backend "")
(mq/send backend request)))))
(.close frontend)
(.close backend)
(.term ctx)))))
| true | (ns lruqueue
(:refer-clojure :exclude [send])
(:require [zhelpers :as mq])
(:import [org.zeromq ZMQ$Poller]))
;;
;; Least-recently used (LRU) queue device
;; Clients and workers are shown here in-process
;;
;; While this example runs in a single process, that is just to make
;; it easier to start and stop the example. Each thread has its own
;; context and conceptually acts as a separate process.
;;
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;
(defrecord Client [n]
Runnable
(run [this]
(let [cntx (mq/context 1)
client (mq/socket cntx mq/req)]
(mq/set-id client n)
(mq/connect client "ipc://frontend.ipc")
(mq/send client "HELLO")
(println (format "Client: %s" (mq/recv-str client)))
(.close client)
(.term cntx))))
(defrecord Worker [n]
Runnable
(run [this]
(let [cnt (mq/context 1)
worker (mq/socket cnt mq/req)]
(mq/set-id worker n)
(mq/connect worker "ipc://backend.ipc")
(mq/send worker "READY")
(while true
(let [address (mq/recv-str worker)
_ (mq/recv worker)
request (mq/recv-str worker)]
(println (format "Worker: %s" request))
(mq/send-more worker address)
(mq/send-more worker "")
(mq/send worker "OK")))
(.close worker)
(.term cnt))))
(def worker-nbr 3)
(def client-nbr 10)
(defn -main []
(let [ctx (mq/context 1)
frontend (mq/socket ctx mq/router)
backend (mq/socket ctx mq/router)]
(mq/bind frontend "ipc://frontend.ipc")
(mq/bind backend "ipc://backend.ipc")
(dotimes [i client-nbr]
(-> i Client. Thread. .start))
(dotimes [i worker-nbr]
(-> i Worker. Thread. .start)
;; Logic of LRU loop
;; - Poll backend always, frontend only if 1+ worker ready
;; - If worker replies, queue worker as ready and forward reply
;; to client if necessary
;; - If client requests, pop next worker and send request to it
;;
;; Queue of available workers
(let [available-workers (atom 0)
worker-queue (atom clojure.lang.PersistentQueue/EMPTY)
items (.poller ctx 2)]
(while (not (.isInterrupted (Thread/currentThread)))
(dotimes [i client-nbr]
(.register items backend ZMQ$Poller/POLLIN)
(.register items frontend ZMQ$Poller/POLLIN)
(.poll items)
;; Handle worker activity on background
(if (.pollin items 0)
;; Queue worker address for LRU routing
(swap! worker-queue #(conj % (mq/recv-str backend)))
(let [_ (mq/recv backend) client-addr (mq/recv-str backend)]
(if (not= "READY" client-addr)
(let [_ (mq/recv backend) reply (mq/recv-str backend)]
(mq/send-more frontend client-addr)
(mq/send-more frontend "")
(mq/send frontend reply)))))
(if (.pollin items 1)
(let [client-addr (mq/recv-str frontend)
_ (mq/recv frontend)
request (mq/recv-str frontend)
worker-addr (peek @worker-queue)]
(swap! worker-queue pop)
(mq/send-more backend worker-addr)
(mq/send-more backend "")
(mq/send-more backend client-addr)
(mq/send-more backend "")
(mq/send backend request)))))
(.close frontend)
(.close backend)
(.term ctx)))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.