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": ";;;;;;;;;;;;;;;;\n;(def DEFAULT-ADMIN-USER {:name \"Roi Sucasas\" :username \"rsucasas\" :password \"password\" :rol \"", "end": 1806, "score": 0.9966402053833008, "start": 1795, "tag": "NAME", "value": "Roi Sucasas" }, { "context": "EFAULT-ADMIN-USER {:name \"Roi Sucasas\" :username \"rsucasas\" :password \"password\" :rol \"admin\" :location \"Spa", "end": 1827, "score": 0.9994006156921387, "start": 1819, "tag": "USERNAME", "value": "rsucasas" }, { "context": "ame \"Roi Sucasas\" :username \"rsucasas\" :password \"password\" :rol \"admin\" :location \"Spain\"})\n;(create-token ", "end": 1848, "score": 0.9993823766708374, "start": 1840, "tag": "PASSWORD", "value": "password" }, { "context": "tion \"Spain\"})\n;(create-token DEFAULT-ADMIN-USER \"127.0.0.1\")\n", "end": 1927, "score": 0.999688982963562, "start": 1918, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
softcare-multimedia-repository/src/softcare/utilities/jwtoken.clj
seaclouds-atos/softcare-final-implementation
0
(ns softcare.utilities.jwtoken (:require [softcare.config :as config] [softcare.logs.logs :as log] [clj-jwt.core :refer :all] [clj-jwt.key :refer [private-key]] [clj-time.core :refer [now plus minutes]] [clj-time.coerce :as tc])) ;; PRIVATE FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; validate token (defn- validate-jwt [token] (try (-> token str->jwt (verify config/get-jwt-secret-token)) (catch Exception e (do (log/error "error validating auth token") false)))) ;; decode token (defn- decode-jwt [token] (-> token str->jwt :claims)) ;; PUBLIC FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; check token (defn check-token [token] (if (validate-jwt token) (if (> (tc/to-long (now)) ((decode-jwt token) :exp-time)) false true) false)) (defn check-token-admin-user [token] (if (check-token token) (if (= (compare "admin" ((decode-jwt token) :rol)) 0) false true) false)) ;; create token (defn create-token [m-user-data ip] (-> (assoc m-user-data :iat-time (tc/to-long (now)) :exp-time (tc/to-long (plus (now) (minutes config/get-jwt-token-time))) :ip ip) jwt (sign :HS256 config/get-jwt-secret-token) to-str)) ;; update token expiration time (defn update-token [token] (-> (assoc (decode-jwt token) :exp-time (tc/to-long (plus (now) (minutes config/get-jwt-token-time)))) jwt (sign :HS256 config/get-jwt-secret-token) to-str)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;(def DEFAULT-ADMIN-USER {:name "Roi Sucasas" :username "rsucasas" :password "password" :rol "admin" :location "Spain"}) ;(create-token DEFAULT-ADMIN-USER "127.0.0.1")
82167
(ns softcare.utilities.jwtoken (:require [softcare.config :as config] [softcare.logs.logs :as log] [clj-jwt.core :refer :all] [clj-jwt.key :refer [private-key]] [clj-time.core :refer [now plus minutes]] [clj-time.coerce :as tc])) ;; PRIVATE FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; validate token (defn- validate-jwt [token] (try (-> token str->jwt (verify config/get-jwt-secret-token)) (catch Exception e (do (log/error "error validating auth token") false)))) ;; decode token (defn- decode-jwt [token] (-> token str->jwt :claims)) ;; PUBLIC FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; check token (defn check-token [token] (if (validate-jwt token) (if (> (tc/to-long (now)) ((decode-jwt token) :exp-time)) false true) false)) (defn check-token-admin-user [token] (if (check-token token) (if (= (compare "admin" ((decode-jwt token) :rol)) 0) false true) false)) ;; create token (defn create-token [m-user-data ip] (-> (assoc m-user-data :iat-time (tc/to-long (now)) :exp-time (tc/to-long (plus (now) (minutes config/get-jwt-token-time))) :ip ip) jwt (sign :HS256 config/get-jwt-secret-token) to-str)) ;; update token expiration time (defn update-token [token] (-> (assoc (decode-jwt token) :exp-time (tc/to-long (plus (now) (minutes config/get-jwt-token-time)))) jwt (sign :HS256 config/get-jwt-secret-token) to-str)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;(def DEFAULT-ADMIN-USER {:name "<NAME>" :username "rsucasas" :password "<PASSWORD>" :rol "admin" :location "Spain"}) ;(create-token DEFAULT-ADMIN-USER "127.0.0.1")
true
(ns softcare.utilities.jwtoken (:require [softcare.config :as config] [softcare.logs.logs :as log] [clj-jwt.core :refer :all] [clj-jwt.key :refer [private-key]] [clj-time.core :refer [now plus minutes]] [clj-time.coerce :as tc])) ;; PRIVATE FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; validate token (defn- validate-jwt [token] (try (-> token str->jwt (verify config/get-jwt-secret-token)) (catch Exception e (do (log/error "error validating auth token") false)))) ;; decode token (defn- decode-jwt [token] (-> token str->jwt :claims)) ;; PUBLIC FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; check token (defn check-token [token] (if (validate-jwt token) (if (> (tc/to-long (now)) ((decode-jwt token) :exp-time)) false true) false)) (defn check-token-admin-user [token] (if (check-token token) (if (= (compare "admin" ((decode-jwt token) :rol)) 0) false true) false)) ;; create token (defn create-token [m-user-data ip] (-> (assoc m-user-data :iat-time (tc/to-long (now)) :exp-time (tc/to-long (plus (now) (minutes config/get-jwt-token-time))) :ip ip) jwt (sign :HS256 config/get-jwt-secret-token) to-str)) ;; update token expiration time (defn update-token [token] (-> (assoc (decode-jwt token) :exp-time (tc/to-long (plus (now) (minutes config/get-jwt-token-time)))) jwt (sign :HS256 config/get-jwt-secret-token) to-str)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;(def DEFAULT-ADMIN-USER {:name "PI:NAME:<NAME>END_PI" :username "rsucasas" :password "PI:PASSWORD:<PASSWORD>END_PI" :rol "admin" :location "Spain"}) ;(create-token DEFAULT-ADMIN-USER "127.0.0.1")
[ { "context": " {:doc \"to examine compiler output.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-09-14\"\n :version \"2017-10-14\"}", "end": 265, "score": 0.9128249883651733, "start": 229, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/main/clojure/palisades/lakes/funx/meta/adder.clj
palisades-lakes/function-experiments
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.funx.meta.adder {:doc "to examine compiler output." :author "palisades dot lakes at gmail dot com" :since "2017-09-14" :version "2017-10-14"}) ;;---------------------------------------------------------------- (defn make-adder ^clojure.lang.IFn$DD [^double delta] (fn adder ^double [^double x] (+ x delta))) #_(defn make-adder ^clojure.lang.IFn$DD [^double delta] (let [f (fn adder ^double [^double x] (+ x delta))] (println (class f) (str f) (instance? clojure.lang.IFn$DD f)) (with-meta f (merge (meta f) {:delta delta})))) #_(def add1 (make-adder 1)) #_(println (class add1) (str add1) (instance? clojure.lang.IFn$DD add1)) #_(println (meta add1)) ;;---------------------------------------------------------------- ;(defn a1 ^double [^double x] (+ 1.0 x)) ;(def m1 (with-meta a1 {:domain Double/TYPE :codomain Double/TYPE})) ; ;(println (class a1) a1) ;(println (class m1) m1) ;(println (= a1 m1)) ;(println (instance? clojure.lang.RestFn a1)) ;(println (instance? clojure.lang.RestFn m1))
63701
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.funx.meta.adder {:doc "to examine compiler output." :author "<EMAIL>" :since "2017-09-14" :version "2017-10-14"}) ;;---------------------------------------------------------------- (defn make-adder ^clojure.lang.IFn$DD [^double delta] (fn adder ^double [^double x] (+ x delta))) #_(defn make-adder ^clojure.lang.IFn$DD [^double delta] (let [f (fn adder ^double [^double x] (+ x delta))] (println (class f) (str f) (instance? clojure.lang.IFn$DD f)) (with-meta f (merge (meta f) {:delta delta})))) #_(def add1 (make-adder 1)) #_(println (class add1) (str add1) (instance? clojure.lang.IFn$DD add1)) #_(println (meta add1)) ;;---------------------------------------------------------------- ;(defn a1 ^double [^double x] (+ 1.0 x)) ;(def m1 (with-meta a1 {:domain Double/TYPE :codomain Double/TYPE})) ; ;(println (class a1) a1) ;(println (class m1) m1) ;(println (= a1 m1)) ;(println (instance? clojure.lang.RestFn a1)) ;(println (instance? clojure.lang.RestFn m1))
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.funx.meta.adder {:doc "to examine compiler output." :author "PI:EMAIL:<EMAIL>END_PI" :since "2017-09-14" :version "2017-10-14"}) ;;---------------------------------------------------------------- (defn make-adder ^clojure.lang.IFn$DD [^double delta] (fn adder ^double [^double x] (+ x delta))) #_(defn make-adder ^clojure.lang.IFn$DD [^double delta] (let [f (fn adder ^double [^double x] (+ x delta))] (println (class f) (str f) (instance? clojure.lang.IFn$DD f)) (with-meta f (merge (meta f) {:delta delta})))) #_(def add1 (make-adder 1)) #_(println (class add1) (str add1) (instance? clojure.lang.IFn$DD add1)) #_(println (meta add1)) ;;---------------------------------------------------------------- ;(defn a1 ^double [^double x] (+ 1.0 x)) ;(def m1 (with-meta a1 {:domain Double/TYPE :codomain Double/TYPE})) ; ;(println (class a1) a1) ;(println (class m1) m1) ;(println (= a1 m1)) ;(println (instance? clojure.lang.RestFn a1)) ;(println (instance? clojure.lang.RestFn m1))
[ { "context": "application/rss+xml\"}]\n [:author\n [:name \"Mark McGranaghan\"]\n [:email \"mmcgrana@gmail.com\"]\n [:uri", "end": 3601, "score": 0.999772846698761, "start": 3585, "tag": "NAME", "value": "Mark McGranaghan" }, { "context": "r\n [:name \"Mark McGranaghan\"]\n [:email \"mmcgrana@gmail.com\"]\n [:uri \"http://github.com/mmcgrana\"]]\n ", "end": 3637, "score": 0.9999144673347473, "start": 3619, "tag": "EMAIL", "value": "mmcgrana@gmail.com" }, { "context": "cgrana@gmail.com\"]\n [:uri \"http://github.com/mmcgrana\"]]\n (for [post posts]\n [:entry\n [:", "end": 3679, "score": 0.9996393322944641, "start": 3671, "tag": "USERNAME", "value": "mmcgrana" } ]
weld-blog-example/src/weldblog/views.clj
mmcgrana/clj-garden
8
(ns weldblog.views (:use (weld routing) (weldblog utils auth) (clj-html core utils helpers helpers-ext) [stash.core :only (errors)] [stash.pagination :except (paginate)]) (:require [clj-time.core :as time] [stash.core :as stash])) ;; Helpers (defmacro layout [assigns-form & body] `(let [assigns# ~assigns-form] (html (doctype :xhtml-transitional) [:html {:xmlns "http://www.w3.org/1999/xhtml"} [:head (include-css "/stylesheets/main.css") (get assigns# :head) [:meta {:http-equiv "Content-Type" :content "text/html;charset=utf-8"}] [:title "Weld Blog Example"] [:body [:div#container [:div#header [:p.session (if (authenticated? (get assigns# :sess)) (delete-button "log out" (path :destroy-session)) (link-to "log in" (path :new-session)))]] [:div#content ~@body]]]]]))) (def message-info {:session-needed [:notice "Please log in"] :session-created [:success "You are now logged in"] :session-destroyed [:notice "You are now logged out"] :post-created [:success "Post created"] :post-updated [:success "Post updated"] :post-destroyed [:success "Post destroyed"]}) (defhtml message-flash [sess] (when-let-html [[type text] (message-info (get sess :flash))] [:h3.message {:class (name type)} text])) (defhtml partial-post [post] [:div {:class (str "post_" (:id post))} [:h2 (link-to (h (:title post)) (path :show-post post))] [:div.post_body (h (:body post))]]) (defhtml error-messages-post [post] (when-let-html [errs (errors post)] [:div.error-messages [:h3 "There were problems with your submission:"] (for-html [err errs] [:p (name (:on err))])])) (defhtml partial-post-form [post] [:p "title:"] [:p (text-field-tag "post[title]" (:title post))] [:p "body:"] [:p (text-area-tag "post[body]" (:body post) {:rows 20 :cols 80})] [:p (submit-tag "Submit Post")]) (defhtml pagination-links [pager] (let-html [p (page pager) tp (total-pages pager)] [:p.pagination [:span.pagination-link (cond (= p 1) "newer" (= p 2) (link-to "newer" (path :index-posts)) :else (link-to "newer" (path :index-posts-paginated {:page (dec p)})))] " " [:span.pagination-link (cond (= p tp) "older" :else (link-to "older" (path :index-posts-paginated {:page (inc p)})))]])) ;; Main Views (defhtml new-session [sess] (layout {:sess sess} (message-flash sess) [:p "password:"] (form {:to (path-info :create-session)} (html [:p (password-field-tag "password")])))) (defhtml index [sess pager] (layout {:sess sess :head (auto-discovery-link-tag :atom {:title "Feed for Ring Blog Example" :href (path :index-posts-atom)})} (message-flash sess) [:h1 "Posts"] (when-html (authenticated? sess) [:p (link-to "New Post" (path :new-post))]) [:div#posts (map-str partial-post (entries pager))] (pagination-links pager))) (defxml index-atom [posts] [:decl! {:version "1.1"}] [:feed {:xmlns "http://www.w3.org/2005/Atom" "xml:lang" "en-US"} [:id (url :index-posts-atom)] [:title "Ring Blog Example"] [:updated (time/xmlschema (time/now))] [:link {:href (url :index-posts-atom) :rel "self" :type "application/rss+xml"}] [:author [:name "Mark McGranaghan"] [:email "mmcgrana@gmail.com"] [:uri "http://github.com/mmcgrana"]] (for [post posts] [:entry [:id (url :show-post post)] [:title (h (:title post))] [:link {:rel "alternate" :type "text/html" :href (url :show-post post)}] [:updated (time/xmlschema (time/now))] [:summary {:type "xhtml"} [:div {:xmlns "http://www.w3.org/1999/xhtml"} (h (:body post))]]])]) (defhtml show [sess post] (layout {:sess sess} (message-flash sess) (partial-post post) [:p (link-to "All Posts" (path :index-posts)) (when-html (authenticated? sess) " | " (link-to "Edit Post" (path :edit-post post)))])) (defhtml new [sess post] (layout {:sess sess} [:h1 "New Post"] (error-messages-post post) (form {:to (path-info :create-post)} (partial-post-form post)))) (defhtml edit [sess post] (layout {:sess sess} [:h1 "Edit Post"] (error-messages-post post) (form {:to (path-info :update-post post)} (partial-post-form post)))) (defhtml not-found [sess] (layout {:sess sess} [:h3 "We're sorry - we couln't find that."] [:p "Please return to the " (link-to "Home Page" (path :index-posts))])) (defhtml internal-error [sess] (layout {:sess sess} [:h3 "We're sorry - something went wrong."] [:p "We've been notified of the problem and are looking into it."]))
43300
(ns weldblog.views (:use (weld routing) (weldblog utils auth) (clj-html core utils helpers helpers-ext) [stash.core :only (errors)] [stash.pagination :except (paginate)]) (:require [clj-time.core :as time] [stash.core :as stash])) ;; Helpers (defmacro layout [assigns-form & body] `(let [assigns# ~assigns-form] (html (doctype :xhtml-transitional) [:html {:xmlns "http://www.w3.org/1999/xhtml"} [:head (include-css "/stylesheets/main.css") (get assigns# :head) [:meta {:http-equiv "Content-Type" :content "text/html;charset=utf-8"}] [:title "Weld Blog Example"] [:body [:div#container [:div#header [:p.session (if (authenticated? (get assigns# :sess)) (delete-button "log out" (path :destroy-session)) (link-to "log in" (path :new-session)))]] [:div#content ~@body]]]]]))) (def message-info {:session-needed [:notice "Please log in"] :session-created [:success "You are now logged in"] :session-destroyed [:notice "You are now logged out"] :post-created [:success "Post created"] :post-updated [:success "Post updated"] :post-destroyed [:success "Post destroyed"]}) (defhtml message-flash [sess] (when-let-html [[type text] (message-info (get sess :flash))] [:h3.message {:class (name type)} text])) (defhtml partial-post [post] [:div {:class (str "post_" (:id post))} [:h2 (link-to (h (:title post)) (path :show-post post))] [:div.post_body (h (:body post))]]) (defhtml error-messages-post [post] (when-let-html [errs (errors post)] [:div.error-messages [:h3 "There were problems with your submission:"] (for-html [err errs] [:p (name (:on err))])])) (defhtml partial-post-form [post] [:p "title:"] [:p (text-field-tag "post[title]" (:title post))] [:p "body:"] [:p (text-area-tag "post[body]" (:body post) {:rows 20 :cols 80})] [:p (submit-tag "Submit Post")]) (defhtml pagination-links [pager] (let-html [p (page pager) tp (total-pages pager)] [:p.pagination [:span.pagination-link (cond (= p 1) "newer" (= p 2) (link-to "newer" (path :index-posts)) :else (link-to "newer" (path :index-posts-paginated {:page (dec p)})))] " " [:span.pagination-link (cond (= p tp) "older" :else (link-to "older" (path :index-posts-paginated {:page (inc p)})))]])) ;; Main Views (defhtml new-session [sess] (layout {:sess sess} (message-flash sess) [:p "password:"] (form {:to (path-info :create-session)} (html [:p (password-field-tag "password")])))) (defhtml index [sess pager] (layout {:sess sess :head (auto-discovery-link-tag :atom {:title "Feed for Ring Blog Example" :href (path :index-posts-atom)})} (message-flash sess) [:h1 "Posts"] (when-html (authenticated? sess) [:p (link-to "New Post" (path :new-post))]) [:div#posts (map-str partial-post (entries pager))] (pagination-links pager))) (defxml index-atom [posts] [:decl! {:version "1.1"}] [:feed {:xmlns "http://www.w3.org/2005/Atom" "xml:lang" "en-US"} [:id (url :index-posts-atom)] [:title "Ring Blog Example"] [:updated (time/xmlschema (time/now))] [:link {:href (url :index-posts-atom) :rel "self" :type "application/rss+xml"}] [:author [:name "<NAME>"] [:email "<EMAIL>"] [:uri "http://github.com/mmcgrana"]] (for [post posts] [:entry [:id (url :show-post post)] [:title (h (:title post))] [:link {:rel "alternate" :type "text/html" :href (url :show-post post)}] [:updated (time/xmlschema (time/now))] [:summary {:type "xhtml"} [:div {:xmlns "http://www.w3.org/1999/xhtml"} (h (:body post))]]])]) (defhtml show [sess post] (layout {:sess sess} (message-flash sess) (partial-post post) [:p (link-to "All Posts" (path :index-posts)) (when-html (authenticated? sess) " | " (link-to "Edit Post" (path :edit-post post)))])) (defhtml new [sess post] (layout {:sess sess} [:h1 "New Post"] (error-messages-post post) (form {:to (path-info :create-post)} (partial-post-form post)))) (defhtml edit [sess post] (layout {:sess sess} [:h1 "Edit Post"] (error-messages-post post) (form {:to (path-info :update-post post)} (partial-post-form post)))) (defhtml not-found [sess] (layout {:sess sess} [:h3 "We're sorry - we couln't find that."] [:p "Please return to the " (link-to "Home Page" (path :index-posts))])) (defhtml internal-error [sess] (layout {:sess sess} [:h3 "We're sorry - something went wrong."] [:p "We've been notified of the problem and are looking into it."]))
true
(ns weldblog.views (:use (weld routing) (weldblog utils auth) (clj-html core utils helpers helpers-ext) [stash.core :only (errors)] [stash.pagination :except (paginate)]) (:require [clj-time.core :as time] [stash.core :as stash])) ;; Helpers (defmacro layout [assigns-form & body] `(let [assigns# ~assigns-form] (html (doctype :xhtml-transitional) [:html {:xmlns "http://www.w3.org/1999/xhtml"} [:head (include-css "/stylesheets/main.css") (get assigns# :head) [:meta {:http-equiv "Content-Type" :content "text/html;charset=utf-8"}] [:title "Weld Blog Example"] [:body [:div#container [:div#header [:p.session (if (authenticated? (get assigns# :sess)) (delete-button "log out" (path :destroy-session)) (link-to "log in" (path :new-session)))]] [:div#content ~@body]]]]]))) (def message-info {:session-needed [:notice "Please log in"] :session-created [:success "You are now logged in"] :session-destroyed [:notice "You are now logged out"] :post-created [:success "Post created"] :post-updated [:success "Post updated"] :post-destroyed [:success "Post destroyed"]}) (defhtml message-flash [sess] (when-let-html [[type text] (message-info (get sess :flash))] [:h3.message {:class (name type)} text])) (defhtml partial-post [post] [:div {:class (str "post_" (:id post))} [:h2 (link-to (h (:title post)) (path :show-post post))] [:div.post_body (h (:body post))]]) (defhtml error-messages-post [post] (when-let-html [errs (errors post)] [:div.error-messages [:h3 "There were problems with your submission:"] (for-html [err errs] [:p (name (:on err))])])) (defhtml partial-post-form [post] [:p "title:"] [:p (text-field-tag "post[title]" (:title post))] [:p "body:"] [:p (text-area-tag "post[body]" (:body post) {:rows 20 :cols 80})] [:p (submit-tag "Submit Post")]) (defhtml pagination-links [pager] (let-html [p (page pager) tp (total-pages pager)] [:p.pagination [:span.pagination-link (cond (= p 1) "newer" (= p 2) (link-to "newer" (path :index-posts)) :else (link-to "newer" (path :index-posts-paginated {:page (dec p)})))] " " [:span.pagination-link (cond (= p tp) "older" :else (link-to "older" (path :index-posts-paginated {:page (inc p)})))]])) ;; Main Views (defhtml new-session [sess] (layout {:sess sess} (message-flash sess) [:p "password:"] (form {:to (path-info :create-session)} (html [:p (password-field-tag "password")])))) (defhtml index [sess pager] (layout {:sess sess :head (auto-discovery-link-tag :atom {:title "Feed for Ring Blog Example" :href (path :index-posts-atom)})} (message-flash sess) [:h1 "Posts"] (when-html (authenticated? sess) [:p (link-to "New Post" (path :new-post))]) [:div#posts (map-str partial-post (entries pager))] (pagination-links pager))) (defxml index-atom [posts] [:decl! {:version "1.1"}] [:feed {:xmlns "http://www.w3.org/2005/Atom" "xml:lang" "en-US"} [:id (url :index-posts-atom)] [:title "Ring Blog Example"] [:updated (time/xmlschema (time/now))] [:link {:href (url :index-posts-atom) :rel "self" :type "application/rss+xml"}] [:author [:name "PI:NAME:<NAME>END_PI"] [:email "PI:EMAIL:<EMAIL>END_PI"] [:uri "http://github.com/mmcgrana"]] (for [post posts] [:entry [:id (url :show-post post)] [:title (h (:title post))] [:link {:rel "alternate" :type "text/html" :href (url :show-post post)}] [:updated (time/xmlschema (time/now))] [:summary {:type "xhtml"} [:div {:xmlns "http://www.w3.org/1999/xhtml"} (h (:body post))]]])]) (defhtml show [sess post] (layout {:sess sess} (message-flash sess) (partial-post post) [:p (link-to "All Posts" (path :index-posts)) (when-html (authenticated? sess) " | " (link-to "Edit Post" (path :edit-post post)))])) (defhtml new [sess post] (layout {:sess sess} [:h1 "New Post"] (error-messages-post post) (form {:to (path-info :create-post)} (partial-post-form post)))) (defhtml edit [sess post] (layout {:sess sess} [:h1 "Edit Post"] (error-messages-post post) (form {:to (path-info :update-post post)} (partial-post-form post)))) (defhtml not-found [sess] (layout {:sess sess} [:h3 "We're sorry - we couln't find that."] [:p "Please return to the " (link-to "Home Page" (path :index-posts))])) (defhtml internal-error [sess] (layout {:sess sess} [:h3 "We're sorry - something went wrong."] [:p "We've been notified of the problem and are looking into it."]))
[ { "context": ";; Copyright (c) 2010 Tom Crayford,\n;;\n;; Redistribution and use in source and binar", "end": 34, "score": 0.9998258948326111, "start": 22, "tag": "NAME", "value": "Tom Crayford" } ]
src/clojure_refactoring/extract_method.clj
tcrayford/clojure-refactoring
6
;; Copyright (c) 2010 Tom Crayford, ;; ;; 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 clojure-refactoring.extract-method (:use [clojure-refactoring.support core formatter find-bindings-above-node] [clojure-refactoring.ast :only [defparsed-fn]] clojure.set [clojure.contrib.seq-utils :only [find-first]]) (:require [clojure-refactoring.ast :as ast])) (defn- find-occurences [args node] "Looks for any occurence of each element of args in the node" (seq (intersection (set args) (set (ast/sub-nodes node))))) (defn fn-name [fn-node] (second (ast/relevant-content fn-node))) (defn fn-call [fn-node] "Uses the arguments of a function node to return a call to it." (ast/list `(~(fn-name fn-node) ~@(ast/parsley-bindings fn-node)))) (defn- arg-occurences [f-node extracted-node] "Finds the bindings from f-node that are also in the extracted node." (-> (find-bindings-above-node f-node extracted-node) (find-occurences extracted-node))) (defn- make-fn-node [name args body] "Creates an ast representing the new function" (format-ast (ast/list-without-whitespace (ast/symbol 'defn) name (ast/vector args) (ast/strip-whitespace body)))) (defn call-extracted [body toplevel extracted] (ast/tree-replace body (fn-call extracted) toplevel)) (defn- nodes-to-string [extract-node fn-node new-fun] "Formats the output for extract-method to print" (str (ast/ast->string new-fun) "\n\n" (ast/ast->string (call-extracted extract-node fn-node new-fun)))) (defparsed-fn extract-method [function-node extract-node new-name] "Extracts extract-string out of fn-string and replaces it with a function call to the extracted method. Only works on single arity root functions" (let [args (arg-occurences function-node extract-node) new-fun (make-fn-node new-name args extract-node)] (nodes-to-string extract-node function-node new-fun)))
54631
;; Copyright (c) 2010 <NAME>, ;; ;; 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 clojure-refactoring.extract-method (:use [clojure-refactoring.support core formatter find-bindings-above-node] [clojure-refactoring.ast :only [defparsed-fn]] clojure.set [clojure.contrib.seq-utils :only [find-first]]) (:require [clojure-refactoring.ast :as ast])) (defn- find-occurences [args node] "Looks for any occurence of each element of args in the node" (seq (intersection (set args) (set (ast/sub-nodes node))))) (defn fn-name [fn-node] (second (ast/relevant-content fn-node))) (defn fn-call [fn-node] "Uses the arguments of a function node to return a call to it." (ast/list `(~(fn-name fn-node) ~@(ast/parsley-bindings fn-node)))) (defn- arg-occurences [f-node extracted-node] "Finds the bindings from f-node that are also in the extracted node." (-> (find-bindings-above-node f-node extracted-node) (find-occurences extracted-node))) (defn- make-fn-node [name args body] "Creates an ast representing the new function" (format-ast (ast/list-without-whitespace (ast/symbol 'defn) name (ast/vector args) (ast/strip-whitespace body)))) (defn call-extracted [body toplevel extracted] (ast/tree-replace body (fn-call extracted) toplevel)) (defn- nodes-to-string [extract-node fn-node new-fun] "Formats the output for extract-method to print" (str (ast/ast->string new-fun) "\n\n" (ast/ast->string (call-extracted extract-node fn-node new-fun)))) (defparsed-fn extract-method [function-node extract-node new-name] "Extracts extract-string out of fn-string and replaces it with a function call to the extracted method. Only works on single arity root functions" (let [args (arg-occurences function-node extract-node) new-fun (make-fn-node new-name args extract-node)] (nodes-to-string extract-node function-node new-fun)))
true
;; Copyright (c) 2010 PI:NAME:<NAME>END_PI, ;; ;; 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 clojure-refactoring.extract-method (:use [clojure-refactoring.support core formatter find-bindings-above-node] [clojure-refactoring.ast :only [defparsed-fn]] clojure.set [clojure.contrib.seq-utils :only [find-first]]) (:require [clojure-refactoring.ast :as ast])) (defn- find-occurences [args node] "Looks for any occurence of each element of args in the node" (seq (intersection (set args) (set (ast/sub-nodes node))))) (defn fn-name [fn-node] (second (ast/relevant-content fn-node))) (defn fn-call [fn-node] "Uses the arguments of a function node to return a call to it." (ast/list `(~(fn-name fn-node) ~@(ast/parsley-bindings fn-node)))) (defn- arg-occurences [f-node extracted-node] "Finds the bindings from f-node that are also in the extracted node." (-> (find-bindings-above-node f-node extracted-node) (find-occurences extracted-node))) (defn- make-fn-node [name args body] "Creates an ast representing the new function" (format-ast (ast/list-without-whitespace (ast/symbol 'defn) name (ast/vector args) (ast/strip-whitespace body)))) (defn call-extracted [body toplevel extracted] (ast/tree-replace body (fn-call extracted) toplevel)) (defn- nodes-to-string [extract-node fn-node new-fun] "Formats the output for extract-method to print" (str (ast/ast->string new-fun) "\n\n" (ast/ast->string (call-extracted extract-node fn-node new-fun)))) (defparsed-fn extract-method [function-node extract-node new-name] "Extracts extract-string out of fn-string and replaces it with a function call to the extracted method. Only works on single arity root functions" (let [args (arg-occurences function-node extract-node) new-fun (make-fn-node new-name args extract-node)] (nodes-to-string extract-node function-node new-fun)))
[ { "context": "tical-to :password1]]]\n input {:password1 \"foobar\"\n :password2 \"foobar.\"}\n err", "end": 2609, "score": 0.9827353358268738, "start": 2603, "tag": "PASSWORD", "value": "foobar" }, { "context": "t {:password1 \"foobar\"\n :password2 \"foobar.\"}\n errors {:password2 \"does not match\"}\n ", "end": 2644, "score": 0.9920241832733154, "start": 2638, "tag": "PASSWORD", "value": "foobar" }, { "context": "errors (first result)))\n (t/is (= {:password1 \"foobar\"} (second result)))))\n\n(t/deftest test-dependent-", "end": 2805, "score": 0.6975133419036865, "start": 2799, "tag": "PASSWORD", "value": "foobar" }, { "context": "tical-to :password1]]]\n input {:password1 \"foobar\"\n :password2 \"foobar\"}\n resu", "end": 2999, "score": 0.994749903678894, "start": 2993, "tag": "PASSWORD", "value": "foobar" }, { "context": "t {:password1 \"foobar\"\n :password2 \"foobar\"}\n result (st/validate input scheme)]\n ", "end": 3034, "score": 0.9957363605499268, "start": 3028, "tag": "PASSWORD", "value": "foobar" }, { "context": "(= nil (first result)))\n (t/is (= {:password1 \"foobar\"\n :password2 \"foobar\"} (second resul", "end": 3146, "score": 0.9509499073028564, "start": 3140, "tag": "PASSWORD", "value": "foobar" }, { "context": "(= {:password1 \"foobar\"\n :password2 \"foobar\"} (second result)))))\n\n(t/deftest test-multiple-v", "end": 3180, "score": 0.9941425919532776, "start": 3174, "tag": "PASSWORD", "value": "foobar" } ]
test/struct/tests.cljc
saitouena/struct
125
(ns struct.tests (:require #?(:cljs [cljs.test :as t] :clj [clojure.test :as t]) [struct.core :as st])) ;; --- Tests (t/deftest test-optional-validators (let [scheme {:max st/number :scope st/string} input {:scope "foobar"} result (st/validate input scheme)] (t/is (= nil (first result))) (t/is (= input (second result))))) (t/deftest test-simple-validators (let [scheme {:max st/number :scope st/string} input {:scope "foobar" :max "d"} errors {:max "must be a number"} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:scope "foobar"} (second result))))) (t/deftest test-neested-validators (let [scheme {[:a :b] st/number [:c :d :e] st/string} input {:a {:b "foo"} :c {:d {:e "bar"}}} errors {:a {:b "must be a number"}} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:c {:d {:e "bar"}}} (second result))))) (t/deftest test-single-validators (let [result1 (st/validate-single 2 st/number) result2 (st/validate-single nil st/number) result3 (st/validate-single nil [st/required st/number])] (t/is (= [nil 2] result1)) (t/is (= [nil nil] result2)) (t/is (= ["this field is mandatory" nil] result3)))) (t/deftest test-parametric-validators (let [result1 (st/validate {:name "foo"} {:name [[st/min-count 4]]}) result2 (st/validate {:name "bar"} {:name [[st/max-count 2]]})] (t/is (= {:name "less than the minimum 4"} (first result1))) (t/is (= {:name "longer than the maximum 2"} (first result2))))) (t/deftest test-simple-validators-with-vector-schema (let [scheme [[:max st/number] [:scope st/string]] input {:scope "foobar" :max "d"} errors {:max "must be a number"} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:scope "foobar"} (second result))))) (t/deftest test-simple-validators-with-translate (let [scheme [[:max st/number] [:scope st/string]] input {:scope "foobar" :max "d"} errors {:max "a"} result (st/validate input scheme {:translate (constantly "a")})] (t/is (= errors (first result))) (t/is (= {:scope "foobar"} (second result))))) (t/deftest test-dependent-validators-1 (let [scheme [[:password1 st/string] [:password2 [st/identical-to :password1]]] input {:password1 "foobar" :password2 "foobar."} errors {:password2 "does not match"} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:password1 "foobar"} (second result))))) (t/deftest test-dependent-validators-2 (let [scheme [[:password1 st/string] [:password2 [st/identical-to :password1]]] input {:password1 "foobar" :password2 "foobar"} result (st/validate input scheme)] (t/is (= nil (first result))) (t/is (= {:password1 "foobar" :password2 "foobar"} (second result))))) (t/deftest test-multiple-validators (let [scheme {:max [st/required st/number] :scope st/string} input {:scope "foobar"} errors {:max "this field is mandatory"} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:scope "foobar"} (second result))))) (t/deftest test-validation-with-coersion (let [scheme {:max st/integer-str :scope st/string} input {:max "2" :scope "foobar"} result (st/validate input scheme)] (t/is (= nil (first result))) (t/is (= {:max 2 :scope "foobar"} (second result))))) (t/deftest test-validation-with-custom-coersion (let [scheme {:max [[st/number-str :coerce (constantly :foo)]] :scope st/string} input {:max "2" :scope "foobar"} result (st/validate input scheme)] (t/is (= nil (first result))) (t/is (= {:max :foo :scope "foobar"} (second result))))) (t/deftest test-validation-with-custom-message (let [scheme {:max [[st/number-str :message "custom msg"]] :scope st/string} input {:max "g" :scope "foobar"} errors {:max "custom msg"} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:scope "foobar"} (second result))))) (t/deftest test-coersion-with-valid-values (let [scheme {:a st/number-str :b st/integer-str} input {:a 2.3 :b 3.3} [errors data] (st/validate input scheme)] (t/is (= {:a 2.3 :b 3} data)))) (t/deftest test-validation-nested-data-in-a-vector (let [scheme {:a [st/vector [st/every number?]]} input1 {:a [1 2 3 4]} input2 {:a [1 2 3 4 "a"]} [errors1 data1] (st/validate input1 scheme) [errors2 data2] (st/validate input2 scheme)] (t/is (= data1 input1)) (t/is (= errors1 nil)) (t/is (= data2 {})) (t/is (= errors2 {:a "must match the predicate"})))) (t/deftest test-in-range-validator (t/is (= {:age "not in range 18 and 26"} (-> {:age 17} (st/validate {:age [[st/in-range 18 26]]}) first)))) (t/deftest test-honor-nested-data (let [scheme {[:a :b] [st/required st/string [st/min-count 2 :message "foobar"] [st/max-count 5]]} input1 {:a {:b "abcd"}} input2 {:a {:b "abcdefgh"}} input3 {:a {:b "a"}} [errors1 data1] (st/validate input1 scheme) [errors2 data2] (st/validate input2 scheme) [errors3 data3] (st/validate input3 scheme)] (t/is (= data1 input1)) (t/is (= errors1 nil)) (t/is (= data2 {})) (t/is (= errors2 {:a {:b "longer than the maximum 5"}})) (t/is (= data3 {})) (t/is (= errors3 {:a {:b "foobar"}})))) ;; --- Entry point #?(:cljs (do (enable-console-print!) (set! *main-cli-fn* #(t/run-tests)))) #?(:cljs (defmethod t/report [:cljs.test/default :end-run-tests] [m] (if (t/successful? m) (set! (.-exitCode js/process) 0) (set! (.-exitCode js/process) 1))))
3065
(ns struct.tests (:require #?(:cljs [cljs.test :as t] :clj [clojure.test :as t]) [struct.core :as st])) ;; --- Tests (t/deftest test-optional-validators (let [scheme {:max st/number :scope st/string} input {:scope "foobar"} result (st/validate input scheme)] (t/is (= nil (first result))) (t/is (= input (second result))))) (t/deftest test-simple-validators (let [scheme {:max st/number :scope st/string} input {:scope "foobar" :max "d"} errors {:max "must be a number"} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:scope "foobar"} (second result))))) (t/deftest test-neested-validators (let [scheme {[:a :b] st/number [:c :d :e] st/string} input {:a {:b "foo"} :c {:d {:e "bar"}}} errors {:a {:b "must be a number"}} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:c {:d {:e "bar"}}} (second result))))) (t/deftest test-single-validators (let [result1 (st/validate-single 2 st/number) result2 (st/validate-single nil st/number) result3 (st/validate-single nil [st/required st/number])] (t/is (= [nil 2] result1)) (t/is (= [nil nil] result2)) (t/is (= ["this field is mandatory" nil] result3)))) (t/deftest test-parametric-validators (let [result1 (st/validate {:name "foo"} {:name [[st/min-count 4]]}) result2 (st/validate {:name "bar"} {:name [[st/max-count 2]]})] (t/is (= {:name "less than the minimum 4"} (first result1))) (t/is (= {:name "longer than the maximum 2"} (first result2))))) (t/deftest test-simple-validators-with-vector-schema (let [scheme [[:max st/number] [:scope st/string]] input {:scope "foobar" :max "d"} errors {:max "must be a number"} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:scope "foobar"} (second result))))) (t/deftest test-simple-validators-with-translate (let [scheme [[:max st/number] [:scope st/string]] input {:scope "foobar" :max "d"} errors {:max "a"} result (st/validate input scheme {:translate (constantly "a")})] (t/is (= errors (first result))) (t/is (= {:scope "foobar"} (second result))))) (t/deftest test-dependent-validators-1 (let [scheme [[:password1 st/string] [:password2 [st/identical-to :password1]]] input {:password1 "<PASSWORD>" :password2 "<PASSWORD>."} errors {:password2 "does not match"} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:password1 "<PASSWORD>"} (second result))))) (t/deftest test-dependent-validators-2 (let [scheme [[:password1 st/string] [:password2 [st/identical-to :password1]]] input {:password1 "<PASSWORD>" :password2 "<PASSWORD>"} result (st/validate input scheme)] (t/is (= nil (first result))) (t/is (= {:password1 "<PASSWORD>" :password2 "<PASSWORD>"} (second result))))) (t/deftest test-multiple-validators (let [scheme {:max [st/required st/number] :scope st/string} input {:scope "foobar"} errors {:max "this field is mandatory"} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:scope "foobar"} (second result))))) (t/deftest test-validation-with-coersion (let [scheme {:max st/integer-str :scope st/string} input {:max "2" :scope "foobar"} result (st/validate input scheme)] (t/is (= nil (first result))) (t/is (= {:max 2 :scope "foobar"} (second result))))) (t/deftest test-validation-with-custom-coersion (let [scheme {:max [[st/number-str :coerce (constantly :foo)]] :scope st/string} input {:max "2" :scope "foobar"} result (st/validate input scheme)] (t/is (= nil (first result))) (t/is (= {:max :foo :scope "foobar"} (second result))))) (t/deftest test-validation-with-custom-message (let [scheme {:max [[st/number-str :message "custom msg"]] :scope st/string} input {:max "g" :scope "foobar"} errors {:max "custom msg"} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:scope "foobar"} (second result))))) (t/deftest test-coersion-with-valid-values (let [scheme {:a st/number-str :b st/integer-str} input {:a 2.3 :b 3.3} [errors data] (st/validate input scheme)] (t/is (= {:a 2.3 :b 3} data)))) (t/deftest test-validation-nested-data-in-a-vector (let [scheme {:a [st/vector [st/every number?]]} input1 {:a [1 2 3 4]} input2 {:a [1 2 3 4 "a"]} [errors1 data1] (st/validate input1 scheme) [errors2 data2] (st/validate input2 scheme)] (t/is (= data1 input1)) (t/is (= errors1 nil)) (t/is (= data2 {})) (t/is (= errors2 {:a "must match the predicate"})))) (t/deftest test-in-range-validator (t/is (= {:age "not in range 18 and 26"} (-> {:age 17} (st/validate {:age [[st/in-range 18 26]]}) first)))) (t/deftest test-honor-nested-data (let [scheme {[:a :b] [st/required st/string [st/min-count 2 :message "foobar"] [st/max-count 5]]} input1 {:a {:b "abcd"}} input2 {:a {:b "abcdefgh"}} input3 {:a {:b "a"}} [errors1 data1] (st/validate input1 scheme) [errors2 data2] (st/validate input2 scheme) [errors3 data3] (st/validate input3 scheme)] (t/is (= data1 input1)) (t/is (= errors1 nil)) (t/is (= data2 {})) (t/is (= errors2 {:a {:b "longer than the maximum 5"}})) (t/is (= data3 {})) (t/is (= errors3 {:a {:b "foobar"}})))) ;; --- Entry point #?(:cljs (do (enable-console-print!) (set! *main-cli-fn* #(t/run-tests)))) #?(:cljs (defmethod t/report [:cljs.test/default :end-run-tests] [m] (if (t/successful? m) (set! (.-exitCode js/process) 0) (set! (.-exitCode js/process) 1))))
true
(ns struct.tests (:require #?(:cljs [cljs.test :as t] :clj [clojure.test :as t]) [struct.core :as st])) ;; --- Tests (t/deftest test-optional-validators (let [scheme {:max st/number :scope st/string} input {:scope "foobar"} result (st/validate input scheme)] (t/is (= nil (first result))) (t/is (= input (second result))))) (t/deftest test-simple-validators (let [scheme {:max st/number :scope st/string} input {:scope "foobar" :max "d"} errors {:max "must be a number"} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:scope "foobar"} (second result))))) (t/deftest test-neested-validators (let [scheme {[:a :b] st/number [:c :d :e] st/string} input {:a {:b "foo"} :c {:d {:e "bar"}}} errors {:a {:b "must be a number"}} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:c {:d {:e "bar"}}} (second result))))) (t/deftest test-single-validators (let [result1 (st/validate-single 2 st/number) result2 (st/validate-single nil st/number) result3 (st/validate-single nil [st/required st/number])] (t/is (= [nil 2] result1)) (t/is (= [nil nil] result2)) (t/is (= ["this field is mandatory" nil] result3)))) (t/deftest test-parametric-validators (let [result1 (st/validate {:name "foo"} {:name [[st/min-count 4]]}) result2 (st/validate {:name "bar"} {:name [[st/max-count 2]]})] (t/is (= {:name "less than the minimum 4"} (first result1))) (t/is (= {:name "longer than the maximum 2"} (first result2))))) (t/deftest test-simple-validators-with-vector-schema (let [scheme [[:max st/number] [:scope st/string]] input {:scope "foobar" :max "d"} errors {:max "must be a number"} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:scope "foobar"} (second result))))) (t/deftest test-simple-validators-with-translate (let [scheme [[:max st/number] [:scope st/string]] input {:scope "foobar" :max "d"} errors {:max "a"} result (st/validate input scheme {:translate (constantly "a")})] (t/is (= errors (first result))) (t/is (= {:scope "foobar"} (second result))))) (t/deftest test-dependent-validators-1 (let [scheme [[:password1 st/string] [:password2 [st/identical-to :password1]]] input {:password1 "PI:PASSWORD:<PASSWORD>END_PI" :password2 "PI:PASSWORD:<PASSWORD>END_PI."} errors {:password2 "does not match"} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:password1 "PI:PASSWORD:<PASSWORD>END_PI"} (second result))))) (t/deftest test-dependent-validators-2 (let [scheme [[:password1 st/string] [:password2 [st/identical-to :password1]]] input {:password1 "PI:PASSWORD:<PASSWORD>END_PI" :password2 "PI:PASSWORD:<PASSWORD>END_PI"} result (st/validate input scheme)] (t/is (= nil (first result))) (t/is (= {:password1 "PI:PASSWORD:<PASSWORD>END_PI" :password2 "PI:PASSWORD:<PASSWORD>END_PI"} (second result))))) (t/deftest test-multiple-validators (let [scheme {:max [st/required st/number] :scope st/string} input {:scope "foobar"} errors {:max "this field is mandatory"} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:scope "foobar"} (second result))))) (t/deftest test-validation-with-coersion (let [scheme {:max st/integer-str :scope st/string} input {:max "2" :scope "foobar"} result (st/validate input scheme)] (t/is (= nil (first result))) (t/is (= {:max 2 :scope "foobar"} (second result))))) (t/deftest test-validation-with-custom-coersion (let [scheme {:max [[st/number-str :coerce (constantly :foo)]] :scope st/string} input {:max "2" :scope "foobar"} result (st/validate input scheme)] (t/is (= nil (first result))) (t/is (= {:max :foo :scope "foobar"} (second result))))) (t/deftest test-validation-with-custom-message (let [scheme {:max [[st/number-str :message "custom msg"]] :scope st/string} input {:max "g" :scope "foobar"} errors {:max "custom msg"} result (st/validate input scheme)] (t/is (= errors (first result))) (t/is (= {:scope "foobar"} (second result))))) (t/deftest test-coersion-with-valid-values (let [scheme {:a st/number-str :b st/integer-str} input {:a 2.3 :b 3.3} [errors data] (st/validate input scheme)] (t/is (= {:a 2.3 :b 3} data)))) (t/deftest test-validation-nested-data-in-a-vector (let [scheme {:a [st/vector [st/every number?]]} input1 {:a [1 2 3 4]} input2 {:a [1 2 3 4 "a"]} [errors1 data1] (st/validate input1 scheme) [errors2 data2] (st/validate input2 scheme)] (t/is (= data1 input1)) (t/is (= errors1 nil)) (t/is (= data2 {})) (t/is (= errors2 {:a "must match the predicate"})))) (t/deftest test-in-range-validator (t/is (= {:age "not in range 18 and 26"} (-> {:age 17} (st/validate {:age [[st/in-range 18 26]]}) first)))) (t/deftest test-honor-nested-data (let [scheme {[:a :b] [st/required st/string [st/min-count 2 :message "foobar"] [st/max-count 5]]} input1 {:a {:b "abcd"}} input2 {:a {:b "abcdefgh"}} input3 {:a {:b "a"}} [errors1 data1] (st/validate input1 scheme) [errors2 data2] (st/validate input2 scheme) [errors3 data3] (st/validate input3 scheme)] (t/is (= data1 input1)) (t/is (= errors1 nil)) (t/is (= data2 {})) (t/is (= errors2 {:a {:b "longer than the maximum 5"}})) (t/is (= data3 {})) (t/is (= errors3 {:a {:b "foobar"}})))) ;; --- Entry point #?(:cljs (do (enable-console-print!) (set! *main-cli-fn* #(t/run-tests)))) #?(:cljs (defmethod t/report [:cljs.test/default :end-run-tests] [m] (if (t/successful? m) (set! (.-exitCode js/process) 0) (set! (.-exitCode js/process) 1))))
[ { "context": "s \"a.nav-link\" tab)\n {:key (str \"a-\" id)\n :data-toggle \"tab\"\n :href ", "end": 3698, "score": 0.6919513940811157, "start": 3698, "tag": "KEY", "value": "" }, { "context": "button.btn.btn-secondary\n {:key (str \"b-\" id)\n :on-click (close-tab id)}\n \"X\"]]", "end": 3900, "score": 0.6494930386543274, "start": 3894, "tag": "KEY", "value": "b-\" id" } ]
src/reddit_viewer/core.cljs
gordielsky/reddit-api
0
(ns reddit-viewer.core (:require [reagent.core :as r] [reddit-viewer.chart :as chart] [reddit-viewer.controllers :as controllers] [re-frame.core :as rf] [clojure.string :as string])) ;; ------------------------- ;; Views (defn display-post [{:keys [permalink subreddit title score url]}] [:div.card.m-2 [:div.card-block [:h4.card-title [:a {:href (str "https://reddit.com" permalink)} title " "]] [:div [:span.badge.badge-info {:color "info"} "Sweet sweet " subreddit " Karma: " score]] [:img {:width "300px" :src url}]]]) (defn display-posts [post-array] (let [posts (take @(rf/subscribe [:get-num-posts]) post-array)] (let [subreddit @(rf/subscribe [:get-subreddit @(rf/subscribe [:get-active-tab-id])])] (cond (not (empty? posts)) [:div (for [posts-row (partition-all 3 posts)] ^{:key posts-row} [:div.row (for [post posts-row] ^{:key post} [:div.col-4 [display-post post]])])] (string/includes? subreddit " ") [:div (str "Enter the subreddit of your choice in the textbox!")] :else [:div (str "loading posts from r/" subreddit)])))) (defn sort-posts [title sort-key] [:button.btn.btn-secondary {:on-click #(rf/dispatch [:sort-posts sort-key @(rf/subscribe [:get-active-tab-id])])} (str "sort posts by " title)]) (defn navitem [title view id] [:li.nav-item {:class-name (when (= id view) "active")} [:a.nav-link {:href "#" :on-click #(rf/dispatch [:select-view id])} title]]) (defn navbar [view] [:nav.navbar.navbar-toggleable-md.navbar-light.bg-faded [:ul.navbar-nav.mr-auto.nav {:className "navbar-nav mr-auto"} [navitem "Posts" view :posts] [navitem "Chart" view :chart]]]) (defn num-post-button [num] [:button.btn.btn-secondary {:on-click #(rf/dispatch [:select-num-posts num])} (str num)]) (defn load-subreddit [id subreddit] (when (not (string/includes? subreddit " ")) (rf/dispatch [:load-posts id (str "https://www.reddit.com/r/" subreddit ".json?sort=new&limit=50")]))) (defn dispatch-subreddit [tab-id] (let [new-sub @(rf/subscribe [:get-textbox tab-id])] #(do (load-subreddit tab-id new-sub)) (rf/dispatch [:select-subreddit tab-id new-sub]))) (defn enter-text [] (let [active-id @(rf/subscribe [:get-active-tab-id])] [:input.m-2 {:type "text" :name :input-subreddit :value @(rf/subscribe [:get-textbox active-id]) :on-change #(do (rf/dispatch [:update-textbox active-id (-> % .-target .-value)])) :on-key-press #(do (when (= (.-charCode %) 13) (dispatch-subreddit active-id))) :style {:color "#292b2c" :backgroundColor "#ffffff" :border-color "#e3e5e8"}}])) (defn submit-subreddit [] (let [active-id @(rf/subscribe [:get-active-tab-id])] [:button.btn.btn-secondary {:on-click #(do (dispatch-subreddit active-id))} (str "Submit Subreddit")])) (defn create-tab [] #(rf/dispatch [:create-tab])) (defn change-tab [id] (rf/dispatch [:change-tab id])) (defn close-tab [id] #(rf/dispatch [:close-tab id])) (defn add-active-class [html-str tab] (if (:active tab) (keyword (str html-str ".active")) (keyword html-str))) (defn display-tab [tab-vector li-key] (let [tab (second tab-vector)] (let [id (first tab-vector)] [:div {:key (str "div-" (str id)) :style {:display "flex"}} [li-key {:key (str id) :on-click #(do (change-tab id))} [(add-active-class "a.nav-link" tab) {:key (str "a-" id) :data-toggle "tab" :href (str "#t" id) :role "tab"} (str (:subreddit tab))]] [:button.btn.btn-secondary {:key (str "b-" id) :on-click (close-tab id)} "X"]]))) (defn setup-tab-contents [tab-vector] (let [tab (second tab-vector)] #_(println "Tab:" tab-vector) (let [id (first tab-vector)] (let [subreddit (:subreddit tab)] [(add-active-class "div.tab-pane" tab) {:key id :id (str "t" id) :role "tabpanel"} [load-subreddit id subreddit]])))) (defn display-tabs [tabs] [:div {:style {:display "flex"}} [:ul.nav.nav-tabs {:key tabs :role "tablist" :id "navtabs"} (for [tab tabs] ^{:key tab} (display-tab tab "li.nav-item"))] [:button.btn.btn-secondary {:on-click (create-tab)} "+"]]) (defn display-tab-contents [tabs] [:div.tab-content {:key "content" :id "content"} (for [tab tabs] ^{:key tab} (setup-tab-contents tab))]) (defn home-page [] (let [tabs @(rf/subscribe [:get-tabs])] (let [view @(rf/subscribe [:view])] [:div [display-tabs tabs] [navbar view] [:div.card>div.card-block [:div.row [:div.col-4 [:div "Enter a subreddit: " [enter-text] [submit-subreddit]]] [:div.btn-group.col-4 [sort-posts "score" :score] [sort-posts "comments" :num_comments]] [:br] [:div.btn-group.col-4 [:h4.m-1 "Number of posts: "] [num-post-button 10] [num-post-button 25] [num-post-button 50]]] [display-tab-contents tabs] (case view :chart [chart/chart-posts-by-votes] :posts [display-posts @(rf/subscribe [:posts @(rf/subscribe [:get-active-tab-id])])] :no-tabs [:p "You have no tabs open. Click the '+' to create a new one!"] (println (str "view in home page:") view))]]))) ;; ------------------------- ;; Initialize app (defn mount-root [] (r/render [home-page] (.getElementById js/document "app"))) (defn init! [] (rf/dispatch-sync [:initialize-db]) (mount-root))
83381
(ns reddit-viewer.core (:require [reagent.core :as r] [reddit-viewer.chart :as chart] [reddit-viewer.controllers :as controllers] [re-frame.core :as rf] [clojure.string :as string])) ;; ------------------------- ;; Views (defn display-post [{:keys [permalink subreddit title score url]}] [:div.card.m-2 [:div.card-block [:h4.card-title [:a {:href (str "https://reddit.com" permalink)} title " "]] [:div [:span.badge.badge-info {:color "info"} "Sweet sweet " subreddit " Karma: " score]] [:img {:width "300px" :src url}]]]) (defn display-posts [post-array] (let [posts (take @(rf/subscribe [:get-num-posts]) post-array)] (let [subreddit @(rf/subscribe [:get-subreddit @(rf/subscribe [:get-active-tab-id])])] (cond (not (empty? posts)) [:div (for [posts-row (partition-all 3 posts)] ^{:key posts-row} [:div.row (for [post posts-row] ^{:key post} [:div.col-4 [display-post post]])])] (string/includes? subreddit " ") [:div (str "Enter the subreddit of your choice in the textbox!")] :else [:div (str "loading posts from r/" subreddit)])))) (defn sort-posts [title sort-key] [:button.btn.btn-secondary {:on-click #(rf/dispatch [:sort-posts sort-key @(rf/subscribe [:get-active-tab-id])])} (str "sort posts by " title)]) (defn navitem [title view id] [:li.nav-item {:class-name (when (= id view) "active")} [:a.nav-link {:href "#" :on-click #(rf/dispatch [:select-view id])} title]]) (defn navbar [view] [:nav.navbar.navbar-toggleable-md.navbar-light.bg-faded [:ul.navbar-nav.mr-auto.nav {:className "navbar-nav mr-auto"} [navitem "Posts" view :posts] [navitem "Chart" view :chart]]]) (defn num-post-button [num] [:button.btn.btn-secondary {:on-click #(rf/dispatch [:select-num-posts num])} (str num)]) (defn load-subreddit [id subreddit] (when (not (string/includes? subreddit " ")) (rf/dispatch [:load-posts id (str "https://www.reddit.com/r/" subreddit ".json?sort=new&limit=50")]))) (defn dispatch-subreddit [tab-id] (let [new-sub @(rf/subscribe [:get-textbox tab-id])] #(do (load-subreddit tab-id new-sub)) (rf/dispatch [:select-subreddit tab-id new-sub]))) (defn enter-text [] (let [active-id @(rf/subscribe [:get-active-tab-id])] [:input.m-2 {:type "text" :name :input-subreddit :value @(rf/subscribe [:get-textbox active-id]) :on-change #(do (rf/dispatch [:update-textbox active-id (-> % .-target .-value)])) :on-key-press #(do (when (= (.-charCode %) 13) (dispatch-subreddit active-id))) :style {:color "#292b2c" :backgroundColor "#ffffff" :border-color "#e3e5e8"}}])) (defn submit-subreddit [] (let [active-id @(rf/subscribe [:get-active-tab-id])] [:button.btn.btn-secondary {:on-click #(do (dispatch-subreddit active-id))} (str "Submit Subreddit")])) (defn create-tab [] #(rf/dispatch [:create-tab])) (defn change-tab [id] (rf/dispatch [:change-tab id])) (defn close-tab [id] #(rf/dispatch [:close-tab id])) (defn add-active-class [html-str tab] (if (:active tab) (keyword (str html-str ".active")) (keyword html-str))) (defn display-tab [tab-vector li-key] (let [tab (second tab-vector)] (let [id (first tab-vector)] [:div {:key (str "div-" (str id)) :style {:display "flex"}} [li-key {:key (str id) :on-click #(do (change-tab id))} [(add-active-class "a.nav-link" tab) {:key (str "a<KEY>-" id) :data-toggle "tab" :href (str "#t" id) :role "tab"} (str (:subreddit tab))]] [:button.btn.btn-secondary {:key (str "<KEY>) :on-click (close-tab id)} "X"]]))) (defn setup-tab-contents [tab-vector] (let [tab (second tab-vector)] #_(println "Tab:" tab-vector) (let [id (first tab-vector)] (let [subreddit (:subreddit tab)] [(add-active-class "div.tab-pane" tab) {:key id :id (str "t" id) :role "tabpanel"} [load-subreddit id subreddit]])))) (defn display-tabs [tabs] [:div {:style {:display "flex"}} [:ul.nav.nav-tabs {:key tabs :role "tablist" :id "navtabs"} (for [tab tabs] ^{:key tab} (display-tab tab "li.nav-item"))] [:button.btn.btn-secondary {:on-click (create-tab)} "+"]]) (defn display-tab-contents [tabs] [:div.tab-content {:key "content" :id "content"} (for [tab tabs] ^{:key tab} (setup-tab-contents tab))]) (defn home-page [] (let [tabs @(rf/subscribe [:get-tabs])] (let [view @(rf/subscribe [:view])] [:div [display-tabs tabs] [navbar view] [:div.card>div.card-block [:div.row [:div.col-4 [:div "Enter a subreddit: " [enter-text] [submit-subreddit]]] [:div.btn-group.col-4 [sort-posts "score" :score] [sort-posts "comments" :num_comments]] [:br] [:div.btn-group.col-4 [:h4.m-1 "Number of posts: "] [num-post-button 10] [num-post-button 25] [num-post-button 50]]] [display-tab-contents tabs] (case view :chart [chart/chart-posts-by-votes] :posts [display-posts @(rf/subscribe [:posts @(rf/subscribe [:get-active-tab-id])])] :no-tabs [:p "You have no tabs open. Click the '+' to create a new one!"] (println (str "view in home page:") view))]]))) ;; ------------------------- ;; Initialize app (defn mount-root [] (r/render [home-page] (.getElementById js/document "app"))) (defn init! [] (rf/dispatch-sync [:initialize-db]) (mount-root))
true
(ns reddit-viewer.core (:require [reagent.core :as r] [reddit-viewer.chart :as chart] [reddit-viewer.controllers :as controllers] [re-frame.core :as rf] [clojure.string :as string])) ;; ------------------------- ;; Views (defn display-post [{:keys [permalink subreddit title score url]}] [:div.card.m-2 [:div.card-block [:h4.card-title [:a {:href (str "https://reddit.com" permalink)} title " "]] [:div [:span.badge.badge-info {:color "info"} "Sweet sweet " subreddit " Karma: " score]] [:img {:width "300px" :src url}]]]) (defn display-posts [post-array] (let [posts (take @(rf/subscribe [:get-num-posts]) post-array)] (let [subreddit @(rf/subscribe [:get-subreddit @(rf/subscribe [:get-active-tab-id])])] (cond (not (empty? posts)) [:div (for [posts-row (partition-all 3 posts)] ^{:key posts-row} [:div.row (for [post posts-row] ^{:key post} [:div.col-4 [display-post post]])])] (string/includes? subreddit " ") [:div (str "Enter the subreddit of your choice in the textbox!")] :else [:div (str "loading posts from r/" subreddit)])))) (defn sort-posts [title sort-key] [:button.btn.btn-secondary {:on-click #(rf/dispatch [:sort-posts sort-key @(rf/subscribe [:get-active-tab-id])])} (str "sort posts by " title)]) (defn navitem [title view id] [:li.nav-item {:class-name (when (= id view) "active")} [:a.nav-link {:href "#" :on-click #(rf/dispatch [:select-view id])} title]]) (defn navbar [view] [:nav.navbar.navbar-toggleable-md.navbar-light.bg-faded [:ul.navbar-nav.mr-auto.nav {:className "navbar-nav mr-auto"} [navitem "Posts" view :posts] [navitem "Chart" view :chart]]]) (defn num-post-button [num] [:button.btn.btn-secondary {:on-click #(rf/dispatch [:select-num-posts num])} (str num)]) (defn load-subreddit [id subreddit] (when (not (string/includes? subreddit " ")) (rf/dispatch [:load-posts id (str "https://www.reddit.com/r/" subreddit ".json?sort=new&limit=50")]))) (defn dispatch-subreddit [tab-id] (let [new-sub @(rf/subscribe [:get-textbox tab-id])] #(do (load-subreddit tab-id new-sub)) (rf/dispatch [:select-subreddit tab-id new-sub]))) (defn enter-text [] (let [active-id @(rf/subscribe [:get-active-tab-id])] [:input.m-2 {:type "text" :name :input-subreddit :value @(rf/subscribe [:get-textbox active-id]) :on-change #(do (rf/dispatch [:update-textbox active-id (-> % .-target .-value)])) :on-key-press #(do (when (= (.-charCode %) 13) (dispatch-subreddit active-id))) :style {:color "#292b2c" :backgroundColor "#ffffff" :border-color "#e3e5e8"}}])) (defn submit-subreddit [] (let [active-id @(rf/subscribe [:get-active-tab-id])] [:button.btn.btn-secondary {:on-click #(do (dispatch-subreddit active-id))} (str "Submit Subreddit")])) (defn create-tab [] #(rf/dispatch [:create-tab])) (defn change-tab [id] (rf/dispatch [:change-tab id])) (defn close-tab [id] #(rf/dispatch [:close-tab id])) (defn add-active-class [html-str tab] (if (:active tab) (keyword (str html-str ".active")) (keyword html-str))) (defn display-tab [tab-vector li-key] (let [tab (second tab-vector)] (let [id (first tab-vector)] [:div {:key (str "div-" (str id)) :style {:display "flex"}} [li-key {:key (str id) :on-click #(do (change-tab id))} [(add-active-class "a.nav-link" tab) {:key (str "aPI:KEY:<KEY>END_PI-" id) :data-toggle "tab" :href (str "#t" id) :role "tab"} (str (:subreddit tab))]] [:button.btn.btn-secondary {:key (str "PI:KEY:<KEY>END_PI) :on-click (close-tab id)} "X"]]))) (defn setup-tab-contents [tab-vector] (let [tab (second tab-vector)] #_(println "Tab:" tab-vector) (let [id (first tab-vector)] (let [subreddit (:subreddit tab)] [(add-active-class "div.tab-pane" tab) {:key id :id (str "t" id) :role "tabpanel"} [load-subreddit id subreddit]])))) (defn display-tabs [tabs] [:div {:style {:display "flex"}} [:ul.nav.nav-tabs {:key tabs :role "tablist" :id "navtabs"} (for [tab tabs] ^{:key tab} (display-tab tab "li.nav-item"))] [:button.btn.btn-secondary {:on-click (create-tab)} "+"]]) (defn display-tab-contents [tabs] [:div.tab-content {:key "content" :id "content"} (for [tab tabs] ^{:key tab} (setup-tab-contents tab))]) (defn home-page [] (let [tabs @(rf/subscribe [:get-tabs])] (let [view @(rf/subscribe [:view])] [:div [display-tabs tabs] [navbar view] [:div.card>div.card-block [:div.row [:div.col-4 [:div "Enter a subreddit: " [enter-text] [submit-subreddit]]] [:div.btn-group.col-4 [sort-posts "score" :score] [sort-posts "comments" :num_comments]] [:br] [:div.btn-group.col-4 [:h4.m-1 "Number of posts: "] [num-post-button 10] [num-post-button 25] [num-post-button 50]]] [display-tab-contents tabs] (case view :chart [chart/chart-posts-by-votes] :posts [display-posts @(rf/subscribe [:posts @(rf/subscribe [:get-active-tab-id])])] :no-tabs [:p "You have no tabs open. Click the '+' to create a new one!"] (println (str "view in home page:") view))]]))) ;; ------------------------- ;; Initialize app (defn mount-root [] (r/render [home-page] (.getElementById js/document "app"))) (defn init! [] (rf/dispatch-sync [:initialize-db]) (mount-root))
[ { "context": " [16 6 \"Mile\" \"time\"]\n ", "end": 2518, "score": 0.9201272130012512, "start": 2514, "tag": "NAME", "value": "Mile" }, { "context": " [17 7 \"Murph\" \"time\"]\n ", "end": 2587, "score": 0.998755931854248, "start": 2582, "tag": "NAME", "value": "Murph" }, { "context": " [18 7 \"Fran\" \"time\"]\n ", "end": 2655, "score": 0.9982270002365112, "start": 2651, "tag": "NAME", "value": "Fran" }, { "context": " [19 7 \"Grace\" \"time\"]\n ", "end": 2724, "score": 0.9991554021835327, "start": 2719, "tag": "NAME", "value": "Grace" }, { "context": " [20 7 \"Isabel\" \"time\"]\n ", "end": 2794, "score": 0.9995207786560059, "start": 2788, "tag": "NAME", "value": "Isabel" } ]
src/prs/db/core.clj
robmerrell/prs
0
(ns prs.db.core (:require [mount.core :as mnt] [migratus.core :as migratus] [prs.config :as config] [prs.db.movements :as movements-db] [prs.db.categories :as categories-db])) (defn connect [] {:classname "org.sqlite.JDBC" :subprotocol "sqlite" :subname (config/database-name)}) (defn disconnect [conn] (println "disconnecting from db")) (mnt/defstate conn :start (connect) :stop (disconnect conn)) (defn migrate "Set up and initialize Migratus. Run migrations from this namespace" [] (-> (config/migrations) (assoc :db (connect)) (migratus/migrate))) (defn new-migration "Create a new migration file" [name] (migratus/create (config/migrations) name)) (defn reseed "Clean categories and movements and reseed them with data" [] (categories-db/remove-all conn) (movements-db/remove-all conn) (categories-db/batch-insert conn {:categories [[1 "Bench"] [2 "Clean"] [3 "Press/Jerk"] [4 "Snatch"] [5 "Squat"] [6 "Cardio"] [7 "Hero"]]}) (movements-db/batch-insert conn {:movements [[1 1 "Standard Grip" "weight"] [2 2 "Clean" "weight"] [3 2 "Clean & Jerk" "weight"] [4 2 "Power Clean" "weight"] [5 2 "Cluster" "weight"] [6 3 "Push Press" "weight"] [7 3 "Push Jerk" "weight"] [8 3 "Split Jerk" "weight"] [9 3 "Shoulder Press" "weight"] [10 4 "Snatch" "weight"] [11 4 "Power Snatch" "weight"] [12 5 "Back Squat" "weight"] [13 5 "Front Squat" "weight"] [14 5 "Overhead Squat" "weight"] [15 6 "5k Row" "time"] [16 6 "Mile" "time"] [17 7 "Murph" "time"] [18 7 "Fran" "time"] [19 7 "Grace" "time"] [20 7 "Isabel" "time"] [21 7 "DT" "time"]]}))
78177
(ns prs.db.core (:require [mount.core :as mnt] [migratus.core :as migratus] [prs.config :as config] [prs.db.movements :as movements-db] [prs.db.categories :as categories-db])) (defn connect [] {:classname "org.sqlite.JDBC" :subprotocol "sqlite" :subname (config/database-name)}) (defn disconnect [conn] (println "disconnecting from db")) (mnt/defstate conn :start (connect) :stop (disconnect conn)) (defn migrate "Set up and initialize Migratus. Run migrations from this namespace" [] (-> (config/migrations) (assoc :db (connect)) (migratus/migrate))) (defn new-migration "Create a new migration file" [name] (migratus/create (config/migrations) name)) (defn reseed "Clean categories and movements and reseed them with data" [] (categories-db/remove-all conn) (movements-db/remove-all conn) (categories-db/batch-insert conn {:categories [[1 "Bench"] [2 "Clean"] [3 "Press/Jerk"] [4 "Snatch"] [5 "Squat"] [6 "Cardio"] [7 "Hero"]]}) (movements-db/batch-insert conn {:movements [[1 1 "Standard Grip" "weight"] [2 2 "Clean" "weight"] [3 2 "Clean & Jerk" "weight"] [4 2 "Power Clean" "weight"] [5 2 "Cluster" "weight"] [6 3 "Push Press" "weight"] [7 3 "Push Jerk" "weight"] [8 3 "Split Jerk" "weight"] [9 3 "Shoulder Press" "weight"] [10 4 "Snatch" "weight"] [11 4 "Power Snatch" "weight"] [12 5 "Back Squat" "weight"] [13 5 "Front Squat" "weight"] [14 5 "Overhead Squat" "weight"] [15 6 "5k Row" "time"] [16 6 "<NAME>" "time"] [17 7 "<NAME>" "time"] [18 7 "<NAME>" "time"] [19 7 "<NAME>" "time"] [20 7 "<NAME>" "time"] [21 7 "DT" "time"]]}))
true
(ns prs.db.core (:require [mount.core :as mnt] [migratus.core :as migratus] [prs.config :as config] [prs.db.movements :as movements-db] [prs.db.categories :as categories-db])) (defn connect [] {:classname "org.sqlite.JDBC" :subprotocol "sqlite" :subname (config/database-name)}) (defn disconnect [conn] (println "disconnecting from db")) (mnt/defstate conn :start (connect) :stop (disconnect conn)) (defn migrate "Set up and initialize Migratus. Run migrations from this namespace" [] (-> (config/migrations) (assoc :db (connect)) (migratus/migrate))) (defn new-migration "Create a new migration file" [name] (migratus/create (config/migrations) name)) (defn reseed "Clean categories and movements and reseed them with data" [] (categories-db/remove-all conn) (movements-db/remove-all conn) (categories-db/batch-insert conn {:categories [[1 "Bench"] [2 "Clean"] [3 "Press/Jerk"] [4 "Snatch"] [5 "Squat"] [6 "Cardio"] [7 "Hero"]]}) (movements-db/batch-insert conn {:movements [[1 1 "Standard Grip" "weight"] [2 2 "Clean" "weight"] [3 2 "Clean & Jerk" "weight"] [4 2 "Power Clean" "weight"] [5 2 "Cluster" "weight"] [6 3 "Push Press" "weight"] [7 3 "Push Jerk" "weight"] [8 3 "Split Jerk" "weight"] [9 3 "Shoulder Press" "weight"] [10 4 "Snatch" "weight"] [11 4 "Power Snatch" "weight"] [12 5 "Back Squat" "weight"] [13 5 "Front Squat" "weight"] [14 5 "Overhead Squat" "weight"] [15 6 "5k Row" "time"] [16 6 "PI:NAME:<NAME>END_PI" "time"] [17 7 "PI:NAME:<NAME>END_PI" "time"] [18 7 "PI:NAME:<NAME>END_PI" "time"] [19 7 "PI:NAME:<NAME>END_PI" "time"] [20 7 "PI:NAME:<NAME>END_PI" "time"] [21 7 "DT" "time"]]}))
[ { "context": "-player 0\n :players [\n {:name \"Bot\" :active? true :round 0 :total 0}\n ", "end": 117, "score": 0.5115747451782227, "start": 114, "tag": "NAME", "value": "Bot" }, { "context": "true :round 0 :total 0}\n {:name \"Player\" :active? false :round 0 :total 0}\n ]})\n", "end": 184, "score": 0.7320107817649841, "start": 178, "tag": "NAME", "value": "Player" } ]
src/nasty_one/db.cljs
fnumatic/nasty-number-one
0
(ns nasty-one.db) (def default-db {:max-value 200 :current-player 0 :players [ {:name "Bot" :active? true :round 0 :total 0} {:name "Player" :active? false :round 0 :total 0} ]})
109663
(ns nasty-one.db) (def default-db {:max-value 200 :current-player 0 :players [ {:name "<NAME>" :active? true :round 0 :total 0} {:name "<NAME>" :active? false :round 0 :total 0} ]})
true
(ns nasty-one.db) (def default-db {:max-value 200 :current-player 0 :players [ {:name "PI:NAME:<NAME>END_PI" :active? true :round 0 :total 0} {:name "PI:NAME:<NAME>END_PI" :active? false :round 0 :total 0} ]})
[ { "context": "; Copyright (c) Anna Shchiptsova, IIASA. All rights reserved.\r\n; The use and dis", "end": 34, "score": 0.9998898506164551, "start": 18, "tag": "NAME", "value": "Anna Shchiptsova" }, { "context": " \"Wraps reading of file content.\"\r\n :author \"Anna Shchiptsova\"}\r\n utilities-clj.reader\r\n (:require [clojure-cs", "end": 528, "score": 0.9998960494995117, "start": 512, "tag": "NAME", "value": "Anna Shchiptsova" } ]
src/utilities_clj/reader.clj
shchipts/utilities-clj
0
; Copyright (c) Anna Shchiptsova, IIASA. All rights reserved. ; The use and distribution terms for this software are covered by the ; MIT License (http://opensource.org/licenses/MIT) ; which can be found in the file LICENSE 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 "Wraps reading of file content." :author "Anna Shchiptsova"} utilities-clj.reader (:require [clojure-csv.core :as csv] [clojure.edn :as edn] [clojure.java.io :as io] [clojure.xml :as xml])) (defn read-file "Reads entire text file and returns text by lines." [file-name] (with-open [rdr (io/reader file-name)] (doall (line-seq rdr)))) (defn read-xml-file "Reads xml file and returns its content." [path] (xml/parse (io/file path))) (defn read-csv "Reads entire csv file and return values by rows." [path] (let [csv-data (slurp path) csv-file (csv/parse-csv csv-data)] csv-file)) ;; from https://clojuredocs.org/clojure.edn/read (defn load-edn "Loads edn file and returns its content." [source] (try (with-open [r (io/reader source)] (edn/read (java.io.PushbackReader. r))) (catch java.io.IOException e (printf "Couldn't open '%s': %s\n" source (.getMessage e))) (catch RuntimeException e (printf "Error parsing edn file '%s': %s\n" source (.getMessage e)))))
80060
; Copyright (c) <NAME>, IIASA. All rights reserved. ; The use and distribution terms for this software are covered by the ; MIT License (http://opensource.org/licenses/MIT) ; which can be found in the file LICENSE 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 "Wraps reading of file content." :author "<NAME>"} utilities-clj.reader (:require [clojure-csv.core :as csv] [clojure.edn :as edn] [clojure.java.io :as io] [clojure.xml :as xml])) (defn read-file "Reads entire text file and returns text by lines." [file-name] (with-open [rdr (io/reader file-name)] (doall (line-seq rdr)))) (defn read-xml-file "Reads xml file and returns its content." [path] (xml/parse (io/file path))) (defn read-csv "Reads entire csv file and return values by rows." [path] (let [csv-data (slurp path) csv-file (csv/parse-csv csv-data)] csv-file)) ;; from https://clojuredocs.org/clojure.edn/read (defn load-edn "Loads edn file and returns its content." [source] (try (with-open [r (io/reader source)] (edn/read (java.io.PushbackReader. r))) (catch java.io.IOException e (printf "Couldn't open '%s': %s\n" source (.getMessage e))) (catch RuntimeException e (printf "Error parsing edn file '%s': %s\n" source (.getMessage e)))))
true
; Copyright (c) PI:NAME:<NAME>END_PI, IIASA. All rights reserved. ; The use and distribution terms for this software are covered by the ; MIT License (http://opensource.org/licenses/MIT) ; which can be found in the file LICENSE 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 "Wraps reading of file content." :author "PI:NAME:<NAME>END_PI"} utilities-clj.reader (:require [clojure-csv.core :as csv] [clojure.edn :as edn] [clojure.java.io :as io] [clojure.xml :as xml])) (defn read-file "Reads entire text file and returns text by lines." [file-name] (with-open [rdr (io/reader file-name)] (doall (line-seq rdr)))) (defn read-xml-file "Reads xml file and returns its content." [path] (xml/parse (io/file path))) (defn read-csv "Reads entire csv file and return values by rows." [path] (let [csv-data (slurp path) csv-file (csv/parse-csv csv-data)] csv-file)) ;; from https://clojuredocs.org/clojure.edn/read (defn load-edn "Loads edn file and returns its content." [source] (try (with-open [r (io/reader source)] (edn/read (java.io.PushbackReader. r))) (catch java.io.IOException e (printf "Couldn't open '%s': %s\n" source (.getMessage e))) (catch RuntimeException e (printf "Error parsing edn file '%s': %s\n" source (.getMessage e)))))
[ { "context": "ptions {:token (echo-util/login (system/context) \"user1\")}\n coll1 (data-core/ingest-umm-spec-colle", "end": 824, "score": 0.8095625638961792, "start": 819, "tag": "USERNAME", "value": "user1" }, { "context": "ptions {:token (echo-util/login (system/context) \"user1\")}\n coll (data-core/ingest-concept-with-", "end": 14889, "score": 0.9167921543121338, "start": 14884, "tag": "USERNAME", "value": "user1" }, { "context": " :format-key :dif10})\n granule (data-core/ingest-concept-wit", "end": 20174, "score": 0.6240878105163574, "start": 20172, "tag": "KEY", "value": "10" }, { "context": "ptions {:token (echo-util/login (system/context) \"user1\")}\n coll (data-core/ingest-concept-with-", "end": 21460, "score": 0.5955884456634521, "start": 21455, "tag": "USERNAME", "value": "user1" } ]
system-int-test/test/cmr/system_int_test/ingest/granule_bulk_update/granule_bulk_update_test.clj
sunshinekyo/Common-Metadata-Repository
0
(ns cmr.system-int-test.ingest.granule-bulk-update.granule-bulk-update-test "CMR bulk update. Test the actual update " (:require [clojure.java.io :as io] [clojure.string :as string] [clojure.test :refer :all] [cmr.mock-echo.client.echo-util :as echo-util] [cmr.system-int-test.data2.core :as data-core] [cmr.system-int-test.data2.granule :as granule] [cmr.system-int-test.data2.umm-spec-collection :as data-umm-c] [cmr.system-int-test.system :as system] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.metadata-db-util :as mdb])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1"})) (deftest bulk-granule-update-test (let [bulk-update-options {:token (echo-util/login (system/context) "user1")} coll1 (data-core/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "coll1" :ShortName "short1" :Version "V1" :native-id "native1"})) gran1 (ingest/ingest-concept (data-core/item->concept (granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:native-id "gran-native1-1" :granule-ur "SC:AE_5DSno.002:30500511"}))) gran2 (ingest/ingest-concept (data-core/item->concept (granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:native-id "gran-native1-2" :granule-ur "SC:AE_5DSno.002:30500512"}))) ;; this granule will fail bulk update as it is in ISO-SMAP format gran3 (ingest/ingest-concept (data-core/item->concept (granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:native-id "gran-native1-3" :granule-ur "SC:AE_5DSno.002:30500513"}) :iso-smap)) ;; UMM-G granule gran4 (ingest/ingest-concept (data-core/item->concept (granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:native-id "gran-native1-4" :granule-ur "SC:AE_5DSno.002:30500514"}) :umm-json)) gran5 (ingest/ingest-concept (data-core/item->concept (granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:native-id "gran-native1-5" :granule-ur "SC:AE_5DSno.002:30500515"})))] (testing "OPeNDAP url granule bulk update" (testing "successful OPeNDAP url granule bulk update" (let [bulk-update {:name "add opendap links 1" :operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["SC:AE_5DSno.002:30500511" "https://url30500511"] ["SC:AE_5DSno.002:30500512" "https://url30500512"] ["SC:AE_5DSno.002:30500514" "https://url30500514"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "All granule updates completed successfully." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500514" :status "UPDATED"}] granule-statuses))))) (testing "failed OPeNDAP url granule bulk update" (let [bulk-update {:name "add opendap links 2" :operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["SC:AE_5DSno.002:30500513" "https://url30500513"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 1 FAILED out of 1 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500513" :status "FAILED" :status-message "Add OPeNDAP url is not supported for format [application/iso:smap+xml]"}] granule-statuses))))) (testing "partial successful OPeNDAP url granule bulk update" (let [bulk-update {:name "add opendap links 3" :operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["SC:AE_5DSno.002:30500511" "https://url30500511"] ["SC:AE_5DSno.002:30500512" "https://url30500512"] ["SC:non-existent-ur" "https://url30500513"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 1 FAILED and 2 UPDATED out of 3 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "UPDATED"} {:granule-ur "SC:non-existent-ur" :status "FAILED" :status-message (format "Granule UR [SC:non-existent-ur] in task-id [%s] does not exist." task-id)}] granule-statuses))))) (testing "invalid OPeNDAP url value in instruction" (let [bulk-update {:name "add opendap links 4" :operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["SC:AE_5DSno.002:30500511" "https://foo,https://bar,https://baz"] ["SC:AE_5DSno.002:30500512" "https://foo, https://bar"] ["SC:AE_5DSno.002:30500514" "https://opendap.sit.earthdata.nasa.gov/foo,https://opendap.earthdata.nasa.gov/bar"] ["SC:AE_5DSno.002:30500515" "s3://opendap.sit.earthdata.nasa.gov/foo"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 4 FAILED out of 4 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "FAILED" :status-message "Invalid URL value, no more than two urls can be provided: https://foo,https://bar,https://baz"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "FAILED" :status-message "Invalid URL value, no more than one on-prem OPeNDAP url can be provided: https://foo, https://bar"} {:granule-ur "SC:AE_5DSno.002:30500514" :status "FAILED" :status-message "Invalid URL value, no more than one Hyrax-in-the-cloud OPeNDAP url can be provided: https://opendap.sit.earthdata.nasa.gov/foo,https://opendap.earthdata.nasa.gov/bar"} {:granule-ur "SC:AE_5DSno.002:30500515" :status "FAILED" :status-message "OPeNDAP URL value cannot start with s3://, but was s3://opendap.sit.earthdata.nasa.gov/foo"}] granule-statuses)))))) (testing "S3 url granule bulk update" (testing "successful S3 url granule bulk update" (let [bulk-update {:name "add S3 links 1" :operation "UPDATE_FIELD" :update-field "S3Link" :updates [["SC:AE_5DSno.002:30500511" "s3://url30500511"] ["SC:AE_5DSno.002:30500512" "s3://url1, s3://url2,s3://url3"] ["SC:AE_5DSno.002:30500514" "s3://url30500514"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "All granule updates completed successfully." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500514" :status "UPDATED"}] granule-statuses))))) (testing "failed S3 link granule bulk update" (let [bulk-update {:name "add s3 links 2" :operation "UPDATE_FIELD" :update-field "S3Link" :updates [["SC:AE_5DSno.002:30500513" "s3://url30500513"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 1 FAILED out of 1 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500513" :status "FAILED" :status-message "Add s3 url is not supported for format [application/iso:smap+xml]"}] granule-statuses))))) (testing "partial successful S3 link granule bulk update" (let [bulk-update {:name "add s3 links 3" :operation "UPDATE_FIELD" :update-field "S3Link" :updates [["SC:AE_5DSno.002:30500511" "s3://url30500511"] ["SC:AE_5DSno.002:30500512" "s3://url30500512"] ["SC:non-existent-ur" "s3://url30500513"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 1 FAILED and 2 UPDATED out of 3 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "UPDATED"} {:granule-ur "SC:non-existent-ur" :status "FAILED" :status-message (format "Granule UR [SC:non-existent-ur] in task-id [%s] does not exist." task-id)}] granule-statuses))))) (testing "invalid S3 url value in instruction" (let [bulk-update {:name "add S3 links 4" :operation "UPDATE_FIELD" :update-field "S3Link" :updates [["SC:AE_5DSno.002:30500511" "https://foo"] ["SC:AE_5DSno.002:30500512" "s3://foo,S3://bar"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 2 FAILED out of 2 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "FAILED" :status-message "Invalid URL value, each S3 url must start with s3://, but was https://foo"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "FAILED" :status-message "Invalid URL value, each S3 url must start with s3://, but was S3://bar"}] granule-statuses)))))))) (deftest add-opendap-url "test adding OPeNDAP url with real granule file that is already in CMR code base" (testing "ECHO10 granule" (let [bulk-update-options {:token (echo-util/login (system/context) "user1")} coll (data-core/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-collection.xml" {:provider-id "PROV1" :concept-type :collection :native-id "OMSO2-collection" :format-key :dif10}) granule (data-core/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-granule.xml" {:provider-id "PROV1" :concept-type :granule :native-id "OMSO2-granule" :format-key :echo10}) {:keys [concept-id revision-id]} granule target-metadata (-> "CMR-4722/OMSO2.003-granule-opendap-url.xml" io/resource slurp) bulk-update {:operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["OMSO2.003:OMI-Aura_L2-OMSO2_2004m1001t2307-o01146_v003-2016m0615t191523.he5" "http://opendap-url.example.com"]]} {:keys [status] :as response} (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options)] (index/wait-until-indexed) (is (= 200 status)) (is (= target-metadata (:metadata (mdb/get-concept concept-id (inc revision-id))))))) (testing "UMM-G granule" (let [bulk-update-options {:token (echo-util/login (system/context) "user1")} coll (data-core/ingest-concept-with-metadata-file "umm-g-samples/Collection.json" {:provider-id "PROV1" :concept-type :collection :native-id "test-coll1" :format "application/vnd.nasa.cmr.umm+json;version=1.16"}) granule (data-core/ingest-concept-with-metadata-file "umm-g-samples/GranuleExample.json" {:provider-id "PROV1" :concept-type :granule :native-id "test-gran1" :format "application/vnd.nasa.cmr.umm+json;version=1.6"}) {:keys [concept-id revision-id]} granule bulk-update {:operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["Unique_Granule_UR_v1.6" "https://opendap.earthdata.nasa.gov/test-gran1"]]} {:keys [status task-id] :as response} (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options)] (index/wait-until-indexed) ;; verify the granule status is UPDATED (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "All granule updates completed successfully." status-message)) (is (= [{:granule-ur "Unique_Granule_UR_v1.6" :status "UPDATED"}] granule-statuses))) ;; verify the granule metadata is updated as expected (let [original-metadata (:metadata (mdb/get-concept concept-id revision-id)) updated-metadata (:metadata (mdb/get-concept concept-id (inc revision-id)))] ;; since the metadata will be returned in the latest UMM-G format, ;; we can't compare the whole metadata to an expected string. ;; We just verify the updated OPeNDAP url, type and subtype exists in the metadata. ;; The different scenarios of the RelatedUrls update are covered in unit tests. (is (string/includes? original-metadata "https://opendap.uat.earthdata.nasa.gov/erbe_albedo_monthly_xdeg")) (is (string/includes? original-metadata "OPENDAP DATA")) (is (not (string/includes? original-metadata "https://opendap.earthdata.nasa.gov/test-gran1"))) (is (not (string/includes? original-metadata "USE SERVICE API"))) (is (not (string/includes? updated-metadata "https://opendap.uat.earthdata.nasa.gov/erbe_albedo_monthly_xdeg"))) (is (string/includes? updated-metadata "OPENDAP DATA")) (is (string/includes? updated-metadata "https://opendap.earthdata.nasa.gov/test-gran1")) (is (string/includes? updated-metadata "USE SERVICE API")))))) (deftest add-s3-url "test adding S3 url with real granule file that is already in CMR code base" (testing "ECHO10 granule" (let [bulk-update-options {:token (echo-util/login (system/context) "user1")} coll (data-core/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-collection.xml" {:provider-id "PROV1" :concept-type :collection :native-id "OMSO2-collection" :format-key :dif10}) granule (data-core/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-granule.xml" {:provider-id "PROV1" :concept-type :granule :native-id "OMSO2-granule" :format-key :echo10}) {:keys [concept-id revision-id]} granule target-metadata (-> "CMR-4722/OMSO2.003-granule-s3-url.xml" io/resource slurp) bulk-update {:operation "UPDATE_FIELD" :update-field "S3Link" :updates [["OMSO2.003:OMI-Aura_L2-OMSO2_2004m1001t2307-o01146_v003-2016m0615t191523.he5" "s3://abcdefg/2016m0615t191523"]]} {:keys [status] :as response} (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options)] (index/wait-until-indexed) (is (= 200 status)) (is (= target-metadata (:metadata (mdb/get-concept concept-id (inc revision-id))))))) (testing "UMM-G granule" (let [bulk-update-options {:token (echo-util/login (system/context) "user1")} coll (data-core/ingest-concept-with-metadata-file "umm-g-samples/Collection.json" {:provider-id "PROV1" :concept-type :collection :native-id "test-coll1" :format "application/vnd.nasa.cmr.umm+json;version=1.16"}) granule (data-core/ingest-concept-with-metadata-file "umm-g-samples/GranuleExample.json" {:provider-id "PROV1" :concept-type :granule :native-id "test-gran1" :format "application/vnd.nasa.cmr.umm+json;version=1.6"}) {:keys [concept-id revision-id]} granule bulk-update {:operation "UPDATE_FIELD" :update-field "S3Link" :updates [["Unique_Granule_UR_v1.6" "s3://abcdefg/test-gran1"]]} {:keys [status task-id] :as response} (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options)] (index/wait-until-indexed) ;; verify the granule status is UPDATED (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "All granule updates completed successfully." status-message)) (is (= [{:granule-ur "Unique_Granule_UR_v1.6" :status "UPDATED"}] granule-statuses))) ;; verify the granule metadata is updated as expected (let [original-metadata (:metadata (mdb/get-concept concept-id revision-id)) updated-metadata (:metadata (mdb/get-concept concept-id (inc revision-id)))] ;; since the metadata will be returned in the latest UMM-G format, ;; we can't compare the whole metadata to an expected string. ;; We just verify the updated S3 url, type and description exists in the metadata. ;; The different scenarios of the RelatedUrls update are covered in unit tests. (is (not (string/includes? original-metadata "s3://abcdefg/test-gran1"))) (is (not (string/includes? original-metadata "GET DATA VIA DIRECT ACCESS"))) (is (not (string/includes? original-metadata "This link provides direct download access via S3 to the granule."))) (is (string/includes? updated-metadata "s3://abcdefg/test-gran1")) (is (string/includes? updated-metadata "GET DATA VIA DIRECT ACCESS")) (is (string/includes? updated-metadata "This link provides direct download access via S3 to the granule."))))))
31926
(ns cmr.system-int-test.ingest.granule-bulk-update.granule-bulk-update-test "CMR bulk update. Test the actual update " (:require [clojure.java.io :as io] [clojure.string :as string] [clojure.test :refer :all] [cmr.mock-echo.client.echo-util :as echo-util] [cmr.system-int-test.data2.core :as data-core] [cmr.system-int-test.data2.granule :as granule] [cmr.system-int-test.data2.umm-spec-collection :as data-umm-c] [cmr.system-int-test.system :as system] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.metadata-db-util :as mdb])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1"})) (deftest bulk-granule-update-test (let [bulk-update-options {:token (echo-util/login (system/context) "user1")} coll1 (data-core/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "coll1" :ShortName "short1" :Version "V1" :native-id "native1"})) gran1 (ingest/ingest-concept (data-core/item->concept (granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:native-id "gran-native1-1" :granule-ur "SC:AE_5DSno.002:30500511"}))) gran2 (ingest/ingest-concept (data-core/item->concept (granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:native-id "gran-native1-2" :granule-ur "SC:AE_5DSno.002:30500512"}))) ;; this granule will fail bulk update as it is in ISO-SMAP format gran3 (ingest/ingest-concept (data-core/item->concept (granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:native-id "gran-native1-3" :granule-ur "SC:AE_5DSno.002:30500513"}) :iso-smap)) ;; UMM-G granule gran4 (ingest/ingest-concept (data-core/item->concept (granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:native-id "gran-native1-4" :granule-ur "SC:AE_5DSno.002:30500514"}) :umm-json)) gran5 (ingest/ingest-concept (data-core/item->concept (granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:native-id "gran-native1-5" :granule-ur "SC:AE_5DSno.002:30500515"})))] (testing "OPeNDAP url granule bulk update" (testing "successful OPeNDAP url granule bulk update" (let [bulk-update {:name "add opendap links 1" :operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["SC:AE_5DSno.002:30500511" "https://url30500511"] ["SC:AE_5DSno.002:30500512" "https://url30500512"] ["SC:AE_5DSno.002:30500514" "https://url30500514"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "All granule updates completed successfully." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500514" :status "UPDATED"}] granule-statuses))))) (testing "failed OPeNDAP url granule bulk update" (let [bulk-update {:name "add opendap links 2" :operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["SC:AE_5DSno.002:30500513" "https://url30500513"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 1 FAILED out of 1 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500513" :status "FAILED" :status-message "Add OPeNDAP url is not supported for format [application/iso:smap+xml]"}] granule-statuses))))) (testing "partial successful OPeNDAP url granule bulk update" (let [bulk-update {:name "add opendap links 3" :operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["SC:AE_5DSno.002:30500511" "https://url30500511"] ["SC:AE_5DSno.002:30500512" "https://url30500512"] ["SC:non-existent-ur" "https://url30500513"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 1 FAILED and 2 UPDATED out of 3 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "UPDATED"} {:granule-ur "SC:non-existent-ur" :status "FAILED" :status-message (format "Granule UR [SC:non-existent-ur] in task-id [%s] does not exist." task-id)}] granule-statuses))))) (testing "invalid OPeNDAP url value in instruction" (let [bulk-update {:name "add opendap links 4" :operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["SC:AE_5DSno.002:30500511" "https://foo,https://bar,https://baz"] ["SC:AE_5DSno.002:30500512" "https://foo, https://bar"] ["SC:AE_5DSno.002:30500514" "https://opendap.sit.earthdata.nasa.gov/foo,https://opendap.earthdata.nasa.gov/bar"] ["SC:AE_5DSno.002:30500515" "s3://opendap.sit.earthdata.nasa.gov/foo"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 4 FAILED out of 4 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "FAILED" :status-message "Invalid URL value, no more than two urls can be provided: https://foo,https://bar,https://baz"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "FAILED" :status-message "Invalid URL value, no more than one on-prem OPeNDAP url can be provided: https://foo, https://bar"} {:granule-ur "SC:AE_5DSno.002:30500514" :status "FAILED" :status-message "Invalid URL value, no more than one Hyrax-in-the-cloud OPeNDAP url can be provided: https://opendap.sit.earthdata.nasa.gov/foo,https://opendap.earthdata.nasa.gov/bar"} {:granule-ur "SC:AE_5DSno.002:30500515" :status "FAILED" :status-message "OPeNDAP URL value cannot start with s3://, but was s3://opendap.sit.earthdata.nasa.gov/foo"}] granule-statuses)))))) (testing "S3 url granule bulk update" (testing "successful S3 url granule bulk update" (let [bulk-update {:name "add S3 links 1" :operation "UPDATE_FIELD" :update-field "S3Link" :updates [["SC:AE_5DSno.002:30500511" "s3://url30500511"] ["SC:AE_5DSno.002:30500512" "s3://url1, s3://url2,s3://url3"] ["SC:AE_5DSno.002:30500514" "s3://url30500514"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "All granule updates completed successfully." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500514" :status "UPDATED"}] granule-statuses))))) (testing "failed S3 link granule bulk update" (let [bulk-update {:name "add s3 links 2" :operation "UPDATE_FIELD" :update-field "S3Link" :updates [["SC:AE_5DSno.002:30500513" "s3://url30500513"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 1 FAILED out of 1 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500513" :status "FAILED" :status-message "Add s3 url is not supported for format [application/iso:smap+xml]"}] granule-statuses))))) (testing "partial successful S3 link granule bulk update" (let [bulk-update {:name "add s3 links 3" :operation "UPDATE_FIELD" :update-field "S3Link" :updates [["SC:AE_5DSno.002:30500511" "s3://url30500511"] ["SC:AE_5DSno.002:30500512" "s3://url30500512"] ["SC:non-existent-ur" "s3://url30500513"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 1 FAILED and 2 UPDATED out of 3 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "UPDATED"} {:granule-ur "SC:non-existent-ur" :status "FAILED" :status-message (format "Granule UR [SC:non-existent-ur] in task-id [%s] does not exist." task-id)}] granule-statuses))))) (testing "invalid S3 url value in instruction" (let [bulk-update {:name "add S3 links 4" :operation "UPDATE_FIELD" :update-field "S3Link" :updates [["SC:AE_5DSno.002:30500511" "https://foo"] ["SC:AE_5DSno.002:30500512" "s3://foo,S3://bar"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 2 FAILED out of 2 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "FAILED" :status-message "Invalid URL value, each S3 url must start with s3://, but was https://foo"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "FAILED" :status-message "Invalid URL value, each S3 url must start with s3://, but was S3://bar"}] granule-statuses)))))))) (deftest add-opendap-url "test adding OPeNDAP url with real granule file that is already in CMR code base" (testing "ECHO10 granule" (let [bulk-update-options {:token (echo-util/login (system/context) "user1")} coll (data-core/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-collection.xml" {:provider-id "PROV1" :concept-type :collection :native-id "OMSO2-collection" :format-key :dif10}) granule (data-core/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-granule.xml" {:provider-id "PROV1" :concept-type :granule :native-id "OMSO2-granule" :format-key :echo10}) {:keys [concept-id revision-id]} granule target-metadata (-> "CMR-4722/OMSO2.003-granule-opendap-url.xml" io/resource slurp) bulk-update {:operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["OMSO2.003:OMI-Aura_L2-OMSO2_2004m1001t2307-o01146_v003-2016m0615t191523.he5" "http://opendap-url.example.com"]]} {:keys [status] :as response} (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options)] (index/wait-until-indexed) (is (= 200 status)) (is (= target-metadata (:metadata (mdb/get-concept concept-id (inc revision-id))))))) (testing "UMM-G granule" (let [bulk-update-options {:token (echo-util/login (system/context) "user1")} coll (data-core/ingest-concept-with-metadata-file "umm-g-samples/Collection.json" {:provider-id "PROV1" :concept-type :collection :native-id "test-coll1" :format "application/vnd.nasa.cmr.umm+json;version=1.16"}) granule (data-core/ingest-concept-with-metadata-file "umm-g-samples/GranuleExample.json" {:provider-id "PROV1" :concept-type :granule :native-id "test-gran1" :format "application/vnd.nasa.cmr.umm+json;version=1.6"}) {:keys [concept-id revision-id]} granule bulk-update {:operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["Unique_Granule_UR_v1.6" "https://opendap.earthdata.nasa.gov/test-gran1"]]} {:keys [status task-id] :as response} (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options)] (index/wait-until-indexed) ;; verify the granule status is UPDATED (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "All granule updates completed successfully." status-message)) (is (= [{:granule-ur "Unique_Granule_UR_v1.6" :status "UPDATED"}] granule-statuses))) ;; verify the granule metadata is updated as expected (let [original-metadata (:metadata (mdb/get-concept concept-id revision-id)) updated-metadata (:metadata (mdb/get-concept concept-id (inc revision-id)))] ;; since the metadata will be returned in the latest UMM-G format, ;; we can't compare the whole metadata to an expected string. ;; We just verify the updated OPeNDAP url, type and subtype exists in the metadata. ;; The different scenarios of the RelatedUrls update are covered in unit tests. (is (string/includes? original-metadata "https://opendap.uat.earthdata.nasa.gov/erbe_albedo_monthly_xdeg")) (is (string/includes? original-metadata "OPENDAP DATA")) (is (not (string/includes? original-metadata "https://opendap.earthdata.nasa.gov/test-gran1"))) (is (not (string/includes? original-metadata "USE SERVICE API"))) (is (not (string/includes? updated-metadata "https://opendap.uat.earthdata.nasa.gov/erbe_albedo_monthly_xdeg"))) (is (string/includes? updated-metadata "OPENDAP DATA")) (is (string/includes? updated-metadata "https://opendap.earthdata.nasa.gov/test-gran1")) (is (string/includes? updated-metadata "USE SERVICE API")))))) (deftest add-s3-url "test adding S3 url with real granule file that is already in CMR code base" (testing "ECHO10 granule" (let [bulk-update-options {:token (echo-util/login (system/context) "user1")} coll (data-core/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-collection.xml" {:provider-id "PROV1" :concept-type :collection :native-id "OMSO2-collection" :format-key :dif<KEY>}) granule (data-core/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-granule.xml" {:provider-id "PROV1" :concept-type :granule :native-id "OMSO2-granule" :format-key :echo10}) {:keys [concept-id revision-id]} granule target-metadata (-> "CMR-4722/OMSO2.003-granule-s3-url.xml" io/resource slurp) bulk-update {:operation "UPDATE_FIELD" :update-field "S3Link" :updates [["OMSO2.003:OMI-Aura_L2-OMSO2_2004m1001t2307-o01146_v003-2016m0615t191523.he5" "s3://abcdefg/2016m0615t191523"]]} {:keys [status] :as response} (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options)] (index/wait-until-indexed) (is (= 200 status)) (is (= target-metadata (:metadata (mdb/get-concept concept-id (inc revision-id))))))) (testing "UMM-G granule" (let [bulk-update-options {:token (echo-util/login (system/context) "user1")} coll (data-core/ingest-concept-with-metadata-file "umm-g-samples/Collection.json" {:provider-id "PROV1" :concept-type :collection :native-id "test-coll1" :format "application/vnd.nasa.cmr.umm+json;version=1.16"}) granule (data-core/ingest-concept-with-metadata-file "umm-g-samples/GranuleExample.json" {:provider-id "PROV1" :concept-type :granule :native-id "test-gran1" :format "application/vnd.nasa.cmr.umm+json;version=1.6"}) {:keys [concept-id revision-id]} granule bulk-update {:operation "UPDATE_FIELD" :update-field "S3Link" :updates [["Unique_Granule_UR_v1.6" "s3://abcdefg/test-gran1"]]} {:keys [status task-id] :as response} (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options)] (index/wait-until-indexed) ;; verify the granule status is UPDATED (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "All granule updates completed successfully." status-message)) (is (= [{:granule-ur "Unique_Granule_UR_v1.6" :status "UPDATED"}] granule-statuses))) ;; verify the granule metadata is updated as expected (let [original-metadata (:metadata (mdb/get-concept concept-id revision-id)) updated-metadata (:metadata (mdb/get-concept concept-id (inc revision-id)))] ;; since the metadata will be returned in the latest UMM-G format, ;; we can't compare the whole metadata to an expected string. ;; We just verify the updated S3 url, type and description exists in the metadata. ;; The different scenarios of the RelatedUrls update are covered in unit tests. (is (not (string/includes? original-metadata "s3://abcdefg/test-gran1"))) (is (not (string/includes? original-metadata "GET DATA VIA DIRECT ACCESS"))) (is (not (string/includes? original-metadata "This link provides direct download access via S3 to the granule."))) (is (string/includes? updated-metadata "s3://abcdefg/test-gran1")) (is (string/includes? updated-metadata "GET DATA VIA DIRECT ACCESS")) (is (string/includes? updated-metadata "This link provides direct download access via S3 to the granule."))))))
true
(ns cmr.system-int-test.ingest.granule-bulk-update.granule-bulk-update-test "CMR bulk update. Test the actual update " (:require [clojure.java.io :as io] [clojure.string :as string] [clojure.test :refer :all] [cmr.mock-echo.client.echo-util :as echo-util] [cmr.system-int-test.data2.core :as data-core] [cmr.system-int-test.data2.granule :as granule] [cmr.system-int-test.data2.umm-spec-collection :as data-umm-c] [cmr.system-int-test.system :as system] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.metadata-db-util :as mdb])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1"})) (deftest bulk-granule-update-test (let [bulk-update-options {:token (echo-util/login (system/context) "user1")} coll1 (data-core/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "coll1" :ShortName "short1" :Version "V1" :native-id "native1"})) gran1 (ingest/ingest-concept (data-core/item->concept (granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:native-id "gran-native1-1" :granule-ur "SC:AE_5DSno.002:30500511"}))) gran2 (ingest/ingest-concept (data-core/item->concept (granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:native-id "gran-native1-2" :granule-ur "SC:AE_5DSno.002:30500512"}))) ;; this granule will fail bulk update as it is in ISO-SMAP format gran3 (ingest/ingest-concept (data-core/item->concept (granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:native-id "gran-native1-3" :granule-ur "SC:AE_5DSno.002:30500513"}) :iso-smap)) ;; UMM-G granule gran4 (ingest/ingest-concept (data-core/item->concept (granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:native-id "gran-native1-4" :granule-ur "SC:AE_5DSno.002:30500514"}) :umm-json)) gran5 (ingest/ingest-concept (data-core/item->concept (granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:native-id "gran-native1-5" :granule-ur "SC:AE_5DSno.002:30500515"})))] (testing "OPeNDAP url granule bulk update" (testing "successful OPeNDAP url granule bulk update" (let [bulk-update {:name "add opendap links 1" :operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["SC:AE_5DSno.002:30500511" "https://url30500511"] ["SC:AE_5DSno.002:30500512" "https://url30500512"] ["SC:AE_5DSno.002:30500514" "https://url30500514"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "All granule updates completed successfully." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500514" :status "UPDATED"}] granule-statuses))))) (testing "failed OPeNDAP url granule bulk update" (let [bulk-update {:name "add opendap links 2" :operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["SC:AE_5DSno.002:30500513" "https://url30500513"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 1 FAILED out of 1 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500513" :status "FAILED" :status-message "Add OPeNDAP url is not supported for format [application/iso:smap+xml]"}] granule-statuses))))) (testing "partial successful OPeNDAP url granule bulk update" (let [bulk-update {:name "add opendap links 3" :operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["SC:AE_5DSno.002:30500511" "https://url30500511"] ["SC:AE_5DSno.002:30500512" "https://url30500512"] ["SC:non-existent-ur" "https://url30500513"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 1 FAILED and 2 UPDATED out of 3 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "UPDATED"} {:granule-ur "SC:non-existent-ur" :status "FAILED" :status-message (format "Granule UR [SC:non-existent-ur] in task-id [%s] does not exist." task-id)}] granule-statuses))))) (testing "invalid OPeNDAP url value in instruction" (let [bulk-update {:name "add opendap links 4" :operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["SC:AE_5DSno.002:30500511" "https://foo,https://bar,https://baz"] ["SC:AE_5DSno.002:30500512" "https://foo, https://bar"] ["SC:AE_5DSno.002:30500514" "https://opendap.sit.earthdata.nasa.gov/foo,https://opendap.earthdata.nasa.gov/bar"] ["SC:AE_5DSno.002:30500515" "s3://opendap.sit.earthdata.nasa.gov/foo"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 4 FAILED out of 4 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "FAILED" :status-message "Invalid URL value, no more than two urls can be provided: https://foo,https://bar,https://baz"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "FAILED" :status-message "Invalid URL value, no more than one on-prem OPeNDAP url can be provided: https://foo, https://bar"} {:granule-ur "SC:AE_5DSno.002:30500514" :status "FAILED" :status-message "Invalid URL value, no more than one Hyrax-in-the-cloud OPeNDAP url can be provided: https://opendap.sit.earthdata.nasa.gov/foo,https://opendap.earthdata.nasa.gov/bar"} {:granule-ur "SC:AE_5DSno.002:30500515" :status "FAILED" :status-message "OPeNDAP URL value cannot start with s3://, but was s3://opendap.sit.earthdata.nasa.gov/foo"}] granule-statuses)))))) (testing "S3 url granule bulk update" (testing "successful S3 url granule bulk update" (let [bulk-update {:name "add S3 links 1" :operation "UPDATE_FIELD" :update-field "S3Link" :updates [["SC:AE_5DSno.002:30500511" "s3://url30500511"] ["SC:AE_5DSno.002:30500512" "s3://url1, s3://url2,s3://url3"] ["SC:AE_5DSno.002:30500514" "s3://url30500514"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "All granule updates completed successfully." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500514" :status "UPDATED"}] granule-statuses))))) (testing "failed S3 link granule bulk update" (let [bulk-update {:name "add s3 links 2" :operation "UPDATE_FIELD" :update-field "S3Link" :updates [["SC:AE_5DSno.002:30500513" "s3://url30500513"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 1 FAILED out of 1 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500513" :status "FAILED" :status-message "Add s3 url is not supported for format [application/iso:smap+xml]"}] granule-statuses))))) (testing "partial successful S3 link granule bulk update" (let [bulk-update {:name "add s3 links 3" :operation "UPDATE_FIELD" :update-field "S3Link" :updates [["SC:AE_5DSno.002:30500511" "s3://url30500511"] ["SC:AE_5DSno.002:30500512" "s3://url30500512"] ["SC:non-existent-ur" "s3://url30500513"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 1 FAILED and 2 UPDATED out of 3 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "UPDATED"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "UPDATED"} {:granule-ur "SC:non-existent-ur" :status "FAILED" :status-message (format "Granule UR [SC:non-existent-ur] in task-id [%s] does not exist." task-id)}] granule-statuses))))) (testing "invalid S3 url value in instruction" (let [bulk-update {:name "add S3 links 4" :operation "UPDATE_FIELD" :update-field "S3Link" :updates [["SC:AE_5DSno.002:30500511" "https://foo"] ["SC:AE_5DSno.002:30500512" "s3://foo,S3://bar"]]} response (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options) {:keys [status task-id]} response] (index/wait-until-indexed) (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "Task completed with 2 FAILED out of 2 total granule update(s)." status-message)) (is (= [{:granule-ur "SC:AE_5DSno.002:30500511" :status "FAILED" :status-message "Invalid URL value, each S3 url must start with s3://, but was https://foo"} {:granule-ur "SC:AE_5DSno.002:30500512" :status "FAILED" :status-message "Invalid URL value, each S3 url must start with s3://, but was S3://bar"}] granule-statuses)))))))) (deftest add-opendap-url "test adding OPeNDAP url with real granule file that is already in CMR code base" (testing "ECHO10 granule" (let [bulk-update-options {:token (echo-util/login (system/context) "user1")} coll (data-core/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-collection.xml" {:provider-id "PROV1" :concept-type :collection :native-id "OMSO2-collection" :format-key :dif10}) granule (data-core/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-granule.xml" {:provider-id "PROV1" :concept-type :granule :native-id "OMSO2-granule" :format-key :echo10}) {:keys [concept-id revision-id]} granule target-metadata (-> "CMR-4722/OMSO2.003-granule-opendap-url.xml" io/resource slurp) bulk-update {:operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["OMSO2.003:OMI-Aura_L2-OMSO2_2004m1001t2307-o01146_v003-2016m0615t191523.he5" "http://opendap-url.example.com"]]} {:keys [status] :as response} (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options)] (index/wait-until-indexed) (is (= 200 status)) (is (= target-metadata (:metadata (mdb/get-concept concept-id (inc revision-id))))))) (testing "UMM-G granule" (let [bulk-update-options {:token (echo-util/login (system/context) "user1")} coll (data-core/ingest-concept-with-metadata-file "umm-g-samples/Collection.json" {:provider-id "PROV1" :concept-type :collection :native-id "test-coll1" :format "application/vnd.nasa.cmr.umm+json;version=1.16"}) granule (data-core/ingest-concept-with-metadata-file "umm-g-samples/GranuleExample.json" {:provider-id "PROV1" :concept-type :granule :native-id "test-gran1" :format "application/vnd.nasa.cmr.umm+json;version=1.6"}) {:keys [concept-id revision-id]} granule bulk-update {:operation "UPDATE_FIELD" :update-field "OPeNDAPLink" :updates [["Unique_Granule_UR_v1.6" "https://opendap.earthdata.nasa.gov/test-gran1"]]} {:keys [status task-id] :as response} (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options)] (index/wait-until-indexed) ;; verify the granule status is UPDATED (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "All granule updates completed successfully." status-message)) (is (= [{:granule-ur "Unique_Granule_UR_v1.6" :status "UPDATED"}] granule-statuses))) ;; verify the granule metadata is updated as expected (let [original-metadata (:metadata (mdb/get-concept concept-id revision-id)) updated-metadata (:metadata (mdb/get-concept concept-id (inc revision-id)))] ;; since the metadata will be returned in the latest UMM-G format, ;; we can't compare the whole metadata to an expected string. ;; We just verify the updated OPeNDAP url, type and subtype exists in the metadata. ;; The different scenarios of the RelatedUrls update are covered in unit tests. (is (string/includes? original-metadata "https://opendap.uat.earthdata.nasa.gov/erbe_albedo_monthly_xdeg")) (is (string/includes? original-metadata "OPENDAP DATA")) (is (not (string/includes? original-metadata "https://opendap.earthdata.nasa.gov/test-gran1"))) (is (not (string/includes? original-metadata "USE SERVICE API"))) (is (not (string/includes? updated-metadata "https://opendap.uat.earthdata.nasa.gov/erbe_albedo_monthly_xdeg"))) (is (string/includes? updated-metadata "OPENDAP DATA")) (is (string/includes? updated-metadata "https://opendap.earthdata.nasa.gov/test-gran1")) (is (string/includes? updated-metadata "USE SERVICE API")))))) (deftest add-s3-url "test adding S3 url with real granule file that is already in CMR code base" (testing "ECHO10 granule" (let [bulk-update-options {:token (echo-util/login (system/context) "user1")} coll (data-core/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-collection.xml" {:provider-id "PROV1" :concept-type :collection :native-id "OMSO2-collection" :format-key :difPI:KEY:<KEY>END_PI}) granule (data-core/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-granule.xml" {:provider-id "PROV1" :concept-type :granule :native-id "OMSO2-granule" :format-key :echo10}) {:keys [concept-id revision-id]} granule target-metadata (-> "CMR-4722/OMSO2.003-granule-s3-url.xml" io/resource slurp) bulk-update {:operation "UPDATE_FIELD" :update-field "S3Link" :updates [["OMSO2.003:OMI-Aura_L2-OMSO2_2004m1001t2307-o01146_v003-2016m0615t191523.he5" "s3://abcdefg/2016m0615t191523"]]} {:keys [status] :as response} (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options)] (index/wait-until-indexed) (is (= 200 status)) (is (= target-metadata (:metadata (mdb/get-concept concept-id (inc revision-id))))))) (testing "UMM-G granule" (let [bulk-update-options {:token (echo-util/login (system/context) "user1")} coll (data-core/ingest-concept-with-metadata-file "umm-g-samples/Collection.json" {:provider-id "PROV1" :concept-type :collection :native-id "test-coll1" :format "application/vnd.nasa.cmr.umm+json;version=1.16"}) granule (data-core/ingest-concept-with-metadata-file "umm-g-samples/GranuleExample.json" {:provider-id "PROV1" :concept-type :granule :native-id "test-gran1" :format "application/vnd.nasa.cmr.umm+json;version=1.6"}) {:keys [concept-id revision-id]} granule bulk-update {:operation "UPDATE_FIELD" :update-field "S3Link" :updates [["Unique_Granule_UR_v1.6" "s3://abcdefg/test-gran1"]]} {:keys [status task-id] :as response} (ingest/bulk-update-granules "PROV1" bulk-update bulk-update-options)] (index/wait-until-indexed) ;; verify the granule status is UPDATED (is (= 200 status)) (is (some? task-id)) (let [status-response (ingest/granule-bulk-update-task-status task-id) {:keys [task-status status-message granule-statuses]} status-response] (is (= "COMPLETE" task-status)) (is (= "All granule updates completed successfully." status-message)) (is (= [{:granule-ur "Unique_Granule_UR_v1.6" :status "UPDATED"}] granule-statuses))) ;; verify the granule metadata is updated as expected (let [original-metadata (:metadata (mdb/get-concept concept-id revision-id)) updated-metadata (:metadata (mdb/get-concept concept-id (inc revision-id)))] ;; since the metadata will be returned in the latest UMM-G format, ;; we can't compare the whole metadata to an expected string. ;; We just verify the updated S3 url, type and description exists in the metadata. ;; The different scenarios of the RelatedUrls update are covered in unit tests. (is (not (string/includes? original-metadata "s3://abcdefg/test-gran1"))) (is (not (string/includes? original-metadata "GET DATA VIA DIRECT ACCESS"))) (is (not (string/includes? original-metadata "This link provides direct download access via S3 to the granule."))) (is (string/includes? updated-metadata "s3://abcdefg/test-gran1")) (is (string/includes? updated-metadata "GET DATA VIA DIRECT ACCESS")) (is (string/includes? updated-metadata "This link provides direct download access via S3 to the granule."))))))
[ { "context": " format for shipping to SCServer.\"\n :author \"Sam Aaron\"}\n overtone.sc.machinery.ugen.sc-ugen\n (:use ", "end": 291, "score": 0.999886691570282, "start": 282, "tag": "NAME", "value": "Sam Aaron" } ]
src/overtone/sc/machinery/ugen/sc_ugen.clj
rosejn/overtone
4
(ns ^{:doc "Records and fns for representing SCUgens. These are to be distinguised with ugens which are Overtone functions which compile down into SCUGens. Trees of SCUGens can then, in turn, be compiled down into a binary synth format for shipping to SCServer." :author "Sam Aaron"} overtone.sc.machinery.ugen.sc-ugen (:use [overtone.sc.machinery.ugen defaults] [overtone.util lib])) (defrecord SCUGen [id name rate rate-name special args n-outputs]) (derive SCUGen ::sc-ugen) (defn sc-ugen? [obj] (isa? (type obj) ::sc-ugen)) (defn sc-ugen "Create a new SCUGen instance. Throws an error if any of the args are nil." [id name rate rate-name special args n-outputs] (if (or (nil? id) (nil? name) (nil? rate) (nil? rate-name) (nil? special) (nil? args) (nil? n-outputs)) (throw (IllegalArgumentException. (str "Attempted to create an SCUGen with nil args. Got " [id name rate rate-name special args n-outputs]))) (SCUGen. id name rate rate-name special args n-outputs))) (defn count-ugen-args "Count the number of ugens in the args of ug (and their args recursively)" [ug] (let [args (:args ug)] (reduce (fn [sum arg] (if (sc-ugen? arg) (+ sum 1 (count-ugen-args arg)) sum)) 0 args))) (defmethod print-method SCUGen [ug w] (.write w (str "#<sc-ugen: " (overtone-ugen-name (:name ug)) (:rate-name ug) " [" (count-ugen-args ug) "]>"))) (defrecord ControlProxy [name value rate rate-name]) (derive ControlProxy ::sc-ugen) (defn control-proxy "Create a new control proxy with the specified name, value and rate. Rate defaults to :kr. Specifically handles :tr which is really a TrigControl ugen at :kr. Throws an error if any of the args are nil." ([name value] (control-proxy name value :kr)) ([name value rate-name] (let [rate (if (= :tr) (:kr RATES) (rate-name RATES))] (if (or (nil? name) (nil? value) (nil? rate) (nil? rate-name)) (throw (IllegalArgumentException. (str "Attempted to create a ControlProxy with nil args. Got " [name value rate rate-name]))) (ControlProxy. name value rate rate-name))))) (defrecord OutputProxy [ugen rate rate-name index]) (derive OutputProxy ::sc-ugen) (defn output-proxy "Create a new output proxy. Throws an error if any of the args are nil." [ugen index] (let [rate (:rate ugen) rate-name (REVERSE-RATES (:rate ugen))] (if (or (nil? ugen) (nil? rate) (nil? rate-name) (nil? index)) (throw (IllegalArgumentException. (str "Attempted to create an OutputProxy with nil args. Got " [ugen rate rate-name index]))) (OutputProxy. ugen rate rate-name index)))) (defn control-proxy? [obj] (= ControlProxy (type obj))) (defn output-proxy? [obj] (= OutputProxy (type obj)))
40114
(ns ^{:doc "Records and fns for representing SCUgens. These are to be distinguised with ugens which are Overtone functions which compile down into SCUGens. Trees of SCUGens can then, in turn, be compiled down into a binary synth format for shipping to SCServer." :author "<NAME>"} overtone.sc.machinery.ugen.sc-ugen (:use [overtone.sc.machinery.ugen defaults] [overtone.util lib])) (defrecord SCUGen [id name rate rate-name special args n-outputs]) (derive SCUGen ::sc-ugen) (defn sc-ugen? [obj] (isa? (type obj) ::sc-ugen)) (defn sc-ugen "Create a new SCUGen instance. Throws an error if any of the args are nil." [id name rate rate-name special args n-outputs] (if (or (nil? id) (nil? name) (nil? rate) (nil? rate-name) (nil? special) (nil? args) (nil? n-outputs)) (throw (IllegalArgumentException. (str "Attempted to create an SCUGen with nil args. Got " [id name rate rate-name special args n-outputs]))) (SCUGen. id name rate rate-name special args n-outputs))) (defn count-ugen-args "Count the number of ugens in the args of ug (and their args recursively)" [ug] (let [args (:args ug)] (reduce (fn [sum arg] (if (sc-ugen? arg) (+ sum 1 (count-ugen-args arg)) sum)) 0 args))) (defmethod print-method SCUGen [ug w] (.write w (str "#<sc-ugen: " (overtone-ugen-name (:name ug)) (:rate-name ug) " [" (count-ugen-args ug) "]>"))) (defrecord ControlProxy [name value rate rate-name]) (derive ControlProxy ::sc-ugen) (defn control-proxy "Create a new control proxy with the specified name, value and rate. Rate defaults to :kr. Specifically handles :tr which is really a TrigControl ugen at :kr. Throws an error if any of the args are nil." ([name value] (control-proxy name value :kr)) ([name value rate-name] (let [rate (if (= :tr) (:kr RATES) (rate-name RATES))] (if (or (nil? name) (nil? value) (nil? rate) (nil? rate-name)) (throw (IllegalArgumentException. (str "Attempted to create a ControlProxy with nil args. Got " [name value rate rate-name]))) (ControlProxy. name value rate rate-name))))) (defrecord OutputProxy [ugen rate rate-name index]) (derive OutputProxy ::sc-ugen) (defn output-proxy "Create a new output proxy. Throws an error if any of the args are nil." [ugen index] (let [rate (:rate ugen) rate-name (REVERSE-RATES (:rate ugen))] (if (or (nil? ugen) (nil? rate) (nil? rate-name) (nil? index)) (throw (IllegalArgumentException. (str "Attempted to create an OutputProxy with nil args. Got " [ugen rate rate-name index]))) (OutputProxy. ugen rate rate-name index)))) (defn control-proxy? [obj] (= ControlProxy (type obj))) (defn output-proxy? [obj] (= OutputProxy (type obj)))
true
(ns ^{:doc "Records and fns for representing SCUgens. These are to be distinguised with ugens which are Overtone functions which compile down into SCUGens. Trees of SCUGens can then, in turn, be compiled down into a binary synth format for shipping to SCServer." :author "PI:NAME:<NAME>END_PI"} overtone.sc.machinery.ugen.sc-ugen (:use [overtone.sc.machinery.ugen defaults] [overtone.util lib])) (defrecord SCUGen [id name rate rate-name special args n-outputs]) (derive SCUGen ::sc-ugen) (defn sc-ugen? [obj] (isa? (type obj) ::sc-ugen)) (defn sc-ugen "Create a new SCUGen instance. Throws an error if any of the args are nil." [id name rate rate-name special args n-outputs] (if (or (nil? id) (nil? name) (nil? rate) (nil? rate-name) (nil? special) (nil? args) (nil? n-outputs)) (throw (IllegalArgumentException. (str "Attempted to create an SCUGen with nil args. Got " [id name rate rate-name special args n-outputs]))) (SCUGen. id name rate rate-name special args n-outputs))) (defn count-ugen-args "Count the number of ugens in the args of ug (and their args recursively)" [ug] (let [args (:args ug)] (reduce (fn [sum arg] (if (sc-ugen? arg) (+ sum 1 (count-ugen-args arg)) sum)) 0 args))) (defmethod print-method SCUGen [ug w] (.write w (str "#<sc-ugen: " (overtone-ugen-name (:name ug)) (:rate-name ug) " [" (count-ugen-args ug) "]>"))) (defrecord ControlProxy [name value rate rate-name]) (derive ControlProxy ::sc-ugen) (defn control-proxy "Create a new control proxy with the specified name, value and rate. Rate defaults to :kr. Specifically handles :tr which is really a TrigControl ugen at :kr. Throws an error if any of the args are nil." ([name value] (control-proxy name value :kr)) ([name value rate-name] (let [rate (if (= :tr) (:kr RATES) (rate-name RATES))] (if (or (nil? name) (nil? value) (nil? rate) (nil? rate-name)) (throw (IllegalArgumentException. (str "Attempted to create a ControlProxy with nil args. Got " [name value rate rate-name]))) (ControlProxy. name value rate rate-name))))) (defrecord OutputProxy [ugen rate rate-name index]) (derive OutputProxy ::sc-ugen) (defn output-proxy "Create a new output proxy. Throws an error if any of the args are nil." [ugen index] (let [rate (:rate ugen) rate-name (REVERSE-RATES (:rate ugen))] (if (or (nil? ugen) (nil? rate) (nil? rate-name) (nil? index)) (throw (IllegalArgumentException. (str "Attempted to create an OutputProxy with nil args. Got " [ugen rate rate-name index]))) (OutputProxy. ugen rate rate-name index)))) (defn control-proxy? [obj] (= ControlProxy (type obj))) (defn output-proxy? [obj] (= OutputProxy (type obj)))
[ { "context": " {:keylength 512}))\n :authorization {:certificate \"foo\"}}))\n\n(d", "end": 1717, "score": 0.731515645980835, "start": 1715, "tag": "KEY", "value": "12" }, { "context": "resources/config/jetty/ssl/private_keys/localhost.pem\"\n :ssl-ca-cert \"./dev-reso", "end": 3641, "score": 0.5288041234016418, "start": 3638, "tag": "KEY", "value": "pem" }, { "context": "and-proxy-servers\n {:target {:host \"0.0.0.0\"\n :port 9000}\n :p", "end": 6663, "score": 0.9996743202209473, "start": 6656, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": " :port 9000}\n :proxy {:host \"0.0.0.0\"\n :port 10000}\n :", "end": 6741, "score": 0.9996832609176636, "start": 6734, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "config\n {:ssl-host \"0.0.0.0\"\n :ssl-port 9001})", "end": 7829, "score": 0.9996678233146667, "start": 7822, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "config\n {:ssl-host \"0.0.0.0\"\n :ssl-port 10001}", "end": 7979, "score": 0.9996881484985352, "start": 7972, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "config\n {:ssl-host \"0.0.0.0\"\n :ssl-port 9001})", "end": 8790, "score": 0.9996885061264038, "start": 8783, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": " :ssl-port 9001})\n :proxy {:host \"0.0.0.0\"\n :port 10000}\n :", "end": 8880, "score": 0.9996953010559082, "start": 8873, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "and-proxy-servers\n {:target {:host \"0.0.0.0\"\n :port 9000}\n :p", "end": 9585, "score": 0.999695360660553, "start": 9578, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "config\n {:ssl-host \"0.0.0.0\"\n :ssl-port 10001}", "end": 9723, "score": 0.9996935129165649, "start": 9716, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "-and-proxy-servers\n {:target {:host \"0.0.0.0\"\n :port 9000}\n :pr", "end": 10427, "score": 0.9996963739395142, "start": 10420, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": " :port 9000}\n :proxy {:host \"0.0.0.0\"\n :port 10000}\n :p", "end": 10503, "score": 0.9996950030326843, "start": 10496, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "and-proxy-servers\n {:target {:host \"0.0.0.0\"\n :port 9000}\n :p", "end": 11947, "score": 0.9996868968009949, "start": 11940, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": " :port 9000}\n :proxy {:host \"0.0.0.0\"\n :port 10000}\n :", "end": 12025, "score": 0.9996782541275024, "start": 12018, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "-and-proxy-servers\n {:target {:host \"0.0.0.0\"\n :port 9000}\n :pr", "end": 12849, "score": 0.9996730089187622, "start": 12842, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": " :port 9000}\n :proxy {:host \"0.0.0.0\"\n :port 10000}\n :p", "end": 12925, "score": 0.9996700882911682, "start": 12918, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "target-and-proxy-servers\n {:target {:host \"0.0.0.0\"\n :port 9000}\n :proxy {", "end": 13561, "score": 0.9996798634529114, "start": 13554, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": " :port 9000}\n :proxy {:host \"0.0.0.0\"\n :port 10000}\n :proxy-h", "end": 13625, "score": 0.9996834397315979, "start": 13618, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "and-proxy-servers\n {:target {:host \"0.0.0.0\"\n :port 9000}\n :p", "end": 14524, "score": 0.9996840357780457, "start": 14517, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": " :port 9000}\n :proxy {:host \"0.0.0.0\"\n :port 10000}\n :", "end": 14602, "score": 0.9996944069862366, "start": 14595, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "and-proxy-servers\n {:target {:host \"0.0.0.0\"\n :port 9000}\n :p", "end": 15272, "score": 0.9997225999832153, "start": 15265, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": " :port 9000}\n :proxy {:host \"0.0.0.0\"\n :port 10000}\n :", "end": 15350, "score": 0.9997265934944153, "start": 15343, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "target-and-proxy-servers\n {:target {:host \"0.0.0.0\"\n :port 9000}\n :proxy ", "end": 16438, "score": 0.9997142553329468, "start": 16431, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": " :port 9000}\n :proxy {:host \"0.0.0.0\"\n :port 10000}\n :proxy-", "end": 16503, "score": 0.9996919631958008, "start": 16496, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "target-and-proxy-servers\n {:target {:host \"0.0.0.0\"\n :port 9000}\n :proxy {", "end": 17204, "score": 0.9996728301048279, "start": 17197, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": " :port 9000}\n :proxy {:host \"0.0.0.0\"\n :port 10000}\n :proxy-h", "end": 17268, "score": 0.9996742606163025, "start": 17261, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "and-proxy-servers\n {:target {:host \"0.0.0.0\"\n :port 9000}\n :p", "end": 17791, "score": 0.9996775984764099, "start": 17784, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": " :port 9000}\n :proxy {:host \"0.0.0.0\"\n :port 10000}\n :", "end": 17869, "score": 0.9996768236160278, "start": 17862, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "and-proxy-servers\n {:target {:host \"0.0.0.0\"\n :port 9000}\n :p", "end": 18414, "score": 0.9996967315673828, "start": 18407, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": " :port 9000}\n :proxy {:host \"0.0.0.0\"\n :port 10000}\n :", "end": 18492, "score": 0.9997001886367798, "start": 18485, "tag": "IP_ADDRESS", "value": "0.0.0.0" } ]
test/puppetlabs/ring_middleware/core_test.clj
camlow325/ring-middleware
0
(ns puppetlabs.ring-middleware.core-test (:require [cheshire.core :as json] [clojure.test :refer :all] [compojure.core :refer :all] [compojure.handler :as handler] [compojure.route :as route] [puppetlabs.ring-middleware.core :as core] [puppetlabs.ring-middleware.utils :as utils] [puppetlabs.ring-middleware.testutils.common :refer :all] [puppetlabs.ssl-utils.core :refer [pem->cert]] [puppetlabs.ssl-utils.simple :as ssl-simple] [puppetlabs.trapperkeeper.app :refer [get-service]] [puppetlabs.trapperkeeper.services.webserver.jetty9-service :refer :all] [puppetlabs.trapperkeeper.testutils.bootstrap :refer [with-app-with-config]] [puppetlabs.trapperkeeper.testutils.logging :as logutils] [ring.util.response :as rr] [schema.core :as schema] [slingshot.slingshot :as slingshot])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Testing Helpers (def WackSchema [schema/Str]) (schema/defn ^:always-validate cause-schema-error [request :- WackSchema] (throw (IllegalStateException. "The test should have never gotten here..."))) (defn throwing-handler [kind msg] (fn [_] (slingshot/throw+ {:kind kind :msg msg}))) (defn basic-request ([] (basic-request "foo-agent" :get "https://example.com")) ([subject method uri] {:request-method method :uri uri :ssl-client-cert (:cert (ssl-simple/gen-self-signed-cert subject 1 {:keylength 512})) :authorization {:certificate "foo"}})) (defn post-target-handler [req] (if (= (:request-method req) :post) {:status 200 :body (slurp (:body req))} {:status 404 :body "Z'oh"})) (defn proxy-target-handler [req] (condp = (:uri req) "/hello" {:status 302 :headers {"Location" "/hello/world"}} "/hello/" {:status 302 :headers {"Location" "/hello/world"}} "/hello/world" {:status 200 :body "Hello, World!"} "/hello/wrong-host" {:status 302 :headers {"Location" "http://localhost:4/fake"}} "/hello/fully-qualified" {:status 302 :headers {"Location" "http://localhost:9000/hello/world"}} "/hello/different-path" {:status 302 :headers {"Location" "http://localhost:9000/different/"}} {:status 404 :body "D'oh"})) (defn non-proxy-target [_] {:status 200 :body "Non-proxied path"}) (def gzip-body (apply str (repeat 1000 "f"))) (defn proxy-gzip-response [_] (-> gzip-body (rr/response) (rr/status 200) (rr/content-type "text/plain") (rr/charset "UTF-8"))) (defn proxy-error-handler [_] {:status 404 :body "N'oh"}) (defn proxy-regex-response [req] {:status 200 :body (str "Proxied to " (:uri req))}) (defroutes fallthrough-routes (GET "/hello/world" [] "Hello, World! (fallthrough)") (GET "/goodbye/world" [] "Goodbye, World! (fallthrough)") (route/not-found "Not Found (fallthrough)")) (def proxy-regex-fallthrough (handler/site fallthrough-routes)) (def proxy-wrapped-app (-> proxy-error-handler (core/wrap-proxy "/hello-proxy" "http://localhost:9000/hello"))) (def proxy-wrapped-app-ssl (-> proxy-error-handler (core/wrap-proxy "/hello-proxy" "https://localhost:9001/hello" {:ssl-cert "./dev-resources/config/jetty/ssl/certs/localhost.pem" :ssl-key "./dev-resources/config/jetty/ssl/private_keys/localhost.pem" :ssl-ca-cert "./dev-resources/config/jetty/ssl/certs/ca.pem"}))) (def proxy-wrapped-app-redirects (-> proxy-error-handler (core/wrap-proxy "/hello-proxy" "http://localhost:9000/hello" {:force-redirects true :follow-redirects true}))) (def proxy-wrapped-app-regex (-> proxy-regex-fallthrough (core/wrap-proxy #"^/([^/]+/certificate.*)$" "http://localhost:9000/hello"))) (def proxy-wrapped-app-regex-alt (-> proxy-regex-fallthrough (core/wrap-proxy #"/hello-proxy" "http://localhost:9000/hello"))) (def proxy-wrapped-app-regex-no-prepend (-> proxy-regex-fallthrough (core/wrap-proxy #"^/([^/]+/certificate.*)$" "http://localhost:9000"))) (def proxy-wrapped-app-regex-trailing-slash (-> proxy-regex-fallthrough (core/wrap-proxy #"^/([^/]+/certificate.*)$" "http://localhost:9000/"))) (defmacro with-target-and-proxy-servers [{:keys [target proxy proxy-handler ring-handler endpoint target-endpoint]} & body] `(with-app-with-config proxy-target-app# [jetty9-service] {:webserver ~target} (let [target-webserver# (get-service proxy-target-app# :WebserverService)] (add-ring-handler target-webserver# ~ring-handler ~target-endpoint) (add-ring-handler target-webserver# non-proxy-target "/different") (add-ring-handler target-webserver# post-target-handler "/hello/post")) (with-app-with-config proxy-app# [jetty9-service] {:webserver ~proxy} (let [proxy-webserver# (get-service proxy-app# :WebserverService)] (add-ring-handler proxy-webserver# ~proxy-handler ~endpoint)) ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Core Helpers (deftest sanitize-client-cert-test (testing "sanitize-client-cert" (let [subject "foo-client" cert (:cert (ssl-simple/gen-self-signed-cert subject 1)) request {:ssl-client-cert cert :authorization {:certificate "stuff"}} response (core/sanitize-client-cert request)] (testing "adds the CN at :ssl-client-cert-cn" (is (= subject (response :ssl-client-cert-cn)))) (testing "removes :ssl-client-cert key from response" (is (nil? (response :ssl-client-cert)))) (testing "remove tk-auth cert info" (is (nil? (get-in response [:authorization :certificate]))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Core Middleware (deftest test-proxy (let [common-ssl-config {:ssl-cert "./dev-resources/config/jetty/ssl/certs/localhost.pem" :ssl-key "./dev-resources/config/jetty/ssl/private_keys/localhost.pem" :ssl-ca-cert "./dev-resources/config/jetty/ssl/certs/ca.pem"}] (testing "basic proxy support" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:9000/hello/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "http://localhost:10000/hello-proxy/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "http://localhost:10000/hello-proxy/world" {:as :stream})] (is (= (slurp (:body response)) "Hello, World!"))) (let [response (http-post "http://localhost:10000/hello-proxy/post/" {:as :stream :body "I'm posted!"})] (is (= (:status response) 200)) (is (= (slurp (:body response)) "I'm posted!"))))) (testing "basic https proxy support" (with-target-and-proxy-servers {:target (merge common-ssl-config {:ssl-host "0.0.0.0" :ssl-port 9001}) :proxy (merge common-ssl-config {:ssl-host "0.0.0.0" :ssl-port 10001}) :proxy-handler proxy-wrapped-app-ssl :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "https://localhost:9001/hello/world" default-options-for-https-client)] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "https://localhost:10001/hello-proxy/world" default-options-for-https-client)] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))))) (testing "basic http->https proxy support" (with-target-and-proxy-servers {:target (merge common-ssl-config {:ssl-host "0.0.0.0" :ssl-port 9001}) :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-ssl :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "https://localhost:9001/hello/world" default-options-for-https-client)] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "http://localhost:10000/hello-proxy/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))))) (testing "basic https->http proxy support" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy (merge common-ssl-config {:ssl-host "0.0.0.0" :ssl-port 10001}) :proxy-handler proxy-wrapped-app :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:9000/hello/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "https://localhost:10001/hello-proxy/world" default-options-for-https-client)] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))))) (testing "redirect test with proxy" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:9000/hello")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "http://localhost:9000/hello/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "http://localhost:10000/hello-proxy/" {:follow-redirects false :as :text})] (is (= (:status response) 302)) (is (= "/hello/world" (get-in response [:headers "location"])))) (let [response (http-post "http://localhost:10000/hello-proxy/" {:follow-redirects false :as :text})] (is (= (:status response) 302)) (is (= "/hello/world" (get-in response [:headers "location"])))) (let [response (http-get "http://localhost:10000/hello-proxy/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))))) (testing "proxy redirect succeeds on POST if :force-redirects set true" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-redirects :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:10000/hello-proxy/" {:follow-redirects false :as :text})] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-post "http://localhost:10000/hello-proxy/" {:follow-redirects false})] (is (= (:status response) 200))))) (testing "redirect test with fully qualified url, correct host, and proxied path" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-redirects :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:10000/hello-proxy/fully-qualified" {:follow-redirects false :as :text})] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))))) (testing "redirect test with correct host on non-proxied path" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-redirects :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:9000/different")] (is (= (:status response) 200)) (is (= (:body response) "Non-proxied path"))) (let [response (http-get "http://localhost:10000/different")] (is (= (:status response) 404))) (let [response (http-get "http://localhost:10000/hello-proxy/different-path" {:follow-redirects false :as :text})] (is (= (:status response) 200)) (is (= (:body response) "Non-proxied path"))))) (testing "gzipped responses not truncated" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app :ring-handler proxy-gzip-response :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:9000/hello")] (is (= gzip-body (:body response))) (is (= "gzip" (:orig-content-encoding response)))) (let [response (http-get "http://localhost:10000/hello-proxy/")] (is (= gzip-body (:body response))) (is (= "gzip" (:orig-content-encoding response)))))) (testing "proxy works with regex" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-regex :ring-handler proxy-regex-response :endpoint "/" :target-endpoint "/hello"} (let [response (http-get "http://localhost:10000/production/certificate/foo")] (is (= (:status response) 200)) (is (= (:body response) "Proxied to /hello/production/certificate/foo"))) (let [response (http-get "http://localhost:10000/hello/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World! (fallthrough)"))) (let [response (http-get "http://localhost:10000/goodbye/world")] (is (= (:status response) 200)) (is (= (:body response) "Goodbye, World! (fallthrough)"))) (let [response (http-get "http://localhost:10000/production/cert/foo")] (is (= (:status response) 404)) (is (= (:body response) "Not Found (fallthrough)"))))) (testing "proxy regex matches beginning of string" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-regex-alt :ring-handler proxy-regex-response :endpoint "/" :target-endpoint "/hello"} (let [response (http-get "http://localhost:10000/hello-proxy")] (is (= (:status response) 200)) (is (= (:body response) "Proxied to /hello/hello-proxy"))) (let [response (http-get "http://localhost:10000/production/hello-proxy")] (is (= (:status response) 404)) (is (= (:body response) "Not Found (fallthrough)"))))) (testing "proxy regex does not need to match entire request uri" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-regex-alt :ring-handler proxy-regex-response :endpoint "/" :target-endpoint "/hello"} (let [response (http-get "http://localhost:10000/hello-proxy/world")] (is (= (:status response) 200)) (is (= (:body response) "Proxied to /hello/hello-proxy/world"))))) (testing "proxy works with regex and no prepended path" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-regex-no-prepend :ring-handler proxy-regex-response :endpoint "/" :target-endpoint "/"} (let [response (http-get "http://localhost:10000/production/certificate/foo")] (is (= (:status response) 200)) (is (= (:body response) "Proxied to /production/certificate/foo"))))) (testing "no repeat slashes exist in rewritten uri" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-regex-trailing-slash :ring-handler proxy-regex-response :endpoint "/" :target-endpoint "/"} (let [response (http-get "http://localhost:10000/production/certificate/foo")] (is (= (:status response) 200)) (is (= (:body response) "Proxied to /production/certificate/foo"))))))) (deftest test-wrap-add-cache-headers (let [put-request {:request-method :put} get-request {:request-method :get} post-request {:request-method :post} delete-request {:request-method :delete} no-cache-header "private, max-age=0, no-cache"] (testing "wrap-add-cache-headers ignores nil response" (let [handler (constantly nil) wrapped-handler (core/wrap-add-cache-headers handler)] (is (nil? (wrapped-handler put-request))) (is (nil? (wrapped-handler get-request))) (is (nil? (wrapped-handler post-request))) (is (nil? (wrapped-handler delete-request))))) (testing "wrap-add-cache-headers observes handled response" (let [handler (constantly {}) wrapped-handler (core/wrap-add-cache-headers handler) handled-response {:headers {"cache-control" no-cache-header}} not-handled-response {}] (is (= handled-response (wrapped-handler get-request))) (is (= handled-response (wrapped-handler put-request))) (is (= not-handled-response (wrapped-handler post-request))) (is (= not-handled-response (wrapped-handler delete-request))))) (testing "wrap-add-cache-headers doesn't stomp on existing headers" (let [fake-response {:headers {:something "Hi mom"}} handler (constantly fake-response) wrapped-handler (core/wrap-add-cache-headers handler) handled-response {:headers {:something "Hi mom" "cache-control" no-cache-header}} not-handled-response fake-response] (is (= handled-response (wrapped-handler get-request))) (is (= handled-response (wrapped-handler put-request))) (is (= not-handled-response (wrapped-handler post-request))) (is (= not-handled-response (wrapped-handler delete-request))))))) (deftest test-wrap-with-cn (testing "When extracting a CN from a cert" (testing "and there is no cert" (let [mw-fn (core/wrap-with-certificate-cn identity) post-req (mw-fn {})] (testing "ssl-client-cn is set to nil" (is (= post-req {:ssl-client-cn nil}))))) (testing "and there is a cert" (let [mw-fn (core/wrap-with-certificate-cn identity) post-req (mw-fn {:ssl-client-cert (pem->cert "dev-resources/ssl/cert.pem")})] (testing "ssl-client-cn is set properly" (is (= (:ssl-client-cn post-req) "localhost"))))))) (deftest test-wrap-add-x-frame-options-deny (let [get-request {:request-method :get} put-request {:request-method :put} post-request {:request-method :post} delete-request {:request-method :delete} x-frame-header "DENY"] (testing "wrap-add-x-frame-options-deny ignores nil response" (let [handler (constantly nil) wrapped-handler (core/wrap-add-x-frame-options-deny handler)] (is (nil? (wrapped-handler get-request))) (is (nil? (wrapped-handler put-request))) (is (nil? (wrapped-handler post-request))) (is (nil? (wrapped-handler delete-request))))) (testing "wrap-add-x-frame-options-deny observes handled response" (let [handler (constantly {}) wrapped-handler (core/wrap-add-x-frame-options-deny handler) handled-response {:headers {"X-Frame-Options" x-frame-header}} not-handled-response {}] (is (= handled-response (wrapped-handler get-request))) (is (= handled-response (wrapped-handler put-request))) (is (= handled-response (wrapped-handler post-request))) (is (= handled-response (wrapped-handler delete-request))))) (testing "wrap-add-x-frame-options-deny doesn't stomp on existing headers" (let [fake-response {:headers {:something "Hi mom"}} handler (constantly fake-response) wrapped-handler (core/wrap-add-x-frame-options-deny handler) handled-response {:headers {:something "Hi mom" "X-Frame-Options" x-frame-header}}] (is (= handled-response (wrapped-handler get-request))) (is (= handled-response (wrapped-handler put-request))) (is (= handled-response (wrapped-handler post-request))) (is (= handled-response (wrapped-handler delete-request))))))) (deftest wrap-response-logging-test (testing "wrap-response-logging" (logutils/with-test-logging (let [stack (core/wrap-response-logging identity) response (stack (basic-request))] (is (logged? #"Computed response.*" :trace)))))) (deftest wrap-request-logging-test (testing "wrap-request-logging" (logutils/with-test-logging (let [subject "foo-agent" method :get uri "https://example.com" stack (core/wrap-request-logging identity) request (basic-request subject method uri) response (stack request)] (is (logged? (format "Processing %s %s" method uri) :debug)) (is (logged? #"Full request" :trace)))))) (deftest wrap-data-errors-test (testing "wrap-data-errors" (testing "default behavior" (logutils/with-test-logging (let [stack (core/wrap-data-errors (throwing-handler :user-data-invalid "Error Message")) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 400 (response :status))) (is (= "Error Message" (get json-body "msg"))) (is (logged? #"Error Message" :error)) (is (logged? #"Submitted data is invalid" :error))))) (doseq [error [:request-data-invalid :user-data-invalid :service-status-version-not-found]] (testing (str "handles errors of " error) (logutils/with-test-logging (let [stack (core/wrap-data-errors (throwing-handler error "Error Message")) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 400 (response :status))) (is (= (name error) (get json-body "kind"))))))) (testing "handles errors thrown by `throw-data-invalid!`" (logutils/with-test-logging (let [stack (core/wrap-data-errors (fn [_] (utils/throw-data-invalid! "Error Message"))) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 400 (response :status))) (is (= (name "data-invalid") (get json-body "kind")))))) (testing "can be plain text" (logutils/with-test-logging (let [stack (core/wrap-data-errors (throwing-handler :user-data-invalid "Error Message") :plain) response (stack (basic-request))] (is (re-matches #"text/plain.*" (get-in response [:headers "Content-Type"])))))))) (deftest wrap-bad-request-test (testing "wrap-bad-request" (testing "default behavior" (logutils/with-test-logging (let [stack (core/wrap-bad-request (fn [_] (utils/throw-bad-request! "Error Message"))) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 400 (response :status))) (is (logged? #".*Bad Request.*" :error)) (is (re-matches #"Error Message.*" (get json-body "msg" ""))) (is (= "bad-request" (get json-body "kind")))))) (testing "can be plain text" (logutils/with-test-logging (let [stack (core/wrap-bad-request (fn [_] (utils/throw-bad-request! "Error Message")) :plain) response (stack (basic-request))] (is (re-matches #"text/plain.*" (get-in response [:headers "Content-Type"])))))))) (deftest wrap-schema-errors-test (testing "wrap-schema-errors" (testing "default behavior" (logutils/with-test-logging (let [stack (core/wrap-schema-errors cause-schema-error) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 500 (response :status))) (is (logged? #".*Something unexpected.*" :error)) (is (re-matches #"Something unexpected.*" (get json-body "msg" ""))) (is (= "application-error" (get json-body "kind")))))) (testing "can be plain text" (logutils/with-test-logging (let [stack (core/wrap-schema-errors cause-schema-error :plain) response (stack (basic-request))] (is (re-matches #"text/plain.*" (get-in response [:headers "Content-Type"])))))))) (deftest wrap-service-unavailable-test (testing "wrap-service-unavailable" (testing "default behavior" (logutils/with-test-logging (let [stack (core/wrap-service-unavailable (fn [_] (utils/throw-service-unavailable! "Test Service is DOWN!"))) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 503 (response :status))) (is (logged? #".*Service Unavailable.*" :error)) (is (= "Test Service is DOWN!" (get json-body "msg"))) (is (= "service-unavailable" (get json-body "kind")))))) (testing "can be plain text" (logutils/with-test-logging (let [stack (core/wrap-service-unavailable (fn [_] (utils/throw-service-unavailable! "Test Service is DOWN!")) :plain) response (stack (basic-request))] (is (re-matches #"text/plain.*" (get-in response [:headers "Content-Type"])))))))) (deftest wrap-uncaught-errors-test (testing "wrap-uncaught-errors" (testing "default behavior" (logutils/with-test-logging (let [stack (core/wrap-uncaught-errors (fn [_] (throw (IllegalStateException. "Woah...")))) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 500 (response :status))) (is (logged? #".*Internal Server Error.*" :error)) (is (re-matches #"Internal Server Error.*" (get json-body "msg" "")))))) (testing "can be plain text" (logutils/with-test-logging (let [stack (core/wrap-uncaught-errors (fn [_] (throw (IllegalStateException. "Woah..."))) :plain) response (stack (basic-request))] (is (re-matches #"text/plain.*" (get-in response [:headers "Content-Type"]))))))))
86168
(ns puppetlabs.ring-middleware.core-test (:require [cheshire.core :as json] [clojure.test :refer :all] [compojure.core :refer :all] [compojure.handler :as handler] [compojure.route :as route] [puppetlabs.ring-middleware.core :as core] [puppetlabs.ring-middleware.utils :as utils] [puppetlabs.ring-middleware.testutils.common :refer :all] [puppetlabs.ssl-utils.core :refer [pem->cert]] [puppetlabs.ssl-utils.simple :as ssl-simple] [puppetlabs.trapperkeeper.app :refer [get-service]] [puppetlabs.trapperkeeper.services.webserver.jetty9-service :refer :all] [puppetlabs.trapperkeeper.testutils.bootstrap :refer [with-app-with-config]] [puppetlabs.trapperkeeper.testutils.logging :as logutils] [ring.util.response :as rr] [schema.core :as schema] [slingshot.slingshot :as slingshot])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Testing Helpers (def WackSchema [schema/Str]) (schema/defn ^:always-validate cause-schema-error [request :- WackSchema] (throw (IllegalStateException. "The test should have never gotten here..."))) (defn throwing-handler [kind msg] (fn [_] (slingshot/throw+ {:kind kind :msg msg}))) (defn basic-request ([] (basic-request "foo-agent" :get "https://example.com")) ([subject method uri] {:request-method method :uri uri :ssl-client-cert (:cert (ssl-simple/gen-self-signed-cert subject 1 {:keylength 5<KEY>})) :authorization {:certificate "foo"}})) (defn post-target-handler [req] (if (= (:request-method req) :post) {:status 200 :body (slurp (:body req))} {:status 404 :body "Z'oh"})) (defn proxy-target-handler [req] (condp = (:uri req) "/hello" {:status 302 :headers {"Location" "/hello/world"}} "/hello/" {:status 302 :headers {"Location" "/hello/world"}} "/hello/world" {:status 200 :body "Hello, World!"} "/hello/wrong-host" {:status 302 :headers {"Location" "http://localhost:4/fake"}} "/hello/fully-qualified" {:status 302 :headers {"Location" "http://localhost:9000/hello/world"}} "/hello/different-path" {:status 302 :headers {"Location" "http://localhost:9000/different/"}} {:status 404 :body "D'oh"})) (defn non-proxy-target [_] {:status 200 :body "Non-proxied path"}) (def gzip-body (apply str (repeat 1000 "f"))) (defn proxy-gzip-response [_] (-> gzip-body (rr/response) (rr/status 200) (rr/content-type "text/plain") (rr/charset "UTF-8"))) (defn proxy-error-handler [_] {:status 404 :body "N'oh"}) (defn proxy-regex-response [req] {:status 200 :body (str "Proxied to " (:uri req))}) (defroutes fallthrough-routes (GET "/hello/world" [] "Hello, World! (fallthrough)") (GET "/goodbye/world" [] "Goodbye, World! (fallthrough)") (route/not-found "Not Found (fallthrough)")) (def proxy-regex-fallthrough (handler/site fallthrough-routes)) (def proxy-wrapped-app (-> proxy-error-handler (core/wrap-proxy "/hello-proxy" "http://localhost:9000/hello"))) (def proxy-wrapped-app-ssl (-> proxy-error-handler (core/wrap-proxy "/hello-proxy" "https://localhost:9001/hello" {:ssl-cert "./dev-resources/config/jetty/ssl/certs/localhost.pem" :ssl-key "./dev-resources/config/jetty/ssl/private_keys/localhost.<KEY>" :ssl-ca-cert "./dev-resources/config/jetty/ssl/certs/ca.pem"}))) (def proxy-wrapped-app-redirects (-> proxy-error-handler (core/wrap-proxy "/hello-proxy" "http://localhost:9000/hello" {:force-redirects true :follow-redirects true}))) (def proxy-wrapped-app-regex (-> proxy-regex-fallthrough (core/wrap-proxy #"^/([^/]+/certificate.*)$" "http://localhost:9000/hello"))) (def proxy-wrapped-app-regex-alt (-> proxy-regex-fallthrough (core/wrap-proxy #"/hello-proxy" "http://localhost:9000/hello"))) (def proxy-wrapped-app-regex-no-prepend (-> proxy-regex-fallthrough (core/wrap-proxy #"^/([^/]+/certificate.*)$" "http://localhost:9000"))) (def proxy-wrapped-app-regex-trailing-slash (-> proxy-regex-fallthrough (core/wrap-proxy #"^/([^/]+/certificate.*)$" "http://localhost:9000/"))) (defmacro with-target-and-proxy-servers [{:keys [target proxy proxy-handler ring-handler endpoint target-endpoint]} & body] `(with-app-with-config proxy-target-app# [jetty9-service] {:webserver ~target} (let [target-webserver# (get-service proxy-target-app# :WebserverService)] (add-ring-handler target-webserver# ~ring-handler ~target-endpoint) (add-ring-handler target-webserver# non-proxy-target "/different") (add-ring-handler target-webserver# post-target-handler "/hello/post")) (with-app-with-config proxy-app# [jetty9-service] {:webserver ~proxy} (let [proxy-webserver# (get-service proxy-app# :WebserverService)] (add-ring-handler proxy-webserver# ~proxy-handler ~endpoint)) ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Core Helpers (deftest sanitize-client-cert-test (testing "sanitize-client-cert" (let [subject "foo-client" cert (:cert (ssl-simple/gen-self-signed-cert subject 1)) request {:ssl-client-cert cert :authorization {:certificate "stuff"}} response (core/sanitize-client-cert request)] (testing "adds the CN at :ssl-client-cert-cn" (is (= subject (response :ssl-client-cert-cn)))) (testing "removes :ssl-client-cert key from response" (is (nil? (response :ssl-client-cert)))) (testing "remove tk-auth cert info" (is (nil? (get-in response [:authorization :certificate]))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Core Middleware (deftest test-proxy (let [common-ssl-config {:ssl-cert "./dev-resources/config/jetty/ssl/certs/localhost.pem" :ssl-key "./dev-resources/config/jetty/ssl/private_keys/localhost.pem" :ssl-ca-cert "./dev-resources/config/jetty/ssl/certs/ca.pem"}] (testing "basic proxy support" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:9000/hello/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "http://localhost:10000/hello-proxy/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "http://localhost:10000/hello-proxy/world" {:as :stream})] (is (= (slurp (:body response)) "Hello, World!"))) (let [response (http-post "http://localhost:10000/hello-proxy/post/" {:as :stream :body "I'm posted!"})] (is (= (:status response) 200)) (is (= (slurp (:body response)) "I'm posted!"))))) (testing "basic https proxy support" (with-target-and-proxy-servers {:target (merge common-ssl-config {:ssl-host "0.0.0.0" :ssl-port 9001}) :proxy (merge common-ssl-config {:ssl-host "0.0.0.0" :ssl-port 10001}) :proxy-handler proxy-wrapped-app-ssl :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "https://localhost:9001/hello/world" default-options-for-https-client)] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "https://localhost:10001/hello-proxy/world" default-options-for-https-client)] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))))) (testing "basic http->https proxy support" (with-target-and-proxy-servers {:target (merge common-ssl-config {:ssl-host "0.0.0.0" :ssl-port 9001}) :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-ssl :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "https://localhost:9001/hello/world" default-options-for-https-client)] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "http://localhost:10000/hello-proxy/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))))) (testing "basic https->http proxy support" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy (merge common-ssl-config {:ssl-host "0.0.0.0" :ssl-port 10001}) :proxy-handler proxy-wrapped-app :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:9000/hello/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "https://localhost:10001/hello-proxy/world" default-options-for-https-client)] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))))) (testing "redirect test with proxy" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:9000/hello")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "http://localhost:9000/hello/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "http://localhost:10000/hello-proxy/" {:follow-redirects false :as :text})] (is (= (:status response) 302)) (is (= "/hello/world" (get-in response [:headers "location"])))) (let [response (http-post "http://localhost:10000/hello-proxy/" {:follow-redirects false :as :text})] (is (= (:status response) 302)) (is (= "/hello/world" (get-in response [:headers "location"])))) (let [response (http-get "http://localhost:10000/hello-proxy/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))))) (testing "proxy redirect succeeds on POST if :force-redirects set true" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-redirects :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:10000/hello-proxy/" {:follow-redirects false :as :text})] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-post "http://localhost:10000/hello-proxy/" {:follow-redirects false})] (is (= (:status response) 200))))) (testing "redirect test with fully qualified url, correct host, and proxied path" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-redirects :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:10000/hello-proxy/fully-qualified" {:follow-redirects false :as :text})] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))))) (testing "redirect test with correct host on non-proxied path" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-redirects :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:9000/different")] (is (= (:status response) 200)) (is (= (:body response) "Non-proxied path"))) (let [response (http-get "http://localhost:10000/different")] (is (= (:status response) 404))) (let [response (http-get "http://localhost:10000/hello-proxy/different-path" {:follow-redirects false :as :text})] (is (= (:status response) 200)) (is (= (:body response) "Non-proxied path"))))) (testing "gzipped responses not truncated" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app :ring-handler proxy-gzip-response :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:9000/hello")] (is (= gzip-body (:body response))) (is (= "gzip" (:orig-content-encoding response)))) (let [response (http-get "http://localhost:10000/hello-proxy/")] (is (= gzip-body (:body response))) (is (= "gzip" (:orig-content-encoding response)))))) (testing "proxy works with regex" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-regex :ring-handler proxy-regex-response :endpoint "/" :target-endpoint "/hello"} (let [response (http-get "http://localhost:10000/production/certificate/foo")] (is (= (:status response) 200)) (is (= (:body response) "Proxied to /hello/production/certificate/foo"))) (let [response (http-get "http://localhost:10000/hello/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World! (fallthrough)"))) (let [response (http-get "http://localhost:10000/goodbye/world")] (is (= (:status response) 200)) (is (= (:body response) "Goodbye, World! (fallthrough)"))) (let [response (http-get "http://localhost:10000/production/cert/foo")] (is (= (:status response) 404)) (is (= (:body response) "Not Found (fallthrough)"))))) (testing "proxy regex matches beginning of string" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-regex-alt :ring-handler proxy-regex-response :endpoint "/" :target-endpoint "/hello"} (let [response (http-get "http://localhost:10000/hello-proxy")] (is (= (:status response) 200)) (is (= (:body response) "Proxied to /hello/hello-proxy"))) (let [response (http-get "http://localhost:10000/production/hello-proxy")] (is (= (:status response) 404)) (is (= (:body response) "Not Found (fallthrough)"))))) (testing "proxy regex does not need to match entire request uri" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-regex-alt :ring-handler proxy-regex-response :endpoint "/" :target-endpoint "/hello"} (let [response (http-get "http://localhost:10000/hello-proxy/world")] (is (= (:status response) 200)) (is (= (:body response) "Proxied to /hello/hello-proxy/world"))))) (testing "proxy works with regex and no prepended path" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-regex-no-prepend :ring-handler proxy-regex-response :endpoint "/" :target-endpoint "/"} (let [response (http-get "http://localhost:10000/production/certificate/foo")] (is (= (:status response) 200)) (is (= (:body response) "Proxied to /production/certificate/foo"))))) (testing "no repeat slashes exist in rewritten uri" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-regex-trailing-slash :ring-handler proxy-regex-response :endpoint "/" :target-endpoint "/"} (let [response (http-get "http://localhost:10000/production/certificate/foo")] (is (= (:status response) 200)) (is (= (:body response) "Proxied to /production/certificate/foo"))))))) (deftest test-wrap-add-cache-headers (let [put-request {:request-method :put} get-request {:request-method :get} post-request {:request-method :post} delete-request {:request-method :delete} no-cache-header "private, max-age=0, no-cache"] (testing "wrap-add-cache-headers ignores nil response" (let [handler (constantly nil) wrapped-handler (core/wrap-add-cache-headers handler)] (is (nil? (wrapped-handler put-request))) (is (nil? (wrapped-handler get-request))) (is (nil? (wrapped-handler post-request))) (is (nil? (wrapped-handler delete-request))))) (testing "wrap-add-cache-headers observes handled response" (let [handler (constantly {}) wrapped-handler (core/wrap-add-cache-headers handler) handled-response {:headers {"cache-control" no-cache-header}} not-handled-response {}] (is (= handled-response (wrapped-handler get-request))) (is (= handled-response (wrapped-handler put-request))) (is (= not-handled-response (wrapped-handler post-request))) (is (= not-handled-response (wrapped-handler delete-request))))) (testing "wrap-add-cache-headers doesn't stomp on existing headers" (let [fake-response {:headers {:something "Hi mom"}} handler (constantly fake-response) wrapped-handler (core/wrap-add-cache-headers handler) handled-response {:headers {:something "Hi mom" "cache-control" no-cache-header}} not-handled-response fake-response] (is (= handled-response (wrapped-handler get-request))) (is (= handled-response (wrapped-handler put-request))) (is (= not-handled-response (wrapped-handler post-request))) (is (= not-handled-response (wrapped-handler delete-request))))))) (deftest test-wrap-with-cn (testing "When extracting a CN from a cert" (testing "and there is no cert" (let [mw-fn (core/wrap-with-certificate-cn identity) post-req (mw-fn {})] (testing "ssl-client-cn is set to nil" (is (= post-req {:ssl-client-cn nil}))))) (testing "and there is a cert" (let [mw-fn (core/wrap-with-certificate-cn identity) post-req (mw-fn {:ssl-client-cert (pem->cert "dev-resources/ssl/cert.pem")})] (testing "ssl-client-cn is set properly" (is (= (:ssl-client-cn post-req) "localhost"))))))) (deftest test-wrap-add-x-frame-options-deny (let [get-request {:request-method :get} put-request {:request-method :put} post-request {:request-method :post} delete-request {:request-method :delete} x-frame-header "DENY"] (testing "wrap-add-x-frame-options-deny ignores nil response" (let [handler (constantly nil) wrapped-handler (core/wrap-add-x-frame-options-deny handler)] (is (nil? (wrapped-handler get-request))) (is (nil? (wrapped-handler put-request))) (is (nil? (wrapped-handler post-request))) (is (nil? (wrapped-handler delete-request))))) (testing "wrap-add-x-frame-options-deny observes handled response" (let [handler (constantly {}) wrapped-handler (core/wrap-add-x-frame-options-deny handler) handled-response {:headers {"X-Frame-Options" x-frame-header}} not-handled-response {}] (is (= handled-response (wrapped-handler get-request))) (is (= handled-response (wrapped-handler put-request))) (is (= handled-response (wrapped-handler post-request))) (is (= handled-response (wrapped-handler delete-request))))) (testing "wrap-add-x-frame-options-deny doesn't stomp on existing headers" (let [fake-response {:headers {:something "Hi mom"}} handler (constantly fake-response) wrapped-handler (core/wrap-add-x-frame-options-deny handler) handled-response {:headers {:something "Hi mom" "X-Frame-Options" x-frame-header}}] (is (= handled-response (wrapped-handler get-request))) (is (= handled-response (wrapped-handler put-request))) (is (= handled-response (wrapped-handler post-request))) (is (= handled-response (wrapped-handler delete-request))))))) (deftest wrap-response-logging-test (testing "wrap-response-logging" (logutils/with-test-logging (let [stack (core/wrap-response-logging identity) response (stack (basic-request))] (is (logged? #"Computed response.*" :trace)))))) (deftest wrap-request-logging-test (testing "wrap-request-logging" (logutils/with-test-logging (let [subject "foo-agent" method :get uri "https://example.com" stack (core/wrap-request-logging identity) request (basic-request subject method uri) response (stack request)] (is (logged? (format "Processing %s %s" method uri) :debug)) (is (logged? #"Full request" :trace)))))) (deftest wrap-data-errors-test (testing "wrap-data-errors" (testing "default behavior" (logutils/with-test-logging (let [stack (core/wrap-data-errors (throwing-handler :user-data-invalid "Error Message")) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 400 (response :status))) (is (= "Error Message" (get json-body "msg"))) (is (logged? #"Error Message" :error)) (is (logged? #"Submitted data is invalid" :error))))) (doseq [error [:request-data-invalid :user-data-invalid :service-status-version-not-found]] (testing (str "handles errors of " error) (logutils/with-test-logging (let [stack (core/wrap-data-errors (throwing-handler error "Error Message")) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 400 (response :status))) (is (= (name error) (get json-body "kind"))))))) (testing "handles errors thrown by `throw-data-invalid!`" (logutils/with-test-logging (let [stack (core/wrap-data-errors (fn [_] (utils/throw-data-invalid! "Error Message"))) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 400 (response :status))) (is (= (name "data-invalid") (get json-body "kind")))))) (testing "can be plain text" (logutils/with-test-logging (let [stack (core/wrap-data-errors (throwing-handler :user-data-invalid "Error Message") :plain) response (stack (basic-request))] (is (re-matches #"text/plain.*" (get-in response [:headers "Content-Type"])))))))) (deftest wrap-bad-request-test (testing "wrap-bad-request" (testing "default behavior" (logutils/with-test-logging (let [stack (core/wrap-bad-request (fn [_] (utils/throw-bad-request! "Error Message"))) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 400 (response :status))) (is (logged? #".*Bad Request.*" :error)) (is (re-matches #"Error Message.*" (get json-body "msg" ""))) (is (= "bad-request" (get json-body "kind")))))) (testing "can be plain text" (logutils/with-test-logging (let [stack (core/wrap-bad-request (fn [_] (utils/throw-bad-request! "Error Message")) :plain) response (stack (basic-request))] (is (re-matches #"text/plain.*" (get-in response [:headers "Content-Type"])))))))) (deftest wrap-schema-errors-test (testing "wrap-schema-errors" (testing "default behavior" (logutils/with-test-logging (let [stack (core/wrap-schema-errors cause-schema-error) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 500 (response :status))) (is (logged? #".*Something unexpected.*" :error)) (is (re-matches #"Something unexpected.*" (get json-body "msg" ""))) (is (= "application-error" (get json-body "kind")))))) (testing "can be plain text" (logutils/with-test-logging (let [stack (core/wrap-schema-errors cause-schema-error :plain) response (stack (basic-request))] (is (re-matches #"text/plain.*" (get-in response [:headers "Content-Type"])))))))) (deftest wrap-service-unavailable-test (testing "wrap-service-unavailable" (testing "default behavior" (logutils/with-test-logging (let [stack (core/wrap-service-unavailable (fn [_] (utils/throw-service-unavailable! "Test Service is DOWN!"))) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 503 (response :status))) (is (logged? #".*Service Unavailable.*" :error)) (is (= "Test Service is DOWN!" (get json-body "msg"))) (is (= "service-unavailable" (get json-body "kind")))))) (testing "can be plain text" (logutils/with-test-logging (let [stack (core/wrap-service-unavailable (fn [_] (utils/throw-service-unavailable! "Test Service is DOWN!")) :plain) response (stack (basic-request))] (is (re-matches #"text/plain.*" (get-in response [:headers "Content-Type"])))))))) (deftest wrap-uncaught-errors-test (testing "wrap-uncaught-errors" (testing "default behavior" (logutils/with-test-logging (let [stack (core/wrap-uncaught-errors (fn [_] (throw (IllegalStateException. "Woah...")))) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 500 (response :status))) (is (logged? #".*Internal Server Error.*" :error)) (is (re-matches #"Internal Server Error.*" (get json-body "msg" "")))))) (testing "can be plain text" (logutils/with-test-logging (let [stack (core/wrap-uncaught-errors (fn [_] (throw (IllegalStateException. "Woah..."))) :plain) response (stack (basic-request))] (is (re-matches #"text/plain.*" (get-in response [:headers "Content-Type"]))))))))
true
(ns puppetlabs.ring-middleware.core-test (:require [cheshire.core :as json] [clojure.test :refer :all] [compojure.core :refer :all] [compojure.handler :as handler] [compojure.route :as route] [puppetlabs.ring-middleware.core :as core] [puppetlabs.ring-middleware.utils :as utils] [puppetlabs.ring-middleware.testutils.common :refer :all] [puppetlabs.ssl-utils.core :refer [pem->cert]] [puppetlabs.ssl-utils.simple :as ssl-simple] [puppetlabs.trapperkeeper.app :refer [get-service]] [puppetlabs.trapperkeeper.services.webserver.jetty9-service :refer :all] [puppetlabs.trapperkeeper.testutils.bootstrap :refer [with-app-with-config]] [puppetlabs.trapperkeeper.testutils.logging :as logutils] [ring.util.response :as rr] [schema.core :as schema] [slingshot.slingshot :as slingshot])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Testing Helpers (def WackSchema [schema/Str]) (schema/defn ^:always-validate cause-schema-error [request :- WackSchema] (throw (IllegalStateException. "The test should have never gotten here..."))) (defn throwing-handler [kind msg] (fn [_] (slingshot/throw+ {:kind kind :msg msg}))) (defn basic-request ([] (basic-request "foo-agent" :get "https://example.com")) ([subject method uri] {:request-method method :uri uri :ssl-client-cert (:cert (ssl-simple/gen-self-signed-cert subject 1 {:keylength 5PI:KEY:<KEY>END_PI})) :authorization {:certificate "foo"}})) (defn post-target-handler [req] (if (= (:request-method req) :post) {:status 200 :body (slurp (:body req))} {:status 404 :body "Z'oh"})) (defn proxy-target-handler [req] (condp = (:uri req) "/hello" {:status 302 :headers {"Location" "/hello/world"}} "/hello/" {:status 302 :headers {"Location" "/hello/world"}} "/hello/world" {:status 200 :body "Hello, World!"} "/hello/wrong-host" {:status 302 :headers {"Location" "http://localhost:4/fake"}} "/hello/fully-qualified" {:status 302 :headers {"Location" "http://localhost:9000/hello/world"}} "/hello/different-path" {:status 302 :headers {"Location" "http://localhost:9000/different/"}} {:status 404 :body "D'oh"})) (defn non-proxy-target [_] {:status 200 :body "Non-proxied path"}) (def gzip-body (apply str (repeat 1000 "f"))) (defn proxy-gzip-response [_] (-> gzip-body (rr/response) (rr/status 200) (rr/content-type "text/plain") (rr/charset "UTF-8"))) (defn proxy-error-handler [_] {:status 404 :body "N'oh"}) (defn proxy-regex-response [req] {:status 200 :body (str "Proxied to " (:uri req))}) (defroutes fallthrough-routes (GET "/hello/world" [] "Hello, World! (fallthrough)") (GET "/goodbye/world" [] "Goodbye, World! (fallthrough)") (route/not-found "Not Found (fallthrough)")) (def proxy-regex-fallthrough (handler/site fallthrough-routes)) (def proxy-wrapped-app (-> proxy-error-handler (core/wrap-proxy "/hello-proxy" "http://localhost:9000/hello"))) (def proxy-wrapped-app-ssl (-> proxy-error-handler (core/wrap-proxy "/hello-proxy" "https://localhost:9001/hello" {:ssl-cert "./dev-resources/config/jetty/ssl/certs/localhost.pem" :ssl-key "./dev-resources/config/jetty/ssl/private_keys/localhost.PI:KEY:<KEY>END_PI" :ssl-ca-cert "./dev-resources/config/jetty/ssl/certs/ca.pem"}))) (def proxy-wrapped-app-redirects (-> proxy-error-handler (core/wrap-proxy "/hello-proxy" "http://localhost:9000/hello" {:force-redirects true :follow-redirects true}))) (def proxy-wrapped-app-regex (-> proxy-regex-fallthrough (core/wrap-proxy #"^/([^/]+/certificate.*)$" "http://localhost:9000/hello"))) (def proxy-wrapped-app-regex-alt (-> proxy-regex-fallthrough (core/wrap-proxy #"/hello-proxy" "http://localhost:9000/hello"))) (def proxy-wrapped-app-regex-no-prepend (-> proxy-regex-fallthrough (core/wrap-proxy #"^/([^/]+/certificate.*)$" "http://localhost:9000"))) (def proxy-wrapped-app-regex-trailing-slash (-> proxy-regex-fallthrough (core/wrap-proxy #"^/([^/]+/certificate.*)$" "http://localhost:9000/"))) (defmacro with-target-and-proxy-servers [{:keys [target proxy proxy-handler ring-handler endpoint target-endpoint]} & body] `(with-app-with-config proxy-target-app# [jetty9-service] {:webserver ~target} (let [target-webserver# (get-service proxy-target-app# :WebserverService)] (add-ring-handler target-webserver# ~ring-handler ~target-endpoint) (add-ring-handler target-webserver# non-proxy-target "/different") (add-ring-handler target-webserver# post-target-handler "/hello/post")) (with-app-with-config proxy-app# [jetty9-service] {:webserver ~proxy} (let [proxy-webserver# (get-service proxy-app# :WebserverService)] (add-ring-handler proxy-webserver# ~proxy-handler ~endpoint)) ~@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Core Helpers (deftest sanitize-client-cert-test (testing "sanitize-client-cert" (let [subject "foo-client" cert (:cert (ssl-simple/gen-self-signed-cert subject 1)) request {:ssl-client-cert cert :authorization {:certificate "stuff"}} response (core/sanitize-client-cert request)] (testing "adds the CN at :ssl-client-cert-cn" (is (= subject (response :ssl-client-cert-cn)))) (testing "removes :ssl-client-cert key from response" (is (nil? (response :ssl-client-cert)))) (testing "remove tk-auth cert info" (is (nil? (get-in response [:authorization :certificate]))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Core Middleware (deftest test-proxy (let [common-ssl-config {:ssl-cert "./dev-resources/config/jetty/ssl/certs/localhost.pem" :ssl-key "./dev-resources/config/jetty/ssl/private_keys/localhost.pem" :ssl-ca-cert "./dev-resources/config/jetty/ssl/certs/ca.pem"}] (testing "basic proxy support" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:9000/hello/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "http://localhost:10000/hello-proxy/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "http://localhost:10000/hello-proxy/world" {:as :stream})] (is (= (slurp (:body response)) "Hello, World!"))) (let [response (http-post "http://localhost:10000/hello-proxy/post/" {:as :stream :body "I'm posted!"})] (is (= (:status response) 200)) (is (= (slurp (:body response)) "I'm posted!"))))) (testing "basic https proxy support" (with-target-and-proxy-servers {:target (merge common-ssl-config {:ssl-host "0.0.0.0" :ssl-port 9001}) :proxy (merge common-ssl-config {:ssl-host "0.0.0.0" :ssl-port 10001}) :proxy-handler proxy-wrapped-app-ssl :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "https://localhost:9001/hello/world" default-options-for-https-client)] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "https://localhost:10001/hello-proxy/world" default-options-for-https-client)] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))))) (testing "basic http->https proxy support" (with-target-and-proxy-servers {:target (merge common-ssl-config {:ssl-host "0.0.0.0" :ssl-port 9001}) :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-ssl :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "https://localhost:9001/hello/world" default-options-for-https-client)] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "http://localhost:10000/hello-proxy/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))))) (testing "basic https->http proxy support" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy (merge common-ssl-config {:ssl-host "0.0.0.0" :ssl-port 10001}) :proxy-handler proxy-wrapped-app :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:9000/hello/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "https://localhost:10001/hello-proxy/world" default-options-for-https-client)] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))))) (testing "redirect test with proxy" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:9000/hello")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "http://localhost:9000/hello/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-get "http://localhost:10000/hello-proxy/" {:follow-redirects false :as :text})] (is (= (:status response) 302)) (is (= "/hello/world" (get-in response [:headers "location"])))) (let [response (http-post "http://localhost:10000/hello-proxy/" {:follow-redirects false :as :text})] (is (= (:status response) 302)) (is (= "/hello/world" (get-in response [:headers "location"])))) (let [response (http-get "http://localhost:10000/hello-proxy/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))))) (testing "proxy redirect succeeds on POST if :force-redirects set true" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-redirects :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:10000/hello-proxy/" {:follow-redirects false :as :text})] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))) (let [response (http-post "http://localhost:10000/hello-proxy/" {:follow-redirects false})] (is (= (:status response) 200))))) (testing "redirect test with fully qualified url, correct host, and proxied path" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-redirects :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:10000/hello-proxy/fully-qualified" {:follow-redirects false :as :text})] (is (= (:status response) 200)) (is (= (:body response) "Hello, World!"))))) (testing "redirect test with correct host on non-proxied path" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-redirects :ring-handler proxy-target-handler :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:9000/different")] (is (= (:status response) 200)) (is (= (:body response) "Non-proxied path"))) (let [response (http-get "http://localhost:10000/different")] (is (= (:status response) 404))) (let [response (http-get "http://localhost:10000/hello-proxy/different-path" {:follow-redirects false :as :text})] (is (= (:status response) 200)) (is (= (:body response) "Non-proxied path"))))) (testing "gzipped responses not truncated" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app :ring-handler proxy-gzip-response :endpoint "/hello-proxy" :target-endpoint "/hello"} (let [response (http-get "http://localhost:9000/hello")] (is (= gzip-body (:body response))) (is (= "gzip" (:orig-content-encoding response)))) (let [response (http-get "http://localhost:10000/hello-proxy/")] (is (= gzip-body (:body response))) (is (= "gzip" (:orig-content-encoding response)))))) (testing "proxy works with regex" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-regex :ring-handler proxy-regex-response :endpoint "/" :target-endpoint "/hello"} (let [response (http-get "http://localhost:10000/production/certificate/foo")] (is (= (:status response) 200)) (is (= (:body response) "Proxied to /hello/production/certificate/foo"))) (let [response (http-get "http://localhost:10000/hello/world")] (is (= (:status response) 200)) (is (= (:body response) "Hello, World! (fallthrough)"))) (let [response (http-get "http://localhost:10000/goodbye/world")] (is (= (:status response) 200)) (is (= (:body response) "Goodbye, World! (fallthrough)"))) (let [response (http-get "http://localhost:10000/production/cert/foo")] (is (= (:status response) 404)) (is (= (:body response) "Not Found (fallthrough)"))))) (testing "proxy regex matches beginning of string" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-regex-alt :ring-handler proxy-regex-response :endpoint "/" :target-endpoint "/hello"} (let [response (http-get "http://localhost:10000/hello-proxy")] (is (= (:status response) 200)) (is (= (:body response) "Proxied to /hello/hello-proxy"))) (let [response (http-get "http://localhost:10000/production/hello-proxy")] (is (= (:status response) 404)) (is (= (:body response) "Not Found (fallthrough)"))))) (testing "proxy regex does not need to match entire request uri" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-regex-alt :ring-handler proxy-regex-response :endpoint "/" :target-endpoint "/hello"} (let [response (http-get "http://localhost:10000/hello-proxy/world")] (is (= (:status response) 200)) (is (= (:body response) "Proxied to /hello/hello-proxy/world"))))) (testing "proxy works with regex and no prepended path" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-regex-no-prepend :ring-handler proxy-regex-response :endpoint "/" :target-endpoint "/"} (let [response (http-get "http://localhost:10000/production/certificate/foo")] (is (= (:status response) 200)) (is (= (:body response) "Proxied to /production/certificate/foo"))))) (testing "no repeat slashes exist in rewritten uri" (with-target-and-proxy-servers {:target {:host "0.0.0.0" :port 9000} :proxy {:host "0.0.0.0" :port 10000} :proxy-handler proxy-wrapped-app-regex-trailing-slash :ring-handler proxy-regex-response :endpoint "/" :target-endpoint "/"} (let [response (http-get "http://localhost:10000/production/certificate/foo")] (is (= (:status response) 200)) (is (= (:body response) "Proxied to /production/certificate/foo"))))))) (deftest test-wrap-add-cache-headers (let [put-request {:request-method :put} get-request {:request-method :get} post-request {:request-method :post} delete-request {:request-method :delete} no-cache-header "private, max-age=0, no-cache"] (testing "wrap-add-cache-headers ignores nil response" (let [handler (constantly nil) wrapped-handler (core/wrap-add-cache-headers handler)] (is (nil? (wrapped-handler put-request))) (is (nil? (wrapped-handler get-request))) (is (nil? (wrapped-handler post-request))) (is (nil? (wrapped-handler delete-request))))) (testing "wrap-add-cache-headers observes handled response" (let [handler (constantly {}) wrapped-handler (core/wrap-add-cache-headers handler) handled-response {:headers {"cache-control" no-cache-header}} not-handled-response {}] (is (= handled-response (wrapped-handler get-request))) (is (= handled-response (wrapped-handler put-request))) (is (= not-handled-response (wrapped-handler post-request))) (is (= not-handled-response (wrapped-handler delete-request))))) (testing "wrap-add-cache-headers doesn't stomp on existing headers" (let [fake-response {:headers {:something "Hi mom"}} handler (constantly fake-response) wrapped-handler (core/wrap-add-cache-headers handler) handled-response {:headers {:something "Hi mom" "cache-control" no-cache-header}} not-handled-response fake-response] (is (= handled-response (wrapped-handler get-request))) (is (= handled-response (wrapped-handler put-request))) (is (= not-handled-response (wrapped-handler post-request))) (is (= not-handled-response (wrapped-handler delete-request))))))) (deftest test-wrap-with-cn (testing "When extracting a CN from a cert" (testing "and there is no cert" (let [mw-fn (core/wrap-with-certificate-cn identity) post-req (mw-fn {})] (testing "ssl-client-cn is set to nil" (is (= post-req {:ssl-client-cn nil}))))) (testing "and there is a cert" (let [mw-fn (core/wrap-with-certificate-cn identity) post-req (mw-fn {:ssl-client-cert (pem->cert "dev-resources/ssl/cert.pem")})] (testing "ssl-client-cn is set properly" (is (= (:ssl-client-cn post-req) "localhost"))))))) (deftest test-wrap-add-x-frame-options-deny (let [get-request {:request-method :get} put-request {:request-method :put} post-request {:request-method :post} delete-request {:request-method :delete} x-frame-header "DENY"] (testing "wrap-add-x-frame-options-deny ignores nil response" (let [handler (constantly nil) wrapped-handler (core/wrap-add-x-frame-options-deny handler)] (is (nil? (wrapped-handler get-request))) (is (nil? (wrapped-handler put-request))) (is (nil? (wrapped-handler post-request))) (is (nil? (wrapped-handler delete-request))))) (testing "wrap-add-x-frame-options-deny observes handled response" (let [handler (constantly {}) wrapped-handler (core/wrap-add-x-frame-options-deny handler) handled-response {:headers {"X-Frame-Options" x-frame-header}} not-handled-response {}] (is (= handled-response (wrapped-handler get-request))) (is (= handled-response (wrapped-handler put-request))) (is (= handled-response (wrapped-handler post-request))) (is (= handled-response (wrapped-handler delete-request))))) (testing "wrap-add-x-frame-options-deny doesn't stomp on existing headers" (let [fake-response {:headers {:something "Hi mom"}} handler (constantly fake-response) wrapped-handler (core/wrap-add-x-frame-options-deny handler) handled-response {:headers {:something "Hi mom" "X-Frame-Options" x-frame-header}}] (is (= handled-response (wrapped-handler get-request))) (is (= handled-response (wrapped-handler put-request))) (is (= handled-response (wrapped-handler post-request))) (is (= handled-response (wrapped-handler delete-request))))))) (deftest wrap-response-logging-test (testing "wrap-response-logging" (logutils/with-test-logging (let [stack (core/wrap-response-logging identity) response (stack (basic-request))] (is (logged? #"Computed response.*" :trace)))))) (deftest wrap-request-logging-test (testing "wrap-request-logging" (logutils/with-test-logging (let [subject "foo-agent" method :get uri "https://example.com" stack (core/wrap-request-logging identity) request (basic-request subject method uri) response (stack request)] (is (logged? (format "Processing %s %s" method uri) :debug)) (is (logged? #"Full request" :trace)))))) (deftest wrap-data-errors-test (testing "wrap-data-errors" (testing "default behavior" (logutils/with-test-logging (let [stack (core/wrap-data-errors (throwing-handler :user-data-invalid "Error Message")) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 400 (response :status))) (is (= "Error Message" (get json-body "msg"))) (is (logged? #"Error Message" :error)) (is (logged? #"Submitted data is invalid" :error))))) (doseq [error [:request-data-invalid :user-data-invalid :service-status-version-not-found]] (testing (str "handles errors of " error) (logutils/with-test-logging (let [stack (core/wrap-data-errors (throwing-handler error "Error Message")) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 400 (response :status))) (is (= (name error) (get json-body "kind"))))))) (testing "handles errors thrown by `throw-data-invalid!`" (logutils/with-test-logging (let [stack (core/wrap-data-errors (fn [_] (utils/throw-data-invalid! "Error Message"))) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 400 (response :status))) (is (= (name "data-invalid") (get json-body "kind")))))) (testing "can be plain text" (logutils/with-test-logging (let [stack (core/wrap-data-errors (throwing-handler :user-data-invalid "Error Message") :plain) response (stack (basic-request))] (is (re-matches #"text/plain.*" (get-in response [:headers "Content-Type"])))))))) (deftest wrap-bad-request-test (testing "wrap-bad-request" (testing "default behavior" (logutils/with-test-logging (let [stack (core/wrap-bad-request (fn [_] (utils/throw-bad-request! "Error Message"))) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 400 (response :status))) (is (logged? #".*Bad Request.*" :error)) (is (re-matches #"Error Message.*" (get json-body "msg" ""))) (is (= "bad-request" (get json-body "kind")))))) (testing "can be plain text" (logutils/with-test-logging (let [stack (core/wrap-bad-request (fn [_] (utils/throw-bad-request! "Error Message")) :plain) response (stack (basic-request))] (is (re-matches #"text/plain.*" (get-in response [:headers "Content-Type"])))))))) (deftest wrap-schema-errors-test (testing "wrap-schema-errors" (testing "default behavior" (logutils/with-test-logging (let [stack (core/wrap-schema-errors cause-schema-error) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 500 (response :status))) (is (logged? #".*Something unexpected.*" :error)) (is (re-matches #"Something unexpected.*" (get json-body "msg" ""))) (is (= "application-error" (get json-body "kind")))))) (testing "can be plain text" (logutils/with-test-logging (let [stack (core/wrap-schema-errors cause-schema-error :plain) response (stack (basic-request))] (is (re-matches #"text/plain.*" (get-in response [:headers "Content-Type"])))))))) (deftest wrap-service-unavailable-test (testing "wrap-service-unavailable" (testing "default behavior" (logutils/with-test-logging (let [stack (core/wrap-service-unavailable (fn [_] (utils/throw-service-unavailable! "Test Service is DOWN!"))) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 503 (response :status))) (is (logged? #".*Service Unavailable.*" :error)) (is (= "Test Service is DOWN!" (get json-body "msg"))) (is (= "service-unavailable" (get json-body "kind")))))) (testing "can be plain text" (logutils/with-test-logging (let [stack (core/wrap-service-unavailable (fn [_] (utils/throw-service-unavailable! "Test Service is DOWN!")) :plain) response (stack (basic-request))] (is (re-matches #"text/plain.*" (get-in response [:headers "Content-Type"])))))))) (deftest wrap-uncaught-errors-test (testing "wrap-uncaught-errors" (testing "default behavior" (logutils/with-test-logging (let [stack (core/wrap-uncaught-errors (fn [_] (throw (IllegalStateException. "Woah...")))) response (stack (basic-request)) json-body (json/parse-string (response :body))] (is (= 500 (response :status))) (is (logged? #".*Internal Server Error.*" :error)) (is (re-matches #"Internal Server Error.*" (get json-body "msg" "")))))) (testing "can be plain text" (logutils/with-test-logging (let [stack (core/wrap-uncaught-errors (fn [_] (throw (IllegalStateException. "Woah..."))) :plain) response (stack (basic-request))] (is (re-matches #"text/plain.*" (get-in response [:headers "Content-Type"]))))))))
[ { "context": ";; Copyright (C) 2018, 2019 by Vlad Kozin\n\n(ns bitfinex-example\n (:require [medley.core :r", "end": 41, "score": 0.999836802482605, "start": 31, "tag": "NAME", "value": "Vlad Kozin" } ]
src/exch/bitfinex_example.clj
vkz/bot
1
;; Copyright (C) 2018, 2019 by Vlad Kozin (ns bitfinex-example (:require [medley.core :refer :all] [manifold.stream :as s] [aleph.http :as http] [cheshire.core :as json] [clojure.string :as string] [clojure.pprint :refer [pprint]] [clojure.core.async :as async] [taoensso.timbre :as log] [clojure.edn :as edn])) (require '[exch :refer :all] :reload) (require '[bitfinex :as bx] :reload) (def tick (ticker :usd/eth)) (log/info "Creating connection") (def c (bx/create-connection)) (log/info "Creating exch") (def e (create-exch c)) (log/info "Start standard handlers") (def handlers-ch (start-standard-msg-handlers e tick)) (defn run-stub [] (connect c) (defadvice print-before-convert :before :incomming [conn msg] (println "Before convert:") (pprint msg) msg) (defadvice print-after-convert :after :incomming [conn msg] (println "After convert:") (pprint msg) msg) (advise c print-before-convert) (advise c print-after-convert) (async/put! (:stub-in c) (json/encode {"event" "subscribed" "chanId" 10961 "pair" "ETHUSD"})) #_(apply-advice c [:before :incomming] {:foo :bar}) (async/put! (:stub-in c) (json/encode '(10961 [[584.58 11 65.64632441] [584.51 1 0.93194317] [584.59 4 -23.39216286] [584.96 1 -7.23746288] [584.97 1 -12.3]]))) (async/put! (:stub-in c) (json/encode '(10961 [583.75 1 1]))) (async/put! (:stub-in c) (json/encode '(10961 [584.97 0 -1]))) (async/put! (:stub-in c) (json/encode '(10961 [584.59 4 -23.34100906]))) (async/put! (:stub-in c) (json/encode '(10961 [586.94 1 -29.9]))) (async/put! (:stub-in c) (json/encode '(10961 [583.75 0 1]))) (Thread/sleep 3000) (unadvise c print-before-convert) (unadvise c print-after-convert) (disconnect c)) (defn run-exch [] (log/info "Connecting to exchange") (connect c) (send-to-exch e [:ping]) (def book (get-book e tick)) (log/info "Book subscribed? " (book-subscribed? book)) (book-sub book) (def result (async/thread (let [result (vector (do (Thread/sleep 3000) (book-snapshot book)) (do (Thread/sleep 2000) (book-snapshot book)))] (log/info "Book subscribed? " (book-subscribed? book)) (book-unsub book) (Thread/sleep 2000) result))) (pprint (async/<!! result)) (log/info "Book subscribed? " (book-subscribed? book)) (disconnect c)) (defn -main [arg] (case (edn/read-string arg) run-stub (run-stub) run-exch (run-exch)))
23317
;; Copyright (C) 2018, 2019 by <NAME> (ns bitfinex-example (:require [medley.core :refer :all] [manifold.stream :as s] [aleph.http :as http] [cheshire.core :as json] [clojure.string :as string] [clojure.pprint :refer [pprint]] [clojure.core.async :as async] [taoensso.timbre :as log] [clojure.edn :as edn])) (require '[exch :refer :all] :reload) (require '[bitfinex :as bx] :reload) (def tick (ticker :usd/eth)) (log/info "Creating connection") (def c (bx/create-connection)) (log/info "Creating exch") (def e (create-exch c)) (log/info "Start standard handlers") (def handlers-ch (start-standard-msg-handlers e tick)) (defn run-stub [] (connect c) (defadvice print-before-convert :before :incomming [conn msg] (println "Before convert:") (pprint msg) msg) (defadvice print-after-convert :after :incomming [conn msg] (println "After convert:") (pprint msg) msg) (advise c print-before-convert) (advise c print-after-convert) (async/put! (:stub-in c) (json/encode {"event" "subscribed" "chanId" 10961 "pair" "ETHUSD"})) #_(apply-advice c [:before :incomming] {:foo :bar}) (async/put! (:stub-in c) (json/encode '(10961 [[584.58 11 65.64632441] [584.51 1 0.93194317] [584.59 4 -23.39216286] [584.96 1 -7.23746288] [584.97 1 -12.3]]))) (async/put! (:stub-in c) (json/encode '(10961 [583.75 1 1]))) (async/put! (:stub-in c) (json/encode '(10961 [584.97 0 -1]))) (async/put! (:stub-in c) (json/encode '(10961 [584.59 4 -23.34100906]))) (async/put! (:stub-in c) (json/encode '(10961 [586.94 1 -29.9]))) (async/put! (:stub-in c) (json/encode '(10961 [583.75 0 1]))) (Thread/sleep 3000) (unadvise c print-before-convert) (unadvise c print-after-convert) (disconnect c)) (defn run-exch [] (log/info "Connecting to exchange") (connect c) (send-to-exch e [:ping]) (def book (get-book e tick)) (log/info "Book subscribed? " (book-subscribed? book)) (book-sub book) (def result (async/thread (let [result (vector (do (Thread/sleep 3000) (book-snapshot book)) (do (Thread/sleep 2000) (book-snapshot book)))] (log/info "Book subscribed? " (book-subscribed? book)) (book-unsub book) (Thread/sleep 2000) result))) (pprint (async/<!! result)) (log/info "Book subscribed? " (book-subscribed? book)) (disconnect c)) (defn -main [arg] (case (edn/read-string arg) run-stub (run-stub) run-exch (run-exch)))
true
;; Copyright (C) 2018, 2019 by PI:NAME:<NAME>END_PI (ns bitfinex-example (:require [medley.core :refer :all] [manifold.stream :as s] [aleph.http :as http] [cheshire.core :as json] [clojure.string :as string] [clojure.pprint :refer [pprint]] [clojure.core.async :as async] [taoensso.timbre :as log] [clojure.edn :as edn])) (require '[exch :refer :all] :reload) (require '[bitfinex :as bx] :reload) (def tick (ticker :usd/eth)) (log/info "Creating connection") (def c (bx/create-connection)) (log/info "Creating exch") (def e (create-exch c)) (log/info "Start standard handlers") (def handlers-ch (start-standard-msg-handlers e tick)) (defn run-stub [] (connect c) (defadvice print-before-convert :before :incomming [conn msg] (println "Before convert:") (pprint msg) msg) (defadvice print-after-convert :after :incomming [conn msg] (println "After convert:") (pprint msg) msg) (advise c print-before-convert) (advise c print-after-convert) (async/put! (:stub-in c) (json/encode {"event" "subscribed" "chanId" 10961 "pair" "ETHUSD"})) #_(apply-advice c [:before :incomming] {:foo :bar}) (async/put! (:stub-in c) (json/encode '(10961 [[584.58 11 65.64632441] [584.51 1 0.93194317] [584.59 4 -23.39216286] [584.96 1 -7.23746288] [584.97 1 -12.3]]))) (async/put! (:stub-in c) (json/encode '(10961 [583.75 1 1]))) (async/put! (:stub-in c) (json/encode '(10961 [584.97 0 -1]))) (async/put! (:stub-in c) (json/encode '(10961 [584.59 4 -23.34100906]))) (async/put! (:stub-in c) (json/encode '(10961 [586.94 1 -29.9]))) (async/put! (:stub-in c) (json/encode '(10961 [583.75 0 1]))) (Thread/sleep 3000) (unadvise c print-before-convert) (unadvise c print-after-convert) (disconnect c)) (defn run-exch [] (log/info "Connecting to exchange") (connect c) (send-to-exch e [:ping]) (def book (get-book e tick)) (log/info "Book subscribed? " (book-subscribed? book)) (book-sub book) (def result (async/thread (let [result (vector (do (Thread/sleep 3000) (book-snapshot book)) (do (Thread/sleep 2000) (book-snapshot book)))] (log/info "Book subscribed? " (book-subscribed? book)) (book-unsub book) (Thread/sleep 2000) result))) (pprint (async/<!! result)) (log/info "Book subscribed? " (book-subscribed? book)) (disconnect c)) (defn -main [arg] (case (edn/read-string arg) run-stub (run-stub) run-exch (run-exch)))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998068809509277, "start": 18, "tag": "NAME", "value": "Rich Hickey" } ]
Chapter 07 Code/niko/clojure/test/clojure/test_clojure/data_structures_interop.clj
PacktPublishing/Clojure-Programming-Cookbook
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 clojure.test-clojure.data-structures-interop (:require [clojure.test :refer :all] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [clojure.test.check.clojure-test :refer (defspec)])) (defn gen-range [min max] (gen/bind (gen/choose min max) (fn [n] (gen/tuple (gen/return n) (gen/choose n max))))) (defn gen-subvec [generator] (gen/bind (gen/not-empty generator) (fn [v] (gen/bind (gen-range 0 (dec (count v))) (fn [[n m]] (gen/return (subvec v n m))))))) (defn gen-gvec ([] (gen/bind (gen/elements {:int gen/int :short (gen/fmap short gen/byte) :long (gen/fmap long gen/int) :float (gen/fmap float gen/int) :double (gen/fmap double gen/int) :byte gen/byte :char gen/char :boolean gen/boolean}) #(apply gen-gvec %))) ([type generator] (gen/bind (gen/list generator) #(gen/return (apply vector-of type %))))) (defn gen-hash-set [generator] (gen/fmap (partial apply hash-set) (gen/list generator))) (defn gen-sorted-set [generator] (gen/fmap (partial apply sorted-set) (gen/list generator))) (defn gen-array-map [key-gen val-gen] (gen/fmap (partial into (array-map)) (gen/map key-gen val-gen))) (defn gen-sorted-map [key-gen val-gen] (gen/fmap (partial into (sorted-map)) (gen/map key-gen val-gen))) (defn gen-array ([] (gen/bind (gen/elements {int-array gen/int short-array gen/int long-array (gen/fmap long gen/int) float-array (gen/fmap float gen/int) double-array (gen/fmap double gen/int) byte-array gen/byte char-array gen/char boolean-array gen/boolean object-array gen/string}) #(apply gen-array %))) ([array-fn generator] (gen/fmap array-fn (gen/list generator)))) (defn exaust-iterator-forward [^java.util.Iterator iter] (loop [_ iter] (when (.hasNext iter) (recur (.next iter)))) (try (.next iter) nil (catch Throwable t t))) (defn exaust-iterator-backward [^java.util.ListIterator iter] (loop [_ iter] (when (.hasPrevious iter) (recur (.previous iter)))) (try (.previous iter) nil (catch Throwable t t))) (defspec iterator-throws-exception-on-exaustion 100 (prop/for-all [[_ x] (gen/bind (gen/elements [['list (gen/list gen/int)] ['vector (gen/vector gen/int)] ['vector-of (gen-gvec)] ['subvec (gen-subvec (gen/vector gen/int))] ['hash-set (gen-hash-set gen/int)] ['sorted-set (gen-sorted-set gen/int)] ['hash-map (gen/hash-map gen/symbol gen/int)] ['array-map (gen-array-map gen/symbol gen/int)] ['sorted-map (gen-sorted-map gen/symbol gen/int)]]) (fn [[s g]] (gen/tuple (gen/return s) g)))] (instance? java.util.NoSuchElementException (exaust-iterator-forward (.iterator x))))) (defspec array-iterator-throws-exception-on-exaustion 100 (prop/for-all [arr (gen-array)] (let [iter (clojure.lang.ArrayIter/createFromObject arr)] (instance? java.util.NoSuchElementException (exaust-iterator-forward iter))))) (defspec list-iterator-throws-exception-on-forward-exaustion 50 (prop/for-all [[_ x] (gen/bind (gen/elements [['vector (gen/vector gen/int)] ['subvec (gen-subvec (gen/vector gen/int))] ['vector-of (gen-gvec)]]) (fn [[s g]] (gen/tuple (gen/return s) g)))] (instance? java.util.NoSuchElementException (exaust-iterator-forward (.listIterator x))))) (defspec list-iterator-throws-exception-on-backward-exaustion 50 (prop/for-all [[_ x] (gen/bind (gen/elements [['vector (gen/vector gen/int)] ['subvec (gen-subvec (gen/vector gen/int))] ['vector-of (gen-gvec)]]) (fn [[s g]] (gen/tuple (gen/return s) g)))] (instance? java.util.NoSuchElementException (exaust-iterator-backward (.listIterator x))))) (defspec map-keyset-iterator-throws-exception-on-exaustion 50 (prop/for-all [[_ m] (gen/bind (gen/elements [['hash-map (gen/hash-map gen/symbol gen/int) 'array-map (gen-array-map gen/symbol gen/int) 'sorted-map (gen-sorted-map gen/symbol gen/int)]]) (fn [[s g]] (gen/tuple (gen/return s) g)))] (let [iter (.iterator (.keySet m))] (instance? java.util.NoSuchElementException (exaust-iterator-forward iter))))) (defspec map-values-iterator-throws-exception-on-exaustion 50 (prop/for-all [[_ m] (gen/bind (gen/elements [['hash-map (gen/hash-map gen/symbol gen/int) 'array-map (gen-array-map gen/symbol gen/int) 'sorted-map (gen-sorted-map gen/symbol gen/int)]]) (fn [[s g]] (gen/tuple (gen/return s) g)))] (let [iter (.iterator (.values m))] (instance? java.util.NoSuchElementException (exaust-iterator-forward iter))))) (defspec map-keys-iterator-throws-exception-on-exaustion 50 (prop/for-all [m (gen-sorted-map gen/symbol gen/int)] (instance? java.util.NoSuchElementException (exaust-iterator-forward (.keys m))))) (defspec map-vals-iterator-throws-exception-on-exaustion 50 (prop/for-all [m (gen-sorted-map gen/symbol gen/int)] (instance? java.util.NoSuchElementException (exaust-iterator-forward (.vals m))))) (defspec map-reverse-iterator-throws-exception-on-exaustion 50 (prop/for-all [m (gen-sorted-map gen/symbol gen/int)] (instance? java.util.NoSuchElementException (exaust-iterator-forward (.reverseIterator m)))))
37081
; 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 clojure.test-clojure.data-structures-interop (:require [clojure.test :refer :all] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [clojure.test.check.clojure-test :refer (defspec)])) (defn gen-range [min max] (gen/bind (gen/choose min max) (fn [n] (gen/tuple (gen/return n) (gen/choose n max))))) (defn gen-subvec [generator] (gen/bind (gen/not-empty generator) (fn [v] (gen/bind (gen-range 0 (dec (count v))) (fn [[n m]] (gen/return (subvec v n m))))))) (defn gen-gvec ([] (gen/bind (gen/elements {:int gen/int :short (gen/fmap short gen/byte) :long (gen/fmap long gen/int) :float (gen/fmap float gen/int) :double (gen/fmap double gen/int) :byte gen/byte :char gen/char :boolean gen/boolean}) #(apply gen-gvec %))) ([type generator] (gen/bind (gen/list generator) #(gen/return (apply vector-of type %))))) (defn gen-hash-set [generator] (gen/fmap (partial apply hash-set) (gen/list generator))) (defn gen-sorted-set [generator] (gen/fmap (partial apply sorted-set) (gen/list generator))) (defn gen-array-map [key-gen val-gen] (gen/fmap (partial into (array-map)) (gen/map key-gen val-gen))) (defn gen-sorted-map [key-gen val-gen] (gen/fmap (partial into (sorted-map)) (gen/map key-gen val-gen))) (defn gen-array ([] (gen/bind (gen/elements {int-array gen/int short-array gen/int long-array (gen/fmap long gen/int) float-array (gen/fmap float gen/int) double-array (gen/fmap double gen/int) byte-array gen/byte char-array gen/char boolean-array gen/boolean object-array gen/string}) #(apply gen-array %))) ([array-fn generator] (gen/fmap array-fn (gen/list generator)))) (defn exaust-iterator-forward [^java.util.Iterator iter] (loop [_ iter] (when (.hasNext iter) (recur (.next iter)))) (try (.next iter) nil (catch Throwable t t))) (defn exaust-iterator-backward [^java.util.ListIterator iter] (loop [_ iter] (when (.hasPrevious iter) (recur (.previous iter)))) (try (.previous iter) nil (catch Throwable t t))) (defspec iterator-throws-exception-on-exaustion 100 (prop/for-all [[_ x] (gen/bind (gen/elements [['list (gen/list gen/int)] ['vector (gen/vector gen/int)] ['vector-of (gen-gvec)] ['subvec (gen-subvec (gen/vector gen/int))] ['hash-set (gen-hash-set gen/int)] ['sorted-set (gen-sorted-set gen/int)] ['hash-map (gen/hash-map gen/symbol gen/int)] ['array-map (gen-array-map gen/symbol gen/int)] ['sorted-map (gen-sorted-map gen/symbol gen/int)]]) (fn [[s g]] (gen/tuple (gen/return s) g)))] (instance? java.util.NoSuchElementException (exaust-iterator-forward (.iterator x))))) (defspec array-iterator-throws-exception-on-exaustion 100 (prop/for-all [arr (gen-array)] (let [iter (clojure.lang.ArrayIter/createFromObject arr)] (instance? java.util.NoSuchElementException (exaust-iterator-forward iter))))) (defspec list-iterator-throws-exception-on-forward-exaustion 50 (prop/for-all [[_ x] (gen/bind (gen/elements [['vector (gen/vector gen/int)] ['subvec (gen-subvec (gen/vector gen/int))] ['vector-of (gen-gvec)]]) (fn [[s g]] (gen/tuple (gen/return s) g)))] (instance? java.util.NoSuchElementException (exaust-iterator-forward (.listIterator x))))) (defspec list-iterator-throws-exception-on-backward-exaustion 50 (prop/for-all [[_ x] (gen/bind (gen/elements [['vector (gen/vector gen/int)] ['subvec (gen-subvec (gen/vector gen/int))] ['vector-of (gen-gvec)]]) (fn [[s g]] (gen/tuple (gen/return s) g)))] (instance? java.util.NoSuchElementException (exaust-iterator-backward (.listIterator x))))) (defspec map-keyset-iterator-throws-exception-on-exaustion 50 (prop/for-all [[_ m] (gen/bind (gen/elements [['hash-map (gen/hash-map gen/symbol gen/int) 'array-map (gen-array-map gen/symbol gen/int) 'sorted-map (gen-sorted-map gen/symbol gen/int)]]) (fn [[s g]] (gen/tuple (gen/return s) g)))] (let [iter (.iterator (.keySet m))] (instance? java.util.NoSuchElementException (exaust-iterator-forward iter))))) (defspec map-values-iterator-throws-exception-on-exaustion 50 (prop/for-all [[_ m] (gen/bind (gen/elements [['hash-map (gen/hash-map gen/symbol gen/int) 'array-map (gen-array-map gen/symbol gen/int) 'sorted-map (gen-sorted-map gen/symbol gen/int)]]) (fn [[s g]] (gen/tuple (gen/return s) g)))] (let [iter (.iterator (.values m))] (instance? java.util.NoSuchElementException (exaust-iterator-forward iter))))) (defspec map-keys-iterator-throws-exception-on-exaustion 50 (prop/for-all [m (gen-sorted-map gen/symbol gen/int)] (instance? java.util.NoSuchElementException (exaust-iterator-forward (.keys m))))) (defspec map-vals-iterator-throws-exception-on-exaustion 50 (prop/for-all [m (gen-sorted-map gen/symbol gen/int)] (instance? java.util.NoSuchElementException (exaust-iterator-forward (.vals m))))) (defspec map-reverse-iterator-throws-exception-on-exaustion 50 (prop/for-all [m (gen-sorted-map gen/symbol gen/int)] (instance? java.util.NoSuchElementException (exaust-iterator-forward (.reverseIterator m)))))
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 clojure.test-clojure.data-structures-interop (:require [clojure.test :refer :all] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [clojure.test.check.clojure-test :refer (defspec)])) (defn gen-range [min max] (gen/bind (gen/choose min max) (fn [n] (gen/tuple (gen/return n) (gen/choose n max))))) (defn gen-subvec [generator] (gen/bind (gen/not-empty generator) (fn [v] (gen/bind (gen-range 0 (dec (count v))) (fn [[n m]] (gen/return (subvec v n m))))))) (defn gen-gvec ([] (gen/bind (gen/elements {:int gen/int :short (gen/fmap short gen/byte) :long (gen/fmap long gen/int) :float (gen/fmap float gen/int) :double (gen/fmap double gen/int) :byte gen/byte :char gen/char :boolean gen/boolean}) #(apply gen-gvec %))) ([type generator] (gen/bind (gen/list generator) #(gen/return (apply vector-of type %))))) (defn gen-hash-set [generator] (gen/fmap (partial apply hash-set) (gen/list generator))) (defn gen-sorted-set [generator] (gen/fmap (partial apply sorted-set) (gen/list generator))) (defn gen-array-map [key-gen val-gen] (gen/fmap (partial into (array-map)) (gen/map key-gen val-gen))) (defn gen-sorted-map [key-gen val-gen] (gen/fmap (partial into (sorted-map)) (gen/map key-gen val-gen))) (defn gen-array ([] (gen/bind (gen/elements {int-array gen/int short-array gen/int long-array (gen/fmap long gen/int) float-array (gen/fmap float gen/int) double-array (gen/fmap double gen/int) byte-array gen/byte char-array gen/char boolean-array gen/boolean object-array gen/string}) #(apply gen-array %))) ([array-fn generator] (gen/fmap array-fn (gen/list generator)))) (defn exaust-iterator-forward [^java.util.Iterator iter] (loop [_ iter] (when (.hasNext iter) (recur (.next iter)))) (try (.next iter) nil (catch Throwable t t))) (defn exaust-iterator-backward [^java.util.ListIterator iter] (loop [_ iter] (when (.hasPrevious iter) (recur (.previous iter)))) (try (.previous iter) nil (catch Throwable t t))) (defspec iterator-throws-exception-on-exaustion 100 (prop/for-all [[_ x] (gen/bind (gen/elements [['list (gen/list gen/int)] ['vector (gen/vector gen/int)] ['vector-of (gen-gvec)] ['subvec (gen-subvec (gen/vector gen/int))] ['hash-set (gen-hash-set gen/int)] ['sorted-set (gen-sorted-set gen/int)] ['hash-map (gen/hash-map gen/symbol gen/int)] ['array-map (gen-array-map gen/symbol gen/int)] ['sorted-map (gen-sorted-map gen/symbol gen/int)]]) (fn [[s g]] (gen/tuple (gen/return s) g)))] (instance? java.util.NoSuchElementException (exaust-iterator-forward (.iterator x))))) (defspec array-iterator-throws-exception-on-exaustion 100 (prop/for-all [arr (gen-array)] (let [iter (clojure.lang.ArrayIter/createFromObject arr)] (instance? java.util.NoSuchElementException (exaust-iterator-forward iter))))) (defspec list-iterator-throws-exception-on-forward-exaustion 50 (prop/for-all [[_ x] (gen/bind (gen/elements [['vector (gen/vector gen/int)] ['subvec (gen-subvec (gen/vector gen/int))] ['vector-of (gen-gvec)]]) (fn [[s g]] (gen/tuple (gen/return s) g)))] (instance? java.util.NoSuchElementException (exaust-iterator-forward (.listIterator x))))) (defspec list-iterator-throws-exception-on-backward-exaustion 50 (prop/for-all [[_ x] (gen/bind (gen/elements [['vector (gen/vector gen/int)] ['subvec (gen-subvec (gen/vector gen/int))] ['vector-of (gen-gvec)]]) (fn [[s g]] (gen/tuple (gen/return s) g)))] (instance? java.util.NoSuchElementException (exaust-iterator-backward (.listIterator x))))) (defspec map-keyset-iterator-throws-exception-on-exaustion 50 (prop/for-all [[_ m] (gen/bind (gen/elements [['hash-map (gen/hash-map gen/symbol gen/int) 'array-map (gen-array-map gen/symbol gen/int) 'sorted-map (gen-sorted-map gen/symbol gen/int)]]) (fn [[s g]] (gen/tuple (gen/return s) g)))] (let [iter (.iterator (.keySet m))] (instance? java.util.NoSuchElementException (exaust-iterator-forward iter))))) (defspec map-values-iterator-throws-exception-on-exaustion 50 (prop/for-all [[_ m] (gen/bind (gen/elements [['hash-map (gen/hash-map gen/symbol gen/int) 'array-map (gen-array-map gen/symbol gen/int) 'sorted-map (gen-sorted-map gen/symbol gen/int)]]) (fn [[s g]] (gen/tuple (gen/return s) g)))] (let [iter (.iterator (.values m))] (instance? java.util.NoSuchElementException (exaust-iterator-forward iter))))) (defspec map-keys-iterator-throws-exception-on-exaustion 50 (prop/for-all [m (gen-sorted-map gen/symbol gen/int)] (instance? java.util.NoSuchElementException (exaust-iterator-forward (.keys m))))) (defspec map-vals-iterator-throws-exception-on-exaustion 50 (prop/for-all [m (gen-sorted-map gen/symbol gen/int)] (instance? java.util.NoSuchElementException (exaust-iterator-forward (.vals m))))) (defspec map-reverse-iterator-throws-exception-on-exaustion 50 (prop/for-all [m (gen-sorted-map gen/symbol gen/int)] (instance? java.util.NoSuchElementException (exaust-iterator-forward (.reverseIterator m)))))
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-09-06\"\n :doc \"Attribute functio", "end": 105, "score": 0.9998692274093628, "start": 87, "tag": "NAME", "value": "John Alan McDonald" } ]
src/main/clojure/zana/data/attribute.clj
wahpenayo/zana
2
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "John Alan McDonald" :date "2016-09-06" :doc "Attribute function generation."} zana.data.attribute (:refer-clojure :exclude [cast emit name]) (:require [clojure.pprint :as pp] [zana.data.reflect :as r])) ;;------------------------------------------------------------------------------ (defn- hint-args [^clojure.lang.IMeta naked-args ^Class c] (let [csymbol (symbol (.getName c)) return-type (case csymbol boolean 'Boolean char 'Character (byte short int long) 'long (float double) 'double csymbol)] (with-meta naked-args {:tag return-type}))) ;;------------------------------------------------------------------------------ (defn- cast-access [^clojure.lang.IMeta naked-access ^Class c] (let [csymbol (symbol (.getName c)) cast (case csymbol boolean 'Boolean/valueOf char 'Character/valueOf (byte short int long) 'long (float double) 'double nil) access (if cast `(~cast ~naked-access) naked-access)] access)) ;;------------------------------------------------------------------------------ ;; Does this public symbol from another namespace look like an attribute ;; function? ;; TODO: should attributes be marked with special meta-data? (defn- attribute? [field-type f] (let [ms (meta f) arglists (:arglists ms) arglist (first arglists) arg (first arglist) ma (meta arg) argtype (eval (:tag ma))] (and (== 1 (count arglists)) (== 1 (count arglist)) (= field-type argtype)))) ;;------------------------------------------------------------------------------ (defn name [defn-expression] (assert (= 'clojure.core/defn (first defn-expression)) (pr-str (first defn-expression) "\n" defn-expression)) (second defn-expression)) ;;------------------------------------------------------------------------------ (defn- qualified-name ^clojure.lang.Symbol [^clojure.lang.Var v] (symbol (str (:ns (meta v))) (str (:name (meta v))))) ;;------------------------------------------------------------------------------ (defn- return-type ^clojure.lang.Symbol [^clojure.lang.Var v] (r/type (first (:arglists (meta v))))) ;;------------------------------------------------------------------------------ (defn functions [^clojure.lang.Symbol bare-datum-type ^clojure.lang.Symbol field] (let [naked-field (with-meta field {:no-doc true}) ;; turn off codox for now datum-type (r/munge bare-datum-type) datum (gensym "datum") hinted-datum (with-meta datum {:tag datum-type}) naked-args [hinted-datum] field-type (r/type field) args (hint-args naked-args field-type) accessor (symbol (str "." field)) naked-access `(~accessor ~hinted-datum) access (cast-access naked-access field-type) outer `(defn ~naked-field ~args ~access) prefix (str field "-") inner-defn (fn inner-defn [[^clojure.lang.Symbol unqualified-name ^clojure.lang.Var v]] (let [^clojure.lang.Symbol qualified-name (qualified-name v) inner-name (with-meta (symbol (str prefix unqualified-name)) {:no-doc true}) inner-type (return-type v) inner-call (cast-access `(~qualified-name ~access) inner-type) inner-args (hint-args naked-args inner-type)] `(defn ~inner-name ~inner-args ~inner-call))) inner (when (r/datum-class? field-type) (mapv inner-defn (filter (fn [[k v]] (attribute? field-type v)) (ns-publics (r/namespace field-type)))))] (cons outer inner))) ;------------------------------------------------------------------------------
53967
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<NAME>" :date "2016-09-06" :doc "Attribute function generation."} zana.data.attribute (:refer-clojure :exclude [cast emit name]) (:require [clojure.pprint :as pp] [zana.data.reflect :as r])) ;;------------------------------------------------------------------------------ (defn- hint-args [^clojure.lang.IMeta naked-args ^Class c] (let [csymbol (symbol (.getName c)) return-type (case csymbol boolean 'Boolean char 'Character (byte short int long) 'long (float double) 'double csymbol)] (with-meta naked-args {:tag return-type}))) ;;------------------------------------------------------------------------------ (defn- cast-access [^clojure.lang.IMeta naked-access ^Class c] (let [csymbol (symbol (.getName c)) cast (case csymbol boolean 'Boolean/valueOf char 'Character/valueOf (byte short int long) 'long (float double) 'double nil) access (if cast `(~cast ~naked-access) naked-access)] access)) ;;------------------------------------------------------------------------------ ;; Does this public symbol from another namespace look like an attribute ;; function? ;; TODO: should attributes be marked with special meta-data? (defn- attribute? [field-type f] (let [ms (meta f) arglists (:arglists ms) arglist (first arglists) arg (first arglist) ma (meta arg) argtype (eval (:tag ma))] (and (== 1 (count arglists)) (== 1 (count arglist)) (= field-type argtype)))) ;;------------------------------------------------------------------------------ (defn name [defn-expression] (assert (= 'clojure.core/defn (first defn-expression)) (pr-str (first defn-expression) "\n" defn-expression)) (second defn-expression)) ;;------------------------------------------------------------------------------ (defn- qualified-name ^clojure.lang.Symbol [^clojure.lang.Var v] (symbol (str (:ns (meta v))) (str (:name (meta v))))) ;;------------------------------------------------------------------------------ (defn- return-type ^clojure.lang.Symbol [^clojure.lang.Var v] (r/type (first (:arglists (meta v))))) ;;------------------------------------------------------------------------------ (defn functions [^clojure.lang.Symbol bare-datum-type ^clojure.lang.Symbol field] (let [naked-field (with-meta field {:no-doc true}) ;; turn off codox for now datum-type (r/munge bare-datum-type) datum (gensym "datum") hinted-datum (with-meta datum {:tag datum-type}) naked-args [hinted-datum] field-type (r/type field) args (hint-args naked-args field-type) accessor (symbol (str "." field)) naked-access `(~accessor ~hinted-datum) access (cast-access naked-access field-type) outer `(defn ~naked-field ~args ~access) prefix (str field "-") inner-defn (fn inner-defn [[^clojure.lang.Symbol unqualified-name ^clojure.lang.Var v]] (let [^clojure.lang.Symbol qualified-name (qualified-name v) inner-name (with-meta (symbol (str prefix unqualified-name)) {:no-doc true}) inner-type (return-type v) inner-call (cast-access `(~qualified-name ~access) inner-type) inner-args (hint-args naked-args inner-type)] `(defn ~inner-name ~inner-args ~inner-call))) inner (when (r/datum-class? field-type) (mapv inner-defn (filter (fn [[k v]] (attribute? field-type v)) (ns-publics (r/namespace field-type)))))] (cons outer inner))) ;------------------------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-09-06" :doc "Attribute function generation."} zana.data.attribute (:refer-clojure :exclude [cast emit name]) (:require [clojure.pprint :as pp] [zana.data.reflect :as r])) ;;------------------------------------------------------------------------------ (defn- hint-args [^clojure.lang.IMeta naked-args ^Class c] (let [csymbol (symbol (.getName c)) return-type (case csymbol boolean 'Boolean char 'Character (byte short int long) 'long (float double) 'double csymbol)] (with-meta naked-args {:tag return-type}))) ;;------------------------------------------------------------------------------ (defn- cast-access [^clojure.lang.IMeta naked-access ^Class c] (let [csymbol (symbol (.getName c)) cast (case csymbol boolean 'Boolean/valueOf char 'Character/valueOf (byte short int long) 'long (float double) 'double nil) access (if cast `(~cast ~naked-access) naked-access)] access)) ;;------------------------------------------------------------------------------ ;; Does this public symbol from another namespace look like an attribute ;; function? ;; TODO: should attributes be marked with special meta-data? (defn- attribute? [field-type f] (let [ms (meta f) arglists (:arglists ms) arglist (first arglists) arg (first arglist) ma (meta arg) argtype (eval (:tag ma))] (and (== 1 (count arglists)) (== 1 (count arglist)) (= field-type argtype)))) ;;------------------------------------------------------------------------------ (defn name [defn-expression] (assert (= 'clojure.core/defn (first defn-expression)) (pr-str (first defn-expression) "\n" defn-expression)) (second defn-expression)) ;;------------------------------------------------------------------------------ (defn- qualified-name ^clojure.lang.Symbol [^clojure.lang.Var v] (symbol (str (:ns (meta v))) (str (:name (meta v))))) ;;------------------------------------------------------------------------------ (defn- return-type ^clojure.lang.Symbol [^clojure.lang.Var v] (r/type (first (:arglists (meta v))))) ;;------------------------------------------------------------------------------ (defn functions [^clojure.lang.Symbol bare-datum-type ^clojure.lang.Symbol field] (let [naked-field (with-meta field {:no-doc true}) ;; turn off codox for now datum-type (r/munge bare-datum-type) datum (gensym "datum") hinted-datum (with-meta datum {:tag datum-type}) naked-args [hinted-datum] field-type (r/type field) args (hint-args naked-args field-type) accessor (symbol (str "." field)) naked-access `(~accessor ~hinted-datum) access (cast-access naked-access field-type) outer `(defn ~naked-field ~args ~access) prefix (str field "-") inner-defn (fn inner-defn [[^clojure.lang.Symbol unqualified-name ^clojure.lang.Var v]] (let [^clojure.lang.Symbol qualified-name (qualified-name v) inner-name (with-meta (symbol (str prefix unqualified-name)) {:no-doc true}) inner-type (return-type v) inner-call (cast-access `(~qualified-name ~access) inner-type) inner-args (hint-args naked-args inner-type)] `(defn ~inner-name ~inner-args ~inner-call))) inner (when (r/datum-class? field-type) (mapv inner-defn (filter (fn [[k v]] (attribute? field-type v)) (ns-publics (r/namespace field-type)))))] (cons outer inner))) ;------------------------------------------------------------------------------
[ { "context": "paredStatement]))\n\n(def pool-spec\n {:username \"benchmarkdbuser\"\n :password \"benchmarkdbpass\"\n :jdbc-url ", "end": 551, "score": 0.9994558691978455, "start": 536, "tag": "USERNAME", "value": "benchmarkdbuser" }, { "context": "\n {:username \"benchmarkdbuser\"\n :password \"benchmarkdbpass\"\n :jdbc-url \"jdbc:postgresql://127.0.0.1:5432", "end": 584, "score": 0.9993260502815247, "start": 569, "tag": "PASSWORD", "value": "benchmarkdbpass" }, { "context": "enchmarkdbpass\"\n :jdbc-url \"jdbc:postgresql://127.0.0.1:5432/hello_world?jdbcCompliantTruncation=false&el", "end": 629, "score": 0.9997538328170776, "start": 620, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
frameworks/Clojure/luminus/hello/src/hello/db/core.clj
astaxie/FrameworkBenchmarks
0
(ns hello.db.core (:require [cheshire.core :refer [generate-string parse-string]] [clojure.java.jdbc :as jdbc] [conman.core :as conman] [environ.core :refer [env]] [mount.core :refer [defstate]]) (:import org.postgresql.util.PGobject org.postgresql.jdbc.PgArray clojure.lang.IPersistentMap clojure.lang.IPersistentVector [java.sql BatchUpdateException Date Timestamp PreparedStatement])) (def pool-spec {:username "benchmarkdbuser" :password "benchmarkdbpass" :jdbc-url "jdbc:postgresql://127.0.0.1:5432/hello_world?jdbcCompliantTruncation=false&elideSetAutoCommits=true&useLocalSessionState=true&cachePrepStmts=true&cacheCallableStmts=true&alwaysSendSetIsolation=false&prepStmtCacheSize=4096&cacheServerConfiguration=true&prepStmtCacheSqlLimit=2048&zeroDateTimeBehavior=convertToNull&traceProtocol=false&useUnbufferedInput=false&useReadAheadInput=false&maintainTimeStats=false&useServerPrepStmts&cacheRSMetadata=true" :init-size 1 :min-idle 1 :max-idle 4 :max-active 32}) (defn connect! [] (let [conn (atom nil)] (conman/connect! conn pool-spec) conn)) (defn disconnect! [conn] (conman/disconnect! conn)) (defstate ^:dynamic *db* :start (connect!) :stop (disconnect! *db*)) (conman/bind-connection *db* "sql/queries.sql") (defn to-date [sql-date] (-> sql-date (.getTime) (java.util.Date.))) (extend-protocol jdbc/IResultSetReadColumn Date (result-set-read-column [v _ _] (to-date v)) Timestamp (result-set-read-column [v _ _] (to-date v)) PgArray (result-set-read-column [v _ _] (vec (.getArray v))) PGobject (result-set-read-column [pgobj _metadata _index] (let [type (.getType pgobj) value (.getValue pgobj)] (case type "json" (parse-string value true) "jsonb" (parse-string value true) "citext" (str value) value)))) (extend-type java.util.Date jdbc/ISQLParameter (set-parameter [v ^PreparedStatement stmt idx] (.setTimestamp stmt idx (Timestamp. (.getTime v))))) (defn to-pg-json [value] (doto (PGobject.) (.setType "jsonb") (.setValue (generate-string value)))) (extend-protocol jdbc/ISQLValue IPersistentMap (sql-value [value] (to-pg-json value)) IPersistentVector (sql-value [value] (to-pg-json value))) ;; queries (defn get-world-random "Query a random World record between 1 and 10,000 from the database" [] (get-world {:id (inc (rand-int 9999))})) (defn get-query-count [queries] "Parse provided string value of query count, clamping values to between 1 and 500." (let [n (try (Integer/parseInt queries) (catch Exception e 1))] ; default to 1 on parse failure (cond (< n 1) 1 (> n 500) 500 :else n))) (defn run-queries "Run the specified number of queries, return the results" [queries] (flatten (repeatedly (get-query-count queries) get-world-random))) (defn get-fortunes [] "Fetch the full list of Fortunes from the database, sort them by the fortune message text, and then return the results." (sort-by :message (conj (get-all-fortunes {}) {:id 0 :message "Additional fortune added at request time."}))) (defn update-and-persist "Changes the :randomNumber of a number of world entities. Persists the changes to sql then returns the updated entities" [queries] (for [world (-> queries run-queries)] (let [updated-world (assoc world :randomNumber (inc (rand-int 9999)))] (update-world<! updated-world) updated-world)))
92931
(ns hello.db.core (:require [cheshire.core :refer [generate-string parse-string]] [clojure.java.jdbc :as jdbc] [conman.core :as conman] [environ.core :refer [env]] [mount.core :refer [defstate]]) (:import org.postgresql.util.PGobject org.postgresql.jdbc.PgArray clojure.lang.IPersistentMap clojure.lang.IPersistentVector [java.sql BatchUpdateException Date Timestamp PreparedStatement])) (def pool-spec {:username "benchmarkdbuser" :password "<PASSWORD>" :jdbc-url "jdbc:postgresql://127.0.0.1:5432/hello_world?jdbcCompliantTruncation=false&elideSetAutoCommits=true&useLocalSessionState=true&cachePrepStmts=true&cacheCallableStmts=true&alwaysSendSetIsolation=false&prepStmtCacheSize=4096&cacheServerConfiguration=true&prepStmtCacheSqlLimit=2048&zeroDateTimeBehavior=convertToNull&traceProtocol=false&useUnbufferedInput=false&useReadAheadInput=false&maintainTimeStats=false&useServerPrepStmts&cacheRSMetadata=true" :init-size 1 :min-idle 1 :max-idle 4 :max-active 32}) (defn connect! [] (let [conn (atom nil)] (conman/connect! conn pool-spec) conn)) (defn disconnect! [conn] (conman/disconnect! conn)) (defstate ^:dynamic *db* :start (connect!) :stop (disconnect! *db*)) (conman/bind-connection *db* "sql/queries.sql") (defn to-date [sql-date] (-> sql-date (.getTime) (java.util.Date.))) (extend-protocol jdbc/IResultSetReadColumn Date (result-set-read-column [v _ _] (to-date v)) Timestamp (result-set-read-column [v _ _] (to-date v)) PgArray (result-set-read-column [v _ _] (vec (.getArray v))) PGobject (result-set-read-column [pgobj _metadata _index] (let [type (.getType pgobj) value (.getValue pgobj)] (case type "json" (parse-string value true) "jsonb" (parse-string value true) "citext" (str value) value)))) (extend-type java.util.Date jdbc/ISQLParameter (set-parameter [v ^PreparedStatement stmt idx] (.setTimestamp stmt idx (Timestamp. (.getTime v))))) (defn to-pg-json [value] (doto (PGobject.) (.setType "jsonb") (.setValue (generate-string value)))) (extend-protocol jdbc/ISQLValue IPersistentMap (sql-value [value] (to-pg-json value)) IPersistentVector (sql-value [value] (to-pg-json value))) ;; queries (defn get-world-random "Query a random World record between 1 and 10,000 from the database" [] (get-world {:id (inc (rand-int 9999))})) (defn get-query-count [queries] "Parse provided string value of query count, clamping values to between 1 and 500." (let [n (try (Integer/parseInt queries) (catch Exception e 1))] ; default to 1 on parse failure (cond (< n 1) 1 (> n 500) 500 :else n))) (defn run-queries "Run the specified number of queries, return the results" [queries] (flatten (repeatedly (get-query-count queries) get-world-random))) (defn get-fortunes [] "Fetch the full list of Fortunes from the database, sort them by the fortune message text, and then return the results." (sort-by :message (conj (get-all-fortunes {}) {:id 0 :message "Additional fortune added at request time."}))) (defn update-and-persist "Changes the :randomNumber of a number of world entities. Persists the changes to sql then returns the updated entities" [queries] (for [world (-> queries run-queries)] (let [updated-world (assoc world :randomNumber (inc (rand-int 9999)))] (update-world<! updated-world) updated-world)))
true
(ns hello.db.core (:require [cheshire.core :refer [generate-string parse-string]] [clojure.java.jdbc :as jdbc] [conman.core :as conman] [environ.core :refer [env]] [mount.core :refer [defstate]]) (:import org.postgresql.util.PGobject org.postgresql.jdbc.PgArray clojure.lang.IPersistentMap clojure.lang.IPersistentVector [java.sql BatchUpdateException Date Timestamp PreparedStatement])) (def pool-spec {:username "benchmarkdbuser" :password "PI:PASSWORD:<PASSWORD>END_PI" :jdbc-url "jdbc:postgresql://127.0.0.1:5432/hello_world?jdbcCompliantTruncation=false&elideSetAutoCommits=true&useLocalSessionState=true&cachePrepStmts=true&cacheCallableStmts=true&alwaysSendSetIsolation=false&prepStmtCacheSize=4096&cacheServerConfiguration=true&prepStmtCacheSqlLimit=2048&zeroDateTimeBehavior=convertToNull&traceProtocol=false&useUnbufferedInput=false&useReadAheadInput=false&maintainTimeStats=false&useServerPrepStmts&cacheRSMetadata=true" :init-size 1 :min-idle 1 :max-idle 4 :max-active 32}) (defn connect! [] (let [conn (atom nil)] (conman/connect! conn pool-spec) conn)) (defn disconnect! [conn] (conman/disconnect! conn)) (defstate ^:dynamic *db* :start (connect!) :stop (disconnect! *db*)) (conman/bind-connection *db* "sql/queries.sql") (defn to-date [sql-date] (-> sql-date (.getTime) (java.util.Date.))) (extend-protocol jdbc/IResultSetReadColumn Date (result-set-read-column [v _ _] (to-date v)) Timestamp (result-set-read-column [v _ _] (to-date v)) PgArray (result-set-read-column [v _ _] (vec (.getArray v))) PGobject (result-set-read-column [pgobj _metadata _index] (let [type (.getType pgobj) value (.getValue pgobj)] (case type "json" (parse-string value true) "jsonb" (parse-string value true) "citext" (str value) value)))) (extend-type java.util.Date jdbc/ISQLParameter (set-parameter [v ^PreparedStatement stmt idx] (.setTimestamp stmt idx (Timestamp. (.getTime v))))) (defn to-pg-json [value] (doto (PGobject.) (.setType "jsonb") (.setValue (generate-string value)))) (extend-protocol jdbc/ISQLValue IPersistentMap (sql-value [value] (to-pg-json value)) IPersistentVector (sql-value [value] (to-pg-json value))) ;; queries (defn get-world-random "Query a random World record between 1 and 10,000 from the database" [] (get-world {:id (inc (rand-int 9999))})) (defn get-query-count [queries] "Parse provided string value of query count, clamping values to between 1 and 500." (let [n (try (Integer/parseInt queries) (catch Exception e 1))] ; default to 1 on parse failure (cond (< n 1) 1 (> n 500) 500 :else n))) (defn run-queries "Run the specified number of queries, return the results" [queries] (flatten (repeatedly (get-query-count queries) get-world-random))) (defn get-fortunes [] "Fetch the full list of Fortunes from the database, sort them by the fortune message text, and then return the results." (sort-by :message (conj (get-all-fortunes {}) {:id 0 :message "Additional fortune added at request time."}))) (defn update-and-persist "Changes the :randomNumber of a number of world entities. Persists the changes to sql then returns the updated entities" [queries] (for [world (-> queries run-queries)] (let [updated-world (assoc world :randomNumber (inc (rand-int 9999)))] (update-world<! updated-world) updated-world)))
[ { "context": "pe \"text\"\n :placeholder \"you@sloth.land\"\n :autocomplete \"off\"\n ", "end": 1629, "score": 0.9999160766601562, "start": 1615, "tag": "EMAIL", "value": "you@sloth.land" } ]
src/cljs/sloth/views/login.cljs
niwibe/sloth
0
(ns sloth.views.login (:require-macros [cljs.core.async.macros :refer [go]]) (:require [om.core :as om :include-macros true] [sablono.core :as html :refer-macros [html]] [cuerdas.core :as str] [cljs.core.async :refer [<!]] [sloth.auth :as auth] [sloth.state :as st] [sloth.xmpp :as xmpp] [sloth.routing :as routing] [sloth.events :as events] [cats.monad.either :as either])) (defn try-login [owner {:keys [username password]}] (go (let [msession (<! (auth/authenticate username password))] (cond (either/right? msession) (routing/navigate "") (either/left? msession) (let [state (om/get-state owner)] (om/set-state! owner (assoc state :error "Wrong credentials!"))))))) (defn- on-enter [{:keys [username password] :as state} owner] ;; TODO: valid username? (when (every? (complement str/empty?) [username password]) (try-login owner state))) (defn- onkeyup [state owner event] (when (events/pressed-enter? event) (on-enter state owner))) (defn login-component [_ owner] (reify om/IDisplayName (display-name [_] "Login") om/IInitState (init-state [_] {:username "" :password "" :error ""}) om/IRenderState (render-state [_ state] (html [:div.lightbox-shadow [:div.lightbox [:div.login [:div.login-form [:div.logo] [:form [:input {:type "text" :placeholder "you@sloth.land" :autocomplete "off" :autofocus true :on-change (fn [ev] (om/set-state! owner (assoc state :username (.-value (.-target ev))))) :default-value (:username state)}] [:input {:type "password" :placeholder "I ♥ sloths" :on-change (fn [ev] (om/set-state! owner (assoc state :password (.-value (.-target ev))))) :default-value (:password state) :on-key-up (partial onkeyup state owner)}] [:button {:on-click (fn [ev] (.preventDefault ev) (try-login owner state))} "Login"]]] [:div.dat-sloth] [:div.dat-text "Open source team communication plataform"] [:div.dat-bubble-arrow]]] (when (:error state) [:p (:error state)])]))))
44842
(ns sloth.views.login (:require-macros [cljs.core.async.macros :refer [go]]) (:require [om.core :as om :include-macros true] [sablono.core :as html :refer-macros [html]] [cuerdas.core :as str] [cljs.core.async :refer [<!]] [sloth.auth :as auth] [sloth.state :as st] [sloth.xmpp :as xmpp] [sloth.routing :as routing] [sloth.events :as events] [cats.monad.either :as either])) (defn try-login [owner {:keys [username password]}] (go (let [msession (<! (auth/authenticate username password))] (cond (either/right? msession) (routing/navigate "") (either/left? msession) (let [state (om/get-state owner)] (om/set-state! owner (assoc state :error "Wrong credentials!"))))))) (defn- on-enter [{:keys [username password] :as state} owner] ;; TODO: valid username? (when (every? (complement str/empty?) [username password]) (try-login owner state))) (defn- onkeyup [state owner event] (when (events/pressed-enter? event) (on-enter state owner))) (defn login-component [_ owner] (reify om/IDisplayName (display-name [_] "Login") om/IInitState (init-state [_] {:username "" :password "" :error ""}) om/IRenderState (render-state [_ state] (html [:div.lightbox-shadow [:div.lightbox [:div.login [:div.login-form [:div.logo] [:form [:input {:type "text" :placeholder "<EMAIL>" :autocomplete "off" :autofocus true :on-change (fn [ev] (om/set-state! owner (assoc state :username (.-value (.-target ev))))) :default-value (:username state)}] [:input {:type "password" :placeholder "I ♥ sloths" :on-change (fn [ev] (om/set-state! owner (assoc state :password (.-value (.-target ev))))) :default-value (:password state) :on-key-up (partial onkeyup state owner)}] [:button {:on-click (fn [ev] (.preventDefault ev) (try-login owner state))} "Login"]]] [:div.dat-sloth] [:div.dat-text "Open source team communication plataform"] [:div.dat-bubble-arrow]]] (when (:error state) [:p (:error state)])]))))
true
(ns sloth.views.login (:require-macros [cljs.core.async.macros :refer [go]]) (:require [om.core :as om :include-macros true] [sablono.core :as html :refer-macros [html]] [cuerdas.core :as str] [cljs.core.async :refer [<!]] [sloth.auth :as auth] [sloth.state :as st] [sloth.xmpp :as xmpp] [sloth.routing :as routing] [sloth.events :as events] [cats.monad.either :as either])) (defn try-login [owner {:keys [username password]}] (go (let [msession (<! (auth/authenticate username password))] (cond (either/right? msession) (routing/navigate "") (either/left? msession) (let [state (om/get-state owner)] (om/set-state! owner (assoc state :error "Wrong credentials!"))))))) (defn- on-enter [{:keys [username password] :as state} owner] ;; TODO: valid username? (when (every? (complement str/empty?) [username password]) (try-login owner state))) (defn- onkeyup [state owner event] (when (events/pressed-enter? event) (on-enter state owner))) (defn login-component [_ owner] (reify om/IDisplayName (display-name [_] "Login") om/IInitState (init-state [_] {:username "" :password "" :error ""}) om/IRenderState (render-state [_ state] (html [:div.lightbox-shadow [:div.lightbox [:div.login [:div.login-form [:div.logo] [:form [:input {:type "text" :placeholder "PI:EMAIL:<EMAIL>END_PI" :autocomplete "off" :autofocus true :on-change (fn [ev] (om/set-state! owner (assoc state :username (.-value (.-target ev))))) :default-value (:username state)}] [:input {:type "password" :placeholder "I ♥ sloths" :on-change (fn [ev] (om/set-state! owner (assoc state :password (.-value (.-target ev))))) :default-value (:password state) :on-key-up (partial onkeyup state owner)}] [:button {:on-click (fn [ev] (.preventDefault ev) (try-login owner state))} "Login"]]] [:div.dat-sloth] [:div.dat-text "Open source team communication plataform"] [:div.dat-bubble-arrow]]] (when (:error state) [:p (:error state)])]))))
[ { "context": " README EXAMPLES\n\n (let [value-1 \"abcdfeghijkl\\rmnopqrstuvwxyz\"\n value-2 \"abcdfeghijkl\\nmnopqrst", "end": 257, "score": 0.5108785629272461, "start": 253, "tag": "KEY", "value": "nopq" } ]
src/text_diff_examples.clj
steenhansen/clojure-html-diff
0
; How to use ; text-diff-examples> (diff-examples) (ns text-diff-examples (:require [clojure.test :refer [is]]) (:require [text-diff :refer [are-vars-eq]])) (defn diff-examples [] ; START OF README EXAMPLES (let [value-1 "abcdfeghijkl\rmnopqrstuvwxyz" value-2 "abcdfeghijkl\nmnopqrstuvwxyz" [diff-1 diff-2] (are-vars-eq value-1 value-2)] ; /r vs /n (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|"abcdfeghijkl" ;|DIFF1|"kl\rmn" ;|DIFF2|"kl\nmn" ;| END|"mnopqrstuvwxyz" ;expected: (= diff-1 diff-2) ; actual: (not (= "\r" "\n")) ;expected: (= value-1 value-2) ; actual: (not (= "abcdfeghijkl\rmnopqrstuvwxyz" "abcdfeghijkl\nmnopqrstuvwxyz")) (let [value-1 "11111111111" value-2 "1111111111l" [diff-1 diff-2] (are-vars-eq value-1 value-2)] ; 1 vs l (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|"1111111111 ;|DIFF1|"111" ;|DIFF2|"11l" ;| END|" ;expected: (= diff-1 diff-2) ; actual: (not (= "1" "l")) ;expected: (= value-1 value-2) ; actual: (not (= "11111111111" "1111111111l")) (let [value-1 {:a "a" :b "b" :c "c"} value-2 {:b "b" :c "c" :a "X"} [diff-1 diff-2] (are-vars-eq value-1 value-2)] ; out of order maps (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|{ :a ;|DIFF1| " a " ;|DIFF2| " X " ;| END| :b "b" :c "c" } ;expected: (= diff-1 diff-2) ; actual: (not (= "a" "X")) ;expected: (= value-1 value-2) ; actual: (not (= {:a "a", :b "b", :c "c"} {:b "b", :c "c", :a "X"})) (let [value-1 "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnXooopppqqqrrrssstttuuuvvvxxxyyyzzz" value-2 "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnYooopppqqqrrrssstttuuuvvvxxxyyyzzz" [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|"aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnn" ;|DIFF1|"nnXoo" ;|DIFF2|"nnYoo" ;| END|"ooopppqqqrrrssstttuuuvvvxxxyyyzzz" ;expected: (= diff-1 diff-2) ; actual: (not (= "X" "Y")) ;expected: (= value-1 value-2) ; actual: (not (= "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnXooopppqqqrrrssstttuuuvvvxxxyyyzzz" "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnYooopppqqqrrrssstttuuuvvvxxxyyyzzz")) (let [value-1 [{:a "a"} 1 '("2" [1 2 3 {:z 123 :arr [1 "2" 3 {:er 1/3}]}])] value-2 [{:a "a"} 1 '("2" [1 2 3 {:z 123 :arr [1 "2" 3 {:er 1/4}]}])] [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|[ { :a "a" } 1 '("2" [1 2 3 {:z 123, :arr [1 "2" 3 {:er 1/ ;|DIFF1|1/ 3 }] ;|DIFF2|1/ 4 }] ;| END|}]}]) ] ;expected: (= diff-1 diff-2) ; actual: (not (= "3" "4")) ;expected: (= value-1 value-2) ; actual: (not (= [{:a "a"} 1 ("2" [1 2 3 {:z 123, :arr [1 "2" 3 {:er 1/3}]}])] [{:a "a"} 1 ("2" [1 2 3 {:z 123, :arr [1 "2" 3 {:er 1/4}]}])])) (let [value-1 "abcdfeghijklmnopqrstuvwxyz" value-2 "abcdfeghijklmnopqrstuvwxyz\n" [diff-1 diff-2] (are-vars-eq value-1 value-2)] ;/n at end (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|"abcdfeghijklmnopqrstuvwxyz ;|DIFF1|"yz" ;|DIFF2|"yz\n" ;| END|" ;expected: (= diff-1 diff-2) ; actual: (not (= "" "\n")) ;expected: (= value-1 value-2) ; actual: (not (= "abcdfeghijklmnopqrstuvwxyz" "abcdfeghijklmnopqrstuvwxyz\n")) (let [value-1 1234567890 value-2 1234567790 [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|1234567 ;|DIFF1|67890 ;|DIFF2|67790 ;| END|90 ;expected: (= diff-1 diff-2) ; actual: (not (= 1234567890 1234567790)) ;expected: (= value-1 value-2) ; actual: (not (= 1234567890 1234567790)) ; END OF README EXAMPLES (let [value-1 "<div>123<div>" value-2 "<div>123<div>" [text-diff-1 text-diff-2] (are-vars-eq value-1 value-2)] (is (= text-diff-1 text-diff-2))) ; true (let [value-1 "<same>DIFFERENT</same>" value-2 "<same>different</same>" [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ; |START|"<same>" ; |DIFF1|"e>DIFFERENT</" ; |DIFF2|"e>different</" ; | END|"</same>" ; expected (= diff-1 diff-2) ; actual (not (= "DIFFERENT" "different")) ; false (let [value-1 "abcdefghijklmnopqrstuvwxyzDIFFERENTabcdefghijklmnopqrstuvwxyz" value-2 "abcdefghijklmnopqrstuvwxyzdifferentabcdefghijklmnopqrstuvwxyz" [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ;|START|"abcdefghijklmnopqrstuvwxyz" ;|DIFF1|"yzDIFFERENTab" ;|DIFF2|"yzdifferentab" ;| END|"abcdefghijklmnopqrstuvwxyz" ;actual: (not (= "DIFFERENT" "different")) (let [value-1 "abcdefghijklmnopqrstuvwxyz_1_abcdefghijklmnopqrstuvwxyz" ; letter L versus number 1 value-2 "abcdefghijklmnopqrstuvwxyz_l_abcdefghijklmnopqrstuvwxyz" [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ;|START|"abcdefghijklmnopqrstuvwxyz_" ;|DIFF1|"z_1_a" ;|DIFF2|"z_l_a" ;| END|"_abcdefghijklmnopqrstuvwxyz" ;actual (not (= "1" "l")) (let [value-1 "abc xyz" ; tab versus value-2 "abc xyz" ; spaces [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ; |START|"abc" ; |DIFF1|"bc\txy" ; |DIFF2|"bc xy" ; | END|"xyz" ; actual (not (= "\t" " ")) (let [value-1 "qwe\r\n_asd" ; Windows eol versus value-2 "qwe\n-asd" ; Unix eol [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ; |START|"qwe" ; |DIFF1|"we\r\n_as" ; |DIFF2|"we\n-as" ; | END|"asd" ; actual (not (= "\r\n_" "\n-")) (let [value-1 "123456789" value-2 123456789 [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ;|diff1|"123456789" String ;|diff2| 123406789 Long ; actual: (not (= "123456789" 123406789)) (let [value-1 {:a "a" :b "b" :c "c"} ; out of order maps value-2 {:b "b" :c "c" :a "a"} [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ; true, nothing printed to repl (let [value-1 [123 "456"] value-2 ["123" 456] [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ;|START|[ ;|DIFF1|[ 123 "456" ] ;|DIFF2|[ "123" 456 ] ;| END|] ; actual: (not (= "123 \"456\"" "\"123\" 456")) )
112844
; How to use ; text-diff-examples> (diff-examples) (ns text-diff-examples (:require [clojure.test :refer [is]]) (:require [text-diff :refer [are-vars-eq]])) (defn diff-examples [] ; START OF README EXAMPLES (let [value-1 "abcdfeghijkl\rm<KEY>rstuvwxyz" value-2 "abcdfeghijkl\nmnopqrstuvwxyz" [diff-1 diff-2] (are-vars-eq value-1 value-2)] ; /r vs /n (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|"abcdfeghijkl" ;|DIFF1|"kl\rmn" ;|DIFF2|"kl\nmn" ;| END|"mnopqrstuvwxyz" ;expected: (= diff-1 diff-2) ; actual: (not (= "\r" "\n")) ;expected: (= value-1 value-2) ; actual: (not (= "abcdfeghijkl\rmnopqrstuvwxyz" "abcdfeghijkl\nmnopqrstuvwxyz")) (let [value-1 "11111111111" value-2 "1111111111l" [diff-1 diff-2] (are-vars-eq value-1 value-2)] ; 1 vs l (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|"1111111111 ;|DIFF1|"111" ;|DIFF2|"11l" ;| END|" ;expected: (= diff-1 diff-2) ; actual: (not (= "1" "l")) ;expected: (= value-1 value-2) ; actual: (not (= "11111111111" "1111111111l")) (let [value-1 {:a "a" :b "b" :c "c"} value-2 {:b "b" :c "c" :a "X"} [diff-1 diff-2] (are-vars-eq value-1 value-2)] ; out of order maps (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|{ :a ;|DIFF1| " a " ;|DIFF2| " X " ;| END| :b "b" :c "c" } ;expected: (= diff-1 diff-2) ; actual: (not (= "a" "X")) ;expected: (= value-1 value-2) ; actual: (not (= {:a "a", :b "b", :c "c"} {:b "b", :c "c", :a "X"})) (let [value-1 "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnXooopppqqqrrrssstttuuuvvvxxxyyyzzz" value-2 "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnYooopppqqqrrrssstttuuuvvvxxxyyyzzz" [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|"aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnn" ;|DIFF1|"nnXoo" ;|DIFF2|"nnYoo" ;| END|"ooopppqqqrrrssstttuuuvvvxxxyyyzzz" ;expected: (= diff-1 diff-2) ; actual: (not (= "X" "Y")) ;expected: (= value-1 value-2) ; actual: (not (= "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnXooopppqqqrrrssstttuuuvvvxxxyyyzzz" "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnYooopppqqqrrrssstttuuuvvvxxxyyyzzz")) (let [value-1 [{:a "a"} 1 '("2" [1 2 3 {:z 123 :arr [1 "2" 3 {:er 1/3}]}])] value-2 [{:a "a"} 1 '("2" [1 2 3 {:z 123 :arr [1 "2" 3 {:er 1/4}]}])] [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|[ { :a "a" } 1 '("2" [1 2 3 {:z 123, :arr [1 "2" 3 {:er 1/ ;|DIFF1|1/ 3 }] ;|DIFF2|1/ 4 }] ;| END|}]}]) ] ;expected: (= diff-1 diff-2) ; actual: (not (= "3" "4")) ;expected: (= value-1 value-2) ; actual: (not (= [{:a "a"} 1 ("2" [1 2 3 {:z 123, :arr [1 "2" 3 {:er 1/3}]}])] [{:a "a"} 1 ("2" [1 2 3 {:z 123, :arr [1 "2" 3 {:er 1/4}]}])])) (let [value-1 "abcdfeghijklmnopqrstuvwxyz" value-2 "abcdfeghijklmnopqrstuvwxyz\n" [diff-1 diff-2] (are-vars-eq value-1 value-2)] ;/n at end (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|"abcdfeghijklmnopqrstuvwxyz ;|DIFF1|"yz" ;|DIFF2|"yz\n" ;| END|" ;expected: (= diff-1 diff-2) ; actual: (not (= "" "\n")) ;expected: (= value-1 value-2) ; actual: (not (= "abcdfeghijklmnopqrstuvwxyz" "abcdfeghijklmnopqrstuvwxyz\n")) (let [value-1 1234567890 value-2 1234567790 [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|1234567 ;|DIFF1|67890 ;|DIFF2|67790 ;| END|90 ;expected: (= diff-1 diff-2) ; actual: (not (= 1234567890 1234567790)) ;expected: (= value-1 value-2) ; actual: (not (= 1234567890 1234567790)) ; END OF README EXAMPLES (let [value-1 "<div>123<div>" value-2 "<div>123<div>" [text-diff-1 text-diff-2] (are-vars-eq value-1 value-2)] (is (= text-diff-1 text-diff-2))) ; true (let [value-1 "<same>DIFFERENT</same>" value-2 "<same>different</same>" [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ; |START|"<same>" ; |DIFF1|"e>DIFFERENT</" ; |DIFF2|"e>different</" ; | END|"</same>" ; expected (= diff-1 diff-2) ; actual (not (= "DIFFERENT" "different")) ; false (let [value-1 "abcdefghijklmnopqrstuvwxyzDIFFERENTabcdefghijklmnopqrstuvwxyz" value-2 "abcdefghijklmnopqrstuvwxyzdifferentabcdefghijklmnopqrstuvwxyz" [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ;|START|"abcdefghijklmnopqrstuvwxyz" ;|DIFF1|"yzDIFFERENTab" ;|DIFF2|"yzdifferentab" ;| END|"abcdefghijklmnopqrstuvwxyz" ;actual: (not (= "DIFFERENT" "different")) (let [value-1 "abcdefghijklmnopqrstuvwxyz_1_abcdefghijklmnopqrstuvwxyz" ; letter L versus number 1 value-2 "abcdefghijklmnopqrstuvwxyz_l_abcdefghijklmnopqrstuvwxyz" [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ;|START|"abcdefghijklmnopqrstuvwxyz_" ;|DIFF1|"z_1_a" ;|DIFF2|"z_l_a" ;| END|"_abcdefghijklmnopqrstuvwxyz" ;actual (not (= "1" "l")) (let [value-1 "abc xyz" ; tab versus value-2 "abc xyz" ; spaces [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ; |START|"abc" ; |DIFF1|"bc\txy" ; |DIFF2|"bc xy" ; | END|"xyz" ; actual (not (= "\t" " ")) (let [value-1 "qwe\r\n_asd" ; Windows eol versus value-2 "qwe\n-asd" ; Unix eol [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ; |START|"qwe" ; |DIFF1|"we\r\n_as" ; |DIFF2|"we\n-as" ; | END|"asd" ; actual (not (= "\r\n_" "\n-")) (let [value-1 "123456789" value-2 123456789 [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ;|diff1|"123456789" String ;|diff2| 123406789 Long ; actual: (not (= "123456789" 123406789)) (let [value-1 {:a "a" :b "b" :c "c"} ; out of order maps value-2 {:b "b" :c "c" :a "a"} [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ; true, nothing printed to repl (let [value-1 [123 "456"] value-2 ["123" 456] [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ;|START|[ ;|DIFF1|[ 123 "456" ] ;|DIFF2|[ "123" 456 ] ;| END|] ; actual: (not (= "123 \"456\"" "\"123\" 456")) )
true
; How to use ; text-diff-examples> (diff-examples) (ns text-diff-examples (:require [clojure.test :refer [is]]) (:require [text-diff :refer [are-vars-eq]])) (defn diff-examples [] ; START OF README EXAMPLES (let [value-1 "abcdfeghijkl\rmPI:KEY:<KEY>END_PIrstuvwxyz" value-2 "abcdfeghijkl\nmnopqrstuvwxyz" [diff-1 diff-2] (are-vars-eq value-1 value-2)] ; /r vs /n (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|"abcdfeghijkl" ;|DIFF1|"kl\rmn" ;|DIFF2|"kl\nmn" ;| END|"mnopqrstuvwxyz" ;expected: (= diff-1 diff-2) ; actual: (not (= "\r" "\n")) ;expected: (= value-1 value-2) ; actual: (not (= "abcdfeghijkl\rmnopqrstuvwxyz" "abcdfeghijkl\nmnopqrstuvwxyz")) (let [value-1 "11111111111" value-2 "1111111111l" [diff-1 diff-2] (are-vars-eq value-1 value-2)] ; 1 vs l (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|"1111111111 ;|DIFF1|"111" ;|DIFF2|"11l" ;| END|" ;expected: (= diff-1 diff-2) ; actual: (not (= "1" "l")) ;expected: (= value-1 value-2) ; actual: (not (= "11111111111" "1111111111l")) (let [value-1 {:a "a" :b "b" :c "c"} value-2 {:b "b" :c "c" :a "X"} [diff-1 diff-2] (are-vars-eq value-1 value-2)] ; out of order maps (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|{ :a ;|DIFF1| " a " ;|DIFF2| " X " ;| END| :b "b" :c "c" } ;expected: (= diff-1 diff-2) ; actual: (not (= "a" "X")) ;expected: (= value-1 value-2) ; actual: (not (= {:a "a", :b "b", :c "c"} {:b "b", :c "c", :a "X"})) (let [value-1 "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnXooopppqqqrrrssstttuuuvvvxxxyyyzzz" value-2 "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnYooopppqqqrrrssstttuuuvvvxxxyyyzzz" [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|"aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnn" ;|DIFF1|"nnXoo" ;|DIFF2|"nnYoo" ;| END|"ooopppqqqrrrssstttuuuvvvxxxyyyzzz" ;expected: (= diff-1 diff-2) ; actual: (not (= "X" "Y")) ;expected: (= value-1 value-2) ; actual: (not (= "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnXooopppqqqrrrssstttuuuvvvxxxyyyzzz" "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnYooopppqqqrrrssstttuuuvvvxxxyyyzzz")) (let [value-1 [{:a "a"} 1 '("2" [1 2 3 {:z 123 :arr [1 "2" 3 {:er 1/3}]}])] value-2 [{:a "a"} 1 '("2" [1 2 3 {:z 123 :arr [1 "2" 3 {:er 1/4}]}])] [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|[ { :a "a" } 1 '("2" [1 2 3 {:z 123, :arr [1 "2" 3 {:er 1/ ;|DIFF1|1/ 3 }] ;|DIFF2|1/ 4 }] ;| END|}]}]) ] ;expected: (= diff-1 diff-2) ; actual: (not (= "3" "4")) ;expected: (= value-1 value-2) ; actual: (not (= [{:a "a"} 1 ("2" [1 2 3 {:z 123, :arr [1 "2" 3 {:er 1/3}]}])] [{:a "a"} 1 ("2" [1 2 3 {:z 123, :arr [1 "2" 3 {:er 1/4}]}])])) (let [value-1 "abcdfeghijklmnopqrstuvwxyz" value-2 "abcdfeghijklmnopqrstuvwxyz\n" [diff-1 diff-2] (are-vars-eq value-1 value-2)] ;/n at end (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|"abcdfeghijklmnopqrstuvwxyz ;|DIFF1|"yz" ;|DIFF2|"yz\n" ;| END|" ;expected: (= diff-1 diff-2) ; actual: (not (= "" "\n")) ;expected: (= value-1 value-2) ; actual: (not (= "abcdfeghijklmnopqrstuvwxyz" "abcdfeghijklmnopqrstuvwxyz\n")) (let [value-1 1234567890 value-2 1234567790 [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2)) (is (= value-1 value-2))) ;|START|1234567 ;|DIFF1|67890 ;|DIFF2|67790 ;| END|90 ;expected: (= diff-1 diff-2) ; actual: (not (= 1234567890 1234567790)) ;expected: (= value-1 value-2) ; actual: (not (= 1234567890 1234567790)) ; END OF README EXAMPLES (let [value-1 "<div>123<div>" value-2 "<div>123<div>" [text-diff-1 text-diff-2] (are-vars-eq value-1 value-2)] (is (= text-diff-1 text-diff-2))) ; true (let [value-1 "<same>DIFFERENT</same>" value-2 "<same>different</same>" [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ; |START|"<same>" ; |DIFF1|"e>DIFFERENT</" ; |DIFF2|"e>different</" ; | END|"</same>" ; expected (= diff-1 diff-2) ; actual (not (= "DIFFERENT" "different")) ; false (let [value-1 "abcdefghijklmnopqrstuvwxyzDIFFERENTabcdefghijklmnopqrstuvwxyz" value-2 "abcdefghijklmnopqrstuvwxyzdifferentabcdefghijklmnopqrstuvwxyz" [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ;|START|"abcdefghijklmnopqrstuvwxyz" ;|DIFF1|"yzDIFFERENTab" ;|DIFF2|"yzdifferentab" ;| END|"abcdefghijklmnopqrstuvwxyz" ;actual: (not (= "DIFFERENT" "different")) (let [value-1 "abcdefghijklmnopqrstuvwxyz_1_abcdefghijklmnopqrstuvwxyz" ; letter L versus number 1 value-2 "abcdefghijklmnopqrstuvwxyz_l_abcdefghijklmnopqrstuvwxyz" [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ;|START|"abcdefghijklmnopqrstuvwxyz_" ;|DIFF1|"z_1_a" ;|DIFF2|"z_l_a" ;| END|"_abcdefghijklmnopqrstuvwxyz" ;actual (not (= "1" "l")) (let [value-1 "abc xyz" ; tab versus value-2 "abc xyz" ; spaces [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ; |START|"abc" ; |DIFF1|"bc\txy" ; |DIFF2|"bc xy" ; | END|"xyz" ; actual (not (= "\t" " ")) (let [value-1 "qwe\r\n_asd" ; Windows eol versus value-2 "qwe\n-asd" ; Unix eol [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ; |START|"qwe" ; |DIFF1|"we\r\n_as" ; |DIFF2|"we\n-as" ; | END|"asd" ; actual (not (= "\r\n_" "\n-")) (let [value-1 "123456789" value-2 123456789 [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ;|diff1|"123456789" String ;|diff2| 123406789 Long ; actual: (not (= "123456789" 123406789)) (let [value-1 {:a "a" :b "b" :c "c"} ; out of order maps value-2 {:b "b" :c "c" :a "a"} [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ; true, nothing printed to repl (let [value-1 [123 "456"] value-2 ["123" 456] [diff-1 diff-2] (are-vars-eq value-1 value-2)] (is (= diff-1 diff-2))) ;|START|[ ;|DIFF1|[ 123 "456" ] ;|DIFF2|[ "123" 456 ] ;| END|] ; actual: (not (= "123 \"456\"" "\"123\" 456")) )
[ { "context": "the form 'Hello, username'\n Default username is 'world'.\"\n ([] (greeting \"world\"))\n ([username] (str \"", "end": 176, "score": 0.9115036725997925, "start": 171, "tag": "USERNAME", "value": "world" }, { "context": " with\" (count chaperones) \"chaperones.\"))\n\n(date \"Romeo\" \"Juliet\" \"Friar Lawrence\" \"Nurse\")\n\n(defn indexa", "end": 450, "score": 0.9997929930686951, "start": 445, "tag": "NAME", "value": "Romeo" }, { "context": "count chaperones) \"chaperones.\"))\n\n(date \"Romeo\" \"Juliet\" \"Friar Lawrence\" \"Nurse\")\n\n(defn indexable-word?", "end": 459, "score": 0.9996191263198853, "start": 453, "tag": "NAME", "value": "Juliet" }, { "context": "perones) \"chaperones.\"))\n\n(date \"Romeo\" \"Juliet\" \"Friar Lawrence\" \"Nurse\")\n\n(defn indexable-word? [word]\n (> (cou", "end": 476, "score": 0.9998043775558472, "start": 462, "tag": "NAME", "value": "Friar Lawrence" }, { "context": "nes.\"))\n\n(date \"Romeo\" \"Juliet\" \"Friar Lawrence\" \"Nurse\")\n\n(defn indexable-word? [word]\n (> (count word)", "end": 484, "score": 0.999528169631958, "start": 479, "tag": "NAME", "value": "Nurse" }, { "context": "ln \"Hello,\" fname))\n\n(greet-author-1 {:last-name \"Vinge\" :first-name \"Vernor\"})\n(greet-author-2 {:last-na", "end": 1544, "score": 0.9997991323471069, "start": 1539, "tag": "NAME", "value": "Vinge" }, { "context": "\n(greet-author-1 {:last-name \"Vinge\" :first-name \"Vernor\"})\n(greet-author-2 {:last-name \"Vinge\" :first-nam", "end": 1565, "score": 0.9997503757476807, "start": 1559, "tag": "NAME", "value": "Vernor" }, { "context": "irst-name \"Vernor\"})\n(greet-author-2 {:last-name \"Vinge\" :first-name \"Vernor\"})\n\n(defn ellipsize [words]\n", "end": 1603, "score": 0.9997934103012085, "start": 1598, "tag": "NAME", "value": "Vinge" }, { "context": "\n(greet-author-2 {:last-name \"Vinge\" :first-name \"Vernor\"})\n\n(defn ellipsize [words]\n (let [[w1 w2 w3] (s", "end": 1624, "score": 0.9997711181640625, "start": 1618, "tag": "NAME", "value": "Vernor" } ]
clojure/programming-clojure-3rd/ch02/exploring.clj
mdssjc/mds-lisp
0
(ns exploring (:require [clojure.string :as str]) (:import (java.io File))) (defn greeting "Returns a greeting of the form 'Hello, username' Default username is 'world'." ([] (greeting "world")) ([username] (str "Hello, " username))) (greeting "world") (greeting) ;;(doc greeting) (defn date [person-1 person-2 & chaperones] (println person-1 "and" person-2 "went out with" (count chaperones) "chaperones.")) (date "Romeo" "Juliet" "Friar Lawrence" "Nurse") (defn indexable-word? [word] (> (count word) 2)) (filter indexable-word? (str/split "A fine day it is" #"\W+")) (filter (fn [w] (> (count w) 2)) (str/split "A fine day it is" #"\W+")) (filter #(> (count %) 2) (str/split "A fine day it is" #"\W+")) (defn indexable-words [text] (let [indexable-word? (fn [w] (> (count w) 2))] (filter indexable-word? (str/split text #"\W+")))) (indexable-words "A fine day it is") (defn make-greeter [greeting-prefix] (fn [username] [str greeting-prefix "," username])) (def hello-greeting (make-greeter "Hello")) (def aloha-greeting (make-greeter "Aloha")) (hello-greeting "world") (aloha-greeting "world") ((make-greeter "Howdy") "pardner") (defn square-corners [bottom left size] (let [top (+ bottom size) right (+ left size)] [[bottom left] [top left] [top right] [bottom right]])) (square-corners 10 5 12) (defn greet-author-1 [author] (println "Hello," (:first-name author))) (defn greet-author-2 [{fname :first-name}] (println "Hello," fname)) (greet-author-1 {:last-name "Vinge" :first-name "Vernor"}) (greet-author-2 {:last-name "Vinge" :first-name "Vernor"}) (defn ellipsize [words] (let [[w1 w2 w3] (str/split words #"\s+")] (str/join " " [w1 w2 w3 "..."]))) (ellipsize "The quick brown fox jumps over the lazy dog.") (defn shout ([s] (clojure.string/upper-case s)) {:tag String}) (meta #'shout) (defn is-small? [number] (if (< number 100) "yes" (do (println "Saw a big number" number) "no"))) (is-small? 50) (is-small? 50000) (loop [result [] x 5] (if (zero? x) result (recur (conj result x) (dec x)))) (defn countdown [result x] (if (zero? x) result (recur (conj result x) (dec x)))) (countdown [] 5) (into [] (take 5 (iterate dec 5))) (into [] (drop-last (reverse (range 6)))) (vec (reverse (rest (range 6)))) (defn indexed [coll] (map-indexed vector coll)) (defn index-filter [pred coll] (when pred (for [[idx elt] (indexed coll) :when (pred elt)] idx))) (defn index-of-any [pred coll] (first (index-filter pred coll))) (indexed "abcde") (index-filter #{\a \b} "abcdbbb") (index-filter #{\a \b} "xyz") (index-of-any #{\z \a} "zzabyycdxx") (index-of-any #{\b \y} "zzabyycdxx") (nth (index-filter #{:h} [:t :t :h :t :h :t :t :t :h :h]) 2)
10082
(ns exploring (:require [clojure.string :as str]) (:import (java.io File))) (defn greeting "Returns a greeting of the form 'Hello, username' Default username is 'world'." ([] (greeting "world")) ([username] (str "Hello, " username))) (greeting "world") (greeting) ;;(doc greeting) (defn date [person-1 person-2 & chaperones] (println person-1 "and" person-2 "went out with" (count chaperones) "chaperones.")) (date "<NAME>" "<NAME>" "<NAME>" "<NAME>") (defn indexable-word? [word] (> (count word) 2)) (filter indexable-word? (str/split "A fine day it is" #"\W+")) (filter (fn [w] (> (count w) 2)) (str/split "A fine day it is" #"\W+")) (filter #(> (count %) 2) (str/split "A fine day it is" #"\W+")) (defn indexable-words [text] (let [indexable-word? (fn [w] (> (count w) 2))] (filter indexable-word? (str/split text #"\W+")))) (indexable-words "A fine day it is") (defn make-greeter [greeting-prefix] (fn [username] [str greeting-prefix "," username])) (def hello-greeting (make-greeter "Hello")) (def aloha-greeting (make-greeter "Aloha")) (hello-greeting "world") (aloha-greeting "world") ((make-greeter "Howdy") "pardner") (defn square-corners [bottom left size] (let [top (+ bottom size) right (+ left size)] [[bottom left] [top left] [top right] [bottom right]])) (square-corners 10 5 12) (defn greet-author-1 [author] (println "Hello," (:first-name author))) (defn greet-author-2 [{fname :first-name}] (println "Hello," fname)) (greet-author-1 {:last-name "<NAME>" :first-name "<NAME>"}) (greet-author-2 {:last-name "<NAME>" :first-name "<NAME>"}) (defn ellipsize [words] (let [[w1 w2 w3] (str/split words #"\s+")] (str/join " " [w1 w2 w3 "..."]))) (ellipsize "The quick brown fox jumps over the lazy dog.") (defn shout ([s] (clojure.string/upper-case s)) {:tag String}) (meta #'shout) (defn is-small? [number] (if (< number 100) "yes" (do (println "Saw a big number" number) "no"))) (is-small? 50) (is-small? 50000) (loop [result [] x 5] (if (zero? x) result (recur (conj result x) (dec x)))) (defn countdown [result x] (if (zero? x) result (recur (conj result x) (dec x)))) (countdown [] 5) (into [] (take 5 (iterate dec 5))) (into [] (drop-last (reverse (range 6)))) (vec (reverse (rest (range 6)))) (defn indexed [coll] (map-indexed vector coll)) (defn index-filter [pred coll] (when pred (for [[idx elt] (indexed coll) :when (pred elt)] idx))) (defn index-of-any [pred coll] (first (index-filter pred coll))) (indexed "abcde") (index-filter #{\a \b} "abcdbbb") (index-filter #{\a \b} "xyz") (index-of-any #{\z \a} "zzabyycdxx") (index-of-any #{\b \y} "zzabyycdxx") (nth (index-filter #{:h} [:t :t :h :t :h :t :t :t :h :h]) 2)
true
(ns exploring (:require [clojure.string :as str]) (:import (java.io File))) (defn greeting "Returns a greeting of the form 'Hello, username' Default username is 'world'." ([] (greeting "world")) ([username] (str "Hello, " username))) (greeting "world") (greeting) ;;(doc greeting) (defn date [person-1 person-2 & chaperones] (println person-1 "and" person-2 "went out with" (count chaperones) "chaperones.")) (date "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") (defn indexable-word? [word] (> (count word) 2)) (filter indexable-word? (str/split "A fine day it is" #"\W+")) (filter (fn [w] (> (count w) 2)) (str/split "A fine day it is" #"\W+")) (filter #(> (count %) 2) (str/split "A fine day it is" #"\W+")) (defn indexable-words [text] (let [indexable-word? (fn [w] (> (count w) 2))] (filter indexable-word? (str/split text #"\W+")))) (indexable-words "A fine day it is") (defn make-greeter [greeting-prefix] (fn [username] [str greeting-prefix "," username])) (def hello-greeting (make-greeter "Hello")) (def aloha-greeting (make-greeter "Aloha")) (hello-greeting "world") (aloha-greeting "world") ((make-greeter "Howdy") "pardner") (defn square-corners [bottom left size] (let [top (+ bottom size) right (+ left size)] [[bottom left] [top left] [top right] [bottom right]])) (square-corners 10 5 12) (defn greet-author-1 [author] (println "Hello," (:first-name author))) (defn greet-author-2 [{fname :first-name}] (println "Hello," fname)) (greet-author-1 {:last-name "PI:NAME:<NAME>END_PI" :first-name "PI:NAME:<NAME>END_PI"}) (greet-author-2 {:last-name "PI:NAME:<NAME>END_PI" :first-name "PI:NAME:<NAME>END_PI"}) (defn ellipsize [words] (let [[w1 w2 w3] (str/split words #"\s+")] (str/join " " [w1 w2 w3 "..."]))) (ellipsize "The quick brown fox jumps over the lazy dog.") (defn shout ([s] (clojure.string/upper-case s)) {:tag String}) (meta #'shout) (defn is-small? [number] (if (< number 100) "yes" (do (println "Saw a big number" number) "no"))) (is-small? 50) (is-small? 50000) (loop [result [] x 5] (if (zero? x) result (recur (conj result x) (dec x)))) (defn countdown [result x] (if (zero? x) result (recur (conj result x) (dec x)))) (countdown [] 5) (into [] (take 5 (iterate dec 5))) (into [] (drop-last (reverse (range 6)))) (vec (reverse (rest (range 6)))) (defn indexed [coll] (map-indexed vector coll)) (defn index-filter [pred coll] (when pred (for [[idx elt] (indexed coll) :when (pred elt)] idx))) (defn index-of-any [pred coll] (first (index-filter pred coll))) (indexed "abcde") (index-filter #{\a \b} "abcdbbb") (index-filter #{\a \b} "xyz") (index-of-any #{\z \a} "zzabyycdxx") (index-of-any #{\b \y} "zzabyycdxx") (nth (index-filter #{:h} [:t :t :h :t :h :t :t :t :h :h]) 2)
[ { "context": "pldb-atom \"test\" \"pldb-test\" :facts\n [[parent \"Shmi Skywalker\" \"Anakin Skywalker\"]\n [parent \"Ruwe", "end": 560, "score": 0.6099648475646973, "start": 556, "tag": "NAME", "value": "Shmi" }, { "context": "\"pldb-test\" :facts\n [[parent \"Shmi Skywalker\" \"Anakin Skywalker\"]\n [parent \"Ruwee Naberrie\" \"Padme Amid", "end": 583, "score": 0.8062254190444946, "start": 573, "tag": "NAME", "value": "Anakin Sky" }, { "context": "Shmi Skywalker\" \"Anakin Skywalker\"]\n [parent \"Ruwee Naberrie\" \"Padme Amidala\"]\n [parent \"Jorbal Naberrie\" ", "end": 620, "score": 0.9994494318962097, "start": 606, "tag": "NAME", "value": "Ruwee Naberrie" }, { "context": "Anakin Skywalker\"]\n [parent \"Ruwee Naberrie\" \"Padme Amidala\"]\n [parent \"Jorbal Naberrie\" \"Padme Amidala\"]", "end": 636, "score": 0.9987238049507141, "start": 623, "tag": "NAME", "value": "Padme Amidala" }, { "context": "t \"Ruwee Naberrie\" \"Padme Amidala\"]\n [parent \"Jorbal Naberrie\" \"Padme Amidala\"]\n [parent \"Cliegg Lars\" \"Owe", "end": 668, "score": 0.9994569420814514, "start": 653, "tag": "NAME", "value": "Jorbal Naberrie" }, { "context": " \"Padme Amidala\"]\n [parent \"Jorbal Naberrie\" \"Padme Amidala\"]\n [parent \"Cliegg Lars\" \"Owen Lars\"]\n [p", "end": 684, "score": 0.9981430172920227, "start": 671, "tag": "NAME", "value": "Padme Amidala" }, { "context": " \"Jorbal Naberrie\" \"Padme Amidala\"]\n [parent \"Cliegg Lars\" \"Owen Lars\"]\n [parent \"Owen Lars\" \"Luke", "end": 707, "score": 0.6216099858283997, "start": 701, "tag": "NAME", "value": "Cliegg" }, { "context": "rie\" \"Padme Amidala\"]\n [parent \"Cliegg Lars\" \"Owen Lars\"]\n [parent \"Owen Lars\" \"Luke Skywalker\"]\n ", "end": 724, "score": 0.8591868281364441, "start": 715, "tag": "NAME", "value": "Owen Lars" }, { "context": " [parent \"Cliegg Lars\" \"Owen Lars\"]\n [parent \"Owen Lars\" \"Luke Skywalker\"]\n [parent \"Beru Lars\" \"Luke", "end": 750, "score": 0.7057692408561707, "start": 741, "tag": "NAME", "value": "Owen Lars" }, { "context": "iegg Lars\" \"Owen Lars\"]\n [parent \"Owen Lars\" \"Luke Skywalker\"]\n [parent \"Beru Lars\" \"Luke Skywalker\"]\n ", "end": 767, "score": 0.7754505276679993, "start": 753, "tag": "NAME", "value": "Luke Skywalker" }, { "context": "arent \"Owen Lars\" \"Luke Skywalker\"]\n [parent \"Beru Lars\" \"Luke Skywalker\"]\n [parent \"Luke Skywalker\" ", "end": 793, "score": 0.7624090313911438, "start": 784, "tag": "NAME", "value": "Beru Lars" }, { "context": "Lars\" \"Luke Skywalker\"]\n [parent \"Beru Lars\" \"Luke Skywalker\"]\n [parent \"Luke Skywalker\" \"Ben Skywal", "end": 804, "score": 0.7302770614624023, "start": 796, "tag": "NAME", "value": "Luke Sky" }, { "context": "ent \"Beru Lars\" \"Luke Skywalker\"]\n [parent \"Luke Skywalker\" \"Ben Skywalker\"]\n [parent \"Mara Ja", "end": 831, "score": 0.6912220120429993, "start": 829, "tag": "NAME", "value": "ke" }, { "context": " \"Luke Skywalker\"]\n [parent \"Luke Skywalker\" \"Ben Skywalker\"]\n [parent \"Mara Jade\" \"Ben Skywalker\"]\n ", "end": 857, "score": 0.8278526663780212, "start": 844, "tag": "NAME", "value": "Ben Skywalker" }, { "context": "t \"Luke Skywalker\" \"Ben Skywalker\"]\n [parent \"Mara Jade\" \"Ben Skywalker\"]\n [parent \"Anakin Skywalker\"", "end": 883, "score": 0.9851542711257935, "start": 874, "tag": "NAME", "value": "Mara Jade" }, { "context": "alker\" \"Ben Skywalker\"]\n [parent \"Mara Jade\" \"Ben Skywalker\"]\n [parent \"Anakin Skywalker\" \"Luke Skywalker", "end": 899, "score": 0.868304431438446, "start": 886, "tag": "NAME", "value": "Ben Skywalker" }, { "context": "parent \"Mara Jade\" \"Ben Skywalker\"]\n [parent \"Anakin Skywalker\" \"Luke Skywalker\"]\n [parent \"Padme ", "end": 922, "score": 0.7868309020996094, "start": 916, "tag": "NAME", "value": "Anakin" }, { "context": "\"Ben Skywalker\"]\n [parent \"Anakin Skywalker\" \"Luke Skywalker\"]\n [parent \"Padme Amidala\" \"Luke Sk", "end": 939, "score": 0.8636469841003418, "start": 935, "tag": "NAME", "value": "Luke" }, { "context": "Anakin Skywalker\" \"Luke Skywalker\"]\n [parent \"Padme Amidala\" \"Luke Skywalker\"]\n [parent \"Anakin Skywalker", "end": 979, "score": 0.9883953332901001, "start": 966, "tag": "NAME", "value": "Padme Amidala" }, { "context": "\" \"Luke Skywalker\"]\n [parent \"Padme Amidala\" \"Luke Skywalker\"]\n [parent \"Anakin Skywalker\" \"Princess", "end": 990, "score": 0.7845757007598877, "start": 982, "tag": "NAME", "value": "Luke Sky" }, { "context": "t \"Padme Amidala\" \"Luke Skywalker\"]\n [parent \"Anakin Skywalker\" \"Princess Leia\"]\n [parent \"Padme Amida", "end": 1023, "score": 0.6953153610229492, "start": 1013, "tag": "NAME", "value": "Anakin Sky" }, { "context": "Luke Skywalker\"]\n [parent \"Anakin Skywalker\" \"Princess Leia\"]\n [parent \"Padme Amidala\" \"Princess Leia\"]\n ", "end": 1045, "score": 0.9911203384399414, "start": 1032, "tag": "NAME", "value": "Princess Leia" }, { "context": "\"Anakin Skywalker\" \"Princess Leia\"]\n [parent \"Padme Amidala\" \"Princess Leia\"]\n [parent \"Bail Organa\" \"Pri", "end": 1075, "score": 0.9681187868118286, "start": 1062, "tag": "NAME", "value": "Padme Amidala" }, { "context": "r\" \"Princess Leia\"]\n [parent \"Padme Amidala\" \"Princess Leia\"]\n [parent \"Bail Organa\" \"Princess Leia\"]\n ", "end": 1091, "score": 0.9841213226318359, "start": 1078, "tag": "NAME", "value": "Princess Leia" }, { "context": "nt \"Padme Amidala\" \"Princess Leia\"]\n [parent \"Bail Organa\" \"Princess Leia\"]\n [parent \"Breha Organa\" ", "end": 1116, "score": 0.766456663608551, "start": 1108, "tag": "NAME", "value": "Bail Org" }, { "context": "ala\" \"Princess Leia\"]\n [parent \"Bail Organa\" \"Princess Leia\"]\n [parent \"Breha Organa\" \"Princess Leia\"]\n ", "end": 1135, "score": 0.9527285695075989, "start": 1122, "tag": "NAME", "value": "Princess Leia" }, { "context": "rent \"Bail Organa\" \"Princess Leia\"]\n [parent \"Breha Organa\" \"Princess Leia\"]\n [parent \"Princess Leia\"", "end": 1161, "score": 0.7944038510322571, "start": 1152, "tag": "NAME", "value": "Breha Org" }, { "context": "na\" \"Princess Leia\"]\n [parent \"Breha Organa\" \"Princess Leia\"]\n [parent \"Princess Leia\" \"Jaina Solo\"]\n ", "end": 1180, "score": 0.9832599759101868, "start": 1167, "tag": "NAME", "value": "Princess Leia" }, { "context": "ent \"Breha Organa\" \"Princess Leia\"]\n [parent \"Princess Leia\" \"Jaina Solo\"]\n [parent \"Princess Leia\" \"Jace", "end": 1210, "score": 0.9591336250305176, "start": 1197, "tag": "NAME", "value": "Princess Leia" }, { "context": "a\" \"Princess Leia\"]\n [parent \"Princess Leia\" \"Jaina Solo\"]\n [parent \"Princess Leia\" \"Jacen Solo\"]\n ", "end": 1223, "score": 0.8363758325576782, "start": 1213, "tag": "NAME", "value": "Jaina Solo" }, { "context": "arent \"Princess Leia\" \"Jaina Solo\"]\n [parent \"Princess Leia\" \"Jacen Solo\"]\n [parent \"Princess Leia\" \"Anak", "end": 1253, "score": 0.9525226354598999, "start": 1240, "tag": "NAME", "value": "Princess Leia" }, { "context": "Leia\" \"Jaina Solo\"]\n [parent \"Princess Leia\" \"Jacen Solo\"]\n [parent \"Princess Leia\" \"Anakin Solo\"]\n ", "end": 1266, "score": 0.8410232663154602, "start": 1256, "tag": "NAME", "value": "Jacen Solo" }, { "context": "arent \"Princess Leia\" \"Jacen Solo\"]\n [parent \"Princess Leia\" \"Anakin Solo\"]\n [parent \"Han Solo\" \"Jaina So", "end": 1296, "score": 0.8783289790153503, "start": 1283, "tag": "NAME", "value": "Princess Leia" }, { "context": "Leia\" \"Jacen Solo\"]\n [parent \"Princess Leia\" \"Anakin Solo\"]\n [parent \"Han Solo\" \"Jaina Solo\"]\n [par", "end": 1310, "score": 0.8629213571548462, "start": 1299, "tag": "NAME", "value": "Anakin Solo" }, { "context": "n Solo\" \"Jaina Solo\"]\n [parent \"Han Solo\" \"Jacen Solo\"]\n [parent \"Han Solo\" \"Anakin Solo\"]\n\n ", "end": 1381, "score": 0.522638738155365, "start": 1379, "tag": "NAME", "value": "en" }, { "context": " Solo\" \"Jacen Solo\"]\n [parent \"Han Solo\" \"Anakin Solo\"]\n\n [female \"Shmi Skywalker\"]\n [fema", "end": 1420, "score": 0.5691314935684204, "start": 1418, "tag": "NAME", "value": "in" }, { "context": " [parent \"Han Solo\" \"Anakin Solo\"]\n\n [female \"Shmi Skywalker\"]\n [female \"Jorbal Naberrie\"]\n [female \"B", "end": 1457, "score": 0.8868885040283203, "start": 1443, "tag": "NAME", "value": "Shmi Skywalker" }, { "context": "o\"]\n\n [female \"Shmi Skywalker\"]\n [female \"Jorbal Naberrie\"]\n [female \"Beru Lars\"]\n [female \"Mara Ja", "end": 1489, "score": 0.9929048418998718, "start": 1474, "tag": "NAME", "value": "Jorbal Naberrie" }, { "context": "r\"]\n [female \"Jorbal Naberrie\"]\n [female \"Beru Lars\"]\n [female \"Mara Jade\"]\n [female \"Padme A", "end": 1515, "score": 0.9989137649536133, "start": 1506, "tag": "NAME", "value": "Beru Lars" }, { "context": "aberrie\"]\n [female \"Beru Lars\"]\n [female \"Mara Jade\"]\n [female \"Padme Amidala\"]\n [female \"Bre", "end": 1541, "score": 0.9994502067565918, "start": 1532, "tag": "NAME", "value": "Mara Jade" }, { "context": "ru Lars\"]\n [female \"Mara Jade\"]\n [female \"Padme Amidala\"]\n [female \"Breha Organa\"]\n [female \"Prin", "end": 1571, "score": 0.9996212124824524, "start": 1558, "tag": "NAME", "value": "Padme Amidala" }, { "context": "ade\"]\n [female \"Padme Amidala\"]\n [female \"Breha Organa\"]\n [female \"Princess Leia\"]\n [female \"Jai", "end": 1600, "score": 0.9992139339447021, "start": 1588, "tag": "NAME", "value": "Breha Organa" }, { "context": "dala\"]\n [female \"Breha Organa\"]\n [female \"Princess Leia\"]\n [female \"Jaina Solo\"]\n\n [male \"Cliegg ", "end": 1630, "score": 0.9996994137763977, "start": 1617, "tag": "NAME", "value": "Princess Leia" }, { "context": "ana\"]\n [female \"Princess Leia\"]\n [female \"Jaina Solo\"]\n\n [male \"Cliegg Lars\"]\n [male \"Owen Lar", "end": 1657, "score": 0.9993885159492493, "start": 1647, "tag": "NAME", "value": "Jaina Solo" }, { "context": "ss Leia\"]\n [female \"Jaina Solo\"]\n\n [male \"Cliegg Lars\"]\n [male \"Owen Lars\"]\n [male \"Ruwee Naber", "end": 1684, "score": 0.9984310865402222, "start": 1673, "tag": "NAME", "value": "Cliegg Lars" }, { "context": "ina Solo\"]\n\n [male \"Cliegg Lars\"]\n [male \"Owen Lars\"]\n [male \"Ruwee Naberrie\"]\n [male \"Anakin", "end": 1708, "score": 0.9987678527832031, "start": 1699, "tag": "NAME", "value": "Owen Lars" }, { "context": "Cliegg Lars\"]\n [male \"Owen Lars\"]\n [male \"Ruwee Naberrie\"]\n [male \"Anakin Skywalker\"]\n [male \"Bail", "end": 1737, "score": 0.9996779561042786, "start": 1723, "tag": "NAME", "value": "Ruwee Naberrie" }, { "context": "n Lars\"]\n [male \"Ruwee Naberrie\"]\n [male \"Anakin Skywalker\"]\n [male \"Bail Organa\"]\n [male \"Ben Skywa", "end": 1768, "score": 0.9946931004524231, "start": 1752, "tag": "NAME", "value": "Anakin Skywalker" }, { "context": "rrie\"]\n [male \"Anakin Skywalker\"]\n [male \"Bail Organa\"]\n [male \"Ben Skywalker\"]\n [male \"Han Sol", "end": 1794, "score": 0.9978980422019958, "start": 1783, "tag": "NAME", "value": "Bail Organa" }, { "context": "Skywalker\"]\n [male \"Bail Organa\"]\n [male \"Ben Skywalker\"]\n [male \"Han Solo\"]\n [male \"Jacen Solo\"]", "end": 1822, "score": 0.9925515055656433, "start": 1809, "tag": "NAME", "value": "Ben Skywalker" }, { "context": " Organa\"]\n [male \"Ben Skywalker\"]\n [male \"Han Solo\"]\n [male \"Jacen Solo\"]\n [male \"Anakin Sol", "end": 1845, "score": 0.9368197321891785, "start": 1837, "tag": "NAME", "value": "Han Solo" }, { "context": "en Skywalker\"]\n [male \"Han Solo\"]\n [male \"Jacen Solo\"]\n [male \"Anakin Solo\"]]))\n\n\n;; Find Luke's f", "end": 1870, "score": 0.9909346699714661, "start": 1860, "tag": "NAME", "value": "Jacen Solo" }, { "context": " \"Han Solo\"]\n [male \"Jacen Solo\"]\n [male \"Anakin Solo\"]]))\n\n\n;; Find Luke's father (he has two because ", "end": 1896, "score": 0.9588780403137207, "start": 1885, "tag": "NAME", "value": "Anakin Solo" }, { "context": "acen Solo\"]\n [male \"Anakin Solo\"]]))\n\n\n;; Find Luke's father (he has two because of adoption)\n(printl", "end": 1916, "score": 0.9660890698432922, "start": 1912, "tag": "NAME", "value": "Luke" }, { "context": "om\n (l/run* [q]\n (parent q \"Luke Skywalker\")\n (male q))))\n\n;; Find Luke's mom (s", "end": 2054, "score": 0.7016677260398865, "start": 2040, "tag": "NAME", "value": "Luke Skywalker" }, { "context": "Luke Skywalker\")\n (male q))))\n\n;; Find Luke's mom (step-mom too)\n(println (pldb/with-db @test", "end": 2095, "score": 0.9227623343467712, "start": 2091, "tag": "NAME", "value": "Luke" }, { "context": "om\n (l/run* [q]\n (parent q \"Luke Skywalker\")\n (female q))))\n\n;; Luke's grandmoth", "end": 2212, "score": 0.8448819518089294, "start": 2198, "tag": "NAME", "value": "Luke Skywalker" }, { "context": "q \"Luke Skywalker\")\n (female q))))\n\n;; Luke's grandmothers\n(println (pldb/with-db @test-atom\n", "end": 2250, "score": 0.8559694886207581, "start": 2246, "tag": "NAME", "value": "Luke" }, { "context": " (l/fresh [p]\n (parent p \"Luke Skywalker\")\n (parent q p)\n (fem", "end": 2389, "score": 0.7932227253913879, "start": 2375, "tag": "NAME", "value": "Luke Skywalker" }, { "context": "tom\n [parent \"???\" \"Chewbacca\"]\n [parent \"???\" \"Anakin Skywalker\"]\n [male \"???\"]\n [male \"Chewbacca\"])\n\n;; So now", "end": 2855, "score": 0.9055968523025513, "start": 2839, "tag": "NAME", "value": "Anakin Skywalker" } ]
examples/star-wars/pldb.cljs
greenyouse/multco
6
(ns examples.star-wars.pldb (:require [multco.core :as m] [cljs.core.logic.pldb :as pldb] [cljs.core.logic :as l])) (pldb/db-rel parent Parent Child) (pldb/db-rel female Person) (pldb/db-rel male Person) ;; This serves as a default set of facts. Any subsequent additions ;; or retractions will be saved and override this set of facts. ;; This allows a program to store its info persistently! ;; For reference: http://www.chartgeek.com/star-wars-family-tree/ (def test-atom (m/pldb-atom "test" "pldb-test" :facts [[parent "Shmi Skywalker" "Anakin Skywalker"] [parent "Ruwee Naberrie" "Padme Amidala"] [parent "Jorbal Naberrie" "Padme Amidala"] [parent "Cliegg Lars" "Owen Lars"] [parent "Owen Lars" "Luke Skywalker"] [parent "Beru Lars" "Luke Skywalker"] [parent "Luke Skywalker" "Ben Skywalker"] [parent "Mara Jade" "Ben Skywalker"] [parent "Anakin Skywalker" "Luke Skywalker"] [parent "Padme Amidala" "Luke Skywalker"] [parent "Anakin Skywalker" "Princess Leia"] [parent "Padme Amidala" "Princess Leia"] [parent "Bail Organa" "Princess Leia"] [parent "Breha Organa" "Princess Leia"] [parent "Princess Leia" "Jaina Solo"] [parent "Princess Leia" "Jacen Solo"] [parent "Princess Leia" "Anakin Solo"] [parent "Han Solo" "Jaina Solo"] [parent "Han Solo" "Jacen Solo"] [parent "Han Solo" "Anakin Solo"] [female "Shmi Skywalker"] [female "Jorbal Naberrie"] [female "Beru Lars"] [female "Mara Jade"] [female "Padme Amidala"] [female "Breha Organa"] [female "Princess Leia"] [female "Jaina Solo"] [male "Cliegg Lars"] [male "Owen Lars"] [male "Ruwee Naberrie"] [male "Anakin Skywalker"] [male "Bail Organa"] [male "Ben Skywalker"] [male "Han Solo"] [male "Jacen Solo"] [male "Anakin Solo"]])) ;; Find Luke's father (he has two because of adoption) (println (pldb/with-db @test-atom (l/run* [q] (parent q "Luke Skywalker") (male q)))) ;; Find Luke's mom (step-mom too) (println (pldb/with-db @test-atom (l/run* [q] (parent q "Luke Skywalker") (female q)))) ;; Luke's grandmothers (println (pldb/with-db @test-atom (l/run* [q] (l/fresh [p] (parent p "Luke Skywalker") (parent q p) (female q))))) ;; let's find all the father-child relations (println (pldb/with-db @test-atom (l/run* [q] (l/fresh [p s] (parent p s) (male p) (l/== q [p s]))))) ;; Now let's add more facts to our database and see how the changes are ;; reflected in the queries (m/add-facts! test-atom [parent "???" "Chewbacca"] [parent "???" "Anakin Skywalker"] [male "???"] [male "Chewbacca"]) ;; So now we have people with unknown fathers in our data (println (pldb/with-db @test-atom (l/run* [q] (parent "???" q)))) ;; Let's get rid of that and go back to the default (m/rm-facts! test-atom [parent "???" "Chewbacca"] [parent "???" "Anakin Skywalker"] [male "???"] [male "Chewbacca"]) ;; Double-check that the facts are gone (println (pldb/with-db @test-atom (l/run* [q] (parent "???" q)))) ;; What if we only care about one relationship and want to delete ;; everything else? Just reset the database: (m/reset-facts! test-atom [parent "???" "Jar Jar Binks"] [female "???"] [male "???"] [male "Jar Jar Binks"]) ;; Try reloading the page and evaluting test-atom and the relations above ;; it. Now check to see if the change we made persisted. (println (pldb/with-db @test-atom (l/run* [q] (male "Jar Jar Binks")))) ;; Is Jar Jar really the only thing we have? (println (pldb/with-db @test-atom (l/run* [q] (l/fresh [p s] (parent p s) (l/== q [p s]))))) ;; Yup, Jar Jar is the only thing in there (oh no) and everything worked! ;; If you want to delete this experiment do: (m/clear! test-atom) ;; and here's how to delete the entire database: (m/rm-db test-atom)
27848
(ns examples.star-wars.pldb (:require [multco.core :as m] [cljs.core.logic.pldb :as pldb] [cljs.core.logic :as l])) (pldb/db-rel parent Parent Child) (pldb/db-rel female Person) (pldb/db-rel male Person) ;; This serves as a default set of facts. Any subsequent additions ;; or retractions will be saved and override this set of facts. ;; This allows a program to store its info persistently! ;; For reference: http://www.chartgeek.com/star-wars-family-tree/ (def test-atom (m/pldb-atom "test" "pldb-test" :facts [[parent "<NAME> Skywalker" "<NAME>walker"] [parent "<NAME>" "<NAME>"] [parent "<NAME>" "<NAME>"] [parent "<NAME> Lars" "<NAME>"] [parent "<NAME>" "<NAME>"] [parent "<NAME>" "<NAME>walker"] [parent "Lu<NAME> Skywalker" "<NAME>"] [parent "<NAME>" "<NAME>"] [parent "<NAME> Skywalker" "<NAME> Skywalker"] [parent "<NAME>" "<NAME>walker"] [parent "<NAME>walker" "<NAME>"] [parent "<NAME>" "<NAME>"] [parent "<NAME>ana" "<NAME>"] [parent "<NAME>ana" "<NAME>"] [parent "<NAME>" "<NAME>"] [parent "<NAME>" "<NAME>"] [parent "<NAME>" "<NAME>"] [parent "Han Solo" "Jaina Solo"] [parent "Han Solo" "Jac<NAME> Solo"] [parent "Han Solo" "Anak<NAME> Solo"] [female "<NAME>"] [female "<NAME>"] [female "<NAME>"] [female "<NAME>"] [female "<NAME>"] [female "<NAME>"] [female "<NAME>"] [female "<NAME>"] [male "<NAME>"] [male "<NAME>"] [male "<NAME>"] [male "<NAME>"] [male "<NAME>"] [male "<NAME>"] [male "<NAME>"] [male "<NAME>"] [male "<NAME>"]])) ;; Find <NAME>'s father (he has two because of adoption) (println (pldb/with-db @test-atom (l/run* [q] (parent q "<NAME>") (male q)))) ;; Find <NAME>'s mom (step-mom too) (println (pldb/with-db @test-atom (l/run* [q] (parent q "<NAME>") (female q)))) ;; <NAME>'s grandmothers (println (pldb/with-db @test-atom (l/run* [q] (l/fresh [p] (parent p "<NAME>") (parent q p) (female q))))) ;; let's find all the father-child relations (println (pldb/with-db @test-atom (l/run* [q] (l/fresh [p s] (parent p s) (male p) (l/== q [p s]))))) ;; Now let's add more facts to our database and see how the changes are ;; reflected in the queries (m/add-facts! test-atom [parent "???" "Chewbacca"] [parent "???" "<NAME>"] [male "???"] [male "Chewbacca"]) ;; So now we have people with unknown fathers in our data (println (pldb/with-db @test-atom (l/run* [q] (parent "???" q)))) ;; Let's get rid of that and go back to the default (m/rm-facts! test-atom [parent "???" "Chewbacca"] [parent "???" "Anakin Skywalker"] [male "???"] [male "Chewbacca"]) ;; Double-check that the facts are gone (println (pldb/with-db @test-atom (l/run* [q] (parent "???" q)))) ;; What if we only care about one relationship and want to delete ;; everything else? Just reset the database: (m/reset-facts! test-atom [parent "???" "Jar Jar Binks"] [female "???"] [male "???"] [male "Jar Jar Binks"]) ;; Try reloading the page and evaluting test-atom and the relations above ;; it. Now check to see if the change we made persisted. (println (pldb/with-db @test-atom (l/run* [q] (male "Jar Jar Binks")))) ;; Is Jar Jar really the only thing we have? (println (pldb/with-db @test-atom (l/run* [q] (l/fresh [p s] (parent p s) (l/== q [p s]))))) ;; Yup, Jar Jar is the only thing in there (oh no) and everything worked! ;; If you want to delete this experiment do: (m/clear! test-atom) ;; and here's how to delete the entire database: (m/rm-db test-atom)
true
(ns examples.star-wars.pldb (:require [multco.core :as m] [cljs.core.logic.pldb :as pldb] [cljs.core.logic :as l])) (pldb/db-rel parent Parent Child) (pldb/db-rel female Person) (pldb/db-rel male Person) ;; This serves as a default set of facts. Any subsequent additions ;; or retractions will be saved and override this set of facts. ;; This allows a program to store its info persistently! ;; For reference: http://www.chartgeek.com/star-wars-family-tree/ (def test-atom (m/pldb-atom "test" "pldb-test" :facts [[parent "PI:NAME:<NAME>END_PI Skywalker" "PI:NAME:<NAME>END_PIwalker"] [parent "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] [parent "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] [parent "PI:NAME:<NAME>END_PI Lars" "PI:NAME:<NAME>END_PI"] [parent "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] [parent "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PIwalker"] [parent "LuPI:NAME:<NAME>END_PI Skywalker" "PI:NAME:<NAME>END_PI"] [parent "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] [parent "PI:NAME:<NAME>END_PI Skywalker" "PI:NAME:<NAME>END_PI Skywalker"] [parent "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PIwalker"] [parent "PI:NAME:<NAME>END_PIwalker" "PI:NAME:<NAME>END_PI"] [parent "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] [parent "PI:NAME:<NAME>END_PIana" "PI:NAME:<NAME>END_PI"] [parent "PI:NAME:<NAME>END_PIana" "PI:NAME:<NAME>END_PI"] [parent "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] [parent "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] [parent "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] [parent "Han Solo" "Jaina Solo"] [parent "Han Solo" "JacPI:NAME:<NAME>END_PI Solo"] [parent "Han Solo" "AnakPI:NAME:<NAME>END_PI Solo"] [female "PI:NAME:<NAME>END_PI"] [female "PI:NAME:<NAME>END_PI"] [female "PI:NAME:<NAME>END_PI"] [female "PI:NAME:<NAME>END_PI"] [female "PI:NAME:<NAME>END_PI"] [female "PI:NAME:<NAME>END_PI"] [female "PI:NAME:<NAME>END_PI"] [female "PI:NAME:<NAME>END_PI"] [male "PI:NAME:<NAME>END_PI"] [male "PI:NAME:<NAME>END_PI"] [male "PI:NAME:<NAME>END_PI"] [male "PI:NAME:<NAME>END_PI"] [male "PI:NAME:<NAME>END_PI"] [male "PI:NAME:<NAME>END_PI"] [male "PI:NAME:<NAME>END_PI"] [male "PI:NAME:<NAME>END_PI"] [male "PI:NAME:<NAME>END_PI"]])) ;; Find PI:NAME:<NAME>END_PI's father (he has two because of adoption) (println (pldb/with-db @test-atom (l/run* [q] (parent q "PI:NAME:<NAME>END_PI") (male q)))) ;; Find PI:NAME:<NAME>END_PI's mom (step-mom too) (println (pldb/with-db @test-atom (l/run* [q] (parent q "PI:NAME:<NAME>END_PI") (female q)))) ;; PI:NAME:<NAME>END_PI's grandmothers (println (pldb/with-db @test-atom (l/run* [q] (l/fresh [p] (parent p "PI:NAME:<NAME>END_PI") (parent q p) (female q))))) ;; let's find all the father-child relations (println (pldb/with-db @test-atom (l/run* [q] (l/fresh [p s] (parent p s) (male p) (l/== q [p s]))))) ;; Now let's add more facts to our database and see how the changes are ;; reflected in the queries (m/add-facts! test-atom [parent "???" "Chewbacca"] [parent "???" "PI:NAME:<NAME>END_PI"] [male "???"] [male "Chewbacca"]) ;; So now we have people with unknown fathers in our data (println (pldb/with-db @test-atom (l/run* [q] (parent "???" q)))) ;; Let's get rid of that and go back to the default (m/rm-facts! test-atom [parent "???" "Chewbacca"] [parent "???" "Anakin Skywalker"] [male "???"] [male "Chewbacca"]) ;; Double-check that the facts are gone (println (pldb/with-db @test-atom (l/run* [q] (parent "???" q)))) ;; What if we only care about one relationship and want to delete ;; everything else? Just reset the database: (m/reset-facts! test-atom [parent "???" "Jar Jar Binks"] [female "???"] [male "???"] [male "Jar Jar Binks"]) ;; Try reloading the page and evaluting test-atom and the relations above ;; it. Now check to see if the change we made persisted. (println (pldb/with-db @test-atom (l/run* [q] (male "Jar Jar Binks")))) ;; Is Jar Jar really the only thing we have? (println (pldb/with-db @test-atom (l/run* [q] (l/fresh [p s] (parent p s) (l/== q [p s]))))) ;; Yup, Jar Jar is the only thing in there (oh no) and everything worked! ;; If you want to delete this experiment do: (m/clear! test-atom) ;; and here's how to delete the entire database: (m/rm-db test-atom)
[ { "context": "SelectorExample : \")\n (def simple-person {:name \"Yourtion Guo\"})\n (def name (selector :name))\n (println \"name", "end": 219, "score": 0.9998335838317871, "start": 207, "tag": "NAME", "value": "Yourtion Guo" }, { "context": "rson))\n (def more-complex-person {:name {:first \"Yourtion\" :last \"Guo\"}})\n (def first-name (selector :name", "end": 364, "score": 0.999701976776123, "start": 356, "tag": "NAME", "value": "Yourtion" }, { "context": "e-complex-person {:name {:first \"Yourtion\" :last \"Guo\"}})\n (def first-name (selector :name :first))\n ", "end": 376, "score": 0.9831385612487793, "start": 373, "tag": "NAME", "value": "Guo" } ]
Clojure/src/com/yourtion/Pattern16/selector_example.clj
yourtion/LearningFunctionalProgramming
14
(ns com.yourtion.Pattern16.selector-example) (defn selector [& path] {:pre [(not (empty? path))]} (fn [ds] (get-in ds path))) (defn run [] (println "SelectorExample : ") (def simple-person {:name "Yourtion Guo"}) (def name (selector :name)) (println "name from simplePerson: " (name simple-person)) (def more-complex-person {:name {:first "Yourtion" :last "Guo"}}) (def first-name (selector :name :first)) (println "firstName from moreComplexPerson: " (first-name more-complex-person)) (def middle-name (selector :name :middle)) (println "middleName from moreComplexPerson: " (middle-name more-complex-person)) (println ""))
72474
(ns com.yourtion.Pattern16.selector-example) (defn selector [& path] {:pre [(not (empty? path))]} (fn [ds] (get-in ds path))) (defn run [] (println "SelectorExample : ") (def simple-person {:name "<NAME>"}) (def name (selector :name)) (println "name from simplePerson: " (name simple-person)) (def more-complex-person {:name {:first "<NAME>" :last "<NAME>"}}) (def first-name (selector :name :first)) (println "firstName from moreComplexPerson: " (first-name more-complex-person)) (def middle-name (selector :name :middle)) (println "middleName from moreComplexPerson: " (middle-name more-complex-person)) (println ""))
true
(ns com.yourtion.Pattern16.selector-example) (defn selector [& path] {:pre [(not (empty? path))]} (fn [ds] (get-in ds path))) (defn run [] (println "SelectorExample : ") (def simple-person {:name "PI:NAME:<NAME>END_PI"}) (def name (selector :name)) (println "name from simplePerson: " (name simple-person)) (def more-complex-person {:name {:first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI"}}) (def first-name (selector :name :first)) (println "firstName from moreComplexPerson: " (first-name more-complex-person)) (def middle-name (selector :name :middle)) (println "middleName from moreComplexPerson: " (middle-name more-complex-person)) (println ""))
[ { "context": "; Copyright (c) 2011-2013, Tom Van Cutsem, Vrije Universiteit Brussel\n; All rights reserved", "end": 41, "score": 0.999858021736145, "start": 27, "tag": "NAME", "value": "Tom Van Cutsem" }, { "context": "Clojure\n;; Multicore Programming\n;; (c) 2011-2013, Tom Van Cutsem\n\n;; simple usage examples of MC-STM\n\n(ns test.exa", "end": 1680, "score": 0.9998412728309631, "start": 1666, "tag": "NAME", "value": "Tom Van Cutsem" }, { "context": " ===\n\n; From clojure.org/concurrent_programming by Rich Hickey:\n; In this example a vector of Refs containing in", "end": 2497, "score": 0.9998292922973633, "start": 2486, "tag": "NAME", "value": "Rich Hickey" }, { "context": "Vector swap ===\n\n; From http://clojure.org/refs by Rich Hickey:\n; In this example a vector of references to vect", "end": 3727, "score": 0.9998537302017212, "start": 3716, "tag": "NAME", "value": "Rich Hickey" } ]
test/examples.clj
tvcutsem/stm-in-clojure
33
; Copyright (c) 2011-2013, Tom Van Cutsem, Vrije Universiteit Brussel ; 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 Vrije Universiteit Brussel 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 VRIJE UNIVERSITEIT BRUSSEL 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. ;; MC-STM: meta-circular STM in Clojure ;; Multicore Programming ;; (c) 2011-2013, Tom Van Cutsem ;; simple usage examples of MC-STM (ns test.examples ;(:use clojure.contrib.test-is) (:use clojure.test) (:import (java.util.concurrent Executors))) ; (use 'stm.v0-native) ; (use 'stm.v1-simple) ; (use 'stm.v2-mvcc) ; (use 'stm.v3-mvcc-commute) ; (use 'stm.v4-mvcc-fine-grained) (use 'stm.v5-mvcc-fine-grained-barging) ;; === Bank account transfer === (defn transfer [amount from to] (mc-dosync (mc-alter from - amount) (mc-alter to + amount))) (deftest transfer-test [] (def accountA (mc-ref 1500)) (def accountB (mc-ref 200)) (is (= 1500 (mc-deref accountA))) (is (= 200 (mc-deref accountB))) (transfer 100 accountA accountB) (is (= 1400 (mc-deref accountA))) (is (= 300 (mc-deref accountB)))) ;; === Contention === ; From clojure.org/concurrent_programming by Rich Hickey: ; In this example a vector of Refs containing integers is created (refs), ; then a set of threads are set up (pool) to run a number of iterations of ; incrementing every Ref (tasks). This creates extreme contention, ; but yields the correct result. No locks! (defn test-stm [nitems nthreads niters] (let [refs (map mc-ref (replicate nitems 0)) pool (Executors/newFixedThreadPool nthreads) tasks (map (fn [t] (fn [] (dotimes [n niters] (mc-dosync (doseq [r refs] (mc-alter r + 1 t)))))) (range nthreads))] (doseq [future (.invokeAll pool tasks)] (.get future)) (.shutdown pool) (map mc-deref refs))) (deftest contention-test ; 10 threads increment each of 10 refs 10000 times ; each ref should be incremented by 550000 in total = ; (* 10000 (+ 1 2 3 4 5 6 7 8 9 10)) ; -> (550000 550000 550000 550000 550000 550000 550000 550000 550000 550000) (let [res (time (test-stm 10 10 10000))] (is (= (count res) 10)) (is (every? (fn [r] (= r 550000)) res)))) ;; === Vector swap === ; From http://clojure.org/refs by Rich Hickey: ; In this example a vector of references to vectors is created, each containing ; (initially sequential) unique numbers. Then a set of threads are started that ; repeatedly select two random positions in two random vectors and swap them, ; in a transaction. No special effort is made to prevent the inevitable ; conflicts other than the use of transactions. (defn vector-swap [nvecs nitems nthreads niters] (let [vec-refs (vec (map (comp mc-ref vec) (partition nitems (range (* nvecs nitems))))) swap #(let [v1 (rand-int nvecs) v2 (rand-int nvecs) i1 (rand-int nitems) i2 (rand-int nitems)] (mc-dosync (let [temp (nth (mc-deref (vec-refs v1)) i1)] (mc-alter (vec-refs v1) assoc i1 (nth (mc-deref (vec-refs v2)) i2)) (mc-alter (vec-refs v2) assoc i2 temp)))) check-distinct #(do ; (prn (map mc-deref vec-refs)) (is (= (* nvecs nitems) (count (distinct (apply concat (map mc-deref vec-refs)))))))] (check-distinct) (dorun (apply pcalls (repeat nthreads #(dotimes [_ niters] (swap))))) (check-distinct))) (deftest vector-swap-test (time (vector-swap 100 10 10 100000))) (run-tests) (shutdown-agents) ; shutdown thread pool used by pcalls ; ----------------------------------------------------- ; observed behavior on: ; Clojure 1.2.0-RC2 ; JDK 1.6.0 ; Mac OS X 10.6.7 ; Macbook, 2.4 GHz Intel Core 2 Duo, 4 GB 1067 MHz DDR3 ; ----------------------------------------------------- ; contention-test: ; v0-native: "Elapsed time: 2731.11 msecs" ; v1-simple: "Elapsed time: 8105.424 msecs" (x2.96) ; v2-mvcc: "Elapsed time: 10714.035 msecs" (x3.92) ; v3-mvcc-commute: "Elapsed time: 9751.687 msecs" (x3.57) ; v4-mvcc-fine-grained: "Elapsed time: 16174.881 msecs" (x5.92) ; vector-swap: ; v0-native: "Elapsed time: 5180.694 msecs" ; v1-simple: "Elapsed time: 16037.275 msecs" (x3.09) ; v2-mvcc: "Elapsed time: 29760.412 msecs" (x5.74) ; v3-mvcc-commute: "Elapsed time: 31856.438 msecs" (x6.14) ; v4-mvcc-fine-grained: "Elapsed time: 21752.742 msecs" (x4.19)
59838
; Copyright (c) 2011-2013, <NAME>, Vrije Universiteit Brussel ; 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 Vrije Universiteit Brussel 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 VRIJE UNIVERSITEIT BRUSSEL 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. ;; MC-STM: meta-circular STM in Clojure ;; Multicore Programming ;; (c) 2011-2013, <NAME> ;; simple usage examples of MC-STM (ns test.examples ;(:use clojure.contrib.test-is) (:use clojure.test) (:import (java.util.concurrent Executors))) ; (use 'stm.v0-native) ; (use 'stm.v1-simple) ; (use 'stm.v2-mvcc) ; (use 'stm.v3-mvcc-commute) ; (use 'stm.v4-mvcc-fine-grained) (use 'stm.v5-mvcc-fine-grained-barging) ;; === Bank account transfer === (defn transfer [amount from to] (mc-dosync (mc-alter from - amount) (mc-alter to + amount))) (deftest transfer-test [] (def accountA (mc-ref 1500)) (def accountB (mc-ref 200)) (is (= 1500 (mc-deref accountA))) (is (= 200 (mc-deref accountB))) (transfer 100 accountA accountB) (is (= 1400 (mc-deref accountA))) (is (= 300 (mc-deref accountB)))) ;; === Contention === ; From clojure.org/concurrent_programming by <NAME>: ; In this example a vector of Refs containing integers is created (refs), ; then a set of threads are set up (pool) to run a number of iterations of ; incrementing every Ref (tasks). This creates extreme contention, ; but yields the correct result. No locks! (defn test-stm [nitems nthreads niters] (let [refs (map mc-ref (replicate nitems 0)) pool (Executors/newFixedThreadPool nthreads) tasks (map (fn [t] (fn [] (dotimes [n niters] (mc-dosync (doseq [r refs] (mc-alter r + 1 t)))))) (range nthreads))] (doseq [future (.invokeAll pool tasks)] (.get future)) (.shutdown pool) (map mc-deref refs))) (deftest contention-test ; 10 threads increment each of 10 refs 10000 times ; each ref should be incremented by 550000 in total = ; (* 10000 (+ 1 2 3 4 5 6 7 8 9 10)) ; -> (550000 550000 550000 550000 550000 550000 550000 550000 550000 550000) (let [res (time (test-stm 10 10 10000))] (is (= (count res) 10)) (is (every? (fn [r] (= r 550000)) res)))) ;; === Vector swap === ; From http://clojure.org/refs by <NAME>: ; In this example a vector of references to vectors is created, each containing ; (initially sequential) unique numbers. Then a set of threads are started that ; repeatedly select two random positions in two random vectors and swap them, ; in a transaction. No special effort is made to prevent the inevitable ; conflicts other than the use of transactions. (defn vector-swap [nvecs nitems nthreads niters] (let [vec-refs (vec (map (comp mc-ref vec) (partition nitems (range (* nvecs nitems))))) swap #(let [v1 (rand-int nvecs) v2 (rand-int nvecs) i1 (rand-int nitems) i2 (rand-int nitems)] (mc-dosync (let [temp (nth (mc-deref (vec-refs v1)) i1)] (mc-alter (vec-refs v1) assoc i1 (nth (mc-deref (vec-refs v2)) i2)) (mc-alter (vec-refs v2) assoc i2 temp)))) check-distinct #(do ; (prn (map mc-deref vec-refs)) (is (= (* nvecs nitems) (count (distinct (apply concat (map mc-deref vec-refs)))))))] (check-distinct) (dorun (apply pcalls (repeat nthreads #(dotimes [_ niters] (swap))))) (check-distinct))) (deftest vector-swap-test (time (vector-swap 100 10 10 100000))) (run-tests) (shutdown-agents) ; shutdown thread pool used by pcalls ; ----------------------------------------------------- ; observed behavior on: ; Clojure 1.2.0-RC2 ; JDK 1.6.0 ; Mac OS X 10.6.7 ; Macbook, 2.4 GHz Intel Core 2 Duo, 4 GB 1067 MHz DDR3 ; ----------------------------------------------------- ; contention-test: ; v0-native: "Elapsed time: 2731.11 msecs" ; v1-simple: "Elapsed time: 8105.424 msecs" (x2.96) ; v2-mvcc: "Elapsed time: 10714.035 msecs" (x3.92) ; v3-mvcc-commute: "Elapsed time: 9751.687 msecs" (x3.57) ; v4-mvcc-fine-grained: "Elapsed time: 16174.881 msecs" (x5.92) ; vector-swap: ; v0-native: "Elapsed time: 5180.694 msecs" ; v1-simple: "Elapsed time: 16037.275 msecs" (x3.09) ; v2-mvcc: "Elapsed time: 29760.412 msecs" (x5.74) ; v3-mvcc-commute: "Elapsed time: 31856.438 msecs" (x6.14) ; v4-mvcc-fine-grained: "Elapsed time: 21752.742 msecs" (x4.19)
true
; Copyright (c) 2011-2013, PI:NAME:<NAME>END_PI, Vrije Universiteit Brussel ; 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 Vrije Universiteit Brussel 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 VRIJE UNIVERSITEIT BRUSSEL 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. ;; MC-STM: meta-circular STM in Clojure ;; Multicore Programming ;; (c) 2011-2013, PI:NAME:<NAME>END_PI ;; simple usage examples of MC-STM (ns test.examples ;(:use clojure.contrib.test-is) (:use clojure.test) (:import (java.util.concurrent Executors))) ; (use 'stm.v0-native) ; (use 'stm.v1-simple) ; (use 'stm.v2-mvcc) ; (use 'stm.v3-mvcc-commute) ; (use 'stm.v4-mvcc-fine-grained) (use 'stm.v5-mvcc-fine-grained-barging) ;; === Bank account transfer === (defn transfer [amount from to] (mc-dosync (mc-alter from - amount) (mc-alter to + amount))) (deftest transfer-test [] (def accountA (mc-ref 1500)) (def accountB (mc-ref 200)) (is (= 1500 (mc-deref accountA))) (is (= 200 (mc-deref accountB))) (transfer 100 accountA accountB) (is (= 1400 (mc-deref accountA))) (is (= 300 (mc-deref accountB)))) ;; === Contention === ; From clojure.org/concurrent_programming by PI:NAME:<NAME>END_PI: ; In this example a vector of Refs containing integers is created (refs), ; then a set of threads are set up (pool) to run a number of iterations of ; incrementing every Ref (tasks). This creates extreme contention, ; but yields the correct result. No locks! (defn test-stm [nitems nthreads niters] (let [refs (map mc-ref (replicate nitems 0)) pool (Executors/newFixedThreadPool nthreads) tasks (map (fn [t] (fn [] (dotimes [n niters] (mc-dosync (doseq [r refs] (mc-alter r + 1 t)))))) (range nthreads))] (doseq [future (.invokeAll pool tasks)] (.get future)) (.shutdown pool) (map mc-deref refs))) (deftest contention-test ; 10 threads increment each of 10 refs 10000 times ; each ref should be incremented by 550000 in total = ; (* 10000 (+ 1 2 3 4 5 6 7 8 9 10)) ; -> (550000 550000 550000 550000 550000 550000 550000 550000 550000 550000) (let [res (time (test-stm 10 10 10000))] (is (= (count res) 10)) (is (every? (fn [r] (= r 550000)) res)))) ;; === Vector swap === ; From http://clojure.org/refs by PI:NAME:<NAME>END_PI: ; In this example a vector of references to vectors is created, each containing ; (initially sequential) unique numbers. Then a set of threads are started that ; repeatedly select two random positions in two random vectors and swap them, ; in a transaction. No special effort is made to prevent the inevitable ; conflicts other than the use of transactions. (defn vector-swap [nvecs nitems nthreads niters] (let [vec-refs (vec (map (comp mc-ref vec) (partition nitems (range (* nvecs nitems))))) swap #(let [v1 (rand-int nvecs) v2 (rand-int nvecs) i1 (rand-int nitems) i2 (rand-int nitems)] (mc-dosync (let [temp (nth (mc-deref (vec-refs v1)) i1)] (mc-alter (vec-refs v1) assoc i1 (nth (mc-deref (vec-refs v2)) i2)) (mc-alter (vec-refs v2) assoc i2 temp)))) check-distinct #(do ; (prn (map mc-deref vec-refs)) (is (= (* nvecs nitems) (count (distinct (apply concat (map mc-deref vec-refs)))))))] (check-distinct) (dorun (apply pcalls (repeat nthreads #(dotimes [_ niters] (swap))))) (check-distinct))) (deftest vector-swap-test (time (vector-swap 100 10 10 100000))) (run-tests) (shutdown-agents) ; shutdown thread pool used by pcalls ; ----------------------------------------------------- ; observed behavior on: ; Clojure 1.2.0-RC2 ; JDK 1.6.0 ; Mac OS X 10.6.7 ; Macbook, 2.4 GHz Intel Core 2 Duo, 4 GB 1067 MHz DDR3 ; ----------------------------------------------------- ; contention-test: ; v0-native: "Elapsed time: 2731.11 msecs" ; v1-simple: "Elapsed time: 8105.424 msecs" (x2.96) ; v2-mvcc: "Elapsed time: 10714.035 msecs" (x3.92) ; v3-mvcc-commute: "Elapsed time: 9751.687 msecs" (x3.57) ; v4-mvcc-fine-grained: "Elapsed time: 16174.881 msecs" (x5.92) ; vector-swap: ; v0-native: "Elapsed time: 5180.694 msecs" ; v1-simple: "Elapsed time: 16037.275 msecs" (x3.09) ; v2-mvcc: "Elapsed time: 29760.412 msecs" (x5.74) ; v3-mvcc-commute: "Elapsed time: 31856.438 msecs" (x6.14) ; v4-mvcc-fine-grained: "Elapsed time: 21752.742 msecs" (x4.19)
[ { "context": "ross-language compiler and build tool\"\r\n author \"Tero Tolonen\"\r\n license \"MIT\"\r\n)\r\n\r\nflag nodecli (\r\n name \"r", "end": 237, "score": 0.9998664855957031, "start": 225, "tag": "NAME", "value": "Tero Tolonen" } ]
compiler/ng_Compiler.clj
terotests/Ranger
6
; def opts ([] "name" "version" "description" "author" "license") flag es6 ( version "2.1.71" ) flag npm ( version "2.1.71" name "ranger-lib" description "Cross-language compiler and build tool" author "Tero Tolonen" license "MIT" ) flag nodecli ( name "ranger-compiler" ) plugin.md "plugins.md" { h2 'How to push code from plugins to the Ranger compiler' h3 'generate_ast phase' p 'Before code gets typechecke during the generate_ast phase you can use' code '(source_code:string node:CodeNode wr:CodeWriter )' p 'to push code before it is statically analyzed' } Import "VirtualCompiler.clj" class CompilerInterface { static fn create_env:InputEnv () { def env (new InputEnv) env.use_real = true env.commandLine = (new CmdParams) env.commandLine.collect() return env } static fn main () { def env (CompilerInterface.create_env()) def o (new VirtualCompiler) def res (o.run( env )) if( has res.target_dir) { res.fileSystem.saveTo(res.target_dir false) } } }
101587
; def opts ([] "name" "version" "description" "author" "license") flag es6 ( version "2.1.71" ) flag npm ( version "2.1.71" name "ranger-lib" description "Cross-language compiler and build tool" author "<NAME>" license "MIT" ) flag nodecli ( name "ranger-compiler" ) plugin.md "plugins.md" { h2 'How to push code from plugins to the Ranger compiler' h3 'generate_ast phase' p 'Before code gets typechecke during the generate_ast phase you can use' code '(source_code:string node:CodeNode wr:CodeWriter )' p 'to push code before it is statically analyzed' } Import "VirtualCompiler.clj" class CompilerInterface { static fn create_env:InputEnv () { def env (new InputEnv) env.use_real = true env.commandLine = (new CmdParams) env.commandLine.collect() return env } static fn main () { def env (CompilerInterface.create_env()) def o (new VirtualCompiler) def res (o.run( env )) if( has res.target_dir) { res.fileSystem.saveTo(res.target_dir false) } } }
true
; def opts ([] "name" "version" "description" "author" "license") flag es6 ( version "2.1.71" ) flag npm ( version "2.1.71" name "ranger-lib" description "Cross-language compiler and build tool" author "PI:NAME:<NAME>END_PI" license "MIT" ) flag nodecli ( name "ranger-compiler" ) plugin.md "plugins.md" { h2 'How to push code from plugins to the Ranger compiler' h3 'generate_ast phase' p 'Before code gets typechecke during the generate_ast phase you can use' code '(source_code:string node:CodeNode wr:CodeWriter )' p 'to push code before it is statically analyzed' } Import "VirtualCompiler.clj" class CompilerInterface { static fn create_env:InputEnv () { def env (new InputEnv) env.use_real = true env.commandLine = (new CmdParams) env.commandLine.collect() return env } static fn main () { def env (CompilerInterface.create_env()) def o (new VirtualCompiler) def res (o.run( env )) if( has res.target_dir) { res.fileSystem.saveTo(res.target_dir false) } } }
[ { "context": " assets into the output directory\"\n\n ;; {:email \"z@caudate.me\", :date \"06 October 2016\" ...}\n (load-settings))", "end": 536, "score": 0.9999241828918457, "start": 524, "tag": "EMAIL", "value": "z@caudate.me" } ]
test/lucid/publish_test.clj
willcohen/lucidity
3
(ns lucid.publish-test (:use hara.test) (:require [lucid.publish :refer :all])) ^{:refer lucid.publish/output-path :added "1.2"} (fact "creates a path representing where the output files will go") ^{:refer lucid.publish/copy-assets :added "1.2"} (comment "copies all theme assets into the output directory" ;; copies theme using the `:copy` key into an output directory (copy-assets)) ^{:refer lucid.publish/load-settings :added "1.2"} (comment "copies all theme assets into the output directory" ;; {:email "z@caudate.me", :date "06 October 2016" ...} (load-settings)) ^{:refer lucid.publish/add-lookup :added "1.2"} (fact "adds a namespace to file lookup table if not existing") ^{:refer lucid.publish/publish :added "1.2"} (comment "publishes a document as an html" ;; publishes the `index` entry in `project.clj` (publish "index") ;; publishes `index` in a specific project with additional options (publish "index" {:refresh true :theme "bolton"} (project/project <PATH>))) ^{:refer lucid.publish/publish-all :added "1.2"} (comment "publishes all documents as html" ;; publishes all the entries in `:publish :files` (publish-all) ;; publishes all entries in a specific project (publish-all {:refresh true :theme "bolton"} (project/project <PATH>))) ^{:refer lucid.publish/unwatch :added "1.2"} (comment "removes the automatic publishing of documentation files" (unwatch)) ^{:refer lucid.publish/watch :added "1.2"} (comment "automatic publishing of documentation files" (watch)) (comment (publish "lucid-unit") (watch) )
61315
(ns lucid.publish-test (:use hara.test) (:require [lucid.publish :refer :all])) ^{:refer lucid.publish/output-path :added "1.2"} (fact "creates a path representing where the output files will go") ^{:refer lucid.publish/copy-assets :added "1.2"} (comment "copies all theme assets into the output directory" ;; copies theme using the `:copy` key into an output directory (copy-assets)) ^{:refer lucid.publish/load-settings :added "1.2"} (comment "copies all theme assets into the output directory" ;; {:email "<EMAIL>", :date "06 October 2016" ...} (load-settings)) ^{:refer lucid.publish/add-lookup :added "1.2"} (fact "adds a namespace to file lookup table if not existing") ^{:refer lucid.publish/publish :added "1.2"} (comment "publishes a document as an html" ;; publishes the `index` entry in `project.clj` (publish "index") ;; publishes `index` in a specific project with additional options (publish "index" {:refresh true :theme "bolton"} (project/project <PATH>))) ^{:refer lucid.publish/publish-all :added "1.2"} (comment "publishes all documents as html" ;; publishes all the entries in `:publish :files` (publish-all) ;; publishes all entries in a specific project (publish-all {:refresh true :theme "bolton"} (project/project <PATH>))) ^{:refer lucid.publish/unwatch :added "1.2"} (comment "removes the automatic publishing of documentation files" (unwatch)) ^{:refer lucid.publish/watch :added "1.2"} (comment "automatic publishing of documentation files" (watch)) (comment (publish "lucid-unit") (watch) )
true
(ns lucid.publish-test (:use hara.test) (:require [lucid.publish :refer :all])) ^{:refer lucid.publish/output-path :added "1.2"} (fact "creates a path representing where the output files will go") ^{:refer lucid.publish/copy-assets :added "1.2"} (comment "copies all theme assets into the output directory" ;; copies theme using the `:copy` key into an output directory (copy-assets)) ^{:refer lucid.publish/load-settings :added "1.2"} (comment "copies all theme assets into the output directory" ;; {:email "PI:EMAIL:<EMAIL>END_PI", :date "06 October 2016" ...} (load-settings)) ^{:refer lucid.publish/add-lookup :added "1.2"} (fact "adds a namespace to file lookup table if not existing") ^{:refer lucid.publish/publish :added "1.2"} (comment "publishes a document as an html" ;; publishes the `index` entry in `project.clj` (publish "index") ;; publishes `index` in a specific project with additional options (publish "index" {:refresh true :theme "bolton"} (project/project <PATH>))) ^{:refer lucid.publish/publish-all :added "1.2"} (comment "publishes all documents as html" ;; publishes all the entries in `:publish :files` (publish-all) ;; publishes all entries in a specific project (publish-all {:refresh true :theme "bolton"} (project/project <PATH>))) ^{:refer lucid.publish/unwatch :added "1.2"} (comment "removes the automatic publishing of documentation files" (unwatch)) ^{:refer lucid.publish/watch :added "1.2"} (comment "automatic publishing of documentation files" (watch)) (comment (publish "lucid-unit") (watch) )
[ { "context": "jective8.middleware :as m]))\n\n(def email-address \"test@email.address.com\")\n(def auth-provider-user-id \"twitter-TWITTER_ID\"", "end": 596, "score": 0.9999202489852905, "start": 574, "tag": "EMAIL", "value": "test@email.address.com" }, { "context": "ider-user-id \"twitter-TWITTER_ID\")\n(def username \"testname1\")\n\n(def app (helpers/api-context))\n\n(def USER_ID ", "end": 672, "score": 0.9996194839477539, "start": 663, "tag": "USERNAME", "value": "testname1" }, { "context": " username\"\n (let [{username :username :as the-user} (sh/store-a-user)\n ", "end": 4252, "score": 0.7085733413696289, "start": 4244, "tag": "USERNAME", "value": "username" }, { "context": " (let [{username :username :as the-user} (sh/store-a-user)\n pe", "end": 4265, "score": 0.9975116848945618, "start": 4257, "tag": "USERNAME", "value": "the-user" } ]
test/objective8/integration/back_end/users.clj
d-cent/objective8
23
(ns objective8.integration.back-end.users (:require [midje.sweet :refer :all] [peridot.core :as p] [oauth.client :as oauth] [cheshire.core :as json] [objective8.core :as core] [objective8.utils :as utils] [objective8.back-end.storage.storage :as s] [objective8.back-end.domain.users :as users] [objective8.integration.integration-helpers :as helpers] [objective8.integration.storage-helpers :as sh] [objective8.middleware :as m])) (def email-address "test@email.address.com") (def auth-provider-user-id "twitter-TWITTER_ID") (def username "testname1") (def app (helpers/api-context)) (def USER_ID 10) (def user {:auth-provider-user-id auth-provider-user-id :email-address email-address :username username }) (def stored-user (assoc user :_id USER_ID)) (facts "GET /api/v1/users/:id" (against-background (m/valid-credentials? anything anything anything) => true) (against-background [(before :contents (do (helpers/db-connection) (helpers/truncate-tables))) (after :facts (helpers/truncate-tables))] (fact "retrieves the user record and associated writer records and owned objectives records by user id" (let [{user-id :_id :as the-user} (sh/store-a-user) {owned-objective-id :_id} (sh/store-an-objective {:user the-user}) writer-record-1 (sh/store-a-writer {:user the-user}) writer-record-2 (sh/store-a-writer {:user the-user}) {response :response} (p/request app (utils/api-path-for :api/get-user :id user-id))] (:body response) => (helpers/json-contains {:writer-records (contains [(contains writer-record-1) (contains writer-record-2)])}) (:body response) => (helpers/json-contains {:owned-objectives (contains [(contains {:_id owned-objective-id})])}) (:body response) => (helpers/json-contains {:admin false}))) (fact "returns a 404 if the user does not exist" (-> (p/request app (utils/api-path-for :api/get-user :id 123456)) (get-in [:response :status])) => 404)) (fact "retrieves user record with admin role for admin user" (let [{user-id :_id auth-provider-user-id :auth-provider-user-id :as the-user} (sh/store-a-user) _ (users/store-admin! {:auth-provider-user-id auth-provider-user-id}) {response :response} (p/request app (utils/api-path-for :api/get-user :id user-id))] (:body response) => (helpers/json-contains {:admin true})))) (facts "users" (facts "about querying for users" (against-background (m/valid-credentials? anything anything anything) => true) (against-background [(before :contents (do (helpers/db-connection) (helpers/truncate-tables))) (after :facts (helpers/truncate-tables))] (fact "a user can be retrieved by auth-provider-user-id" (let [{auth-provider-user-id :auth-provider-user-id :as the-user} (sh/store-a-user) peridot-response (p/request app (str (utils/api-path-for :api/get-user-by-query) "?auth_provider_user_id=" auth-provider-user-id)) body (get-in peridot-response [:response :body])] body => (helpers/json-contains the-user))) (fact "returns a 404 if the user does not exist" (let [user-request (p/request app (str (utils/api-path-for :api/get-user-by-query) "?auth_provider_user_id=twitter-IDONTEXIST"))] (-> user-request :response :status)) => 404) (fact "a user can be retrieved by username" (let [{username :username :as the-user} (sh/store-a-user) peridot-response (p/request app (str (utils/api-path-for :api/get-user-by-query) "?username=" username)) body (get-in peridot-response [:response :body])] body => (helpers/json-contains the-user))))) (facts "about posting users" (against-background (m/valid-credentials? anything anything anything) => true) (fact "the posted user is stored" (let [peridot-response (p/request app (utils/api-path-for :api/post-user-profile) :request-method :post :content-type "application/json" :body (json/generate-string user))] peridot-response) => (helpers/check-json-body stored-user) (provided (users/store-user! user) => stored-user)) (fact "the http response indicates the location of the user" (against-background (users/store-user! anything) => stored-user) (let [result (p/request app (utils/api-path-for :api/post-user-profile) :request-method :post :content-type "application/json" :body (json/generate-string user)) response (:response result) headers (:headers response)] response => (contains {:status 201}) headers => (contains {"Location" (contains (str "/api/v1/users/" USER_ID))}))) (fact "a 400 status is returned if a PSQLException is raised" (against-background (users/store-user! anything) =throws=> (org.postgresql.util.PSQLException. (org.postgresql.util.ServerErrorMessage. "" 0))) (:response (p/request app (utils/api-path-for :api/post-user-profile) :request-method :post :content-type "application/json" :body (json/generate-string user))) => (contains {:status 400}))) (facts "about posting writer profiles" (against-background (m/valid-credentials? anything anything anything) => true) (fact "the writer profile info is updated in a user" (let [{user-id :_id :as user} (sh/store-a-user) {response :response} (p/request app (utils/api-path-for :api/put-writer-profile) :request-method :put :content-type "application/json" :body (json/generate-string {:name "name" :biog "biography" :user-uri (str "/users/" user-id)}))] (:status response) => 200 (:headers response) => (helpers/location-contains (str "/api/v1/users/" user-id)) (:body response) => (helpers/json-contains {:profile {:name "name" :biog "biography"}}))) (fact "returns a 404 if the user does not exist" (let [invalid-user-id 2323 {response :response} (p/request app (utils/api-path-for :api/put-writer-profile) :request-method :put :content-type "application/json" :body (json/generate-string {:name "name" :biog "biography" :user-uri (str "/users/" invalid-user-id)}))] (:status response) => 404)) (fact "returns a 400 when posting invalid profile data" (let [profile-data-without-biog {:name "name" :user-uri (str "/users/" USER_ID)} {response :response} (p/request app (utils/api-path-for :api/put-writer-profile) :request-method :put :content-type "application/json" :body (json/generate-string profile-data-without-biog))] (:status response) => 400))))
116121
(ns objective8.integration.back-end.users (:require [midje.sweet :refer :all] [peridot.core :as p] [oauth.client :as oauth] [cheshire.core :as json] [objective8.core :as core] [objective8.utils :as utils] [objective8.back-end.storage.storage :as s] [objective8.back-end.domain.users :as users] [objective8.integration.integration-helpers :as helpers] [objective8.integration.storage-helpers :as sh] [objective8.middleware :as m])) (def email-address "<EMAIL>") (def auth-provider-user-id "twitter-TWITTER_ID") (def username "testname1") (def app (helpers/api-context)) (def USER_ID 10) (def user {:auth-provider-user-id auth-provider-user-id :email-address email-address :username username }) (def stored-user (assoc user :_id USER_ID)) (facts "GET /api/v1/users/:id" (against-background (m/valid-credentials? anything anything anything) => true) (against-background [(before :contents (do (helpers/db-connection) (helpers/truncate-tables))) (after :facts (helpers/truncate-tables))] (fact "retrieves the user record and associated writer records and owned objectives records by user id" (let [{user-id :_id :as the-user} (sh/store-a-user) {owned-objective-id :_id} (sh/store-an-objective {:user the-user}) writer-record-1 (sh/store-a-writer {:user the-user}) writer-record-2 (sh/store-a-writer {:user the-user}) {response :response} (p/request app (utils/api-path-for :api/get-user :id user-id))] (:body response) => (helpers/json-contains {:writer-records (contains [(contains writer-record-1) (contains writer-record-2)])}) (:body response) => (helpers/json-contains {:owned-objectives (contains [(contains {:_id owned-objective-id})])}) (:body response) => (helpers/json-contains {:admin false}))) (fact "returns a 404 if the user does not exist" (-> (p/request app (utils/api-path-for :api/get-user :id 123456)) (get-in [:response :status])) => 404)) (fact "retrieves user record with admin role for admin user" (let [{user-id :_id auth-provider-user-id :auth-provider-user-id :as the-user} (sh/store-a-user) _ (users/store-admin! {:auth-provider-user-id auth-provider-user-id}) {response :response} (p/request app (utils/api-path-for :api/get-user :id user-id))] (:body response) => (helpers/json-contains {:admin true})))) (facts "users" (facts "about querying for users" (against-background (m/valid-credentials? anything anything anything) => true) (against-background [(before :contents (do (helpers/db-connection) (helpers/truncate-tables))) (after :facts (helpers/truncate-tables))] (fact "a user can be retrieved by auth-provider-user-id" (let [{auth-provider-user-id :auth-provider-user-id :as the-user} (sh/store-a-user) peridot-response (p/request app (str (utils/api-path-for :api/get-user-by-query) "?auth_provider_user_id=" auth-provider-user-id)) body (get-in peridot-response [:response :body])] body => (helpers/json-contains the-user))) (fact "returns a 404 if the user does not exist" (let [user-request (p/request app (str (utils/api-path-for :api/get-user-by-query) "?auth_provider_user_id=twitter-IDONTEXIST"))] (-> user-request :response :status)) => 404) (fact "a user can be retrieved by username" (let [{username :username :as the-user} (sh/store-a-user) peridot-response (p/request app (str (utils/api-path-for :api/get-user-by-query) "?username=" username)) body (get-in peridot-response [:response :body])] body => (helpers/json-contains the-user))))) (facts "about posting users" (against-background (m/valid-credentials? anything anything anything) => true) (fact "the posted user is stored" (let [peridot-response (p/request app (utils/api-path-for :api/post-user-profile) :request-method :post :content-type "application/json" :body (json/generate-string user))] peridot-response) => (helpers/check-json-body stored-user) (provided (users/store-user! user) => stored-user)) (fact "the http response indicates the location of the user" (against-background (users/store-user! anything) => stored-user) (let [result (p/request app (utils/api-path-for :api/post-user-profile) :request-method :post :content-type "application/json" :body (json/generate-string user)) response (:response result) headers (:headers response)] response => (contains {:status 201}) headers => (contains {"Location" (contains (str "/api/v1/users/" USER_ID))}))) (fact "a 400 status is returned if a PSQLException is raised" (against-background (users/store-user! anything) =throws=> (org.postgresql.util.PSQLException. (org.postgresql.util.ServerErrorMessage. "" 0))) (:response (p/request app (utils/api-path-for :api/post-user-profile) :request-method :post :content-type "application/json" :body (json/generate-string user))) => (contains {:status 400}))) (facts "about posting writer profiles" (against-background (m/valid-credentials? anything anything anything) => true) (fact "the writer profile info is updated in a user" (let [{user-id :_id :as user} (sh/store-a-user) {response :response} (p/request app (utils/api-path-for :api/put-writer-profile) :request-method :put :content-type "application/json" :body (json/generate-string {:name "name" :biog "biography" :user-uri (str "/users/" user-id)}))] (:status response) => 200 (:headers response) => (helpers/location-contains (str "/api/v1/users/" user-id)) (:body response) => (helpers/json-contains {:profile {:name "name" :biog "biography"}}))) (fact "returns a 404 if the user does not exist" (let [invalid-user-id 2323 {response :response} (p/request app (utils/api-path-for :api/put-writer-profile) :request-method :put :content-type "application/json" :body (json/generate-string {:name "name" :biog "biography" :user-uri (str "/users/" invalid-user-id)}))] (:status response) => 404)) (fact "returns a 400 when posting invalid profile data" (let [profile-data-without-biog {:name "name" :user-uri (str "/users/" USER_ID)} {response :response} (p/request app (utils/api-path-for :api/put-writer-profile) :request-method :put :content-type "application/json" :body (json/generate-string profile-data-without-biog))] (:status response) => 400))))
true
(ns objective8.integration.back-end.users (:require [midje.sweet :refer :all] [peridot.core :as p] [oauth.client :as oauth] [cheshire.core :as json] [objective8.core :as core] [objective8.utils :as utils] [objective8.back-end.storage.storage :as s] [objective8.back-end.domain.users :as users] [objective8.integration.integration-helpers :as helpers] [objective8.integration.storage-helpers :as sh] [objective8.middleware :as m])) (def email-address "PI:EMAIL:<EMAIL>END_PI") (def auth-provider-user-id "twitter-TWITTER_ID") (def username "testname1") (def app (helpers/api-context)) (def USER_ID 10) (def user {:auth-provider-user-id auth-provider-user-id :email-address email-address :username username }) (def stored-user (assoc user :_id USER_ID)) (facts "GET /api/v1/users/:id" (against-background (m/valid-credentials? anything anything anything) => true) (against-background [(before :contents (do (helpers/db-connection) (helpers/truncate-tables))) (after :facts (helpers/truncate-tables))] (fact "retrieves the user record and associated writer records and owned objectives records by user id" (let [{user-id :_id :as the-user} (sh/store-a-user) {owned-objective-id :_id} (sh/store-an-objective {:user the-user}) writer-record-1 (sh/store-a-writer {:user the-user}) writer-record-2 (sh/store-a-writer {:user the-user}) {response :response} (p/request app (utils/api-path-for :api/get-user :id user-id))] (:body response) => (helpers/json-contains {:writer-records (contains [(contains writer-record-1) (contains writer-record-2)])}) (:body response) => (helpers/json-contains {:owned-objectives (contains [(contains {:_id owned-objective-id})])}) (:body response) => (helpers/json-contains {:admin false}))) (fact "returns a 404 if the user does not exist" (-> (p/request app (utils/api-path-for :api/get-user :id 123456)) (get-in [:response :status])) => 404)) (fact "retrieves user record with admin role for admin user" (let [{user-id :_id auth-provider-user-id :auth-provider-user-id :as the-user} (sh/store-a-user) _ (users/store-admin! {:auth-provider-user-id auth-provider-user-id}) {response :response} (p/request app (utils/api-path-for :api/get-user :id user-id))] (:body response) => (helpers/json-contains {:admin true})))) (facts "users" (facts "about querying for users" (against-background (m/valid-credentials? anything anything anything) => true) (against-background [(before :contents (do (helpers/db-connection) (helpers/truncate-tables))) (after :facts (helpers/truncate-tables))] (fact "a user can be retrieved by auth-provider-user-id" (let [{auth-provider-user-id :auth-provider-user-id :as the-user} (sh/store-a-user) peridot-response (p/request app (str (utils/api-path-for :api/get-user-by-query) "?auth_provider_user_id=" auth-provider-user-id)) body (get-in peridot-response [:response :body])] body => (helpers/json-contains the-user))) (fact "returns a 404 if the user does not exist" (let [user-request (p/request app (str (utils/api-path-for :api/get-user-by-query) "?auth_provider_user_id=twitter-IDONTEXIST"))] (-> user-request :response :status)) => 404) (fact "a user can be retrieved by username" (let [{username :username :as the-user} (sh/store-a-user) peridot-response (p/request app (str (utils/api-path-for :api/get-user-by-query) "?username=" username)) body (get-in peridot-response [:response :body])] body => (helpers/json-contains the-user))))) (facts "about posting users" (against-background (m/valid-credentials? anything anything anything) => true) (fact "the posted user is stored" (let [peridot-response (p/request app (utils/api-path-for :api/post-user-profile) :request-method :post :content-type "application/json" :body (json/generate-string user))] peridot-response) => (helpers/check-json-body stored-user) (provided (users/store-user! user) => stored-user)) (fact "the http response indicates the location of the user" (against-background (users/store-user! anything) => stored-user) (let [result (p/request app (utils/api-path-for :api/post-user-profile) :request-method :post :content-type "application/json" :body (json/generate-string user)) response (:response result) headers (:headers response)] response => (contains {:status 201}) headers => (contains {"Location" (contains (str "/api/v1/users/" USER_ID))}))) (fact "a 400 status is returned if a PSQLException is raised" (against-background (users/store-user! anything) =throws=> (org.postgresql.util.PSQLException. (org.postgresql.util.ServerErrorMessage. "" 0))) (:response (p/request app (utils/api-path-for :api/post-user-profile) :request-method :post :content-type "application/json" :body (json/generate-string user))) => (contains {:status 400}))) (facts "about posting writer profiles" (against-background (m/valid-credentials? anything anything anything) => true) (fact "the writer profile info is updated in a user" (let [{user-id :_id :as user} (sh/store-a-user) {response :response} (p/request app (utils/api-path-for :api/put-writer-profile) :request-method :put :content-type "application/json" :body (json/generate-string {:name "name" :biog "biography" :user-uri (str "/users/" user-id)}))] (:status response) => 200 (:headers response) => (helpers/location-contains (str "/api/v1/users/" user-id)) (:body response) => (helpers/json-contains {:profile {:name "name" :biog "biography"}}))) (fact "returns a 404 if the user does not exist" (let [invalid-user-id 2323 {response :response} (p/request app (utils/api-path-for :api/put-writer-profile) :request-method :put :content-type "application/json" :body (json/generate-string {:name "name" :biog "biography" :user-uri (str "/users/" invalid-user-id)}))] (:status response) => 404)) (fact "returns a 400 when posting invalid profile data" (let [profile-data-without-biog {:name "name" :user-uri (str "/users/" USER_ID)} {response :response} (p/request app (utils/api-path-for :api/put-writer-profile) :request-method :put :content-type "application/json" :body (json/generate-string profile-data-without-biog))] (:status response) => 400))))
[ { "context": "bs.kitchensink.core :as kitchensink]\n [robert.hooke :as rh]\n [puppetlabs.trapperkeeper.cor", "end": 2267, "score": 0.7963509559631348, "start": 2255, "tag": "NAME", "value": "robert.hooke" } ]
src/puppetlabs/puppetdb/cli/services.clj
shrug/puppetdb
0
(ns puppetlabs.puppetdb.cli.services "Main entrypoint PuppetDB consists of several, cooperating components: * Command processing PuppetDB uses a CQRS pattern for making changes to its domain objects (facts, catalogs, etc). Instead of simply submitting data to PuppetDB and having it figure out the intent, the intent needs to explicitly be codified as part of the operation. This is known as a \"command\" (e.g. \"replace the current facts for node X\"). Commands are processed asynchronously, however we try to do our best to ensure that once a command has been accepted, it will eventually be executed. Ordering is also preserved. To do this, all incoming commands are placed in a message queue which the command processing subsystem reads from in FIFO order. Refer to `puppetlabs.puppetdb.command` for more details. * Message queue We use an embedded instance of AciveMQ to handle queueing duties for the command processing subsystem. The message queue is persistent, and it only allows connections from within the same VM. Refer to `puppetlabs.puppetdb.mq` for more details. * REST interface All interaction with PuppetDB is conducted via its REST API. We embed an instance of Jetty to handle web server duties. Commands that come in via REST are relayed to the message queue. Read-only requests are serviced synchronously. * Database sweeper As catalogs are modified, unused records may accumulate and stale data may linger in the database. We periodically sweep the database, compacting it and performing regular cleanup so we can maintain acceptable performance." (:require [puppetlabs.puppetdb.scf.storage :as scf-store] [puppetlabs.puppetdb.command.dlo :as dlo] [puppetlabs.puppetdb.query.population :as pop] [puppetlabs.puppetdb.jdbc :as pl-jdbc] [puppetlabs.puppetdb.mq :as mq] [clojure.java.jdbc :as sql] [clojure.tools.logging :as log] [puppetlabs.puppetdb.http.server :as server] [puppetlabs.puppetdb.config :as conf] [puppetlabs.kitchensink.core :as kitchensink] [robert.hooke :as rh] [puppetlabs.trapperkeeper.core :refer [defservice] :as tk] [puppetlabs.trapperkeeper.services :refer [service-id service-context]] [compojure.core :as compojure] [clojure.java.io :refer [file]] [clj-time.core :refer [ago]] [overtone.at-at :refer [mk-pool interspaced]] [slingshot.slingshot :refer [throw+ try+]] [puppetlabs.puppetdb.time :refer [to-seconds to-millis parse-period format-period period?]] [puppetlabs.puppetdb.jdbc :refer [with-transacted-connection]] [puppetlabs.puppetdb.scf.migrate :refer [migrate! indexes!]] [puppetlabs.puppetdb.meta.version :refer [version update-info]] [puppetlabs.puppetdb.command.constants :refer [command-names]] [puppetlabs.puppetdb.cheshire :as json] [puppetlabs.puppetdb.query-eng :as qeng] [puppetlabs.puppetdb.utils :as utils]) (:import [javax.jms ExceptionListener])) (def cli-description "Main PuppetDB daemon") ;; ## Wiring ;; ;; The following functions setup interaction between the main ;; PuppetDB components. (def mq-addr "vm://localhost?jms.prefetchPolicy.all=1&create=false") (def mq-endpoint "puppetlabs.puppetdb.commands") (defn auto-expire-nodes! "Expire nodes which haven't had any activity (catalog/fact submission) for more than `node-ttl`." [node-ttl db mq-connection] {:pre [(map? db) (period? node-ttl)]} (try (kitchensink/demarcate (format "sweep of stale nodes (threshold: %s)" (format-period node-ttl)) (with-transacted-connection db (doseq [node (scf-store/stale-nodes (ago node-ttl))] (log/infof "Auto-expiring node %s" node) (scf-store/expire-node! node)))) (catch Exception e (log/error e "Error while deactivating stale nodes")))) (defn purge-nodes! "Delete nodes which have been *deactivated or expired* longer than `node-purge-ttl`." [node-purge-ttl db] {:pre [(map? db) (period? node-purge-ttl)]} (try (kitchensink/demarcate (format "purge deactivated and expired nodes (threshold: %s)" (format-period node-purge-ttl)) (with-transacted-connection db (scf-store/purge-deactivated-and-expired-nodes! (ago node-purge-ttl)))) (catch Exception e (log/error e "Error while purging deactivated and expired nodes")))) (defn sweep-reports! "Delete reports which are older than than `report-ttl`." [report-ttl db] {:pre [(map? db) (period? report-ttl)]} (try (kitchensink/demarcate (format "sweep of stale reports (threshold: %s)" (format-period report-ttl)) (with-transacted-connection db (scf-store/delete-reports-older-than! (ago report-ttl)))) (catch Exception e (log/error e "Error while sweeping reports")))) (defn compress-dlo! "Compresses discarded message which are older than `dlo-compression-threshold`." [dlo dlo-compression-threshold] (try (kitchensink/demarcate (format "compression of discarded messages (threshold: %s)" (format-period dlo-compression-threshold)) (dlo/compress! dlo dlo-compression-threshold)) (catch Exception e (log/error e "Error while compressing discarded messages")))) (defn garbage-collect! "Perform garbage collection on `db`, which means deleting any orphaned data. This basically just wraps the corresponding scf.storage function with some logging and other ceremony. Exceptions are logged but otherwise ignored." [db] {:pre [(map? db)]} (try (kitchensink/demarcate "database garbage collection" (scf-store/garbage-collect! db)) (catch Exception e (log/error e "Error during garbage collection")))) (defn check-for-updates "This will fetch the latest version number of PuppetDB and log if the system is out of date." [update-server db] (let [{:keys [version newer link]} (try (update-info update-server db) (catch Throwable e (log/debugf e "Could not retrieve update information (%s)" update-server)))] (when newer (log/info (cond-> (format "Newer version %s is available!" version) link (str " Visit " link " for details.")))))) (defn maybe-check-for-updates "Check for updates if our `product-name` indicates we should, and skip the check otherwise." [product-name update-server db] (if (= product-name "puppetdb") (check-for-updates update-server db) (log/debug "Skipping update check on Puppet Enterprise"))) (defn build-whitelist-authorizer "Build a function that will authorize requests based on the supplied certificate whitelist (see `cn-whitelist->authorizer` for more details). Returns :authorized if the request is allowed, otherwise a string describing the reason not." [whitelist] {:pre [(string? whitelist)] :post [(fn? %)]} (let [allowed? (kitchensink/cn-whitelist->authorizer whitelist)] (fn [{:keys [ssl-client-cn] :as req}] (if (allowed? req) :authorized (do (log/warnf "%s rejected by certificate whitelist %s" ssl-client-cn whitelist) (format (str "The client certificate name (%s) doesn't " "appear in the certificate whitelist. Is your " "master's (or other PuppetDB client's) certname " "listed in PuppetDB's certificate-whitelist file?") ssl-client-cn)))))) (defn shutdown-mq "Explicitly shut down the queue `broker`" [{:keys [broker mq-factory mq-connection]}] (when broker (log/info "Shutting down the messsage queues.") (.close mq-connection) (.close mq-factory) (mq/stop-broker! broker))) (defn stop-puppetdb "Shuts down PuppetDB, releasing resources when possible.  If this is not a normal shutdown, emergency? must be set, which currently just produces a fatal level level log message, instead of info." [context emergency?] (if emergency? (log/error "A fatal error occurred; shutting down all subsystems.") (log/info "Shutdown request received; puppetdb exiting.")) (when-let [updater (context :updater)] (log/info "Shutting down updater thread.") (future-cancel updater)) (shutdown-mq context) (when-let [ds (get-in context [:shared-globals :scf-write-db :datasource])] (.close ds)) (when-let [ds (get-in context [:shared-globals :scf-read-db :datasource])] (.close ds)) context) (defn add-max-framesize "Add a maxFrameSize to broker url for activemq." [max-frame-size url] (format "%s&wireFormat.maxFrameSize=%s&marshal=true" url max-frame-size)) (defn- transfer-old-messages! [connection] (let [[pending exists?] (try+ [(mq/queue-size "localhost" "com.puppetlabs.puppetdb.commands") true] (catch [:type ::mq/queue-not-found] ex [0 false]))] (when (pos? pending) (log/infof "Transferring %d commands from legacy queue" pending) (let [n (mq/transfer-messages! "localhost" "com.puppetlabs.puppetdb.commands" mq-endpoint)] (log/infof "Transferred %d commands from legacy queue" n))) (when exists? (mq/remove-queue! "localhost" "com.puppetlabs.puppetdb.commands") (log/info "Removed legacy queue")))) (defn start-puppetdb [context config service add-ring-handler get-route shutdown-on-error] {:pre [(map? context) (map? config) (ifn? add-ring-handler) (ifn? shutdown-on-error)] :post [(map? %) (every? (partial contains? %) [:broker])]} (let [{:keys [global jetty database read-database puppetdb command-processing]} (conf/process-config! config) {:keys [product-name update-server vardir catalog-hash-debug-dir]} global {:keys [gc-interval node-ttl node-purge-ttl report-ttl]} database {:keys [dlo-compression-threshold max-frame-size threads]} command-processing {:keys [certificate-whitelist disable-update-checking]} puppetdb url-prefix (get-route service) write-db (pl-jdbc/pooled-datasource database) read-db (pl-jdbc/pooled-datasource (assoc read-database :read-only? true)) mq-dir (str (file vardir "mq")) discard-dir (file mq-dir "discarded") mq-connection-str (add-max-framesize max-frame-size mq-addr) authorizer (when certificate-whitelist (build-whitelist-authorizer certificate-whitelist))] (when-let [v (version)] (log/infof "PuppetDB version %s" v)) ;; Ensure the database is migrated to the latest version, and warn ;; if it's deprecated, log and exit if it's unsupported. We do ;; this in a single connection because HSQLDB seems to get ;; confused if the database doesn't exist but we open and close a ;; connection without creating anything. (sql/with-connection write-db (scf-store/validate-database-version #(System/exit 1)) (migrate!) (indexes! product-name)) ;; Initialize database-dependent metrics and dlo metrics if existent. (pop/initialize-metrics write-db) (when (.exists discard-dir) (dlo/create-metrics-for-dlo! discard-dir)) (let [broker (try (log/info "Starting broker") (mq/build-and-start-broker! "localhost" mq-dir command-processing) (catch java.io.EOFException e (log/error "EOF Exception caught during broker start, this " "might be due to KahaDB corruption. Consult the " "PuppetDB troubleshooting guide.") (throw e))) mq-factory (mq/activemq-connection-factory (add-max-framesize max-frame-size mq-addr)) mq-connection (doto (.createConnection mq-factory) (.setExceptionListener (reify ExceptionListener (onException [this ex] (log/error ex "service queue connection error")))) .start) globals {:scf-read-db read-db :scf-write-db write-db :authorizer authorizer :update-server update-server :product-name product-name :url-prefix url-prefix :discard-dir (.getAbsolutePath discard-dir) :mq-addr mq-addr :mq-dest mq-endpoint :mq-threads threads :catalog-hash-debug-dir catalog-hash-debug-dir :command-mq {:connection mq-connection :endpoint mq-endpoint}} updater (when-not disable-update-checking (future (shutdown-on-error (service-id service) #(maybe-check-for-updates product-name update-server read-db) #(stop-puppetdb % true))))] (transfer-old-messages! mq-connection) (let [app (->> (server/build-app globals) (compojure/context url-prefix []))] (log/info "Starting query server") (add-ring-handler service app)) ;; Pretty much this helper just knows our job-pool and gc-interval (let [job-pool (mk-pool) gc-interval-millis (to-millis gc-interval) gc-task #(interspaced gc-interval-millis % job-pool) seconds-pos? (comp pos? to-seconds) db-maintenance-tasks (fn [] (do (when (seconds-pos? node-ttl) (auto-expire-nodes! node-ttl write-db mq-connection)) (when (seconds-pos? node-purge-ttl) (purge-nodes! node-purge-ttl write-db)) (when (seconds-pos? report-ttl) (sweep-reports! report-ttl write-db)) ;; Order is important here to ensure ;; anything referencing an env or resource ;; param is purged first (garbage-collect! write-db)))] ;; Run database maintenance tasks seqentially to avoid ;; competition. Each task must handle its own errors. (gc-task db-maintenance-tasks) (gc-task #(compress-dlo! dlo-compression-threshold discard-dir))) (-> context (assoc :broker broker :mq-factory mq-factory :mq-connection mq-connection :shared-globals globals) (merge (when updater {:updater updater})))))) (defprotocol PuppetDBServer (shared-globals [this]) (query [this query-obj version query-expr paging-options row-callback-fn] "Call `row-callback-fn' for matching rows. The `paging-options' should be a map containing :order_by, :offset, and/or :limit.")) (defservice puppetdb-service "Defines a trapperkeeper service for PuppetDB; this service is responsible for initializing all of the PuppetDB subsystems and registering shutdown hooks that trapperkeeper will call on exit." PuppetDBServer [[:ConfigService get-config] [:WebroutingService add-ring-handler get-route] [:ShutdownService shutdown-on-error]] (start [this context] (start-puppetdb context (get-config) this add-ring-handler get-route shutdown-on-error)) (stop [this context] (stop-puppetdb context false)) (shared-globals [this] (:shared-globals (service-context this))) (query [this query-obj version query-expr paging-options row-callback-fn] (let [{db :scf-read-db url-prefix :url-prefix} (get (service-context this) :shared-globals)] (qeng/stream-query-result query-obj version query-expr paging-options db url-prefix row-callback-fn)))) (def ^{:arglists `([& args]) :doc "Starts PuppetDB as a service via Trapperkeeper. Aguments TK's normal config parsing to do a bit of extra customization."} -main (utils/wrap-main (fn [& args] (rh/add-hook #'puppetlabs.trapperkeeper.config/parse-config-data #'conf/hook-tk-parse-config-data) (try+ (apply tk/main args) (catch [:type ::conf/configuration-error] obj (log/error (:message obj)) (throw+ (assoc obj ::utils/exit-status 1)))))))
95535
(ns puppetlabs.puppetdb.cli.services "Main entrypoint PuppetDB consists of several, cooperating components: * Command processing PuppetDB uses a CQRS pattern for making changes to its domain objects (facts, catalogs, etc). Instead of simply submitting data to PuppetDB and having it figure out the intent, the intent needs to explicitly be codified as part of the operation. This is known as a \"command\" (e.g. \"replace the current facts for node X\"). Commands are processed asynchronously, however we try to do our best to ensure that once a command has been accepted, it will eventually be executed. Ordering is also preserved. To do this, all incoming commands are placed in a message queue which the command processing subsystem reads from in FIFO order. Refer to `puppetlabs.puppetdb.command` for more details. * Message queue We use an embedded instance of AciveMQ to handle queueing duties for the command processing subsystem. The message queue is persistent, and it only allows connections from within the same VM. Refer to `puppetlabs.puppetdb.mq` for more details. * REST interface All interaction with PuppetDB is conducted via its REST API. We embed an instance of Jetty to handle web server duties. Commands that come in via REST are relayed to the message queue. Read-only requests are serviced synchronously. * Database sweeper As catalogs are modified, unused records may accumulate and stale data may linger in the database. We periodically sweep the database, compacting it and performing regular cleanup so we can maintain acceptable performance." (:require [puppetlabs.puppetdb.scf.storage :as scf-store] [puppetlabs.puppetdb.command.dlo :as dlo] [puppetlabs.puppetdb.query.population :as pop] [puppetlabs.puppetdb.jdbc :as pl-jdbc] [puppetlabs.puppetdb.mq :as mq] [clojure.java.jdbc :as sql] [clojure.tools.logging :as log] [puppetlabs.puppetdb.http.server :as server] [puppetlabs.puppetdb.config :as conf] [puppetlabs.kitchensink.core :as kitchensink] [<NAME> :as rh] [puppetlabs.trapperkeeper.core :refer [defservice] :as tk] [puppetlabs.trapperkeeper.services :refer [service-id service-context]] [compojure.core :as compojure] [clojure.java.io :refer [file]] [clj-time.core :refer [ago]] [overtone.at-at :refer [mk-pool interspaced]] [slingshot.slingshot :refer [throw+ try+]] [puppetlabs.puppetdb.time :refer [to-seconds to-millis parse-period format-period period?]] [puppetlabs.puppetdb.jdbc :refer [with-transacted-connection]] [puppetlabs.puppetdb.scf.migrate :refer [migrate! indexes!]] [puppetlabs.puppetdb.meta.version :refer [version update-info]] [puppetlabs.puppetdb.command.constants :refer [command-names]] [puppetlabs.puppetdb.cheshire :as json] [puppetlabs.puppetdb.query-eng :as qeng] [puppetlabs.puppetdb.utils :as utils]) (:import [javax.jms ExceptionListener])) (def cli-description "Main PuppetDB daemon") ;; ## Wiring ;; ;; The following functions setup interaction between the main ;; PuppetDB components. (def mq-addr "vm://localhost?jms.prefetchPolicy.all=1&create=false") (def mq-endpoint "puppetlabs.puppetdb.commands") (defn auto-expire-nodes! "Expire nodes which haven't had any activity (catalog/fact submission) for more than `node-ttl`." [node-ttl db mq-connection] {:pre [(map? db) (period? node-ttl)]} (try (kitchensink/demarcate (format "sweep of stale nodes (threshold: %s)" (format-period node-ttl)) (with-transacted-connection db (doseq [node (scf-store/stale-nodes (ago node-ttl))] (log/infof "Auto-expiring node %s" node) (scf-store/expire-node! node)))) (catch Exception e (log/error e "Error while deactivating stale nodes")))) (defn purge-nodes! "Delete nodes which have been *deactivated or expired* longer than `node-purge-ttl`." [node-purge-ttl db] {:pre [(map? db) (period? node-purge-ttl)]} (try (kitchensink/demarcate (format "purge deactivated and expired nodes (threshold: %s)" (format-period node-purge-ttl)) (with-transacted-connection db (scf-store/purge-deactivated-and-expired-nodes! (ago node-purge-ttl)))) (catch Exception e (log/error e "Error while purging deactivated and expired nodes")))) (defn sweep-reports! "Delete reports which are older than than `report-ttl`." [report-ttl db] {:pre [(map? db) (period? report-ttl)]} (try (kitchensink/demarcate (format "sweep of stale reports (threshold: %s)" (format-period report-ttl)) (with-transacted-connection db (scf-store/delete-reports-older-than! (ago report-ttl)))) (catch Exception e (log/error e "Error while sweeping reports")))) (defn compress-dlo! "Compresses discarded message which are older than `dlo-compression-threshold`." [dlo dlo-compression-threshold] (try (kitchensink/demarcate (format "compression of discarded messages (threshold: %s)" (format-period dlo-compression-threshold)) (dlo/compress! dlo dlo-compression-threshold)) (catch Exception e (log/error e "Error while compressing discarded messages")))) (defn garbage-collect! "Perform garbage collection on `db`, which means deleting any orphaned data. This basically just wraps the corresponding scf.storage function with some logging and other ceremony. Exceptions are logged but otherwise ignored." [db] {:pre [(map? db)]} (try (kitchensink/demarcate "database garbage collection" (scf-store/garbage-collect! db)) (catch Exception e (log/error e "Error during garbage collection")))) (defn check-for-updates "This will fetch the latest version number of PuppetDB and log if the system is out of date." [update-server db] (let [{:keys [version newer link]} (try (update-info update-server db) (catch Throwable e (log/debugf e "Could not retrieve update information (%s)" update-server)))] (when newer (log/info (cond-> (format "Newer version %s is available!" version) link (str " Visit " link " for details.")))))) (defn maybe-check-for-updates "Check for updates if our `product-name` indicates we should, and skip the check otherwise." [product-name update-server db] (if (= product-name "puppetdb") (check-for-updates update-server db) (log/debug "Skipping update check on Puppet Enterprise"))) (defn build-whitelist-authorizer "Build a function that will authorize requests based on the supplied certificate whitelist (see `cn-whitelist->authorizer` for more details). Returns :authorized if the request is allowed, otherwise a string describing the reason not." [whitelist] {:pre [(string? whitelist)] :post [(fn? %)]} (let [allowed? (kitchensink/cn-whitelist->authorizer whitelist)] (fn [{:keys [ssl-client-cn] :as req}] (if (allowed? req) :authorized (do (log/warnf "%s rejected by certificate whitelist %s" ssl-client-cn whitelist) (format (str "The client certificate name (%s) doesn't " "appear in the certificate whitelist. Is your " "master's (or other PuppetDB client's) certname " "listed in PuppetDB's certificate-whitelist file?") ssl-client-cn)))))) (defn shutdown-mq "Explicitly shut down the queue `broker`" [{:keys [broker mq-factory mq-connection]}] (when broker (log/info "Shutting down the messsage queues.") (.close mq-connection) (.close mq-factory) (mq/stop-broker! broker))) (defn stop-puppetdb "Shuts down PuppetDB, releasing resources when possible.  If this is not a normal shutdown, emergency? must be set, which currently just produces a fatal level level log message, instead of info." [context emergency?] (if emergency? (log/error "A fatal error occurred; shutting down all subsystems.") (log/info "Shutdown request received; puppetdb exiting.")) (when-let [updater (context :updater)] (log/info "Shutting down updater thread.") (future-cancel updater)) (shutdown-mq context) (when-let [ds (get-in context [:shared-globals :scf-write-db :datasource])] (.close ds)) (when-let [ds (get-in context [:shared-globals :scf-read-db :datasource])] (.close ds)) context) (defn add-max-framesize "Add a maxFrameSize to broker url for activemq." [max-frame-size url] (format "%s&wireFormat.maxFrameSize=%s&marshal=true" url max-frame-size)) (defn- transfer-old-messages! [connection] (let [[pending exists?] (try+ [(mq/queue-size "localhost" "com.puppetlabs.puppetdb.commands") true] (catch [:type ::mq/queue-not-found] ex [0 false]))] (when (pos? pending) (log/infof "Transferring %d commands from legacy queue" pending) (let [n (mq/transfer-messages! "localhost" "com.puppetlabs.puppetdb.commands" mq-endpoint)] (log/infof "Transferred %d commands from legacy queue" n))) (when exists? (mq/remove-queue! "localhost" "com.puppetlabs.puppetdb.commands") (log/info "Removed legacy queue")))) (defn start-puppetdb [context config service add-ring-handler get-route shutdown-on-error] {:pre [(map? context) (map? config) (ifn? add-ring-handler) (ifn? shutdown-on-error)] :post [(map? %) (every? (partial contains? %) [:broker])]} (let [{:keys [global jetty database read-database puppetdb command-processing]} (conf/process-config! config) {:keys [product-name update-server vardir catalog-hash-debug-dir]} global {:keys [gc-interval node-ttl node-purge-ttl report-ttl]} database {:keys [dlo-compression-threshold max-frame-size threads]} command-processing {:keys [certificate-whitelist disable-update-checking]} puppetdb url-prefix (get-route service) write-db (pl-jdbc/pooled-datasource database) read-db (pl-jdbc/pooled-datasource (assoc read-database :read-only? true)) mq-dir (str (file vardir "mq")) discard-dir (file mq-dir "discarded") mq-connection-str (add-max-framesize max-frame-size mq-addr) authorizer (when certificate-whitelist (build-whitelist-authorizer certificate-whitelist))] (when-let [v (version)] (log/infof "PuppetDB version %s" v)) ;; Ensure the database is migrated to the latest version, and warn ;; if it's deprecated, log and exit if it's unsupported. We do ;; this in a single connection because HSQLDB seems to get ;; confused if the database doesn't exist but we open and close a ;; connection without creating anything. (sql/with-connection write-db (scf-store/validate-database-version #(System/exit 1)) (migrate!) (indexes! product-name)) ;; Initialize database-dependent metrics and dlo metrics if existent. (pop/initialize-metrics write-db) (when (.exists discard-dir) (dlo/create-metrics-for-dlo! discard-dir)) (let [broker (try (log/info "Starting broker") (mq/build-and-start-broker! "localhost" mq-dir command-processing) (catch java.io.EOFException e (log/error "EOF Exception caught during broker start, this " "might be due to KahaDB corruption. Consult the " "PuppetDB troubleshooting guide.") (throw e))) mq-factory (mq/activemq-connection-factory (add-max-framesize max-frame-size mq-addr)) mq-connection (doto (.createConnection mq-factory) (.setExceptionListener (reify ExceptionListener (onException [this ex] (log/error ex "service queue connection error")))) .start) globals {:scf-read-db read-db :scf-write-db write-db :authorizer authorizer :update-server update-server :product-name product-name :url-prefix url-prefix :discard-dir (.getAbsolutePath discard-dir) :mq-addr mq-addr :mq-dest mq-endpoint :mq-threads threads :catalog-hash-debug-dir catalog-hash-debug-dir :command-mq {:connection mq-connection :endpoint mq-endpoint}} updater (when-not disable-update-checking (future (shutdown-on-error (service-id service) #(maybe-check-for-updates product-name update-server read-db) #(stop-puppetdb % true))))] (transfer-old-messages! mq-connection) (let [app (->> (server/build-app globals) (compojure/context url-prefix []))] (log/info "Starting query server") (add-ring-handler service app)) ;; Pretty much this helper just knows our job-pool and gc-interval (let [job-pool (mk-pool) gc-interval-millis (to-millis gc-interval) gc-task #(interspaced gc-interval-millis % job-pool) seconds-pos? (comp pos? to-seconds) db-maintenance-tasks (fn [] (do (when (seconds-pos? node-ttl) (auto-expire-nodes! node-ttl write-db mq-connection)) (when (seconds-pos? node-purge-ttl) (purge-nodes! node-purge-ttl write-db)) (when (seconds-pos? report-ttl) (sweep-reports! report-ttl write-db)) ;; Order is important here to ensure ;; anything referencing an env or resource ;; param is purged first (garbage-collect! write-db)))] ;; Run database maintenance tasks seqentially to avoid ;; competition. Each task must handle its own errors. (gc-task db-maintenance-tasks) (gc-task #(compress-dlo! dlo-compression-threshold discard-dir))) (-> context (assoc :broker broker :mq-factory mq-factory :mq-connection mq-connection :shared-globals globals) (merge (when updater {:updater updater})))))) (defprotocol PuppetDBServer (shared-globals [this]) (query [this query-obj version query-expr paging-options row-callback-fn] "Call `row-callback-fn' for matching rows. The `paging-options' should be a map containing :order_by, :offset, and/or :limit.")) (defservice puppetdb-service "Defines a trapperkeeper service for PuppetDB; this service is responsible for initializing all of the PuppetDB subsystems and registering shutdown hooks that trapperkeeper will call on exit." PuppetDBServer [[:ConfigService get-config] [:WebroutingService add-ring-handler get-route] [:ShutdownService shutdown-on-error]] (start [this context] (start-puppetdb context (get-config) this add-ring-handler get-route shutdown-on-error)) (stop [this context] (stop-puppetdb context false)) (shared-globals [this] (:shared-globals (service-context this))) (query [this query-obj version query-expr paging-options row-callback-fn] (let [{db :scf-read-db url-prefix :url-prefix} (get (service-context this) :shared-globals)] (qeng/stream-query-result query-obj version query-expr paging-options db url-prefix row-callback-fn)))) (def ^{:arglists `([& args]) :doc "Starts PuppetDB as a service via Trapperkeeper. Aguments TK's normal config parsing to do a bit of extra customization."} -main (utils/wrap-main (fn [& args] (rh/add-hook #'puppetlabs.trapperkeeper.config/parse-config-data #'conf/hook-tk-parse-config-data) (try+ (apply tk/main args) (catch [:type ::conf/configuration-error] obj (log/error (:message obj)) (throw+ (assoc obj ::utils/exit-status 1)))))))
true
(ns puppetlabs.puppetdb.cli.services "Main entrypoint PuppetDB consists of several, cooperating components: * Command processing PuppetDB uses a CQRS pattern for making changes to its domain objects (facts, catalogs, etc). Instead of simply submitting data to PuppetDB and having it figure out the intent, the intent needs to explicitly be codified as part of the operation. This is known as a \"command\" (e.g. \"replace the current facts for node X\"). Commands are processed asynchronously, however we try to do our best to ensure that once a command has been accepted, it will eventually be executed. Ordering is also preserved. To do this, all incoming commands are placed in a message queue which the command processing subsystem reads from in FIFO order. Refer to `puppetlabs.puppetdb.command` for more details. * Message queue We use an embedded instance of AciveMQ to handle queueing duties for the command processing subsystem. The message queue is persistent, and it only allows connections from within the same VM. Refer to `puppetlabs.puppetdb.mq` for more details. * REST interface All interaction with PuppetDB is conducted via its REST API. We embed an instance of Jetty to handle web server duties. Commands that come in via REST are relayed to the message queue. Read-only requests are serviced synchronously. * Database sweeper As catalogs are modified, unused records may accumulate and stale data may linger in the database. We periodically sweep the database, compacting it and performing regular cleanup so we can maintain acceptable performance." (:require [puppetlabs.puppetdb.scf.storage :as scf-store] [puppetlabs.puppetdb.command.dlo :as dlo] [puppetlabs.puppetdb.query.population :as pop] [puppetlabs.puppetdb.jdbc :as pl-jdbc] [puppetlabs.puppetdb.mq :as mq] [clojure.java.jdbc :as sql] [clojure.tools.logging :as log] [puppetlabs.puppetdb.http.server :as server] [puppetlabs.puppetdb.config :as conf] [puppetlabs.kitchensink.core :as kitchensink] [PI:NAME:<NAME>END_PI :as rh] [puppetlabs.trapperkeeper.core :refer [defservice] :as tk] [puppetlabs.trapperkeeper.services :refer [service-id service-context]] [compojure.core :as compojure] [clojure.java.io :refer [file]] [clj-time.core :refer [ago]] [overtone.at-at :refer [mk-pool interspaced]] [slingshot.slingshot :refer [throw+ try+]] [puppetlabs.puppetdb.time :refer [to-seconds to-millis parse-period format-period period?]] [puppetlabs.puppetdb.jdbc :refer [with-transacted-connection]] [puppetlabs.puppetdb.scf.migrate :refer [migrate! indexes!]] [puppetlabs.puppetdb.meta.version :refer [version update-info]] [puppetlabs.puppetdb.command.constants :refer [command-names]] [puppetlabs.puppetdb.cheshire :as json] [puppetlabs.puppetdb.query-eng :as qeng] [puppetlabs.puppetdb.utils :as utils]) (:import [javax.jms ExceptionListener])) (def cli-description "Main PuppetDB daemon") ;; ## Wiring ;; ;; The following functions setup interaction between the main ;; PuppetDB components. (def mq-addr "vm://localhost?jms.prefetchPolicy.all=1&create=false") (def mq-endpoint "puppetlabs.puppetdb.commands") (defn auto-expire-nodes! "Expire nodes which haven't had any activity (catalog/fact submission) for more than `node-ttl`." [node-ttl db mq-connection] {:pre [(map? db) (period? node-ttl)]} (try (kitchensink/demarcate (format "sweep of stale nodes (threshold: %s)" (format-period node-ttl)) (with-transacted-connection db (doseq [node (scf-store/stale-nodes (ago node-ttl))] (log/infof "Auto-expiring node %s" node) (scf-store/expire-node! node)))) (catch Exception e (log/error e "Error while deactivating stale nodes")))) (defn purge-nodes! "Delete nodes which have been *deactivated or expired* longer than `node-purge-ttl`." [node-purge-ttl db] {:pre [(map? db) (period? node-purge-ttl)]} (try (kitchensink/demarcate (format "purge deactivated and expired nodes (threshold: %s)" (format-period node-purge-ttl)) (with-transacted-connection db (scf-store/purge-deactivated-and-expired-nodes! (ago node-purge-ttl)))) (catch Exception e (log/error e "Error while purging deactivated and expired nodes")))) (defn sweep-reports! "Delete reports which are older than than `report-ttl`." [report-ttl db] {:pre [(map? db) (period? report-ttl)]} (try (kitchensink/demarcate (format "sweep of stale reports (threshold: %s)" (format-period report-ttl)) (with-transacted-connection db (scf-store/delete-reports-older-than! (ago report-ttl)))) (catch Exception e (log/error e "Error while sweeping reports")))) (defn compress-dlo! "Compresses discarded message which are older than `dlo-compression-threshold`." [dlo dlo-compression-threshold] (try (kitchensink/demarcate (format "compression of discarded messages (threshold: %s)" (format-period dlo-compression-threshold)) (dlo/compress! dlo dlo-compression-threshold)) (catch Exception e (log/error e "Error while compressing discarded messages")))) (defn garbage-collect! "Perform garbage collection on `db`, which means deleting any orphaned data. This basically just wraps the corresponding scf.storage function with some logging and other ceremony. Exceptions are logged but otherwise ignored." [db] {:pre [(map? db)]} (try (kitchensink/demarcate "database garbage collection" (scf-store/garbage-collect! db)) (catch Exception e (log/error e "Error during garbage collection")))) (defn check-for-updates "This will fetch the latest version number of PuppetDB and log if the system is out of date." [update-server db] (let [{:keys [version newer link]} (try (update-info update-server db) (catch Throwable e (log/debugf e "Could not retrieve update information (%s)" update-server)))] (when newer (log/info (cond-> (format "Newer version %s is available!" version) link (str " Visit " link " for details.")))))) (defn maybe-check-for-updates "Check for updates if our `product-name` indicates we should, and skip the check otherwise." [product-name update-server db] (if (= product-name "puppetdb") (check-for-updates update-server db) (log/debug "Skipping update check on Puppet Enterprise"))) (defn build-whitelist-authorizer "Build a function that will authorize requests based on the supplied certificate whitelist (see `cn-whitelist->authorizer` for more details). Returns :authorized if the request is allowed, otherwise a string describing the reason not." [whitelist] {:pre [(string? whitelist)] :post [(fn? %)]} (let [allowed? (kitchensink/cn-whitelist->authorizer whitelist)] (fn [{:keys [ssl-client-cn] :as req}] (if (allowed? req) :authorized (do (log/warnf "%s rejected by certificate whitelist %s" ssl-client-cn whitelist) (format (str "The client certificate name (%s) doesn't " "appear in the certificate whitelist. Is your " "master's (or other PuppetDB client's) certname " "listed in PuppetDB's certificate-whitelist file?") ssl-client-cn)))))) (defn shutdown-mq "Explicitly shut down the queue `broker`" [{:keys [broker mq-factory mq-connection]}] (when broker (log/info "Shutting down the messsage queues.") (.close mq-connection) (.close mq-factory) (mq/stop-broker! broker))) (defn stop-puppetdb "Shuts down PuppetDB, releasing resources when possible.  If this is not a normal shutdown, emergency? must be set, which currently just produces a fatal level level log message, instead of info." [context emergency?] (if emergency? (log/error "A fatal error occurred; shutting down all subsystems.") (log/info "Shutdown request received; puppetdb exiting.")) (when-let [updater (context :updater)] (log/info "Shutting down updater thread.") (future-cancel updater)) (shutdown-mq context) (when-let [ds (get-in context [:shared-globals :scf-write-db :datasource])] (.close ds)) (when-let [ds (get-in context [:shared-globals :scf-read-db :datasource])] (.close ds)) context) (defn add-max-framesize "Add a maxFrameSize to broker url for activemq." [max-frame-size url] (format "%s&wireFormat.maxFrameSize=%s&marshal=true" url max-frame-size)) (defn- transfer-old-messages! [connection] (let [[pending exists?] (try+ [(mq/queue-size "localhost" "com.puppetlabs.puppetdb.commands") true] (catch [:type ::mq/queue-not-found] ex [0 false]))] (when (pos? pending) (log/infof "Transferring %d commands from legacy queue" pending) (let [n (mq/transfer-messages! "localhost" "com.puppetlabs.puppetdb.commands" mq-endpoint)] (log/infof "Transferred %d commands from legacy queue" n))) (when exists? (mq/remove-queue! "localhost" "com.puppetlabs.puppetdb.commands") (log/info "Removed legacy queue")))) (defn start-puppetdb [context config service add-ring-handler get-route shutdown-on-error] {:pre [(map? context) (map? config) (ifn? add-ring-handler) (ifn? shutdown-on-error)] :post [(map? %) (every? (partial contains? %) [:broker])]} (let [{:keys [global jetty database read-database puppetdb command-processing]} (conf/process-config! config) {:keys [product-name update-server vardir catalog-hash-debug-dir]} global {:keys [gc-interval node-ttl node-purge-ttl report-ttl]} database {:keys [dlo-compression-threshold max-frame-size threads]} command-processing {:keys [certificate-whitelist disable-update-checking]} puppetdb url-prefix (get-route service) write-db (pl-jdbc/pooled-datasource database) read-db (pl-jdbc/pooled-datasource (assoc read-database :read-only? true)) mq-dir (str (file vardir "mq")) discard-dir (file mq-dir "discarded") mq-connection-str (add-max-framesize max-frame-size mq-addr) authorizer (when certificate-whitelist (build-whitelist-authorizer certificate-whitelist))] (when-let [v (version)] (log/infof "PuppetDB version %s" v)) ;; Ensure the database is migrated to the latest version, and warn ;; if it's deprecated, log and exit if it's unsupported. We do ;; this in a single connection because HSQLDB seems to get ;; confused if the database doesn't exist but we open and close a ;; connection without creating anything. (sql/with-connection write-db (scf-store/validate-database-version #(System/exit 1)) (migrate!) (indexes! product-name)) ;; Initialize database-dependent metrics and dlo metrics if existent. (pop/initialize-metrics write-db) (when (.exists discard-dir) (dlo/create-metrics-for-dlo! discard-dir)) (let [broker (try (log/info "Starting broker") (mq/build-and-start-broker! "localhost" mq-dir command-processing) (catch java.io.EOFException e (log/error "EOF Exception caught during broker start, this " "might be due to KahaDB corruption. Consult the " "PuppetDB troubleshooting guide.") (throw e))) mq-factory (mq/activemq-connection-factory (add-max-framesize max-frame-size mq-addr)) mq-connection (doto (.createConnection mq-factory) (.setExceptionListener (reify ExceptionListener (onException [this ex] (log/error ex "service queue connection error")))) .start) globals {:scf-read-db read-db :scf-write-db write-db :authorizer authorizer :update-server update-server :product-name product-name :url-prefix url-prefix :discard-dir (.getAbsolutePath discard-dir) :mq-addr mq-addr :mq-dest mq-endpoint :mq-threads threads :catalog-hash-debug-dir catalog-hash-debug-dir :command-mq {:connection mq-connection :endpoint mq-endpoint}} updater (when-not disable-update-checking (future (shutdown-on-error (service-id service) #(maybe-check-for-updates product-name update-server read-db) #(stop-puppetdb % true))))] (transfer-old-messages! mq-connection) (let [app (->> (server/build-app globals) (compojure/context url-prefix []))] (log/info "Starting query server") (add-ring-handler service app)) ;; Pretty much this helper just knows our job-pool and gc-interval (let [job-pool (mk-pool) gc-interval-millis (to-millis gc-interval) gc-task #(interspaced gc-interval-millis % job-pool) seconds-pos? (comp pos? to-seconds) db-maintenance-tasks (fn [] (do (when (seconds-pos? node-ttl) (auto-expire-nodes! node-ttl write-db mq-connection)) (when (seconds-pos? node-purge-ttl) (purge-nodes! node-purge-ttl write-db)) (when (seconds-pos? report-ttl) (sweep-reports! report-ttl write-db)) ;; Order is important here to ensure ;; anything referencing an env or resource ;; param is purged first (garbage-collect! write-db)))] ;; Run database maintenance tasks seqentially to avoid ;; competition. Each task must handle its own errors. (gc-task db-maintenance-tasks) (gc-task #(compress-dlo! dlo-compression-threshold discard-dir))) (-> context (assoc :broker broker :mq-factory mq-factory :mq-connection mq-connection :shared-globals globals) (merge (when updater {:updater updater})))))) (defprotocol PuppetDBServer (shared-globals [this]) (query [this query-obj version query-expr paging-options row-callback-fn] "Call `row-callback-fn' for matching rows. The `paging-options' should be a map containing :order_by, :offset, and/or :limit.")) (defservice puppetdb-service "Defines a trapperkeeper service for PuppetDB; this service is responsible for initializing all of the PuppetDB subsystems and registering shutdown hooks that trapperkeeper will call on exit." PuppetDBServer [[:ConfigService get-config] [:WebroutingService add-ring-handler get-route] [:ShutdownService shutdown-on-error]] (start [this context] (start-puppetdb context (get-config) this add-ring-handler get-route shutdown-on-error)) (stop [this context] (stop-puppetdb context false)) (shared-globals [this] (:shared-globals (service-context this))) (query [this query-obj version query-expr paging-options row-callback-fn] (let [{db :scf-read-db url-prefix :url-prefix} (get (service-context this) :shared-globals)] (qeng/stream-query-result query-obj version query-expr paging-options db url-prefix row-callback-fn)))) (def ^{:arglists `([& args]) :doc "Starts PuppetDB as a service via Trapperkeeper. Aguments TK's normal config parsing to do a bit of extra customization."} -main (utils/wrap-main (fn [& args] (rh/add-hook #'puppetlabs.trapperkeeper.config/parse-config-data #'conf/hook-tk-parse-config-data) (try+ (apply tk/main args) (catch [:type ::conf/configuration-error] obj (log/error (:message obj)) (throw+ (assoc obj ::utils/exit-status 1)))))))
[ { "context": ";;; Copyright 2014 Mitchell Kember. Subject to the MIT License.\n\n(ns conceal.word)\n\n", "end": 34, "score": 0.9998885989189148, "start": 19, "tag": "NAME", "value": "Mitchell Kember" } ]
src/cljs/conceal/word.cljs
mk12/conceal
0
;;; Copyright 2014 Mitchell Kember. Subject to the MIT License. (ns conceal.word) (defn empty-grid "Creates a grid of n rows and m columns of empty cells." [n m] {:rows n :cols m :words [] :data (vec (repeat (* n m) :empty))}) (defn rand-letter "Returns a random lowercase alphabetic character." [] (char (+ 97 (rand-int 26)))) (defn empty->letter "Returns x, or a random letter if x is :empty." [x] (if (= x :empty) (rand-letter) x)) (defn fill-grid "Fills the empty cells in a grid with random letters." [grid] (update-in grid [:data] (partial map empty->letter))) (defn nth-index "Returns the index in a grid with cols columns of the nth letter in a word starting from (r,c) and going in the direction of the vector (dr,dc)." [n cols [r c dr dc]] (+ (* cols (+ r (* n dr))) (+ c (* n dc)))) (defn nth-cell "Returns the nth cell in the grid for a word placed with posdir. Returns nil if the cell would be out of bounds." [n {:keys [cols data]} posdir] (get data (nth-index n cols posdir))) (defn every-indexed? "Returns true if (pred i x) is logical true for every index i and item x in coll, otherwise returns false." [pred coll] (letfn [(every-i? [idx coll] (or (nil? (seq coll)) (and (pred idx (first coll)) (recur (inc idx) (next coll)))))] (every-i? 0 coll))) (defn word-fits? "Returns whether it is possible to place the given word in the grid with posdir. A letter can only be placed in a cell if the cell is within bounds and either the cell is empty or it already contains the right letter." [grid word posdir] {:pre [grid posdir]} (every-indexed? (fn [i letter] (let [c (nth-cell i grid posdir)] (#{:empty letter} c))) word)) (defn add-word "Adds a word into the grid with the position and direction given by posdir. Assumes the word will not go out of bounds." [{:keys [cols words data] :as grid} word posdir] {:pre [grid posdir]} (if (empty? word) grid (let [word-inds (range (count word)) grid-inds (map #(nth-index % cols posdir) word-inds) mappings (interleave grid-inds word) new-data (apply assoc data mappings) new-words (conj words word)] (assoc grid :words new-words :data new-data)))) (defn irand "Returns a random int between a (defaults to zero) and b (exclusive)." ([b] (rand-int b)) ([a b] (+ a (rand-int (- b a))))) (defn rand-pos-1d "Generates a random position along a dimension of size dim for a word of length wlen going in the direction dir." [dim wlen dir] (case dir 0 (irand dim) 1 (irand (inc (- dim wlen))) -1 (irand (dec wlen) dim))) (defn rand-posdir "Generates a random valid position-direction vector (row, column, row-dir, column-dir) for a word of length wlen on the given grid." [{:keys [rows cols]} wlen] (let [dr (rand-nth [-1 0 1]) dc (if (zero? dr) (rand-nth [-1 1]) (rand-nth [-1 0 1])) r (rand-pos-1d rows wlen dr) c (rand-pos-1d cols wlen dc)] [r c dr dc])) (defn try-placing-word "Attempts to randomly place the word. If successful, returns the new grid. If still unsuccessful after give-up tries, returns the original grid." [grid word give-up] (if (or (nil? grid) (zero? give-up)) grid (let [posdir (rand-posdir grid (count word))] (if (word-fits? grid word posdir) (add-word grid word posdir) (recur grid word (dec give-up)))))) (defn make-wordsearch "Generates a word search grid with n rows and m columns. Attempts to place each word in the word search, but gives up after give-up tries." [n m give-up words] (let [place (fn [g w] (try-placing-word g w give-up)) grid (reduce place (empty-grid n m) words)] (fill-grid grid))) (defn grid->dom "Converts a grid into a dommy-compatible data structure representing a table." [{:keys [cols data]}] (letfn [(make-row [r] (into [:tr] (map make-cell r))) (make-cell [c] [:td (str c)])] (into [:table] (map make-row (partition cols data)))))
14734
;;; Copyright 2014 <NAME>. Subject to the MIT License. (ns conceal.word) (defn empty-grid "Creates a grid of n rows and m columns of empty cells." [n m] {:rows n :cols m :words [] :data (vec (repeat (* n m) :empty))}) (defn rand-letter "Returns a random lowercase alphabetic character." [] (char (+ 97 (rand-int 26)))) (defn empty->letter "Returns x, or a random letter if x is :empty." [x] (if (= x :empty) (rand-letter) x)) (defn fill-grid "Fills the empty cells in a grid with random letters." [grid] (update-in grid [:data] (partial map empty->letter))) (defn nth-index "Returns the index in a grid with cols columns of the nth letter in a word starting from (r,c) and going in the direction of the vector (dr,dc)." [n cols [r c dr dc]] (+ (* cols (+ r (* n dr))) (+ c (* n dc)))) (defn nth-cell "Returns the nth cell in the grid for a word placed with posdir. Returns nil if the cell would be out of bounds." [n {:keys [cols data]} posdir] (get data (nth-index n cols posdir))) (defn every-indexed? "Returns true if (pred i x) is logical true for every index i and item x in coll, otherwise returns false." [pred coll] (letfn [(every-i? [idx coll] (or (nil? (seq coll)) (and (pred idx (first coll)) (recur (inc idx) (next coll)))))] (every-i? 0 coll))) (defn word-fits? "Returns whether it is possible to place the given word in the grid with posdir. A letter can only be placed in a cell if the cell is within bounds and either the cell is empty or it already contains the right letter." [grid word posdir] {:pre [grid posdir]} (every-indexed? (fn [i letter] (let [c (nth-cell i grid posdir)] (#{:empty letter} c))) word)) (defn add-word "Adds a word into the grid with the position and direction given by posdir. Assumes the word will not go out of bounds." [{:keys [cols words data] :as grid} word posdir] {:pre [grid posdir]} (if (empty? word) grid (let [word-inds (range (count word)) grid-inds (map #(nth-index % cols posdir) word-inds) mappings (interleave grid-inds word) new-data (apply assoc data mappings) new-words (conj words word)] (assoc grid :words new-words :data new-data)))) (defn irand "Returns a random int between a (defaults to zero) and b (exclusive)." ([b] (rand-int b)) ([a b] (+ a (rand-int (- b a))))) (defn rand-pos-1d "Generates a random position along a dimension of size dim for a word of length wlen going in the direction dir." [dim wlen dir] (case dir 0 (irand dim) 1 (irand (inc (- dim wlen))) -1 (irand (dec wlen) dim))) (defn rand-posdir "Generates a random valid position-direction vector (row, column, row-dir, column-dir) for a word of length wlen on the given grid." [{:keys [rows cols]} wlen] (let [dr (rand-nth [-1 0 1]) dc (if (zero? dr) (rand-nth [-1 1]) (rand-nth [-1 0 1])) r (rand-pos-1d rows wlen dr) c (rand-pos-1d cols wlen dc)] [r c dr dc])) (defn try-placing-word "Attempts to randomly place the word. If successful, returns the new grid. If still unsuccessful after give-up tries, returns the original grid." [grid word give-up] (if (or (nil? grid) (zero? give-up)) grid (let [posdir (rand-posdir grid (count word))] (if (word-fits? grid word posdir) (add-word grid word posdir) (recur grid word (dec give-up)))))) (defn make-wordsearch "Generates a word search grid with n rows and m columns. Attempts to place each word in the word search, but gives up after give-up tries." [n m give-up words] (let [place (fn [g w] (try-placing-word g w give-up)) grid (reduce place (empty-grid n m) words)] (fill-grid grid))) (defn grid->dom "Converts a grid into a dommy-compatible data structure representing a table." [{:keys [cols data]}] (letfn [(make-row [r] (into [:tr] (map make-cell r))) (make-cell [c] [:td (str c)])] (into [:table] (map make-row (partition cols data)))))
true
;;; Copyright 2014 PI:NAME:<NAME>END_PI. Subject to the MIT License. (ns conceal.word) (defn empty-grid "Creates a grid of n rows and m columns of empty cells." [n m] {:rows n :cols m :words [] :data (vec (repeat (* n m) :empty))}) (defn rand-letter "Returns a random lowercase alphabetic character." [] (char (+ 97 (rand-int 26)))) (defn empty->letter "Returns x, or a random letter if x is :empty." [x] (if (= x :empty) (rand-letter) x)) (defn fill-grid "Fills the empty cells in a grid with random letters." [grid] (update-in grid [:data] (partial map empty->letter))) (defn nth-index "Returns the index in a grid with cols columns of the nth letter in a word starting from (r,c) and going in the direction of the vector (dr,dc)." [n cols [r c dr dc]] (+ (* cols (+ r (* n dr))) (+ c (* n dc)))) (defn nth-cell "Returns the nth cell in the grid for a word placed with posdir. Returns nil if the cell would be out of bounds." [n {:keys [cols data]} posdir] (get data (nth-index n cols posdir))) (defn every-indexed? "Returns true if (pred i x) is logical true for every index i and item x in coll, otherwise returns false." [pred coll] (letfn [(every-i? [idx coll] (or (nil? (seq coll)) (and (pred idx (first coll)) (recur (inc idx) (next coll)))))] (every-i? 0 coll))) (defn word-fits? "Returns whether it is possible to place the given word in the grid with posdir. A letter can only be placed in a cell if the cell is within bounds and either the cell is empty or it already contains the right letter." [grid word posdir] {:pre [grid posdir]} (every-indexed? (fn [i letter] (let [c (nth-cell i grid posdir)] (#{:empty letter} c))) word)) (defn add-word "Adds a word into the grid with the position and direction given by posdir. Assumes the word will not go out of bounds." [{:keys [cols words data] :as grid} word posdir] {:pre [grid posdir]} (if (empty? word) grid (let [word-inds (range (count word)) grid-inds (map #(nth-index % cols posdir) word-inds) mappings (interleave grid-inds word) new-data (apply assoc data mappings) new-words (conj words word)] (assoc grid :words new-words :data new-data)))) (defn irand "Returns a random int between a (defaults to zero) and b (exclusive)." ([b] (rand-int b)) ([a b] (+ a (rand-int (- b a))))) (defn rand-pos-1d "Generates a random position along a dimension of size dim for a word of length wlen going in the direction dir." [dim wlen dir] (case dir 0 (irand dim) 1 (irand (inc (- dim wlen))) -1 (irand (dec wlen) dim))) (defn rand-posdir "Generates a random valid position-direction vector (row, column, row-dir, column-dir) for a word of length wlen on the given grid." [{:keys [rows cols]} wlen] (let [dr (rand-nth [-1 0 1]) dc (if (zero? dr) (rand-nth [-1 1]) (rand-nth [-1 0 1])) r (rand-pos-1d rows wlen dr) c (rand-pos-1d cols wlen dc)] [r c dr dc])) (defn try-placing-word "Attempts to randomly place the word. If successful, returns the new grid. If still unsuccessful after give-up tries, returns the original grid." [grid word give-up] (if (or (nil? grid) (zero? give-up)) grid (let [posdir (rand-posdir grid (count word))] (if (word-fits? grid word posdir) (add-word grid word posdir) (recur grid word (dec give-up)))))) (defn make-wordsearch "Generates a word search grid with n rows and m columns. Attempts to place each word in the word search, but gives up after give-up tries." [n m give-up words] (let [place (fn [g w] (try-placing-word g w give-up)) grid (reduce place (empty-grid n m) words)] (fill-grid grid))) (defn grid->dom "Converts a grid into a dommy-compatible data structure representing a table." [{:keys [cols data]}] (letfn [(make-row [r] (into [:tr] (map make-cell r))) (make-cell [c] [:td (str c)])] (into [:table] (map make-row (partition cols data)))))
[ { "context": "(ns ^{:author \"Victor Ursan\"\n :doc \"Pushes inventory events (fy-inventor", "end": 27, "score": 0.9998917579650879, "start": 15, "tag": "NAME", "value": "Victor Ursan" } ]
src/clj/fy_inventory/event_store/inventory_updater.clj
victorursan/fy-inventory
0
(ns ^{:author "Victor Ursan" :doc "Pushes inventory events (fy-inventory.schemas.inventory-event/InventoryEvent) into the Event Store (eg. Kafka), like the increase or decrease of an item's stock"} fy-inventory.event-store.inventory-updater)
93155
(ns ^{:author "<NAME>" :doc "Pushes inventory events (fy-inventory.schemas.inventory-event/InventoryEvent) into the Event Store (eg. Kafka), like the increase or decrease of an item's stock"} fy-inventory.event-store.inventory-updater)
true
(ns ^{:author "PI:NAME:<NAME>END_PI" :doc "Pushes inventory events (fy-inventory.schemas.inventory-event/InventoryEvent) into the Event Store (eg. Kafka), like the increase or decrease of an item's stock"} fy-inventory.event-store.inventory-updater)
[ { "context": "driver-opt-name-\" index)\n :key (str \"form-driver-opt-name-\" index)\n :value value\n ", "end": 2512, "score": 0.5230194330215454, "start": 2512, "tag": "KEY", "value": "" }, { "context": "opt-name-\" index)\n :key (str \"form-driver-opt-name-\" index)\n :value value\n :onCha", "end": 2519, "score": 0.5230770111083984, "start": 2519, "tag": "KEY", "value": "" }, { "context": "name-\" index)\n :key (str \"form-driver-opt-name-\" index)\n :value value\n :onChange ", "end": 2523, "score": 0.5074795484542847, "start": 2523, "tag": "KEY", "value": "" }, { "context": "river-opt-value-\" index)\n :key (str \"form-driver-opt-value-\" index)\n :value value\n ", "end": 2802, "score": 0.5385441780090332, "start": 2802, "tag": "KEY", "value": "" }, { "context": "pt-value-\" index)\n :key (str \"form-driver-opt-value-\" index)\n :value value\n :onCh", "end": 2809, "score": 0.5694640874862671, "start": 2809, "tag": "KEY", "value": "" }, { "context": "alue-\" index)\n :key (str \"form-driver-opt-value-\" index)\n :value value\n :onChange", "end": 2813, "score": 0.5617993474006653, "start": 2813, "tag": "KEY", "value": "" } ]
ch16/swarmpit/src/cljs/swarmpit/component/volume/create.cljs
vincestorm/Docker-on-Amazon-Web-Services
0
(ns swarmpit.component.volume.create (:require [material.icon :as icon] [material.component :as comp] [material.component.list-table-form :as list] [material.component.form :as form] [material.component.panel :as panel] [swarmpit.component.mixin :as mixin] [swarmpit.component.state :as state] [swarmpit.component.message :as message] [swarmpit.ajax :as ajax] [swarmpit.routes :as routes] [swarmpit.url :refer [dispatch!]] [sablono.core :refer-macros [html]] [rum.core :as rum])) (enable-console-print!) (def form-driver-opts-cursor (conj state/form-value-cursor :options)) (def form-driver-opts-headers [{:name "Name" :width "35%"} {:name "Value" :width "35%"}]) (defn- volume-plugin-handler [] (ajax/get (routes/path-for-backend :plugin-volume) {:on-success (fn [{:keys [response]}] (state/update-value [:plugins] response state/form-state-cursor))})) (defn- create-volume-handler [] (ajax/post (routes/path-for-backend :volume-create) {:params (state/get-value state/form-value-cursor) :state [:processing?] :on-success (fn [{:keys [response origin?]}] (when origin? (dispatch! (routes/path-for-frontend :volume-info {:name (:volumeName response)}))) (message/info (str "Volume " (:volumeName response) " has been created."))) :on-error (fn [{:keys [response]}] (message/error (str "Volume creation failed. " (:error response))))})) (defn- form-name [value] (form/comp "VOLUME NAME" (comp/vtext-field {:name "name" :key "name" :required true :value value :onChange (fn [_ v] (state/update-value [:volumeName] v state/form-value-cursor))}))) (defn- form-driver [value plugins] (form/comp "NAME" (comp/select-field {:value value :onChange (fn [_ _ v] (state/update-value [:driver] v state/form-value-cursor))} (->> plugins (map #(comp/menu-item {:key % :value % :primaryText %})))))) (defn- form-driver-opt-name [value index] (list/textfield {:name (str "form-driver-opt-name-" index) :key (str "form-driver-opt-name-" index) :value value :onChange (fn [_ v] (state/update-item index :name v form-driver-opts-cursor))})) (defn- form-driver-opt-value [value index] (list/textfield {:name (str "form-driver-opt-value-" index) :key (str "form-driver-opt-value-" index) :value value :onChange (fn [_ v] (state/update-item index :value v form-driver-opts-cursor))})) (defn- form-driver-render-opts [item index] (let [{:keys [name value]} item] [(form-driver-opt-name name index) (form-driver-opt-value value index)])) (defn- form-driver-opts-table [opts] (list/table-raw form-driver-opts-headers opts nil form-driver-render-opts (fn [index] (state/remove-item index form-driver-opts-cursor)))) (defn- add-driver-opt [] (state/add-item {:name "" :value ""} form-driver-opts-cursor)) (defn- init-form-state [] (state/set-value {:valid? false :processing? false :plugins []} state/form-state-cursor)) (defn- init-form-value [] (state/set-value {:volumeName nil :driver "local" :options []} state/form-value-cursor)) (def mixin-init-form (mixin/init-form (fn [_] (init-form-state) (init-form-value) (volume-plugin-handler)))) (rum/defc form < rum/reactive mixin-init-form [_] (let [{:keys [volumeName driver options]} (state/react state/form-value-cursor) {:keys [valid? processing? plugins]} (state/react state/form-state-cursor)] [:div [:div.form-panel [:div.form-panel-left (panel/info icon/networks "New volume")] [:div.form-panel-right (comp/progress-button {:label "Create" :disabled (not valid?) :primary true :onTouchTap create-volume-handler} processing?)]] [:div.form-layout [:div.form-layout-group (form/form {:onValid #(state/update-value [:valid?] true state/form-state-cursor) :onInvalid #(state/update-value [:valid?] false state/form-state-cursor)} (form-name volumeName))] [:div.form-layout-group.form-layout-group-border (form/section "Driver") (form/form {} (form-driver driver plugins) (html (form/subsection-add "Add volume driver option" add-driver-opt)) (when (not (empty? options)) (form-driver-opts-table options)))]]]))
66728
(ns swarmpit.component.volume.create (:require [material.icon :as icon] [material.component :as comp] [material.component.list-table-form :as list] [material.component.form :as form] [material.component.panel :as panel] [swarmpit.component.mixin :as mixin] [swarmpit.component.state :as state] [swarmpit.component.message :as message] [swarmpit.ajax :as ajax] [swarmpit.routes :as routes] [swarmpit.url :refer [dispatch!]] [sablono.core :refer-macros [html]] [rum.core :as rum])) (enable-console-print!) (def form-driver-opts-cursor (conj state/form-value-cursor :options)) (def form-driver-opts-headers [{:name "Name" :width "35%"} {:name "Value" :width "35%"}]) (defn- volume-plugin-handler [] (ajax/get (routes/path-for-backend :plugin-volume) {:on-success (fn [{:keys [response]}] (state/update-value [:plugins] response state/form-state-cursor))})) (defn- create-volume-handler [] (ajax/post (routes/path-for-backend :volume-create) {:params (state/get-value state/form-value-cursor) :state [:processing?] :on-success (fn [{:keys [response origin?]}] (when origin? (dispatch! (routes/path-for-frontend :volume-info {:name (:volumeName response)}))) (message/info (str "Volume " (:volumeName response) " has been created."))) :on-error (fn [{:keys [response]}] (message/error (str "Volume creation failed. " (:error response))))})) (defn- form-name [value] (form/comp "VOLUME NAME" (comp/vtext-field {:name "name" :key "name" :required true :value value :onChange (fn [_ v] (state/update-value [:volumeName] v state/form-value-cursor))}))) (defn- form-driver [value plugins] (form/comp "NAME" (comp/select-field {:value value :onChange (fn [_ _ v] (state/update-value [:driver] v state/form-value-cursor))} (->> plugins (map #(comp/menu-item {:key % :value % :primaryText %})))))) (defn- form-driver-opt-name [value index] (list/textfield {:name (str "form-driver-opt-name-" index) :key (str "form<KEY>-driver<KEY>-opt<KEY>-name-" index) :value value :onChange (fn [_ v] (state/update-item index :name v form-driver-opts-cursor))})) (defn- form-driver-opt-value [value index] (list/textfield {:name (str "form-driver-opt-value-" index) :key (str "form<KEY>-driver<KEY>-opt<KEY>-value-" index) :value value :onChange (fn [_ v] (state/update-item index :value v form-driver-opts-cursor))})) (defn- form-driver-render-opts [item index] (let [{:keys [name value]} item] [(form-driver-opt-name name index) (form-driver-opt-value value index)])) (defn- form-driver-opts-table [opts] (list/table-raw form-driver-opts-headers opts nil form-driver-render-opts (fn [index] (state/remove-item index form-driver-opts-cursor)))) (defn- add-driver-opt [] (state/add-item {:name "" :value ""} form-driver-opts-cursor)) (defn- init-form-state [] (state/set-value {:valid? false :processing? false :plugins []} state/form-state-cursor)) (defn- init-form-value [] (state/set-value {:volumeName nil :driver "local" :options []} state/form-value-cursor)) (def mixin-init-form (mixin/init-form (fn [_] (init-form-state) (init-form-value) (volume-plugin-handler)))) (rum/defc form < rum/reactive mixin-init-form [_] (let [{:keys [volumeName driver options]} (state/react state/form-value-cursor) {:keys [valid? processing? plugins]} (state/react state/form-state-cursor)] [:div [:div.form-panel [:div.form-panel-left (panel/info icon/networks "New volume")] [:div.form-panel-right (comp/progress-button {:label "Create" :disabled (not valid?) :primary true :onTouchTap create-volume-handler} processing?)]] [:div.form-layout [:div.form-layout-group (form/form {:onValid #(state/update-value [:valid?] true state/form-state-cursor) :onInvalid #(state/update-value [:valid?] false state/form-state-cursor)} (form-name volumeName))] [:div.form-layout-group.form-layout-group-border (form/section "Driver") (form/form {} (form-driver driver plugins) (html (form/subsection-add "Add volume driver option" add-driver-opt)) (when (not (empty? options)) (form-driver-opts-table options)))]]]))
true
(ns swarmpit.component.volume.create (:require [material.icon :as icon] [material.component :as comp] [material.component.list-table-form :as list] [material.component.form :as form] [material.component.panel :as panel] [swarmpit.component.mixin :as mixin] [swarmpit.component.state :as state] [swarmpit.component.message :as message] [swarmpit.ajax :as ajax] [swarmpit.routes :as routes] [swarmpit.url :refer [dispatch!]] [sablono.core :refer-macros [html]] [rum.core :as rum])) (enable-console-print!) (def form-driver-opts-cursor (conj state/form-value-cursor :options)) (def form-driver-opts-headers [{:name "Name" :width "35%"} {:name "Value" :width "35%"}]) (defn- volume-plugin-handler [] (ajax/get (routes/path-for-backend :plugin-volume) {:on-success (fn [{:keys [response]}] (state/update-value [:plugins] response state/form-state-cursor))})) (defn- create-volume-handler [] (ajax/post (routes/path-for-backend :volume-create) {:params (state/get-value state/form-value-cursor) :state [:processing?] :on-success (fn [{:keys [response origin?]}] (when origin? (dispatch! (routes/path-for-frontend :volume-info {:name (:volumeName response)}))) (message/info (str "Volume " (:volumeName response) " has been created."))) :on-error (fn [{:keys [response]}] (message/error (str "Volume creation failed. " (:error response))))})) (defn- form-name [value] (form/comp "VOLUME NAME" (comp/vtext-field {:name "name" :key "name" :required true :value value :onChange (fn [_ v] (state/update-value [:volumeName] v state/form-value-cursor))}))) (defn- form-driver [value plugins] (form/comp "NAME" (comp/select-field {:value value :onChange (fn [_ _ v] (state/update-value [:driver] v state/form-value-cursor))} (->> plugins (map #(comp/menu-item {:key % :value % :primaryText %})))))) (defn- form-driver-opt-name [value index] (list/textfield {:name (str "form-driver-opt-name-" index) :key (str "formPI:KEY:<KEY>END_PI-driverPI:KEY:<KEY>END_PI-optPI:KEY:<KEY>END_PI-name-" index) :value value :onChange (fn [_ v] (state/update-item index :name v form-driver-opts-cursor))})) (defn- form-driver-opt-value [value index] (list/textfield {:name (str "form-driver-opt-value-" index) :key (str "formPI:KEY:<KEY>END_PI-driverPI:KEY:<KEY>END_PI-optPI:KEY:<KEY>END_PI-value-" index) :value value :onChange (fn [_ v] (state/update-item index :value v form-driver-opts-cursor))})) (defn- form-driver-render-opts [item index] (let [{:keys [name value]} item] [(form-driver-opt-name name index) (form-driver-opt-value value index)])) (defn- form-driver-opts-table [opts] (list/table-raw form-driver-opts-headers opts nil form-driver-render-opts (fn [index] (state/remove-item index form-driver-opts-cursor)))) (defn- add-driver-opt [] (state/add-item {:name "" :value ""} form-driver-opts-cursor)) (defn- init-form-state [] (state/set-value {:valid? false :processing? false :plugins []} state/form-state-cursor)) (defn- init-form-value [] (state/set-value {:volumeName nil :driver "local" :options []} state/form-value-cursor)) (def mixin-init-form (mixin/init-form (fn [_] (init-form-state) (init-form-value) (volume-plugin-handler)))) (rum/defc form < rum/reactive mixin-init-form [_] (let [{:keys [volumeName driver options]} (state/react state/form-value-cursor) {:keys [valid? processing? plugins]} (state/react state/form-state-cursor)] [:div [:div.form-panel [:div.form-panel-left (panel/info icon/networks "New volume")] [:div.form-panel-right (comp/progress-button {:label "Create" :disabled (not valid?) :primary true :onTouchTap create-volume-handler} processing?)]] [:div.form-layout [:div.form-layout-group (form/form {:onValid #(state/update-value [:valid?] true state/form-state-cursor) :onInvalid #(state/update-value [:valid?] false state/form-state-cursor)} (form-name volumeName))] [:div.form-layout-group.form-layout-group-border (form/section "Driver") (form/form {} (form-driver driver plugins) (html (form/subsection-add "Add volume driver option" add-driver-opt)) (when (not (empty? options)) (form-driver-opts-table options)))]]]))
[ { "context": " (= {:keys [{:alg \"RS256\"\n :n \"0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw\"\n :kid \"2011-04-29\"\n ", "end": 948, "score": 0.9997862577438354, "start": 606, "tag": "KEY", "value": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw" }, { "context": "deftest permissions-test-content\n (let [api-key \"42\"]\n (testing \"all for alice as handler\"\n (", "end": 1757, "score": 0.9231833815574646, "start": 1755, "tag": "KEY", "value": "42" }, { "context": "eftest permissions-test-security\n (let [api-key \"42\"]\n (testing \"listing without authentication\"\n ", "end": 2609, "score": 0.9764518141746521, "start": 2607, "tag": "KEY", "value": "42" }, { "context": ")\n (authenticate api-key \"approver1\")\n handler)\n b", "end": 3018, "score": 0.6914379596710205, "start": 3009, "tag": "USERNAME", "value": "approver1" }, { "context": "enable-permissions-api false)]\n (let [api-key \"42\"]\n (testing \"when permissions api is disable", "end": 3557, "score": 0.9906032085418701, "start": 3555, "tag": "KEY", "value": "42" } ]
test/clj/rems/api/test_permissions.clj
BadAlgorithm/rems
0
(ns ^:integration rems.api.test-permissions (:require [buddy.sign.jws :as buddy-jws] [buddy.sign.jwt :as buddy-jwt] [buddy.core.keys :as buddy-keys] [clojure.test :refer :all] [rems.api.testing :refer :all] [rems.config] [rems.ga4gh :as ga4gh] [rems.handler :refer [handler]] [ring.mock.request :refer :all] [schema.core :as s])) (use-fixtures :once api-fixture) (deftest jwk-api (let [data (api-call :get "/api/jwk" nil nil nil)] (is (= {:keys [{:alg "RS256" :n "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw" :kid "2011-04-29" :e "AQAB" :kty "RSA"}]} data)))) (defn- validate-visa [visa] (s/validate ga4gh/VisaClaim visa)) (defn- validate-alice-result [data] (doseq [visa (:ga4gh_passport_v1 data)] (let [header (buddy-jws/decode-header visa) key (buddy-keys/jwk->public-key (rems.config/env :ga4gh-visa-public-key)) data (buddy-jwt/unsign visa key {:alg :rs256})] (is (= (str (:public-url rems.config/env) "api/jwk") (:jku header))) (is (= "JWT" (:typ header))) (is (= "2011-04-29" (:kid header))) (validate-visa data) (is (= "alice" (:sub data))) (is (= "urn:nbn:fi:lb-201403262" (get-in data [:ga4gh_visa_v1 :value])))))) (deftest permissions-test-content (let [api-key "42"] (testing "all for alice as handler" (let [data (-> (request :get "/api/permissions/alice") (authenticate api-key "handler") handler read-ok-body)] (validate-alice-result data))) (testing "all for alice as owner" (let [data (-> (request :get "/api/permissions/alice") (authenticate api-key "owner") handler read-ok-body)] (validate-alice-result data))) (testing "without user not found is returned" (let [response (-> (request :get "/api/permissions") (authenticate api-key "handler") handler) body (read-body response)] (is (= "not found" body)))))) (deftest permissions-test-security (let [api-key "42"] (testing "listing without authentication" (let [response (-> (request :get (str "/api/permissions/userx")) handler) body (read-body response)] (is (= "unauthorized" body)))) (testing "listing without appropriate role" (let [response (-> (request :get (str "/api/permissions/alice")) (authenticate api-key "approver1") handler) body (read-body response)] (is (= "forbidden" body)))) (testing "all for alice as malice" (let [response (-> (request :get (str "/api/permissions/alice")) (authenticate api-key "malice") handler) body (read-body response)] (is (= "forbidden" body)))))) (deftest permissions-test-api-disabled (with-redefs [rems.config/env (assoc rems.config/env :enable-permissions-api false)] (let [api-key "42"] (testing "when permissions api is disabled" (let [response (-> (request :get "/api/permissions/alice") (authenticate api-key "handler") handler) body (read-body response)] (is (= "permissions api not implemented" body)))))))
7933
(ns ^:integration rems.api.test-permissions (:require [buddy.sign.jws :as buddy-jws] [buddy.sign.jwt :as buddy-jwt] [buddy.core.keys :as buddy-keys] [clojure.test :refer :all] [rems.api.testing :refer :all] [rems.config] [rems.ga4gh :as ga4gh] [rems.handler :refer [handler]] [ring.mock.request :refer :all] [schema.core :as s])) (use-fixtures :once api-fixture) (deftest jwk-api (let [data (api-call :get "/api/jwk" nil nil nil)] (is (= {:keys [{:alg "RS256" :n "<KEY>" :kid "2011-04-29" :e "AQAB" :kty "RSA"}]} data)))) (defn- validate-visa [visa] (s/validate ga4gh/VisaClaim visa)) (defn- validate-alice-result [data] (doseq [visa (:ga4gh_passport_v1 data)] (let [header (buddy-jws/decode-header visa) key (buddy-keys/jwk->public-key (rems.config/env :ga4gh-visa-public-key)) data (buddy-jwt/unsign visa key {:alg :rs256})] (is (= (str (:public-url rems.config/env) "api/jwk") (:jku header))) (is (= "JWT" (:typ header))) (is (= "2011-04-29" (:kid header))) (validate-visa data) (is (= "alice" (:sub data))) (is (= "urn:nbn:fi:lb-201403262" (get-in data [:ga4gh_visa_v1 :value])))))) (deftest permissions-test-content (let [api-key "<KEY>"] (testing "all for alice as handler" (let [data (-> (request :get "/api/permissions/alice") (authenticate api-key "handler") handler read-ok-body)] (validate-alice-result data))) (testing "all for alice as owner" (let [data (-> (request :get "/api/permissions/alice") (authenticate api-key "owner") handler read-ok-body)] (validate-alice-result data))) (testing "without user not found is returned" (let [response (-> (request :get "/api/permissions") (authenticate api-key "handler") handler) body (read-body response)] (is (= "not found" body)))))) (deftest permissions-test-security (let [api-key "<KEY>"] (testing "listing without authentication" (let [response (-> (request :get (str "/api/permissions/userx")) handler) body (read-body response)] (is (= "unauthorized" body)))) (testing "listing without appropriate role" (let [response (-> (request :get (str "/api/permissions/alice")) (authenticate api-key "approver1") handler) body (read-body response)] (is (= "forbidden" body)))) (testing "all for alice as malice" (let [response (-> (request :get (str "/api/permissions/alice")) (authenticate api-key "malice") handler) body (read-body response)] (is (= "forbidden" body)))))) (deftest permissions-test-api-disabled (with-redefs [rems.config/env (assoc rems.config/env :enable-permissions-api false)] (let [api-key "<KEY>"] (testing "when permissions api is disabled" (let [response (-> (request :get "/api/permissions/alice") (authenticate api-key "handler") handler) body (read-body response)] (is (= "permissions api not implemented" body)))))))
true
(ns ^:integration rems.api.test-permissions (:require [buddy.sign.jws :as buddy-jws] [buddy.sign.jwt :as buddy-jwt] [buddy.core.keys :as buddy-keys] [clojure.test :refer :all] [rems.api.testing :refer :all] [rems.config] [rems.ga4gh :as ga4gh] [rems.handler :refer [handler]] [ring.mock.request :refer :all] [schema.core :as s])) (use-fixtures :once api-fixture) (deftest jwk-api (let [data (api-call :get "/api/jwk" nil nil nil)] (is (= {:keys [{:alg "RS256" :n "PI:KEY:<KEY>END_PI" :kid "2011-04-29" :e "AQAB" :kty "RSA"}]} data)))) (defn- validate-visa [visa] (s/validate ga4gh/VisaClaim visa)) (defn- validate-alice-result [data] (doseq [visa (:ga4gh_passport_v1 data)] (let [header (buddy-jws/decode-header visa) key (buddy-keys/jwk->public-key (rems.config/env :ga4gh-visa-public-key)) data (buddy-jwt/unsign visa key {:alg :rs256})] (is (= (str (:public-url rems.config/env) "api/jwk") (:jku header))) (is (= "JWT" (:typ header))) (is (= "2011-04-29" (:kid header))) (validate-visa data) (is (= "alice" (:sub data))) (is (= "urn:nbn:fi:lb-201403262" (get-in data [:ga4gh_visa_v1 :value])))))) (deftest permissions-test-content (let [api-key "PI:KEY:<KEY>END_PI"] (testing "all for alice as handler" (let [data (-> (request :get "/api/permissions/alice") (authenticate api-key "handler") handler read-ok-body)] (validate-alice-result data))) (testing "all for alice as owner" (let [data (-> (request :get "/api/permissions/alice") (authenticate api-key "owner") handler read-ok-body)] (validate-alice-result data))) (testing "without user not found is returned" (let [response (-> (request :get "/api/permissions") (authenticate api-key "handler") handler) body (read-body response)] (is (= "not found" body)))))) (deftest permissions-test-security (let [api-key "PI:KEY:<KEY>END_PI"] (testing "listing without authentication" (let [response (-> (request :get (str "/api/permissions/userx")) handler) body (read-body response)] (is (= "unauthorized" body)))) (testing "listing without appropriate role" (let [response (-> (request :get (str "/api/permissions/alice")) (authenticate api-key "approver1") handler) body (read-body response)] (is (= "forbidden" body)))) (testing "all for alice as malice" (let [response (-> (request :get (str "/api/permissions/alice")) (authenticate api-key "malice") handler) body (read-body response)] (is (= "forbidden" body)))))) (deftest permissions-test-api-disabled (with-redefs [rems.config/env (assoc rems.config/env :enable-permissions-api false)] (let [api-key "PI:KEY:<KEY>END_PI"] (testing "when permissions api is disabled" (let [response (-> (request :get "/api/permissions/alice") (authenticate api-key "handler") handler) body (read-body response)] (is (= "permissions api not implemented" body)))))))
[ { "context": "eaction (:duration @player))\n {:keys [title author author-url author-img-url]} @player]\n (pipe\n ", "end": 13432, "score": 0.6086097955703735, "start": 13426, "tag": "NAME", "value": "author" } ]
src/asciinema/player/view.cljs
hoskovecjan/asciinema-player
2,094
(ns asciinema.player.view (:require [clojure.string :as string] [clojure.set :as set] [reagent.core :as reagent] [reagent.ratom :refer-macros [reaction]] [cljs.core.async :refer [chan >! <! put! alts! timeout dropping-buffer pipe]] [asciinema.player.messages :as m] [asciinema.player.source :as source] [asciinema.player.util :as util] [asciinema.player.screen :as screen] [asciinema.player.fullscreen :as fullscreen] [clojure.string :as str]) (:require-macros [cljs.core.async.macros :refer [go-loop]])) (extend-protocol screen/Screen cljs.core/PersistentArrayMap (lines [this] (:lines this)) (cursor [this] (:cursor this))) (defn send-value! [ch f] (fn [dom-event] (when-some [msg (f dom-event)] (put! ch msg) (.stopPropagation dom-event)))) (defn send! [ch msg] (send-value! ch (fn [_] msg))) (defn indexed-color? [c] (or (number? c) (= c "fg") (= c "bg"))) (def rgb-color? vector?) (defn color-class-name [color high-intensity prefix] (when (indexed-color? color) (let [color (if (and high-intensity (< color 8)) (+ color 8) color)] (str prefix color)))) (defn part-class-name [{:keys [fg bg bold blink underline inverse italic strikethrough cursor]}] (let [fg-final (if inverse (or bg "bg") fg) bg-final (if inverse (or fg "fg") bg) fg-class (color-class-name fg-final bold "fg-") bg-class (color-class-name bg-final blink "bg-") bold-class (when bold "bright") italic-class (when italic "italic") underline-class (when underline "underline") strikethrough-class (when strikethrough "strikethrough") cursor-class (when cursor "cursor") classes (remove nil? [fg-class bg-class bold-class italic-class underline-class strikethrough-class cursor-class])] (when (seq classes) (string/join " " classes)))) (defn css-rgb [[r g b]] (str "rgb(" r "," g "," b ")")) (defn part-style [{:keys [fg bg inverse]}] (let [fg-final (if inverse bg fg) bg-final (if inverse fg bg)] (merge (when (rgb-color? fg-final) {:color (css-rgb fg-final)}) (when (rgb-color? bg-final) {:background-color (css-rgb bg-final)})))) (defn part-props [{:keys [inverse cursor] :as attrs}] (let [inverse (if cursor (not inverse) inverse) attrs (assoc attrs :inverse inverse) class-name (part-class-name attrs) style (part-style attrs)] (merge (when class-name {:class-name class-name}) (when style {:style style})))) (def part-props-memoized (memoize part-props)) (defn part [[text attrs] cursor-on] (let [attrs (update attrs :cursor #(and % @cursor-on))] [:span (part-props-memoized attrs) text])) (defn split-part-with-cursor [[text attrs] position] (let [left-chars (take position text) left-part (if (seq left-chars) [(str/join left-chars) attrs]) cursor-attrs (assoc attrs :cursor true) center-part [(nth text position) cursor-attrs] right-chars (drop (inc position) text) right-part (if (seq right-chars) [(str/join right-chars) attrs])] (remove nil? (vector left-part center-part right-part)))) (defn insert-cursor "Marks proper character in line with ':cursor true' by locating and splitting a fragment that contains the cursor position." [parts cursor-x] (loop [left [] right parts idx cursor-x] (if (seq right) (let [[text attrs :as part] (first right) len (count text)] (if (<= len idx) (recur (conj left part) (rest right) (- idx len)) (concat left (split-part-with-cursor part idx) (rest right)))) left))) (defn line [parts cursor-x cursor-on] (let [parts (if @cursor-x (insert-cursor @parts @cursor-x) @parts)] [:span.line (doall (map-indexed (fn [idx p] ^{:key idx} [part p cursor-on]) parts))])) (def named-font-sizes #{"small" "medium" "big"}) (defn terminal-class-name [font-size] (when (named-font-sizes font-size) (str "font-" font-size))) (defn terminal-style [width height font-size] (let [font-size (when-not (named-font-sizes font-size) {:font-size font-size})] (merge {:width (str width "ch") :height (str (* 1.3333333333 height) "em")} font-size))) (defn terminal [width height font-size screen cursor-on] (let [class-name (reaction (terminal-class-name @font-size)) style (reaction (terminal-style @width @height @font-size)) lines (reaction (screen/lines @screen)) line-reactions (reaction (mapv (fn [n] (reaction (get @lines n))) (range @height))) cursor (reaction (screen/cursor @screen)) cursor-x (reaction (:x @cursor)) cursor-y (reaction (:y @cursor)) cursor-visible (reaction (:visible @cursor))] (fn [] [:pre.asciinema-terminal {:class-name @class-name :style @style} (map-indexed (fn [idx parts] (let [cursor-x (reaction (and @cursor-visible (= idx @cursor-y) @cursor-x))] ^{:key idx} [line parts cursor-x cursor-on])) @line-reactions)]))) (def logo-raw-svg "<defs> <mask id=\"small-triangle-mask\"> <rect width=\"100%\" height=\"100%\" fill=\"white\"/> <polygon points=\"508.01270189221935 433.01270189221935, 208.0127018922194 259.8076211353316, 208.01270189221927 606.217782649107\" fill=\"black\"></polygon> </mask> </defs> <polygon points=\"808.0127018922194 433.01270189221935, 58.01270189221947 -1.1368683772161603e-13, 58.01270189221913 866.0254037844386\" mask=\"url(#small-triangle-mask)\" fill=\"white\"></polygon> <polyline points=\"481.2177826491071 333.0127018922194, 134.80762113533166 533.0127018922194\" stroke=\"white\" stroke-width=\"90\"></polyline>") (defn logo-play-icon [] [:svg {:version "1.1" :view-box "0 0 866.0254037844387 866.0254037844387" :class-name "icon" :dangerouslySetInnerHTML {:__html logo-raw-svg}}]) (defn play-icon [] [:svg {:version "1.1" :view-box "0 0 12 12" :class-name "icon"} [:path {:d "M1,0 L11,6 L1,12 Z"}]]) (defn pause-icon [] [:svg {:version "1.1" :view-box "0 0 12 12" :class-name "icon"} [:path {:d "M1,0 L4,0 L4,12 L1,12 Z"}] [:path {:d "M8,0 L11,0 L11,12 L8,12 Z"}]]) (defn expand-icon [] [:svg {:version "1.1" :view-box "0 0 12 12" :class-name "icon"} [:path {:d "M12,0 L7,0 L9,2 L7,4 L8,5 L10,3 L12,5 Z"}] [:path {:d "M0,12 L0,7 L2,9 L4,7 L5,8 L3,10 L5,12 Z"}]]) (defn shrink-icon [] [:svg {:version "1.1" :view-box "0 0 12 12" :class-name "icon"} [:path {:d "M7,5 L7,0 L9,2 L11,0 L12,1 L10,3 L12,5 Z"}] [:path {:d "M5,7 L0,7 L2,9 L0,11 L1,12 L3,10 L5,12 Z"}]]) (defn playback-control-button [playing? msg-ch] (let [on-click (send! msg-ch (m/->TogglePlay))] (fn [] [:span.playback-button {:on-click on-click} [(if @playing? pause-icon play-icon)]]))) (defn pad2 [number] (if (< number 10) (str "0" number) number)) (defn format-time [seconds] (let [m (.floor js/Math (/ seconds 60)) s (.floor js/Math (mod seconds 60))] (str (pad2 m) ":" (pad2 s)))) (defn elapsed-time [current-time] (format-time current-time)) (defn remaining-time [current-time total-time] (str "-" (format-time (- total-time current-time)))) (defn timer [current-time total-time] [:span.timer [:span.time-elapsed (elapsed-time @current-time)] [:span.time-remaining (remaining-time @current-time @total-time)]]) (defn fullscreen-toggle-button [] (letfn [(on-click [e] (.preventDefault e) (fullscreen/toggle (-> e .-currentTarget .-parentNode .-parentNode .-parentNode)))] (fn [] [:span.fullscreen-button {:on-click on-click} [expand-icon] [shrink-icon]]))) (defn element-local-mouse-x [e] (let [rect (-> e .-currentTarget .getBoundingClientRect)] (- (.-clientX e) (.-left rect)))) (defn click-position [e] (let [bar-width (-> e .-currentTarget .-offsetWidth) mouse-x (util/adjust-to-range (element-local-mouse-x e) 0 bar-width)] (/ mouse-x bar-width))) (defn progress-bar [progress msg-ch] (let [on-mouse-down (send-value! msg-ch (fn [e] (-> e click-position m/->Seek))) progress-str (reaction (str (* 100 @progress) "%"))] (fn [] [:span.progressbar [:span.bar {:on-mouse-down on-mouse-down} [:span.gutter [:span {:style {:width @progress-str}}]]]]))) (defn recorded-control-bar [playing? current-time total-time msg-ch] (let [progress (reaction (/ @current-time @total-time))] (fn [] [:div.control-bar [playback-control-button playing? msg-ch] [timer current-time total-time] [fullscreen-toggle-button] [progress-bar progress msg-ch]]))) (defn stream-control-bar [] [:div.control-bar.live [:span.timer "LIVE"] [fullscreen-toggle-button] [progress-bar 0 (fn [& _])]]) (defn start-overlay [msg-ch] (let [on-click (send! msg-ch (m/->TogglePlay))] (fn [] [:div.start-prompt {:on-click on-click} [:div.play-button [:div [:span [logo-play-icon]]]]]))) (defn loading-overlay [] [:div.loading [:div.loader]]) (defn player-class-name [theme-name] (str "asciinema-theme-" theme-name)) (defn has-modifiers? [dom-event] (some #(aget dom-event %) ["altKey" "shiftKey" "metaKey" "ctrlKey"])) (defn key-press->message [dom-event] (or (when-not (has-modifiers? dom-event) (case (.-key dom-event) " " (m/->TogglePlay) "f" :toggle-fullscreen "0" (m/->Seek 0.0) "1" (m/->Seek 0.1) "2" (m/->Seek 0.2) "3" (m/->Seek 0.3) "4" (m/->Seek 0.4) "5" (m/->Seek 0.5) "6" (m/->Seek 0.6) "7" (m/->Seek 0.7) "8" (m/->Seek 0.8) "9" (m/->Seek 0.9) nil)) (case (.-key dom-event) ">" (m/->SpeedUp) "<" (m/->SpeedDown) nil))) (defn key-down->message [dom-event] (when-not (has-modifiers? dom-event) (case (.-which dom-event) 37 (m/->Rewind) 39 (m/->FastForward) nil))) (defn handle-key-press [dom-event] (when-let [msg (key-press->message dom-event)] (.preventDefault dom-event) (if (= msg :toggle-fullscreen) (do (fullscreen/toggle (.-currentTarget dom-event)) nil) msg))) (defn handle-key-down [dom-event] (when-let [msg (key-down->message dom-event)] (.preventDefault dom-event) msg)) (defn title-bar [title author author-url author-img-url] (let [title-text (if title (str "\"" title "\"") "untitled")] [:span.title-bar (when author-img-url [:img {:src author-img-url}]) title-text (when author [:span " by " (if author-url [:a {:href author-url} author] author)])])) (defn activity-chan "Converts given channel into an activity indicator channel. The resulting channel emits false when there are no reads on input channel within msec, then true when new values show up on input, then false again after msec without reads on input, and so on." ([input msec] (activity-chan input msec (chan))) ([input msec output] (go-loop [] ;; wait for activity on input channel (<! input) (>! output true) ;; wait for inactivity on input channel (loop [] (let [t (timeout msec) [_ c] (alts! [input t])] (when (= c input) (recur)))) (>! output false) (recur)) output)) (defn start-message-loop! "Starts message processing loop. Updates Reagent atom with the result of applying a message to player state." [player-atom initial-channels] (let [channels (atom initial-channels)] (go-loop [] (let [[message channel] (alts! (seq @channels))] (when (nil? message) (swap! channels disj channel)) (when (satisfies? m/Update message) (swap! player-atom #(m/update-player message %))) (when (satisfies? m/ChannelSource message) (swap! channels set/union (m/get-channels message @player-atom)))) (recur)))) (defn player* [player ui-ch] (let [mouse-moves-ch (chan (dropping-buffer 1)) on-mouse-move (send! mouse-moves-ch true) on-mouse-enter (send! ui-ch (m/->ShowHud true)) on-mouse-leave (send! ui-ch (m/->ShowHud false)) on-key-press (send-value! ui-ch handle-key-press) on-key-down (send-value! ui-ch handle-key-down) loading (reaction (:loading @player)) loaded (reaction (:loaded @player)) started (reaction (or @loading @loaded)) wrapper-class-name (reaction (when (or (:show-hud @player) (not @started)) "hud")) player-class-name (reaction (player-class-name (:theme @player))) width (reaction (or (:width @player) 80)) height (reaction (or (:height @player) 24)) font-size (reaction (:font-size @player)) screen (reaction (:screen @player)) cursor-on (reaction (:cursor-on @player)) playing (reaction (:playing @player)) current-time (reaction (:current-time @player)) total-time (reaction (:duration @player)) {:keys [title author author-url author-img-url]} @player] (pipe (activity-chan mouse-moves-ch 3000 (chan 1 (map m/->ShowHud))) ui-ch) (fn [] [:div.asciinema-player-wrapper {:tab-index -1 :on-key-press on-key-press :on-key-down on-key-down :class-name @wrapper-class-name} [:div.asciinema-player {:class-name @player-class-name :on-mouse-move on-mouse-move :on-mouse-enter on-mouse-enter :on-mouse-leave on-mouse-leave} [terminal width height font-size screen cursor-on] [recorded-control-bar playing current-time total-time ui-ch] (when (or title author) [title-bar title author author-url author-img-url]) (when-not @started [start-overlay ui-ch]) (when @loading [loading-overlay])]]))) (defn player-component [player] (let [ui-ch (chan)] (fn [] (reagent/create-class {:display-name "asciinema-player" :reagent-render #(player* player ui-ch) :component-did-mount (fn [this] (let [source-ch (source/init (:source @player))] (start-message-loop! player #{ui-ch source-ch}))) :component-will-unmount (fn [this] (source/close (:source @player)))}))))
45826
(ns asciinema.player.view (:require [clojure.string :as string] [clojure.set :as set] [reagent.core :as reagent] [reagent.ratom :refer-macros [reaction]] [cljs.core.async :refer [chan >! <! put! alts! timeout dropping-buffer pipe]] [asciinema.player.messages :as m] [asciinema.player.source :as source] [asciinema.player.util :as util] [asciinema.player.screen :as screen] [asciinema.player.fullscreen :as fullscreen] [clojure.string :as str]) (:require-macros [cljs.core.async.macros :refer [go-loop]])) (extend-protocol screen/Screen cljs.core/PersistentArrayMap (lines [this] (:lines this)) (cursor [this] (:cursor this))) (defn send-value! [ch f] (fn [dom-event] (when-some [msg (f dom-event)] (put! ch msg) (.stopPropagation dom-event)))) (defn send! [ch msg] (send-value! ch (fn [_] msg))) (defn indexed-color? [c] (or (number? c) (= c "fg") (= c "bg"))) (def rgb-color? vector?) (defn color-class-name [color high-intensity prefix] (when (indexed-color? color) (let [color (if (and high-intensity (< color 8)) (+ color 8) color)] (str prefix color)))) (defn part-class-name [{:keys [fg bg bold blink underline inverse italic strikethrough cursor]}] (let [fg-final (if inverse (or bg "bg") fg) bg-final (if inverse (or fg "fg") bg) fg-class (color-class-name fg-final bold "fg-") bg-class (color-class-name bg-final blink "bg-") bold-class (when bold "bright") italic-class (when italic "italic") underline-class (when underline "underline") strikethrough-class (when strikethrough "strikethrough") cursor-class (when cursor "cursor") classes (remove nil? [fg-class bg-class bold-class italic-class underline-class strikethrough-class cursor-class])] (when (seq classes) (string/join " " classes)))) (defn css-rgb [[r g b]] (str "rgb(" r "," g "," b ")")) (defn part-style [{:keys [fg bg inverse]}] (let [fg-final (if inverse bg fg) bg-final (if inverse fg bg)] (merge (when (rgb-color? fg-final) {:color (css-rgb fg-final)}) (when (rgb-color? bg-final) {:background-color (css-rgb bg-final)})))) (defn part-props [{:keys [inverse cursor] :as attrs}] (let [inverse (if cursor (not inverse) inverse) attrs (assoc attrs :inverse inverse) class-name (part-class-name attrs) style (part-style attrs)] (merge (when class-name {:class-name class-name}) (when style {:style style})))) (def part-props-memoized (memoize part-props)) (defn part [[text attrs] cursor-on] (let [attrs (update attrs :cursor #(and % @cursor-on))] [:span (part-props-memoized attrs) text])) (defn split-part-with-cursor [[text attrs] position] (let [left-chars (take position text) left-part (if (seq left-chars) [(str/join left-chars) attrs]) cursor-attrs (assoc attrs :cursor true) center-part [(nth text position) cursor-attrs] right-chars (drop (inc position) text) right-part (if (seq right-chars) [(str/join right-chars) attrs])] (remove nil? (vector left-part center-part right-part)))) (defn insert-cursor "Marks proper character in line with ':cursor true' by locating and splitting a fragment that contains the cursor position." [parts cursor-x] (loop [left [] right parts idx cursor-x] (if (seq right) (let [[text attrs :as part] (first right) len (count text)] (if (<= len idx) (recur (conj left part) (rest right) (- idx len)) (concat left (split-part-with-cursor part idx) (rest right)))) left))) (defn line [parts cursor-x cursor-on] (let [parts (if @cursor-x (insert-cursor @parts @cursor-x) @parts)] [:span.line (doall (map-indexed (fn [idx p] ^{:key idx} [part p cursor-on]) parts))])) (def named-font-sizes #{"small" "medium" "big"}) (defn terminal-class-name [font-size] (when (named-font-sizes font-size) (str "font-" font-size))) (defn terminal-style [width height font-size] (let [font-size (when-not (named-font-sizes font-size) {:font-size font-size})] (merge {:width (str width "ch") :height (str (* 1.3333333333 height) "em")} font-size))) (defn terminal [width height font-size screen cursor-on] (let [class-name (reaction (terminal-class-name @font-size)) style (reaction (terminal-style @width @height @font-size)) lines (reaction (screen/lines @screen)) line-reactions (reaction (mapv (fn [n] (reaction (get @lines n))) (range @height))) cursor (reaction (screen/cursor @screen)) cursor-x (reaction (:x @cursor)) cursor-y (reaction (:y @cursor)) cursor-visible (reaction (:visible @cursor))] (fn [] [:pre.asciinema-terminal {:class-name @class-name :style @style} (map-indexed (fn [idx parts] (let [cursor-x (reaction (and @cursor-visible (= idx @cursor-y) @cursor-x))] ^{:key idx} [line parts cursor-x cursor-on])) @line-reactions)]))) (def logo-raw-svg "<defs> <mask id=\"small-triangle-mask\"> <rect width=\"100%\" height=\"100%\" fill=\"white\"/> <polygon points=\"508.01270189221935 433.01270189221935, 208.0127018922194 259.8076211353316, 208.01270189221927 606.217782649107\" fill=\"black\"></polygon> </mask> </defs> <polygon points=\"808.0127018922194 433.01270189221935, 58.01270189221947 -1.1368683772161603e-13, 58.01270189221913 866.0254037844386\" mask=\"url(#small-triangle-mask)\" fill=\"white\"></polygon> <polyline points=\"481.2177826491071 333.0127018922194, 134.80762113533166 533.0127018922194\" stroke=\"white\" stroke-width=\"90\"></polyline>") (defn logo-play-icon [] [:svg {:version "1.1" :view-box "0 0 866.0254037844387 866.0254037844387" :class-name "icon" :dangerouslySetInnerHTML {:__html logo-raw-svg}}]) (defn play-icon [] [:svg {:version "1.1" :view-box "0 0 12 12" :class-name "icon"} [:path {:d "M1,0 L11,6 L1,12 Z"}]]) (defn pause-icon [] [:svg {:version "1.1" :view-box "0 0 12 12" :class-name "icon"} [:path {:d "M1,0 L4,0 L4,12 L1,12 Z"}] [:path {:d "M8,0 L11,0 L11,12 L8,12 Z"}]]) (defn expand-icon [] [:svg {:version "1.1" :view-box "0 0 12 12" :class-name "icon"} [:path {:d "M12,0 L7,0 L9,2 L7,4 L8,5 L10,3 L12,5 Z"}] [:path {:d "M0,12 L0,7 L2,9 L4,7 L5,8 L3,10 L5,12 Z"}]]) (defn shrink-icon [] [:svg {:version "1.1" :view-box "0 0 12 12" :class-name "icon"} [:path {:d "M7,5 L7,0 L9,2 L11,0 L12,1 L10,3 L12,5 Z"}] [:path {:d "M5,7 L0,7 L2,9 L0,11 L1,12 L3,10 L5,12 Z"}]]) (defn playback-control-button [playing? msg-ch] (let [on-click (send! msg-ch (m/->TogglePlay))] (fn [] [:span.playback-button {:on-click on-click} [(if @playing? pause-icon play-icon)]]))) (defn pad2 [number] (if (< number 10) (str "0" number) number)) (defn format-time [seconds] (let [m (.floor js/Math (/ seconds 60)) s (.floor js/Math (mod seconds 60))] (str (pad2 m) ":" (pad2 s)))) (defn elapsed-time [current-time] (format-time current-time)) (defn remaining-time [current-time total-time] (str "-" (format-time (- total-time current-time)))) (defn timer [current-time total-time] [:span.timer [:span.time-elapsed (elapsed-time @current-time)] [:span.time-remaining (remaining-time @current-time @total-time)]]) (defn fullscreen-toggle-button [] (letfn [(on-click [e] (.preventDefault e) (fullscreen/toggle (-> e .-currentTarget .-parentNode .-parentNode .-parentNode)))] (fn [] [:span.fullscreen-button {:on-click on-click} [expand-icon] [shrink-icon]]))) (defn element-local-mouse-x [e] (let [rect (-> e .-currentTarget .getBoundingClientRect)] (- (.-clientX e) (.-left rect)))) (defn click-position [e] (let [bar-width (-> e .-currentTarget .-offsetWidth) mouse-x (util/adjust-to-range (element-local-mouse-x e) 0 bar-width)] (/ mouse-x bar-width))) (defn progress-bar [progress msg-ch] (let [on-mouse-down (send-value! msg-ch (fn [e] (-> e click-position m/->Seek))) progress-str (reaction (str (* 100 @progress) "%"))] (fn [] [:span.progressbar [:span.bar {:on-mouse-down on-mouse-down} [:span.gutter [:span {:style {:width @progress-str}}]]]]))) (defn recorded-control-bar [playing? current-time total-time msg-ch] (let [progress (reaction (/ @current-time @total-time))] (fn [] [:div.control-bar [playback-control-button playing? msg-ch] [timer current-time total-time] [fullscreen-toggle-button] [progress-bar progress msg-ch]]))) (defn stream-control-bar [] [:div.control-bar.live [:span.timer "LIVE"] [fullscreen-toggle-button] [progress-bar 0 (fn [& _])]]) (defn start-overlay [msg-ch] (let [on-click (send! msg-ch (m/->TogglePlay))] (fn [] [:div.start-prompt {:on-click on-click} [:div.play-button [:div [:span [logo-play-icon]]]]]))) (defn loading-overlay [] [:div.loading [:div.loader]]) (defn player-class-name [theme-name] (str "asciinema-theme-" theme-name)) (defn has-modifiers? [dom-event] (some #(aget dom-event %) ["altKey" "shiftKey" "metaKey" "ctrlKey"])) (defn key-press->message [dom-event] (or (when-not (has-modifiers? dom-event) (case (.-key dom-event) " " (m/->TogglePlay) "f" :toggle-fullscreen "0" (m/->Seek 0.0) "1" (m/->Seek 0.1) "2" (m/->Seek 0.2) "3" (m/->Seek 0.3) "4" (m/->Seek 0.4) "5" (m/->Seek 0.5) "6" (m/->Seek 0.6) "7" (m/->Seek 0.7) "8" (m/->Seek 0.8) "9" (m/->Seek 0.9) nil)) (case (.-key dom-event) ">" (m/->SpeedUp) "<" (m/->SpeedDown) nil))) (defn key-down->message [dom-event] (when-not (has-modifiers? dom-event) (case (.-which dom-event) 37 (m/->Rewind) 39 (m/->FastForward) nil))) (defn handle-key-press [dom-event] (when-let [msg (key-press->message dom-event)] (.preventDefault dom-event) (if (= msg :toggle-fullscreen) (do (fullscreen/toggle (.-currentTarget dom-event)) nil) msg))) (defn handle-key-down [dom-event] (when-let [msg (key-down->message dom-event)] (.preventDefault dom-event) msg)) (defn title-bar [title author author-url author-img-url] (let [title-text (if title (str "\"" title "\"") "untitled")] [:span.title-bar (when author-img-url [:img {:src author-img-url}]) title-text (when author [:span " by " (if author-url [:a {:href author-url} author] author)])])) (defn activity-chan "Converts given channel into an activity indicator channel. The resulting channel emits false when there are no reads on input channel within msec, then true when new values show up on input, then false again after msec without reads on input, and so on." ([input msec] (activity-chan input msec (chan))) ([input msec output] (go-loop [] ;; wait for activity on input channel (<! input) (>! output true) ;; wait for inactivity on input channel (loop [] (let [t (timeout msec) [_ c] (alts! [input t])] (when (= c input) (recur)))) (>! output false) (recur)) output)) (defn start-message-loop! "Starts message processing loop. Updates Reagent atom with the result of applying a message to player state." [player-atom initial-channels] (let [channels (atom initial-channels)] (go-loop [] (let [[message channel] (alts! (seq @channels))] (when (nil? message) (swap! channels disj channel)) (when (satisfies? m/Update message) (swap! player-atom #(m/update-player message %))) (when (satisfies? m/ChannelSource message) (swap! channels set/union (m/get-channels message @player-atom)))) (recur)))) (defn player* [player ui-ch] (let [mouse-moves-ch (chan (dropping-buffer 1)) on-mouse-move (send! mouse-moves-ch true) on-mouse-enter (send! ui-ch (m/->ShowHud true)) on-mouse-leave (send! ui-ch (m/->ShowHud false)) on-key-press (send-value! ui-ch handle-key-press) on-key-down (send-value! ui-ch handle-key-down) loading (reaction (:loading @player)) loaded (reaction (:loaded @player)) started (reaction (or @loading @loaded)) wrapper-class-name (reaction (when (or (:show-hud @player) (not @started)) "hud")) player-class-name (reaction (player-class-name (:theme @player))) width (reaction (or (:width @player) 80)) height (reaction (or (:height @player) 24)) font-size (reaction (:font-size @player)) screen (reaction (:screen @player)) cursor-on (reaction (:cursor-on @player)) playing (reaction (:playing @player)) current-time (reaction (:current-time @player)) total-time (reaction (:duration @player)) {:keys [title <NAME> author-url author-img-url]} @player] (pipe (activity-chan mouse-moves-ch 3000 (chan 1 (map m/->ShowHud))) ui-ch) (fn [] [:div.asciinema-player-wrapper {:tab-index -1 :on-key-press on-key-press :on-key-down on-key-down :class-name @wrapper-class-name} [:div.asciinema-player {:class-name @player-class-name :on-mouse-move on-mouse-move :on-mouse-enter on-mouse-enter :on-mouse-leave on-mouse-leave} [terminal width height font-size screen cursor-on] [recorded-control-bar playing current-time total-time ui-ch] (when (or title author) [title-bar title author author-url author-img-url]) (when-not @started [start-overlay ui-ch]) (when @loading [loading-overlay])]]))) (defn player-component [player] (let [ui-ch (chan)] (fn [] (reagent/create-class {:display-name "asciinema-player" :reagent-render #(player* player ui-ch) :component-did-mount (fn [this] (let [source-ch (source/init (:source @player))] (start-message-loop! player #{ui-ch source-ch}))) :component-will-unmount (fn [this] (source/close (:source @player)))}))))
true
(ns asciinema.player.view (:require [clojure.string :as string] [clojure.set :as set] [reagent.core :as reagent] [reagent.ratom :refer-macros [reaction]] [cljs.core.async :refer [chan >! <! put! alts! timeout dropping-buffer pipe]] [asciinema.player.messages :as m] [asciinema.player.source :as source] [asciinema.player.util :as util] [asciinema.player.screen :as screen] [asciinema.player.fullscreen :as fullscreen] [clojure.string :as str]) (:require-macros [cljs.core.async.macros :refer [go-loop]])) (extend-protocol screen/Screen cljs.core/PersistentArrayMap (lines [this] (:lines this)) (cursor [this] (:cursor this))) (defn send-value! [ch f] (fn [dom-event] (when-some [msg (f dom-event)] (put! ch msg) (.stopPropagation dom-event)))) (defn send! [ch msg] (send-value! ch (fn [_] msg))) (defn indexed-color? [c] (or (number? c) (= c "fg") (= c "bg"))) (def rgb-color? vector?) (defn color-class-name [color high-intensity prefix] (when (indexed-color? color) (let [color (if (and high-intensity (< color 8)) (+ color 8) color)] (str prefix color)))) (defn part-class-name [{:keys [fg bg bold blink underline inverse italic strikethrough cursor]}] (let [fg-final (if inverse (or bg "bg") fg) bg-final (if inverse (or fg "fg") bg) fg-class (color-class-name fg-final bold "fg-") bg-class (color-class-name bg-final blink "bg-") bold-class (when bold "bright") italic-class (when italic "italic") underline-class (when underline "underline") strikethrough-class (when strikethrough "strikethrough") cursor-class (when cursor "cursor") classes (remove nil? [fg-class bg-class bold-class italic-class underline-class strikethrough-class cursor-class])] (when (seq classes) (string/join " " classes)))) (defn css-rgb [[r g b]] (str "rgb(" r "," g "," b ")")) (defn part-style [{:keys [fg bg inverse]}] (let [fg-final (if inverse bg fg) bg-final (if inverse fg bg)] (merge (when (rgb-color? fg-final) {:color (css-rgb fg-final)}) (when (rgb-color? bg-final) {:background-color (css-rgb bg-final)})))) (defn part-props [{:keys [inverse cursor] :as attrs}] (let [inverse (if cursor (not inverse) inverse) attrs (assoc attrs :inverse inverse) class-name (part-class-name attrs) style (part-style attrs)] (merge (when class-name {:class-name class-name}) (when style {:style style})))) (def part-props-memoized (memoize part-props)) (defn part [[text attrs] cursor-on] (let [attrs (update attrs :cursor #(and % @cursor-on))] [:span (part-props-memoized attrs) text])) (defn split-part-with-cursor [[text attrs] position] (let [left-chars (take position text) left-part (if (seq left-chars) [(str/join left-chars) attrs]) cursor-attrs (assoc attrs :cursor true) center-part [(nth text position) cursor-attrs] right-chars (drop (inc position) text) right-part (if (seq right-chars) [(str/join right-chars) attrs])] (remove nil? (vector left-part center-part right-part)))) (defn insert-cursor "Marks proper character in line with ':cursor true' by locating and splitting a fragment that contains the cursor position." [parts cursor-x] (loop [left [] right parts idx cursor-x] (if (seq right) (let [[text attrs :as part] (first right) len (count text)] (if (<= len idx) (recur (conj left part) (rest right) (- idx len)) (concat left (split-part-with-cursor part idx) (rest right)))) left))) (defn line [parts cursor-x cursor-on] (let [parts (if @cursor-x (insert-cursor @parts @cursor-x) @parts)] [:span.line (doall (map-indexed (fn [idx p] ^{:key idx} [part p cursor-on]) parts))])) (def named-font-sizes #{"small" "medium" "big"}) (defn terminal-class-name [font-size] (when (named-font-sizes font-size) (str "font-" font-size))) (defn terminal-style [width height font-size] (let [font-size (when-not (named-font-sizes font-size) {:font-size font-size})] (merge {:width (str width "ch") :height (str (* 1.3333333333 height) "em")} font-size))) (defn terminal [width height font-size screen cursor-on] (let [class-name (reaction (terminal-class-name @font-size)) style (reaction (terminal-style @width @height @font-size)) lines (reaction (screen/lines @screen)) line-reactions (reaction (mapv (fn [n] (reaction (get @lines n))) (range @height))) cursor (reaction (screen/cursor @screen)) cursor-x (reaction (:x @cursor)) cursor-y (reaction (:y @cursor)) cursor-visible (reaction (:visible @cursor))] (fn [] [:pre.asciinema-terminal {:class-name @class-name :style @style} (map-indexed (fn [idx parts] (let [cursor-x (reaction (and @cursor-visible (= idx @cursor-y) @cursor-x))] ^{:key idx} [line parts cursor-x cursor-on])) @line-reactions)]))) (def logo-raw-svg "<defs> <mask id=\"small-triangle-mask\"> <rect width=\"100%\" height=\"100%\" fill=\"white\"/> <polygon points=\"508.01270189221935 433.01270189221935, 208.0127018922194 259.8076211353316, 208.01270189221927 606.217782649107\" fill=\"black\"></polygon> </mask> </defs> <polygon points=\"808.0127018922194 433.01270189221935, 58.01270189221947 -1.1368683772161603e-13, 58.01270189221913 866.0254037844386\" mask=\"url(#small-triangle-mask)\" fill=\"white\"></polygon> <polyline points=\"481.2177826491071 333.0127018922194, 134.80762113533166 533.0127018922194\" stroke=\"white\" stroke-width=\"90\"></polyline>") (defn logo-play-icon [] [:svg {:version "1.1" :view-box "0 0 866.0254037844387 866.0254037844387" :class-name "icon" :dangerouslySetInnerHTML {:__html logo-raw-svg}}]) (defn play-icon [] [:svg {:version "1.1" :view-box "0 0 12 12" :class-name "icon"} [:path {:d "M1,0 L11,6 L1,12 Z"}]]) (defn pause-icon [] [:svg {:version "1.1" :view-box "0 0 12 12" :class-name "icon"} [:path {:d "M1,0 L4,0 L4,12 L1,12 Z"}] [:path {:d "M8,0 L11,0 L11,12 L8,12 Z"}]]) (defn expand-icon [] [:svg {:version "1.1" :view-box "0 0 12 12" :class-name "icon"} [:path {:d "M12,0 L7,0 L9,2 L7,4 L8,5 L10,3 L12,5 Z"}] [:path {:d "M0,12 L0,7 L2,9 L4,7 L5,8 L3,10 L5,12 Z"}]]) (defn shrink-icon [] [:svg {:version "1.1" :view-box "0 0 12 12" :class-name "icon"} [:path {:d "M7,5 L7,0 L9,2 L11,0 L12,1 L10,3 L12,5 Z"}] [:path {:d "M5,7 L0,7 L2,9 L0,11 L1,12 L3,10 L5,12 Z"}]]) (defn playback-control-button [playing? msg-ch] (let [on-click (send! msg-ch (m/->TogglePlay))] (fn [] [:span.playback-button {:on-click on-click} [(if @playing? pause-icon play-icon)]]))) (defn pad2 [number] (if (< number 10) (str "0" number) number)) (defn format-time [seconds] (let [m (.floor js/Math (/ seconds 60)) s (.floor js/Math (mod seconds 60))] (str (pad2 m) ":" (pad2 s)))) (defn elapsed-time [current-time] (format-time current-time)) (defn remaining-time [current-time total-time] (str "-" (format-time (- total-time current-time)))) (defn timer [current-time total-time] [:span.timer [:span.time-elapsed (elapsed-time @current-time)] [:span.time-remaining (remaining-time @current-time @total-time)]]) (defn fullscreen-toggle-button [] (letfn [(on-click [e] (.preventDefault e) (fullscreen/toggle (-> e .-currentTarget .-parentNode .-parentNode .-parentNode)))] (fn [] [:span.fullscreen-button {:on-click on-click} [expand-icon] [shrink-icon]]))) (defn element-local-mouse-x [e] (let [rect (-> e .-currentTarget .getBoundingClientRect)] (- (.-clientX e) (.-left rect)))) (defn click-position [e] (let [bar-width (-> e .-currentTarget .-offsetWidth) mouse-x (util/adjust-to-range (element-local-mouse-x e) 0 bar-width)] (/ mouse-x bar-width))) (defn progress-bar [progress msg-ch] (let [on-mouse-down (send-value! msg-ch (fn [e] (-> e click-position m/->Seek))) progress-str (reaction (str (* 100 @progress) "%"))] (fn [] [:span.progressbar [:span.bar {:on-mouse-down on-mouse-down} [:span.gutter [:span {:style {:width @progress-str}}]]]]))) (defn recorded-control-bar [playing? current-time total-time msg-ch] (let [progress (reaction (/ @current-time @total-time))] (fn [] [:div.control-bar [playback-control-button playing? msg-ch] [timer current-time total-time] [fullscreen-toggle-button] [progress-bar progress msg-ch]]))) (defn stream-control-bar [] [:div.control-bar.live [:span.timer "LIVE"] [fullscreen-toggle-button] [progress-bar 0 (fn [& _])]]) (defn start-overlay [msg-ch] (let [on-click (send! msg-ch (m/->TogglePlay))] (fn [] [:div.start-prompt {:on-click on-click} [:div.play-button [:div [:span [logo-play-icon]]]]]))) (defn loading-overlay [] [:div.loading [:div.loader]]) (defn player-class-name [theme-name] (str "asciinema-theme-" theme-name)) (defn has-modifiers? [dom-event] (some #(aget dom-event %) ["altKey" "shiftKey" "metaKey" "ctrlKey"])) (defn key-press->message [dom-event] (or (when-not (has-modifiers? dom-event) (case (.-key dom-event) " " (m/->TogglePlay) "f" :toggle-fullscreen "0" (m/->Seek 0.0) "1" (m/->Seek 0.1) "2" (m/->Seek 0.2) "3" (m/->Seek 0.3) "4" (m/->Seek 0.4) "5" (m/->Seek 0.5) "6" (m/->Seek 0.6) "7" (m/->Seek 0.7) "8" (m/->Seek 0.8) "9" (m/->Seek 0.9) nil)) (case (.-key dom-event) ">" (m/->SpeedUp) "<" (m/->SpeedDown) nil))) (defn key-down->message [dom-event] (when-not (has-modifiers? dom-event) (case (.-which dom-event) 37 (m/->Rewind) 39 (m/->FastForward) nil))) (defn handle-key-press [dom-event] (when-let [msg (key-press->message dom-event)] (.preventDefault dom-event) (if (= msg :toggle-fullscreen) (do (fullscreen/toggle (.-currentTarget dom-event)) nil) msg))) (defn handle-key-down [dom-event] (when-let [msg (key-down->message dom-event)] (.preventDefault dom-event) msg)) (defn title-bar [title author author-url author-img-url] (let [title-text (if title (str "\"" title "\"") "untitled")] [:span.title-bar (when author-img-url [:img {:src author-img-url}]) title-text (when author [:span " by " (if author-url [:a {:href author-url} author] author)])])) (defn activity-chan "Converts given channel into an activity indicator channel. The resulting channel emits false when there are no reads on input channel within msec, then true when new values show up on input, then false again after msec without reads on input, and so on." ([input msec] (activity-chan input msec (chan))) ([input msec output] (go-loop [] ;; wait for activity on input channel (<! input) (>! output true) ;; wait for inactivity on input channel (loop [] (let [t (timeout msec) [_ c] (alts! [input t])] (when (= c input) (recur)))) (>! output false) (recur)) output)) (defn start-message-loop! "Starts message processing loop. Updates Reagent atom with the result of applying a message to player state." [player-atom initial-channels] (let [channels (atom initial-channels)] (go-loop [] (let [[message channel] (alts! (seq @channels))] (when (nil? message) (swap! channels disj channel)) (when (satisfies? m/Update message) (swap! player-atom #(m/update-player message %))) (when (satisfies? m/ChannelSource message) (swap! channels set/union (m/get-channels message @player-atom)))) (recur)))) (defn player* [player ui-ch] (let [mouse-moves-ch (chan (dropping-buffer 1)) on-mouse-move (send! mouse-moves-ch true) on-mouse-enter (send! ui-ch (m/->ShowHud true)) on-mouse-leave (send! ui-ch (m/->ShowHud false)) on-key-press (send-value! ui-ch handle-key-press) on-key-down (send-value! ui-ch handle-key-down) loading (reaction (:loading @player)) loaded (reaction (:loaded @player)) started (reaction (or @loading @loaded)) wrapper-class-name (reaction (when (or (:show-hud @player) (not @started)) "hud")) player-class-name (reaction (player-class-name (:theme @player))) width (reaction (or (:width @player) 80)) height (reaction (or (:height @player) 24)) font-size (reaction (:font-size @player)) screen (reaction (:screen @player)) cursor-on (reaction (:cursor-on @player)) playing (reaction (:playing @player)) current-time (reaction (:current-time @player)) total-time (reaction (:duration @player)) {:keys [title PI:NAME:<NAME>END_PI author-url author-img-url]} @player] (pipe (activity-chan mouse-moves-ch 3000 (chan 1 (map m/->ShowHud))) ui-ch) (fn [] [:div.asciinema-player-wrapper {:tab-index -1 :on-key-press on-key-press :on-key-down on-key-down :class-name @wrapper-class-name} [:div.asciinema-player {:class-name @player-class-name :on-mouse-move on-mouse-move :on-mouse-enter on-mouse-enter :on-mouse-leave on-mouse-leave} [terminal width height font-size screen cursor-on] [recorded-control-bar playing current-time total-time ui-ch] (when (or title author) [title-bar title author author-url author-img-url]) (when-not @started [start-overlay ui-ch]) (when @loading [loading-overlay])]]))) (defn player-component [player] (let [ui-ch (chan)] (fn [] (reagent/create-class {:display-name "asciinema-player" :reagent-render #(player* player ui-ch) :component-did-mount (fn [this] (let [source-ch (source/init (:source @player))] (start-message-loop! player #{ui-ch source-ch}))) :component-will-unmount (fn [this] (source/close (:source @player)))}))))
[ { "context": ";; Ben Fry's Visualizing Data, Chapter 3 (Data on a Map), figu", "end": 12, "score": 0.9978318810462952, "start": 3, "tag": "NAME", "value": "Ben Fry's" }, { "context": "onverted from Processing to Quil as an exercise by Dave Liepmann\n\n(ns vdquil.chapter3.figure6\n (:use [quil.core]\n", "end": 171, "score": 0.9998788833618164, "start": 158, "tag": "NAME", "value": "Dave Liepmann" } ]
src/vdquil/chapter3/figure6.clj
Jjunior130/vdquil
33
;; Ben Fry's Visualizing Data, Chapter 3 (Data on a Map), figure 6: ;; Magnitude and positive/negative ;; Converted from Processing to Quil as an exercise by Dave Liepmann (ns vdquil.chapter3.figure6 (:use [quil.core] [vdquil.chapter3.ch3data] [vdquil.util])) (defn setup [] (background 255) (smooth) (no-stroke) (set-state! :img (load-image "resources/ch3/map.png")) (fill 192 0 0)) (defn create-ellipse [location] (let [[abbrev [x y]] location random-value (random-data abbrev) radius (if (>= random-value 0) (map-range random-value 0 (apply max (map second random-data)) 3 30) (map-range random-value 0 (apply min (map second random-data)) 3 30)) low-color (hex-to-color "#333366") high-color (hex-to-color "#EC5166")] (if (>= random-value 0) (fill low-color) (fill high-color)) (ellipse x y radius radius))) (defn draw [] (image (state :img) 0 0) (doseq [row location-data] (create-ellipse row))) (defsketch ch3_map :title "Map with opposing colors for positive/negative values and size for magnitude" :setup setup :draw draw :size [640 400])
121407
;; <NAME> Visualizing Data, Chapter 3 (Data on a Map), figure 6: ;; Magnitude and positive/negative ;; Converted from Processing to Quil as an exercise by <NAME> (ns vdquil.chapter3.figure6 (:use [quil.core] [vdquil.chapter3.ch3data] [vdquil.util])) (defn setup [] (background 255) (smooth) (no-stroke) (set-state! :img (load-image "resources/ch3/map.png")) (fill 192 0 0)) (defn create-ellipse [location] (let [[abbrev [x y]] location random-value (random-data abbrev) radius (if (>= random-value 0) (map-range random-value 0 (apply max (map second random-data)) 3 30) (map-range random-value 0 (apply min (map second random-data)) 3 30)) low-color (hex-to-color "#333366") high-color (hex-to-color "#EC5166")] (if (>= random-value 0) (fill low-color) (fill high-color)) (ellipse x y radius radius))) (defn draw [] (image (state :img) 0 0) (doseq [row location-data] (create-ellipse row))) (defsketch ch3_map :title "Map with opposing colors for positive/negative values and size for magnitude" :setup setup :draw draw :size [640 400])
true
;; PI:NAME:<NAME>END_PI Visualizing Data, Chapter 3 (Data on a Map), figure 6: ;; Magnitude and positive/negative ;; Converted from Processing to Quil as an exercise by PI:NAME:<NAME>END_PI (ns vdquil.chapter3.figure6 (:use [quil.core] [vdquil.chapter3.ch3data] [vdquil.util])) (defn setup [] (background 255) (smooth) (no-stroke) (set-state! :img (load-image "resources/ch3/map.png")) (fill 192 0 0)) (defn create-ellipse [location] (let [[abbrev [x y]] location random-value (random-data abbrev) radius (if (>= random-value 0) (map-range random-value 0 (apply max (map second random-data)) 3 30) (map-range random-value 0 (apply min (map second random-data)) 3 30)) low-color (hex-to-color "#333366") high-color (hex-to-color "#EC5166")] (if (>= random-value 0) (fill low-color) (fill high-color)) (ellipse x y radius radius))) (defn draw [] (image (state :img) 0 0) (doseq [row location-data] (create-ellipse row))) (defsketch ch3_map :title "Map with opposing colors for positive/negative values and size for magnitude" :setup setup :draw draw :size [640 400])
[ { "context": "\n [token-acc \"606645.0000 EFX\" \"24042.0000 NFX\"]]))\n (<! (e2e.dao/deploy", "end": 2023, "score": 0.7330319285392761, "start": 2008, "tag": "KEY", "value": "606645.0000 EFX" } ]
tests/e2e/proposals.cljs
jabbarn/effect-network
0
(ns e2e.proposals (:require [eos-cljs.core :as eos] [eos-cljs.node-api :refer [deploy-file]] [e2e.util :as util :refer [p-all wait]] [cljs.test :refer-macros [deftest is testing run-tests async use-fixtures]] [cljs.core.async :refer [go <!] ] [cljs.core.async.interop :refer [<p!]] [e2e.macros :refer-macros [<p-should-fail! <p-should-succeed! <p-should-fail-with! <p-may-fail! async-deftest]] e2e.token e2e.dao e2e.stake)) (def owner-acc e2e.token/owner-acc) (def acc-2 (eos/random-account "acc")) (def token-acc (eos/random-account "tkn")) (def prop-acc (eos/random-account "prop")) (def stake-acc (eos/random-account "stk")) (def dao-acc e2e.dao/dao-acc) (println "prop acc = " prop-acc) (println "acc-2 = " acc-2) (println "token acc = " token-acc) (println "stake acc = " stake-acc) (def cycle-duration-sec 1209600) (def cycle-start-date (js/Date. (- (.valueOf (js/Date.)) (* cycle-duration-sec 1e3)))) (def proposal-cost "1.0000 EFX") (def hash1 "ab58606332f813bcf6ea26f732014f49a2197d2d281cc2939e59813721ee5246") (defn eos-tx-owner [contr action args] (eos/transact contr action args [{:actor owner-acc :permission "active"}])) (use-fixtures :once ; {:before (fn [] (async done (go (<p! (p-all (eos/create-account owner-acc prop-acc) (eos/create-account owner-acc acc-2))) (<p! (eos/update-auth prop-acc "xfer" [{:permission {:actor prop-acc :permission "eosio.code"} :weight 1}])) (<p! (deploy-file prop-acc "contracts/proposals/proposals")) (<! (e2e.token/deploy-token token-acc [owner-acc token-acc prop-acc])) (<! (e2e.stake/deploy-stake stake-acc token-acc "4,EFX" "4,NFX" [[owner-acc "1056569.0000 EFX" "37276.0000 NFX"] [token-acc "606645.0000 EFX" "24042.0000 NFX"]])) (<! (e2e.dao/deploy-dao dao-acc stake-acc prop-acc token-acc "4,EFX" "4,NFX" [owner-acc token-acc acc-2])) ;; proposal needs a xfer permission that can make token transactions (<p! (eos/transact "eosio" "linkauth" {:account prop-acc :requirement "xfer" :code token-acc :type "transfer"} [{:actor prop-acc :permission "active"}])) (done)))) :after (fn [])}) (def prop-config {:cycle_duration_sec cycle-duration-sec :quorum 4 :cycle_voting_duration_sec 0 :proposal_cost {:quantity proposal-cost :contract token-acc} :dao_contract dao-acc :first_cycle_start_time (.toLocaleDateString cycle-start-date "en-US")}) (defn deploy-proposals "Deploy a basic proposal account and fill it with data for testing" ([acc] (go (try (<p! (eos/create-account owner-acc acc)) (<p! (deploy-file acc "contracts/proposals/proposals")) (<p! (eos/transact acc "init" prop-config)) (print "Deployed proposals") (catch js/Error e "Error deploying props " e))))) ;;;;;;;;;; ;; Init (async-deftest init (<p-should-fail-with! (eos/transact prop-acc "update" prop-config) "need init to update" "not yet initialized") (<p-should-succeed! (eos/transact prop-acc "init" prop-config) "can init") (<p-should-succeed! (eos/transact prop-acc "update" (assoc-in prop-config [:proposal_cost :quantity] "0.0000 EFX")) "can update after init") (let [rows (<p! (eos/get-table-rows prop-acc prop-acc "config"))] (is (= (count rows) 1)))) (def base-prop {:author owner-acc :pay [{:field_0 {:quantity "400.0000 EFX" :contract token-acc} :field_1 "2010-01-12"}] :content_hash "aa" :category 0 :cycle 0 :transaction_hash nil}) ;;;;;;;;;; ;; Proposal payments (async-deftest proposal-payment (<p! (eos/transact prop-acc "update" prop-config)) ;; note: change the content_hash to avoid duplicate transactions (<p-should-fail-with! (eos/transact prop-acc "createprop" (assoc base-prop :content_hash "ee") [{:actor owner-acc :permission "active"}]) "need a reservation" "no proposal reserved") (<p-should-fail-with! (eos-tx-owner token-acc "transfer" {:from owner-acc :to prop-acc :quantity "1.5000 EFX" :memo "proposal"}) "needs correct amount" "wrong amount") (<p-should-succeed! (eos-tx-owner token-acc "transfer" {:from owner-acc :to prop-acc :quantity proposal-cost :memo "proposal"}) "can send correct amount") (<p! (eos/transact token-acc "issue" {:to acc-2 :quantity proposal-cost :memo ""})) (<p-should-succeed! (eos/transact token-acc "transfer" {:from acc-2 :to prop-acc :quantity proposal-cost :memo "proposal"} [{:actor acc-2 :permission "active"}]) "can send correct amount twice")) (async-deftest new-proposal (<p-should-fail-with! (eos/transact prop-acc "createprop" (assoc base-prop :author prop-acc)) "need to be a dao member" "not a dao member") (<p-should-succeed! (eos/transact prop-acc "createprop" base-prop [{:actor owner-acc :permission "active"}]) "can make a proposal") (let [rows (<p! (eos/get-table-rows prop-acc prop-acc "proposal"))] (is (= (count rows) 1))) (<p-should-succeed! (eos/transact prop-acc "createprop" (assoc base-prop :content_hash "bb" :author acc-2) [{:actor acc-2 :permission "active"}]) "can make a second proposal") (let [rows (<p! (eos/get-table-rows prop-acc prop-acc "proposal"))] (is (= (count rows) 2)))) (async-deftest update-proposal (<p-should-succeed! (eos/transact prop-acc "updateprop" (assoc base-prop :id 0 :cycle 2) [{:actor owner-acc :permission "active"}]) "can update proposal") (<p-should-succeed! (eos/transact prop-acc "updateprop" (assoc base-prop :id 1 :cycle 2) [{:actor acc-2 :permission "active"}]) "can update proposal")) (defn- change-voting-duration "Helper function to change the cycle and voting duration config. This config is convenient to change during testing." [cd vd] (eos/transact prop-acc "update" (assoc prop-config :cycle_duration_sec cd :cycle_voting_duration_sec vd))) (defn create-cycle [budget] (eos/transact prop-acc "addcycle" {:start_time (.toLocaleDateString cycle-start-date "en-US") :budget [{:quantity budget :contract token-acc}]})) (defn get-config [] (.then (eos/get-table-rows prop-acc prop-acc "config") first)) (async-deftest add-cycle (<p-should-succeed! (create-cycle "326000.000 EFX")) (<p-should-succeed! (create-cycle "500.1000 EFX")) (<p-should-succeed! (create-cycle "326000.2000 EFX")) (<p-should-succeed! (create-cycle "326000.3000 EFX")) (let [{cycle "current_cycle"} (<p! (get-config))] (is (= cycle 0))) (<p-should-succeed! (eos/transact prop-acc "cycleupdate" {}) "can progress cycle") (let [{cycle "current_cycle"} (<p! (get-config))] (is (= cycle 1))) (<p! (eos/wait-block (js/Promise.resolve 1)) 2) (<p-should-succeed! (eos/transact prop-acc "cycleupdate" {}) "can progress cycle") (let [{cycle "current_cycle"} (<p! (get-config))] (is (= cycle 2)))) (async-deftest update-cycle (<p-should-fail-with! (eos/transact prop-acc "updatecycle" {:id 1 :start_time "2021-01-01 12:00:00" :budget [{:quantity (str "326000.0000 EFX") :contract token-acc}]}) "cycle must be in the future" "cycle is not in the future") (<p-should-succeed! (eos/transact prop-acc "updatecycle" {:id 3 :start_time "2021-01-01 12:00:00" :budget [{:quantity (str "326000.0000 EFX") :contract token-acc}]})) (<p-should-fail-with! (eos-tx-owner prop-acc "updatecycle" {:id 3 :start_time "2021-01-01 12:00:00" :budget [{:quantity (str "326000.0000 EFX") :contract token-acc}]}) "must be contract owner" (str "missing authority of " prop-acc))) (async-deftest vote ;; needs to be in voting period (<p-should-fail-with! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 0 :vote_type 0}) "can vote on own proposal" "not in voting period") (<p! (eos/transact prop-acc "update" (assoc prop-config :cycle_duration_sec (inc 9e6) :cycle_voting_duration_sec 9e6))) (<p-should-succeed! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 0 :vote_type 0}) "can vote on own proposal") (<p-should-succeed! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 0 :vote_type 1}) "can update vote") (<p-should-succeed! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 0 :vote_type 2}) "can update vote twice") (<p! (eos/wait-block (js/Promise.resolve 42) 2)) (<p! (eos/transact prop-acc "addvote" {:voter token-acc :prop_id 0 :vote_type 1} [{:actor token-acc :permission "active"}]) "multiple accounts can vote") (let [rows (<p! (eos/get-table-rows prop-acc prop-acc "proposal")) r (->> rows (filter #(= (% "id") 0)) first)] (is (= (get-in r ["vote_counts" 0 "value"]) 0)) (is (= (get-in r ["vote_counts" 1 "value"]) 24042)) (is (= (get-in r ["vote_counts" 2 "value"]) 37276))) (<p! (eos/wait-block (js/Promise.resolve 42) 2)) (<p! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 1 :vote_type 1}) "multiple accounts can vote") (<p! (eos/transact dao-acc "newmemterms" {:hash hash1})) (<p-should-fail-with! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 1 :vote_type 3}) "needs latest terms accepted" "agreed terms are not the latest") (<p! (eos/transact dao-acc "memberreg" {:account acc-2 :agreedterms hash1} [{:actor acc-2 :permission "active"}]))) (async-deftest process-cycle (<p-should-fail-with! (eos-tx-owner prop-acc "processcycle" {:account owner-acc :id 2}) "cycle needs to be in the past" "cycle is not in the past") (<p! (eos/transact prop-acc "update" (assoc prop-config :cycle_duration_sec 1))) (<p! (eos/transact prop-acc "cycleupdate" {})) (<p-should-succeed! (eos-tx-owner prop-acc "processcycle" {:account owner-acc :id 2}) "can finalize cycle")) (async-deftest execute-proposal (<p-should-succeed! (eos/transact prop-acc "executeprop" {:id 1}) "can execute proposal") (let [rows (<p! (eos/get-table-rows token-acc acc-2 "accounts"))] (is (= (-> rows first (get "balance")) "400.0000 EFX") "executed proposal gets paid")) (<p! (wait 500)) (<p-should-fail-with! (eos/transact prop-acc "executeprop" {:id 1}) "can't execute proposal twice" "proposal is not accepted") (<p-should-fail-with! (eos/transact prop-acc "executeprop" {:id 0}) "can't execute rejected proposal" "proposal is not accepted")) (async-deftest reject-proposal (<p! (eos/transact token-acc "issue" {:to acc-2 :quantity proposal-cost :memo ""})) (<p! (eos/transact token-acc "transfer" {:from acc-2 :to prop-acc :quantity proposal-cost :memo "proposal"} [{:actor acc-2 :permission "active"}])) (<p! (eos/transact prop-acc "createprop" (assoc base-prop :content_hash "cc" :author acc-2 :cycle 4) [{:actor acc-2 :permission "active"}])) (<p-should-fail-with! (eos-tx-owner prop-acc "hgrejectprop" {:id 2}) "needs self signature" (str "missing authority of " prop-acc)) (<p! (eos/transact prop-acc "cycleupdate" {})) (<p! (change-voting-duration (inc 9e6) 9e6)) (<p-should-fail-with! (eos/transact prop-acc "hgrejectprop" {:id 2}) "voting period must have passed" "voting period not ended") (<p! (change-voting-duration 1 0)) (<p-should-succeed! (eos/transact prop-acc "hgrejectprop" {:id 2}))) (defn -main [& args] (run-tests))
90584
(ns e2e.proposals (:require [eos-cljs.core :as eos] [eos-cljs.node-api :refer [deploy-file]] [e2e.util :as util :refer [p-all wait]] [cljs.test :refer-macros [deftest is testing run-tests async use-fixtures]] [cljs.core.async :refer [go <!] ] [cljs.core.async.interop :refer [<p!]] [e2e.macros :refer-macros [<p-should-fail! <p-should-succeed! <p-should-fail-with! <p-may-fail! async-deftest]] e2e.token e2e.dao e2e.stake)) (def owner-acc e2e.token/owner-acc) (def acc-2 (eos/random-account "acc")) (def token-acc (eos/random-account "tkn")) (def prop-acc (eos/random-account "prop")) (def stake-acc (eos/random-account "stk")) (def dao-acc e2e.dao/dao-acc) (println "prop acc = " prop-acc) (println "acc-2 = " acc-2) (println "token acc = " token-acc) (println "stake acc = " stake-acc) (def cycle-duration-sec 1209600) (def cycle-start-date (js/Date. (- (.valueOf (js/Date.)) (* cycle-duration-sec 1e3)))) (def proposal-cost "1.0000 EFX") (def hash1 "ab58606332f813bcf6ea26f732014f49a2197d2d281cc2939e59813721ee5246") (defn eos-tx-owner [contr action args] (eos/transact contr action args [{:actor owner-acc :permission "active"}])) (use-fixtures :once ; {:before (fn [] (async done (go (<p! (p-all (eos/create-account owner-acc prop-acc) (eos/create-account owner-acc acc-2))) (<p! (eos/update-auth prop-acc "xfer" [{:permission {:actor prop-acc :permission "eosio.code"} :weight 1}])) (<p! (deploy-file prop-acc "contracts/proposals/proposals")) (<! (e2e.token/deploy-token token-acc [owner-acc token-acc prop-acc])) (<! (e2e.stake/deploy-stake stake-acc token-acc "4,EFX" "4,NFX" [[owner-acc "1056569.0000 EFX" "37276.0000 NFX"] [token-acc "<KEY>" "24042.0000 NFX"]])) (<! (e2e.dao/deploy-dao dao-acc stake-acc prop-acc token-acc "4,EFX" "4,NFX" [owner-acc token-acc acc-2])) ;; proposal needs a xfer permission that can make token transactions (<p! (eos/transact "eosio" "linkauth" {:account prop-acc :requirement "xfer" :code token-acc :type "transfer"} [{:actor prop-acc :permission "active"}])) (done)))) :after (fn [])}) (def prop-config {:cycle_duration_sec cycle-duration-sec :quorum 4 :cycle_voting_duration_sec 0 :proposal_cost {:quantity proposal-cost :contract token-acc} :dao_contract dao-acc :first_cycle_start_time (.toLocaleDateString cycle-start-date "en-US")}) (defn deploy-proposals "Deploy a basic proposal account and fill it with data for testing" ([acc] (go (try (<p! (eos/create-account owner-acc acc)) (<p! (deploy-file acc "contracts/proposals/proposals")) (<p! (eos/transact acc "init" prop-config)) (print "Deployed proposals") (catch js/Error e "Error deploying props " e))))) ;;;;;;;;;; ;; Init (async-deftest init (<p-should-fail-with! (eos/transact prop-acc "update" prop-config) "need init to update" "not yet initialized") (<p-should-succeed! (eos/transact prop-acc "init" prop-config) "can init") (<p-should-succeed! (eos/transact prop-acc "update" (assoc-in prop-config [:proposal_cost :quantity] "0.0000 EFX")) "can update after init") (let [rows (<p! (eos/get-table-rows prop-acc prop-acc "config"))] (is (= (count rows) 1)))) (def base-prop {:author owner-acc :pay [{:field_0 {:quantity "400.0000 EFX" :contract token-acc} :field_1 "2010-01-12"}] :content_hash "aa" :category 0 :cycle 0 :transaction_hash nil}) ;;;;;;;;;; ;; Proposal payments (async-deftest proposal-payment (<p! (eos/transact prop-acc "update" prop-config)) ;; note: change the content_hash to avoid duplicate transactions (<p-should-fail-with! (eos/transact prop-acc "createprop" (assoc base-prop :content_hash "ee") [{:actor owner-acc :permission "active"}]) "need a reservation" "no proposal reserved") (<p-should-fail-with! (eos-tx-owner token-acc "transfer" {:from owner-acc :to prop-acc :quantity "1.5000 EFX" :memo "proposal"}) "needs correct amount" "wrong amount") (<p-should-succeed! (eos-tx-owner token-acc "transfer" {:from owner-acc :to prop-acc :quantity proposal-cost :memo "proposal"}) "can send correct amount") (<p! (eos/transact token-acc "issue" {:to acc-2 :quantity proposal-cost :memo ""})) (<p-should-succeed! (eos/transact token-acc "transfer" {:from acc-2 :to prop-acc :quantity proposal-cost :memo "proposal"} [{:actor acc-2 :permission "active"}]) "can send correct amount twice")) (async-deftest new-proposal (<p-should-fail-with! (eos/transact prop-acc "createprop" (assoc base-prop :author prop-acc)) "need to be a dao member" "not a dao member") (<p-should-succeed! (eos/transact prop-acc "createprop" base-prop [{:actor owner-acc :permission "active"}]) "can make a proposal") (let [rows (<p! (eos/get-table-rows prop-acc prop-acc "proposal"))] (is (= (count rows) 1))) (<p-should-succeed! (eos/transact prop-acc "createprop" (assoc base-prop :content_hash "bb" :author acc-2) [{:actor acc-2 :permission "active"}]) "can make a second proposal") (let [rows (<p! (eos/get-table-rows prop-acc prop-acc "proposal"))] (is (= (count rows) 2)))) (async-deftest update-proposal (<p-should-succeed! (eos/transact prop-acc "updateprop" (assoc base-prop :id 0 :cycle 2) [{:actor owner-acc :permission "active"}]) "can update proposal") (<p-should-succeed! (eos/transact prop-acc "updateprop" (assoc base-prop :id 1 :cycle 2) [{:actor acc-2 :permission "active"}]) "can update proposal")) (defn- change-voting-duration "Helper function to change the cycle and voting duration config. This config is convenient to change during testing." [cd vd] (eos/transact prop-acc "update" (assoc prop-config :cycle_duration_sec cd :cycle_voting_duration_sec vd))) (defn create-cycle [budget] (eos/transact prop-acc "addcycle" {:start_time (.toLocaleDateString cycle-start-date "en-US") :budget [{:quantity budget :contract token-acc}]})) (defn get-config [] (.then (eos/get-table-rows prop-acc prop-acc "config") first)) (async-deftest add-cycle (<p-should-succeed! (create-cycle "326000.000 EFX")) (<p-should-succeed! (create-cycle "500.1000 EFX")) (<p-should-succeed! (create-cycle "326000.2000 EFX")) (<p-should-succeed! (create-cycle "326000.3000 EFX")) (let [{cycle "current_cycle"} (<p! (get-config))] (is (= cycle 0))) (<p-should-succeed! (eos/transact prop-acc "cycleupdate" {}) "can progress cycle") (let [{cycle "current_cycle"} (<p! (get-config))] (is (= cycle 1))) (<p! (eos/wait-block (js/Promise.resolve 1)) 2) (<p-should-succeed! (eos/transact prop-acc "cycleupdate" {}) "can progress cycle") (let [{cycle "current_cycle"} (<p! (get-config))] (is (= cycle 2)))) (async-deftest update-cycle (<p-should-fail-with! (eos/transact prop-acc "updatecycle" {:id 1 :start_time "2021-01-01 12:00:00" :budget [{:quantity (str "326000.0000 EFX") :contract token-acc}]}) "cycle must be in the future" "cycle is not in the future") (<p-should-succeed! (eos/transact prop-acc "updatecycle" {:id 3 :start_time "2021-01-01 12:00:00" :budget [{:quantity (str "326000.0000 EFX") :contract token-acc}]})) (<p-should-fail-with! (eos-tx-owner prop-acc "updatecycle" {:id 3 :start_time "2021-01-01 12:00:00" :budget [{:quantity (str "326000.0000 EFX") :contract token-acc}]}) "must be contract owner" (str "missing authority of " prop-acc))) (async-deftest vote ;; needs to be in voting period (<p-should-fail-with! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 0 :vote_type 0}) "can vote on own proposal" "not in voting period") (<p! (eos/transact prop-acc "update" (assoc prop-config :cycle_duration_sec (inc 9e6) :cycle_voting_duration_sec 9e6))) (<p-should-succeed! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 0 :vote_type 0}) "can vote on own proposal") (<p-should-succeed! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 0 :vote_type 1}) "can update vote") (<p-should-succeed! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 0 :vote_type 2}) "can update vote twice") (<p! (eos/wait-block (js/Promise.resolve 42) 2)) (<p! (eos/transact prop-acc "addvote" {:voter token-acc :prop_id 0 :vote_type 1} [{:actor token-acc :permission "active"}]) "multiple accounts can vote") (let [rows (<p! (eos/get-table-rows prop-acc prop-acc "proposal")) r (->> rows (filter #(= (% "id") 0)) first)] (is (= (get-in r ["vote_counts" 0 "value"]) 0)) (is (= (get-in r ["vote_counts" 1 "value"]) 24042)) (is (= (get-in r ["vote_counts" 2 "value"]) 37276))) (<p! (eos/wait-block (js/Promise.resolve 42) 2)) (<p! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 1 :vote_type 1}) "multiple accounts can vote") (<p! (eos/transact dao-acc "newmemterms" {:hash hash1})) (<p-should-fail-with! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 1 :vote_type 3}) "needs latest terms accepted" "agreed terms are not the latest") (<p! (eos/transact dao-acc "memberreg" {:account acc-2 :agreedterms hash1} [{:actor acc-2 :permission "active"}]))) (async-deftest process-cycle (<p-should-fail-with! (eos-tx-owner prop-acc "processcycle" {:account owner-acc :id 2}) "cycle needs to be in the past" "cycle is not in the past") (<p! (eos/transact prop-acc "update" (assoc prop-config :cycle_duration_sec 1))) (<p! (eos/transact prop-acc "cycleupdate" {})) (<p-should-succeed! (eos-tx-owner prop-acc "processcycle" {:account owner-acc :id 2}) "can finalize cycle")) (async-deftest execute-proposal (<p-should-succeed! (eos/transact prop-acc "executeprop" {:id 1}) "can execute proposal") (let [rows (<p! (eos/get-table-rows token-acc acc-2 "accounts"))] (is (= (-> rows first (get "balance")) "400.0000 EFX") "executed proposal gets paid")) (<p! (wait 500)) (<p-should-fail-with! (eos/transact prop-acc "executeprop" {:id 1}) "can't execute proposal twice" "proposal is not accepted") (<p-should-fail-with! (eos/transact prop-acc "executeprop" {:id 0}) "can't execute rejected proposal" "proposal is not accepted")) (async-deftest reject-proposal (<p! (eos/transact token-acc "issue" {:to acc-2 :quantity proposal-cost :memo ""})) (<p! (eos/transact token-acc "transfer" {:from acc-2 :to prop-acc :quantity proposal-cost :memo "proposal"} [{:actor acc-2 :permission "active"}])) (<p! (eos/transact prop-acc "createprop" (assoc base-prop :content_hash "cc" :author acc-2 :cycle 4) [{:actor acc-2 :permission "active"}])) (<p-should-fail-with! (eos-tx-owner prop-acc "hgrejectprop" {:id 2}) "needs self signature" (str "missing authority of " prop-acc)) (<p! (eos/transact prop-acc "cycleupdate" {})) (<p! (change-voting-duration (inc 9e6) 9e6)) (<p-should-fail-with! (eos/transact prop-acc "hgrejectprop" {:id 2}) "voting period must have passed" "voting period not ended") (<p! (change-voting-duration 1 0)) (<p-should-succeed! (eos/transact prop-acc "hgrejectprop" {:id 2}))) (defn -main [& args] (run-tests))
true
(ns e2e.proposals (:require [eos-cljs.core :as eos] [eos-cljs.node-api :refer [deploy-file]] [e2e.util :as util :refer [p-all wait]] [cljs.test :refer-macros [deftest is testing run-tests async use-fixtures]] [cljs.core.async :refer [go <!] ] [cljs.core.async.interop :refer [<p!]] [e2e.macros :refer-macros [<p-should-fail! <p-should-succeed! <p-should-fail-with! <p-may-fail! async-deftest]] e2e.token e2e.dao e2e.stake)) (def owner-acc e2e.token/owner-acc) (def acc-2 (eos/random-account "acc")) (def token-acc (eos/random-account "tkn")) (def prop-acc (eos/random-account "prop")) (def stake-acc (eos/random-account "stk")) (def dao-acc e2e.dao/dao-acc) (println "prop acc = " prop-acc) (println "acc-2 = " acc-2) (println "token acc = " token-acc) (println "stake acc = " stake-acc) (def cycle-duration-sec 1209600) (def cycle-start-date (js/Date. (- (.valueOf (js/Date.)) (* cycle-duration-sec 1e3)))) (def proposal-cost "1.0000 EFX") (def hash1 "ab58606332f813bcf6ea26f732014f49a2197d2d281cc2939e59813721ee5246") (defn eos-tx-owner [contr action args] (eos/transact contr action args [{:actor owner-acc :permission "active"}])) (use-fixtures :once ; {:before (fn [] (async done (go (<p! (p-all (eos/create-account owner-acc prop-acc) (eos/create-account owner-acc acc-2))) (<p! (eos/update-auth prop-acc "xfer" [{:permission {:actor prop-acc :permission "eosio.code"} :weight 1}])) (<p! (deploy-file prop-acc "contracts/proposals/proposals")) (<! (e2e.token/deploy-token token-acc [owner-acc token-acc prop-acc])) (<! (e2e.stake/deploy-stake stake-acc token-acc "4,EFX" "4,NFX" [[owner-acc "1056569.0000 EFX" "37276.0000 NFX"] [token-acc "PI:KEY:<KEY>END_PI" "24042.0000 NFX"]])) (<! (e2e.dao/deploy-dao dao-acc stake-acc prop-acc token-acc "4,EFX" "4,NFX" [owner-acc token-acc acc-2])) ;; proposal needs a xfer permission that can make token transactions (<p! (eos/transact "eosio" "linkauth" {:account prop-acc :requirement "xfer" :code token-acc :type "transfer"} [{:actor prop-acc :permission "active"}])) (done)))) :after (fn [])}) (def prop-config {:cycle_duration_sec cycle-duration-sec :quorum 4 :cycle_voting_duration_sec 0 :proposal_cost {:quantity proposal-cost :contract token-acc} :dao_contract dao-acc :first_cycle_start_time (.toLocaleDateString cycle-start-date "en-US")}) (defn deploy-proposals "Deploy a basic proposal account and fill it with data for testing" ([acc] (go (try (<p! (eos/create-account owner-acc acc)) (<p! (deploy-file acc "contracts/proposals/proposals")) (<p! (eos/transact acc "init" prop-config)) (print "Deployed proposals") (catch js/Error e "Error deploying props " e))))) ;;;;;;;;;; ;; Init (async-deftest init (<p-should-fail-with! (eos/transact prop-acc "update" prop-config) "need init to update" "not yet initialized") (<p-should-succeed! (eos/transact prop-acc "init" prop-config) "can init") (<p-should-succeed! (eos/transact prop-acc "update" (assoc-in prop-config [:proposal_cost :quantity] "0.0000 EFX")) "can update after init") (let [rows (<p! (eos/get-table-rows prop-acc prop-acc "config"))] (is (= (count rows) 1)))) (def base-prop {:author owner-acc :pay [{:field_0 {:quantity "400.0000 EFX" :contract token-acc} :field_1 "2010-01-12"}] :content_hash "aa" :category 0 :cycle 0 :transaction_hash nil}) ;;;;;;;;;; ;; Proposal payments (async-deftest proposal-payment (<p! (eos/transact prop-acc "update" prop-config)) ;; note: change the content_hash to avoid duplicate transactions (<p-should-fail-with! (eos/transact prop-acc "createprop" (assoc base-prop :content_hash "ee") [{:actor owner-acc :permission "active"}]) "need a reservation" "no proposal reserved") (<p-should-fail-with! (eos-tx-owner token-acc "transfer" {:from owner-acc :to prop-acc :quantity "1.5000 EFX" :memo "proposal"}) "needs correct amount" "wrong amount") (<p-should-succeed! (eos-tx-owner token-acc "transfer" {:from owner-acc :to prop-acc :quantity proposal-cost :memo "proposal"}) "can send correct amount") (<p! (eos/transact token-acc "issue" {:to acc-2 :quantity proposal-cost :memo ""})) (<p-should-succeed! (eos/transact token-acc "transfer" {:from acc-2 :to prop-acc :quantity proposal-cost :memo "proposal"} [{:actor acc-2 :permission "active"}]) "can send correct amount twice")) (async-deftest new-proposal (<p-should-fail-with! (eos/transact prop-acc "createprop" (assoc base-prop :author prop-acc)) "need to be a dao member" "not a dao member") (<p-should-succeed! (eos/transact prop-acc "createprop" base-prop [{:actor owner-acc :permission "active"}]) "can make a proposal") (let [rows (<p! (eos/get-table-rows prop-acc prop-acc "proposal"))] (is (= (count rows) 1))) (<p-should-succeed! (eos/transact prop-acc "createprop" (assoc base-prop :content_hash "bb" :author acc-2) [{:actor acc-2 :permission "active"}]) "can make a second proposal") (let [rows (<p! (eos/get-table-rows prop-acc prop-acc "proposal"))] (is (= (count rows) 2)))) (async-deftest update-proposal (<p-should-succeed! (eos/transact prop-acc "updateprop" (assoc base-prop :id 0 :cycle 2) [{:actor owner-acc :permission "active"}]) "can update proposal") (<p-should-succeed! (eos/transact prop-acc "updateprop" (assoc base-prop :id 1 :cycle 2) [{:actor acc-2 :permission "active"}]) "can update proposal")) (defn- change-voting-duration "Helper function to change the cycle and voting duration config. This config is convenient to change during testing." [cd vd] (eos/transact prop-acc "update" (assoc prop-config :cycle_duration_sec cd :cycle_voting_duration_sec vd))) (defn create-cycle [budget] (eos/transact prop-acc "addcycle" {:start_time (.toLocaleDateString cycle-start-date "en-US") :budget [{:quantity budget :contract token-acc}]})) (defn get-config [] (.then (eos/get-table-rows prop-acc prop-acc "config") first)) (async-deftest add-cycle (<p-should-succeed! (create-cycle "326000.000 EFX")) (<p-should-succeed! (create-cycle "500.1000 EFX")) (<p-should-succeed! (create-cycle "326000.2000 EFX")) (<p-should-succeed! (create-cycle "326000.3000 EFX")) (let [{cycle "current_cycle"} (<p! (get-config))] (is (= cycle 0))) (<p-should-succeed! (eos/transact prop-acc "cycleupdate" {}) "can progress cycle") (let [{cycle "current_cycle"} (<p! (get-config))] (is (= cycle 1))) (<p! (eos/wait-block (js/Promise.resolve 1)) 2) (<p-should-succeed! (eos/transact prop-acc "cycleupdate" {}) "can progress cycle") (let [{cycle "current_cycle"} (<p! (get-config))] (is (= cycle 2)))) (async-deftest update-cycle (<p-should-fail-with! (eos/transact prop-acc "updatecycle" {:id 1 :start_time "2021-01-01 12:00:00" :budget [{:quantity (str "326000.0000 EFX") :contract token-acc}]}) "cycle must be in the future" "cycle is not in the future") (<p-should-succeed! (eos/transact prop-acc "updatecycle" {:id 3 :start_time "2021-01-01 12:00:00" :budget [{:quantity (str "326000.0000 EFX") :contract token-acc}]})) (<p-should-fail-with! (eos-tx-owner prop-acc "updatecycle" {:id 3 :start_time "2021-01-01 12:00:00" :budget [{:quantity (str "326000.0000 EFX") :contract token-acc}]}) "must be contract owner" (str "missing authority of " prop-acc))) (async-deftest vote ;; needs to be in voting period (<p-should-fail-with! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 0 :vote_type 0}) "can vote on own proposal" "not in voting period") (<p! (eos/transact prop-acc "update" (assoc prop-config :cycle_duration_sec (inc 9e6) :cycle_voting_duration_sec 9e6))) (<p-should-succeed! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 0 :vote_type 0}) "can vote on own proposal") (<p-should-succeed! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 0 :vote_type 1}) "can update vote") (<p-should-succeed! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 0 :vote_type 2}) "can update vote twice") (<p! (eos/wait-block (js/Promise.resolve 42) 2)) (<p! (eos/transact prop-acc "addvote" {:voter token-acc :prop_id 0 :vote_type 1} [{:actor token-acc :permission "active"}]) "multiple accounts can vote") (let [rows (<p! (eos/get-table-rows prop-acc prop-acc "proposal")) r (->> rows (filter #(= (% "id") 0)) first)] (is (= (get-in r ["vote_counts" 0 "value"]) 0)) (is (= (get-in r ["vote_counts" 1 "value"]) 24042)) (is (= (get-in r ["vote_counts" 2 "value"]) 37276))) (<p! (eos/wait-block (js/Promise.resolve 42) 2)) (<p! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 1 :vote_type 1}) "multiple accounts can vote") (<p! (eos/transact dao-acc "newmemterms" {:hash hash1})) (<p-should-fail-with! (eos-tx-owner prop-acc "addvote" {:voter owner-acc :prop_id 1 :vote_type 3}) "needs latest terms accepted" "agreed terms are not the latest") (<p! (eos/transact dao-acc "memberreg" {:account acc-2 :agreedterms hash1} [{:actor acc-2 :permission "active"}]))) (async-deftest process-cycle (<p-should-fail-with! (eos-tx-owner prop-acc "processcycle" {:account owner-acc :id 2}) "cycle needs to be in the past" "cycle is not in the past") (<p! (eos/transact prop-acc "update" (assoc prop-config :cycle_duration_sec 1))) (<p! (eos/transact prop-acc "cycleupdate" {})) (<p-should-succeed! (eos-tx-owner prop-acc "processcycle" {:account owner-acc :id 2}) "can finalize cycle")) (async-deftest execute-proposal (<p-should-succeed! (eos/transact prop-acc "executeprop" {:id 1}) "can execute proposal") (let [rows (<p! (eos/get-table-rows token-acc acc-2 "accounts"))] (is (= (-> rows first (get "balance")) "400.0000 EFX") "executed proposal gets paid")) (<p! (wait 500)) (<p-should-fail-with! (eos/transact prop-acc "executeprop" {:id 1}) "can't execute proposal twice" "proposal is not accepted") (<p-should-fail-with! (eos/transact prop-acc "executeprop" {:id 0}) "can't execute rejected proposal" "proposal is not accepted")) (async-deftest reject-proposal (<p! (eos/transact token-acc "issue" {:to acc-2 :quantity proposal-cost :memo ""})) (<p! (eos/transact token-acc "transfer" {:from acc-2 :to prop-acc :quantity proposal-cost :memo "proposal"} [{:actor acc-2 :permission "active"}])) (<p! (eos/transact prop-acc "createprop" (assoc base-prop :content_hash "cc" :author acc-2 :cycle 4) [{:actor acc-2 :permission "active"}])) (<p-should-fail-with! (eos-tx-owner prop-acc "hgrejectprop" {:id 2}) "needs self signature" (str "missing authority of " prop-acc)) (<p! (eos/transact prop-acc "cycleupdate" {})) (<p! (change-voting-duration (inc 9e6) 9e6)) (<p-should-fail-with! (eos/transact prop-acc "hgrejectprop" {:id 2}) "voting period must have passed" "voting period not ended") (<p! (change-voting-duration 1 0)) (<p-should-succeed! (eos/transact prop-acc "hgrejectprop" {:id 2}))) (defn -main [& args] (run-tests))
[ { "context": "nitial-data\n [{:db/id -1\n :author/name \"Lew Tolstoj\"}\n {:db/id -2\n :author/name \"Henryk Si", "end": 145, "score": 0.9998791813850403, "start": 134, "tag": "NAME", "value": "Lew Tolstoj" }, { "context": "w Tolstoj\"}\n {:db/id -2\n :author/name \"Henryk Sienkiewicz\"}])\n\n(defonce conn (let [conn (ds/create-conn sch", "end": 204, "score": 0.9998649954795837, "start": 186, "tag": "NAME", "value": "Henryk Sienkiewicz" } ]
src/cljs/reitit_db_fun/db.cljs
rotaliator/reitit-db-fun
7
(ns reitit-db-fun.db (:require [datascript.core :as ds])) (def schema {}) (def initial-data [{:db/id -1 :author/name "Lew Tolstoj"} {:db/id -2 :author/name "Henryk Sienkiewicz"}]) (defonce conn (let [conn (ds/create-conn schema)] (ds/transact! conn initial-data) conn)) (defn- add-db-add "dodaje :db/add do datomów.... TODO TOFIX" [datoms] (into [] (map (partial concat [:db/add])) datoms)) (defn save-datoms! [datoms] (ds/transact! conn (add-db-add datoms))) (comment (ds/datoms @conn :eavt) )
64590
(ns reitit-db-fun.db (:require [datascript.core :as ds])) (def schema {}) (def initial-data [{:db/id -1 :author/name "<NAME>"} {:db/id -2 :author/name "<NAME>"}]) (defonce conn (let [conn (ds/create-conn schema)] (ds/transact! conn initial-data) conn)) (defn- add-db-add "dodaje :db/add do datomów.... TODO TOFIX" [datoms] (into [] (map (partial concat [:db/add])) datoms)) (defn save-datoms! [datoms] (ds/transact! conn (add-db-add datoms))) (comment (ds/datoms @conn :eavt) )
true
(ns reitit-db-fun.db (:require [datascript.core :as ds])) (def schema {}) (def initial-data [{:db/id -1 :author/name "PI:NAME:<NAME>END_PI"} {:db/id -2 :author/name "PI:NAME:<NAME>END_PI"}]) (defonce conn (let [conn (ds/create-conn schema)] (ds/transact! conn initial-data) conn)) (defn- add-db-add "dodaje :db/add do datomów.... TODO TOFIX" [datoms] (into [] (map (partial concat [:db/add])) datoms)) (defn save-datoms! [datoms] (ds/transact! conn (add-db-add datoms))) (comment (ds/datoms @conn :eavt) )
[ { "context": "e.org/legal/epl-v10.html\"}\n :maintainer {:email \"open@trawler.io\"}\n :dependencies [[org.clojure/clojure \"1.8.0\"]\n", "end": 318, "score": 0.9999275207519531, "start": 303, "tag": "EMAIL", "value": "open@trawler.io" } ]
trawler.shipper/project.clj
atowndata/trawler
2
(defproject org.atown.trawler.shipper "0.0.1" :slug "trawler-shipper" :description "The log shipper for the Trawler log monitoring system" :url "https://www.trawler.io" :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :maintainer {:email "open@trawler.io"} :dependencies [[org.clojure/clojure "1.8.0"] [cprop "0.1.10"] [mount "0.1.11"] [org.clojure/core.async "0.3.443"] [org.clojure/tools.cli "0.3.5"] [org.clojure/tools.logging "0.3.1"] [cheshire "5.7.1"] [ch.qos.logback/logback-classic "1.1.3"] [hawk "0.2.11"] [com.taoensso/carmine "2.16.0"] [org.clojure/java.jdbc "0.6.1"] [me.raynes/fs "1.4.6"] [com.mchange/c3p0 "0.9.5.2"] [com.h2database/h2 "1.3.170"] [org.yaml/snakeyaml "1.18"] [org.clojure/tools.nrepl "0.2.12"]] :main org.atown.trawler.shipper.core :min-lein-version "2.0.0" :jvm-opts ["-server" "-Dconf=.lein-env"] :resource-paths ["resources"] :target-path "target/%s/" :plugins [[lein-cprop "1.0.3"] [lein-rpm "0.0.6" :exclusions [org.apache.maven/maven-plugin-api org.codehaus.plexus/plexus-container-default org.codehaus.plexus/plexus-utils org.clojure/clojure classworlds]] ; for lein-rpm [org.apache.maven/maven-plugin-api "2.0"] [org.codehaus.plexus/plexus-container-default "1.0-alpha-9-stable-1"] [org.codehaus.plexus/plexus-utils "1.5.15"] [classworlds "1.1"] ] :profiles {:uberjar {:omit-source true :aot :all :uberjar-name "trawler-shipper.jar" :source-paths ["env/prod/clj"] :resource-paths ["env/prod/resources"]} :dev [:project/dev :profiles/dev] :test [:project/dev :project/test :profiles/test] :project/dev {:dependencies [[prone "1.1.4"] [ring/ring-mock "0.3.0"] [ring/ring-devel "1.6.1"] [pjstadig/humane-test-output "0.8.1"]] :plugins [[com.jakemccrary/lein-test-refresh "0.19.0"]] :source-paths ["env/dev/clj"] :resource-paths ["env/dev/resources"] :repl-options {:init-ns user} :injections [(require 'pjstadig.humane-test-output) (pjstadig.humane-test-output/activate!)]} :project/test {:resource-paths ["env/test/resources"]} :profiles/dev {} :profiles/test {}})
42027
(defproject org.atown.trawler.shipper "0.0.1" :slug "trawler-shipper" :description "The log shipper for the Trawler log monitoring system" :url "https://www.trawler.io" :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :maintainer {:email "<EMAIL>"} :dependencies [[org.clojure/clojure "1.8.0"] [cprop "0.1.10"] [mount "0.1.11"] [org.clojure/core.async "0.3.443"] [org.clojure/tools.cli "0.3.5"] [org.clojure/tools.logging "0.3.1"] [cheshire "5.7.1"] [ch.qos.logback/logback-classic "1.1.3"] [hawk "0.2.11"] [com.taoensso/carmine "2.16.0"] [org.clojure/java.jdbc "0.6.1"] [me.raynes/fs "1.4.6"] [com.mchange/c3p0 "0.9.5.2"] [com.h2database/h2 "1.3.170"] [org.yaml/snakeyaml "1.18"] [org.clojure/tools.nrepl "0.2.12"]] :main org.atown.trawler.shipper.core :min-lein-version "2.0.0" :jvm-opts ["-server" "-Dconf=.lein-env"] :resource-paths ["resources"] :target-path "target/%s/" :plugins [[lein-cprop "1.0.3"] [lein-rpm "0.0.6" :exclusions [org.apache.maven/maven-plugin-api org.codehaus.plexus/plexus-container-default org.codehaus.plexus/plexus-utils org.clojure/clojure classworlds]] ; for lein-rpm [org.apache.maven/maven-plugin-api "2.0"] [org.codehaus.plexus/plexus-container-default "1.0-alpha-9-stable-1"] [org.codehaus.plexus/plexus-utils "1.5.15"] [classworlds "1.1"] ] :profiles {:uberjar {:omit-source true :aot :all :uberjar-name "trawler-shipper.jar" :source-paths ["env/prod/clj"] :resource-paths ["env/prod/resources"]} :dev [:project/dev :profiles/dev] :test [:project/dev :project/test :profiles/test] :project/dev {:dependencies [[prone "1.1.4"] [ring/ring-mock "0.3.0"] [ring/ring-devel "1.6.1"] [pjstadig/humane-test-output "0.8.1"]] :plugins [[com.jakemccrary/lein-test-refresh "0.19.0"]] :source-paths ["env/dev/clj"] :resource-paths ["env/dev/resources"] :repl-options {:init-ns user} :injections [(require 'pjstadig.humane-test-output) (pjstadig.humane-test-output/activate!)]} :project/test {:resource-paths ["env/test/resources"]} :profiles/dev {} :profiles/test {}})
true
(defproject org.atown.trawler.shipper "0.0.1" :slug "trawler-shipper" :description "The log shipper for the Trawler log monitoring system" :url "https://www.trawler.io" :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :maintainer {:email "PI:EMAIL:<EMAIL>END_PI"} :dependencies [[org.clojure/clojure "1.8.0"] [cprop "0.1.10"] [mount "0.1.11"] [org.clojure/core.async "0.3.443"] [org.clojure/tools.cli "0.3.5"] [org.clojure/tools.logging "0.3.1"] [cheshire "5.7.1"] [ch.qos.logback/logback-classic "1.1.3"] [hawk "0.2.11"] [com.taoensso/carmine "2.16.0"] [org.clojure/java.jdbc "0.6.1"] [me.raynes/fs "1.4.6"] [com.mchange/c3p0 "0.9.5.2"] [com.h2database/h2 "1.3.170"] [org.yaml/snakeyaml "1.18"] [org.clojure/tools.nrepl "0.2.12"]] :main org.atown.trawler.shipper.core :min-lein-version "2.0.0" :jvm-opts ["-server" "-Dconf=.lein-env"] :resource-paths ["resources"] :target-path "target/%s/" :plugins [[lein-cprop "1.0.3"] [lein-rpm "0.0.6" :exclusions [org.apache.maven/maven-plugin-api org.codehaus.plexus/plexus-container-default org.codehaus.plexus/plexus-utils org.clojure/clojure classworlds]] ; for lein-rpm [org.apache.maven/maven-plugin-api "2.0"] [org.codehaus.plexus/plexus-container-default "1.0-alpha-9-stable-1"] [org.codehaus.plexus/plexus-utils "1.5.15"] [classworlds "1.1"] ] :profiles {:uberjar {:omit-source true :aot :all :uberjar-name "trawler-shipper.jar" :source-paths ["env/prod/clj"] :resource-paths ["env/prod/resources"]} :dev [:project/dev :profiles/dev] :test [:project/dev :project/test :profiles/test] :project/dev {:dependencies [[prone "1.1.4"] [ring/ring-mock "0.3.0"] [ring/ring-devel "1.6.1"] [pjstadig/humane-test-output "0.8.1"]] :plugins [[com.jakemccrary/lein-test-refresh "0.19.0"]] :source-paths ["env/dev/clj"] :resource-paths ["env/dev/resources"] :repl-options {:init-ns user} :injections [(require 'pjstadig.humane-test-output) (pjstadig.humane-test-output/activate!)]} :project/test {:resource-paths ["env/test/resources"]} :profiles/dev {} :profiles/test {}})
[ { "context": "\n\n(+ 1 2)\n\n\n(defn wisdom\n [words]\n (str words \", Daniel-san\"))\n\n\n(wisdom \"Never clip your toes on a Tueday\")\n", "end": 190, "score": 0.9994797110557556, "start": 180, "tag": "NAME", "value": "Daniel-san" }, { "context": " Tueday\")\n;; => \"Never clip your toes on a Tueday, Daniel-san\"\n\n;; This function is not referentially transpare", "end": 291, "score": 0.9982066750526428, "start": 281, "tag": "NAME", "value": "Daniel-san" }, { "context": "to take only one arg\n;; \n(def character\n {:name \"Smooches McCutes\"\n :attributes {:intelligence 10\n ", "end": 2933, "score": 0.9997164607048035, "start": 2917, "tag": "NAME", "value": "Smooches McCutes" }, { "context": "memoize sleepy-identity))\n\n(memo-sleepy-identity \"Henlo Frens\")\n;; => \"Henlo Frens\" took 1 second\n\n(memo-sleepy", "end": 4081, "score": 0.999398946762085, "start": 4070, "tag": "NAME", "value": "Henlo Frens" }, { "context": "ty))\n\n(memo-sleepy-identity \"Henlo Frens\")\n;; => \"Henlo Frens\" took 1 second\n\n(memo-sleepy-identity \"Henlo Fren", "end": 4102, "score": 0.9994556307792664, "start": 4091, "tag": "NAME", "value": "Henlo Frens" }, { "context": "enlo Frens\" took 1 second\n\n(memo-sleepy-identity \"Henlo Frens\")\n;; => \"Henlo Frens\" returned immediately\n\n(memo", "end": 4153, "score": 0.9993851184844971, "start": 4142, "tag": "NAME", "value": "Henlo Frens" }, { "context": "cond\n\n(memo-sleepy-identity \"Henlo Frens\")\n;; => \"Henlo Frens\" returned immediately\n\n(memo-sleepy-identity \"Dif", "end": 4174, "score": 0.9993755221366882, "start": 4163, "tag": "NAME", "value": "Henlo Frens" } ]
code/clojure-noob/src/clojure_noob/ch5.clj
itsrainingmani/learn-clojure-in-public
7
(ns clojure-noob.ch5 (:gen-class)) (println "Welcome to ch5 of Brave Clojure") ;; Pure Function ;; Referential Transparency (+ 1 2) (defn wisdom [words] (str words ", Daniel-san")) (wisdom "Never clip your toes on a Tueday") ;; => "Never clip your toes on a Tueday, Daniel-san" ;; This function is not referentially transparent since it relies on a random number (defn year-end-evaluation [] (if (> (rand) 0.5) "You get a raise!" "Better luck next year :-(")) (year-end-evaluation) ;; => "Better luck next year :-(" ;; => "You get a raise!" ;; => "Better luck next year :-(" ;; If your function interacts with file systems, its not referentially transparent (defn analysis ;; Referentially transparent "Returns the count of characters in given string" [text] (str "Character count: " (count text))) ;; (defn analyze-file ;; Not referentially transparent [filename] (analysis (slurp filename))) ;; Side FX ;; ;; To perform a side effect is to change the association between a name and its value within a given scope. ;; ;; Side effects allow you to interact with the real world ;; However, now you have to be careful about what the names in your code are referring to ;; ;; Immutable Data Structures ;; Functional Alternative to Mutation is Recursion ;; (defn sum ; -> arity overloading to provide a default val of 0 ([vals] (sum vals 0)) ([vals accum] (if (empty? vals) ; -> recursion base case accum (sum (rest vals) (+ (first vals) accum))))) (sum [39 5 1]) ;; => 45 ;; Each recursive call to sum creates a new scope where vals and accum are bound to different values, without needing to alter the originally passed values ;; (defn sum-recur ([vals] (sum vals 0)) ([vals accum] (if (empty? vals) accum (recur (rest vals) (+ (first vals) accum))))) (sum-recur [45 54 123]) ;; => 222 ;; Function Composition instead of Attribute Mutation ;; (require '[clojure.string :as s]) (defn clean [text] (s/replace (s/trim text) #"lol" "LOL")) (clean "My boa constrictor is so sassy lol! ") ;; => "My boa constrictor is so sassy LOL!" ;; => "My boa constrictor is so sassy LOL!" ;; Functional Programming encourages you to build more complex functions by combining simpler functions. ;; ;; Decoupling functions and data ;; Programming to a small set of abstractions ;; ;; OOP -> modify data by embodying it as an object. original data is lost ;; FP -> Data is unchanging and you derive new data from existing data ;; ;; comp ;; allows you to compose pure functions ;; ((comp inc *) 2 3) ;; => 7 ;; (comp f1 f2 f3) -> creates an anonymous function that composes the results of the args passed to it ;; ;; (f1 (f2 (f3 x1 x2 x3))) ;; ;; The innermost function (the last arg to comp) can take any number of args, but each of the successive functions must be able to take only one arg ;; (def character {:name "Smooches McCutes" :attributes {:intelligence 10 :strength 4 :dexterity 5}}) (def c-int (comp :intelligence :attributes)) (def c-str (comp :strength :attributes)) (def c-dex (comp :dexterity :attributes)) (c-int character) ;; => 10 (c-str character) ;; => 4 (c-dex character) ;; => 5 (defn spell-slots [char] (int (inc (/ (c-int char) 2)))) (spell-slots character) ;; What do we do if one of the functions you want to compose needs to take more than one arg (def spell-slots-comp (comp int inc #(/ % 2) c-int)) (spell-slots-comp character) (defn two-comp [f g] (fn [& args] (f (apply g args)))) ((two-comp inc *) 2 3) ;; => 7 ;; memoize ;; Memoization lets you take advantage of referential transparency by storing the arguments passed to a function and the return value of the function. ;; (defn sleepy-identity "Returns the given value after 1 second" [x] (Thread/sleep 1000) x) (sleepy-identity "Hello") ;; => "Hello" took 1 second ;; subsequent calls will also return "hello" after sleeping for 1 second (def memo-sleepy-identity (memoize sleepy-identity)) (memo-sleepy-identity "Henlo Frens") ;; => "Henlo Frens" took 1 second (memo-sleepy-identity "Henlo Frens") ;; => "Henlo Frens" returned immediately (memo-sleepy-identity "Different arg") ;; => "Different arg" took 1 second ;; Peg Things ;; ;; Reducing over functions is another way of composing functions ;; (defn clean-reduce [text] (reduce (fn [string string-fn] (string-fn string)) text [s/trim #(s/replace % #"lol" "LOL")])) ;; 1. You used (comp :intelligence :attributes) to create a function that returns a character’s intelligence. Create a new function, attr, that you can call like (attr :intelligence) and that does the same thing. ;; (def attr #(get-in character [:attributes %])) ;; 2. Implement the comp function ;; comp function syntax -> (comp f g h ...) ;; comp takes a variable number of arguments ;; (f (g (h ...))) ;; (defn my-comp [& args] (fn [& more-args] (let [i (apply (last args) more-args) rest-args (reverse (drop-last 1 args))] (reduce (fn [acc v] (v acc)) i rest-args)))) ;; 3. Implement the assoc-in function. Hint: use the assoc function and define its parameters as [m [k & ks] v] (defn my-assoc-in [m [k & ks] v] (println m k ks v) (if (empty? ks) (assoc m k v) (assoc m k (my-assoc-in (get m k) ks v)))) ;; 4. Look up and use the update-in function (update-in {:hello {:si {:hi 4}}} [:hello :si :hi] + 20) ;; => {:hello {:si {:hi 24}}} ;; 5. Implement update-in (defn my-update-in [m [k & ks] f & args] (println m k ks f args) (if (empty? ks) (assoc m k (apply f args)) (assoc m k (my-update-in (get m k) ks f args)))) (update-in {:hello {:si {:hi 4}}} [:hello :si :hi] + 20 3333) ;; => {:hello {:si {:hi 3357}}}
116288
(ns clojure-noob.ch5 (:gen-class)) (println "Welcome to ch5 of Brave Clojure") ;; Pure Function ;; Referential Transparency (+ 1 2) (defn wisdom [words] (str words ", <NAME>")) (wisdom "Never clip your toes on a Tueday") ;; => "Never clip your toes on a Tueday, <NAME>" ;; This function is not referentially transparent since it relies on a random number (defn year-end-evaluation [] (if (> (rand) 0.5) "You get a raise!" "Better luck next year :-(")) (year-end-evaluation) ;; => "Better luck next year :-(" ;; => "You get a raise!" ;; => "Better luck next year :-(" ;; If your function interacts with file systems, its not referentially transparent (defn analysis ;; Referentially transparent "Returns the count of characters in given string" [text] (str "Character count: " (count text))) ;; (defn analyze-file ;; Not referentially transparent [filename] (analysis (slurp filename))) ;; Side FX ;; ;; To perform a side effect is to change the association between a name and its value within a given scope. ;; ;; Side effects allow you to interact with the real world ;; However, now you have to be careful about what the names in your code are referring to ;; ;; Immutable Data Structures ;; Functional Alternative to Mutation is Recursion ;; (defn sum ; -> arity overloading to provide a default val of 0 ([vals] (sum vals 0)) ([vals accum] (if (empty? vals) ; -> recursion base case accum (sum (rest vals) (+ (first vals) accum))))) (sum [39 5 1]) ;; => 45 ;; Each recursive call to sum creates a new scope where vals and accum are bound to different values, without needing to alter the originally passed values ;; (defn sum-recur ([vals] (sum vals 0)) ([vals accum] (if (empty? vals) accum (recur (rest vals) (+ (first vals) accum))))) (sum-recur [45 54 123]) ;; => 222 ;; Function Composition instead of Attribute Mutation ;; (require '[clojure.string :as s]) (defn clean [text] (s/replace (s/trim text) #"lol" "LOL")) (clean "My boa constrictor is so sassy lol! ") ;; => "My boa constrictor is so sassy LOL!" ;; => "My boa constrictor is so sassy LOL!" ;; Functional Programming encourages you to build more complex functions by combining simpler functions. ;; ;; Decoupling functions and data ;; Programming to a small set of abstractions ;; ;; OOP -> modify data by embodying it as an object. original data is lost ;; FP -> Data is unchanging and you derive new data from existing data ;; ;; comp ;; allows you to compose pure functions ;; ((comp inc *) 2 3) ;; => 7 ;; (comp f1 f2 f3) -> creates an anonymous function that composes the results of the args passed to it ;; ;; (f1 (f2 (f3 x1 x2 x3))) ;; ;; The innermost function (the last arg to comp) can take any number of args, but each of the successive functions must be able to take only one arg ;; (def character {:name "<NAME>" :attributes {:intelligence 10 :strength 4 :dexterity 5}}) (def c-int (comp :intelligence :attributes)) (def c-str (comp :strength :attributes)) (def c-dex (comp :dexterity :attributes)) (c-int character) ;; => 10 (c-str character) ;; => 4 (c-dex character) ;; => 5 (defn spell-slots [char] (int (inc (/ (c-int char) 2)))) (spell-slots character) ;; What do we do if one of the functions you want to compose needs to take more than one arg (def spell-slots-comp (comp int inc #(/ % 2) c-int)) (spell-slots-comp character) (defn two-comp [f g] (fn [& args] (f (apply g args)))) ((two-comp inc *) 2 3) ;; => 7 ;; memoize ;; Memoization lets you take advantage of referential transparency by storing the arguments passed to a function and the return value of the function. ;; (defn sleepy-identity "Returns the given value after 1 second" [x] (Thread/sleep 1000) x) (sleepy-identity "Hello") ;; => "Hello" took 1 second ;; subsequent calls will also return "hello" after sleeping for 1 second (def memo-sleepy-identity (memoize sleepy-identity)) (memo-sleepy-identity "<NAME>") ;; => "<NAME>" took 1 second (memo-sleepy-identity "<NAME>") ;; => "<NAME>" returned immediately (memo-sleepy-identity "Different arg") ;; => "Different arg" took 1 second ;; Peg Things ;; ;; Reducing over functions is another way of composing functions ;; (defn clean-reduce [text] (reduce (fn [string string-fn] (string-fn string)) text [s/trim #(s/replace % #"lol" "LOL")])) ;; 1. You used (comp :intelligence :attributes) to create a function that returns a character’s intelligence. Create a new function, attr, that you can call like (attr :intelligence) and that does the same thing. ;; (def attr #(get-in character [:attributes %])) ;; 2. Implement the comp function ;; comp function syntax -> (comp f g h ...) ;; comp takes a variable number of arguments ;; (f (g (h ...))) ;; (defn my-comp [& args] (fn [& more-args] (let [i (apply (last args) more-args) rest-args (reverse (drop-last 1 args))] (reduce (fn [acc v] (v acc)) i rest-args)))) ;; 3. Implement the assoc-in function. Hint: use the assoc function and define its parameters as [m [k & ks] v] (defn my-assoc-in [m [k & ks] v] (println m k ks v) (if (empty? ks) (assoc m k v) (assoc m k (my-assoc-in (get m k) ks v)))) ;; 4. Look up and use the update-in function (update-in {:hello {:si {:hi 4}}} [:hello :si :hi] + 20) ;; => {:hello {:si {:hi 24}}} ;; 5. Implement update-in (defn my-update-in [m [k & ks] f & args] (println m k ks f args) (if (empty? ks) (assoc m k (apply f args)) (assoc m k (my-update-in (get m k) ks f args)))) (update-in {:hello {:si {:hi 4}}} [:hello :si :hi] + 20 3333) ;; => {:hello {:si {:hi 3357}}}
true
(ns clojure-noob.ch5 (:gen-class)) (println "Welcome to ch5 of Brave Clojure") ;; Pure Function ;; Referential Transparency (+ 1 2) (defn wisdom [words] (str words ", PI:NAME:<NAME>END_PI")) (wisdom "Never clip your toes on a Tueday") ;; => "Never clip your toes on a Tueday, PI:NAME:<NAME>END_PI" ;; This function is not referentially transparent since it relies on a random number (defn year-end-evaluation [] (if (> (rand) 0.5) "You get a raise!" "Better luck next year :-(")) (year-end-evaluation) ;; => "Better luck next year :-(" ;; => "You get a raise!" ;; => "Better luck next year :-(" ;; If your function interacts with file systems, its not referentially transparent (defn analysis ;; Referentially transparent "Returns the count of characters in given string" [text] (str "Character count: " (count text))) ;; (defn analyze-file ;; Not referentially transparent [filename] (analysis (slurp filename))) ;; Side FX ;; ;; To perform a side effect is to change the association between a name and its value within a given scope. ;; ;; Side effects allow you to interact with the real world ;; However, now you have to be careful about what the names in your code are referring to ;; ;; Immutable Data Structures ;; Functional Alternative to Mutation is Recursion ;; (defn sum ; -> arity overloading to provide a default val of 0 ([vals] (sum vals 0)) ([vals accum] (if (empty? vals) ; -> recursion base case accum (sum (rest vals) (+ (first vals) accum))))) (sum [39 5 1]) ;; => 45 ;; Each recursive call to sum creates a new scope where vals and accum are bound to different values, without needing to alter the originally passed values ;; (defn sum-recur ([vals] (sum vals 0)) ([vals accum] (if (empty? vals) accum (recur (rest vals) (+ (first vals) accum))))) (sum-recur [45 54 123]) ;; => 222 ;; Function Composition instead of Attribute Mutation ;; (require '[clojure.string :as s]) (defn clean [text] (s/replace (s/trim text) #"lol" "LOL")) (clean "My boa constrictor is so sassy lol! ") ;; => "My boa constrictor is so sassy LOL!" ;; => "My boa constrictor is so sassy LOL!" ;; Functional Programming encourages you to build more complex functions by combining simpler functions. ;; ;; Decoupling functions and data ;; Programming to a small set of abstractions ;; ;; OOP -> modify data by embodying it as an object. original data is lost ;; FP -> Data is unchanging and you derive new data from existing data ;; ;; comp ;; allows you to compose pure functions ;; ((comp inc *) 2 3) ;; => 7 ;; (comp f1 f2 f3) -> creates an anonymous function that composes the results of the args passed to it ;; ;; (f1 (f2 (f3 x1 x2 x3))) ;; ;; The innermost function (the last arg to comp) can take any number of args, but each of the successive functions must be able to take only one arg ;; (def character {:name "PI:NAME:<NAME>END_PI" :attributes {:intelligence 10 :strength 4 :dexterity 5}}) (def c-int (comp :intelligence :attributes)) (def c-str (comp :strength :attributes)) (def c-dex (comp :dexterity :attributes)) (c-int character) ;; => 10 (c-str character) ;; => 4 (c-dex character) ;; => 5 (defn spell-slots [char] (int (inc (/ (c-int char) 2)))) (spell-slots character) ;; What do we do if one of the functions you want to compose needs to take more than one arg (def spell-slots-comp (comp int inc #(/ % 2) c-int)) (spell-slots-comp character) (defn two-comp [f g] (fn [& args] (f (apply g args)))) ((two-comp inc *) 2 3) ;; => 7 ;; memoize ;; Memoization lets you take advantage of referential transparency by storing the arguments passed to a function and the return value of the function. ;; (defn sleepy-identity "Returns the given value after 1 second" [x] (Thread/sleep 1000) x) (sleepy-identity "Hello") ;; => "Hello" took 1 second ;; subsequent calls will also return "hello" after sleeping for 1 second (def memo-sleepy-identity (memoize sleepy-identity)) (memo-sleepy-identity "PI:NAME:<NAME>END_PI") ;; => "PI:NAME:<NAME>END_PI" took 1 second (memo-sleepy-identity "PI:NAME:<NAME>END_PI") ;; => "PI:NAME:<NAME>END_PI" returned immediately (memo-sleepy-identity "Different arg") ;; => "Different arg" took 1 second ;; Peg Things ;; ;; Reducing over functions is another way of composing functions ;; (defn clean-reduce [text] (reduce (fn [string string-fn] (string-fn string)) text [s/trim #(s/replace % #"lol" "LOL")])) ;; 1. You used (comp :intelligence :attributes) to create a function that returns a character’s intelligence. Create a new function, attr, that you can call like (attr :intelligence) and that does the same thing. ;; (def attr #(get-in character [:attributes %])) ;; 2. Implement the comp function ;; comp function syntax -> (comp f g h ...) ;; comp takes a variable number of arguments ;; (f (g (h ...))) ;; (defn my-comp [& args] (fn [& more-args] (let [i (apply (last args) more-args) rest-args (reverse (drop-last 1 args))] (reduce (fn [acc v] (v acc)) i rest-args)))) ;; 3. Implement the assoc-in function. Hint: use the assoc function and define its parameters as [m [k & ks] v] (defn my-assoc-in [m [k & ks] v] (println m k ks v) (if (empty? ks) (assoc m k v) (assoc m k (my-assoc-in (get m k) ks v)))) ;; 4. Look up and use the update-in function (update-in {:hello {:si {:hi 4}}} [:hello :si :hi] + 20) ;; => {:hello {:si {:hi 24}}} ;; 5. Implement update-in (defn my-update-in [m [k & ks] f & args] (println m k ks f args) (if (empty? ks) (assoc m k (apply f args)) (assoc m k (my-update-in (get m k) ks f args)))) (update-in {:hello {:si {:hi 4}}} [:hello :si :hi] + 20 3333) ;; => {:hello {:si {:hi 3357}}}
[ { "context": ":invoice_number_format \"#yyyy#-#dddd#\"\n :email \"muj@email.cz\"\n :eet_invoice_default false\n :invoice_langua", "end": 681, "score": 0.9999227523803711, "start": 669, "tag": "EMAIL", "value": "muj@email.cz" }, { "context": "\n :invoice_language \"cz\"\n :phone \"\"\n :name \"Vaše Jméno\"\n :swift_bic nil\n :vat_rate 21\n :city \"Adre", "end": 772, "score": 0.9998806118965149, "start": 762, "tag": "NAME", "value": "Vaše Jméno" }, { "context": ":vat_rate 21\n :city \"Adresa\"\n :invoice_email \"muj@email.cz\"\n :plan_price 0\n :send_invoice_from_proforma_", "end": 857, "score": 0.9999222159385681, "start": 845, "tag": "EMAIL", "value": "muj@email.cz" } ]
test/clj_fakturoid_test/get_account_test.clj
druids/clj-fakturoid
0
(ns clj-fakturoid-test.get-account-test (:require [clojure.test :refer [deftest is testing]] [clj-http.fake :refer [with-fake-routes]] [clj-fakturoid.core :as fakturoid] [clj-fakturoid-test.fake-http :as fake-http])) (def fakturoid-host "https://api-staging.fakturoid.localhost/api/v2") (def get-account (partial fakturoid/get-account fakturoid-host ["username" "token"])) (def json-handler (partial fake-http/json-handler fakturoid-host)) (def account-response {:html_url "https://app.fakturoid.cz/slug/account" :invoice_payment_method nil :send_thank_you_email false :eet false :invoice_number_format "#yyyy#-#dddd#" :email "muj@email.cz" :eet_invoice_default false :invoice_language "cz" :phone "" :name "Vaše Jméno" :swift_bic nil :vat_rate 21 :city "Adresa" :invoice_email "muj@email.cz" :plan_price 0 :send_invoice_from_proforma_email false :due 14 :street2 nil :bank_account "0000000000/0000" :street "Adresa 1" :subdomain "slug" :displayed_note "Fyzická osoba zapsaná v živnostenském rejstříku." :updated_at "2017-04-18T09:06:00.832+01:00" :currency "CZK" :vat_no "CZ0000000000" :vat_price_mode "without_vat" :zip "00000" :unit_name "" :url "https://app.fakturoid.cz/api/v2/accounts/slug/account.json" :invoice_note nil :registration_no "00000000" :vat_mode "vat_payer" :invoice_gopay false :iban nil :full_name nil :invoice_paypal false :overdue_email_text (str "Zdravím,\n\nmůj fakturační robot mě upozornil, že faktura č. #no# je po splatnosti.\n" "Fakturu najdete na #link#\n\nZkuste se na to mrknout. Díky.\n\nVaše Jméno"), :send_overdue_email false :plan "Zdarma" :custom_email_text "Hezký den,\n\nvystavil jsem pro Vás fakturu \n#link#\n\nDíky!\n\nVaše Jméno" :country "CZ" :invoice_proforma false :created_at "2017-04-18T09:04:31.764+01:00" :web ""}) (deftest get-account-test (testing "should return account" (with-fake-routes (json-handler "/accounts/slug/account.json" account-response 200) (let [response (get-account "slug")] (is (= 200 (:status response))) (is (= account-response (:body response)))))) (testing "should return not found" (with-fake-routes (json-handler "/accounts/nonexisting/account.json" {} 404) (let [response (get-account "nonexisting")] (is (= 404 (:status response)))))) (testing "should return 499, with unparsed body" (with-fake-routes {(str fakturoid-host "/accounts/slug/account.json") (fn [_] {:status 499, :body "---"})} (let [response (get-account "slug")] (is (= 499 (:status response))) (is (-> response :body nil?)) (is ( = "---" (:body-unparsed response)))))))
65302
(ns clj-fakturoid-test.get-account-test (:require [clojure.test :refer [deftest is testing]] [clj-http.fake :refer [with-fake-routes]] [clj-fakturoid.core :as fakturoid] [clj-fakturoid-test.fake-http :as fake-http])) (def fakturoid-host "https://api-staging.fakturoid.localhost/api/v2") (def get-account (partial fakturoid/get-account fakturoid-host ["username" "token"])) (def json-handler (partial fake-http/json-handler fakturoid-host)) (def account-response {:html_url "https://app.fakturoid.cz/slug/account" :invoice_payment_method nil :send_thank_you_email false :eet false :invoice_number_format "#yyyy#-#dddd#" :email "<EMAIL>" :eet_invoice_default false :invoice_language "cz" :phone "" :name "<NAME>" :swift_bic nil :vat_rate 21 :city "Adresa" :invoice_email "<EMAIL>" :plan_price 0 :send_invoice_from_proforma_email false :due 14 :street2 nil :bank_account "0000000000/0000" :street "Adresa 1" :subdomain "slug" :displayed_note "Fyzická osoba zapsaná v živnostenském rejstříku." :updated_at "2017-04-18T09:06:00.832+01:00" :currency "CZK" :vat_no "CZ0000000000" :vat_price_mode "without_vat" :zip "00000" :unit_name "" :url "https://app.fakturoid.cz/api/v2/accounts/slug/account.json" :invoice_note nil :registration_no "00000000" :vat_mode "vat_payer" :invoice_gopay false :iban nil :full_name nil :invoice_paypal false :overdue_email_text (str "Zdravím,\n\nmůj fakturační robot mě upozornil, že faktura č. #no# je po splatnosti.\n" "Fakturu najdete na #link#\n\nZkuste se na to mrknout. Díky.\n\nVaše Jméno"), :send_overdue_email false :plan "Zdarma" :custom_email_text "Hezký den,\n\nvystavil jsem pro Vás fakturu \n#link#\n\nDíky!\n\nVaše Jméno" :country "CZ" :invoice_proforma false :created_at "2017-04-18T09:04:31.764+01:00" :web ""}) (deftest get-account-test (testing "should return account" (with-fake-routes (json-handler "/accounts/slug/account.json" account-response 200) (let [response (get-account "slug")] (is (= 200 (:status response))) (is (= account-response (:body response)))))) (testing "should return not found" (with-fake-routes (json-handler "/accounts/nonexisting/account.json" {} 404) (let [response (get-account "nonexisting")] (is (= 404 (:status response)))))) (testing "should return 499, with unparsed body" (with-fake-routes {(str fakturoid-host "/accounts/slug/account.json") (fn [_] {:status 499, :body "---"})} (let [response (get-account "slug")] (is (= 499 (:status response))) (is (-> response :body nil?)) (is ( = "---" (:body-unparsed response)))))))
true
(ns clj-fakturoid-test.get-account-test (:require [clojure.test :refer [deftest is testing]] [clj-http.fake :refer [with-fake-routes]] [clj-fakturoid.core :as fakturoid] [clj-fakturoid-test.fake-http :as fake-http])) (def fakturoid-host "https://api-staging.fakturoid.localhost/api/v2") (def get-account (partial fakturoid/get-account fakturoid-host ["username" "token"])) (def json-handler (partial fake-http/json-handler fakturoid-host)) (def account-response {:html_url "https://app.fakturoid.cz/slug/account" :invoice_payment_method nil :send_thank_you_email false :eet false :invoice_number_format "#yyyy#-#dddd#" :email "PI:EMAIL:<EMAIL>END_PI" :eet_invoice_default false :invoice_language "cz" :phone "" :name "PI:NAME:<NAME>END_PI" :swift_bic nil :vat_rate 21 :city "Adresa" :invoice_email "PI:EMAIL:<EMAIL>END_PI" :plan_price 0 :send_invoice_from_proforma_email false :due 14 :street2 nil :bank_account "0000000000/0000" :street "Adresa 1" :subdomain "slug" :displayed_note "Fyzická osoba zapsaná v živnostenském rejstříku." :updated_at "2017-04-18T09:06:00.832+01:00" :currency "CZK" :vat_no "CZ0000000000" :vat_price_mode "without_vat" :zip "00000" :unit_name "" :url "https://app.fakturoid.cz/api/v2/accounts/slug/account.json" :invoice_note nil :registration_no "00000000" :vat_mode "vat_payer" :invoice_gopay false :iban nil :full_name nil :invoice_paypal false :overdue_email_text (str "Zdravím,\n\nmůj fakturační robot mě upozornil, že faktura č. #no# je po splatnosti.\n" "Fakturu najdete na #link#\n\nZkuste se na to mrknout. Díky.\n\nVaše Jméno"), :send_overdue_email false :plan "Zdarma" :custom_email_text "Hezký den,\n\nvystavil jsem pro Vás fakturu \n#link#\n\nDíky!\n\nVaše Jméno" :country "CZ" :invoice_proforma false :created_at "2017-04-18T09:04:31.764+01:00" :web ""}) (deftest get-account-test (testing "should return account" (with-fake-routes (json-handler "/accounts/slug/account.json" account-response 200) (let [response (get-account "slug")] (is (= 200 (:status response))) (is (= account-response (:body response)))))) (testing "should return not found" (with-fake-routes (json-handler "/accounts/nonexisting/account.json" {} 404) (let [response (get-account "nonexisting")] (is (= 404 (:status response)))))) (testing "should return 499, with unparsed body" (with-fake-routes {(str fakturoid-host "/accounts/slug/account.json") (fn [_] {:status 499, :body "---"})} (let [response (get-account "slug")] (is (= 499 (:status response))) (is (-> response :body nil?)) (is ( = "---" (:body-unparsed response)))))))
[ { "context": "in!\")))\n\n(defsc Signup [this {:account/keys [email password password-again]\n :ui/keys ", "end": 1419, "score": 0.5414404273033142, "start": 1411, "tag": "PASSWORD", "value": "password" }, { "context": "(defsc Signup [this {:account/keys [email password password-again]\n :ui/keys [signup", "end": 1428, "score": 0.5881399512290955, "start": 1420, "tag": "PASSWORD", "value": "password" }, { "context": " :password password}))\n ; ", "end": 15547, "score": 0.9973470568656921, "start": 15539, "tag": "PASSWORD", "value": "password" } ]
src/main/app/ui/auth.cljs
joshuawood2894/fulcro_postgresql_mqtt_template
0
(ns app.ui.auth (:require [app.ui.antd.components :as ant] [app.ui.session :as session] [app.model.session :as m-session] [com.fulcrologic.fulcro.dom :as dom :refer [div ul li p h3 b]] [com.fulcrologic.fulcro.dom.html-entities :as ent] [com.fulcrologic.fulcro.dom.events :as evt] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.routing.dynamic-routing :as dr] [com.fulcrologic.fulcro.ui-state-machines :as uism :refer [defstatemachine]] [com.fulcrologic.fulcro.mutations :as m :refer [defmutation]] [com.fulcrologic.fulcro.algorithms.react-interop :as interop] [com.fulcrologic.fulcro.algorithms.form-state :as fs] [com.fulcrologic.fulcro-css.css :as css] [taoensso.timbre :as log])) (defn field [{:keys [label valid? error-message] :as props}] (let [input-props (-> props (assoc :name label) (dissoc :label :valid? :error-message))] (div :.ui.field (dom/label {:htmlFor label} label) (dom/input input-props) (dom/div :.ui.error.message {:classes [(when valid? "hidden")]} error-message)))) (defsc SignupSuccess [this props] {:query ['*] :initial-state {} :ident (fn [] [:component/id :signup-success]) :route-segment ["signup-success"]} (div (dom/h3 "Signup Complete!") (dom/p "You can now log in!"))) (defsc Signup [this {:account/keys [email password password-again] :ui/keys [signup-open?] :as props}] {:query [:ui/signup-open? [::uism/asm-id ::session/session-id] :account/email :account/password :account/password-again fs/form-config-join] :initial-state (fn [_] (fs/add-form-config Signup {:account/email "" :account/password "" :account/password-again ""})) :form-fields #{:account/email :account/password :account/password-again} :ident (fn [] m-session/signup-ident) ;:route-segment ["signup"] :componentDidMount (fn [this] (comp/transact! this [(m-session/clear-signup-form)]))} (let [submit! (fn [evt] (when (or (identical? true evt) (evt/enter-key? evt)) (comp/transact! this [(m-session/signup! {:email email :password password})]) (log/info "Sign up"))) checked? (fs/checked? props) email-valid? (= :invalid (m-session/signup-validator props :account/email)) password-valid? (= :invalid (m-session/signup-validator props :account/password)) password-again-valid? (= :invalid (m-session/signup-validator props :account/password-again))] ;(ant/form {:labelCol {:span 0} ; :wrapperCol {:span 12} ; :name "normal_login" ; :initialValues {:remember false} ; :onFinish (fn [] (js/console.log "onFinish")) ; :onFinishFailed (fn [] (js/console.log "onFinishFailed"))} ; (ant/form-item {:name "email" ; :rules [{:message "Please input your email!"}]} ; (ant/input {:prefix (ant/user-outlined) ; :placeholder "Email" ; :onChange #(m/set-string! this :account/email :event %)})) ; (ant/form-item {:name "password" ; :rules [{:message "Please input your password!"}]} ; (ant/input-password {:prefix (ant/lock-outlined) ; :placeholder "Password" ; :onChange #(comp/set-state! this {:password (evt/target-value %)})}))) (ant/modal {:title "sign up" :width "20vw" :style {:minWidth "300px"} ;:visible true :visible signup-open? :closable false :maskClosable false :okText "Log in" :footer [(ant/button {:key "back" :onClick (fn [] (uism/trigger! this ::session/session-id :event/exit-signup-modal)) :size "middle"} "Cancel") (ant/button {:key "submit" :onClick (fn [] (when (= :valid (m-session/signup-validator props)) (uism/trigger! this ::session/session-id :event/exit-signup-modal)) (submit! true)) :size "middle" :style {:background ant/blue-primary :color "white"}} "Sign up")]} ;(div ; (dom/h3 "Signup") ; (div :.ui.form {:classes [(when checked? "error")]} ; (field {:label "Email" ; :value (or email "") ; ;:valid? (m-session/valid-email? email) ; :valid? (not email-valid?) ; :error-message "Must be an email address" ; :autoComplete "off" ; :onKeyDown submit! ; :onChange #(m/set-string! this :account/email :event %)}) ; (field {:label "Password" ; :type "password" ; :value (or password "") ; ;:valid? (m-session/valid-password? password) ; :valid? (not password-valid?) ; :error-message "Password must be at least 8 characters." ; :onKeyDown submit! ; :autoComplete "off" ; :onChange #(m/set-string! this :account/password :event %)}) ; (field {:label "Repeat Password" :type "password" :value (or password-again "") ; :autoComplete "off" ; :valid? (not password-again-valid?) ; ;:valid? (= password password-again) ; :error-message "Passwords do not match." ; :onChange #(m/set-string! this :account/password-again :event %)}) ; (dom/button :.ui.primary.button {:onClick #(submit! true)} ; "Sign Up")) ; ) (ant/form {:labelCol {:span 0} :wrapperCol {:span 24} :name "normal_login" :initialValues {:remember false}} (ant/form-item {:name "email"} (ant/input {:prefix (ant/user-outlined) :placeholder "Email" :onChange #(m/set-string! this :account/email :event %) :onKeyDown submit!})) (when (and checked? email-valid?) (dom/p {:style {:color "red"}} "Must be an email address.")) (ant/form-item {:name "password"} (ant/input-password {:prefix (ant/lock-outlined) :placeholder "Password" :onChange #(m/set-string! this :account/password :event %) :onKeyDown submit!})) (when (and checked? password-valid?) (dom/p {:style {:color "red"}} "Password must be at least 8 characters.")) (ant/form-item {:name "confirm password"} (ant/input-password {:prefix (ant/lock-outlined) :placeholder "Confirm Password" :onChange #(m/set-string! this :account/password-again :event %) :onKeyDown submit!})) (when (and checked? password-again-valid?) (dom/p {:style {:color "red"}} "Password must match.")) ) ))) (def ui-signup (comp/factory Signup)) (defsc Login [this {:account/keys [email] :ui/keys [error open?] :as props}] {:query [:ui/open? :ui/error :account/email {[:component/id :session] (comp/get-query session/Session)} [::uism/asm-id ::session/session-id]] :initial-state {:account/email "" :ui/error ""} :ident (fn [] [:component/id :login])} (let [current-state (uism/get-active-state this ::session/session-id) {current-user :account/email} (get props [:component/id :session]) initial? (= :initial current-state) loading? (= :state/checking-session current-state) logged-in? (= :state/logged-in current-state) password (or (comp/get-state this :password) "") ; c.l. state for security drop (ant/menu {:style {:textAlign "center"}} (ant/menu-item-group {:title current-user} (ant/divider) (ant/button {:onClick #(uism/trigger! this ::session/session-id :event/logout) :style {:margin "5px"} :danger true} "Logout")))] (div (when-not initial? (div (if logged-in? (ant/dropdown {:overlay drop :trigger ["click"]} (ant/avatar {:shape "square" :style {:backgroundColor "#001529"} :icon (ant/user-outlined) :size 42})) (ant/button {:onClick #(uism/trigger! this ::session/session-id :event/toggle-login-modal)} "Login")) (ant/modal {:title "Login" :width "20vw" :style {:minWidth "300px"} :visible open? :closable false :maskClosable false :okText "Log in" :footer [(ant/button {:key "back" :onClick (fn [] (uism/trigger! this ::session/session-id :event/toggle-login-modal)) :size "middle"} "Cancel") (ant/button {:key "submit" :onClick (fn [] (uism/trigger! this ::session/session-id :event/login {:email email :password password})) :loading loading? :size "middle" :style {:background ant/blue-primary :color "white"}} "Log in")]} (ant/form {:labelCol {:span 0} :wrapperCol {:span 24} :name "normal_login" :initialValues {:remember false}} (ant/form-item {:name "email"} (ant/input {:prefix (ant/user-outlined) :placeholder "Email" :onChange #(m/set-string! this :account/email :event %)})) (ant/form-item {:name "password"} (ant/input-password {:prefix (ant/lock-outlined) :placeholder "Password" :onChange #(comp/set-state! this {:password (evt/target-value %)})})) (when (not= error "") (dom/p {:style {:color "red"}} error)) (ant/card {:style {:background "#eeee"}} (dom/p "Don't have an account?") (dom/p "Please " (dom/a {:onClick (fn [] (uism/trigger! this ::session/session-id :event/enter-signup-modal) ;(dr/change-route this ; ["signup"]) )} "Sign Up!")))))))) ;(dom/div ; (when-not initial? ; (dom/div :.right.menu ; (if logged-in? ; (dom/button :.item ; {:onClick #(uism/trigger! this ; ::session/session-id ; :event/logout)} ; (dom/span current-user) ent/nbsp "Log out") ; (dom/div :.item {:style {:position "relative"} ; :onClick #(uism/trigger! this ; ::session/session-id :event/toggle-modal) ; } ; "Login" ; (when open? ; (dom/div :.four.wide.ui.raised.teal.segment {:onClick (fn [e] ; ;; Stop bubbling (would trigger the menu toggle) ; (evt/stop-propagation! e)) ; :classes [floating-menu]} ; (dom/h3 :.ui.header "Login") ; (div :.ui.form {:classes [(when (seq error) "error")]} ; (field {:label "Email" ; :value email ; :onChange #(m/set-string! this :account/email :event %)}) ; (field {:label "Password" ; :type "password" ; :value password ; :onChange #(comp/set-state! this {:password (evt/target-value %)})}) ; (div :.ui.error.message error) ; (div :.ui.field ; (dom/button :.ui.button ; {:onClick (fn [] ; (uism/trigger! this ::session/session-id :event/login {:email email ; :password password})) ; :classes [(when loading? "loading")]} "Login")) ; (div :.ui.message ; (dom/p "Don't have an account?") ; (dom/a {:onClick (fn [] ; (uism/trigger! this ::session/session-id :event/toggle-modal {}) ; (dr/change-route this ["signup"]))} ; "Please sign up!")))))))))) )) (def ui-login (comp/factory Login))
53486
(ns app.ui.auth (:require [app.ui.antd.components :as ant] [app.ui.session :as session] [app.model.session :as m-session] [com.fulcrologic.fulcro.dom :as dom :refer [div ul li p h3 b]] [com.fulcrologic.fulcro.dom.html-entities :as ent] [com.fulcrologic.fulcro.dom.events :as evt] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.routing.dynamic-routing :as dr] [com.fulcrologic.fulcro.ui-state-machines :as uism :refer [defstatemachine]] [com.fulcrologic.fulcro.mutations :as m :refer [defmutation]] [com.fulcrologic.fulcro.algorithms.react-interop :as interop] [com.fulcrologic.fulcro.algorithms.form-state :as fs] [com.fulcrologic.fulcro-css.css :as css] [taoensso.timbre :as log])) (defn field [{:keys [label valid? error-message] :as props}] (let [input-props (-> props (assoc :name label) (dissoc :label :valid? :error-message))] (div :.ui.field (dom/label {:htmlFor label} label) (dom/input input-props) (dom/div :.ui.error.message {:classes [(when valid? "hidden")]} error-message)))) (defsc SignupSuccess [this props] {:query ['*] :initial-state {} :ident (fn [] [:component/id :signup-success]) :route-segment ["signup-success"]} (div (dom/h3 "Signup Complete!") (dom/p "You can now log in!"))) (defsc Signup [this {:account/keys [email <PASSWORD> <PASSWORD>-again] :ui/keys [signup-open?] :as props}] {:query [:ui/signup-open? [::uism/asm-id ::session/session-id] :account/email :account/password :account/password-again fs/form-config-join] :initial-state (fn [_] (fs/add-form-config Signup {:account/email "" :account/password "" :account/password-again ""})) :form-fields #{:account/email :account/password :account/password-again} :ident (fn [] m-session/signup-ident) ;:route-segment ["signup"] :componentDidMount (fn [this] (comp/transact! this [(m-session/clear-signup-form)]))} (let [submit! (fn [evt] (when (or (identical? true evt) (evt/enter-key? evt)) (comp/transact! this [(m-session/signup! {:email email :password password})]) (log/info "Sign up"))) checked? (fs/checked? props) email-valid? (= :invalid (m-session/signup-validator props :account/email)) password-valid? (= :invalid (m-session/signup-validator props :account/password)) password-again-valid? (= :invalid (m-session/signup-validator props :account/password-again))] ;(ant/form {:labelCol {:span 0} ; :wrapperCol {:span 12} ; :name "normal_login" ; :initialValues {:remember false} ; :onFinish (fn [] (js/console.log "onFinish")) ; :onFinishFailed (fn [] (js/console.log "onFinishFailed"))} ; (ant/form-item {:name "email" ; :rules [{:message "Please input your email!"}]} ; (ant/input {:prefix (ant/user-outlined) ; :placeholder "Email" ; :onChange #(m/set-string! this :account/email :event %)})) ; (ant/form-item {:name "password" ; :rules [{:message "Please input your password!"}]} ; (ant/input-password {:prefix (ant/lock-outlined) ; :placeholder "Password" ; :onChange #(comp/set-state! this {:password (evt/target-value %)})}))) (ant/modal {:title "sign up" :width "20vw" :style {:minWidth "300px"} ;:visible true :visible signup-open? :closable false :maskClosable false :okText "Log in" :footer [(ant/button {:key "back" :onClick (fn [] (uism/trigger! this ::session/session-id :event/exit-signup-modal)) :size "middle"} "Cancel") (ant/button {:key "submit" :onClick (fn [] (when (= :valid (m-session/signup-validator props)) (uism/trigger! this ::session/session-id :event/exit-signup-modal)) (submit! true)) :size "middle" :style {:background ant/blue-primary :color "white"}} "Sign up")]} ;(div ; (dom/h3 "Signup") ; (div :.ui.form {:classes [(when checked? "error")]} ; (field {:label "Email" ; :value (or email "") ; ;:valid? (m-session/valid-email? email) ; :valid? (not email-valid?) ; :error-message "Must be an email address" ; :autoComplete "off" ; :onKeyDown submit! ; :onChange #(m/set-string! this :account/email :event %)}) ; (field {:label "Password" ; :type "password" ; :value (or password "") ; ;:valid? (m-session/valid-password? password) ; :valid? (not password-valid?) ; :error-message "Password must be at least 8 characters." ; :onKeyDown submit! ; :autoComplete "off" ; :onChange #(m/set-string! this :account/password :event %)}) ; (field {:label "Repeat Password" :type "password" :value (or password-again "") ; :autoComplete "off" ; :valid? (not password-again-valid?) ; ;:valid? (= password password-again) ; :error-message "Passwords do not match." ; :onChange #(m/set-string! this :account/password-again :event %)}) ; (dom/button :.ui.primary.button {:onClick #(submit! true)} ; "Sign Up")) ; ) (ant/form {:labelCol {:span 0} :wrapperCol {:span 24} :name "normal_login" :initialValues {:remember false}} (ant/form-item {:name "email"} (ant/input {:prefix (ant/user-outlined) :placeholder "Email" :onChange #(m/set-string! this :account/email :event %) :onKeyDown submit!})) (when (and checked? email-valid?) (dom/p {:style {:color "red"}} "Must be an email address.")) (ant/form-item {:name "password"} (ant/input-password {:prefix (ant/lock-outlined) :placeholder "Password" :onChange #(m/set-string! this :account/password :event %) :onKeyDown submit!})) (when (and checked? password-valid?) (dom/p {:style {:color "red"}} "Password must be at least 8 characters.")) (ant/form-item {:name "confirm password"} (ant/input-password {:prefix (ant/lock-outlined) :placeholder "Confirm Password" :onChange #(m/set-string! this :account/password-again :event %) :onKeyDown submit!})) (when (and checked? password-again-valid?) (dom/p {:style {:color "red"}} "Password must match.")) ) ))) (def ui-signup (comp/factory Signup)) (defsc Login [this {:account/keys [email] :ui/keys [error open?] :as props}] {:query [:ui/open? :ui/error :account/email {[:component/id :session] (comp/get-query session/Session)} [::uism/asm-id ::session/session-id]] :initial-state {:account/email "" :ui/error ""} :ident (fn [] [:component/id :login])} (let [current-state (uism/get-active-state this ::session/session-id) {current-user :account/email} (get props [:component/id :session]) initial? (= :initial current-state) loading? (= :state/checking-session current-state) logged-in? (= :state/logged-in current-state) password (or (comp/get-state this :password) "") ; c.l. state for security drop (ant/menu {:style {:textAlign "center"}} (ant/menu-item-group {:title current-user} (ant/divider) (ant/button {:onClick #(uism/trigger! this ::session/session-id :event/logout) :style {:margin "5px"} :danger true} "Logout")))] (div (when-not initial? (div (if logged-in? (ant/dropdown {:overlay drop :trigger ["click"]} (ant/avatar {:shape "square" :style {:backgroundColor "#001529"} :icon (ant/user-outlined) :size 42})) (ant/button {:onClick #(uism/trigger! this ::session/session-id :event/toggle-login-modal)} "Login")) (ant/modal {:title "Login" :width "20vw" :style {:minWidth "300px"} :visible open? :closable false :maskClosable false :okText "Log in" :footer [(ant/button {:key "back" :onClick (fn [] (uism/trigger! this ::session/session-id :event/toggle-login-modal)) :size "middle"} "Cancel") (ant/button {:key "submit" :onClick (fn [] (uism/trigger! this ::session/session-id :event/login {:email email :password password})) :loading loading? :size "middle" :style {:background ant/blue-primary :color "white"}} "Log in")]} (ant/form {:labelCol {:span 0} :wrapperCol {:span 24} :name "normal_login" :initialValues {:remember false}} (ant/form-item {:name "email"} (ant/input {:prefix (ant/user-outlined) :placeholder "Email" :onChange #(m/set-string! this :account/email :event %)})) (ant/form-item {:name "password"} (ant/input-password {:prefix (ant/lock-outlined) :placeholder "Password" :onChange #(comp/set-state! this {:password (evt/target-value %)})})) (when (not= error "") (dom/p {:style {:color "red"}} error)) (ant/card {:style {:background "#eeee"}} (dom/p "Don't have an account?") (dom/p "Please " (dom/a {:onClick (fn [] (uism/trigger! this ::session/session-id :event/enter-signup-modal) ;(dr/change-route this ; ["signup"]) )} "Sign Up!")))))))) ;(dom/div ; (when-not initial? ; (dom/div :.right.menu ; (if logged-in? ; (dom/button :.item ; {:onClick #(uism/trigger! this ; ::session/session-id ; :event/logout)} ; (dom/span current-user) ent/nbsp "Log out") ; (dom/div :.item {:style {:position "relative"} ; :onClick #(uism/trigger! this ; ::session/session-id :event/toggle-modal) ; } ; "Login" ; (when open? ; (dom/div :.four.wide.ui.raised.teal.segment {:onClick (fn [e] ; ;; Stop bubbling (would trigger the menu toggle) ; (evt/stop-propagation! e)) ; :classes [floating-menu]} ; (dom/h3 :.ui.header "Login") ; (div :.ui.form {:classes [(when (seq error) "error")]} ; (field {:label "Email" ; :value email ; :onChange #(m/set-string! this :account/email :event %)}) ; (field {:label "Password" ; :type "password" ; :value password ; :onChange #(comp/set-state! this {:password (evt/target-value %)})}) ; (div :.ui.error.message error) ; (div :.ui.field ; (dom/button :.ui.button ; {:onClick (fn [] ; (uism/trigger! this ::session/session-id :event/login {:email email ; :password <PASSWORD>})) ; :classes [(when loading? "loading")]} "Login")) ; (div :.ui.message ; (dom/p "Don't have an account?") ; (dom/a {:onClick (fn [] ; (uism/trigger! this ::session/session-id :event/toggle-modal {}) ; (dr/change-route this ["signup"]))} ; "Please sign up!")))))))))) )) (def ui-login (comp/factory Login))
true
(ns app.ui.auth (:require [app.ui.antd.components :as ant] [app.ui.session :as session] [app.model.session :as m-session] [com.fulcrologic.fulcro.dom :as dom :refer [div ul li p h3 b]] [com.fulcrologic.fulcro.dom.html-entities :as ent] [com.fulcrologic.fulcro.dom.events :as evt] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.routing.dynamic-routing :as dr] [com.fulcrologic.fulcro.ui-state-machines :as uism :refer [defstatemachine]] [com.fulcrologic.fulcro.mutations :as m :refer [defmutation]] [com.fulcrologic.fulcro.algorithms.react-interop :as interop] [com.fulcrologic.fulcro.algorithms.form-state :as fs] [com.fulcrologic.fulcro-css.css :as css] [taoensso.timbre :as log])) (defn field [{:keys [label valid? error-message] :as props}] (let [input-props (-> props (assoc :name label) (dissoc :label :valid? :error-message))] (div :.ui.field (dom/label {:htmlFor label} label) (dom/input input-props) (dom/div :.ui.error.message {:classes [(when valid? "hidden")]} error-message)))) (defsc SignupSuccess [this props] {:query ['*] :initial-state {} :ident (fn [] [:component/id :signup-success]) :route-segment ["signup-success"]} (div (dom/h3 "Signup Complete!") (dom/p "You can now log in!"))) (defsc Signup [this {:account/keys [email PI:PASSWORD:<PASSWORD>END_PI PI:PASSWORD:<PASSWORD>END_PI-again] :ui/keys [signup-open?] :as props}] {:query [:ui/signup-open? [::uism/asm-id ::session/session-id] :account/email :account/password :account/password-again fs/form-config-join] :initial-state (fn [_] (fs/add-form-config Signup {:account/email "" :account/password "" :account/password-again ""})) :form-fields #{:account/email :account/password :account/password-again} :ident (fn [] m-session/signup-ident) ;:route-segment ["signup"] :componentDidMount (fn [this] (comp/transact! this [(m-session/clear-signup-form)]))} (let [submit! (fn [evt] (when (or (identical? true evt) (evt/enter-key? evt)) (comp/transact! this [(m-session/signup! {:email email :password password})]) (log/info "Sign up"))) checked? (fs/checked? props) email-valid? (= :invalid (m-session/signup-validator props :account/email)) password-valid? (= :invalid (m-session/signup-validator props :account/password)) password-again-valid? (= :invalid (m-session/signup-validator props :account/password-again))] ;(ant/form {:labelCol {:span 0} ; :wrapperCol {:span 12} ; :name "normal_login" ; :initialValues {:remember false} ; :onFinish (fn [] (js/console.log "onFinish")) ; :onFinishFailed (fn [] (js/console.log "onFinishFailed"))} ; (ant/form-item {:name "email" ; :rules [{:message "Please input your email!"}]} ; (ant/input {:prefix (ant/user-outlined) ; :placeholder "Email" ; :onChange #(m/set-string! this :account/email :event %)})) ; (ant/form-item {:name "password" ; :rules [{:message "Please input your password!"}]} ; (ant/input-password {:prefix (ant/lock-outlined) ; :placeholder "Password" ; :onChange #(comp/set-state! this {:password (evt/target-value %)})}))) (ant/modal {:title "sign up" :width "20vw" :style {:minWidth "300px"} ;:visible true :visible signup-open? :closable false :maskClosable false :okText "Log in" :footer [(ant/button {:key "back" :onClick (fn [] (uism/trigger! this ::session/session-id :event/exit-signup-modal)) :size "middle"} "Cancel") (ant/button {:key "submit" :onClick (fn [] (when (= :valid (m-session/signup-validator props)) (uism/trigger! this ::session/session-id :event/exit-signup-modal)) (submit! true)) :size "middle" :style {:background ant/blue-primary :color "white"}} "Sign up")]} ;(div ; (dom/h3 "Signup") ; (div :.ui.form {:classes [(when checked? "error")]} ; (field {:label "Email" ; :value (or email "") ; ;:valid? (m-session/valid-email? email) ; :valid? (not email-valid?) ; :error-message "Must be an email address" ; :autoComplete "off" ; :onKeyDown submit! ; :onChange #(m/set-string! this :account/email :event %)}) ; (field {:label "Password" ; :type "password" ; :value (or password "") ; ;:valid? (m-session/valid-password? password) ; :valid? (not password-valid?) ; :error-message "Password must be at least 8 characters." ; :onKeyDown submit! ; :autoComplete "off" ; :onChange #(m/set-string! this :account/password :event %)}) ; (field {:label "Repeat Password" :type "password" :value (or password-again "") ; :autoComplete "off" ; :valid? (not password-again-valid?) ; ;:valid? (= password password-again) ; :error-message "Passwords do not match." ; :onChange #(m/set-string! this :account/password-again :event %)}) ; (dom/button :.ui.primary.button {:onClick #(submit! true)} ; "Sign Up")) ; ) (ant/form {:labelCol {:span 0} :wrapperCol {:span 24} :name "normal_login" :initialValues {:remember false}} (ant/form-item {:name "email"} (ant/input {:prefix (ant/user-outlined) :placeholder "Email" :onChange #(m/set-string! this :account/email :event %) :onKeyDown submit!})) (when (and checked? email-valid?) (dom/p {:style {:color "red"}} "Must be an email address.")) (ant/form-item {:name "password"} (ant/input-password {:prefix (ant/lock-outlined) :placeholder "Password" :onChange #(m/set-string! this :account/password :event %) :onKeyDown submit!})) (when (and checked? password-valid?) (dom/p {:style {:color "red"}} "Password must be at least 8 characters.")) (ant/form-item {:name "confirm password"} (ant/input-password {:prefix (ant/lock-outlined) :placeholder "Confirm Password" :onChange #(m/set-string! this :account/password-again :event %) :onKeyDown submit!})) (when (and checked? password-again-valid?) (dom/p {:style {:color "red"}} "Password must match.")) ) ))) (def ui-signup (comp/factory Signup)) (defsc Login [this {:account/keys [email] :ui/keys [error open?] :as props}] {:query [:ui/open? :ui/error :account/email {[:component/id :session] (comp/get-query session/Session)} [::uism/asm-id ::session/session-id]] :initial-state {:account/email "" :ui/error ""} :ident (fn [] [:component/id :login])} (let [current-state (uism/get-active-state this ::session/session-id) {current-user :account/email} (get props [:component/id :session]) initial? (= :initial current-state) loading? (= :state/checking-session current-state) logged-in? (= :state/logged-in current-state) password (or (comp/get-state this :password) "") ; c.l. state for security drop (ant/menu {:style {:textAlign "center"}} (ant/menu-item-group {:title current-user} (ant/divider) (ant/button {:onClick #(uism/trigger! this ::session/session-id :event/logout) :style {:margin "5px"} :danger true} "Logout")))] (div (when-not initial? (div (if logged-in? (ant/dropdown {:overlay drop :trigger ["click"]} (ant/avatar {:shape "square" :style {:backgroundColor "#001529"} :icon (ant/user-outlined) :size 42})) (ant/button {:onClick #(uism/trigger! this ::session/session-id :event/toggle-login-modal)} "Login")) (ant/modal {:title "Login" :width "20vw" :style {:minWidth "300px"} :visible open? :closable false :maskClosable false :okText "Log in" :footer [(ant/button {:key "back" :onClick (fn [] (uism/trigger! this ::session/session-id :event/toggle-login-modal)) :size "middle"} "Cancel") (ant/button {:key "submit" :onClick (fn [] (uism/trigger! this ::session/session-id :event/login {:email email :password password})) :loading loading? :size "middle" :style {:background ant/blue-primary :color "white"}} "Log in")]} (ant/form {:labelCol {:span 0} :wrapperCol {:span 24} :name "normal_login" :initialValues {:remember false}} (ant/form-item {:name "email"} (ant/input {:prefix (ant/user-outlined) :placeholder "Email" :onChange #(m/set-string! this :account/email :event %)})) (ant/form-item {:name "password"} (ant/input-password {:prefix (ant/lock-outlined) :placeholder "Password" :onChange #(comp/set-state! this {:password (evt/target-value %)})})) (when (not= error "") (dom/p {:style {:color "red"}} error)) (ant/card {:style {:background "#eeee"}} (dom/p "Don't have an account?") (dom/p "Please " (dom/a {:onClick (fn [] (uism/trigger! this ::session/session-id :event/enter-signup-modal) ;(dr/change-route this ; ["signup"]) )} "Sign Up!")))))))) ;(dom/div ; (when-not initial? ; (dom/div :.right.menu ; (if logged-in? ; (dom/button :.item ; {:onClick #(uism/trigger! this ; ::session/session-id ; :event/logout)} ; (dom/span current-user) ent/nbsp "Log out") ; (dom/div :.item {:style {:position "relative"} ; :onClick #(uism/trigger! this ; ::session/session-id :event/toggle-modal) ; } ; "Login" ; (when open? ; (dom/div :.four.wide.ui.raised.teal.segment {:onClick (fn [e] ; ;; Stop bubbling (would trigger the menu toggle) ; (evt/stop-propagation! e)) ; :classes [floating-menu]} ; (dom/h3 :.ui.header "Login") ; (div :.ui.form {:classes [(when (seq error) "error")]} ; (field {:label "Email" ; :value email ; :onChange #(m/set-string! this :account/email :event %)}) ; (field {:label "Password" ; :type "password" ; :value password ; :onChange #(comp/set-state! this {:password (evt/target-value %)})}) ; (div :.ui.error.message error) ; (div :.ui.field ; (dom/button :.ui.button ; {:onClick (fn [] ; (uism/trigger! this ::session/session-id :event/login {:email email ; :password PI:PASSWORD:<PASSWORD>END_PI})) ; :classes [(when loading? "loading")]} "Login")) ; (div :.ui.message ; (dom/p "Don't have an account?") ; (dom/a {:onClick (fn [] ; (uism/trigger! this ::session/session-id :event/toggle-modal {}) ; (dr/change-route this ["signup"]))} ; "Please sign up!")))))))))) )) (def ui-login (comp/factory Login))
[ { "context": ":c) 2)\n(list 1 \"two\" {3 4})\n(conj '(1 2 3) 4)\n\n#{\"kurt vonnegut\" 20 :ice 9}\n(hash-set 1 1 2 2)\n(conj #{:a :b} :b)", "end": 1313, "score": 0.9979920387268066, "start": 1300, "tag": "NAME", "value": "kurt vonnegut" }, { "context": "ueer\n [& things]\n (map squee things))\n\n(squeer \"Puppy\" \"Kitty\")\n\n(defn favorite-things\n [name & things", "end": 2051, "score": 0.9717162251472473, "start": 2046, "tag": "NAME", "value": "Puppy" }, { "context": "& things]\n (map squee things))\n\n(squeer \"Puppy\" \"Kitty\")\n\n(defn favorite-things\n [name & things]\n (str", "end": 2059, "score": 0.9148068428039551, "start": 2054, "tag": "NAME", "value": "Kitty" }, { "context": "\", \" things)\n \", etc.\"))\n\n(favorite-things \"Lilly\" \"puppies\" \"kitties\")\n\n(defn x-first\n [[first-th", "end": 2227, "score": 0.9980942010879517, "start": 2222, "tag": "NAME", "value": "Lilly" }, { "context": "y 2})\n\n(map (fn [name] (str \"Hey, \" name))\n [\"Dick\" \"Jane\"])\n\n(def three-er (fn [x] (* 3 x)))\n(three", "end": 2886, "score": 0.9998291730880737, "start": 2882, "tag": "NAME", "value": "Dick" }, { "context": "(map (fn [name] (str \"Hey, \" name))\n [\"Dick\" \"Jane\"])\n\n(def three-er (fn [x] (* 3 x)))\n(three-er 11)", "end": 2893, "score": 0.9998050928115845, "start": 2889, "tag": "NAME", "value": "Jane" }, { "context": "r 11)\n\n(#(* % 3) 8)\n\n(map #(str \"Hey, \" %)\n [\"Dick\" \"Jane\"])\n\n(#(str %1 \" and \" %2) \"this\" \"that\")\n(", "end": 2992, "score": 0.9998209476470947, "start": 2988, "tag": "NAME", "value": "Dick" }, { "context": "(#(* % 3) 8)\n\n(map #(str \"Hey, \" %)\n [\"Dick\" \"Jane\"])\n\n(#(str %1 \" and \" %2) \"this\" \"that\")\n(#(ident", "end": 2999, "score": 0.9997835755348206, "start": 2995, "tag": "NAME", "value": "Jane" }, { "context": "t [x 1] x)\n(let [x (inc x)] x)\n\n(def puppy-list [\"Pongo\" \"Corgi\" \"Husky\"])\n(let [[pongo & puppies] puppy-", "end": 3250, "score": 0.9988975524902344, "start": 3245, "tag": "NAME", "value": "Pongo" }, { "context": "x)\n(let [x (inc x)] x)\n\n(def puppy-list [\"Pongo\" \"Corgi\" \"Husky\"])\n(let [[pongo & puppies] puppy-list]\n ", "end": 3258, "score": 0.9996657371520996, "start": 3253, "tag": "NAME", "value": "Corgi" }, { "context": "[x (inc x)] x)\n\n(def puppy-list [\"Pongo\" \"Corgi\" \"Husky\"])\n(let [[pongo & puppies] puppy-list]\n [pongo p", "end": 3266, "score": 0.9989848732948303, "start": 3261, "tag": "NAME", "value": "Husky" }, { "context": " [3.2 44 53.1 3.11])\n\n(def identities\n [{:alias \"Batman\" :real \"Bruce Wayne\"}\n {:alias \"Spider-Man\" :re", "end": 3993, "score": 0.9996545910835266, "start": 3987, "tag": "NAME", "value": "Batman" }, { "context": ".11])\n\n(def identities\n [{:alias \"Batman\" :real \"Bruce Wayne\"}\n {:alias \"Spider-Man\" :real \"Peter Parker\"}\n ", "end": 4013, "score": 0.9998099207878113, "start": 4002, "tag": "NAME", "value": "Bruce Wayne" }, { "context": "eal \"Bruce Wayne\"}\n {:alias \"Spider-Man\" :real \"Peter Parker\"}\n {:alias \"Santa\" :real \"Your mom\"}\n {:alias", "end": 4059, "score": 0.9996564388275146, "start": 4047, "tag": "NAME", "value": "Peter Parker" }, { "context": "as \"Spider-Man\" :real \"Peter Parker\"}\n {:alias \"Santa\" :real \"Your mom\"}\n {:alias \"Easter Bunny\" :rea", "end": 4079, "score": 0.9616724252700806, "start": 4074, "tag": "NAME", "value": "Santa" }, { "context": "\n {:alias \"Santa\" :real \"Your mom\"}\n {:alias \"Easter Bunny\" :real \"Your dad\"}])\n\n(map :real identities)\n\n(re", "end": 4123, "score": 0.8353703618049622, "start": 4111, "tag": "NAME", "value": "Easter Bunny" }, { "context": "at [1 2] [3 4])\n\n(concat (take 8 (repeat \"na\")) [\"Batman!\"])\n(take 3 (repeatedly #(rand-int 10)))\n\n(defn e", "end": 5334, "score": 0.6561424732208252, "start": 5328, "tag": "NAME", "value": "Batman" } ]
clojure-noob/src/clojure_noob/core.clj
rxedu/braveclojure
0
(ns clojure-noob.core (:gen-class)) (defn -main "I don't do a whole lot ... yet." [& args] (println "I'm a little teapot!")) ; Chapter 3 (+ 1 2 3) (str "I " "am " "brave.") (if true "Puppies" "No Puppies") (if false "Puppies" "No Puppies") (if false "No Puppies") (if true (do (println "Success!") "Puppies") (do (println "Failure!") "No Puppies")) (when true (println "Success!") "Puppies") (nil? 1) (nil? nil?) (if 0 "Puppies") (if nil "Puppies" "No Puppies") (= 1 1) (= nil nil) (= 1 2) (or false nil :puppies :kitties) (or (= 0 1) (= "yes" "no")) (or nil) (and :kitties :puppies) (and :puppies nil false) (def tools-to-use ["vim", "zsh", "tmux", "git"]) tools-to-use (defn error-message [severity] (str "Oh noes! " (if (= severity :cuddles) "Too many puppies!" "No puppies!"))) (error-message :cuddles) (error-message :itsbad) (hash-map :a 1 :b 2) (get {:a 0 :b 1} :b) (get {:a 0 :b 1} :c) (get {:a 0 :b 1} :c "puppies") (get-in {:a 0 :b {:c "puppies"}} [:b :c]) ({:name "Razor"} :name) (:a {:a 1 :b 2 :c 3}) (:d {:a 1 :b 2 :c 3} "Nope") (get [3 2 1] 0) (get [:a "b" 3] 1) (vector 3 2 1) (conj [1 2 3] 4) '(1 2 3 4) (nth '(:a :b :c) 0) (nth '(:a :b :c) 2) (list 1 "two" {3 4}) (conj '(1 2 3) 4) #{"kurt vonnegut" 20 :ice 9} (hash-set 1 1 2 2) (conj #{:a :b} :b) (set [3 3 3 4 4]) (contains? #{:a :b} :a) (contains? #{:a :b} 3) (contains? #{:a :b nil} nil) (:a #{:a :b}) (get #{:a :b} :a) (get #{:a nil} nil) (get #{:a nil} :c) (or + -) ((or + -) 1 2 3) ((and (= 1 1) +) 1 2 3) ((first [+ 0]) 1 2 3) (inc 1.1) (map inc [0 1 2 3]) (defn too-cute "Return a cheer for something cute" [thing] (str "That " thing "is too cute!")) (too-cute "puppy") (defn x-chop "Neochop" ([name chop] (str "Your " chop " chop inflicts pain on " name ".")) ([name] (x-chop name "karate"))) (x-chop "Khan") (x-chop "Khan" "slap") (defn squee [thing] (str "SQUEE! It's a " thing)) (defn squeer [& things] (map squee things)) (squeer "Puppy" "Kitty") (defn favorite-things [name & things] (str "My name is " name " and I like " (clojure.string/join ", " things) ", etc.")) (favorite-things "Lilly" "puppies" "kitties") (defn x-first [[first-thing]] first-thing) (x-first [1 2 3 4]) (defn x-choose [[first-thing second-thing & other-things]] (str first-thing ", " second-thing ", " (clojure.string/join ", " other-things))) (x-choose ["this" "that" "the other" "the another"]) (defn x-find [{x :horz y :vert}] (println (str "(" x ", " y ")"))) (x-find {:horz 3 :vert -7}) (defn x-finder [{:keys [x y]}] (println (str "(" x ", " y ")"))) (x-finder {:x 4 :y -2}) (defn x-goer [{:keys [x y] :as coor}] (println (str "(" x ", " y ")")) (println coor)) (x-goer {:x 4 :y 2}) (map (fn [name] (str "Hey, " name)) ["Dick" "Jane"]) (def three-er (fn [x] (* 3 x))) (three-er 11) (#(* % 3) 8) (map #(str "Hey, " %) ["Dick" "Jane"]) (#(str %1 " and " %2) "this" "that") (#(identity %&) 1 2 3 :yo) (defn inc-maker "Make a custom incrementor" [inc-by] #(+ % inc-by)) (def inc42 (inc-maker 42)) (inc42 8) (def x 0) (let [x 1] x) (let [x (inc x)] x) (def puppy-list ["Pongo" "Corgi" "Husky"]) (let [[pongo & puppies] puppy-list] [pongo puppies]) (into [:b] (set [:a :a])) (loop [itr 0] (println (str "Num " itr)) (if (> itr 3) (println "Done") (recur (inc itr)))) ; Chapter 4 (seq '(1 2 3)) (seq [1 2 3]) (seq #{1 2 3}) (seq {:a 1 :b 2}) (into {} (seq {:a 1 :b 2})) (map str ["a" "b" "c"] ["d" "e" "f"]) (map + [1 2 3] [-3 2 1]) (def humans [2.3 4.5 2.4 6.6 7.7]) (def critters [4.5 6.7 4.3 7.5 3.2]) (defn unify-diet [human critter] {:human human :critter critter}) (map unify-diet humans critters) (def sum #(reduce + %)) (def avg #(/ (sum %) (count %))) (defn stats [numbers] (map #(% numbers) [sum count avg])) (stats [3 4 1]) (stats [3.2 44 53.1 3.11]) (def identities [{:alias "Batman" :real "Bruce Wayne"} {:alias "Spider-Man" :real "Peter Parker"} {:alias "Santa" :real "Your mom"} {:alias "Easter Bunny" :real "Your dad"}]) (map :real identities) (reduce (fn [new-map [key val]] (assoc new-map key (inc val))) {} {:a 20 :b 30}) (reduce (fn [new-map [key val]] (if (> val 4) (assoc new-map key val) new-map)) {} {:a 5 :b 2}) (take 3 [1 2 3 4 5]) (drop 3 [1 2 3 4 5]) (def food-journal [{:month 1 :day 1 :human 5.3 :critter 2.3} {:month 1 :day 2 :human 5.1 :critter 2.0} {:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} {:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} {:month 4 :day 1 :human 3.7 :critter 3.9} {:month 4 :day 2 :human 3.7 :critter 3.6}]) (take-while #(< (:month %) 3) food-journal) (drop-while #(< (:month %) 3) food-journal) (take-while #(< (:month %) 4) (drop-while #(< (:month %) 2) food-journal)) (filter #(< (:human %) 5) food-journal) (filter #(< (:month %) 3) food-journal) (some #(> (:critter %) 5) food-journal) (some #(> (:critter %) 3) food-journal) (some #(and (> (:critter %) 3) %) food-journal) (sort [4 3 5 3 2]) (sort-by count ["aaa" "c" "cc"]) (concat [1 2] [3 4]) (concat (take 8 (repeat "na")) ["Batman!"]) (take 3 (repeatedly #(rand-int 10))) (defn even-numbers ([] (even-numbers 0)) ([n] (cons n (lazy-seq (even-numbers (+ n 2)))))) (take 10 (even-numbers)) (map identity {:a "b"}) (into {} (map identity {:a "b"})) (into [] (map identity {:a "b"})) (into [] (map identity [:a "b"])) (into #{} (map identity [:a :b :a])) (into {:a 1} [[:b 2]]) (into [:a] '(:b :c)) (into {:a 1} {:b 2}) (conj [0] 1 2 3 4 5) (max 0 4 5 2) (apply max [3 5 3 2 45 4 32]) (def add10 (partial + 10)) (add10 20) (defn lousy-logger [log-level message] (condp = log-level :warn (clojure.string/lower-case message) :emergency (clojure.string/upper-case message))) (def warn (partial lousy-logger :warn)) (warn "Puppies") ; Chapter 5 ((comp inc *) 3 5) (def character {:name "Link" :attrs {:int 10 :str 12 :dex 18}}) (def c-int (comp :int :attrs)) (def c-str (comp :str :attrs)) (def c-dex (comp :dex :attrs)) (c-int character) (c-str character) (c-dex character) (defn spell-slots [char] (int (inc (/ (c-int char) 2)))) (def spell-slots-comp (comp int inc #(/ % 2) c-int)) (spell-slots-comp character) (defn sleepy-ident [x] (Thread/sleep 100) x) (sleepy-ident "Ant-Man") (sleepy-ident "Ant-Man") (def memo-sleppy-ident (memoize sleepy-ident)) (memo-sleppy-ident "Ant-Man") (memo-sleppy-ident "Ant-Man") ; Chapter 7 (read-string "(1 + 1)") (let [infix (read-string "(1 + 1)")] (list (second infix) (first infix) (last infix))) (defmacro ignore-last-operand [function-call] (butlast function-call)) (ignore-last-operand (+ 1 2 10)) (defmacro infix [infixed] (list (second infixed) (first infixed) (last infixed))) (infix (1 + 2))
20765
(ns clojure-noob.core (:gen-class)) (defn -main "I don't do a whole lot ... yet." [& args] (println "I'm a little teapot!")) ; Chapter 3 (+ 1 2 3) (str "I " "am " "brave.") (if true "Puppies" "No Puppies") (if false "Puppies" "No Puppies") (if false "No Puppies") (if true (do (println "Success!") "Puppies") (do (println "Failure!") "No Puppies")) (when true (println "Success!") "Puppies") (nil? 1) (nil? nil?) (if 0 "Puppies") (if nil "Puppies" "No Puppies") (= 1 1) (= nil nil) (= 1 2) (or false nil :puppies :kitties) (or (= 0 1) (= "yes" "no")) (or nil) (and :kitties :puppies) (and :puppies nil false) (def tools-to-use ["vim", "zsh", "tmux", "git"]) tools-to-use (defn error-message [severity] (str "Oh noes! " (if (= severity :cuddles) "Too many puppies!" "No puppies!"))) (error-message :cuddles) (error-message :itsbad) (hash-map :a 1 :b 2) (get {:a 0 :b 1} :b) (get {:a 0 :b 1} :c) (get {:a 0 :b 1} :c "puppies") (get-in {:a 0 :b {:c "puppies"}} [:b :c]) ({:name "Razor"} :name) (:a {:a 1 :b 2 :c 3}) (:d {:a 1 :b 2 :c 3} "Nope") (get [3 2 1] 0) (get [:a "b" 3] 1) (vector 3 2 1) (conj [1 2 3] 4) '(1 2 3 4) (nth '(:a :b :c) 0) (nth '(:a :b :c) 2) (list 1 "two" {3 4}) (conj '(1 2 3) 4) #{"<NAME>" 20 :ice 9} (hash-set 1 1 2 2) (conj #{:a :b} :b) (set [3 3 3 4 4]) (contains? #{:a :b} :a) (contains? #{:a :b} 3) (contains? #{:a :b nil} nil) (:a #{:a :b}) (get #{:a :b} :a) (get #{:a nil} nil) (get #{:a nil} :c) (or + -) ((or + -) 1 2 3) ((and (= 1 1) +) 1 2 3) ((first [+ 0]) 1 2 3) (inc 1.1) (map inc [0 1 2 3]) (defn too-cute "Return a cheer for something cute" [thing] (str "That " thing "is too cute!")) (too-cute "puppy") (defn x-chop "Neochop" ([name chop] (str "Your " chop " chop inflicts pain on " name ".")) ([name] (x-chop name "karate"))) (x-chop "Khan") (x-chop "Khan" "slap") (defn squee [thing] (str "SQUEE! It's a " thing)) (defn squeer [& things] (map squee things)) (squeer "<NAME>" "<NAME>") (defn favorite-things [name & things] (str "My name is " name " and I like " (clojure.string/join ", " things) ", etc.")) (favorite-things "<NAME>" "puppies" "kitties") (defn x-first [[first-thing]] first-thing) (x-first [1 2 3 4]) (defn x-choose [[first-thing second-thing & other-things]] (str first-thing ", " second-thing ", " (clojure.string/join ", " other-things))) (x-choose ["this" "that" "the other" "the another"]) (defn x-find [{x :horz y :vert}] (println (str "(" x ", " y ")"))) (x-find {:horz 3 :vert -7}) (defn x-finder [{:keys [x y]}] (println (str "(" x ", " y ")"))) (x-finder {:x 4 :y -2}) (defn x-goer [{:keys [x y] :as coor}] (println (str "(" x ", " y ")")) (println coor)) (x-goer {:x 4 :y 2}) (map (fn [name] (str "Hey, " name)) ["<NAME>" "<NAME>"]) (def three-er (fn [x] (* 3 x))) (three-er 11) (#(* % 3) 8) (map #(str "Hey, " %) ["<NAME>" "<NAME>"]) (#(str %1 " and " %2) "this" "that") (#(identity %&) 1 2 3 :yo) (defn inc-maker "Make a custom incrementor" [inc-by] #(+ % inc-by)) (def inc42 (inc-maker 42)) (inc42 8) (def x 0) (let [x 1] x) (let [x (inc x)] x) (def puppy-list ["<NAME>" "<NAME>" "<NAME>"]) (let [[pongo & puppies] puppy-list] [pongo puppies]) (into [:b] (set [:a :a])) (loop [itr 0] (println (str "Num " itr)) (if (> itr 3) (println "Done") (recur (inc itr)))) ; Chapter 4 (seq '(1 2 3)) (seq [1 2 3]) (seq #{1 2 3}) (seq {:a 1 :b 2}) (into {} (seq {:a 1 :b 2})) (map str ["a" "b" "c"] ["d" "e" "f"]) (map + [1 2 3] [-3 2 1]) (def humans [2.3 4.5 2.4 6.6 7.7]) (def critters [4.5 6.7 4.3 7.5 3.2]) (defn unify-diet [human critter] {:human human :critter critter}) (map unify-diet humans critters) (def sum #(reduce + %)) (def avg #(/ (sum %) (count %))) (defn stats [numbers] (map #(% numbers) [sum count avg])) (stats [3 4 1]) (stats [3.2 44 53.1 3.11]) (def identities [{:alias "<NAME>" :real "<NAME>"} {:alias "Spider-Man" :real "<NAME>"} {:alias "<NAME>" :real "Your mom"} {:alias "<NAME>" :real "Your dad"}]) (map :real identities) (reduce (fn [new-map [key val]] (assoc new-map key (inc val))) {} {:a 20 :b 30}) (reduce (fn [new-map [key val]] (if (> val 4) (assoc new-map key val) new-map)) {} {:a 5 :b 2}) (take 3 [1 2 3 4 5]) (drop 3 [1 2 3 4 5]) (def food-journal [{:month 1 :day 1 :human 5.3 :critter 2.3} {:month 1 :day 2 :human 5.1 :critter 2.0} {:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} {:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} {:month 4 :day 1 :human 3.7 :critter 3.9} {:month 4 :day 2 :human 3.7 :critter 3.6}]) (take-while #(< (:month %) 3) food-journal) (drop-while #(< (:month %) 3) food-journal) (take-while #(< (:month %) 4) (drop-while #(< (:month %) 2) food-journal)) (filter #(< (:human %) 5) food-journal) (filter #(< (:month %) 3) food-journal) (some #(> (:critter %) 5) food-journal) (some #(> (:critter %) 3) food-journal) (some #(and (> (:critter %) 3) %) food-journal) (sort [4 3 5 3 2]) (sort-by count ["aaa" "c" "cc"]) (concat [1 2] [3 4]) (concat (take 8 (repeat "na")) ["<NAME>!"]) (take 3 (repeatedly #(rand-int 10))) (defn even-numbers ([] (even-numbers 0)) ([n] (cons n (lazy-seq (even-numbers (+ n 2)))))) (take 10 (even-numbers)) (map identity {:a "b"}) (into {} (map identity {:a "b"})) (into [] (map identity {:a "b"})) (into [] (map identity [:a "b"])) (into #{} (map identity [:a :b :a])) (into {:a 1} [[:b 2]]) (into [:a] '(:b :c)) (into {:a 1} {:b 2}) (conj [0] 1 2 3 4 5) (max 0 4 5 2) (apply max [3 5 3 2 45 4 32]) (def add10 (partial + 10)) (add10 20) (defn lousy-logger [log-level message] (condp = log-level :warn (clojure.string/lower-case message) :emergency (clojure.string/upper-case message))) (def warn (partial lousy-logger :warn)) (warn "Puppies") ; Chapter 5 ((comp inc *) 3 5) (def character {:name "Link" :attrs {:int 10 :str 12 :dex 18}}) (def c-int (comp :int :attrs)) (def c-str (comp :str :attrs)) (def c-dex (comp :dex :attrs)) (c-int character) (c-str character) (c-dex character) (defn spell-slots [char] (int (inc (/ (c-int char) 2)))) (def spell-slots-comp (comp int inc #(/ % 2) c-int)) (spell-slots-comp character) (defn sleepy-ident [x] (Thread/sleep 100) x) (sleepy-ident "Ant-Man") (sleepy-ident "Ant-Man") (def memo-sleppy-ident (memoize sleepy-ident)) (memo-sleppy-ident "Ant-Man") (memo-sleppy-ident "Ant-Man") ; Chapter 7 (read-string "(1 + 1)") (let [infix (read-string "(1 + 1)")] (list (second infix) (first infix) (last infix))) (defmacro ignore-last-operand [function-call] (butlast function-call)) (ignore-last-operand (+ 1 2 10)) (defmacro infix [infixed] (list (second infixed) (first infixed) (last infixed))) (infix (1 + 2))
true
(ns clojure-noob.core (:gen-class)) (defn -main "I don't do a whole lot ... yet." [& args] (println "I'm a little teapot!")) ; Chapter 3 (+ 1 2 3) (str "I " "am " "brave.") (if true "Puppies" "No Puppies") (if false "Puppies" "No Puppies") (if false "No Puppies") (if true (do (println "Success!") "Puppies") (do (println "Failure!") "No Puppies")) (when true (println "Success!") "Puppies") (nil? 1) (nil? nil?) (if 0 "Puppies") (if nil "Puppies" "No Puppies") (= 1 1) (= nil nil) (= 1 2) (or false nil :puppies :kitties) (or (= 0 1) (= "yes" "no")) (or nil) (and :kitties :puppies) (and :puppies nil false) (def tools-to-use ["vim", "zsh", "tmux", "git"]) tools-to-use (defn error-message [severity] (str "Oh noes! " (if (= severity :cuddles) "Too many puppies!" "No puppies!"))) (error-message :cuddles) (error-message :itsbad) (hash-map :a 1 :b 2) (get {:a 0 :b 1} :b) (get {:a 0 :b 1} :c) (get {:a 0 :b 1} :c "puppies") (get-in {:a 0 :b {:c "puppies"}} [:b :c]) ({:name "Razor"} :name) (:a {:a 1 :b 2 :c 3}) (:d {:a 1 :b 2 :c 3} "Nope") (get [3 2 1] 0) (get [:a "b" 3] 1) (vector 3 2 1) (conj [1 2 3] 4) '(1 2 3 4) (nth '(:a :b :c) 0) (nth '(:a :b :c) 2) (list 1 "two" {3 4}) (conj '(1 2 3) 4) #{"PI:NAME:<NAME>END_PI" 20 :ice 9} (hash-set 1 1 2 2) (conj #{:a :b} :b) (set [3 3 3 4 4]) (contains? #{:a :b} :a) (contains? #{:a :b} 3) (contains? #{:a :b nil} nil) (:a #{:a :b}) (get #{:a :b} :a) (get #{:a nil} nil) (get #{:a nil} :c) (or + -) ((or + -) 1 2 3) ((and (= 1 1) +) 1 2 3) ((first [+ 0]) 1 2 3) (inc 1.1) (map inc [0 1 2 3]) (defn too-cute "Return a cheer for something cute" [thing] (str "That " thing "is too cute!")) (too-cute "puppy") (defn x-chop "Neochop" ([name chop] (str "Your " chop " chop inflicts pain on " name ".")) ([name] (x-chop name "karate"))) (x-chop "Khan") (x-chop "Khan" "slap") (defn squee [thing] (str "SQUEE! It's a " thing)) (defn squeer [& things] (map squee things)) (squeer "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") (defn favorite-things [name & things] (str "My name is " name " and I like " (clojure.string/join ", " things) ", etc.")) (favorite-things "PI:NAME:<NAME>END_PI" "puppies" "kitties") (defn x-first [[first-thing]] first-thing) (x-first [1 2 3 4]) (defn x-choose [[first-thing second-thing & other-things]] (str first-thing ", " second-thing ", " (clojure.string/join ", " other-things))) (x-choose ["this" "that" "the other" "the another"]) (defn x-find [{x :horz y :vert}] (println (str "(" x ", " y ")"))) (x-find {:horz 3 :vert -7}) (defn x-finder [{:keys [x y]}] (println (str "(" x ", " y ")"))) (x-finder {:x 4 :y -2}) (defn x-goer [{:keys [x y] :as coor}] (println (str "(" x ", " y ")")) (println coor)) (x-goer {:x 4 :y 2}) (map (fn [name] (str "Hey, " name)) ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) (def three-er (fn [x] (* 3 x))) (three-er 11) (#(* % 3) 8) (map #(str "Hey, " %) ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) (#(str %1 " and " %2) "this" "that") (#(identity %&) 1 2 3 :yo) (defn inc-maker "Make a custom incrementor" [inc-by] #(+ % inc-by)) (def inc42 (inc-maker 42)) (inc42 8) (def x 0) (let [x 1] x) (let [x (inc x)] x) (def puppy-list ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) (let [[pongo & puppies] puppy-list] [pongo puppies]) (into [:b] (set [:a :a])) (loop [itr 0] (println (str "Num " itr)) (if (> itr 3) (println "Done") (recur (inc itr)))) ; Chapter 4 (seq '(1 2 3)) (seq [1 2 3]) (seq #{1 2 3}) (seq {:a 1 :b 2}) (into {} (seq {:a 1 :b 2})) (map str ["a" "b" "c"] ["d" "e" "f"]) (map + [1 2 3] [-3 2 1]) (def humans [2.3 4.5 2.4 6.6 7.7]) (def critters [4.5 6.7 4.3 7.5 3.2]) (defn unify-diet [human critter] {:human human :critter critter}) (map unify-diet humans critters) (def sum #(reduce + %)) (def avg #(/ (sum %) (count %))) (defn stats [numbers] (map #(% numbers) [sum count avg])) (stats [3 4 1]) (stats [3.2 44 53.1 3.11]) (def identities [{:alias "PI:NAME:<NAME>END_PI" :real "PI:NAME:<NAME>END_PI"} {:alias "Spider-Man" :real "PI:NAME:<NAME>END_PI"} {:alias "PI:NAME:<NAME>END_PI" :real "Your mom"} {:alias "PI:NAME:<NAME>END_PI" :real "Your dad"}]) (map :real identities) (reduce (fn [new-map [key val]] (assoc new-map key (inc val))) {} {:a 20 :b 30}) (reduce (fn [new-map [key val]] (if (> val 4) (assoc new-map key val) new-map)) {} {:a 5 :b 2}) (take 3 [1 2 3 4 5]) (drop 3 [1 2 3 4 5]) (def food-journal [{:month 1 :day 1 :human 5.3 :critter 2.3} {:month 1 :day 2 :human 5.1 :critter 2.0} {:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} {:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} {:month 4 :day 1 :human 3.7 :critter 3.9} {:month 4 :day 2 :human 3.7 :critter 3.6}]) (take-while #(< (:month %) 3) food-journal) (drop-while #(< (:month %) 3) food-journal) (take-while #(< (:month %) 4) (drop-while #(< (:month %) 2) food-journal)) (filter #(< (:human %) 5) food-journal) (filter #(< (:month %) 3) food-journal) (some #(> (:critter %) 5) food-journal) (some #(> (:critter %) 3) food-journal) (some #(and (> (:critter %) 3) %) food-journal) (sort [4 3 5 3 2]) (sort-by count ["aaa" "c" "cc"]) (concat [1 2] [3 4]) (concat (take 8 (repeat "na")) ["PI:NAME:<NAME>END_PI!"]) (take 3 (repeatedly #(rand-int 10))) (defn even-numbers ([] (even-numbers 0)) ([n] (cons n (lazy-seq (even-numbers (+ n 2)))))) (take 10 (even-numbers)) (map identity {:a "b"}) (into {} (map identity {:a "b"})) (into [] (map identity {:a "b"})) (into [] (map identity [:a "b"])) (into #{} (map identity [:a :b :a])) (into {:a 1} [[:b 2]]) (into [:a] '(:b :c)) (into {:a 1} {:b 2}) (conj [0] 1 2 3 4 5) (max 0 4 5 2) (apply max [3 5 3 2 45 4 32]) (def add10 (partial + 10)) (add10 20) (defn lousy-logger [log-level message] (condp = log-level :warn (clojure.string/lower-case message) :emergency (clojure.string/upper-case message))) (def warn (partial lousy-logger :warn)) (warn "Puppies") ; Chapter 5 ((comp inc *) 3 5) (def character {:name "Link" :attrs {:int 10 :str 12 :dex 18}}) (def c-int (comp :int :attrs)) (def c-str (comp :str :attrs)) (def c-dex (comp :dex :attrs)) (c-int character) (c-str character) (c-dex character) (defn spell-slots [char] (int (inc (/ (c-int char) 2)))) (def spell-slots-comp (comp int inc #(/ % 2) c-int)) (spell-slots-comp character) (defn sleepy-ident [x] (Thread/sleep 100) x) (sleepy-ident "Ant-Man") (sleepy-ident "Ant-Man") (def memo-sleppy-ident (memoize sleepy-ident)) (memo-sleppy-ident "Ant-Man") (memo-sleppy-ident "Ant-Man") ; Chapter 7 (read-string "(1 + 1)") (let [infix (read-string "(1 + 1)")] (list (second infix) (first infix) (last infix))) (defmacro ignore-last-operand [function-call] (butlast function-call)) (ignore-last-operand (+ 1 2 10)) (defmacro infix [infixed] (list (second infixed) (first infixed) (last infixed))) (infix (1 + 2))
[ { "context": "----------------------------\n;; Copyright (c) 2011 Basho Technologies, Inc. All Rights Reserved.\n;;\n;; This file is pr", "end": 111, "score": 0.9715189933776855, "start": 93, "tag": "NAME", "value": "Basho Technologies" } ]
src/sumo/core.clj
reiddraper/sumo
3
;; ------------------------------------------------------------------- ;; Copyright (c) 2011 Basho Technologies, Inc. All Rights Reserved. ;; ;; This file is provided to you under the Apache License, ;; Version 2.0 (the "License"); you may not use this file ;; except in compliance with the License. You may obtain ;; a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, ;; software distributed under the License is distributed on an ;; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ;; KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations ;; under the License. ;; ;; ------------------------------------------------------------------- (ns sumo.core)
80517
;; ------------------------------------------------------------------- ;; Copyright (c) 2011 <NAME>, Inc. All Rights Reserved. ;; ;; This file is provided to you under the Apache License, ;; Version 2.0 (the "License"); you may not use this file ;; except in compliance with the License. You may obtain ;; a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, ;; software distributed under the License is distributed on an ;; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ;; KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations ;; under the License. ;; ;; ------------------------------------------------------------------- (ns sumo.core)
true
;; ------------------------------------------------------------------- ;; Copyright (c) 2011 PI:NAME:<NAME>END_PI, Inc. All Rights Reserved. ;; ;; This file is provided to you under the Apache License, ;; Version 2.0 (the "License"); you may not use this file ;; except in compliance with the License. You may obtain ;; a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, ;; software distributed under the License is distributed on an ;; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ;; KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations ;; under the License. ;; ;; ------------------------------------------------------------------- (ns sumo.core)
[ { "context": ";;;\n;;; Copyright 2020 David Edwards\n;;;\n;;; Licensed under the Apache License, Versio", "end": 36, "score": 0.9997876286506653, "start": 23, "tag": "NAME", "value": "David Edwards" } ]
src/rpn/optimizer.clj
davidledwards/rpn-clojure
1
;;; ;;; Copyright 2020 David Edwards ;;; ;;; 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 rpn.optimizer "Optimizer." (:require [rpn.code :as code]) (:require [rpn.evaluator :as evaluator])) (def ^:private dynamic-ctors {:add code/add-code :subtract code/subtract-code :multiply code/multiply-code :divide code/divide-code :min code/min-code :max code/max-code}) (defn- dynamic-code [kind argn] ((dynamic-ctors kind) argn)) (def ^:private operator-ctors (conj {:modulo (fn [& _] code/modulo-code) :power (fn [& _] code/power-code)} dynamic-ctors)) (defn- operator-code [kind argn] ((operator-ctors kind) argn)) (defn- revise [codes revs] (->> (reduce (fn [state code] (let [[pos cs] state] [(inc pos) (if-let [c (revs pos)] (if (code/nop-code? c) cs (conj cs c)) (conj cs code))])) [0 []] codes) (#(seq (last %))))) (defn- combine-operators-revisions [codes] (->> (reduce (fn [state code] (let [[pos frames revs] state] (cons (inc pos) (cond (or (code/push-symbol-code? code) (code/push-code? code)) [(cons nil frames) revs] (code/multiary-operator? code) (->> (let [f (first (drop (dec (code :argn)) frames))] (if (and f (code/same-kind? (f :code) code)) (let [new-code (dynamic-code (code/kind code) (dec (+ (code :argn) ((f :code) :argn))))] [new-code (assoc revs (f :pos) code/nop-code pos new-code)]) [code revs])) (#(let [[new-code revs] %] [(->> (drop (code :argn) frames) (cons {:pos pos :code new-code})) revs]))) (code/operator? code) [(->> (drop (code :argn) frames) (cons nil)) revs] :else [frames revs])))) [0 nil {}] codes) (#(last %)))) (defn combine-operators "An optimization that combines a series of identical operations as they appear in the original source. Consider the following input: `x + y + z` The parser generates an AST that first evaluates `x + y`, then evaluates the result of that expression and `z`. The corresponding bytecode follows: ``` push x push y add 2 push z add 2 ``` The `add 2` instruction tells the interpreter to pop `2` elements from the evaluation stack, compute the sum, and push the result onto the stack. Since the `add` instruction can operate on any number of arguments, both `add` operations can be combined into a single instruction: ``` push x push y push z add 3 ``` A slightly more complicated example illustrates the same principle. Consider the input, `a + (b * c) + d`, and the corresponding bytecode: ``` push a push b push c mul 2 add 2 push d add 2 ``` Similar to the first scenario, both `add` operations can be combined even though the intervening expression `b * c` exists. Note that adjacency of instructions is not relevant, but rather the equivalence of the evaluation stack frame depth. In other words, all operations of the same type at the same frame can be combined into a single operation. The algorithm works by simulating execution using an evaluation stack, maintaining a set of instructions that are candidates for elimination. If another instruction at the same frame depth is encountered, the original instruction is replaced with a `nop` and the current instruction modified to evaluate additional elements on the stack. Once all instructions have been evaluated, the set of revisions are applied, resulting in a new sequence of instructions." [codes] (revise codes (combine-operators-revisions codes))) (defn- flatten-operators-revisions [codes] (->> (reduce (fn [state code] (let [[pos prior revs] state] (cons (inc pos) (if (and (code/multiary-operator? code) (code/associative-operator? code)) (if (code/same-kind? code prior) (let [new-code (dynamic-code (code/kind code) (dec (+ (code :argn) (prior :argn))))] [new-code (assoc revs (dec pos) code/nop-code pos new-code)]) [code revs]) [nil revs])))) [0 nil {}] codes) (#(last %)))) (defn flatten-operators "An optimization that flattens identical operations adjacent to each other in the instruction sequence. This optimization is similar to [[combine-operators]] in that operations are essentially combined, but instead it looks for special cases in which identical operations occur in adjacent frames on the evaluation stack. Consider the input, `x * (y * z)`, and the corresponding bytecode: ``` push x push y push z mul 2 mul 2 ``` Note that both `mul` instructions occur in adjacent positions. At first glance, it may appear as though [[combine-operators]] would eliminate one of the operations, but each occurs at a different frame on the evaluation stack. The intuition behind this optimization is that the first `mul 2` would push its result onto the stack, only to be removed for evaluation by the second `mul 2` instruction. So, rather than performing an intermediate calculation, the first can be eliminated in lieu of a single `mul 3` instruction. In general, any number of adjacent identical instructions can be reduced to a single instruction. One may notice that this phase optimizes right-to-left evaluation scenarios, but only for those operators with the associative property, i.e. evaluation can be left-to-right or right-to-left. This becomes more clear with another example: `a * (b * (c * d))`. The original instruction sequence follows: ``` push a push b push c push d mul 2 mul 2 mul 2 ``` In essence, the parentheses are being removed and evaluated in a left-to-right manner by eliminating all but the last `mul` instruction: ``` push a push b push c push d mul 4 ``` The algorithm works by stepping through each associative operator instruction, finding adjacent identical pairs, and eliminating all but the final instruction, which is then modified to reflect the combined number of arguments." [codes] (revise codes (flatten-operators-revisions codes))) (defn- evaluate-literals-revisions ([codes] (evaluate-literals-revisions 0 codes ())) ([pos codes stack] (let [c (first codes)] (cond (code/declare-symbol-code? c) (recur (inc pos) (rest codes) stack) (code/push-symbol-code? c) (recur (inc pos) (rest codes) (cons nil stack)) (code/push-code? c) (recur (inc pos) (rest codes) (cons {:pos pos :value (c :value)} stack)) (code/operator? c) (->> [(let [nums (filter some? (reverse (take (c :argn) stack)))] (if (or (and (> (count nums) 1) (code/commutative-operator? c)) (= (count nums) (c :argn))) (conj (reduce (fn [revs num] (conj revs {(num :pos) code/nop-code})) {} (drop-last nums)) {((last nums) :pos) (code/push-code (reduce (evaluator/operators (code/kind c)) (map #(% :value) nums)))} {pos (if (= (count nums) (c :argn)) code/nop-code (operator-code (code/kind c) (inc (- (c :argn) (count nums)))))}) {})) (cons nil (drop (c :argn) stack))] (#(let [[revs stack] %] (if (empty? revs) (evaluate-literals-revisions (inc pos) (rest codes) stack) revs)))) (nil? c) {} :else (recur (inc pos) (rest codes) stack))))) (defn evaluate-literals "An optimization that evaluates literal expressions. This optimization finds expressions containing only literal values and reduces them to a single value, thereby eliminating the need for the interpreter to perform the computation. Consider the input, `x + 1 + y + 2`, which produces the following sequence of unoptimized instructions: ``` push x push 1 add 2 push y add 2 push 2 add 2 ``` Applying the [[combine-operators]] optimization produces the following: ``` push x push 1 push y push 2 add 4 ``` In either case, there is still opportunity to further optimize. Had the original input been written as `x + y + 1 + 2`, it becomes more clear that `1 + 2` could be replaced with `3`. The purpose of this optimization phase is to find such expressions and reduce them to a single value. In the latter optimized case above, applying this optimization reduces the instruction sequence to the following: ``` push x push y push 3 add 3 ``` The algorithm works by simulating execution of the instruction sequence using an evaluation stack, though recording only literal values. As operations are encountered, the optimizer peeks into the evaluation stack to determine if two or more literals are present, and if so, eliminates the `push` instruction corresponding to each literal in lieu of a single `push`. When an optimization is detected, the evaluation terminates and revisions are applied to the original sequence of instructions. This process repeats itself until a complete evaluation yields no new optimizations. Note that an expression consisting entirely of literals will always be reduced to a single `push` instruction containing the computed value." [codes] (let [revs (evaluate-literals-revisions codes)] (if (empty? revs) codes (recur (revise codes revs))))) (def ^:private optimizations (comp evaluate-literals flatten-operators combine-operators)) (defn optimizer "An optimizer that transforms a sequence of instructions into another sequence of instructions." [codes] (let [cs (optimizations codes)] (if (< (count cs) (count codes)) (recur cs) cs)))
91067
;;; ;;; Copyright 2020 <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 rpn.optimizer "Optimizer." (:require [rpn.code :as code]) (:require [rpn.evaluator :as evaluator])) (def ^:private dynamic-ctors {:add code/add-code :subtract code/subtract-code :multiply code/multiply-code :divide code/divide-code :min code/min-code :max code/max-code}) (defn- dynamic-code [kind argn] ((dynamic-ctors kind) argn)) (def ^:private operator-ctors (conj {:modulo (fn [& _] code/modulo-code) :power (fn [& _] code/power-code)} dynamic-ctors)) (defn- operator-code [kind argn] ((operator-ctors kind) argn)) (defn- revise [codes revs] (->> (reduce (fn [state code] (let [[pos cs] state] [(inc pos) (if-let [c (revs pos)] (if (code/nop-code? c) cs (conj cs c)) (conj cs code))])) [0 []] codes) (#(seq (last %))))) (defn- combine-operators-revisions [codes] (->> (reduce (fn [state code] (let [[pos frames revs] state] (cons (inc pos) (cond (or (code/push-symbol-code? code) (code/push-code? code)) [(cons nil frames) revs] (code/multiary-operator? code) (->> (let [f (first (drop (dec (code :argn)) frames))] (if (and f (code/same-kind? (f :code) code)) (let [new-code (dynamic-code (code/kind code) (dec (+ (code :argn) ((f :code) :argn))))] [new-code (assoc revs (f :pos) code/nop-code pos new-code)]) [code revs])) (#(let [[new-code revs] %] [(->> (drop (code :argn) frames) (cons {:pos pos :code new-code})) revs]))) (code/operator? code) [(->> (drop (code :argn) frames) (cons nil)) revs] :else [frames revs])))) [0 nil {}] codes) (#(last %)))) (defn combine-operators "An optimization that combines a series of identical operations as they appear in the original source. Consider the following input: `x + y + z` The parser generates an AST that first evaluates `x + y`, then evaluates the result of that expression and `z`. The corresponding bytecode follows: ``` push x push y add 2 push z add 2 ``` The `add 2` instruction tells the interpreter to pop `2` elements from the evaluation stack, compute the sum, and push the result onto the stack. Since the `add` instruction can operate on any number of arguments, both `add` operations can be combined into a single instruction: ``` push x push y push z add 3 ``` A slightly more complicated example illustrates the same principle. Consider the input, `a + (b * c) + d`, and the corresponding bytecode: ``` push a push b push c mul 2 add 2 push d add 2 ``` Similar to the first scenario, both `add` operations can be combined even though the intervening expression `b * c` exists. Note that adjacency of instructions is not relevant, but rather the equivalence of the evaluation stack frame depth. In other words, all operations of the same type at the same frame can be combined into a single operation. The algorithm works by simulating execution using an evaluation stack, maintaining a set of instructions that are candidates for elimination. If another instruction at the same frame depth is encountered, the original instruction is replaced with a `nop` and the current instruction modified to evaluate additional elements on the stack. Once all instructions have been evaluated, the set of revisions are applied, resulting in a new sequence of instructions." [codes] (revise codes (combine-operators-revisions codes))) (defn- flatten-operators-revisions [codes] (->> (reduce (fn [state code] (let [[pos prior revs] state] (cons (inc pos) (if (and (code/multiary-operator? code) (code/associative-operator? code)) (if (code/same-kind? code prior) (let [new-code (dynamic-code (code/kind code) (dec (+ (code :argn) (prior :argn))))] [new-code (assoc revs (dec pos) code/nop-code pos new-code)]) [code revs]) [nil revs])))) [0 nil {}] codes) (#(last %)))) (defn flatten-operators "An optimization that flattens identical operations adjacent to each other in the instruction sequence. This optimization is similar to [[combine-operators]] in that operations are essentially combined, but instead it looks for special cases in which identical operations occur in adjacent frames on the evaluation stack. Consider the input, `x * (y * z)`, and the corresponding bytecode: ``` push x push y push z mul 2 mul 2 ``` Note that both `mul` instructions occur in adjacent positions. At first glance, it may appear as though [[combine-operators]] would eliminate one of the operations, but each occurs at a different frame on the evaluation stack. The intuition behind this optimization is that the first `mul 2` would push its result onto the stack, only to be removed for evaluation by the second `mul 2` instruction. So, rather than performing an intermediate calculation, the first can be eliminated in lieu of a single `mul 3` instruction. In general, any number of adjacent identical instructions can be reduced to a single instruction. One may notice that this phase optimizes right-to-left evaluation scenarios, but only for those operators with the associative property, i.e. evaluation can be left-to-right or right-to-left. This becomes more clear with another example: `a * (b * (c * d))`. The original instruction sequence follows: ``` push a push b push c push d mul 2 mul 2 mul 2 ``` In essence, the parentheses are being removed and evaluated in a left-to-right manner by eliminating all but the last `mul` instruction: ``` push a push b push c push d mul 4 ``` The algorithm works by stepping through each associative operator instruction, finding adjacent identical pairs, and eliminating all but the final instruction, which is then modified to reflect the combined number of arguments." [codes] (revise codes (flatten-operators-revisions codes))) (defn- evaluate-literals-revisions ([codes] (evaluate-literals-revisions 0 codes ())) ([pos codes stack] (let [c (first codes)] (cond (code/declare-symbol-code? c) (recur (inc pos) (rest codes) stack) (code/push-symbol-code? c) (recur (inc pos) (rest codes) (cons nil stack)) (code/push-code? c) (recur (inc pos) (rest codes) (cons {:pos pos :value (c :value)} stack)) (code/operator? c) (->> [(let [nums (filter some? (reverse (take (c :argn) stack)))] (if (or (and (> (count nums) 1) (code/commutative-operator? c)) (= (count nums) (c :argn))) (conj (reduce (fn [revs num] (conj revs {(num :pos) code/nop-code})) {} (drop-last nums)) {((last nums) :pos) (code/push-code (reduce (evaluator/operators (code/kind c)) (map #(% :value) nums)))} {pos (if (= (count nums) (c :argn)) code/nop-code (operator-code (code/kind c) (inc (- (c :argn) (count nums)))))}) {})) (cons nil (drop (c :argn) stack))] (#(let [[revs stack] %] (if (empty? revs) (evaluate-literals-revisions (inc pos) (rest codes) stack) revs)))) (nil? c) {} :else (recur (inc pos) (rest codes) stack))))) (defn evaluate-literals "An optimization that evaluates literal expressions. This optimization finds expressions containing only literal values and reduces them to a single value, thereby eliminating the need for the interpreter to perform the computation. Consider the input, `x + 1 + y + 2`, which produces the following sequence of unoptimized instructions: ``` push x push 1 add 2 push y add 2 push 2 add 2 ``` Applying the [[combine-operators]] optimization produces the following: ``` push x push 1 push y push 2 add 4 ``` In either case, there is still opportunity to further optimize. Had the original input been written as `x + y + 1 + 2`, it becomes more clear that `1 + 2` could be replaced with `3`. The purpose of this optimization phase is to find such expressions and reduce them to a single value. In the latter optimized case above, applying this optimization reduces the instruction sequence to the following: ``` push x push y push 3 add 3 ``` The algorithm works by simulating execution of the instruction sequence using an evaluation stack, though recording only literal values. As operations are encountered, the optimizer peeks into the evaluation stack to determine if two or more literals are present, and if so, eliminates the `push` instruction corresponding to each literal in lieu of a single `push`. When an optimization is detected, the evaluation terminates and revisions are applied to the original sequence of instructions. This process repeats itself until a complete evaluation yields no new optimizations. Note that an expression consisting entirely of literals will always be reduced to a single `push` instruction containing the computed value." [codes] (let [revs (evaluate-literals-revisions codes)] (if (empty? revs) codes (recur (revise codes revs))))) (def ^:private optimizations (comp evaluate-literals flatten-operators combine-operators)) (defn optimizer "An optimizer that transforms a sequence of instructions into another sequence of instructions." [codes] (let [cs (optimizations codes)] (if (< (count cs) (count codes)) (recur cs) cs)))
true
;;; ;;; Copyright 2020 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 rpn.optimizer "Optimizer." (:require [rpn.code :as code]) (:require [rpn.evaluator :as evaluator])) (def ^:private dynamic-ctors {:add code/add-code :subtract code/subtract-code :multiply code/multiply-code :divide code/divide-code :min code/min-code :max code/max-code}) (defn- dynamic-code [kind argn] ((dynamic-ctors kind) argn)) (def ^:private operator-ctors (conj {:modulo (fn [& _] code/modulo-code) :power (fn [& _] code/power-code)} dynamic-ctors)) (defn- operator-code [kind argn] ((operator-ctors kind) argn)) (defn- revise [codes revs] (->> (reduce (fn [state code] (let [[pos cs] state] [(inc pos) (if-let [c (revs pos)] (if (code/nop-code? c) cs (conj cs c)) (conj cs code))])) [0 []] codes) (#(seq (last %))))) (defn- combine-operators-revisions [codes] (->> (reduce (fn [state code] (let [[pos frames revs] state] (cons (inc pos) (cond (or (code/push-symbol-code? code) (code/push-code? code)) [(cons nil frames) revs] (code/multiary-operator? code) (->> (let [f (first (drop (dec (code :argn)) frames))] (if (and f (code/same-kind? (f :code) code)) (let [new-code (dynamic-code (code/kind code) (dec (+ (code :argn) ((f :code) :argn))))] [new-code (assoc revs (f :pos) code/nop-code pos new-code)]) [code revs])) (#(let [[new-code revs] %] [(->> (drop (code :argn) frames) (cons {:pos pos :code new-code})) revs]))) (code/operator? code) [(->> (drop (code :argn) frames) (cons nil)) revs] :else [frames revs])))) [0 nil {}] codes) (#(last %)))) (defn combine-operators "An optimization that combines a series of identical operations as they appear in the original source. Consider the following input: `x + y + z` The parser generates an AST that first evaluates `x + y`, then evaluates the result of that expression and `z`. The corresponding bytecode follows: ``` push x push y add 2 push z add 2 ``` The `add 2` instruction tells the interpreter to pop `2` elements from the evaluation stack, compute the sum, and push the result onto the stack. Since the `add` instruction can operate on any number of arguments, both `add` operations can be combined into a single instruction: ``` push x push y push z add 3 ``` A slightly more complicated example illustrates the same principle. Consider the input, `a + (b * c) + d`, and the corresponding bytecode: ``` push a push b push c mul 2 add 2 push d add 2 ``` Similar to the first scenario, both `add` operations can be combined even though the intervening expression `b * c` exists. Note that adjacency of instructions is not relevant, but rather the equivalence of the evaluation stack frame depth. In other words, all operations of the same type at the same frame can be combined into a single operation. The algorithm works by simulating execution using an evaluation stack, maintaining a set of instructions that are candidates for elimination. If another instruction at the same frame depth is encountered, the original instruction is replaced with a `nop` and the current instruction modified to evaluate additional elements on the stack. Once all instructions have been evaluated, the set of revisions are applied, resulting in a new sequence of instructions." [codes] (revise codes (combine-operators-revisions codes))) (defn- flatten-operators-revisions [codes] (->> (reduce (fn [state code] (let [[pos prior revs] state] (cons (inc pos) (if (and (code/multiary-operator? code) (code/associative-operator? code)) (if (code/same-kind? code prior) (let [new-code (dynamic-code (code/kind code) (dec (+ (code :argn) (prior :argn))))] [new-code (assoc revs (dec pos) code/nop-code pos new-code)]) [code revs]) [nil revs])))) [0 nil {}] codes) (#(last %)))) (defn flatten-operators "An optimization that flattens identical operations adjacent to each other in the instruction sequence. This optimization is similar to [[combine-operators]] in that operations are essentially combined, but instead it looks for special cases in which identical operations occur in adjacent frames on the evaluation stack. Consider the input, `x * (y * z)`, and the corresponding bytecode: ``` push x push y push z mul 2 mul 2 ``` Note that both `mul` instructions occur in adjacent positions. At first glance, it may appear as though [[combine-operators]] would eliminate one of the operations, but each occurs at a different frame on the evaluation stack. The intuition behind this optimization is that the first `mul 2` would push its result onto the stack, only to be removed for evaluation by the second `mul 2` instruction. So, rather than performing an intermediate calculation, the first can be eliminated in lieu of a single `mul 3` instruction. In general, any number of adjacent identical instructions can be reduced to a single instruction. One may notice that this phase optimizes right-to-left evaluation scenarios, but only for those operators with the associative property, i.e. evaluation can be left-to-right or right-to-left. This becomes more clear with another example: `a * (b * (c * d))`. The original instruction sequence follows: ``` push a push b push c push d mul 2 mul 2 mul 2 ``` In essence, the parentheses are being removed and evaluated in a left-to-right manner by eliminating all but the last `mul` instruction: ``` push a push b push c push d mul 4 ``` The algorithm works by stepping through each associative operator instruction, finding adjacent identical pairs, and eliminating all but the final instruction, which is then modified to reflect the combined number of arguments." [codes] (revise codes (flatten-operators-revisions codes))) (defn- evaluate-literals-revisions ([codes] (evaluate-literals-revisions 0 codes ())) ([pos codes stack] (let [c (first codes)] (cond (code/declare-symbol-code? c) (recur (inc pos) (rest codes) stack) (code/push-symbol-code? c) (recur (inc pos) (rest codes) (cons nil stack)) (code/push-code? c) (recur (inc pos) (rest codes) (cons {:pos pos :value (c :value)} stack)) (code/operator? c) (->> [(let [nums (filter some? (reverse (take (c :argn) stack)))] (if (or (and (> (count nums) 1) (code/commutative-operator? c)) (= (count nums) (c :argn))) (conj (reduce (fn [revs num] (conj revs {(num :pos) code/nop-code})) {} (drop-last nums)) {((last nums) :pos) (code/push-code (reduce (evaluator/operators (code/kind c)) (map #(% :value) nums)))} {pos (if (= (count nums) (c :argn)) code/nop-code (operator-code (code/kind c) (inc (- (c :argn) (count nums)))))}) {})) (cons nil (drop (c :argn) stack))] (#(let [[revs stack] %] (if (empty? revs) (evaluate-literals-revisions (inc pos) (rest codes) stack) revs)))) (nil? c) {} :else (recur (inc pos) (rest codes) stack))))) (defn evaluate-literals "An optimization that evaluates literal expressions. This optimization finds expressions containing only literal values and reduces them to a single value, thereby eliminating the need for the interpreter to perform the computation. Consider the input, `x + 1 + y + 2`, which produces the following sequence of unoptimized instructions: ``` push x push 1 add 2 push y add 2 push 2 add 2 ``` Applying the [[combine-operators]] optimization produces the following: ``` push x push 1 push y push 2 add 4 ``` In either case, there is still opportunity to further optimize. Had the original input been written as `x + y + 1 + 2`, it becomes more clear that `1 + 2` could be replaced with `3`. The purpose of this optimization phase is to find such expressions and reduce them to a single value. In the latter optimized case above, applying this optimization reduces the instruction sequence to the following: ``` push x push y push 3 add 3 ``` The algorithm works by simulating execution of the instruction sequence using an evaluation stack, though recording only literal values. As operations are encountered, the optimizer peeks into the evaluation stack to determine if two or more literals are present, and if so, eliminates the `push` instruction corresponding to each literal in lieu of a single `push`. When an optimization is detected, the evaluation terminates and revisions are applied to the original sequence of instructions. This process repeats itself until a complete evaluation yields no new optimizations. Note that an expression consisting entirely of literals will always be reduced to a single `push` instruction containing the computed value." [codes] (let [revs (evaluate-literals-revisions codes)] (if (empty? revs) codes (recur (revise codes revs))))) (def ^:private optimizations (comp evaluate-literals flatten-operators combine-operators)) (defn optimizer "An optimizer that transforms a sequence of instructions into another sequence of instructions." [codes] (let [cs (optimizations codes)] (if (< (count cs) (count codes)) (recur cs) cs)))
[ { "context": " [{:first_name \"Sergey\"} {:first_name \"Uniqueman\"}])\n (let [response ", "end": 981, "score": 0.9998397827148438, "start": 975, "tag": "NAME", "value": "Sergey" }, { "context": " [{:first_name \"Sergey\"} {:first_name \"Uniqueman\"}])\n (let [response (app/handler (test-utils/j", "end": 1007, "score": 0.9998235702514648, "start": 998, "tag": "NAME", "value": "Uniqueman" }, { "context": " :body {:patients [{:full_name #(str/includes? % \"Sergey\")}\n {:full_name #(str/i", "end": 1194, "score": 0.9997100234031677, "start": 1188, "tag": "NAME", "value": "Sergey" }, { "context": " {:full_name #(str/includes? % \"Uniqueman\")}]}}\n response))))\n\n\n(deftest show-patien", "end": 1265, "score": 0.9996234178543091, "start": 1256, "tag": "NAME", "value": "Uniqueman" }, { "context": " [{:id 1 :first_name \"Sergey\" :last_name \"Zaborovsky\"}])\n (let [response (a", "end": 1519, "score": 0.9998111724853516, "start": 1513, "tag": "NAME", "value": "Sergey" }, { "context": " [{:id 1 :first_name \"Sergey\" :last_name \"Zaborovsky\"}])\n (let [response (app/handler (test-utils/j", "end": 1543, "score": 0.9997602701187134, "start": 1533, "tag": "NAME", "value": "Zaborovsky" }, { "context": " {:status 200\n :body {:first_name \"Sergey\"\n :last_name \"Zaborovsky\"}}\n ", "end": 1703, "score": 0.9997838139533997, "start": 1697, "tag": "NAME", "value": "Sergey" }, { "context": "{:first_name \"Sergey\"\n :last_name \"Zaborovsky\"}}\n response)))\n\n (testing \"Don't show no", "end": 1743, "score": 0.9997521638870239, "start": 1733, "tag": "NAME", "value": "Zaborovsky" }, { "context": " [{:id 1 :first_name \"Sergey\"}])\n (let [response (app/handler (test-utils/j", "end": 2189, "score": 0.997648298740387, "start": 2183, "tag": "NAME", "value": "Sergey" }, { "context": " [{:id 1, :first_name \"Not-Sergey\"}])\n (let [updated-patient-data (test-utils/ma", "end": 2855, "score": 0.9844716787338257, "start": 2845, "tag": "NAME", "value": "Not-Sergey" }, { "context": "s/make-test-record generate-patient {:first_name \"Updated-Sergey\"})\n response (app/handler (test-u", "end": 2958, "score": 0.5123268365859985, "start": 2951, "tag": "NAME", "value": "Updated" }, { "context": "-record generate-patient {:first_name \"Updated-Sergey\"})\n response (app/handler (test-utils/js", "end": 2965, "score": 0.8424980044364929, "start": 2962, "tag": "NAME", "value": "gey" }, { "context": "ssert {:status 200 :body {:first_name \"Updated-Sergey\"}} response))))\n\n(deftest insert-patient-test\n (", "end": 3266, "score": 0.7778500318527222, "start": 3263, "tag": "NAME", "value": "gey" }, { "context": "records :patients generate-patient [{:first_name \"Sergey\"}\n ", "end": 3682, "score": 0.9998437762260437, "start": 3676, "tag": "NAME", "value": "Sergey" }, { "context": " {:first_name \"Ivan\"}])\n (let [response (app/handler (test-utils/j", "end": 3767, "score": 0.9998475313186646, "start": 3763, "tag": "NAME", "value": "Ivan" }, { "context": "equest :get \"/api/patients\" :query {:search-name \"Ser\"}))]\n (m/assert\n {:status 200\n ", "end": 3875, "score": 0.9975276589393616, "start": 3872, "tag": "NAME", "value": "Ser" }, { "context": " :body {:patients [{:full_name #(str/includes? % \"Sergey\")}]}}\n response))))\n", "end": 3982, "score": 0.9998135566711426, "start": 3976, "tag": "NAME", "value": "Sergey" } ]
test/health_patient/patients_test.clj
Seryiza/health-patient
0
(ns health-patient.patients-test (:require [re-rand :refer [re-rand]] [clojure.test :refer [deftest testing use-fixtures]] [clojure.string :as str] [matcho.core :as m] [health-patient.app :as app] [health-patient.test-utils :as test-utils])) (use-fixtures :once test-utils/with-test-db) (use-fixtures :each test-utils/with-transaction) (defn generate-patient [] {:first_name (re-rand #"[A-Z][a-z]{1,20}") :last_name (re-rand #"[A-Z][a-z]{1,20}") :middle_name (re-rand #"[A-Z][a-z]{1,20}") :sex (rand-nth ["male" "female" "not-known" "not-applicable"]) :birth_date (re-rand #"19[0-9]{2}-0[1-9]-0[1-9]") :address (re-rand #"[A-Za-z0-9\ ]{1,40}") :cmi_number (re-rand #"[1-9]{16}")}) (deftest list-patients-test (testing "List all patients" (test-utils/insert-test-records :patients generate-patient [{:first_name "Sergey"} {:first_name "Uniqueman"}]) (let [response (app/handler (test-utils/json-request :get "/api/patients"))] (m/assert {:status 200 :body {:patients [{:full_name #(str/includes? % "Sergey")} {:full_name #(str/includes? % "Uniqueman")}]}} response)))) (deftest show-patient-test (testing "Show existing patient" (test-utils/insert-test-records :patients generate-patient [{:id 1 :first_name "Sergey" :last_name "Zaborovsky"}]) (let [response (app/handler (test-utils/json-request :get "/api/patients/1"))] (m/assert {:status 200 :body {:first_name "Sergey" :last_name "Zaborovsky"}} response))) (testing "Don't show non-existing patient" (let [response (app/handler (test-utils/json-request :get "/api/patients/2"))] (m/assert {:status 404} response)))) (deftest delete-patient-test (testing "Delete existing patient and try delete again" (test-utils/insert-test-records :patients generate-patient [{:id 1 :first_name "Sergey"}]) (let [response (app/handler (test-utils/json-request :delete "/api/patients/1"))] (m/assert {:status 200} response)) (let [response (app/handler (test-utils/json-request :delete "/api/patients/1"))] (m/assert {:status 404} response))) (testing "Delete non-existing patient" (let [response (app/handler (test-utils/json-request :delete "/api/patients/2"))] (m/assert {:status 404} response)))) (deftest update-patient-test (testing "Update exisiting patient" (test-utils/insert-test-records :patients generate-patient [{:id 1, :first_name "Not-Sergey"}]) (let [updated-patient-data (test-utils/make-test-record generate-patient {:first_name "Updated-Sergey"}) response (app/handler (test-utils/json-request :put "/api/patients/1" :json updated-patient-data))] (m/assert {:status 200} response)) (let [response (app/handler (test-utils/json-request :get "/api/patients/1"))] (m/assert {:status 200 :body {:first_name "Updated-Sergey"}} response)))) (deftest insert-patient-test (testing "Insert new patient" (let [patient-data (generate-patient) response (app/handler (test-utils/json-request :post "/api/patients" :json patient-data))] (m/assert {:status 201} response)))) (deftest search-patient-test (testing "Search patients by name" (test-utils/insert-test-records :patients generate-patient [{:first_name "Sergey"} {:first_name "Ivan"}]) (let [response (app/handler (test-utils/json-request :get "/api/patients" :query {:search-name "Ser"}))] (m/assert {:status 200 :body {:patients [{:full_name #(str/includes? % "Sergey")}]}} response))))
69565
(ns health-patient.patients-test (:require [re-rand :refer [re-rand]] [clojure.test :refer [deftest testing use-fixtures]] [clojure.string :as str] [matcho.core :as m] [health-patient.app :as app] [health-patient.test-utils :as test-utils])) (use-fixtures :once test-utils/with-test-db) (use-fixtures :each test-utils/with-transaction) (defn generate-patient [] {:first_name (re-rand #"[A-Z][a-z]{1,20}") :last_name (re-rand #"[A-Z][a-z]{1,20}") :middle_name (re-rand #"[A-Z][a-z]{1,20}") :sex (rand-nth ["male" "female" "not-known" "not-applicable"]) :birth_date (re-rand #"19[0-9]{2}-0[1-9]-0[1-9]") :address (re-rand #"[A-Za-z0-9\ ]{1,40}") :cmi_number (re-rand #"[1-9]{16}")}) (deftest list-patients-test (testing "List all patients" (test-utils/insert-test-records :patients generate-patient [{:first_name "<NAME>"} {:first_name "<NAME>"}]) (let [response (app/handler (test-utils/json-request :get "/api/patients"))] (m/assert {:status 200 :body {:patients [{:full_name #(str/includes? % "<NAME>")} {:full_name #(str/includes? % "<NAME>")}]}} response)))) (deftest show-patient-test (testing "Show existing patient" (test-utils/insert-test-records :patients generate-patient [{:id 1 :first_name "<NAME>" :last_name "<NAME>"}]) (let [response (app/handler (test-utils/json-request :get "/api/patients/1"))] (m/assert {:status 200 :body {:first_name "<NAME>" :last_name "<NAME>"}} response))) (testing "Don't show non-existing patient" (let [response (app/handler (test-utils/json-request :get "/api/patients/2"))] (m/assert {:status 404} response)))) (deftest delete-patient-test (testing "Delete existing patient and try delete again" (test-utils/insert-test-records :patients generate-patient [{:id 1 :first_name "<NAME>"}]) (let [response (app/handler (test-utils/json-request :delete "/api/patients/1"))] (m/assert {:status 200} response)) (let [response (app/handler (test-utils/json-request :delete "/api/patients/1"))] (m/assert {:status 404} response))) (testing "Delete non-existing patient" (let [response (app/handler (test-utils/json-request :delete "/api/patients/2"))] (m/assert {:status 404} response)))) (deftest update-patient-test (testing "Update exisiting patient" (test-utils/insert-test-records :patients generate-patient [{:id 1, :first_name "<NAME>"}]) (let [updated-patient-data (test-utils/make-test-record generate-patient {:first_name "<NAME>-Ser<NAME>"}) response (app/handler (test-utils/json-request :put "/api/patients/1" :json updated-patient-data))] (m/assert {:status 200} response)) (let [response (app/handler (test-utils/json-request :get "/api/patients/1"))] (m/assert {:status 200 :body {:first_name "Updated-Ser<NAME>"}} response)))) (deftest insert-patient-test (testing "Insert new patient" (let [patient-data (generate-patient) response (app/handler (test-utils/json-request :post "/api/patients" :json patient-data))] (m/assert {:status 201} response)))) (deftest search-patient-test (testing "Search patients by name" (test-utils/insert-test-records :patients generate-patient [{:first_name "<NAME>"} {:first_name "<NAME>"}]) (let [response (app/handler (test-utils/json-request :get "/api/patients" :query {:search-name "<NAME>"}))] (m/assert {:status 200 :body {:patients [{:full_name #(str/includes? % "<NAME>")}]}} response))))
true
(ns health-patient.patients-test (:require [re-rand :refer [re-rand]] [clojure.test :refer [deftest testing use-fixtures]] [clojure.string :as str] [matcho.core :as m] [health-patient.app :as app] [health-patient.test-utils :as test-utils])) (use-fixtures :once test-utils/with-test-db) (use-fixtures :each test-utils/with-transaction) (defn generate-patient [] {:first_name (re-rand #"[A-Z][a-z]{1,20}") :last_name (re-rand #"[A-Z][a-z]{1,20}") :middle_name (re-rand #"[A-Z][a-z]{1,20}") :sex (rand-nth ["male" "female" "not-known" "not-applicable"]) :birth_date (re-rand #"19[0-9]{2}-0[1-9]-0[1-9]") :address (re-rand #"[A-Za-z0-9\ ]{1,40}") :cmi_number (re-rand #"[1-9]{16}")}) (deftest list-patients-test (testing "List all patients" (test-utils/insert-test-records :patients generate-patient [{:first_name "PI:NAME:<NAME>END_PI"} {:first_name "PI:NAME:<NAME>END_PI"}]) (let [response (app/handler (test-utils/json-request :get "/api/patients"))] (m/assert {:status 200 :body {:patients [{:full_name #(str/includes? % "PI:NAME:<NAME>END_PI")} {:full_name #(str/includes? % "PI:NAME:<NAME>END_PI")}]}} response)))) (deftest show-patient-test (testing "Show existing patient" (test-utils/insert-test-records :patients generate-patient [{:id 1 :first_name "PI:NAME:<NAME>END_PI" :last_name "PI:NAME:<NAME>END_PI"}]) (let [response (app/handler (test-utils/json-request :get "/api/patients/1"))] (m/assert {:status 200 :body {:first_name "PI:NAME:<NAME>END_PI" :last_name "PI:NAME:<NAME>END_PI"}} response))) (testing "Don't show non-existing patient" (let [response (app/handler (test-utils/json-request :get "/api/patients/2"))] (m/assert {:status 404} response)))) (deftest delete-patient-test (testing "Delete existing patient and try delete again" (test-utils/insert-test-records :patients generate-patient [{:id 1 :first_name "PI:NAME:<NAME>END_PI"}]) (let [response (app/handler (test-utils/json-request :delete "/api/patients/1"))] (m/assert {:status 200} response)) (let [response (app/handler (test-utils/json-request :delete "/api/patients/1"))] (m/assert {:status 404} response))) (testing "Delete non-existing patient" (let [response (app/handler (test-utils/json-request :delete "/api/patients/2"))] (m/assert {:status 404} response)))) (deftest update-patient-test (testing "Update exisiting patient" (test-utils/insert-test-records :patients generate-patient [{:id 1, :first_name "PI:NAME:<NAME>END_PI"}]) (let [updated-patient-data (test-utils/make-test-record generate-patient {:first_name "PI:NAME:<NAME>END_PI-SerPI:NAME:<NAME>END_PI"}) response (app/handler (test-utils/json-request :put "/api/patients/1" :json updated-patient-data))] (m/assert {:status 200} response)) (let [response (app/handler (test-utils/json-request :get "/api/patients/1"))] (m/assert {:status 200 :body {:first_name "Updated-SerPI:NAME:<NAME>END_PI"}} response)))) (deftest insert-patient-test (testing "Insert new patient" (let [patient-data (generate-patient) response (app/handler (test-utils/json-request :post "/api/patients" :json patient-data))] (m/assert {:status 201} response)))) (deftest search-patient-test (testing "Search patients by name" (test-utils/insert-test-records :patients generate-patient [{:first_name "PI:NAME:<NAME>END_PI"} {:first_name "PI:NAME:<NAME>END_PI"}]) (let [response (app/handler (test-utils/json-request :get "/api/patients" :query {:search-name "PI:NAME:<NAME>END_PI"}))] (m/assert {:status 200 :body {:patients [{:full_name #(str/includes? % "PI:NAME:<NAME>END_PI")}]}} response))))
[ { "context": ".g.:\n ;; [{:oname \"Hartford Electronics\", :email \"jerry@hec.org\"}\n ;; {:oname \"Fourier Method Co\", :email \"thoma", "end": 1783, "score": 0.9999012351036072, "start": 1770, "tag": "EMAIL", "value": "jerry@hec.org" }, { "context": "c.org\"}\n ;; {:oname \"Fourier Method Co\", :email \"thomas@sorkin.edu\"}]\n (fn [{:keys [db]} [_ group-id org-ids new-org", "end": 1845, "score": 0.999919056892395, "start": 1828, "tag": "EMAIL", "value": "thomas@sorkin.edu" }, { "context": " :value id}))\n ;; e.g., [{:oname \"Hartford Electronics\", :email& (atom \"jerry@hec.org\")}\n ;; ", "end": 8111, "score": 0.999062716960907, "start": 8091, "tag": "NAME", "value": "Hartford Electronics" }, { "context": ", [{:oname \"Hartford Electronics\", :email& (atom \"jerry@hec.org\")}\n ;; {:oname \"Fourier Method Co\",", "end": 8142, "score": 0.9996733069419861, "start": 8129, "tag": "EMAIL", "value": "jerry@hec.org" }, { "context": "atom \"jerry@hec.org\")}\n ;; {:oname \"Fourier Method Co\", :email& (atom nil)}]\n new-orgs& (r/atom ", "end": 8190, "score": 0.9938644170761108, "start": 8173, "tag": "NAME", "value": "Fourier Method Co" }, { "context": "tark Industries\"]\n [:> ui/TableCell \"tony@starkindustries.co\"]]\n [:> ui/TableRow\n [:>", "end": 15448, "score": 0.9999227523803711, "start": 15425, "tag": "EMAIL", "value": "tony@starkindustries.co" }, { "context": "tark Industries\"]\n [:> ui/TableCell \"mark@starkindustries\"]]\n [:> ui/TableRow\n [:>", "end": 15584, "score": 0.9998732209205627, "start": 15564, "tag": "EMAIL", "value": "mark@starkindustries" }, { "context": "eCell \"XYZ Corp\"]\n [:> ui/TableCell \"jerry@xyz.org\"]]]]]\n [:> ui/ModalActions\n [:", "end": 15705, "score": 0.99991375207901, "start": 15692, "tag": "EMAIL", "value": "jerry@xyz.org" } ]
src/cljs/app/vetd_app/groups/pages/settings.cljs
jaydeesimon/vetd-app
98
(ns vetd-app.groups.pages.settings (:require [vetd-app.ui :as ui] [vetd-app.util :as util] [vetd-app.common.components :as cc] [vetd-app.buyers.components :as bc] [vetd-app.common.fx :as cfx] [reagent.core :as r] [re-frame.core :as rf] [goog.labs.format.csv :as csv] [clojure.string :as s])) (rf/reg-event-fx :g/nav-settings (constantly {:nav {:path "/c/settings"} :analytics/track {:event "Navigate" :props {:category "Navigation" :label "Groups Settings"}}})) (rf/reg-event-fx :g/route-settings (fn [{:keys [db]}] {:db (assoc db :page :g/settings :page-params {:fields-editing #{}})})) (rf/reg-event-fx :g/add-orgs-to-group.submit (fn [{:keys [db]} [_ group-id org-ids new-orgs]] (cfx/validated-dispatch-fx db [:g/add-orgs-to-group group-id org-ids new-orgs] #(cond (some (complement util/valid-email-address?) (flatten (map (comp (partial map s/trim) (fn [x] (s/split x ",")) :email) new-orgs))) [:invite-email-address "Please enter a valid email address."] :else nil)))) (rf/reg-event-fx :g/add-orgs-to-group ;; org-ids are ids of orgs that exist in our database ;; new-orgs is a coll of maps, e.g.: ;; [{:oname "Hartford Electronics", :email "jerry@hec.org"} ;; {:oname "Fourier Method Co", :email "thomas@sorkin.edu"}] (fn [{:keys [db]} [_ group-id org-ids new-orgs]] {:ws-send {:payload {:cmd :g/add-orgs-to-group :return {:handler :g/add-orgs-to-group-return :group-id group-id :org-ids org-ids :new-orgs new-orgs} :group-id group-id :org-ids org-ids :new-orgs new-orgs :from-user-id (-> db :user :id)}} :analytics/track {:event "Add Organization" :props {:category "Community"}}})) (rf/reg-event-fx :g/add-orgs-to-group-return (fn [{:keys [db]} [_ _ {{:keys [group-id org-ids new-orgs]} :return}]] {:toast {:type "success" :title (str "Organization" (when (> (count (concat org-ids new-orgs)) 1) "s") " added to your community!")} :dispatch [:stop-edit-field (str "add-orgs-to-group-" group-id)]})) (rf/reg-event-fx :g/create-invite-link (fn [{:keys [db]} [_ group-id]] {:ws-send {:payload {:cmd :g/create-invite-link :return {:handler :g/create-invite-link.return} :group-id group-id}}})) (rf/reg-event-fx :g/create-invite-link.return (fn [{:keys [db]} [_ {:keys [url]}]] {:dispatch [:modal {:header "Shareable Invite Link" :size "tiny" :content [:<> [:p "Share this link with anyone you want to join your community." [:br] [:em "It can be used an unlimited number of times, but will expire in 45 days."]] [:> ui/Input {:id "group-invite-url" :action (r/as-element [:> ui/Button {:on-click (fn [] (do (doto (util/node-by-id "group-invite-url") .focus .select) (.execCommand js/document "copy") (rf/dispatch [:toast {:type "success" :title "Link copied"}]))) :color "teal" :labelPosition "right" :icon "copy" :content "Copy"}]) :default-value url :fluid true}]]}]})) ;; remove an org from a group (rf/reg-event-fx :g/remove-org (fn [{:keys [db]} [_ group-id org-id]] {:ws-send {:payload {:cmd :g/remove-org :return {:handler :g/remove-org-return} :group-id group-id :org-id org-id}} :analytics/track {:event "Remove Organization" :props {:category "Community"}}})) (rf/reg-event-fx :g/remove-org-return (fn [{:keys [db]}] {:toast {:type "success" :title "Organization removed from your community."}})) (rf/reg-event-fx :g/add-discount-to-group.submit (fn [{:keys [db]} [_ group-id product-id details redemption-descr]] (cfx/validated-dispatch-fx db [:g/add-discount-to-group group-id product-id details redemption-descr] #(cond (s/blank? product-id) [(keyword (str "add-discount-to-group" group-id ".product-id")) "You must select a product."] (s/blank? details) [(keyword (str "add-discount-to-group" group-id ".details")) "Discount details cannot be blank."] :else nil)))) (rf/reg-event-fx :g/add-discount-to-group (fn [{:keys [db]} [_ group-id product-id details redemption-descr]] {:ws-send {:payload {:cmd :g/add-discount :return {:handler :g/add-discount-to-group-return :group-id group-id} :group-id group-id :product-id product-id :descr details :redemption-descr redemption-descr}} :analytics/track {:event "Add Discount" :props {:category "Community" :label product-id}}})) (rf/reg-event-fx :g/add-discount-to-group-return (fn [{:keys [db]} [_ _ {{:keys [group-id]} :return}]] {:toast {:type "success" :title "Discount added to community!"} :dispatch [:stop-edit-field (str "add-discount-to-group-" group-id)]})) (rf/reg-event-fx :g/delete-discount (fn [{:keys [db]} [_ discount-id]] {:ws-send {:payload {:cmd :g/delete-discount :return {:handler :g/delete-discount-return} :discount-id discount-id}} :analytics/track {:event "Delete Discount" :props {:category "Community" :label discount-id}}})) (rf/reg-event-fx :g/delete-discount-return (fn [{:keys [db]}] {:toast {:type "success" :title "Discount deleted from community."}})) ;;;; Components (defn c-add-orgs-form [group csv-invite-modal-showing?& field-name] (let [fields-editing& (rf/subscribe [:fields-editing]) bad-input& (rf/subscribe [:bad-input]) value& (r/atom []) options& (r/atom []) ; options from search results + current values search-query& (r/atom "") orgs->options (fn [orgs] (for [{:keys [id oname]} orgs] {:key id :text oname :value id})) ;; e.g., [{:oname "Hartford Electronics", :email& (atom "jerry@hec.org")} ;; {:oname "Fourier Method Co", :email& (atom nil)}] new-orgs& (r/atom []) file-contents& (r/atom nil) csv-added-count& (r/atom 0)] (fn [group csv-invite-modal-showing?& field-name] (let [orgs& (rf/subscribe [:gql/q {:queries [[:orgs {:_where {:_and ;; while this trims search-query, the Dropdown's search filter doesn't... [{:oname {:_ilike (str "%" (s/trim @search-query&) "%")}} {:deleted {:_is_null true}}]} :_limit 100 :_order_by {:oname :asc}} [:id :oname]]]}]) org-ids-already-in-group (set (map :id (:orgs group))) lc-org-names-already-in-group (set (map (comp s/lower-case :oname) (:orgs group))) _ (when-not (= :loading @orgs&) (let [options (->> @orgs& :orgs orgs->options ; now we have options from gql sub ;; (this dumbly actually keeps everything, but that seems fine) (concat @options&) ; keep options for the current values distinct (remove (comp (partial contains? org-ids-already-in-group) :value)))] (when-not (= @options& options) (reset! options& options))))] [:<> [:> ui/Form {:as "div" :class "popup-dropdown-form"} ;; popup is a misnomer here [:> ui/FormField {:style {:padding-top 7 :width "100%"} ;; this class combo w/ width 100% is a hack :class "ui action input"} [:> ui/Dropdown {:loading (= :loading @orgs&) :options @options& :placeholder "Enter the name of the organization..." :search true :selection true :multiple true ;; :auto-focus true ;; TODO this doesn't work :selectOnBlur false :selectOnNavigation true :closeOnChange true :allowAdditions true :additionLabel "Hit 'Enter' to Invite " :onAddItem (fn [_ this] (let [new-value (-> this .-value vector) new-entry (first new-value)] (if-not ((set lc-org-names-already-in-group) (s/lower-case new-entry)) (do (->> new-value ui/as-dropdown-options (swap! options& concat)) (swap! new-orgs& conj {:oname new-entry :email& (r/atom nil)})) (rf/dispatch [:toast {:type "error" :title "Already in Community" :message (str new-entry " is already part of your community.")}])))) :onSearchChange (fn [_ this] (reset! search-query& (aget this "searchQuery"))) :onChange (fn [_ this] (reset! value& (remove (set lc-org-names-already-in-group) (.-value this))) (reset! new-orgs& (remove (comp not (set (js->clj (.-value this))) :oname) @new-orgs&)))}] (when (empty? @new-orgs&) [:> ui/Button {:color "teal" :disabled (empty? @value&) :on-click #(rf/dispatch [:g/add-orgs-to-group.submit (:id group) (js->clj @value&)])} "Add"])]] ;; this is in a second Form to fix formatting issues (TODO could be better) (when (seq @new-orgs&) [:> ui/Form {:as "div"} (doall (for [{:keys [oname email&]} @new-orgs&] ^{:key oname} [:> ui/FormField {:style {:padding-top 7 :margin-bottom 0}} [:label (str "Email address of someone at " oname) [ui/input {:placeholder "Enter email address..." :fluid true :autoFocus true :spellCheck false :value @email& :on-change (fn [e] (reset! email& (-> e .-target .-value)))}]]])) [:> ui/Button {:color "teal" :style {:margin-top 10} :on-click (fn [] (rf/dispatch [:g/add-orgs-to-group.submit (:id group) ;; orgs that exist (remove (set (map :oname @new-orgs&)) @value&) ;; orgs that need to be created (map #(-> % (assoc :email @(:email& %)) (dissoc :email&)) @new-orgs&)]))} (str "Send Community Invite (" (+ (count @value&) @csv-added-count&) ")")]]) [:> ui/Modal {:open @csv-invite-modal-showing?& :on-close (fn [] (do (reset! file-contents& nil) (reset! csv-invite-modal-showing?& false) (rf/dispatch [:stop-edit-field field-name]))) :size "tiny" :dimmer "inverted" :closeOnDimmerClick false :closeOnEscape true :closeIcon true} [:> ui/ModalHeader "Upload a CSV of Organizations to Invite"] [:> ui/ModalContent [:p "Upload a .csv file to invite multiple organizations to your community, and to add additional users to those organizations."] [:p [:em "For any organizations that are already on Vetd, no invitation email will be sent, but they will be added to your community."]] [:h4 "Required format:"] [:> ui/Table [:> ui/TableHeader [:> ui/TableRow [:> ui/TableHeaderCell "Organization"] [:> ui/TableHeaderCell "Email"]]] [:> ui/TableBody [:> ui/TableRow [:> ui/TableCell "Stark Industries"] [:> ui/TableCell "tony@starkindustries.co"]] [:> ui/TableRow [:> ui/TableCell "Stark Industries"] [:> ui/TableCell "mark@starkindustries"]] [:> ui/TableRow [:> ui/TableCell "XYZ Corp"] [:> ui/TableCell "jerry@xyz.org"]]]]] [:> ui/ModalActions [:> ui/Form {:method "post" :enc-type "multipart/form-data" :style {:margin "5px auto 15px auto"}} [:input {:type "file" :accept "text/csv" ;; not sure how much this does... :on-change (fn [e] (let [file (aget e "target" "files" 0)] (if (or (= (aget file "type") "text/csv") (= "csv" (s/lower-case (last (s/split (aget file "name") #"\."))))) (let [onloadend #(reset! file-contents& (aget % "target" "result")) reader (doto (js/FileReader.) (aset "onloadend" onloadend))] (.readAsBinaryString reader file)) (do (rf/dispatch [:toast {:type "error" :title "Only CSV files are accepted."}]) (aset (aget e "target") "value" "")))))}]] [:div {:style {:clear "both"}}] [:> ui/Button {:onClick #(do (reset! file-contents& nil) (reset! csv-invite-modal-showing?& false) (rf/dispatch [:stop-edit-field field-name]))} "Cancel"] [:> ui/Button {:disabled (nil? @file-contents&) :color "blue" :on-click (fn [] (let [data (-> @file-contents& csv/parse js->clj) [org-header email-header] (first data)] (if (and (s/starts-with? (s/lower-case org-header) "org") (s/starts-with? (s/lower-case email-header) "email")) (do (doall (->> data (drop 1) ;; drop the header row (group-by first) (map (fn [[k v]] (swap! new-orgs& conj {:oname k :email& (r/atom (s/join ", " (map second v)))}) (swap! csv-added-count& inc))))) (reset! file-contents& nil) (reset! csv-invite-modal-showing?& false)) (rf/dispatch [:toast {:type "error" :message "The first row of your CSV file must be a header for columns \"Organization\" and \"Email\"."}]))))} "Upload"]]]])))) (defn c-org [org group] (let [popup-open? (r/atom false)] (fn [{:keys [id idstr oname memberships] :as org} {:keys [gname] :as group}] (let [num-members (count memberships)] [cc/c-field {:label [:<> [:> ui/Popup {:position "bottom right" :on "click" :open @popup-open? :on-close #(reset! popup-open? false) :content (r/as-element [:div [:h5 "Are you sure you want to remove " oname " from " gname "?"] [:> ui/ButtonGroup {:fluid true} [:> ui/Button {:on-click #(reset! popup-open? false)} "Cancel"] [:> ui/Button {:on-click (fn [] (reset! popup-open? false) (rf/dispatch [:g/remove-org (:id group) id])) :color "red"} "Remove"]]]) :trigger (r/as-element [:> ui/Label {:on-click #(swap! popup-open? not) :as "a" :style {:float "right" :margin-top 5}} [:> ui/Icon {:name "remove"}] "Remove"])}] oname] :value [:<> (str num-members " member" (when-not (= num-members 1) "s") " ") (when (pos? num-members) [:> ui/Popup {:position "bottom left" :wide "very" :offset -10 :content (let [max-members-show 15] (str (s/join ", " (->> memberships (map (comp :uname :user)) (take max-members-show))) (when (> num-members max-members-show) (str " and " (- num-members max-members-show) " more.")))) :trigger (r/as-element [:> ui/Icon {:name "question circle"}])}])]}])))) (defn c-add-discount-form [group] (let [fields-editing& (rf/subscribe [:fields-editing]) bad-input& (rf/subscribe [:bad-input]) product& (r/atom nil) details& (r/atom "") redemption-descr& (r/atom "") options& (r/atom []) ; options from search results + current values search-query& (r/atom "") products->options (fn [products] (for [{:keys [id pname vendor]} products] {:key id :text (str pname (when-not (= pname (:oname vendor)) (str " by " (:oname vendor)))) :value id}))] (fn [group] (let [products& (rf/subscribe [:gql/q {:queries [[:products {:_where {:_and ;; while this trims search-query, the Dropdown's search filter doesn't... [{:pname {:_ilike (str "%" @search-query& "%")}} {:deleted {:_is_null true}}]} :_limit 100 :_order_by {:pname :asc}} [:id :pname [:vendor [:oname]]]]]}]) _ (when-not (= :loading @products&) (let [options (->> @products& :products products->options ; now we have options from gql sub ;; (this dumbly actually keeps everything, but that seems fine) (concat @options&) ; keep options for the current values distinct)] (when-not (= @options& options) (reset! options& options))))] [:> ui/Form [:> ui/FormField {:error (= @bad-input& (keyword (str "add-discount-to-group" (:id group) ".product-id"))) :style {:padding-top 7}} [:> ui/Dropdown {:loading (= :loading @products&) :options @options& :placeholder "Search products..." :search true :selection true :multiple false ;; :auto-focus true ;; TODO this doesn't work :selectOnBlur false :selectOnNavigation true :closeOnChange true :onSearchChange (fn [_ this] (reset! search-query& (aget this "searchQuery"))) :onChange (fn [_ this] (reset! product& (.-value this)))}]] [:> ui/FormField {:error (= @bad-input& (keyword (str "add-discount-to-group" (:id group) ".details")))} [:> ui/TextArea {:placeholder "Discount details..." :fluid "true" :spellCheck true :on-change (fn [_ this] (reset! details& (.-value this)))}]] [:> ui/FormField {:error (= @bad-input& (keyword (str "add-discount-to-group" (:id group) ".redemption-descr")))} [:> ui/TextArea {:placeholder "Redemption details..." :fluid "true" :spellCheck true :on-change (fn [_ this] (reset! redemption-descr& (.-value this)))}]] [:> ui/Button {:on-click #(rf/dispatch [:g/add-discount-to-group.submit (:id group) (js->clj @product&) @details& @redemption-descr&]) :disabled (nil? @product&) :color "blue"} "Add"]])))) (defn c-discount [discount] (let [popup-open? (r/atom false)] (fn [{:keys [id idstr pname ref-id ; the discount ID group-discount-descr group-discount-redemption-descr vendor] :as discount}] [cc/c-field {:label [:<> [:> ui/Popup {:position "bottom right" :on "click" :open @popup-open? :on-close #(reset! popup-open? false) :content (r/as-element [:div [:h5 "Are you sure you want to delete this discount?"] [:> ui/ButtonGroup {:fluid true} [:> ui/Button {:on-click #(reset! popup-open? false)} "Cancel"] [:> ui/Button {:on-click (fn [] (reset! popup-open? false) (rf/dispatch [:g/delete-discount ref-id])) :color "red"} "Delete"]]]) :trigger (r/as-element [:> ui/Label {:on-click #(swap! popup-open? not) :as "a" :style {:float "right" :margin-top 5}} [:> ui/Icon {:name "remove"}] "Delete"])}] [:a.name {:on-click #(rf/dispatch [:b/nav-product-detail idstr])} pname] [:small " by " (:oname vendor)]] :value [:<> (util/parse-md group-discount-descr) (when-not (s/blank? group-discount-redemption-descr) [:<> [:br] [:em "Redemption Details"] (util/parse-md group-discount-redemption-descr)])]}]))) (defn c-orgs [group] (let [fields-editing& (rf/subscribe [:fields-editing]) csv-invite-modal-showing?& (r/atom false)] (fn [{:keys [id orgs] :as group}] (let [field-name (str "add-orgs-to-group-" id)] [bc/c-profile-segment {:title [:<> (if (@fields-editing& field-name) [:> ui/Label {:on-click #(rf/dispatch [:stop-edit-field field-name]) :as "a" :style {:float "right"}} "Cancel"] [:<> [:> ui/Popup {:position "bottom center" :content "Add (or invite) an organization to your community." :trigger (r/as-element [:> ui/Label {:on-click #(rf/dispatch [:edit-field field-name]) :as "a" :color "blue" :style {:float "right"}} [:> ui/Icon {:name "add group"}] "Add By Name"])}] [:> ui/Popup {:position "bottom center" :content "Upload a CSV of Organization names with email addresses." :trigger (r/as-element [:> ui/Label {:on-click (fn [] (rf/dispatch [:edit-field field-name]) (reset! csv-invite-modal-showing?& true)) :as "a" :color "blue" :style {:float "right" :margin-right 10}} [:> ui/Icon {:name "upload"}] "Upload"])}] [:> ui/Popup {:position "bottom center" :content "Create a shareable invite link that lasts for 45 days." :trigger (r/as-element [:> ui/Label {:on-click #(rf/dispatch [:g/create-invite-link id]) :as "a" :color "teal" :style {:float "right" :margin-right 10}} [:> ui/Icon {:name "linkify"}] "Invite Link"])}]]) "Organizations" (when (@fields-editing& field-name) [c-add-orgs-form group csv-invite-modal-showing?& field-name])]} (for [org orgs] ^{:key (:id org)} [c-org org group])])))) (defn c-discounts [group] (let [fields-editing& (rf/subscribe [:fields-editing])] (fn [{:keys [id discounts] :as group}] (let [field-name (str "add-discount-to-group-" id)] [bc/c-profile-segment {:title [:<> (if (@fields-editing& field-name) [:> ui/Label {:on-click #(rf/dispatch [:stop-edit-field field-name]) :as "a" :style {:float "right"}} "Cancel"] [:> ui/Label {:on-click #(rf/dispatch [:edit-field field-name]) :as "a" :color "blue" :style {:float "right"}} [:> ui/Icon {:name "dollar"}] "Add Discount"]) "Discounts" (when (@fields-editing& field-name) [c-add-discount-form group])]} (for [discount discounts] ^{:key (:id discount)} [c-discount discount])])))) (defn c-group [{:keys [gname] :as group}] [:> ui/Grid {:stackable true :style {:padding-bottom 35}} ; in case they are admin of multiple communities [:> ui/GridRow [:> ui/GridColumn {:computer 16 :mobile 16} [:h1 {:style {:text-align "center"}} gname]]] [:> ui/GridRow [:> ui/GridColumn {:computer 8 :mobile 16} [c-orgs group]] [:> ui/GridColumn {:computer 8 :mobile 16} [c-discounts group]]]]) (defn c-groups [groups] [:div (for [group groups] ^{:key (:id group)} [c-group group])]) (defn c-page [] (let [org-id& (rf/subscribe [:org-id]) groups& (rf/subscribe [:gql/sub {:queries [[:groups {:admin-org-id @org-id& :deleted nil} [:id :gname [:orgs [:id :oname [:memberships [:id [:user [:id :uname]]]]]] [:discounts {:ref-deleted nil} ;; NOTE :id is product id and idstr ;; ref-id is the id of the discount [:ref-id :id :idstr :pname :group-discount-descr :group-discount-redemption-descr [:vendor [:id :oname]]]]]]]}])] (fn [] (if (= :loading @groups&) [cc/c-loader] [c-groups (:groups @groups&)]))))
4106
(ns vetd-app.groups.pages.settings (:require [vetd-app.ui :as ui] [vetd-app.util :as util] [vetd-app.common.components :as cc] [vetd-app.buyers.components :as bc] [vetd-app.common.fx :as cfx] [reagent.core :as r] [re-frame.core :as rf] [goog.labs.format.csv :as csv] [clojure.string :as s])) (rf/reg-event-fx :g/nav-settings (constantly {:nav {:path "/c/settings"} :analytics/track {:event "Navigate" :props {:category "Navigation" :label "Groups Settings"}}})) (rf/reg-event-fx :g/route-settings (fn [{:keys [db]}] {:db (assoc db :page :g/settings :page-params {:fields-editing #{}})})) (rf/reg-event-fx :g/add-orgs-to-group.submit (fn [{:keys [db]} [_ group-id org-ids new-orgs]] (cfx/validated-dispatch-fx db [:g/add-orgs-to-group group-id org-ids new-orgs] #(cond (some (complement util/valid-email-address?) (flatten (map (comp (partial map s/trim) (fn [x] (s/split x ",")) :email) new-orgs))) [:invite-email-address "Please enter a valid email address."] :else nil)))) (rf/reg-event-fx :g/add-orgs-to-group ;; org-ids are ids of orgs that exist in our database ;; new-orgs is a coll of maps, e.g.: ;; [{:oname "Hartford Electronics", :email "<EMAIL>"} ;; {:oname "Fourier Method Co", :email "<EMAIL>"}] (fn [{:keys [db]} [_ group-id org-ids new-orgs]] {:ws-send {:payload {:cmd :g/add-orgs-to-group :return {:handler :g/add-orgs-to-group-return :group-id group-id :org-ids org-ids :new-orgs new-orgs} :group-id group-id :org-ids org-ids :new-orgs new-orgs :from-user-id (-> db :user :id)}} :analytics/track {:event "Add Organization" :props {:category "Community"}}})) (rf/reg-event-fx :g/add-orgs-to-group-return (fn [{:keys [db]} [_ _ {{:keys [group-id org-ids new-orgs]} :return}]] {:toast {:type "success" :title (str "Organization" (when (> (count (concat org-ids new-orgs)) 1) "s") " added to your community!")} :dispatch [:stop-edit-field (str "add-orgs-to-group-" group-id)]})) (rf/reg-event-fx :g/create-invite-link (fn [{:keys [db]} [_ group-id]] {:ws-send {:payload {:cmd :g/create-invite-link :return {:handler :g/create-invite-link.return} :group-id group-id}}})) (rf/reg-event-fx :g/create-invite-link.return (fn [{:keys [db]} [_ {:keys [url]}]] {:dispatch [:modal {:header "Shareable Invite Link" :size "tiny" :content [:<> [:p "Share this link with anyone you want to join your community." [:br] [:em "It can be used an unlimited number of times, but will expire in 45 days."]] [:> ui/Input {:id "group-invite-url" :action (r/as-element [:> ui/Button {:on-click (fn [] (do (doto (util/node-by-id "group-invite-url") .focus .select) (.execCommand js/document "copy") (rf/dispatch [:toast {:type "success" :title "Link copied"}]))) :color "teal" :labelPosition "right" :icon "copy" :content "Copy"}]) :default-value url :fluid true}]]}]})) ;; remove an org from a group (rf/reg-event-fx :g/remove-org (fn [{:keys [db]} [_ group-id org-id]] {:ws-send {:payload {:cmd :g/remove-org :return {:handler :g/remove-org-return} :group-id group-id :org-id org-id}} :analytics/track {:event "Remove Organization" :props {:category "Community"}}})) (rf/reg-event-fx :g/remove-org-return (fn [{:keys [db]}] {:toast {:type "success" :title "Organization removed from your community."}})) (rf/reg-event-fx :g/add-discount-to-group.submit (fn [{:keys [db]} [_ group-id product-id details redemption-descr]] (cfx/validated-dispatch-fx db [:g/add-discount-to-group group-id product-id details redemption-descr] #(cond (s/blank? product-id) [(keyword (str "add-discount-to-group" group-id ".product-id")) "You must select a product."] (s/blank? details) [(keyword (str "add-discount-to-group" group-id ".details")) "Discount details cannot be blank."] :else nil)))) (rf/reg-event-fx :g/add-discount-to-group (fn [{:keys [db]} [_ group-id product-id details redemption-descr]] {:ws-send {:payload {:cmd :g/add-discount :return {:handler :g/add-discount-to-group-return :group-id group-id} :group-id group-id :product-id product-id :descr details :redemption-descr redemption-descr}} :analytics/track {:event "Add Discount" :props {:category "Community" :label product-id}}})) (rf/reg-event-fx :g/add-discount-to-group-return (fn [{:keys [db]} [_ _ {{:keys [group-id]} :return}]] {:toast {:type "success" :title "Discount added to community!"} :dispatch [:stop-edit-field (str "add-discount-to-group-" group-id)]})) (rf/reg-event-fx :g/delete-discount (fn [{:keys [db]} [_ discount-id]] {:ws-send {:payload {:cmd :g/delete-discount :return {:handler :g/delete-discount-return} :discount-id discount-id}} :analytics/track {:event "Delete Discount" :props {:category "Community" :label discount-id}}})) (rf/reg-event-fx :g/delete-discount-return (fn [{:keys [db]}] {:toast {:type "success" :title "Discount deleted from community."}})) ;;;; Components (defn c-add-orgs-form [group csv-invite-modal-showing?& field-name] (let [fields-editing& (rf/subscribe [:fields-editing]) bad-input& (rf/subscribe [:bad-input]) value& (r/atom []) options& (r/atom []) ; options from search results + current values search-query& (r/atom "") orgs->options (fn [orgs] (for [{:keys [id oname]} orgs] {:key id :text oname :value id})) ;; e.g., [{:oname "<NAME>", :email& (atom "<EMAIL>")} ;; {:oname "<NAME>", :email& (atom nil)}] new-orgs& (r/atom []) file-contents& (r/atom nil) csv-added-count& (r/atom 0)] (fn [group csv-invite-modal-showing?& field-name] (let [orgs& (rf/subscribe [:gql/q {:queries [[:orgs {:_where {:_and ;; while this trims search-query, the Dropdown's search filter doesn't... [{:oname {:_ilike (str "%" (s/trim @search-query&) "%")}} {:deleted {:_is_null true}}]} :_limit 100 :_order_by {:oname :asc}} [:id :oname]]]}]) org-ids-already-in-group (set (map :id (:orgs group))) lc-org-names-already-in-group (set (map (comp s/lower-case :oname) (:orgs group))) _ (when-not (= :loading @orgs&) (let [options (->> @orgs& :orgs orgs->options ; now we have options from gql sub ;; (this dumbly actually keeps everything, but that seems fine) (concat @options&) ; keep options for the current values distinct (remove (comp (partial contains? org-ids-already-in-group) :value)))] (when-not (= @options& options) (reset! options& options))))] [:<> [:> ui/Form {:as "div" :class "popup-dropdown-form"} ;; popup is a misnomer here [:> ui/FormField {:style {:padding-top 7 :width "100%"} ;; this class combo w/ width 100% is a hack :class "ui action input"} [:> ui/Dropdown {:loading (= :loading @orgs&) :options @options& :placeholder "Enter the name of the organization..." :search true :selection true :multiple true ;; :auto-focus true ;; TODO this doesn't work :selectOnBlur false :selectOnNavigation true :closeOnChange true :allowAdditions true :additionLabel "Hit 'Enter' to Invite " :onAddItem (fn [_ this] (let [new-value (-> this .-value vector) new-entry (first new-value)] (if-not ((set lc-org-names-already-in-group) (s/lower-case new-entry)) (do (->> new-value ui/as-dropdown-options (swap! options& concat)) (swap! new-orgs& conj {:oname new-entry :email& (r/atom nil)})) (rf/dispatch [:toast {:type "error" :title "Already in Community" :message (str new-entry " is already part of your community.")}])))) :onSearchChange (fn [_ this] (reset! search-query& (aget this "searchQuery"))) :onChange (fn [_ this] (reset! value& (remove (set lc-org-names-already-in-group) (.-value this))) (reset! new-orgs& (remove (comp not (set (js->clj (.-value this))) :oname) @new-orgs&)))}] (when (empty? @new-orgs&) [:> ui/Button {:color "teal" :disabled (empty? @value&) :on-click #(rf/dispatch [:g/add-orgs-to-group.submit (:id group) (js->clj @value&)])} "Add"])]] ;; this is in a second Form to fix formatting issues (TODO could be better) (when (seq @new-orgs&) [:> ui/Form {:as "div"} (doall (for [{:keys [oname email&]} @new-orgs&] ^{:key oname} [:> ui/FormField {:style {:padding-top 7 :margin-bottom 0}} [:label (str "Email address of someone at " oname) [ui/input {:placeholder "Enter email address..." :fluid true :autoFocus true :spellCheck false :value @email& :on-change (fn [e] (reset! email& (-> e .-target .-value)))}]]])) [:> ui/Button {:color "teal" :style {:margin-top 10} :on-click (fn [] (rf/dispatch [:g/add-orgs-to-group.submit (:id group) ;; orgs that exist (remove (set (map :oname @new-orgs&)) @value&) ;; orgs that need to be created (map #(-> % (assoc :email @(:email& %)) (dissoc :email&)) @new-orgs&)]))} (str "Send Community Invite (" (+ (count @value&) @csv-added-count&) ")")]]) [:> ui/Modal {:open @csv-invite-modal-showing?& :on-close (fn [] (do (reset! file-contents& nil) (reset! csv-invite-modal-showing?& false) (rf/dispatch [:stop-edit-field field-name]))) :size "tiny" :dimmer "inverted" :closeOnDimmerClick false :closeOnEscape true :closeIcon true} [:> ui/ModalHeader "Upload a CSV of Organizations to Invite"] [:> ui/ModalContent [:p "Upload a .csv file to invite multiple organizations to your community, and to add additional users to those organizations."] [:p [:em "For any organizations that are already on Vetd, no invitation email will be sent, but they will be added to your community."]] [:h4 "Required format:"] [:> ui/Table [:> ui/TableHeader [:> ui/TableRow [:> ui/TableHeaderCell "Organization"] [:> ui/TableHeaderCell "Email"]]] [:> ui/TableBody [:> ui/TableRow [:> ui/TableCell "Stark Industries"] [:> ui/TableCell "<EMAIL>"]] [:> ui/TableRow [:> ui/TableCell "Stark Industries"] [:> ui/TableCell "<EMAIL>"]] [:> ui/TableRow [:> ui/TableCell "XYZ Corp"] [:> ui/TableCell "<EMAIL>"]]]]] [:> ui/ModalActions [:> ui/Form {:method "post" :enc-type "multipart/form-data" :style {:margin "5px auto 15px auto"}} [:input {:type "file" :accept "text/csv" ;; not sure how much this does... :on-change (fn [e] (let [file (aget e "target" "files" 0)] (if (or (= (aget file "type") "text/csv") (= "csv" (s/lower-case (last (s/split (aget file "name") #"\."))))) (let [onloadend #(reset! file-contents& (aget % "target" "result")) reader (doto (js/FileReader.) (aset "onloadend" onloadend))] (.readAsBinaryString reader file)) (do (rf/dispatch [:toast {:type "error" :title "Only CSV files are accepted."}]) (aset (aget e "target") "value" "")))))}]] [:div {:style {:clear "both"}}] [:> ui/Button {:onClick #(do (reset! file-contents& nil) (reset! csv-invite-modal-showing?& false) (rf/dispatch [:stop-edit-field field-name]))} "Cancel"] [:> ui/Button {:disabled (nil? @file-contents&) :color "blue" :on-click (fn [] (let [data (-> @file-contents& csv/parse js->clj) [org-header email-header] (first data)] (if (and (s/starts-with? (s/lower-case org-header) "org") (s/starts-with? (s/lower-case email-header) "email")) (do (doall (->> data (drop 1) ;; drop the header row (group-by first) (map (fn [[k v]] (swap! new-orgs& conj {:oname k :email& (r/atom (s/join ", " (map second v)))}) (swap! csv-added-count& inc))))) (reset! file-contents& nil) (reset! csv-invite-modal-showing?& false)) (rf/dispatch [:toast {:type "error" :message "The first row of your CSV file must be a header for columns \"Organization\" and \"Email\"."}]))))} "Upload"]]]])))) (defn c-org [org group] (let [popup-open? (r/atom false)] (fn [{:keys [id idstr oname memberships] :as org} {:keys [gname] :as group}] (let [num-members (count memberships)] [cc/c-field {:label [:<> [:> ui/Popup {:position "bottom right" :on "click" :open @popup-open? :on-close #(reset! popup-open? false) :content (r/as-element [:div [:h5 "Are you sure you want to remove " oname " from " gname "?"] [:> ui/ButtonGroup {:fluid true} [:> ui/Button {:on-click #(reset! popup-open? false)} "Cancel"] [:> ui/Button {:on-click (fn [] (reset! popup-open? false) (rf/dispatch [:g/remove-org (:id group) id])) :color "red"} "Remove"]]]) :trigger (r/as-element [:> ui/Label {:on-click #(swap! popup-open? not) :as "a" :style {:float "right" :margin-top 5}} [:> ui/Icon {:name "remove"}] "Remove"])}] oname] :value [:<> (str num-members " member" (when-not (= num-members 1) "s") " ") (when (pos? num-members) [:> ui/Popup {:position "bottom left" :wide "very" :offset -10 :content (let [max-members-show 15] (str (s/join ", " (->> memberships (map (comp :uname :user)) (take max-members-show))) (when (> num-members max-members-show) (str " and " (- num-members max-members-show) " more.")))) :trigger (r/as-element [:> ui/Icon {:name "question circle"}])}])]}])))) (defn c-add-discount-form [group] (let [fields-editing& (rf/subscribe [:fields-editing]) bad-input& (rf/subscribe [:bad-input]) product& (r/atom nil) details& (r/atom "") redemption-descr& (r/atom "") options& (r/atom []) ; options from search results + current values search-query& (r/atom "") products->options (fn [products] (for [{:keys [id pname vendor]} products] {:key id :text (str pname (when-not (= pname (:oname vendor)) (str " by " (:oname vendor)))) :value id}))] (fn [group] (let [products& (rf/subscribe [:gql/q {:queries [[:products {:_where {:_and ;; while this trims search-query, the Dropdown's search filter doesn't... [{:pname {:_ilike (str "%" @search-query& "%")}} {:deleted {:_is_null true}}]} :_limit 100 :_order_by {:pname :asc}} [:id :pname [:vendor [:oname]]]]]}]) _ (when-not (= :loading @products&) (let [options (->> @products& :products products->options ; now we have options from gql sub ;; (this dumbly actually keeps everything, but that seems fine) (concat @options&) ; keep options for the current values distinct)] (when-not (= @options& options) (reset! options& options))))] [:> ui/Form [:> ui/FormField {:error (= @bad-input& (keyword (str "add-discount-to-group" (:id group) ".product-id"))) :style {:padding-top 7}} [:> ui/Dropdown {:loading (= :loading @products&) :options @options& :placeholder "Search products..." :search true :selection true :multiple false ;; :auto-focus true ;; TODO this doesn't work :selectOnBlur false :selectOnNavigation true :closeOnChange true :onSearchChange (fn [_ this] (reset! search-query& (aget this "searchQuery"))) :onChange (fn [_ this] (reset! product& (.-value this)))}]] [:> ui/FormField {:error (= @bad-input& (keyword (str "add-discount-to-group" (:id group) ".details")))} [:> ui/TextArea {:placeholder "Discount details..." :fluid "true" :spellCheck true :on-change (fn [_ this] (reset! details& (.-value this)))}]] [:> ui/FormField {:error (= @bad-input& (keyword (str "add-discount-to-group" (:id group) ".redemption-descr")))} [:> ui/TextArea {:placeholder "Redemption details..." :fluid "true" :spellCheck true :on-change (fn [_ this] (reset! redemption-descr& (.-value this)))}]] [:> ui/Button {:on-click #(rf/dispatch [:g/add-discount-to-group.submit (:id group) (js->clj @product&) @details& @redemption-descr&]) :disabled (nil? @product&) :color "blue"} "Add"]])))) (defn c-discount [discount] (let [popup-open? (r/atom false)] (fn [{:keys [id idstr pname ref-id ; the discount ID group-discount-descr group-discount-redemption-descr vendor] :as discount}] [cc/c-field {:label [:<> [:> ui/Popup {:position "bottom right" :on "click" :open @popup-open? :on-close #(reset! popup-open? false) :content (r/as-element [:div [:h5 "Are you sure you want to delete this discount?"] [:> ui/ButtonGroup {:fluid true} [:> ui/Button {:on-click #(reset! popup-open? false)} "Cancel"] [:> ui/Button {:on-click (fn [] (reset! popup-open? false) (rf/dispatch [:g/delete-discount ref-id])) :color "red"} "Delete"]]]) :trigger (r/as-element [:> ui/Label {:on-click #(swap! popup-open? not) :as "a" :style {:float "right" :margin-top 5}} [:> ui/Icon {:name "remove"}] "Delete"])}] [:a.name {:on-click #(rf/dispatch [:b/nav-product-detail idstr])} pname] [:small " by " (:oname vendor)]] :value [:<> (util/parse-md group-discount-descr) (when-not (s/blank? group-discount-redemption-descr) [:<> [:br] [:em "Redemption Details"] (util/parse-md group-discount-redemption-descr)])]}]))) (defn c-orgs [group] (let [fields-editing& (rf/subscribe [:fields-editing]) csv-invite-modal-showing?& (r/atom false)] (fn [{:keys [id orgs] :as group}] (let [field-name (str "add-orgs-to-group-" id)] [bc/c-profile-segment {:title [:<> (if (@fields-editing& field-name) [:> ui/Label {:on-click #(rf/dispatch [:stop-edit-field field-name]) :as "a" :style {:float "right"}} "Cancel"] [:<> [:> ui/Popup {:position "bottom center" :content "Add (or invite) an organization to your community." :trigger (r/as-element [:> ui/Label {:on-click #(rf/dispatch [:edit-field field-name]) :as "a" :color "blue" :style {:float "right"}} [:> ui/Icon {:name "add group"}] "Add By Name"])}] [:> ui/Popup {:position "bottom center" :content "Upload a CSV of Organization names with email addresses." :trigger (r/as-element [:> ui/Label {:on-click (fn [] (rf/dispatch [:edit-field field-name]) (reset! csv-invite-modal-showing?& true)) :as "a" :color "blue" :style {:float "right" :margin-right 10}} [:> ui/Icon {:name "upload"}] "Upload"])}] [:> ui/Popup {:position "bottom center" :content "Create a shareable invite link that lasts for 45 days." :trigger (r/as-element [:> ui/Label {:on-click #(rf/dispatch [:g/create-invite-link id]) :as "a" :color "teal" :style {:float "right" :margin-right 10}} [:> ui/Icon {:name "linkify"}] "Invite Link"])}]]) "Organizations" (when (@fields-editing& field-name) [c-add-orgs-form group csv-invite-modal-showing?& field-name])]} (for [org orgs] ^{:key (:id org)} [c-org org group])])))) (defn c-discounts [group] (let [fields-editing& (rf/subscribe [:fields-editing])] (fn [{:keys [id discounts] :as group}] (let [field-name (str "add-discount-to-group-" id)] [bc/c-profile-segment {:title [:<> (if (@fields-editing& field-name) [:> ui/Label {:on-click #(rf/dispatch [:stop-edit-field field-name]) :as "a" :style {:float "right"}} "Cancel"] [:> ui/Label {:on-click #(rf/dispatch [:edit-field field-name]) :as "a" :color "blue" :style {:float "right"}} [:> ui/Icon {:name "dollar"}] "Add Discount"]) "Discounts" (when (@fields-editing& field-name) [c-add-discount-form group])]} (for [discount discounts] ^{:key (:id discount)} [c-discount discount])])))) (defn c-group [{:keys [gname] :as group}] [:> ui/Grid {:stackable true :style {:padding-bottom 35}} ; in case they are admin of multiple communities [:> ui/GridRow [:> ui/GridColumn {:computer 16 :mobile 16} [:h1 {:style {:text-align "center"}} gname]]] [:> ui/GridRow [:> ui/GridColumn {:computer 8 :mobile 16} [c-orgs group]] [:> ui/GridColumn {:computer 8 :mobile 16} [c-discounts group]]]]) (defn c-groups [groups] [:div (for [group groups] ^{:key (:id group)} [c-group group])]) (defn c-page [] (let [org-id& (rf/subscribe [:org-id]) groups& (rf/subscribe [:gql/sub {:queries [[:groups {:admin-org-id @org-id& :deleted nil} [:id :gname [:orgs [:id :oname [:memberships [:id [:user [:id :uname]]]]]] [:discounts {:ref-deleted nil} ;; NOTE :id is product id and idstr ;; ref-id is the id of the discount [:ref-id :id :idstr :pname :group-discount-descr :group-discount-redemption-descr [:vendor [:id :oname]]]]]]]}])] (fn [] (if (= :loading @groups&) [cc/c-loader] [c-groups (:groups @groups&)]))))
true
(ns vetd-app.groups.pages.settings (:require [vetd-app.ui :as ui] [vetd-app.util :as util] [vetd-app.common.components :as cc] [vetd-app.buyers.components :as bc] [vetd-app.common.fx :as cfx] [reagent.core :as r] [re-frame.core :as rf] [goog.labs.format.csv :as csv] [clojure.string :as s])) (rf/reg-event-fx :g/nav-settings (constantly {:nav {:path "/c/settings"} :analytics/track {:event "Navigate" :props {:category "Navigation" :label "Groups Settings"}}})) (rf/reg-event-fx :g/route-settings (fn [{:keys [db]}] {:db (assoc db :page :g/settings :page-params {:fields-editing #{}})})) (rf/reg-event-fx :g/add-orgs-to-group.submit (fn [{:keys [db]} [_ group-id org-ids new-orgs]] (cfx/validated-dispatch-fx db [:g/add-orgs-to-group group-id org-ids new-orgs] #(cond (some (complement util/valid-email-address?) (flatten (map (comp (partial map s/trim) (fn [x] (s/split x ",")) :email) new-orgs))) [:invite-email-address "Please enter a valid email address."] :else nil)))) (rf/reg-event-fx :g/add-orgs-to-group ;; org-ids are ids of orgs that exist in our database ;; new-orgs is a coll of maps, e.g.: ;; [{:oname "Hartford Electronics", :email "PI:EMAIL:<EMAIL>END_PI"} ;; {:oname "Fourier Method Co", :email "PI:EMAIL:<EMAIL>END_PI"}] (fn [{:keys [db]} [_ group-id org-ids new-orgs]] {:ws-send {:payload {:cmd :g/add-orgs-to-group :return {:handler :g/add-orgs-to-group-return :group-id group-id :org-ids org-ids :new-orgs new-orgs} :group-id group-id :org-ids org-ids :new-orgs new-orgs :from-user-id (-> db :user :id)}} :analytics/track {:event "Add Organization" :props {:category "Community"}}})) (rf/reg-event-fx :g/add-orgs-to-group-return (fn [{:keys [db]} [_ _ {{:keys [group-id org-ids new-orgs]} :return}]] {:toast {:type "success" :title (str "Organization" (when (> (count (concat org-ids new-orgs)) 1) "s") " added to your community!")} :dispatch [:stop-edit-field (str "add-orgs-to-group-" group-id)]})) (rf/reg-event-fx :g/create-invite-link (fn [{:keys [db]} [_ group-id]] {:ws-send {:payload {:cmd :g/create-invite-link :return {:handler :g/create-invite-link.return} :group-id group-id}}})) (rf/reg-event-fx :g/create-invite-link.return (fn [{:keys [db]} [_ {:keys [url]}]] {:dispatch [:modal {:header "Shareable Invite Link" :size "tiny" :content [:<> [:p "Share this link with anyone you want to join your community." [:br] [:em "It can be used an unlimited number of times, but will expire in 45 days."]] [:> ui/Input {:id "group-invite-url" :action (r/as-element [:> ui/Button {:on-click (fn [] (do (doto (util/node-by-id "group-invite-url") .focus .select) (.execCommand js/document "copy") (rf/dispatch [:toast {:type "success" :title "Link copied"}]))) :color "teal" :labelPosition "right" :icon "copy" :content "Copy"}]) :default-value url :fluid true}]]}]})) ;; remove an org from a group (rf/reg-event-fx :g/remove-org (fn [{:keys [db]} [_ group-id org-id]] {:ws-send {:payload {:cmd :g/remove-org :return {:handler :g/remove-org-return} :group-id group-id :org-id org-id}} :analytics/track {:event "Remove Organization" :props {:category "Community"}}})) (rf/reg-event-fx :g/remove-org-return (fn [{:keys [db]}] {:toast {:type "success" :title "Organization removed from your community."}})) (rf/reg-event-fx :g/add-discount-to-group.submit (fn [{:keys [db]} [_ group-id product-id details redemption-descr]] (cfx/validated-dispatch-fx db [:g/add-discount-to-group group-id product-id details redemption-descr] #(cond (s/blank? product-id) [(keyword (str "add-discount-to-group" group-id ".product-id")) "You must select a product."] (s/blank? details) [(keyword (str "add-discount-to-group" group-id ".details")) "Discount details cannot be blank."] :else nil)))) (rf/reg-event-fx :g/add-discount-to-group (fn [{:keys [db]} [_ group-id product-id details redemption-descr]] {:ws-send {:payload {:cmd :g/add-discount :return {:handler :g/add-discount-to-group-return :group-id group-id} :group-id group-id :product-id product-id :descr details :redemption-descr redemption-descr}} :analytics/track {:event "Add Discount" :props {:category "Community" :label product-id}}})) (rf/reg-event-fx :g/add-discount-to-group-return (fn [{:keys [db]} [_ _ {{:keys [group-id]} :return}]] {:toast {:type "success" :title "Discount added to community!"} :dispatch [:stop-edit-field (str "add-discount-to-group-" group-id)]})) (rf/reg-event-fx :g/delete-discount (fn [{:keys [db]} [_ discount-id]] {:ws-send {:payload {:cmd :g/delete-discount :return {:handler :g/delete-discount-return} :discount-id discount-id}} :analytics/track {:event "Delete Discount" :props {:category "Community" :label discount-id}}})) (rf/reg-event-fx :g/delete-discount-return (fn [{:keys [db]}] {:toast {:type "success" :title "Discount deleted from community."}})) ;;;; Components (defn c-add-orgs-form [group csv-invite-modal-showing?& field-name] (let [fields-editing& (rf/subscribe [:fields-editing]) bad-input& (rf/subscribe [:bad-input]) value& (r/atom []) options& (r/atom []) ; options from search results + current values search-query& (r/atom "") orgs->options (fn [orgs] (for [{:keys [id oname]} orgs] {:key id :text oname :value id})) ;; e.g., [{:oname "PI:NAME:<NAME>END_PI", :email& (atom "PI:EMAIL:<EMAIL>END_PI")} ;; {:oname "PI:NAME:<NAME>END_PI", :email& (atom nil)}] new-orgs& (r/atom []) file-contents& (r/atom nil) csv-added-count& (r/atom 0)] (fn [group csv-invite-modal-showing?& field-name] (let [orgs& (rf/subscribe [:gql/q {:queries [[:orgs {:_where {:_and ;; while this trims search-query, the Dropdown's search filter doesn't... [{:oname {:_ilike (str "%" (s/trim @search-query&) "%")}} {:deleted {:_is_null true}}]} :_limit 100 :_order_by {:oname :asc}} [:id :oname]]]}]) org-ids-already-in-group (set (map :id (:orgs group))) lc-org-names-already-in-group (set (map (comp s/lower-case :oname) (:orgs group))) _ (when-not (= :loading @orgs&) (let [options (->> @orgs& :orgs orgs->options ; now we have options from gql sub ;; (this dumbly actually keeps everything, but that seems fine) (concat @options&) ; keep options for the current values distinct (remove (comp (partial contains? org-ids-already-in-group) :value)))] (when-not (= @options& options) (reset! options& options))))] [:<> [:> ui/Form {:as "div" :class "popup-dropdown-form"} ;; popup is a misnomer here [:> ui/FormField {:style {:padding-top 7 :width "100%"} ;; this class combo w/ width 100% is a hack :class "ui action input"} [:> ui/Dropdown {:loading (= :loading @orgs&) :options @options& :placeholder "Enter the name of the organization..." :search true :selection true :multiple true ;; :auto-focus true ;; TODO this doesn't work :selectOnBlur false :selectOnNavigation true :closeOnChange true :allowAdditions true :additionLabel "Hit 'Enter' to Invite " :onAddItem (fn [_ this] (let [new-value (-> this .-value vector) new-entry (first new-value)] (if-not ((set lc-org-names-already-in-group) (s/lower-case new-entry)) (do (->> new-value ui/as-dropdown-options (swap! options& concat)) (swap! new-orgs& conj {:oname new-entry :email& (r/atom nil)})) (rf/dispatch [:toast {:type "error" :title "Already in Community" :message (str new-entry " is already part of your community.")}])))) :onSearchChange (fn [_ this] (reset! search-query& (aget this "searchQuery"))) :onChange (fn [_ this] (reset! value& (remove (set lc-org-names-already-in-group) (.-value this))) (reset! new-orgs& (remove (comp not (set (js->clj (.-value this))) :oname) @new-orgs&)))}] (when (empty? @new-orgs&) [:> ui/Button {:color "teal" :disabled (empty? @value&) :on-click #(rf/dispatch [:g/add-orgs-to-group.submit (:id group) (js->clj @value&)])} "Add"])]] ;; this is in a second Form to fix formatting issues (TODO could be better) (when (seq @new-orgs&) [:> ui/Form {:as "div"} (doall (for [{:keys [oname email&]} @new-orgs&] ^{:key oname} [:> ui/FormField {:style {:padding-top 7 :margin-bottom 0}} [:label (str "Email address of someone at " oname) [ui/input {:placeholder "Enter email address..." :fluid true :autoFocus true :spellCheck false :value @email& :on-change (fn [e] (reset! email& (-> e .-target .-value)))}]]])) [:> ui/Button {:color "teal" :style {:margin-top 10} :on-click (fn [] (rf/dispatch [:g/add-orgs-to-group.submit (:id group) ;; orgs that exist (remove (set (map :oname @new-orgs&)) @value&) ;; orgs that need to be created (map #(-> % (assoc :email @(:email& %)) (dissoc :email&)) @new-orgs&)]))} (str "Send Community Invite (" (+ (count @value&) @csv-added-count&) ")")]]) [:> ui/Modal {:open @csv-invite-modal-showing?& :on-close (fn [] (do (reset! file-contents& nil) (reset! csv-invite-modal-showing?& false) (rf/dispatch [:stop-edit-field field-name]))) :size "tiny" :dimmer "inverted" :closeOnDimmerClick false :closeOnEscape true :closeIcon true} [:> ui/ModalHeader "Upload a CSV of Organizations to Invite"] [:> ui/ModalContent [:p "Upload a .csv file to invite multiple organizations to your community, and to add additional users to those organizations."] [:p [:em "For any organizations that are already on Vetd, no invitation email will be sent, but they will be added to your community."]] [:h4 "Required format:"] [:> ui/Table [:> ui/TableHeader [:> ui/TableRow [:> ui/TableHeaderCell "Organization"] [:> ui/TableHeaderCell "Email"]]] [:> ui/TableBody [:> ui/TableRow [:> ui/TableCell "Stark Industries"] [:> ui/TableCell "PI:EMAIL:<EMAIL>END_PI"]] [:> ui/TableRow [:> ui/TableCell "Stark Industries"] [:> ui/TableCell "PI:EMAIL:<EMAIL>END_PI"]] [:> ui/TableRow [:> ui/TableCell "XYZ Corp"] [:> ui/TableCell "PI:EMAIL:<EMAIL>END_PI"]]]]] [:> ui/ModalActions [:> ui/Form {:method "post" :enc-type "multipart/form-data" :style {:margin "5px auto 15px auto"}} [:input {:type "file" :accept "text/csv" ;; not sure how much this does... :on-change (fn [e] (let [file (aget e "target" "files" 0)] (if (or (= (aget file "type") "text/csv") (= "csv" (s/lower-case (last (s/split (aget file "name") #"\."))))) (let [onloadend #(reset! file-contents& (aget % "target" "result")) reader (doto (js/FileReader.) (aset "onloadend" onloadend))] (.readAsBinaryString reader file)) (do (rf/dispatch [:toast {:type "error" :title "Only CSV files are accepted."}]) (aset (aget e "target") "value" "")))))}]] [:div {:style {:clear "both"}}] [:> ui/Button {:onClick #(do (reset! file-contents& nil) (reset! csv-invite-modal-showing?& false) (rf/dispatch [:stop-edit-field field-name]))} "Cancel"] [:> ui/Button {:disabled (nil? @file-contents&) :color "blue" :on-click (fn [] (let [data (-> @file-contents& csv/parse js->clj) [org-header email-header] (first data)] (if (and (s/starts-with? (s/lower-case org-header) "org") (s/starts-with? (s/lower-case email-header) "email")) (do (doall (->> data (drop 1) ;; drop the header row (group-by first) (map (fn [[k v]] (swap! new-orgs& conj {:oname k :email& (r/atom (s/join ", " (map second v)))}) (swap! csv-added-count& inc))))) (reset! file-contents& nil) (reset! csv-invite-modal-showing?& false)) (rf/dispatch [:toast {:type "error" :message "The first row of your CSV file must be a header for columns \"Organization\" and \"Email\"."}]))))} "Upload"]]]])))) (defn c-org [org group] (let [popup-open? (r/atom false)] (fn [{:keys [id idstr oname memberships] :as org} {:keys [gname] :as group}] (let [num-members (count memberships)] [cc/c-field {:label [:<> [:> ui/Popup {:position "bottom right" :on "click" :open @popup-open? :on-close #(reset! popup-open? false) :content (r/as-element [:div [:h5 "Are you sure you want to remove " oname " from " gname "?"] [:> ui/ButtonGroup {:fluid true} [:> ui/Button {:on-click #(reset! popup-open? false)} "Cancel"] [:> ui/Button {:on-click (fn [] (reset! popup-open? false) (rf/dispatch [:g/remove-org (:id group) id])) :color "red"} "Remove"]]]) :trigger (r/as-element [:> ui/Label {:on-click #(swap! popup-open? not) :as "a" :style {:float "right" :margin-top 5}} [:> ui/Icon {:name "remove"}] "Remove"])}] oname] :value [:<> (str num-members " member" (when-not (= num-members 1) "s") " ") (when (pos? num-members) [:> ui/Popup {:position "bottom left" :wide "very" :offset -10 :content (let [max-members-show 15] (str (s/join ", " (->> memberships (map (comp :uname :user)) (take max-members-show))) (when (> num-members max-members-show) (str " and " (- num-members max-members-show) " more.")))) :trigger (r/as-element [:> ui/Icon {:name "question circle"}])}])]}])))) (defn c-add-discount-form [group] (let [fields-editing& (rf/subscribe [:fields-editing]) bad-input& (rf/subscribe [:bad-input]) product& (r/atom nil) details& (r/atom "") redemption-descr& (r/atom "") options& (r/atom []) ; options from search results + current values search-query& (r/atom "") products->options (fn [products] (for [{:keys [id pname vendor]} products] {:key id :text (str pname (when-not (= pname (:oname vendor)) (str " by " (:oname vendor)))) :value id}))] (fn [group] (let [products& (rf/subscribe [:gql/q {:queries [[:products {:_where {:_and ;; while this trims search-query, the Dropdown's search filter doesn't... [{:pname {:_ilike (str "%" @search-query& "%")}} {:deleted {:_is_null true}}]} :_limit 100 :_order_by {:pname :asc}} [:id :pname [:vendor [:oname]]]]]}]) _ (when-not (= :loading @products&) (let [options (->> @products& :products products->options ; now we have options from gql sub ;; (this dumbly actually keeps everything, but that seems fine) (concat @options&) ; keep options for the current values distinct)] (when-not (= @options& options) (reset! options& options))))] [:> ui/Form [:> ui/FormField {:error (= @bad-input& (keyword (str "add-discount-to-group" (:id group) ".product-id"))) :style {:padding-top 7}} [:> ui/Dropdown {:loading (= :loading @products&) :options @options& :placeholder "Search products..." :search true :selection true :multiple false ;; :auto-focus true ;; TODO this doesn't work :selectOnBlur false :selectOnNavigation true :closeOnChange true :onSearchChange (fn [_ this] (reset! search-query& (aget this "searchQuery"))) :onChange (fn [_ this] (reset! product& (.-value this)))}]] [:> ui/FormField {:error (= @bad-input& (keyword (str "add-discount-to-group" (:id group) ".details")))} [:> ui/TextArea {:placeholder "Discount details..." :fluid "true" :spellCheck true :on-change (fn [_ this] (reset! details& (.-value this)))}]] [:> ui/FormField {:error (= @bad-input& (keyword (str "add-discount-to-group" (:id group) ".redemption-descr")))} [:> ui/TextArea {:placeholder "Redemption details..." :fluid "true" :spellCheck true :on-change (fn [_ this] (reset! redemption-descr& (.-value this)))}]] [:> ui/Button {:on-click #(rf/dispatch [:g/add-discount-to-group.submit (:id group) (js->clj @product&) @details& @redemption-descr&]) :disabled (nil? @product&) :color "blue"} "Add"]])))) (defn c-discount [discount] (let [popup-open? (r/atom false)] (fn [{:keys [id idstr pname ref-id ; the discount ID group-discount-descr group-discount-redemption-descr vendor] :as discount}] [cc/c-field {:label [:<> [:> ui/Popup {:position "bottom right" :on "click" :open @popup-open? :on-close #(reset! popup-open? false) :content (r/as-element [:div [:h5 "Are you sure you want to delete this discount?"] [:> ui/ButtonGroup {:fluid true} [:> ui/Button {:on-click #(reset! popup-open? false)} "Cancel"] [:> ui/Button {:on-click (fn [] (reset! popup-open? false) (rf/dispatch [:g/delete-discount ref-id])) :color "red"} "Delete"]]]) :trigger (r/as-element [:> ui/Label {:on-click #(swap! popup-open? not) :as "a" :style {:float "right" :margin-top 5}} [:> ui/Icon {:name "remove"}] "Delete"])}] [:a.name {:on-click #(rf/dispatch [:b/nav-product-detail idstr])} pname] [:small " by " (:oname vendor)]] :value [:<> (util/parse-md group-discount-descr) (when-not (s/blank? group-discount-redemption-descr) [:<> [:br] [:em "Redemption Details"] (util/parse-md group-discount-redemption-descr)])]}]))) (defn c-orgs [group] (let [fields-editing& (rf/subscribe [:fields-editing]) csv-invite-modal-showing?& (r/atom false)] (fn [{:keys [id orgs] :as group}] (let [field-name (str "add-orgs-to-group-" id)] [bc/c-profile-segment {:title [:<> (if (@fields-editing& field-name) [:> ui/Label {:on-click #(rf/dispatch [:stop-edit-field field-name]) :as "a" :style {:float "right"}} "Cancel"] [:<> [:> ui/Popup {:position "bottom center" :content "Add (or invite) an organization to your community." :trigger (r/as-element [:> ui/Label {:on-click #(rf/dispatch [:edit-field field-name]) :as "a" :color "blue" :style {:float "right"}} [:> ui/Icon {:name "add group"}] "Add By Name"])}] [:> ui/Popup {:position "bottom center" :content "Upload a CSV of Organization names with email addresses." :trigger (r/as-element [:> ui/Label {:on-click (fn [] (rf/dispatch [:edit-field field-name]) (reset! csv-invite-modal-showing?& true)) :as "a" :color "blue" :style {:float "right" :margin-right 10}} [:> ui/Icon {:name "upload"}] "Upload"])}] [:> ui/Popup {:position "bottom center" :content "Create a shareable invite link that lasts for 45 days." :trigger (r/as-element [:> ui/Label {:on-click #(rf/dispatch [:g/create-invite-link id]) :as "a" :color "teal" :style {:float "right" :margin-right 10}} [:> ui/Icon {:name "linkify"}] "Invite Link"])}]]) "Organizations" (when (@fields-editing& field-name) [c-add-orgs-form group csv-invite-modal-showing?& field-name])]} (for [org orgs] ^{:key (:id org)} [c-org org group])])))) (defn c-discounts [group] (let [fields-editing& (rf/subscribe [:fields-editing])] (fn [{:keys [id discounts] :as group}] (let [field-name (str "add-discount-to-group-" id)] [bc/c-profile-segment {:title [:<> (if (@fields-editing& field-name) [:> ui/Label {:on-click #(rf/dispatch [:stop-edit-field field-name]) :as "a" :style {:float "right"}} "Cancel"] [:> ui/Label {:on-click #(rf/dispatch [:edit-field field-name]) :as "a" :color "blue" :style {:float "right"}} [:> ui/Icon {:name "dollar"}] "Add Discount"]) "Discounts" (when (@fields-editing& field-name) [c-add-discount-form group])]} (for [discount discounts] ^{:key (:id discount)} [c-discount discount])])))) (defn c-group [{:keys [gname] :as group}] [:> ui/Grid {:stackable true :style {:padding-bottom 35}} ; in case they are admin of multiple communities [:> ui/GridRow [:> ui/GridColumn {:computer 16 :mobile 16} [:h1 {:style {:text-align "center"}} gname]]] [:> ui/GridRow [:> ui/GridColumn {:computer 8 :mobile 16} [c-orgs group]] [:> ui/GridColumn {:computer 8 :mobile 16} [c-discounts group]]]]) (defn c-groups [groups] [:div (for [group groups] ^{:key (:id group)} [c-group group])]) (defn c-page [] (let [org-id& (rf/subscribe [:org-id]) groups& (rf/subscribe [:gql/sub {:queries [[:groups {:admin-org-id @org-id& :deleted nil} [:id :gname [:orgs [:id :oname [:memberships [:id [:user [:id :uname]]]]]] [:discounts {:ref-deleted nil} ;; NOTE :id is product id and idstr ;; ref-id is the id of the discount [:ref-id :id :idstr :pname :group-discount-descr :group-discount-redemption-descr [:vendor [:id :oname]]]]]]]}])] (fn [] (if (= :loading @groups&) [cc/c-loader] [c-groups (:groups @groups&)]))))
[ { "context": "gic Tools / Milestones>\n;; Copyright (C) 2016 , Rafik NACCACHE <rafik@fekr.tech>\n\n(ns milestones.graph-utilities", "end": 104, "score": 0.9998674988746643, "start": 90, "tag": "NAME", "value": "Rafik NACCACHE" }, { "context": "tones>\n;; Copyright (C) 2016 , Rafik NACCACHE <rafik@fekr.tech>\n\n(ns milestones.graph-utilities)\n\n(defn predeces", "end": 121, "score": 0.9999345541000366, "start": 106, "tag": "EMAIL", "value": "rafik@fekr.tech" } ]
src/milestones/graph_utilities.cljc
vinity/milestones
63
;; <Graph Utilities - Part of Automagic Tools / Milestones> ;; Copyright (C) 2016 , Rafik NACCACHE <rafik@fekr.tech> (ns milestones.graph-utilities) (defn predecessors-of-task-exist? "return true if all predecessors of this task exist or if this task has no preds" [tasks the-task] (every? (partial contains? (set (keys tasks))) (:predecessors the-task))) (defn task-has-predecessors? "return true if this task has preds" [the-task] (seq (:predecessors the-task))) (defn gen-precendence-edge "a utility function, given 1 + [ 2 3] returns [1 2], [1 3]" [task-id predecessors] (mapv (fn[predecessor] [task-id predecessor]) predecessors)) (defn gen-all-precedence-edges "Given tasks, computes all the edges present in this graph" [tasks] (let [raw-maps (map (fn [[k v]] [k (:predecessors v)]) tasks)] (mapcat (fn [[k v]] (gen-precendence-edge k v) ) raw-maps))) (defn vertices [edges] (->> edges (mapcat identity ) set)) (defn successors [vertex edges] (->> edges (filter (comp (partial = vertex) first)) (map second))) (defn graph-cycles "Uses [Tarjan]((https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm)'s strongly connectect components algorithm to find if there are any cycles in a graph" [edges] (let [index (atom 0) indices (atom {}) ;;{vertex index, ...} lowlinks (atom {}) S (atom (list));;{vertex lowlink} output (atom [])] (letfn [(strong-connect [v] (swap! indices assoc-in [v] @index) (swap! lowlinks assoc-in [v] @index) (swap! index inc) (swap! S conj v) (let [succs (successors v edges)] (doseq [w succs] (if (not (contains? @indices w)) (do (strong-connect w) (swap! lowlinks assoc-in [v] (min (get @lowlinks v) (get @lowlinks w)))) (if (some #{w} @S ) (swap! lowlinks assoc-in [v] (min (get @lowlinks v) (get @indices w)))))) (if (= (get @lowlinks v) (get @indices v)) (loop [w (peek @S) r []] (swap! S pop) (if (not (= v w)) (recur (peek @S) (conj r w)) (when-not (empty? r) (swap! output conj (conj r w))))))))] (doseq [v (vertices edges)] (when-not (get @indices v) (strong-connect v))) @output)))
49786
;; <Graph Utilities - Part of Automagic Tools / Milestones> ;; Copyright (C) 2016 , <NAME> <<EMAIL>> (ns milestones.graph-utilities) (defn predecessors-of-task-exist? "return true if all predecessors of this task exist or if this task has no preds" [tasks the-task] (every? (partial contains? (set (keys tasks))) (:predecessors the-task))) (defn task-has-predecessors? "return true if this task has preds" [the-task] (seq (:predecessors the-task))) (defn gen-precendence-edge "a utility function, given 1 + [ 2 3] returns [1 2], [1 3]" [task-id predecessors] (mapv (fn[predecessor] [task-id predecessor]) predecessors)) (defn gen-all-precedence-edges "Given tasks, computes all the edges present in this graph" [tasks] (let [raw-maps (map (fn [[k v]] [k (:predecessors v)]) tasks)] (mapcat (fn [[k v]] (gen-precendence-edge k v) ) raw-maps))) (defn vertices [edges] (->> edges (mapcat identity ) set)) (defn successors [vertex edges] (->> edges (filter (comp (partial = vertex) first)) (map second))) (defn graph-cycles "Uses [Tarjan]((https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm)'s strongly connectect components algorithm to find if there are any cycles in a graph" [edges] (let [index (atom 0) indices (atom {}) ;;{vertex index, ...} lowlinks (atom {}) S (atom (list));;{vertex lowlink} output (atom [])] (letfn [(strong-connect [v] (swap! indices assoc-in [v] @index) (swap! lowlinks assoc-in [v] @index) (swap! index inc) (swap! S conj v) (let [succs (successors v edges)] (doseq [w succs] (if (not (contains? @indices w)) (do (strong-connect w) (swap! lowlinks assoc-in [v] (min (get @lowlinks v) (get @lowlinks w)))) (if (some #{w} @S ) (swap! lowlinks assoc-in [v] (min (get @lowlinks v) (get @indices w)))))) (if (= (get @lowlinks v) (get @indices v)) (loop [w (peek @S) r []] (swap! S pop) (if (not (= v w)) (recur (peek @S) (conj r w)) (when-not (empty? r) (swap! output conj (conj r w))))))))] (doseq [v (vertices edges)] (when-not (get @indices v) (strong-connect v))) @output)))
true
;; <Graph Utilities - Part of Automagic Tools / Milestones> ;; Copyright (C) 2016 , PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (ns milestones.graph-utilities) (defn predecessors-of-task-exist? "return true if all predecessors of this task exist or if this task has no preds" [tasks the-task] (every? (partial contains? (set (keys tasks))) (:predecessors the-task))) (defn task-has-predecessors? "return true if this task has preds" [the-task] (seq (:predecessors the-task))) (defn gen-precendence-edge "a utility function, given 1 + [ 2 3] returns [1 2], [1 3]" [task-id predecessors] (mapv (fn[predecessor] [task-id predecessor]) predecessors)) (defn gen-all-precedence-edges "Given tasks, computes all the edges present in this graph" [tasks] (let [raw-maps (map (fn [[k v]] [k (:predecessors v)]) tasks)] (mapcat (fn [[k v]] (gen-precendence-edge k v) ) raw-maps))) (defn vertices [edges] (->> edges (mapcat identity ) set)) (defn successors [vertex edges] (->> edges (filter (comp (partial = vertex) first)) (map second))) (defn graph-cycles "Uses [Tarjan]((https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm)'s strongly connectect components algorithm to find if there are any cycles in a graph" [edges] (let [index (atom 0) indices (atom {}) ;;{vertex index, ...} lowlinks (atom {}) S (atom (list));;{vertex lowlink} output (atom [])] (letfn [(strong-connect [v] (swap! indices assoc-in [v] @index) (swap! lowlinks assoc-in [v] @index) (swap! index inc) (swap! S conj v) (let [succs (successors v edges)] (doseq [w succs] (if (not (contains? @indices w)) (do (strong-connect w) (swap! lowlinks assoc-in [v] (min (get @lowlinks v) (get @lowlinks w)))) (if (some #{w} @S ) (swap! lowlinks assoc-in [v] (min (get @lowlinks v) (get @indices w)))))) (if (= (get @lowlinks v) (get @indices v)) (loop [w (peek @S) r []] (swap! S pop) (if (not (= v w)) (recur (peek @S) (conj r w)) (when-not (empty? r) (swap! output conj (conj r w))))))))] (doseq [v (vertices edges)] (when-not (get @indices v) (strong-connect v))) @output)))
[ { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and dis", "end": 33, "score": 0.9998462796211243, "start": 19, "tag": "NAME", "value": "Nicola Mometto" }, { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and distribution ter", "end": 46, "score": 0.9998295307159424, "start": 35, "tag": "NAME", "value": "Rich Hickey" } ]
server/target/clojure/tools/analyzer/passes/jvm/annotate_loops.clj
OctavioBR/healthcheck
0
;; Copyright (c) Nicola Mometto, Rich Hickey & contributors. ;; 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 clojure.tools.analyzer.passes.jvm.annotate-loops (:require [clojure.tools.analyzer.ast :refer [update-children]])) (defmulti annotate-loops "Adds a :loops field to nodes that represent a code path that might be visited more than once because of a recur. The field is a set of loop-ids representing the loops that might recur into that path Note that because (recur expr) is equivalent to (let [e expr] (recur e)) the node corresponting to expr will have the same :loops field as the nodes in the same code path of the recur" {:pass-info {:walk :pre :depends #{}}} :op) (defmulti check-recur :op) (defn -check-recur [ast k] (let [ast (update-in ast [k] check-recur)] (if (:recurs (k ast)) (assoc ast :recurs true) ast))) (defmethod check-recur :do [ast] (let [ast (-check-recur ast :ret)] (if (:recurs ast) (assoc ast :statements (mapv (fn [s] (assoc s :recurs true)) (:statements ast))) ast))) (defmethod check-recur :let [ast] (-check-recur ast :body)) (defmethod check-recur :letfn [ast] (-check-recur ast :body)) (defmethod check-recur :if [ast] (-> ast (-check-recur :then) (-check-recur :else))) (defmethod check-recur :case [ast] (let [ast (-> ast (-check-recur :default) (update-in [:thens] #(mapv check-recur %)))] (if (some :recurs (:thens ast)) (assoc ast :recurs true) ast))) (defmethod check-recur :case-then [ast] (-check-recur ast :then)) (defmethod check-recur :recur [ast] (assoc ast :recurs true)) (defmethod check-recur :default [ast] ast) (defn -loops [ast loop-id] (update-in ast [:loops] (fnil conj #{}) loop-id)) (defmethod annotate-loops :loop [{:keys [loops loop-id] :as ast}] (let [ast (if loops (update-children ast #(assoc % :loops loops)) ast) ast (update-in ast [:body] check-recur)] (if (-> ast :body :recurs) (update-in ast [:body] -loops loop-id) ast))) (defmethod annotate-loops :default [{:keys [loops] :as ast}] (if loops (update-children ast #(assoc % :loops loops)) ast)) (defmethod annotate-loops :if [{:keys [loops test then else env] :as ast}] (if loops (let [loop-id (:loop-id env) loops-no-recur (disj loops loop-id) branch-recurs? (or (:recurs then) (:recurs else)) then (if (or (:recurs then) ;; the recur is inside the then branch ;; the recur is in the same code path of the if expression (not branch-recurs?)) (assoc then :loops loops) (assoc then :loops loops-no-recur)) else (if (or (:recurs else) (not branch-recurs?)) (assoc else :loops loops) (assoc else :loops loops-no-recur))] (assoc ast :then then :else else :test (assoc test :loops loops))) ast)) (defmethod annotate-loops :case [{:keys [loops test default thens env] :as ast}] (if loops (let [loop-id (:loop-id env) loops-no-recur (disj loops loop-id) branch-recurs? (some :recurs (conj thens default)) default (if (or (:recurs default) (not branch-recurs?)) (assoc default :loops loops) (assoc default :loops loops-no-recur)) thens (mapv #(if (or (:recurs %) (not branch-recurs?)) (assoc % :loops loops) (assoc % :loops loops-no-recur)) thens)] (assoc ast :thens thens :default default :test (assoc test :loops loops))) ast))
57260
;; Copyright (c) <NAME>, <NAME> & contributors. ;; 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 clojure.tools.analyzer.passes.jvm.annotate-loops (:require [clojure.tools.analyzer.ast :refer [update-children]])) (defmulti annotate-loops "Adds a :loops field to nodes that represent a code path that might be visited more than once because of a recur. The field is a set of loop-ids representing the loops that might recur into that path Note that because (recur expr) is equivalent to (let [e expr] (recur e)) the node corresponting to expr will have the same :loops field as the nodes in the same code path of the recur" {:pass-info {:walk :pre :depends #{}}} :op) (defmulti check-recur :op) (defn -check-recur [ast k] (let [ast (update-in ast [k] check-recur)] (if (:recurs (k ast)) (assoc ast :recurs true) ast))) (defmethod check-recur :do [ast] (let [ast (-check-recur ast :ret)] (if (:recurs ast) (assoc ast :statements (mapv (fn [s] (assoc s :recurs true)) (:statements ast))) ast))) (defmethod check-recur :let [ast] (-check-recur ast :body)) (defmethod check-recur :letfn [ast] (-check-recur ast :body)) (defmethod check-recur :if [ast] (-> ast (-check-recur :then) (-check-recur :else))) (defmethod check-recur :case [ast] (let [ast (-> ast (-check-recur :default) (update-in [:thens] #(mapv check-recur %)))] (if (some :recurs (:thens ast)) (assoc ast :recurs true) ast))) (defmethod check-recur :case-then [ast] (-check-recur ast :then)) (defmethod check-recur :recur [ast] (assoc ast :recurs true)) (defmethod check-recur :default [ast] ast) (defn -loops [ast loop-id] (update-in ast [:loops] (fnil conj #{}) loop-id)) (defmethod annotate-loops :loop [{:keys [loops loop-id] :as ast}] (let [ast (if loops (update-children ast #(assoc % :loops loops)) ast) ast (update-in ast [:body] check-recur)] (if (-> ast :body :recurs) (update-in ast [:body] -loops loop-id) ast))) (defmethod annotate-loops :default [{:keys [loops] :as ast}] (if loops (update-children ast #(assoc % :loops loops)) ast)) (defmethod annotate-loops :if [{:keys [loops test then else env] :as ast}] (if loops (let [loop-id (:loop-id env) loops-no-recur (disj loops loop-id) branch-recurs? (or (:recurs then) (:recurs else)) then (if (or (:recurs then) ;; the recur is inside the then branch ;; the recur is in the same code path of the if expression (not branch-recurs?)) (assoc then :loops loops) (assoc then :loops loops-no-recur)) else (if (or (:recurs else) (not branch-recurs?)) (assoc else :loops loops) (assoc else :loops loops-no-recur))] (assoc ast :then then :else else :test (assoc test :loops loops))) ast)) (defmethod annotate-loops :case [{:keys [loops test default thens env] :as ast}] (if loops (let [loop-id (:loop-id env) loops-no-recur (disj loops loop-id) branch-recurs? (some :recurs (conj thens default)) default (if (or (:recurs default) (not branch-recurs?)) (assoc default :loops loops) (assoc default :loops loops-no-recur)) thens (mapv #(if (or (:recurs %) (not branch-recurs?)) (assoc % :loops loops) (assoc % :loops loops-no-recur)) thens)] (assoc ast :thens thens :default default :test (assoc test :loops loops))) ast))
true
;; Copyright (c) PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI & contributors. ;; 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 clojure.tools.analyzer.passes.jvm.annotate-loops (:require [clojure.tools.analyzer.ast :refer [update-children]])) (defmulti annotate-loops "Adds a :loops field to nodes that represent a code path that might be visited more than once because of a recur. The field is a set of loop-ids representing the loops that might recur into that path Note that because (recur expr) is equivalent to (let [e expr] (recur e)) the node corresponting to expr will have the same :loops field as the nodes in the same code path of the recur" {:pass-info {:walk :pre :depends #{}}} :op) (defmulti check-recur :op) (defn -check-recur [ast k] (let [ast (update-in ast [k] check-recur)] (if (:recurs (k ast)) (assoc ast :recurs true) ast))) (defmethod check-recur :do [ast] (let [ast (-check-recur ast :ret)] (if (:recurs ast) (assoc ast :statements (mapv (fn [s] (assoc s :recurs true)) (:statements ast))) ast))) (defmethod check-recur :let [ast] (-check-recur ast :body)) (defmethod check-recur :letfn [ast] (-check-recur ast :body)) (defmethod check-recur :if [ast] (-> ast (-check-recur :then) (-check-recur :else))) (defmethod check-recur :case [ast] (let [ast (-> ast (-check-recur :default) (update-in [:thens] #(mapv check-recur %)))] (if (some :recurs (:thens ast)) (assoc ast :recurs true) ast))) (defmethod check-recur :case-then [ast] (-check-recur ast :then)) (defmethod check-recur :recur [ast] (assoc ast :recurs true)) (defmethod check-recur :default [ast] ast) (defn -loops [ast loop-id] (update-in ast [:loops] (fnil conj #{}) loop-id)) (defmethod annotate-loops :loop [{:keys [loops loop-id] :as ast}] (let [ast (if loops (update-children ast #(assoc % :loops loops)) ast) ast (update-in ast [:body] check-recur)] (if (-> ast :body :recurs) (update-in ast [:body] -loops loop-id) ast))) (defmethod annotate-loops :default [{:keys [loops] :as ast}] (if loops (update-children ast #(assoc % :loops loops)) ast)) (defmethod annotate-loops :if [{:keys [loops test then else env] :as ast}] (if loops (let [loop-id (:loop-id env) loops-no-recur (disj loops loop-id) branch-recurs? (or (:recurs then) (:recurs else)) then (if (or (:recurs then) ;; the recur is inside the then branch ;; the recur is in the same code path of the if expression (not branch-recurs?)) (assoc then :loops loops) (assoc then :loops loops-no-recur)) else (if (or (:recurs else) (not branch-recurs?)) (assoc else :loops loops) (assoc else :loops loops-no-recur))] (assoc ast :then then :else else :test (assoc test :loops loops))) ast)) (defmethod annotate-loops :case [{:keys [loops test default thens env] :as ast}] (if loops (let [loop-id (:loop-id env) loops-no-recur (disj loops loop-id) branch-recurs? (some :recurs (conj thens default)) default (if (or (:recurs default) (not branch-recurs?)) (assoc default :loops loops) (assoc default :loops loops-no-recur)) thens (mapv #(if (or (:recurs %) (not branch-recurs?)) (assoc % :loops loops) (assoc % :loops loops-no-recur)) thens)] (assoc ast :thens thens :default default :test (assoc test :loops loops))) ast))
[ { "context": "key\n \"309b7c4ce9104b1b94d0c8b887d2cf77\"}\n :preloads [devtools.", "end": 4048, "score": 0.9997765421867371, "start": 4016, "tag": "KEY", "value": "309b7c4ce9104b1b94d0c8b887d2cf77" }, { "context": "key\n \"85da2596bf35435b8dcc9df11e437d25\"\n\n sh", "end": 4791, "score": 0.9997759461402893, "start": 4759, "tag": "KEY", "value": "85da2596bf35435b8dcc9df11e437d25" }, { "context": "key\n \"d55efd60669c41f0ac2792436a29f2bf\"\n\n sh", "end": 5898, "score": 0.9997506737709045, "start": 5866, "tag": "KEY", "value": "d55efd60669c41f0ac2792436a29f2bf" } ]
project.clj
skygear-demo/shotbot3
2
(defproject shotbot3 "3.0.0-beta0" :description "Shotbot 3.0 screenshot creator" :url "https://shotbot.io/" :min-lein-version "2.6.1" :plugins [[lein-figwheel "0.5.7"] [lein-cljsbuild "1.1.4" :exclusions [[org.clojure/clojure]]] [lein-re-frisk "0.4.4"] [lein-garden "0.3.0"] [lein-hiera "0.9.5"] [lein-pdo "0.1.1"] [lein-skygear "0.1.5"] [lein-cljfmt "0.5.6"]] :dependencies [;; language core [org.clojure/clojure "1.9.0-alpha13"] [org.clojure/clojurescript "1.9.229"] [org.clojure/core.incubator "0.1.4"] ;; utilities [binaryage/oops "0.1.0"] [binaryage/devtools "0.8.2"] [secretary "1.2.3"] [re-frisk-remote "0.4.1"] ;; framework [reagent "0.6.0"] [re-frame "0.9.2"] [akiroz.re-frame/storage "0.1.1"] [akiroz.re-frame/skygear "0.1.5-SNAPSHOT"] [madvas.re-frame/google-analytics-fx "0.1.0"] ;; forign libs [cljsjs/jscolor "2.0.4-0"] [cljsjs/jszip "3.1.3-0"] [cljsjs/filesaverjs "1.3.3-0"] [cljsjs/raven "3.9.1-0"] ] ;; command aliases :aliases {"deploy-staging!" ["do" ["clean"] ["garden" "once"] ["cljsbuild" "once" "staging"] ["deploy-skygear" "staging"]] "deploy-production!" ["do" ["clean"] ["garden" "once"] ["cljsbuild" "once" "production"] ["deploy-skygear" "production"]] "dev" ["do" ["clean"] ["pdo" ["garden" "auto"] ["re-frisk"] ["figwheel"]]] } ;; generate source dependency tree :hiera {:path "doc/ns-graph.png" :vertical false :show-external true :ignore-ns #{re-frame re-frisk-remote oops reagent garden cljs clojure goog} :cluster-depth 0} ;; clean generated files :clean-targets ^{:protect false} ["resources/public/js/compiled" "resources/public/css/compiled" "target"] ;; watch CSS file changes :figwheel {:css-dirs ["resources/public/css"] :server-ip "localhost"} ;; compile CSS :garden {:builds [{:source-paths ["src/garden"] :stylesheet shotbot.styles/screen :compiler {:output-to "resources/public/css/compiled/screen.css" :pretty-print? false}}]} ;; compile JS :cljsbuild {:builds [;; development build {:id "dev" :source-paths ["src/cljs"] :figwheel {:on-jsload shotbot.core/fig-reload} :compiler {:main shotbot.core :output-to "resources/public/js/compiled/shotbot3.js" :output-dir "resources/public/js/compiled/out" :asset-path "js/compiled/out" :libs ["src/js"] :source-map-timestamp true :closure-defines {shotbot.core/enable-re-frisk true shotbot.re-frame.events/skygear-end-point "https://shotbotdev.skygeario.com/" shotbot.re-frame.events/skygear-api-key "309b7c4ce9104b1b94d0c8b887d2cf77"} :preloads [devtools.preload]}} ;; minified staging build {:id "staging" :source-paths ["src/cljs"] :compiler {:main shotbot.core :output-to "resources/public/js/compiled/shotbot3.js" :output-dir "target/out_staging" :libs ["src/js"] :closure-defines {shotbot.re-frame.events/skygear-end-point "https://shotbotstaging.skygeario.com/" shotbot.re-frame.events/skygear-api-key "85da2596bf35435b8dcc9df11e437d25" shotbot.core/ga-tracking-id "UA-90337813-1" shotbot.core/sentry-endpoint "[Masked]"} :optimizations :advanced :language-in :ecmascript5 :pretty-print false}} ;; minified production build {:id "production" :source-paths ["src/cljs"] :compiler {:main shotbot.core :output-to "resources/public/js/compiled/shotbot3.js" :output-dir "target/out_production" :libs ["src/js"] :closure-defines {shotbot.re-frame.events/skygear-end-point "https://shotbot.skygeario.com/" shotbot.re-frame.events/skygear-api-key "d55efd60669c41f0ac2792436a29f2bf" shotbot.core/ga-tracking-id "UA-90337813-1" shotbot.core/sentry-endpoint "[Masked]"} :optimizations :advanced :language-in :ecmascript5 :pretty-print false}}]} ;; deploy to skygear cloud :skygear {:dev {:git-url "ssh://git@git.skygeario.com/shotbotdev.git" :source-dir "src/cloud" :static-dir "resources/public"} :staging {:git-url "ssh://git@git.skygeario.com/shotbotstaging.git" :source-dir "src/cloud" :static-dir "resources/public"} :production {:git-url "ssh://git@git.skygeario.com/shotbot.git" :source-dir "src/cloud" :static-dir "resources/public"}} )
36634
(defproject shotbot3 "3.0.0-beta0" :description "Shotbot 3.0 screenshot creator" :url "https://shotbot.io/" :min-lein-version "2.6.1" :plugins [[lein-figwheel "0.5.7"] [lein-cljsbuild "1.1.4" :exclusions [[org.clojure/clojure]]] [lein-re-frisk "0.4.4"] [lein-garden "0.3.0"] [lein-hiera "0.9.5"] [lein-pdo "0.1.1"] [lein-skygear "0.1.5"] [lein-cljfmt "0.5.6"]] :dependencies [;; language core [org.clojure/clojure "1.9.0-alpha13"] [org.clojure/clojurescript "1.9.229"] [org.clojure/core.incubator "0.1.4"] ;; utilities [binaryage/oops "0.1.0"] [binaryage/devtools "0.8.2"] [secretary "1.2.3"] [re-frisk-remote "0.4.1"] ;; framework [reagent "0.6.0"] [re-frame "0.9.2"] [akiroz.re-frame/storage "0.1.1"] [akiroz.re-frame/skygear "0.1.5-SNAPSHOT"] [madvas.re-frame/google-analytics-fx "0.1.0"] ;; forign libs [cljsjs/jscolor "2.0.4-0"] [cljsjs/jszip "3.1.3-0"] [cljsjs/filesaverjs "1.3.3-0"] [cljsjs/raven "3.9.1-0"] ] ;; command aliases :aliases {"deploy-staging!" ["do" ["clean"] ["garden" "once"] ["cljsbuild" "once" "staging"] ["deploy-skygear" "staging"]] "deploy-production!" ["do" ["clean"] ["garden" "once"] ["cljsbuild" "once" "production"] ["deploy-skygear" "production"]] "dev" ["do" ["clean"] ["pdo" ["garden" "auto"] ["re-frisk"] ["figwheel"]]] } ;; generate source dependency tree :hiera {:path "doc/ns-graph.png" :vertical false :show-external true :ignore-ns #{re-frame re-frisk-remote oops reagent garden cljs clojure goog} :cluster-depth 0} ;; clean generated files :clean-targets ^{:protect false} ["resources/public/js/compiled" "resources/public/css/compiled" "target"] ;; watch CSS file changes :figwheel {:css-dirs ["resources/public/css"] :server-ip "localhost"} ;; compile CSS :garden {:builds [{:source-paths ["src/garden"] :stylesheet shotbot.styles/screen :compiler {:output-to "resources/public/css/compiled/screen.css" :pretty-print? false}}]} ;; compile JS :cljsbuild {:builds [;; development build {:id "dev" :source-paths ["src/cljs"] :figwheel {:on-jsload shotbot.core/fig-reload} :compiler {:main shotbot.core :output-to "resources/public/js/compiled/shotbot3.js" :output-dir "resources/public/js/compiled/out" :asset-path "js/compiled/out" :libs ["src/js"] :source-map-timestamp true :closure-defines {shotbot.core/enable-re-frisk true shotbot.re-frame.events/skygear-end-point "https://shotbotdev.skygeario.com/" shotbot.re-frame.events/skygear-api-key "<KEY>"} :preloads [devtools.preload]}} ;; minified staging build {:id "staging" :source-paths ["src/cljs"] :compiler {:main shotbot.core :output-to "resources/public/js/compiled/shotbot3.js" :output-dir "target/out_staging" :libs ["src/js"] :closure-defines {shotbot.re-frame.events/skygear-end-point "https://shotbotstaging.skygeario.com/" shotbot.re-frame.events/skygear-api-key "<KEY>" shotbot.core/ga-tracking-id "UA-90337813-1" shotbot.core/sentry-endpoint "[Masked]"} :optimizations :advanced :language-in :ecmascript5 :pretty-print false}} ;; minified production build {:id "production" :source-paths ["src/cljs"] :compiler {:main shotbot.core :output-to "resources/public/js/compiled/shotbot3.js" :output-dir "target/out_production" :libs ["src/js"] :closure-defines {shotbot.re-frame.events/skygear-end-point "https://shotbot.skygeario.com/" shotbot.re-frame.events/skygear-api-key "<KEY>" shotbot.core/ga-tracking-id "UA-90337813-1" shotbot.core/sentry-endpoint "[Masked]"} :optimizations :advanced :language-in :ecmascript5 :pretty-print false}}]} ;; deploy to skygear cloud :skygear {:dev {:git-url "ssh://git@git.skygeario.com/shotbotdev.git" :source-dir "src/cloud" :static-dir "resources/public"} :staging {:git-url "ssh://git@git.skygeario.com/shotbotstaging.git" :source-dir "src/cloud" :static-dir "resources/public"} :production {:git-url "ssh://git@git.skygeario.com/shotbot.git" :source-dir "src/cloud" :static-dir "resources/public"}} )
true
(defproject shotbot3 "3.0.0-beta0" :description "Shotbot 3.0 screenshot creator" :url "https://shotbot.io/" :min-lein-version "2.6.1" :plugins [[lein-figwheel "0.5.7"] [lein-cljsbuild "1.1.4" :exclusions [[org.clojure/clojure]]] [lein-re-frisk "0.4.4"] [lein-garden "0.3.0"] [lein-hiera "0.9.5"] [lein-pdo "0.1.1"] [lein-skygear "0.1.5"] [lein-cljfmt "0.5.6"]] :dependencies [;; language core [org.clojure/clojure "1.9.0-alpha13"] [org.clojure/clojurescript "1.9.229"] [org.clojure/core.incubator "0.1.4"] ;; utilities [binaryage/oops "0.1.0"] [binaryage/devtools "0.8.2"] [secretary "1.2.3"] [re-frisk-remote "0.4.1"] ;; framework [reagent "0.6.0"] [re-frame "0.9.2"] [akiroz.re-frame/storage "0.1.1"] [akiroz.re-frame/skygear "0.1.5-SNAPSHOT"] [madvas.re-frame/google-analytics-fx "0.1.0"] ;; forign libs [cljsjs/jscolor "2.0.4-0"] [cljsjs/jszip "3.1.3-0"] [cljsjs/filesaverjs "1.3.3-0"] [cljsjs/raven "3.9.1-0"] ] ;; command aliases :aliases {"deploy-staging!" ["do" ["clean"] ["garden" "once"] ["cljsbuild" "once" "staging"] ["deploy-skygear" "staging"]] "deploy-production!" ["do" ["clean"] ["garden" "once"] ["cljsbuild" "once" "production"] ["deploy-skygear" "production"]] "dev" ["do" ["clean"] ["pdo" ["garden" "auto"] ["re-frisk"] ["figwheel"]]] } ;; generate source dependency tree :hiera {:path "doc/ns-graph.png" :vertical false :show-external true :ignore-ns #{re-frame re-frisk-remote oops reagent garden cljs clojure goog} :cluster-depth 0} ;; clean generated files :clean-targets ^{:protect false} ["resources/public/js/compiled" "resources/public/css/compiled" "target"] ;; watch CSS file changes :figwheel {:css-dirs ["resources/public/css"] :server-ip "localhost"} ;; compile CSS :garden {:builds [{:source-paths ["src/garden"] :stylesheet shotbot.styles/screen :compiler {:output-to "resources/public/css/compiled/screen.css" :pretty-print? false}}]} ;; compile JS :cljsbuild {:builds [;; development build {:id "dev" :source-paths ["src/cljs"] :figwheel {:on-jsload shotbot.core/fig-reload} :compiler {:main shotbot.core :output-to "resources/public/js/compiled/shotbot3.js" :output-dir "resources/public/js/compiled/out" :asset-path "js/compiled/out" :libs ["src/js"] :source-map-timestamp true :closure-defines {shotbot.core/enable-re-frisk true shotbot.re-frame.events/skygear-end-point "https://shotbotdev.skygeario.com/" shotbot.re-frame.events/skygear-api-key "PI:KEY:<KEY>END_PI"} :preloads [devtools.preload]}} ;; minified staging build {:id "staging" :source-paths ["src/cljs"] :compiler {:main shotbot.core :output-to "resources/public/js/compiled/shotbot3.js" :output-dir "target/out_staging" :libs ["src/js"] :closure-defines {shotbot.re-frame.events/skygear-end-point "https://shotbotstaging.skygeario.com/" shotbot.re-frame.events/skygear-api-key "PI:KEY:<KEY>END_PI" shotbot.core/ga-tracking-id "UA-90337813-1" shotbot.core/sentry-endpoint "[Masked]"} :optimizations :advanced :language-in :ecmascript5 :pretty-print false}} ;; minified production build {:id "production" :source-paths ["src/cljs"] :compiler {:main shotbot.core :output-to "resources/public/js/compiled/shotbot3.js" :output-dir "target/out_production" :libs ["src/js"] :closure-defines {shotbot.re-frame.events/skygear-end-point "https://shotbot.skygeario.com/" shotbot.re-frame.events/skygear-api-key "PI:KEY:<KEY>END_PI" shotbot.core/ga-tracking-id "UA-90337813-1" shotbot.core/sentry-endpoint "[Masked]"} :optimizations :advanced :language-in :ecmascript5 :pretty-print false}}]} ;; deploy to skygear cloud :skygear {:dev {:git-url "ssh://git@git.skygeario.com/shotbotdev.git" :source-dir "src/cloud" :static-dir "resources/public"} :staging {:git-url "ssh://git@git.skygeario.com/shotbotstaging.git" :source-dir "src/cloud" :static-dir "resources/public"} :production {:git-url "ssh://git@git.skygeario.com/shotbot.git" :source-dir "src/cloud" :static-dir "resources/public"}} )
[ { "context": "(ns ^{:author \"Adam Berger\"} ulvm.re-loaders\n \"ULVM runnable env loaders de", "end": 26, "score": 0.9998661875724792, "start": 15, "tag": "NAME", "value": "Adam Berger" } ]
src/ulvm/re_loaders.clj
abrgr/ulvm
0
(ns ^{:author "Adam Berger"} ulvm.re-loaders "ULVM runnable env loaders definition" (:require [clojure.spec :as s] [ulvm.core :as ucore] [ulvm.runnable-envs :as re] [ulvm.project :as uprj] [ulvm.func-utils :as futil] [cats.core :as m] [cats.monad.either :as e])) ; TODO: actually implement this (deftype CustomREnvLoader [renv] uprj/REnvLoader (-get-runnable-env-rep [this prj desc] (e/right {}))) (defmethod uprj/make-renv-loader :default [proj re-loader-name re-loader-entity] (futil/mlet e/context [p-el (uprj/deref-runnable-env proj re-loader-entity) prj (:prj p-el) runnable-env (:el p-el)] (uprj/set prj :renv-loaders re-loader-name (e/right (CustomREnvLoader. runnable-env))))) (load "re_loaders/builtin_project_file_re_loader")
101433
(ns ^{:author "<NAME>"} ulvm.re-loaders "ULVM runnable env loaders definition" (:require [clojure.spec :as s] [ulvm.core :as ucore] [ulvm.runnable-envs :as re] [ulvm.project :as uprj] [ulvm.func-utils :as futil] [cats.core :as m] [cats.monad.either :as e])) ; TODO: actually implement this (deftype CustomREnvLoader [renv] uprj/REnvLoader (-get-runnable-env-rep [this prj desc] (e/right {}))) (defmethod uprj/make-renv-loader :default [proj re-loader-name re-loader-entity] (futil/mlet e/context [p-el (uprj/deref-runnable-env proj re-loader-entity) prj (:prj p-el) runnable-env (:el p-el)] (uprj/set prj :renv-loaders re-loader-name (e/right (CustomREnvLoader. runnable-env))))) (load "re_loaders/builtin_project_file_re_loader")
true
(ns ^{:author "PI:NAME:<NAME>END_PI"} ulvm.re-loaders "ULVM runnable env loaders definition" (:require [clojure.spec :as s] [ulvm.core :as ucore] [ulvm.runnable-envs :as re] [ulvm.project :as uprj] [ulvm.func-utils :as futil] [cats.core :as m] [cats.monad.either :as e])) ; TODO: actually implement this (deftype CustomREnvLoader [renv] uprj/REnvLoader (-get-runnable-env-rep [this prj desc] (e/right {}))) (defmethod uprj/make-renv-loader :default [proj re-loader-name re-loader-entity] (futil/mlet e/context [p-el (uprj/deref-runnable-env proj re-loader-entity) prj (:prj p-el) runnable-env (:el p-el)] (uprj/set prj :renv-loaders re-loader-name (e/right (CustomREnvLoader. runnable-env))))) (load "re_loaders/builtin_project_file_re_loader")
[ { "context": " (set/union valid-waiter-hostnames #{\"localhost\" \"127.0.0.1\"})]\n (fn waiter-request? [{:keys [uri headers]", "end": 28304, "score": 0.9996975660324097, "start": 28295, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " (let [{:keys [query-state-fn]} gc-for-transient-metrics]\n ", "end": 98221, "score": 0.5521946549415588, "start": 98221, "tag": "KEY", "value": "" }, { "context": " (let [{:keys [query-state-fn]} gc-for-transient-metrics]\n ", "end": 98227, "score": 0.5907023549079895, "start": 98227, "tag": "KEY", "value": "" } ]
waiter/src/waiter/core.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.core (:require [bidi.bidi :as bidi] [clj-time.core :as t] [clojure.core.async :as async] [clojure.java.io :as io] [clojure.set :as set] [clojure.string :as str] [clojure.tools.logging :as log] [digest] [full.async :refer (<?? <? go-try)] [metrics.core] [metrics.counters :as counters] [metrics.timers :as timers] [plumbing.core :as pc] [qbits.jet.client.http :as http] [ring.middleware.basic-authentication :as basic-authentication] [ring.middleware.ssl :as ssl] [ring.util.response :as rr] [slingshot.slingshot :refer [try+]] [waiter.async-request :as async-req] [waiter.auth.authentication :as auth] [waiter.authorization :as authz] [waiter.cookie-support :as cookie-support] [waiter.correlation-id :as cid] [waiter.cors :as cors] [waiter.curator :as curator] [waiter.descriptor :as descriptor] [waiter.discovery :as discovery] [waiter.handler :as handler] [waiter.headers :as headers] [waiter.interstitial :as interstitial] [waiter.kv :as kv] [waiter.metrics :as metrics] [waiter.metrics-sync :as metrics-sync] [waiter.password-store :as password-store] [waiter.process-request :as pr] [waiter.reporter :as reporter] [waiter.scaling :as scaling] [waiter.scheduler :as scheduler] [waiter.service :as service] [waiter.service-description :as sd] [waiter.settings :as settings] [waiter.simulator :as simulator] [waiter.state :as state] [waiter.statsd :as statsd] [waiter.token :as token] [waiter.util.async-utils :as au] [waiter.util.cache-utils :as cu] [waiter.util.date-utils :as du] [waiter.util.http-utils :as http-utils] [waiter.util.ring-utils :as ru] [waiter.util.utils :as utils] [waiter.websocket :as ws] [waiter.work-stealing :as work-stealing]) (:import (java.net InetAddress URI) java.util.concurrent.Executors (javax.servlet ServletRequest) org.apache.curator.framework.CuratorFrameworkFactory org.apache.curator.framework.api.CuratorEventType org.apache.curator.framework.api.CuratorListener org.apache.curator.framework.recipes.leader.LeaderLatch org.apache.curator.retry.BoundedExponentialBackoffRetry org.eclipse.jetty.client.HttpClient org.eclipse.jetty.client.util.BasicAuthentication$BasicResult org.eclipse.jetty.websocket.client.WebSocketClient (org.eclipse.jetty.websocket.servlet ServletUpgradeResponse ServletUpgradeRequest))) (defn routes-mapper "Returns a map containing a keyword handler and the parsed route-params based on the request uri." ;; Please include/update a corresponding unit test anytime the routes data structure is modified [{:keys [uri]}] (let [routes ["/" {"" :welcome-handler-fn "app-name" :app-name-handler-fn "apps" {"" :service-list-handler-fn ["/" :service-id] :service-handler-fn ["/" :service-id "/logs"] :service-view-logs-handler-fn ["/" :service-id "/override"] :service-override-handler-fn ["/" :service-id "/refresh"] :service-refresh-handler-fn ["/" :service-id "/resume"] :service-resume-handler-fn ["/" :service-id "/suspend"] :service-suspend-handler-fn} "blacklist" {"" :blacklist-instance-handler-fn ["/" :service-id] :blacklisted-instances-list-handler-fn} "favicon.ico" :favicon-handler-fn "metrics" :metrics-request-handler-fn "service-id" :service-id-handler-fn "settings" :display-settings-handler-fn "sim" :sim-request-handler "state" [["" :state-all-handler-fn] ["/autoscaler" :state-autoscaler-handler-fn] ["/autoscaling-multiplexer" :state-autoscaling-multiplexer-handler-fn] ["/codahale-reporters" :state-codahale-reporters-handler-fn] ["/fallback" :state-fallback-handler-fn] ["/gc-broken-services" :state-gc-for-broken-services] ["/gc-services" :state-gc-for-services] ["/gc-transient-metrics" :state-gc-for-transient-metrics] ["/interstitial" :state-interstitial-handler-fn] ["/launch-metrics" :state-launch-metrics-handler-fn] ["/kv-store" :state-kv-store-handler-fn] ["/leader" :state-leader-handler-fn] ["/local-usage" :state-local-usage-handler-fn] ["/maintainer" :state-maintainer-handler-fn] ["/router-metrics" :state-router-metrics-handler-fn] ["/scheduler" :state-scheduler-handler-fn] ["/statsd" :state-statsd-handler-fn] [["/" :service-id] :state-service-handler-fn]] "status" :status-handler-fn "token" :token-handler-fn "tokens" {"" :token-list-handler-fn "/owners" :token-owners-handler-fn "/refresh" :token-refresh-handler-fn "/reindex" :token-reindex-handler-fn} "waiter-async" {["/complete/" :request-id "/" :service-id] :async-complete-handler-fn ["/result/" :request-id "/" :router-id "/" :service-id "/" :host "/" :port "/" [#".+" :location]] :async-result-handler-fn ["/status/" :request-id "/" :router-id "/" :service-id "/" :host "/" :port "/" [#".+" :location]] :async-status-handler-fn} "waiter-auth" :waiter-auth-handler-fn "waiter-consent" {"" :waiter-acknowledge-consent-handler-fn ["/" [#".*" :path]] :waiter-request-consent-handler-fn} "waiter-interstitial" {["/" [#".*" :path]] :waiter-request-interstitial-handler-fn} "waiter-kill-instance" {["/" :service-id] :kill-instance-handler-fn} "work-stealing" :work-stealing-handler-fn}]] (or (bidi/match-route routes uri) {:handler :not-found-handler-fn}))) (defn ring-handler-factory "Creates the handler for processing http requests." [waiter-request?-fn {:keys [process-request-fn] :as handlers}] (fn http-handler [{:keys [uri] :as request}] (if-not (waiter-request?-fn request) (do (counters/inc! (metrics/waiter-counter "requests" "service-request")) (process-request-fn request)) (let [{:keys [handler route-params]} (routes-mapper request) request (assoc request :route-params (or route-params {})) handler-fn (get handlers handler process-request-fn)] (when (and (not= handler :process-request-fn) (= handler-fn process-request-fn)) (log/warn "using default handler as no mapping found for" handler "at uri" uri)) (when handler (counters/inc! (metrics/waiter-counter "requests" (name handler)))) (handler-fn request))))) (defn websocket-handler-factory "Creates the handler for processing websocket requests. Websockets are currently used for inter-router metrics syncing." [{:keys [default-websocket-handler-fn router-metrics-handler-fn]}] (fn websocket-handler [{:keys [uri] :as request}] (case uri "/waiter-router-metrics" (router-metrics-handler-fn request) (default-websocket-handler-fn request)))) (defn correlation-id-middleware "Attaches an x-cid header to the request and response if one is not already provided." [handler] (fn correlation-id-middleware-fn [request] (let [request (cid/ensure-correlation-id request utils/unique-identifier) request-cid (cid/http-object->correlation-id request)] (cid/with-correlation-id request-cid (log/info "request received:" (-> (dissoc request :body :ctrl :in :out :request-time :server-name :server-port :servlet-request :ssl-client-cert :support-info :trailers-fn) (update :headers headers/truncate-header-values))) (let [response (handler request) get-request-cid (fn get-request-cid [] request-cid)] (if (map? response) (cid/ensure-correlation-id response get-request-cid) (async/go (let [nested-response (async/<! response)] (if (map? nested-response) ;; websocket responses may be another channel (cid/ensure-correlation-id nested-response get-request-cid) nested-response))))))))) (defn request->protocol "Determines the protocol and version used by the request. For HTTP requests, it returns values like HTTP/1.0, HTTP/1.1, HTTP/2. For WebSocket requests, it returns values like WS/8, WS/13." [{:keys [headers scheme ^ServletRequest servlet-request]}] (if servlet-request (or (some-> headers (get "x-forwarded-proto-version") str/upper-case) (.getProtocol servlet-request)) (when scheme (str/upper-case ;; currently, only websockets need this branch to determine version (if-let [version (get headers "sec-websocket-version")] (str (name scheme) "/" version) (name scheme)))))) (defn wrap-request-info "Attaches request info to the request." [handler router-id support-info] (fn wrap-request-info-fn [{:keys [servlet-request] :as request}] (-> request (assoc :client-protocol (request->protocol request) :internal-protocol (some-> servlet-request .getProtocol) :request-id (str (utils/unique-identifier) "-" (-> request utils/request->scheme name)) :request-time (t/now) :router-id router-id :support-info support-info) handler))) (defn wrap-debug "Attaches debugging headers to requests when enabled." [handler generate-log-url-fn] (fn wrap-debug-fn [{:keys [request-id request-time router-id] :as request}] (if (utils/request->debug-enabled? request) (let [response (handler request) add-headers (fn [{:keys [descriptor instance] :as response}] (let [{:strs [backend-proto]} (:service-description descriptor) backend-directory (:log-directory instance) backend-log-url (when backend-directory (generate-log-url-fn instance)) request-date (when request-time (du/date-to-str request-time du/formatter-rfc822))] (update response :headers (fn [headers] (cond-> headers request-time (assoc "x-waiter-request-date" request-date) request-id (assoc "x-waiter-request-id" request-id) router-id (assoc "x-waiter-router-id" router-id) descriptor (assoc "x-waiter-service-id" (:service-id descriptor)) instance (assoc "x-waiter-backend-id" (:id instance) "x-waiter-backend-host" (:host instance) "x-waiter-backend-port" (str (:port instance)) "x-waiter-backend-proto" backend-proto) backend-directory (assoc "x-waiter-backend-directory" backend-directory "x-waiter-backend-log-url" backend-log-url))))))] (ru/update-response response add-headers)) (handler request)))) (defn wrap-error-handling "Catches any uncaught exceptions and returns an error response." [handler] (fn wrap-error-handling-fn [request] (try (let [response (handler request)] (if (au/chan? response) (async/go (try (<? response) (catch Exception e (utils/exception->response e request)))) response)) (catch Exception e (utils/exception->response e request))))) (defn- make-blacklist-request [make-inter-router-requests-fn blacklist-period-ms dest-router-id dest-endpoint {:keys [id] :as instance} reason] (log/info "peer communication requesting" dest-router-id "to blacklist" id "via endpoint" dest-endpoint) (try (-> (make-inter-router-requests-fn dest-endpoint :acceptable-router? #(= dest-router-id %) :body (utils/clj->json {:instance instance :period-in-ms blacklist-period-ms :reason reason}) :method :post) (get dest-router-id)) (catch Exception e (log/error e "error in making blacklist request" {:instance instance :period-in-ms blacklist-period-ms :reason reason})))) (defn peers-acknowledged-blacklist-requests? "Note that the ids used in here are internal ids generated by the curator api." [{:keys [id] :as instance} short-circuit? router-ids endpoint make-blacklist-request-fn reason] (if (seq router-ids) (loop [[dest-router-id & remaining-peer-ids] (seq router-ids) blacklist-successful? true] (log/info {:dest-id dest-router-id, :blacklist-successful? blacklist-successful?}, :reason reason) (let [response (make-blacklist-request-fn dest-router-id endpoint instance reason) response-successful? (= 200 (:status response)) blacklist-successful? (and blacklist-successful? response-successful?)] (when (and short-circuit? (not response-successful?)) (log/info "peer communication" dest-router-id "veto-ed killing of" id {:http-status (:status response)})) (when (and short-circuit? response-successful?) (log/info "peer communication" dest-router-id "approves killing of" id)) (if (and remaining-peer-ids (or (not short-circuit?) response-successful?)) (recur remaining-peer-ids blacklist-successful?) blacklist-successful?))) (do (log/warn "no peer routers found to acknowledge blacklist request!") true))) (defn make-kill-instance-request "Makes a request to a peer router to kill an instance of a service." [make-inter-router-requests-fn service-id dest-router-id kill-instance-endpoint] (log/info "peer communication requesting" dest-router-id "to kill an instance of" service-id "via endpoint" kill-instance-endpoint) (try (-> (make-inter-router-requests-fn kill-instance-endpoint :acceptable-router? #(= dest-router-id %) :method :post) (get dest-router-id)) (catch Exception e (log/error e "error in killing instance of" service-id)))) (defn delegate-instance-kill-request "Delegates requests to kill an instance of a service to peer routers." [service-id router-ids make-kill-instance-request-fn] (if (not-empty router-ids) (loop [[dest-router-id & remaining-router-ids] (seq router-ids)] (let [dest-endpoint (str "waiter-kill-instance/" service-id) {:keys [body status]} (make-kill-instance-request-fn dest-router-id dest-endpoint) kill-successful? (= 200 status)] (when kill-successful? (log/info "peer communication" dest-router-id "killed instance of" service-id body)) (if (and remaining-router-ids (not kill-successful?)) (recur remaining-router-ids) kill-successful?))) (do (log/warn "no peer routers found! Unable to delegate call to kill instance of" service-id) false))) (defn service-gc-go-routine "Go-routine that performs GC of services. Only the leader gets to perform the GC operations. Other routers keep looping waiting for their turn to become a leader. Parameters: `read-state-fn`: (fn [name] ...) used to read the current state. `write-state-fn`: (fn [name state] ...) used to write the current state which potentially is used by the read. `leader?`: Returns true if the router is currently the leader, only the leader writes state into persistent store at `(str base-path '/' gc-relative-path '/' name`. `clock` (fn [] ...) returns the current time. `name`: Name of the go-routine. `service->raw-data-source`: A channel or a no-args function which produces service data. `timeout-interval-ms`: Timeout interval used as a refractory period while listening for data from `service-data-mult-chan` to allow effects of any GC run to propagate through the system. `in-exit-chan`: The exit signal channel. `sanitize-state-fn`: (fn [prev-service->state cur-services] ...). Sanitizes the previous state based on services available currently. `service->state-fn`: (fn [service cur-state data] ...). Transforms `data` into state to be used by the gc-service? function. `gc-service?`: (fn [service {:keys [state last-modified-time]} cur-time] ...). Predicate function that returns true for apps that need to be gc-ed. `perform-gc-fn`: (fn [service] ...). Function that performs GC of the service. It must return a truth-y value when successful." [read-state-fn write-state-fn leader? clock name service->raw-data-source timeout-interval-ms sanitize-state-fn service->state-fn gc-service? perform-gc-fn] {:pre (pos? timeout-interval-ms)} (let [query-chan (async/chan 10) state-cache (cu/cache-factory {:ttl (/ timeout-interval-ms 2)}) query-state-fn (fn query-state-fn [] (cu/cache-get-or-load state-cache name #(read-state-fn name))) query-service-state-fn (fn query-service-state-fn [{:keys [service-id]}] (-> (query-state-fn) (get service-id) (or {}))) exit-chan (async/chan 1)] (cid/with-correlation-id name (async/go-loop [iter 0 timeout-chan (async/timeout timeout-interval-ms)] (let [[chan args] (async/alt! exit-chan ([_] [:exit]) query-chan ([args] [:query args]) timeout-chan ([_] [:continue]) :priority true)] (case chan :exit (log/info "[service-gc-go-routine] exiting" name) :query (let [{:keys [response-chan]} args state (query-service-state-fn args)] (async/>! response-chan (or state {})) (recur (inc iter) timeout-chan)) :continue (do (when (leader?) (let [service->raw-data (if (fn? service->raw-data-source) (service->raw-data-source) (async/<! service->raw-data-source))] (timers/start-stop-time! (metrics/waiter-timer "gc" name "iteration-duration") (try (let [service->state (or (read-state-fn name) {}) current-time (clock) service->state' (apply merge (sanitize-state-fn service->state (keys service->raw-data)) (map (fn [[service raw-data]] (let [cur-state (get service->state service) new-state (service->state-fn service (:state cur-state) raw-data)] (if (= (:state cur-state) new-state) [service cur-state] [service {:state new-state :last-modified-time current-time}]))) service->raw-data)) apps-to-gc (map first (filter (fn [[service state]] (when-let [gc-service (gc-service? service state current-time)] (log/info service "with state" (:state state) "and last modified time" (du/date-to-str (:last-modified-time state)) "marked for deletion") gc-service)) service->state')) apps-successfully-gced (filter (fn [service] (try (when (leader?) ; check to ensure still the leader (perform-gc-fn service)) (catch Exception e (log/error e "error in deleting:" service)))) apps-to-gc) apps-failed-to-delete (apply disj (set apps-to-gc) apps-successfully-gced) service->state'' (apply dissoc service->state' apps-successfully-gced)] (when (or (not= (set (keys service->state'')) (set (keys service->raw-data))) (not= (set (keys service->state'')) (set (keys service->state)))) (log/info "state has" (count service->state'') "active services, received" (count service->raw-data) "services in latest update.")) (when (not-empty apps-failed-to-delete) (log/warn "unable to delete services:" apps-failed-to-delete)) (write-state-fn name service->state'') (cu/cache-evict state-cache name)) (catch Exception e (log/error e "error in" name {:iteration iter})))))) (recur (inc iter) (async/timeout timeout-interval-ms))))))) {:exit exit-chan :query query-chan :query-service-state-fn query-service-state-fn :query-state-fn query-state-fn})) (defn make-inter-router-requests "Helper function to make inter-router requests with basic authentication. It assumes that the response from inter-router communication always supports json." [make-request-fn make-basic-auth-fn my-router-id discovery passwords endpoint & {:keys [acceptable-router? body config method] :or {acceptable-router? (constantly true) body "" config {} method :get}}] (let [router-id->endpoint-url (discovery/router-id->endpoint-url discovery "http" endpoint :exclude-set #{my-router-id}) router-id->endpoint-url' (filter (fn [[router-id _]] (acceptable-router? router-id)) router-id->endpoint-url) request-config (update config :headers (fn prepare-inter-router-requests-headers [headers] (-> headers (assoc "accept" "application/json") (update "x-cid" (fn attach-inter-router-cid [provided-cid] (or provided-cid (let [current-cid (cid/get-correlation-id) cid-prefix (if (or (nil? current-cid) (= cid/default-correlation-id current-cid)) "waiter" current-cid)] (str cid-prefix "." (utils/unique-identifier)))))))))] (when (and (empty? router-id->endpoint-url') (not-empty router-id->endpoint-url)) (log/info "no acceptable routers found to make request!")) (loop [[[dest-router-id endpoint-url] & remaining-items] router-id->endpoint-url' router-id->response {}] (if dest-router-id (let [secret-word (utils/generate-secret-word my-router-id dest-router-id passwords) auth (make-basic-auth-fn endpoint-url my-router-id secret-word) response (make-request-fn method endpoint-url auth body request-config)] (recur remaining-items (assoc router-id->response dest-router-id response))) router-id->response)))) (defn make-request-async "Makes an asynchronous request to the endpoint using the provided authentication scheme. Returns a core.async channel that will return the response map." [http-client idle-timeout method endpoint-url auth body config] (http/request http-client (merge {:auth auth :body body :follow-redirects? false :idle-timeout idle-timeout :method method :url endpoint-url} config))) (defn make-request-sync "Makes a synchronous request to the endpoint using the provided authentication scheme. Returns a response map with the body, status and headers populated." [http-client idle-timeout method endpoint-url auth body config] (let [resp-chan (make-request-async http-client idle-timeout method endpoint-url auth body config) {:keys [body error] :as response} (async/<!! resp-chan)] (if error (log/error error "Error in communicating at" endpoint-url) (let [body-response (async/<!! body)] ;; response has been read, close as we do not use chunked encoding in inter-router (async/close! body) (assoc response :body body-response))))) (defn waiter-request?-factory "Creates a function that determines for a given request whether or not the request is intended for Waiter itself or a service of Waiter." [valid-waiter-hostnames] (let [valid-waiter-hostnames (set/union valid-waiter-hostnames #{"localhost" "127.0.0.1"})] (fn waiter-request? [{:keys [uri headers]}] (let [{:strs [host]} headers] (or (#{"/app-name" "/service-id" "/token"} uri) ; special urls that are always for Waiter (FIXME) (some #(str/starts-with? (str uri) %) ["/waiter-async/complete/" "/waiter-async/result/" "/waiter-async/status/" "/waiter-consent" "/waiter-interstitial"]) (and (or (str/blank? host) (valid-waiter-hostnames (-> host (str/split #":") first))) (not-any? #(str/starts-with? (key %) headers/waiter-header-prefix) (remove #(= "x-waiter-debug" (key %)) headers)))))))) (defn leader-fn-factory "Creates the leader? function. Leadership is decided by the leader latch and presence of at least `min-cluster-routers` peers." [router-id has-leadership? discovery min-cluster-routers] #(and (has-leadership?) ; no one gets to be the leader if there aren't at least min-cluster-routers in the clique (let [num-routers (discovery/cluster-size discovery)] (when (< num-routers min-cluster-routers) (log/info router-id "relinquishing leadership as there are too few routers in cluster:" num-routers)) (>= num-routers min-cluster-routers)))) ;; PRIVATE API (def state {:async-request-store-atom (pc/fnk [] (atom {})) :authenticator (pc/fnk [[:settings authenticator-config] passwords] (utils/create-component authenticator-config :context {:password (first passwords)})) :clock (pc/fnk [] t/now) :cors-validator (pc/fnk [[:settings cors-config]] (utils/create-component cors-config)) :entitlement-manager (pc/fnk [[:settings entitlement-config]] (utils/create-component entitlement-config)) :fallback-state-atom (pc/fnk [] (atom {:available-service-ids #{} :healthy-service-ids #{}})) :http-clients (pc/fnk [[:settings [:instance-request-properties connection-timeout-ms]] server-name] (http-utils/prepare-http-clients {:conn-timeout connection-timeout-ms :follow-redirects? false :user-agent server-name})) :instance-rpc-chan (pc/fnk [] (async/chan 1024)) ; TODO move to service-chan-maintainer :interstitial-state-atom (pc/fnk [] (atom {:initialized? false :service-id->interstitial-promise {}})) :local-usage-agent (pc/fnk [] (agent {})) :passwords (pc/fnk [[:settings password-store-config]] (let [password-provider (utils/create-component password-store-config) passwords (password-store/retrieve-passwords password-provider) _ (password-store/check-empty-passwords passwords) processed-passwords (mapv #(vector :cached %) passwords)] processed-passwords)) :query-service-maintainer-chan (pc/fnk [] (au/latest-chan)) ; TODO move to service-chan-maintainer :router-metrics-agent (pc/fnk [router-id] (metrics-sync/new-router-metrics-agent router-id {})) :router-id (pc/fnk [[:settings router-id-prefix]] (cond->> (utils/unique-identifier) (not (str/blank? router-id-prefix)) (str (str/replace router-id-prefix #"[@.]" "-") "-"))) :scaling-timeout-config (pc/fnk [[:settings [:blacklist-config blacklist-backoff-base-time-ms max-blacklist-time-ms] [:scaling inter-kill-request-wait-time-ms]]] {:blacklist-backoff-base-time-ms blacklist-backoff-base-time-ms :inter-kill-request-wait-time-ms inter-kill-request-wait-time-ms :max-blacklist-time-ms max-blacklist-time-ms}) :scheduler-interactions-thread-pool (pc/fnk [] (Executors/newFixedThreadPool 20)) :scheduler-state-chan (pc/fnk [] (au/latest-chan)) :server-name (pc/fnk [[:settings git-version]] (let [server-name (str "waiter/" (str/join (take 7 git-version)))] (utils/reset-server-name-atom! server-name) server-name)) :service-description-builder (pc/fnk [[:settings service-description-builder-config service-description-constraints]] (when-let [unknown-keys (-> service-description-constraints keys set (set/difference sd/service-parameter-keys) seq)] (throw (ex-info "Unsupported keys present in the service description constraints" {:service-description-constraints service-description-constraints :unsupported-keys (-> unknown-keys vec sort)}))) (utils/create-component service-description-builder-config :context {:constraints service-description-constraints})) :service-id-prefix (pc/fnk [[:settings [:cluster-config service-prefix]]] service-prefix) :start-service-cache (pc/fnk [] (cu/cache-factory {:threshold 100 :ttl (-> 1 t/minutes t/in-millis)})) :token-cluster-calculator (pc/fnk [[:settings [:cluster-config name] [:token-config cluster-calculator]]] (utils/create-component cluster-calculator :context {:default-cluster name})) :token-root (pc/fnk [[:settings [:cluster-config name]]] name) :waiter-hostnames (pc/fnk [[:settings hostname]] (set (if (sequential? hostname) hostname [hostname]))) :websocket-client (pc/fnk [[:settings [:websocket-config ws-max-binary-message-size ws-max-text-message-size]] http-clients] (let [http-client (http-utils/select-http-client "http" http-clients) websocket-client (WebSocketClient. ^HttpClient http-client)] (doto (.getPolicy websocket-client) (.setMaxBinaryMessageSize ws-max-binary-message-size) (.setMaxTextMessageSize ws-max-text-message-size)) websocket-client))}) (def curator {:curator (pc/fnk [[:settings [:zookeeper [:curator-retry-policy base-sleep-time-ms max-retries max-sleep-time-ms] connect-string]]] (let [retry-policy (BoundedExponentialBackoffRetry. base-sleep-time-ms max-sleep-time-ms max-retries) zk-connection-string (if (= :in-process connect-string) (:zk-connection-string (curator/start-in-process-zookeeper)) connect-string) curator (CuratorFrameworkFactory/newClient zk-connection-string 5000 5000 retry-policy)] (.start curator) ; register listener that notifies of sync call completions (.addListener (.getCuratorListenable curator) (reify CuratorListener (eventReceived [_ _ event] (when (= CuratorEventType/SYNC (.getType event)) (log/info "received SYNC event for" (.getPath event)) (when-let [response-promise (.getContext event)] (log/info "releasing response promise provided for" (.getPath event)) (deliver response-promise :release)))))) curator)) :curator-base-init (pc/fnk [curator [:settings [:zookeeper base-path]]] (curator/create-path curator base-path :create-parent-zknodes? true)) :discovery (pc/fnk [[:settings [:cluster-config name] [:zookeeper base-path discovery-relative-path] host port] [:state router-id] curator] (discovery/register router-id curator name (str base-path "/" discovery-relative-path) {:host host :port port})) :gc-base-path (pc/fnk [[:settings [:zookeeper base-path gc-relative-path]]] (str base-path "/" gc-relative-path)) :gc-state-reader-fn (pc/fnk [curator gc-base-path] (fn read-gc-state [name] (:data (curator/read-path curator (str gc-base-path "/" name) :nil-on-missing? true :serializer :nippy)))) :gc-state-writer-fn (pc/fnk [curator gc-base-path] (fn write-gc-state [name state] (curator/write-path curator (str gc-base-path "/" name) state :serializer :nippy :create-parent-zknodes? true))) :kv-store (pc/fnk [[:settings [:zookeeper base-path] kv-config] [:state passwords] curator] (kv/new-kv-store kv-config curator base-path passwords)) :leader?-fn (pc/fnk [[:settings [:cluster-config min-routers]] [:state router-id] discovery leader-latch] (let [has-leadership? #(.hasLeadership leader-latch)] (leader-fn-factory router-id has-leadership? discovery min-routers))) :leader-id-fn (pc/fnk [leader-latch] #(try (-> leader-latch .getLeader .getId) (catch Exception ex (log/error ex "unable to retrieve leader id")))) :leader-latch (pc/fnk [[:settings [:zookeeper base-path leader-latch-relative-path]] [:state router-id] curator] (let [leader-latch-path (str base-path "/" leader-latch-relative-path) latch (LeaderLatch. curator leader-latch-path router-id)] (.start latch) latch))}) (def scheduler {:scheduler (pc/fnk [[:curator leader?-fn] [:settings scheduler-config scheduler-syncer-interval-secs] [:state scheduler-state-chan service-id-prefix] service-id->password-fn* service-id->service-description-fn* start-scheduler-syncer-fn] (let [is-waiter-service?-fn (fn is-waiter-service? [^String service-id] (str/starts-with? service-id service-id-prefix)) scheduler-context {:is-waiter-service?-fn is-waiter-service?-fn :leader?-fn leader?-fn :scheduler-name (-> scheduler-config :kind utils/keyword->str) :scheduler-state-chan scheduler-state-chan ;; TODO scheduler-syncer-interval-secs should be inside the scheduler's config :scheduler-syncer-interval-secs scheduler-syncer-interval-secs :service-id->password-fn service-id->password-fn* :service-id->service-description-fn service-id->service-description-fn* :start-scheduler-syncer-fn start-scheduler-syncer-fn}] (utils/create-component scheduler-config :context scheduler-context))) ; This function is only included here for initializing the scheduler above. ; Prefer accessing the non-starred version of this function through the routines map. :service-id->password-fn* (pc/fnk [[:state passwords]] (fn service-id->password [service-id] (log/debug "generating password for" service-id) (digest/md5 (str service-id (first passwords))))) ; This function is only included here for initializing the scheduler above. ; Prefer accessing the non-starred version of this function through the routines map. :service-id->service-description-fn* (pc/fnk [[:curator kv-store] [:settings service-description-defaults metric-group-mappings]] (fn service-id->service-description [service-id & {:keys [effective?] :or {effective? true}}] (sd/service-id->service-description kv-store service-id service-description-defaults metric-group-mappings :effective? effective?))) :start-scheduler-syncer-fn (pc/fnk [[:settings [:health-check-config health-check-timeout-ms failed-check-threshold] git-version] [:state clock] service-id->service-description-fn*] (let [http-client (http-utils/http-client-factory {:conn-timeout health-check-timeout-ms :socket-timeout health-check-timeout-ms :user-agent (str "waiter-syncer/" (str/join (take 7 git-version)))}) available? (fn scheduler-available? [scheduler-name service-instance health-check-proto health-check-port-index health-check-path] (scheduler/available? http-client scheduler-name service-instance health-check-proto health-check-port-index health-check-path))] (fn start-scheduler-syncer-fn [scheduler-name get-service->instances-fn scheduler-state-chan scheduler-syncer-interval-secs] (let [timeout-chan (->> (t/seconds scheduler-syncer-interval-secs) (du/time-seq (t/now)) chime/chime-ch)] (scheduler/start-scheduler-syncer clock timeout-chan service-id->service-description-fn* available? failed-check-threshold scheduler-name get-service->instances-fn scheduler-state-chan)))))}) (def routines {:allowed-to-manage-service?-fn (pc/fnk [[:curator kv-store] [:state entitlement-manager]] (fn allowed-to-manage-service? [service-id auth-user] ; Returns whether the authenticated user is allowed to manage the service. ; Either she can run as the waiter user or the run-as-user of the service description." (sd/can-manage-service? kv-store entitlement-manager service-id auth-user))) :assoc-run-as-user-approved? (pc/fnk [[:settings consent-expiry-days] [:state clock passwords] token->token-metadata] (fn assoc-run-as-user-approved? [{:keys [headers]} service-id] (let [{:strs [cookie host]} headers token (when-not (headers/contains-waiter-header headers sd/on-the-fly-service-description-keys) (utils/authority->host host)) token-metadata (when token (token->token-metadata token)) service-consent-cookie (cookie-support/cookie-value cookie "x-waiter-consent") decoded-cookie (when service-consent-cookie (some #(cookie-support/decode-cookie-cached service-consent-cookie %1) passwords))] (sd/assoc-run-as-user-approved? clock consent-expiry-days service-id token token-metadata decoded-cookie)))) :async-request-terminate-fn (pc/fnk [[:state async-request-store-atom]] (fn async-request-terminate [request-id] (async-req/async-request-terminate async-request-store-atom request-id))) :async-trigger-terminate-fn (pc/fnk [[:state router-id] async-request-terminate-fn make-inter-router-requests-sync-fn] (fn async-trigger-terminate-fn [target-router-id service-id request-id] (async-req/async-trigger-terminate async-request-terminate-fn make-inter-router-requests-sync-fn router-id target-router-id service-id request-id))) :authentication-method-wrapper-fn (pc/fnk [[:state authenticator]] (fn authentication-method-wrapper [request-handler] (let [auth-handler (auth/wrap-auth-handler authenticator request-handler)] (fn authenticate-request [request] (if (:skip-authentication request) (do (log/info "skipping authentication for request") (request-handler request)) (auth-handler request)))))) :can-run-as?-fn (pc/fnk [[:state entitlement-manager]] (fn can-run-as [auth-user run-as-user] (authz/run-as? entitlement-manager auth-user run-as-user))) :crypt-helpers (pc/fnk [[:state passwords]] (let [password (first passwords)] {:bytes-decryptor (fn bytes-decryptor [data] (utils/compressed-bytes->map data password)) :bytes-encryptor (fn bytes-encryptor [data] (utils/map->compressed-bytes data password))})) :delegate-instance-kill-request-fn (pc/fnk [[:curator discovery] [:state router-id] make-inter-router-requests-sync-fn] (fn delegate-instance-kill-request-fn [service-id] (delegate-instance-kill-request service-id (discovery/router-ids discovery :exclude-set #{router-id}) (partial make-kill-instance-request make-inter-router-requests-sync-fn service-id)))) :determine-priority-fn (pc/fnk [] (let [position-generator-atom (atom 0)] (fn determine-priority-fn [waiter-headers] (pr/determine-priority position-generator-atom waiter-headers)))) :generate-log-url-fn (pc/fnk [prepend-waiter-url] (partial handler/generate-log-url prepend-waiter-url)) :list-tokens-fn (pc/fnk [[:curator curator] [:settings [:zookeeper base-path] kv-config]] (fn list-tokens-fn [] (let [{:keys [relative-path]} kv-config] (->> (kv/zk-keys curator (str base-path "/" relative-path)) (filter (fn [k] (not (str/starts-with? k "^")))))))) :make-basic-auth-fn (pc/fnk [] (fn make-basic-auth-fn [uri username password] (BasicAuthentication$BasicResult. (URI. uri) username password))) :make-http-request-fn (pc/fnk [[:settings instance-request-properties] [:state http-clients] make-basic-auth-fn service-id->password-fn] (handler/async-make-request-helper http-clients instance-request-properties make-basic-auth-fn service-id->password-fn pr/prepare-request-properties pr/make-request)) :make-inter-router-requests-async-fn (pc/fnk [[:curator discovery] [:settings [:instance-request-properties initial-socket-timeout-ms]] [:state http-clients passwords router-id] make-basic-auth-fn] (let [http-client (http-utils/select-http-client "http" http-clients) make-request-async-fn (fn make-request-async-fn [method endpoint-url auth body config] (make-request-async http-client initial-socket-timeout-ms method endpoint-url auth body config))] (fn make-inter-router-requests-async-fn [endpoint & args] (apply make-inter-router-requests make-request-async-fn make-basic-auth-fn router-id discovery passwords endpoint args)))) :make-inter-router-requests-sync-fn (pc/fnk [[:curator discovery] [:settings [:instance-request-properties initial-socket-timeout-ms]] [:state http-clients passwords router-id] make-basic-auth-fn] (let [http-client (http-utils/select-http-client "http" http-clients) make-request-sync-fn (fn make-request-sync-fn [method endpoint-url auth body config] (make-request-sync http-client initial-socket-timeout-ms method endpoint-url auth body config))] (fn make-inter-router-requests-sync-fn [endpoint & args] (apply make-inter-router-requests make-request-sync-fn make-basic-auth-fn router-id discovery passwords endpoint args)))) :peers-acknowledged-blacklist-requests-fn (pc/fnk [[:curator discovery] [:state router-id] make-inter-router-requests-sync-fn] (fn peers-acknowledged-blacklist-requests [instance short-circuit? blacklist-period-ms reason] (let [router-ids (discovery/router-ids discovery :exclude-set #{router-id})] (peers-acknowledged-blacklist-requests? instance short-circuit? router-ids "blacklist" (partial make-blacklist-request make-inter-router-requests-sync-fn blacklist-period-ms) reason)))) :post-process-async-request-response-fn (pc/fnk [[:state async-request-store-atom instance-rpc-chan router-id] make-http-request-fn] (fn post-process-async-request-response-wrapper [response service-id metric-group backend-proto instance _ reason-map request-properties location query-string] (async-req/post-process-async-request-response router-id async-request-store-atom make-http-request-fn instance-rpc-chan response service-id metric-group backend-proto instance reason-map request-properties location query-string))) :prepend-waiter-url (pc/fnk [[:settings port hostname]] (let [hostname (if (sequential? hostname) (first hostname) hostname)] (fn [endpoint-url] (if (str/blank? endpoint-url) endpoint-url (str "http://" hostname ":" port endpoint-url))))) :refresh-service-descriptions-fn (pc/fnk [[:curator kv-store]] (fn refresh-service-descriptions-fn [service-ids] (sd/refresh-service-descriptions kv-store service-ids))) :request->descriptor-fn (pc/fnk [[:curator kv-store] [:settings [:token-config history-length token-defaults] metric-group-mappings service-description-defaults] [:state fallback-state-atom service-description-builder service-id-prefix waiter-hostnames] assoc-run-as-user-approved? can-run-as?-fn store-source-tokens-fn] (fn request->descriptor-fn [request] (let [{:keys [latest-descriptor] :as result} (descriptor/request->descriptor assoc-run-as-user-approved? can-run-as?-fn fallback-state-atom kv-store metric-group-mappings history-length service-description-builder service-description-defaults service-id-prefix token-defaults waiter-hostnames request)] (when-let [source-tokens (-> latest-descriptor :source-tokens seq)] (store-source-tokens-fn (:service-id latest-descriptor) source-tokens)) result))) :router-metrics-helpers (pc/fnk [[:state passwords router-metrics-agent]] (let [password (first passwords)] {:decryptor (fn router-metrics-decryptor [data] (utils/compressed-bytes->map data password)) :encryptor (fn router-metrics-encryptor [data] (utils/map->compressed-bytes data password)) :router-metrics-state-fn (fn router-metrics-state [] @router-metrics-agent) :service-id->metrics-fn (fn service-id->metrics [] (metrics-sync/agent->service-id->metrics router-metrics-agent)) :service-id->router-id->metrics (fn service-id->router-id->metrics [service-id] (metrics-sync/agent->service-id->router-id->metrics router-metrics-agent service-id))})) :service-description->service-id (pc/fnk [[:state service-id-prefix]] (fn service-description->service-id [service-description] (sd/service-description->service-id service-id-prefix service-description))) :service-id->idle-timeout (pc/fnk [[:settings [:token-config token-defaults]] service-id->service-description-fn service-id->source-tokens-entries-fn token->token-hash token->token-metadata] (fn service-id->idle-timeout [service-id] (sd/service-id->idle-timeout service-id->service-description-fn service-id->source-tokens-entries-fn token->token-hash token->token-metadata token-defaults service-id))) :service-id->password-fn (pc/fnk [[:scheduler service-id->password-fn*]] service-id->password-fn*) :service-id->service-description-fn (pc/fnk [[:scheduler service-id->service-description-fn*]] service-id->service-description-fn*) :service-id->source-tokens-entries-fn (pc/fnk [[:curator kv-store]] (partial sd/service-id->source-tokens-entries kv-store)) :start-new-service-fn (pc/fnk [[:scheduler scheduler] [:state start-service-cache scheduler-interactions-thread-pool] store-service-description-fn] (fn start-new-service [{:keys [service-id] :as descriptor}] (store-service-description-fn descriptor) (scheduler/validate-service scheduler service-id) (service/start-new-service scheduler descriptor start-service-cache scheduler-interactions-thread-pool))) :start-work-stealing-balancer-fn (pc/fnk [[:settings [:work-stealing offer-help-interval-ms reserve-timeout-ms]] [:state instance-rpc-chan router-id] make-inter-router-requests-async-fn router-metrics-helpers] (fn start-work-stealing-balancer [service-id] (let [{:keys [service-id->router-id->metrics]} router-metrics-helpers] (work-stealing/start-work-stealing-balancer instance-rpc-chan reserve-timeout-ms offer-help-interval-ms service-id->router-id->metrics make-inter-router-requests-async-fn router-id service-id)))) :stop-work-stealing-balancer-fn (pc/fnk [] (fn stop-work-stealing-balancer [service-id work-stealing-chan-map] (log/info "stopping work-stealing balancer for" service-id) (async/go (when-let [exit-chan (get work-stealing-chan-map [:exit-chan])] (async/>! exit-chan :exit))))) :store-service-description-fn (pc/fnk [[:curator kv-store] validate-service-description-fn] (fn store-service-description [{:keys [core-service-description service-id]}] (sd/store-core kv-store service-id core-service-description validate-service-description-fn))) :store-source-tokens-fn (pc/fnk [[:curator kv-store] synchronize-fn] (fn store-source-tokens-fn [service-id source-tokens] (sd/store-source-tokens! synchronize-fn kv-store service-id source-tokens))) :synchronize-fn (pc/fnk [[:curator curator] [:settings [:zookeeper base-path mutex-timeout-ms]]] (fn synchronize-fn [path f] (let [lock-path (str base-path "/" path)] (curator/synchronize curator lock-path mutex-timeout-ms f)))) :token->service-description-template (pc/fnk [[:curator kv-store]] (fn token->service-description-template [token] (sd/token->service-description-template kv-store token :error-on-missing false))) :token->token-hash (pc/fnk [[:curator kv-store]] (fn token->token-hash [token] (sd/token->token-hash kv-store token))) :token->token-metadata (pc/fnk [[:curator kv-store]] (fn token->token-metadata [token] (sd/token->token-metadata kv-store token :error-on-missing false))) :validate-service-description-fn (pc/fnk [[:state service-description-builder]] (fn validate-service-description [service-description] (sd/validate service-description-builder service-description {}))) :waiter-request?-fn (pc/fnk [[:state waiter-hostnames]] (let [local-router (InetAddress/getLocalHost) waiter-router-hostname (.getCanonicalHostName local-router) waiter-router-ip (.getHostAddress local-router) hostnames (conj waiter-hostnames waiter-router-hostname waiter-router-ip)] (waiter-request?-factory hostnames))) :websocket-request-auth-cookie-attacher (pc/fnk [[:state passwords router-id]] (fn websocket-request-auth-cookie-attacher [request] (ws/inter-router-request-middleware router-id (first passwords) request))) :websocket-request-acceptor (pc/fnk [[:state passwords]] (fn websocket-request-acceptor [^ServletUpgradeRequest request ^ServletUpgradeResponse response] (.setHeader response "x-cid" (cid/get-correlation-id)) (if (ws/request-authenticator (first passwords) request response) (ws/request-subprotocol-acceptor request response) false)))}) (def daemons {:autoscaler (pc/fnk [[:curator leader?-fn] [:routines router-metrics-helpers service-id->service-description-fn] [:scheduler scheduler] [:settings [:scaling autoscaler-interval-ms]] [:state scheduler-interactions-thread-pool] autoscaling-multiplexer router-state-maintainer] (let [service-id->metrics-fn (:service-id->metrics-fn router-metrics-helpers) {{:keys [router-state-push-mult]} :maintainer} router-state-maintainer {:keys [executor-multiplexer-chan]} autoscaling-multiplexer] (scaling/autoscaler-goroutine {} leader?-fn service-id->metrics-fn executor-multiplexer-chan scheduler autoscaler-interval-ms scaling/scale-service service-id->service-description-fn router-state-push-mult scheduler-interactions-thread-pool))) :autoscaling-multiplexer (pc/fnk [[:routines delegate-instance-kill-request-fn peers-acknowledged-blacklist-requests-fn service-id->service-description-fn] [:scheduler scheduler] [:settings [:scaling quanta-constraints]] [:state instance-rpc-chan scheduler-interactions-thread-pool scaling-timeout-config] router-state-maintainer] (let [{{:keys [notify-instance-killed-fn]} :maintainer} router-state-maintainer] (scaling/service-scaling-multiplexer (fn scaling-executor-factory [service-id] (scaling/service-scaling-executor notify-instance-killed-fn peers-acknowledged-blacklist-requests-fn delegate-instance-kill-request-fn service-id->service-description-fn scheduler instance-rpc-chan quanta-constraints scaling-timeout-config scheduler-interactions-thread-pool service-id)) {}))) :codahale-reporters (pc/fnk [[:settings [:metrics-config codahale-reporters]]] (pc/map-vals (fn make-codahale-reporter [{:keys [factory-fn] :as reporter-config}] (let [resolved-factory-fn (utils/resolve-symbol! factory-fn) reporter-instance (resolved-factory-fn reporter-config)] (when-not (satisfies? reporter/CodahaleReporter reporter-instance) (throw (ex-info "Reporter factory did not create an instance of CodahaleReporter" {:reporter-config reporter-config :reporter-instance reporter-instance :resolved-factory-fn resolved-factory-fn}))) reporter-instance)) codahale-reporters)) :fallback-maintainer (pc/fnk [[:state fallback-state-atom] router-state-maintainer] (let [{{:keys [router-state-push-mult]} :maintainer} router-state-maintainer router-state-chan (async/tap router-state-push-mult (au/latest-chan))] (descriptor/fallback-maintainer router-state-chan fallback-state-atom))) :gc-for-transient-metrics (pc/fnk [[:routines router-metrics-helpers] [:settings metrics-config] [:state clock local-usage-agent] router-state-maintainer] (let [state-store-atom (atom {}) read-state-fn (fn read-state [_] @state-store-atom) write-state-fn (fn write-state [_ state] (reset! state-store-atom state)) leader?-fn (constantly true) service-gc-go-routine (partial service-gc-go-routine read-state-fn write-state-fn leader?-fn clock) {{:keys [query-state-fn]} :maintainer} router-state-maintainer {:keys [service-id->metrics-fn]} router-metrics-helpers {:keys [service-id->metrics-chan] :as metrics-gc-chans} (metrics/transient-metrics-gc query-state-fn local-usage-agent service-gc-go-routine metrics-config)] (metrics/transient-metrics-data-producer service-id->metrics-chan service-id->metrics-fn metrics-config) metrics-gc-chans)) :interstitial-maintainer (pc/fnk [[:routines service-id->service-description-fn] [:state interstitial-state-atom] router-state-maintainer] (let [{{:keys [router-state-push-mult]} :maintainer} router-state-maintainer router-state-chan (async/tap router-state-push-mult (au/latest-chan)) initial-state {}] (interstitial/interstitial-maintainer service-id->service-description-fn router-state-chan interstitial-state-atom initial-state))) :launch-metrics-maintainer (pc/fnk [[:curator leader?-fn] [:routines service-id->service-description-fn] router-state-maintainer] (let [{{:keys [router-state-push-mult]} :maintainer} router-state-maintainer] (scheduler/start-launch-metrics-maintainer (async/tap router-state-push-mult (au/latest-chan)) leader?-fn service-id->service-description-fn))) :messages (pc/fnk [[:settings {messages nil}]] (when messages (utils/load-messages messages))) :router-list-maintainer (pc/fnk [[:curator discovery] [:settings router-syncer]] (let [{:keys [delay-ms interval-ms]} router-syncer router-chan (au/latest-chan) router-mult-chan (async/mult router-chan)] (state/start-router-syncer discovery router-chan interval-ms delay-ms) {:router-mult-chan router-mult-chan})) :router-metrics-syncer (pc/fnk [[:routines crypt-helpers websocket-request-auth-cookie-attacher] [:settings [:metrics-config inter-router-metrics-idle-timeout-ms metrics-sync-interval-ms router-update-interval-ms]] [:state local-usage-agent router-metrics-agent websocket-client] router-list-maintainer] (let [{:keys [bytes-encryptor]} crypt-helpers router-chan (async/tap (:router-mult-chan router-list-maintainer) (au/latest-chan))] {:metrics-syncer (metrics-sync/setup-metrics-syncer router-metrics-agent local-usage-agent metrics-sync-interval-ms bytes-encryptor) :router-syncer (metrics-sync/setup-router-syncer router-chan router-metrics-agent router-update-interval-ms inter-router-metrics-idle-timeout-ms metrics-sync-interval-ms websocket-client bytes-encryptor websocket-request-auth-cookie-attacher)})) :router-state-maintainer (pc/fnk [[:routines refresh-service-descriptions-fn service-id->service-description-fn] [:scheduler scheduler] [:settings deployment-error-config] [:state router-id scheduler-state-chan] router-list-maintainer] (let [exit-chan (async/chan) router-chan (async/tap (:router-mult-chan router-list-maintainer) (au/latest-chan)) service-id->deployment-error-config-fn #(scheduler/deployment-error-config scheduler %) maintainer (state/start-router-state-maintainer scheduler-state-chan router-chan router-id exit-chan service-id->service-description-fn refresh-service-descriptions-fn service-id->deployment-error-config-fn deployment-error-config)] {:exit-chan exit-chan :maintainer maintainer})) :scheduler-broken-services-gc (pc/fnk [[:curator gc-state-reader-fn gc-state-writer-fn leader?-fn] [:scheduler scheduler] [:settings scheduler-gc-config] [:state clock] router-state-maintainer] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer service-gc-go-routine (partial service-gc-go-routine gc-state-reader-fn gc-state-writer-fn leader?-fn clock)] (scheduler/scheduler-broken-services-gc service-gc-go-routine query-state-fn scheduler scheduler-gc-config))) :scheduler-services-gc (pc/fnk [[:curator gc-state-reader-fn gc-state-writer-fn leader?-fn] [:routines router-metrics-helpers service-id->idle-timeout] [:scheduler scheduler] [:settings scheduler-gc-config] [:state clock] router-state-maintainer] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer {:keys [service-id->metrics-fn]} router-metrics-helpers service-gc-go-routine (partial service-gc-go-routine gc-state-reader-fn gc-state-writer-fn leader?-fn clock)] (scheduler/scheduler-services-gc scheduler query-state-fn service-id->metrics-fn scheduler-gc-config service-gc-go-routine service-id->idle-timeout))) :service-chan-maintainer (pc/fnk [[:routines start-work-stealing-balancer-fn stop-work-stealing-balancer-fn] [:settings blacklist-config instance-request-properties] [:state instance-rpc-chan query-service-maintainer-chan] router-state-maintainer] (let [start-service (fn start-service [service-id] (let [maintainer-chan-map (state/prepare-and-start-service-chan-responder service-id instance-request-properties blacklist-config) workstealing-chan-map (start-work-stealing-balancer-fn service-id)] {:maintainer-chan-map maintainer-chan-map :work-stealing-chan-map workstealing-chan-map})) remove-service (fn remove-service [service-id {:keys [maintainer-chan-map work-stealing-chan-map]}] (state/close-update-state-channel service-id maintainer-chan-map) (stop-work-stealing-balancer-fn service-id work-stealing-chan-map)) retrieve-channel (fn retrieve-channel [channel-map method] (let [method-chan (case method :blacklist [:maintainer-chan-map :blacklist-instance-chan] :kill [:maintainer-chan-map :kill-instance-chan] :offer [:maintainer-chan-map :work-stealing-chan] :query-state [:maintainer-chan-map :query-state-chan] :query-work-stealing [:work-stealing-chan-map :query-chan] :release [:maintainer-chan-map :release-instance-chan] :reserve [:maintainer-chan-map :reserve-instance-chan-in] :update-state [:maintainer-chan-map :update-state-chan])] (get-in channel-map method-chan))) {{:keys [router-state-push-mult]} :maintainer} router-state-maintainer state-chan (au/latest-chan)] (async/tap router-state-push-mult state-chan) (state/start-service-chan-maintainer {} instance-rpc-chan state-chan query-service-maintainer-chan start-service remove-service retrieve-channel))) :state-sources (pc/fnk [[:scheduler scheduler] [:state query-service-maintainer-chan] autoscaler autoscaling-multiplexer gc-for-transient-metrics interstitial-maintainer scheduler-broken-services-gc scheduler-services-gc] {:autoscaler-state (:query-service-state-fn autoscaler) :autoscaling-multiplexer-state (:query-chan autoscaling-multiplexer) :interstitial-maintainer-state (:query-chan interstitial-maintainer) :scheduler-broken-services-gc-state (:query-service-state-fn scheduler-broken-services-gc) :scheduler-services-gc-state (:query-service-state-fn scheduler-services-gc) :scheduler-state (fn scheduler-state-fn [service-id] (scheduler/service-id->state scheduler service-id)) :service-maintainer-state query-service-maintainer-chan :transient-metrics-gc-state (:query-service-state-fn gc-for-transient-metrics)}) :statsd (pc/fnk [[:routines service-id->service-description-fn] [:settings statsd] router-state-maintainer] (when (not= statsd :disabled) (statsd/setup statsd) (let [{:keys [sync-instances-interval-ms]} statsd {{:keys [query-state-fn]} :maintainer} router-state-maintainer] (statsd/start-service-instance-metrics-publisher service-id->service-description-fn query-state-fn sync-instances-interval-ms))))}) (def request-handlers {:app-name-handler-fn (pc/fnk [service-id-handler-fn] service-id-handler-fn) :async-complete-handler-fn (pc/fnk [[:routines async-request-terminate-fn] wrap-router-auth-fn] (wrap-router-auth-fn (fn async-complete-handler-fn [request] (handler/complete-async-handler async-request-terminate-fn request)))) :async-result-handler-fn (pc/fnk [[:routines async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn async-result-handler-fn [request] (handler/async-result-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request)))) :async-status-handler-fn (pc/fnk [[:routines async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn async-status-handler-fn [request] (handler/async-status-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request)))) :blacklist-instance-handler-fn (pc/fnk [[:daemons router-state-maintainer] [:state instance-rpc-chan] wrap-router-auth-fn] (let [{{:keys [notify-instance-killed-fn]} :maintainer} router-state-maintainer] (wrap-router-auth-fn (fn blacklist-instance-handler-fn [request] (handler/blacklist-instance notify-instance-killed-fn instance-rpc-chan request))))) :blacklisted-instances-list-handler-fn (pc/fnk [[:state instance-rpc-chan]] (fn blacklisted-instances-list-handler-fn [{{:keys [service-id]} :route-params :as request}] (handler/get-blacklisted-instances instance-rpc-chan service-id request))) :default-websocket-handler-fn (pc/fnk [[:routines determine-priority-fn service-id->password-fn start-new-service-fn] [:settings instance-request-properties] [:state instance-rpc-chan local-usage-agent passwords websocket-client] wrap-descriptor-fn] (fn default-websocket-handler-fn [request] (let [password (first passwords) make-request-fn (fn make-ws-request [instance request request-properties passthrough-headers end-route metric-group backend-proto proto-version] (ws/make-request websocket-client service-id->password-fn instance request request-properties passthrough-headers end-route metric-group backend-proto proto-version)) process-request-fn (fn process-request-fn [request] (pr/process make-request-fn instance-rpc-chan start-new-service-fn instance-request-properties determine-priority-fn ws/process-response! ws/abort-request-callback-factory local-usage-agent request)) handler (-> process-request-fn (ws/wrap-ws-close-on-error) wrap-descriptor-fn)] (ws/request-handler password handler request)))) :display-settings-handler-fn (pc/fnk [wrap-secure-request-fn settings] (wrap-secure-request-fn (fn display-settings-handler-fn [_] (settings/display-settings settings)))) :favicon-handler-fn (pc/fnk [] (fn favicon-handler-fn [_] {:body (io/input-stream (io/resource "web/favicon.ico")) :content-type "image/png"})) :kill-instance-handler-fn (pc/fnk [[:daemons router-state-maintainer] [:routines peers-acknowledged-blacklist-requests-fn] [:scheduler scheduler] [:state instance-rpc-chan scaling-timeout-config scheduler-interactions-thread-pool] wrap-router-auth-fn] (let [{{:keys [notify-instance-killed-fn]} :maintainer} router-state-maintainer] (wrap-router-auth-fn (fn kill-instance-handler-fn [request] (scaling/kill-instance-handler notify-instance-killed-fn peers-acknowledged-blacklist-requests-fn scheduler instance-rpc-chan scaling-timeout-config scheduler-interactions-thread-pool request))))) :metrics-request-handler-fn (pc/fnk [] (fn metrics-request-handler-fn [request] (handler/metrics-request-handler request))) :not-found-handler-fn (pc/fnk [] handler/not-found-handler) :process-request-fn (pc/fnk [[:routines determine-priority-fn make-basic-auth-fn post-process-async-request-response-fn service-id->password-fn start-new-service-fn] [:settings instance-request-properties] [:state http-clients instance-rpc-chan local-usage-agent interstitial-state-atom] wrap-auth-bypass-fn wrap-descriptor-fn wrap-https-redirect-fn wrap-secure-request-fn wrap-service-discovery-fn] (let [make-request-fn (fn [instance request request-properties passthrough-headers end-route metric-group backend-proto proto-version] (pr/make-request http-clients make-basic-auth-fn service-id->password-fn instance request request-properties passthrough-headers end-route metric-group backend-proto proto-version)) process-response-fn (partial pr/process-http-response post-process-async-request-response-fn) inner-process-request-fn (fn inner-process-request [request] (pr/process make-request-fn instance-rpc-chan start-new-service-fn instance-request-properties determine-priority-fn process-response-fn pr/abort-http-request-callback-factory local-usage-agent request))] (-> inner-process-request-fn pr/wrap-too-many-requests pr/wrap-suspended-service pr/wrap-response-status-metrics (interstitial/wrap-interstitial interstitial-state-atom) wrap-descriptor-fn wrap-secure-request-fn wrap-auth-bypass-fn wrap-https-redirect-fn wrap-service-discovery-fn))) :router-metrics-handler-fn (pc/fnk [[:routines crypt-helpers] [:settings [:metrics-config metrics-sync-interval-ms]] [:state router-metrics-agent]] (let [{:keys [bytes-decryptor bytes-encryptor]} crypt-helpers] (fn router-metrics-handler-fn [request] (metrics-sync/incoming-router-metrics-handler router-metrics-agent metrics-sync-interval-ms bytes-encryptor bytes-decryptor request)))) :service-handler-fn (pc/fnk [[:curator kv-store] [:daemons router-state-maintainer] [:routines allowed-to-manage-service?-fn generate-log-url-fn make-inter-router-requests-sync-fn router-metrics-helpers service-id->service-description-fn service-id->source-tokens-entries-fn] [:scheduler scheduler] [:state router-id scheduler-interactions-thread-pool] wrap-secure-request-fn] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer {:keys [service-id->metrics-fn]} router-metrics-helpers] (wrap-secure-request-fn (fn service-handler-fn [{:as request {:keys [service-id]} :route-params}] (handler/service-handler router-id service-id scheduler kv-store allowed-to-manage-service?-fn generate-log-url-fn make-inter-router-requests-sync-fn service-id->service-description-fn service-id->source-tokens-entries-fn query-state-fn service-id->metrics-fn scheduler-interactions-thread-pool request))))) :service-id-handler-fn (pc/fnk [[:curator kv-store] [:routines store-service-description-fn] wrap-descriptor-fn wrap-secure-request-fn] (-> (fn service-id-handler-fn [request] (handler/service-id-handler request kv-store store-service-description-fn)) wrap-descriptor-fn wrap-secure-request-fn)) :service-list-handler-fn (pc/fnk [[:daemons router-state-maintainer] [:routines prepend-waiter-url router-metrics-helpers service-id->service-description-fn service-id->source-tokens-entries-fn] [:state entitlement-manager] wrap-secure-request-fn] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer {:keys [service-id->metrics-fn]} router-metrics-helpers] (wrap-secure-request-fn (fn service-list-handler-fn [request] (handler/list-services-handler entitlement-manager query-state-fn prepend-waiter-url service-id->service-description-fn service-id->metrics-fn service-id->source-tokens-entries-fn request))))) :service-override-handler-fn (pc/fnk [[:curator kv-store] [:routines allowed-to-manage-service?-fn make-inter-router-requests-sync-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn service-override-handler-fn [{:as request {:keys [service-id]} :route-params}] (handler/override-service-handler kv-store allowed-to-manage-service?-fn make-inter-router-requests-sync-fn service-id request)))) :service-refresh-handler-fn (pc/fnk [[:curator kv-store] wrap-router-auth-fn] (wrap-router-auth-fn (fn service-refresh-handler [{{:keys [service-id]} :route-params {:keys [src-router-id]} :basic-authentication}] (log/info service-id "refresh triggered by router" src-router-id) (sd/fetch-core kv-store service-id :refresh true) (sd/service-id->suspended-state kv-store service-id :refresh true) (sd/service-id->overrides kv-store service-id :refresh true)))) :service-resume-handler-fn (pc/fnk [[:curator kv-store] [:routines allowed-to-manage-service?-fn make-inter-router-requests-sync-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn service-resume-handler-fn [{:as request {:keys [service-id]} :route-params}] (handler/suspend-or-resume-service-handler kv-store allowed-to-manage-service?-fn make-inter-router-requests-sync-fn service-id :resume request)))) :service-suspend-handler-fn (pc/fnk [[:curator kv-store] [:routines allowed-to-manage-service?-fn make-inter-router-requests-sync-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn service-suspend-handler-fn [{:as request {:keys [service-id]} :route-params}] (handler/suspend-or-resume-service-handler kv-store allowed-to-manage-service?-fn make-inter-router-requests-sync-fn service-id :suspend request)))) :service-view-logs-handler-fn (pc/fnk [[:routines generate-log-url-fn] [:scheduler scheduler] wrap-secure-request-fn] (wrap-secure-request-fn (fn service-view-logs-handler-fn [{:as request {:keys [service-id]} :route-params}] (handler/service-view-logs-handler scheduler service-id generate-log-url-fn request)))) :sim-request-handler (pc/fnk [] simulator/handle-sim-request) :state-all-handler-fn (pc/fnk [[:daemons router-state-maintainer] [:state router-id] wrap-secure-request-fn] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer] (wrap-secure-request-fn (fn state-all-handler-fn [request] (handler/get-router-state router-id query-state-fn request))))) :state-autoscaler-handler-fn (pc/fnk [[:daemons autoscaler] [:state router-id] wrap-secure-request-fn] (let [{:keys [query-state-fn]} autoscaler] (wrap-secure-request-fn (fn state-autoscaler-handler-fn [request] (handler/get-query-fn-state router-id query-state-fn request))))) :state-autoscaling-multiplexer-handler-fn (pc/fnk [[:daemons autoscaling-multiplexer] [:state router-id] wrap-secure-request-fn] (let [{:keys [query-chan]} autoscaling-multiplexer] (wrap-secure-request-fn (fn state-autoscaling-multiplexer-handler-fn [request] (handler/get-query-chan-state-handler router-id query-chan request))))) :state-codahale-reporters-handler-fn (pc/fnk [[:daemons codahale-reporters] [:state router-id]] (fn codahale-reporter-state-handler-fn [request] (handler/get-query-fn-state router-id #(pc/map-vals reporter/state codahale-reporters) request))) :state-fallback-handler-fn (pc/fnk [[:daemons fallback-maintainer] [:state router-id] wrap-secure-request-fn] (let [fallback-query-chan (:query-chan fallback-maintainer)] (wrap-secure-request-fn (fn state-fallback-handler-fn [request] (handler/get-query-chan-state-handler router-id fallback-query-chan request))))) :state-gc-for-broken-services (pc/fnk [[:daemons scheduler-broken-services-gc] [:state router-id] wrap-secure-request-fn] (let [{:keys [query-state-fn]} scheduler-broken-services-gc] (wrap-secure-request-fn (fn state-autoscaler-handler-fn [request] (handler/get-query-fn-state router-id query-state-fn request))))) :state-gc-for-services (pc/fnk [[:daemons scheduler-services-gc] [:state router-id] wrap-secure-request-fn] (let [{:keys [query-state-fn]} scheduler-services-gc] (wrap-secure-request-fn (fn state-autoscaler-handler-fn [request] (handler/get-query-fn-state router-id query-state-fn request))))) :state-gc-for-transient-metrics (pc/fnk [[:daemons gc-for-transient-metrics] [:state router-id] wrap-secure-request-fn] (let [{:keys [query-state-fn]} gc-for-transient-metrics] (wrap-secure-request-fn (fn state-autoscaler-handler-fn [request] (handler/get-query-fn-state router-id query-state-fn request))))) :state-interstitial-handler-fn (pc/fnk [[:daemons interstitial-maintainer] [:state router-id] wrap-secure-request-fn] (let [interstitial-query-chan (:query-chan interstitial-maintainer)] (wrap-secure-request-fn (fn state-interstitial-handler-fn [request] (handler/get-query-chan-state-handler router-id interstitial-query-chan request))))) :state-launch-metrics-handler-fn (pc/fnk [[:daemons launch-metrics-maintainer] [:state router-id] wrap-secure-request-fn] (let [query-chan (:query-chan launch-metrics-maintainer)] (wrap-secure-request-fn (fn state-launch-metrics-handler-fn [request] (handler/get-query-chan-state-handler router-id query-chan request))))) :state-kv-store-handler-fn (pc/fnk [[:curator kv-store] [:state router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn kv-store-state-handler-fn [request] (handler/get-kv-store-state router-id kv-store request)))) :state-leader-handler-fn (pc/fnk [[:curator leader?-fn leader-id-fn] [:state router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn leader-state-handler-fn [request] (handler/get-leader-state router-id leader?-fn leader-id-fn request)))) :state-local-usage-handler-fn (pc/fnk [[:state local-usage-agent router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn local-usage-state-handler-fn [request] (handler/get-local-usage-state router-id local-usage-agent request)))) :state-maintainer-handler-fn (pc/fnk [[:daemons router-state-maintainer] [:state router-id] wrap-secure-request-fn] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer] (wrap-secure-request-fn (fn maintainer-state-handler-fn [request] (handler/get-chan-latest-state-handler router-id query-state-fn request))))) :state-router-metrics-handler-fn (pc/fnk [[:routines router-metrics-helpers] [:state router-id] wrap-secure-request-fn] (let [router-metrics-state-fn (:router-metrics-state-fn router-metrics-helpers)] (wrap-secure-request-fn (fn r-router-metrics-state-handler-fn [request] (handler/get-router-metrics-state router-id router-metrics-state-fn request))))) :state-scheduler-handler-fn (pc/fnk [[:scheduler scheduler] [:state router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn scheduler-state-handler-fn [request] (handler/get-scheduler-state router-id scheduler request)))) :state-service-handler-fn (pc/fnk [[:daemons state-sources] [:state instance-rpc-chan local-usage-agent router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn service-state-handler-fn [{{:keys [service-id]} :route-params :as request}] (handler/get-service-state router-id instance-rpc-chan local-usage-agent service-id state-sources request)))) :state-statsd-handler-fn (pc/fnk [[:state router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn state-statsd-handler-fn [request] (handler/get-statsd-state router-id request)))) :status-handler-fn (pc/fnk [] handler/status-handler) :token-handler-fn (pc/fnk [[:curator kv-store] [:routines make-inter-router-requests-sync-fn synchronize-fn validate-service-description-fn] [:settings [:token-config history-length limit-per-owner]] [:state clock entitlement-manager token-cluster-calculator token-root waiter-hostnames] wrap-secure-request-fn] (wrap-secure-request-fn (fn token-handler-fn [request] (token/handle-token-request clock synchronize-fn kv-store token-cluster-calculator token-root history-length limit-per-owner waiter-hostnames entitlement-manager make-inter-router-requests-sync-fn validate-service-description-fn request)))) :token-list-handler-fn (pc/fnk [[:curator kv-store] [:state entitlement-manager] wrap-secure-request-fn] (wrap-secure-request-fn (fn token-handler-fn [request] (token/handle-list-tokens-request kv-store entitlement-manager request)))) :token-owners-handler-fn (pc/fnk [[:curator kv-store] wrap-secure-request-fn] (wrap-secure-request-fn (fn token-owners-handler-fn [request] (token/handle-list-token-owners-request kv-store request)))) :token-refresh-handler-fn (pc/fnk [[:curator kv-store] wrap-router-auth-fn] (wrap-router-auth-fn (fn token-refresh-handler-fn [request] (token/handle-refresh-token-request kv-store request)))) :token-reindex-handler-fn (pc/fnk [[:curator kv-store] [:routines list-tokens-fn make-inter-router-requests-sync-fn synchronize-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn token-handler-fn [request] (token/handle-reindex-tokens-request synchronize-fn make-inter-router-requests-sync-fn kv-store list-tokens-fn request)))) :waiter-auth-handler-fn (pc/fnk [wrap-secure-request-fn] (wrap-secure-request-fn (fn waiter-auth-handler-fn [request] {:body (str (:authorization/user request)), :status 200}))) :waiter-acknowledge-consent-handler-fn (pc/fnk [[:routines service-description->service-id token->service-description-template token->token-metadata] [:settings consent-expiry-days] [:state clock passwords] wrap-secure-request-fn] (let [password (first passwords)] (letfn [(add-encoded-cookie [response cookie-name value expiry-days] (cookie-support/add-encoded-cookie response password cookie-name value expiry-days)) (consent-cookie-value [mode service-id token token-metadata] (sd/consent-cookie-value clock mode service-id token token-metadata))] (wrap-secure-request-fn (fn inner-waiter-acknowledge-consent-handler-fn [request] (handler/acknowledge-consent-handler token->service-description-template token->token-metadata service-description->service-id consent-cookie-value add-encoded-cookie consent-expiry-days request)))))) :waiter-request-consent-handler-fn (pc/fnk [[:routines service-description->service-id token->service-description-template] [:settings consent-expiry-days] wrap-secure-request-fn] (wrap-secure-request-fn (fn waiter-request-consent-handler-fn [request] (handler/request-consent-handler token->service-description-template service-description->service-id consent-expiry-days request)))) :waiter-request-interstitial-handler-fn (pc/fnk [wrap-secure-request-fn] (wrap-secure-request-fn (fn waiter-request-interstitial-handler-fn [request] (interstitial/display-interstitial-handler request)))) :welcome-handler-fn (pc/fnk [settings] (partial handler/welcome-handler settings)) :work-stealing-handler-fn (pc/fnk [[:state instance-rpc-chan] wrap-router-auth-fn] (wrap-router-auth-fn (fn [request] (handler/work-stealing-handler instance-rpc-chan request)))) :wrap-auth-bypass-fn (pc/fnk [] (fn wrap-auth-bypass-fn [handler] (fn [{:keys [waiter-discovery] :as request}] (let [{:keys [service-parameter-template token waiter-headers]} waiter-discovery {:strs [authentication] :as service-description} service-parameter-template authentication-disabled? (= authentication "disabled")] (cond (contains? waiter-headers "x-waiter-authentication") (do (log/info "x-waiter-authentication is not supported as an on-the-fly header" {:service-description service-description, :token token}) (utils/clj->json-response {:error "An authentication parameter is not supported for on-the-fly headers"} :status 400)) ;; ensure service description formed comes entirely from the token by ensuring absence of on-the-fly headers (and authentication-disabled? (some sd/service-parameter-keys (-> waiter-headers headers/drop-waiter-header-prefix keys))) (do (log/info "request cannot proceed as it is mixing an authentication disabled token with on-the-fly headers" {:service-description service-description, :token token}) (utils/clj->json-response {:error "An authentication disabled token may not be combined with on-the-fly headers"} :status 400)) authentication-disabled? (do (log/info "request configured to skip authentication") (handler (assoc request :skip-authentication true))) :else (handler request)))))) :wrap-descriptor-fn (pc/fnk [[:routines request->descriptor-fn start-new-service-fn] [:state fallback-state-atom]] (fn wrap-descriptor-fn [handler] (descriptor/wrap-descriptor handler request->descriptor-fn start-new-service-fn fallback-state-atom))) :wrap-https-redirect-fn (pc/fnk [] (fn wrap-https-redirect-fn [handler] (fn [request] (cond (and (get-in request [:waiter-discovery :token-metadata "https-redirect"]) ;; ignore websocket requests (= :http (utils/request->scheme request))) (do (log/info "triggering ssl redirect") (-> (ssl/ssl-redirect-response request {}) (rr/header "server" (utils/get-current-server-name)))) :else (handler request))))) :wrap-router-auth-fn (pc/fnk [[:state passwords router-id]] (fn wrap-router-auth-fn [handler] (fn [request] (let [router-comm-authenticated? (fn router-comm-authenticated? [source-id secret-word] (let [expected-word (utils/generate-secret-word source-id router-id passwords) authenticated? (= expected-word secret-word)] (log/info "Authenticating inter-router communication from" source-id) (if-not authenticated? (log/info "inter-router request authentication failed!" {:actual secret-word, :expected expected-word}) {:src-router-id source-id}))) basic-auth-handler (basic-authentication/wrap-basic-authentication handler router-comm-authenticated?)] (basic-auth-handler request))))) :wrap-secure-request-fn (pc/fnk [[:routines authentication-method-wrapper-fn waiter-request?-fn] [:settings cors-config] [:state cors-validator]] (let [{:keys [exposed-headers]} cors-config] (fn wrap-secure-request-fn [handler] (let [handler (-> handler (cors/wrap-cors-request cors-validator waiter-request?-fn exposed-headers) authentication-method-wrapper-fn)] (fn inner-wrap-secure-request-fn [{:keys [uri] :as request}] (log/debug "secure request received at" uri) (handler request)))))) :wrap-service-discovery-fn (pc/fnk [[:curator kv-store] [:settings [:token-config token-defaults]] [:state waiter-hostnames]] (fn wrap-service-discovery-fn [handler] (fn [{:keys [headers] :as request}] ;; TODO optimization opportunity to avoid this re-computation later in the chain (let [discovered-parameters (sd/discover-service-parameters kv-store token-defaults waiter-hostnames headers)] (handler (assoc request :waiter-discovery discovered-parameters))))))})
68118
;; ;; 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.core (:require [bidi.bidi :as bidi] [clj-time.core :as t] [clojure.core.async :as async] [clojure.java.io :as io] [clojure.set :as set] [clojure.string :as str] [clojure.tools.logging :as log] [digest] [full.async :refer (<?? <? go-try)] [metrics.core] [metrics.counters :as counters] [metrics.timers :as timers] [plumbing.core :as pc] [qbits.jet.client.http :as http] [ring.middleware.basic-authentication :as basic-authentication] [ring.middleware.ssl :as ssl] [ring.util.response :as rr] [slingshot.slingshot :refer [try+]] [waiter.async-request :as async-req] [waiter.auth.authentication :as auth] [waiter.authorization :as authz] [waiter.cookie-support :as cookie-support] [waiter.correlation-id :as cid] [waiter.cors :as cors] [waiter.curator :as curator] [waiter.descriptor :as descriptor] [waiter.discovery :as discovery] [waiter.handler :as handler] [waiter.headers :as headers] [waiter.interstitial :as interstitial] [waiter.kv :as kv] [waiter.metrics :as metrics] [waiter.metrics-sync :as metrics-sync] [waiter.password-store :as password-store] [waiter.process-request :as pr] [waiter.reporter :as reporter] [waiter.scaling :as scaling] [waiter.scheduler :as scheduler] [waiter.service :as service] [waiter.service-description :as sd] [waiter.settings :as settings] [waiter.simulator :as simulator] [waiter.state :as state] [waiter.statsd :as statsd] [waiter.token :as token] [waiter.util.async-utils :as au] [waiter.util.cache-utils :as cu] [waiter.util.date-utils :as du] [waiter.util.http-utils :as http-utils] [waiter.util.ring-utils :as ru] [waiter.util.utils :as utils] [waiter.websocket :as ws] [waiter.work-stealing :as work-stealing]) (:import (java.net InetAddress URI) java.util.concurrent.Executors (javax.servlet ServletRequest) org.apache.curator.framework.CuratorFrameworkFactory org.apache.curator.framework.api.CuratorEventType org.apache.curator.framework.api.CuratorListener org.apache.curator.framework.recipes.leader.LeaderLatch org.apache.curator.retry.BoundedExponentialBackoffRetry org.eclipse.jetty.client.HttpClient org.eclipse.jetty.client.util.BasicAuthentication$BasicResult org.eclipse.jetty.websocket.client.WebSocketClient (org.eclipse.jetty.websocket.servlet ServletUpgradeResponse ServletUpgradeRequest))) (defn routes-mapper "Returns a map containing a keyword handler and the parsed route-params based on the request uri." ;; Please include/update a corresponding unit test anytime the routes data structure is modified [{:keys [uri]}] (let [routes ["/" {"" :welcome-handler-fn "app-name" :app-name-handler-fn "apps" {"" :service-list-handler-fn ["/" :service-id] :service-handler-fn ["/" :service-id "/logs"] :service-view-logs-handler-fn ["/" :service-id "/override"] :service-override-handler-fn ["/" :service-id "/refresh"] :service-refresh-handler-fn ["/" :service-id "/resume"] :service-resume-handler-fn ["/" :service-id "/suspend"] :service-suspend-handler-fn} "blacklist" {"" :blacklist-instance-handler-fn ["/" :service-id] :blacklisted-instances-list-handler-fn} "favicon.ico" :favicon-handler-fn "metrics" :metrics-request-handler-fn "service-id" :service-id-handler-fn "settings" :display-settings-handler-fn "sim" :sim-request-handler "state" [["" :state-all-handler-fn] ["/autoscaler" :state-autoscaler-handler-fn] ["/autoscaling-multiplexer" :state-autoscaling-multiplexer-handler-fn] ["/codahale-reporters" :state-codahale-reporters-handler-fn] ["/fallback" :state-fallback-handler-fn] ["/gc-broken-services" :state-gc-for-broken-services] ["/gc-services" :state-gc-for-services] ["/gc-transient-metrics" :state-gc-for-transient-metrics] ["/interstitial" :state-interstitial-handler-fn] ["/launch-metrics" :state-launch-metrics-handler-fn] ["/kv-store" :state-kv-store-handler-fn] ["/leader" :state-leader-handler-fn] ["/local-usage" :state-local-usage-handler-fn] ["/maintainer" :state-maintainer-handler-fn] ["/router-metrics" :state-router-metrics-handler-fn] ["/scheduler" :state-scheduler-handler-fn] ["/statsd" :state-statsd-handler-fn] [["/" :service-id] :state-service-handler-fn]] "status" :status-handler-fn "token" :token-handler-fn "tokens" {"" :token-list-handler-fn "/owners" :token-owners-handler-fn "/refresh" :token-refresh-handler-fn "/reindex" :token-reindex-handler-fn} "waiter-async" {["/complete/" :request-id "/" :service-id] :async-complete-handler-fn ["/result/" :request-id "/" :router-id "/" :service-id "/" :host "/" :port "/" [#".+" :location]] :async-result-handler-fn ["/status/" :request-id "/" :router-id "/" :service-id "/" :host "/" :port "/" [#".+" :location]] :async-status-handler-fn} "waiter-auth" :waiter-auth-handler-fn "waiter-consent" {"" :waiter-acknowledge-consent-handler-fn ["/" [#".*" :path]] :waiter-request-consent-handler-fn} "waiter-interstitial" {["/" [#".*" :path]] :waiter-request-interstitial-handler-fn} "waiter-kill-instance" {["/" :service-id] :kill-instance-handler-fn} "work-stealing" :work-stealing-handler-fn}]] (or (bidi/match-route routes uri) {:handler :not-found-handler-fn}))) (defn ring-handler-factory "Creates the handler for processing http requests." [waiter-request?-fn {:keys [process-request-fn] :as handlers}] (fn http-handler [{:keys [uri] :as request}] (if-not (waiter-request?-fn request) (do (counters/inc! (metrics/waiter-counter "requests" "service-request")) (process-request-fn request)) (let [{:keys [handler route-params]} (routes-mapper request) request (assoc request :route-params (or route-params {})) handler-fn (get handlers handler process-request-fn)] (when (and (not= handler :process-request-fn) (= handler-fn process-request-fn)) (log/warn "using default handler as no mapping found for" handler "at uri" uri)) (when handler (counters/inc! (metrics/waiter-counter "requests" (name handler)))) (handler-fn request))))) (defn websocket-handler-factory "Creates the handler for processing websocket requests. Websockets are currently used for inter-router metrics syncing." [{:keys [default-websocket-handler-fn router-metrics-handler-fn]}] (fn websocket-handler [{:keys [uri] :as request}] (case uri "/waiter-router-metrics" (router-metrics-handler-fn request) (default-websocket-handler-fn request)))) (defn correlation-id-middleware "Attaches an x-cid header to the request and response if one is not already provided." [handler] (fn correlation-id-middleware-fn [request] (let [request (cid/ensure-correlation-id request utils/unique-identifier) request-cid (cid/http-object->correlation-id request)] (cid/with-correlation-id request-cid (log/info "request received:" (-> (dissoc request :body :ctrl :in :out :request-time :server-name :server-port :servlet-request :ssl-client-cert :support-info :trailers-fn) (update :headers headers/truncate-header-values))) (let [response (handler request) get-request-cid (fn get-request-cid [] request-cid)] (if (map? response) (cid/ensure-correlation-id response get-request-cid) (async/go (let [nested-response (async/<! response)] (if (map? nested-response) ;; websocket responses may be another channel (cid/ensure-correlation-id nested-response get-request-cid) nested-response))))))))) (defn request->protocol "Determines the protocol and version used by the request. For HTTP requests, it returns values like HTTP/1.0, HTTP/1.1, HTTP/2. For WebSocket requests, it returns values like WS/8, WS/13." [{:keys [headers scheme ^ServletRequest servlet-request]}] (if servlet-request (or (some-> headers (get "x-forwarded-proto-version") str/upper-case) (.getProtocol servlet-request)) (when scheme (str/upper-case ;; currently, only websockets need this branch to determine version (if-let [version (get headers "sec-websocket-version")] (str (name scheme) "/" version) (name scheme)))))) (defn wrap-request-info "Attaches request info to the request." [handler router-id support-info] (fn wrap-request-info-fn [{:keys [servlet-request] :as request}] (-> request (assoc :client-protocol (request->protocol request) :internal-protocol (some-> servlet-request .getProtocol) :request-id (str (utils/unique-identifier) "-" (-> request utils/request->scheme name)) :request-time (t/now) :router-id router-id :support-info support-info) handler))) (defn wrap-debug "Attaches debugging headers to requests when enabled." [handler generate-log-url-fn] (fn wrap-debug-fn [{:keys [request-id request-time router-id] :as request}] (if (utils/request->debug-enabled? request) (let [response (handler request) add-headers (fn [{:keys [descriptor instance] :as response}] (let [{:strs [backend-proto]} (:service-description descriptor) backend-directory (:log-directory instance) backend-log-url (when backend-directory (generate-log-url-fn instance)) request-date (when request-time (du/date-to-str request-time du/formatter-rfc822))] (update response :headers (fn [headers] (cond-> headers request-time (assoc "x-waiter-request-date" request-date) request-id (assoc "x-waiter-request-id" request-id) router-id (assoc "x-waiter-router-id" router-id) descriptor (assoc "x-waiter-service-id" (:service-id descriptor)) instance (assoc "x-waiter-backend-id" (:id instance) "x-waiter-backend-host" (:host instance) "x-waiter-backend-port" (str (:port instance)) "x-waiter-backend-proto" backend-proto) backend-directory (assoc "x-waiter-backend-directory" backend-directory "x-waiter-backend-log-url" backend-log-url))))))] (ru/update-response response add-headers)) (handler request)))) (defn wrap-error-handling "Catches any uncaught exceptions and returns an error response." [handler] (fn wrap-error-handling-fn [request] (try (let [response (handler request)] (if (au/chan? response) (async/go (try (<? response) (catch Exception e (utils/exception->response e request)))) response)) (catch Exception e (utils/exception->response e request))))) (defn- make-blacklist-request [make-inter-router-requests-fn blacklist-period-ms dest-router-id dest-endpoint {:keys [id] :as instance} reason] (log/info "peer communication requesting" dest-router-id "to blacklist" id "via endpoint" dest-endpoint) (try (-> (make-inter-router-requests-fn dest-endpoint :acceptable-router? #(= dest-router-id %) :body (utils/clj->json {:instance instance :period-in-ms blacklist-period-ms :reason reason}) :method :post) (get dest-router-id)) (catch Exception e (log/error e "error in making blacklist request" {:instance instance :period-in-ms blacklist-period-ms :reason reason})))) (defn peers-acknowledged-blacklist-requests? "Note that the ids used in here are internal ids generated by the curator api." [{:keys [id] :as instance} short-circuit? router-ids endpoint make-blacklist-request-fn reason] (if (seq router-ids) (loop [[dest-router-id & remaining-peer-ids] (seq router-ids) blacklist-successful? true] (log/info {:dest-id dest-router-id, :blacklist-successful? blacklist-successful?}, :reason reason) (let [response (make-blacklist-request-fn dest-router-id endpoint instance reason) response-successful? (= 200 (:status response)) blacklist-successful? (and blacklist-successful? response-successful?)] (when (and short-circuit? (not response-successful?)) (log/info "peer communication" dest-router-id "veto-ed killing of" id {:http-status (:status response)})) (when (and short-circuit? response-successful?) (log/info "peer communication" dest-router-id "approves killing of" id)) (if (and remaining-peer-ids (or (not short-circuit?) response-successful?)) (recur remaining-peer-ids blacklist-successful?) blacklist-successful?))) (do (log/warn "no peer routers found to acknowledge blacklist request!") true))) (defn make-kill-instance-request "Makes a request to a peer router to kill an instance of a service." [make-inter-router-requests-fn service-id dest-router-id kill-instance-endpoint] (log/info "peer communication requesting" dest-router-id "to kill an instance of" service-id "via endpoint" kill-instance-endpoint) (try (-> (make-inter-router-requests-fn kill-instance-endpoint :acceptable-router? #(= dest-router-id %) :method :post) (get dest-router-id)) (catch Exception e (log/error e "error in killing instance of" service-id)))) (defn delegate-instance-kill-request "Delegates requests to kill an instance of a service to peer routers." [service-id router-ids make-kill-instance-request-fn] (if (not-empty router-ids) (loop [[dest-router-id & remaining-router-ids] (seq router-ids)] (let [dest-endpoint (str "waiter-kill-instance/" service-id) {:keys [body status]} (make-kill-instance-request-fn dest-router-id dest-endpoint) kill-successful? (= 200 status)] (when kill-successful? (log/info "peer communication" dest-router-id "killed instance of" service-id body)) (if (and remaining-router-ids (not kill-successful?)) (recur remaining-router-ids) kill-successful?))) (do (log/warn "no peer routers found! Unable to delegate call to kill instance of" service-id) false))) (defn service-gc-go-routine "Go-routine that performs GC of services. Only the leader gets to perform the GC operations. Other routers keep looping waiting for their turn to become a leader. Parameters: `read-state-fn`: (fn [name] ...) used to read the current state. `write-state-fn`: (fn [name state] ...) used to write the current state which potentially is used by the read. `leader?`: Returns true if the router is currently the leader, only the leader writes state into persistent store at `(str base-path '/' gc-relative-path '/' name`. `clock` (fn [] ...) returns the current time. `name`: Name of the go-routine. `service->raw-data-source`: A channel or a no-args function which produces service data. `timeout-interval-ms`: Timeout interval used as a refractory period while listening for data from `service-data-mult-chan` to allow effects of any GC run to propagate through the system. `in-exit-chan`: The exit signal channel. `sanitize-state-fn`: (fn [prev-service->state cur-services] ...). Sanitizes the previous state based on services available currently. `service->state-fn`: (fn [service cur-state data] ...). Transforms `data` into state to be used by the gc-service? function. `gc-service?`: (fn [service {:keys [state last-modified-time]} cur-time] ...). Predicate function that returns true for apps that need to be gc-ed. `perform-gc-fn`: (fn [service] ...). Function that performs GC of the service. It must return a truth-y value when successful." [read-state-fn write-state-fn leader? clock name service->raw-data-source timeout-interval-ms sanitize-state-fn service->state-fn gc-service? perform-gc-fn] {:pre (pos? timeout-interval-ms)} (let [query-chan (async/chan 10) state-cache (cu/cache-factory {:ttl (/ timeout-interval-ms 2)}) query-state-fn (fn query-state-fn [] (cu/cache-get-or-load state-cache name #(read-state-fn name))) query-service-state-fn (fn query-service-state-fn [{:keys [service-id]}] (-> (query-state-fn) (get service-id) (or {}))) exit-chan (async/chan 1)] (cid/with-correlation-id name (async/go-loop [iter 0 timeout-chan (async/timeout timeout-interval-ms)] (let [[chan args] (async/alt! exit-chan ([_] [:exit]) query-chan ([args] [:query args]) timeout-chan ([_] [:continue]) :priority true)] (case chan :exit (log/info "[service-gc-go-routine] exiting" name) :query (let [{:keys [response-chan]} args state (query-service-state-fn args)] (async/>! response-chan (or state {})) (recur (inc iter) timeout-chan)) :continue (do (when (leader?) (let [service->raw-data (if (fn? service->raw-data-source) (service->raw-data-source) (async/<! service->raw-data-source))] (timers/start-stop-time! (metrics/waiter-timer "gc" name "iteration-duration") (try (let [service->state (or (read-state-fn name) {}) current-time (clock) service->state' (apply merge (sanitize-state-fn service->state (keys service->raw-data)) (map (fn [[service raw-data]] (let [cur-state (get service->state service) new-state (service->state-fn service (:state cur-state) raw-data)] (if (= (:state cur-state) new-state) [service cur-state] [service {:state new-state :last-modified-time current-time}]))) service->raw-data)) apps-to-gc (map first (filter (fn [[service state]] (when-let [gc-service (gc-service? service state current-time)] (log/info service "with state" (:state state) "and last modified time" (du/date-to-str (:last-modified-time state)) "marked for deletion") gc-service)) service->state')) apps-successfully-gced (filter (fn [service] (try (when (leader?) ; check to ensure still the leader (perform-gc-fn service)) (catch Exception e (log/error e "error in deleting:" service)))) apps-to-gc) apps-failed-to-delete (apply disj (set apps-to-gc) apps-successfully-gced) service->state'' (apply dissoc service->state' apps-successfully-gced)] (when (or (not= (set (keys service->state'')) (set (keys service->raw-data))) (not= (set (keys service->state'')) (set (keys service->state)))) (log/info "state has" (count service->state'') "active services, received" (count service->raw-data) "services in latest update.")) (when (not-empty apps-failed-to-delete) (log/warn "unable to delete services:" apps-failed-to-delete)) (write-state-fn name service->state'') (cu/cache-evict state-cache name)) (catch Exception e (log/error e "error in" name {:iteration iter})))))) (recur (inc iter) (async/timeout timeout-interval-ms))))))) {:exit exit-chan :query query-chan :query-service-state-fn query-service-state-fn :query-state-fn query-state-fn})) (defn make-inter-router-requests "Helper function to make inter-router requests with basic authentication. It assumes that the response from inter-router communication always supports json." [make-request-fn make-basic-auth-fn my-router-id discovery passwords endpoint & {:keys [acceptable-router? body config method] :or {acceptable-router? (constantly true) body "" config {} method :get}}] (let [router-id->endpoint-url (discovery/router-id->endpoint-url discovery "http" endpoint :exclude-set #{my-router-id}) router-id->endpoint-url' (filter (fn [[router-id _]] (acceptable-router? router-id)) router-id->endpoint-url) request-config (update config :headers (fn prepare-inter-router-requests-headers [headers] (-> headers (assoc "accept" "application/json") (update "x-cid" (fn attach-inter-router-cid [provided-cid] (or provided-cid (let [current-cid (cid/get-correlation-id) cid-prefix (if (or (nil? current-cid) (= cid/default-correlation-id current-cid)) "waiter" current-cid)] (str cid-prefix "." (utils/unique-identifier)))))))))] (when (and (empty? router-id->endpoint-url') (not-empty router-id->endpoint-url)) (log/info "no acceptable routers found to make request!")) (loop [[[dest-router-id endpoint-url] & remaining-items] router-id->endpoint-url' router-id->response {}] (if dest-router-id (let [secret-word (utils/generate-secret-word my-router-id dest-router-id passwords) auth (make-basic-auth-fn endpoint-url my-router-id secret-word) response (make-request-fn method endpoint-url auth body request-config)] (recur remaining-items (assoc router-id->response dest-router-id response))) router-id->response)))) (defn make-request-async "Makes an asynchronous request to the endpoint using the provided authentication scheme. Returns a core.async channel that will return the response map." [http-client idle-timeout method endpoint-url auth body config] (http/request http-client (merge {:auth auth :body body :follow-redirects? false :idle-timeout idle-timeout :method method :url endpoint-url} config))) (defn make-request-sync "Makes a synchronous request to the endpoint using the provided authentication scheme. Returns a response map with the body, status and headers populated." [http-client idle-timeout method endpoint-url auth body config] (let [resp-chan (make-request-async http-client idle-timeout method endpoint-url auth body config) {:keys [body error] :as response} (async/<!! resp-chan)] (if error (log/error error "Error in communicating at" endpoint-url) (let [body-response (async/<!! body)] ;; response has been read, close as we do not use chunked encoding in inter-router (async/close! body) (assoc response :body body-response))))) (defn waiter-request?-factory "Creates a function that determines for a given request whether or not the request is intended for Waiter itself or a service of Waiter." [valid-waiter-hostnames] (let [valid-waiter-hostnames (set/union valid-waiter-hostnames #{"localhost" "127.0.0.1"})] (fn waiter-request? [{:keys [uri headers]}] (let [{:strs [host]} headers] (or (#{"/app-name" "/service-id" "/token"} uri) ; special urls that are always for Waiter (FIXME) (some #(str/starts-with? (str uri) %) ["/waiter-async/complete/" "/waiter-async/result/" "/waiter-async/status/" "/waiter-consent" "/waiter-interstitial"]) (and (or (str/blank? host) (valid-waiter-hostnames (-> host (str/split #":") first))) (not-any? #(str/starts-with? (key %) headers/waiter-header-prefix) (remove #(= "x-waiter-debug" (key %)) headers)))))))) (defn leader-fn-factory "Creates the leader? function. Leadership is decided by the leader latch and presence of at least `min-cluster-routers` peers." [router-id has-leadership? discovery min-cluster-routers] #(and (has-leadership?) ; no one gets to be the leader if there aren't at least min-cluster-routers in the clique (let [num-routers (discovery/cluster-size discovery)] (when (< num-routers min-cluster-routers) (log/info router-id "relinquishing leadership as there are too few routers in cluster:" num-routers)) (>= num-routers min-cluster-routers)))) ;; PRIVATE API (def state {:async-request-store-atom (pc/fnk [] (atom {})) :authenticator (pc/fnk [[:settings authenticator-config] passwords] (utils/create-component authenticator-config :context {:password (first passwords)})) :clock (pc/fnk [] t/now) :cors-validator (pc/fnk [[:settings cors-config]] (utils/create-component cors-config)) :entitlement-manager (pc/fnk [[:settings entitlement-config]] (utils/create-component entitlement-config)) :fallback-state-atom (pc/fnk [] (atom {:available-service-ids #{} :healthy-service-ids #{}})) :http-clients (pc/fnk [[:settings [:instance-request-properties connection-timeout-ms]] server-name] (http-utils/prepare-http-clients {:conn-timeout connection-timeout-ms :follow-redirects? false :user-agent server-name})) :instance-rpc-chan (pc/fnk [] (async/chan 1024)) ; TODO move to service-chan-maintainer :interstitial-state-atom (pc/fnk [] (atom {:initialized? false :service-id->interstitial-promise {}})) :local-usage-agent (pc/fnk [] (agent {})) :passwords (pc/fnk [[:settings password-store-config]] (let [password-provider (utils/create-component password-store-config) passwords (password-store/retrieve-passwords password-provider) _ (password-store/check-empty-passwords passwords) processed-passwords (mapv #(vector :cached %) passwords)] processed-passwords)) :query-service-maintainer-chan (pc/fnk [] (au/latest-chan)) ; TODO move to service-chan-maintainer :router-metrics-agent (pc/fnk [router-id] (metrics-sync/new-router-metrics-agent router-id {})) :router-id (pc/fnk [[:settings router-id-prefix]] (cond->> (utils/unique-identifier) (not (str/blank? router-id-prefix)) (str (str/replace router-id-prefix #"[@.]" "-") "-"))) :scaling-timeout-config (pc/fnk [[:settings [:blacklist-config blacklist-backoff-base-time-ms max-blacklist-time-ms] [:scaling inter-kill-request-wait-time-ms]]] {:blacklist-backoff-base-time-ms blacklist-backoff-base-time-ms :inter-kill-request-wait-time-ms inter-kill-request-wait-time-ms :max-blacklist-time-ms max-blacklist-time-ms}) :scheduler-interactions-thread-pool (pc/fnk [] (Executors/newFixedThreadPool 20)) :scheduler-state-chan (pc/fnk [] (au/latest-chan)) :server-name (pc/fnk [[:settings git-version]] (let [server-name (str "waiter/" (str/join (take 7 git-version)))] (utils/reset-server-name-atom! server-name) server-name)) :service-description-builder (pc/fnk [[:settings service-description-builder-config service-description-constraints]] (when-let [unknown-keys (-> service-description-constraints keys set (set/difference sd/service-parameter-keys) seq)] (throw (ex-info "Unsupported keys present in the service description constraints" {:service-description-constraints service-description-constraints :unsupported-keys (-> unknown-keys vec sort)}))) (utils/create-component service-description-builder-config :context {:constraints service-description-constraints})) :service-id-prefix (pc/fnk [[:settings [:cluster-config service-prefix]]] service-prefix) :start-service-cache (pc/fnk [] (cu/cache-factory {:threshold 100 :ttl (-> 1 t/minutes t/in-millis)})) :token-cluster-calculator (pc/fnk [[:settings [:cluster-config name] [:token-config cluster-calculator]]] (utils/create-component cluster-calculator :context {:default-cluster name})) :token-root (pc/fnk [[:settings [:cluster-config name]]] name) :waiter-hostnames (pc/fnk [[:settings hostname]] (set (if (sequential? hostname) hostname [hostname]))) :websocket-client (pc/fnk [[:settings [:websocket-config ws-max-binary-message-size ws-max-text-message-size]] http-clients] (let [http-client (http-utils/select-http-client "http" http-clients) websocket-client (WebSocketClient. ^HttpClient http-client)] (doto (.getPolicy websocket-client) (.setMaxBinaryMessageSize ws-max-binary-message-size) (.setMaxTextMessageSize ws-max-text-message-size)) websocket-client))}) (def curator {:curator (pc/fnk [[:settings [:zookeeper [:curator-retry-policy base-sleep-time-ms max-retries max-sleep-time-ms] connect-string]]] (let [retry-policy (BoundedExponentialBackoffRetry. base-sleep-time-ms max-sleep-time-ms max-retries) zk-connection-string (if (= :in-process connect-string) (:zk-connection-string (curator/start-in-process-zookeeper)) connect-string) curator (CuratorFrameworkFactory/newClient zk-connection-string 5000 5000 retry-policy)] (.start curator) ; register listener that notifies of sync call completions (.addListener (.getCuratorListenable curator) (reify CuratorListener (eventReceived [_ _ event] (when (= CuratorEventType/SYNC (.getType event)) (log/info "received SYNC event for" (.getPath event)) (when-let [response-promise (.getContext event)] (log/info "releasing response promise provided for" (.getPath event)) (deliver response-promise :release)))))) curator)) :curator-base-init (pc/fnk [curator [:settings [:zookeeper base-path]]] (curator/create-path curator base-path :create-parent-zknodes? true)) :discovery (pc/fnk [[:settings [:cluster-config name] [:zookeeper base-path discovery-relative-path] host port] [:state router-id] curator] (discovery/register router-id curator name (str base-path "/" discovery-relative-path) {:host host :port port})) :gc-base-path (pc/fnk [[:settings [:zookeeper base-path gc-relative-path]]] (str base-path "/" gc-relative-path)) :gc-state-reader-fn (pc/fnk [curator gc-base-path] (fn read-gc-state [name] (:data (curator/read-path curator (str gc-base-path "/" name) :nil-on-missing? true :serializer :nippy)))) :gc-state-writer-fn (pc/fnk [curator gc-base-path] (fn write-gc-state [name state] (curator/write-path curator (str gc-base-path "/" name) state :serializer :nippy :create-parent-zknodes? true))) :kv-store (pc/fnk [[:settings [:zookeeper base-path] kv-config] [:state passwords] curator] (kv/new-kv-store kv-config curator base-path passwords)) :leader?-fn (pc/fnk [[:settings [:cluster-config min-routers]] [:state router-id] discovery leader-latch] (let [has-leadership? #(.hasLeadership leader-latch)] (leader-fn-factory router-id has-leadership? discovery min-routers))) :leader-id-fn (pc/fnk [leader-latch] #(try (-> leader-latch .getLeader .getId) (catch Exception ex (log/error ex "unable to retrieve leader id")))) :leader-latch (pc/fnk [[:settings [:zookeeper base-path leader-latch-relative-path]] [:state router-id] curator] (let [leader-latch-path (str base-path "/" leader-latch-relative-path) latch (LeaderLatch. curator leader-latch-path router-id)] (.start latch) latch))}) (def scheduler {:scheduler (pc/fnk [[:curator leader?-fn] [:settings scheduler-config scheduler-syncer-interval-secs] [:state scheduler-state-chan service-id-prefix] service-id->password-fn* service-id->service-description-fn* start-scheduler-syncer-fn] (let [is-waiter-service?-fn (fn is-waiter-service? [^String service-id] (str/starts-with? service-id service-id-prefix)) scheduler-context {:is-waiter-service?-fn is-waiter-service?-fn :leader?-fn leader?-fn :scheduler-name (-> scheduler-config :kind utils/keyword->str) :scheduler-state-chan scheduler-state-chan ;; TODO scheduler-syncer-interval-secs should be inside the scheduler's config :scheduler-syncer-interval-secs scheduler-syncer-interval-secs :service-id->password-fn service-id->password-fn* :service-id->service-description-fn service-id->service-description-fn* :start-scheduler-syncer-fn start-scheduler-syncer-fn}] (utils/create-component scheduler-config :context scheduler-context))) ; This function is only included here for initializing the scheduler above. ; Prefer accessing the non-starred version of this function through the routines map. :service-id->password-fn* (pc/fnk [[:state passwords]] (fn service-id->password [service-id] (log/debug "generating password for" service-id) (digest/md5 (str service-id (first passwords))))) ; This function is only included here for initializing the scheduler above. ; Prefer accessing the non-starred version of this function through the routines map. :service-id->service-description-fn* (pc/fnk [[:curator kv-store] [:settings service-description-defaults metric-group-mappings]] (fn service-id->service-description [service-id & {:keys [effective?] :or {effective? true}}] (sd/service-id->service-description kv-store service-id service-description-defaults metric-group-mappings :effective? effective?))) :start-scheduler-syncer-fn (pc/fnk [[:settings [:health-check-config health-check-timeout-ms failed-check-threshold] git-version] [:state clock] service-id->service-description-fn*] (let [http-client (http-utils/http-client-factory {:conn-timeout health-check-timeout-ms :socket-timeout health-check-timeout-ms :user-agent (str "waiter-syncer/" (str/join (take 7 git-version)))}) available? (fn scheduler-available? [scheduler-name service-instance health-check-proto health-check-port-index health-check-path] (scheduler/available? http-client scheduler-name service-instance health-check-proto health-check-port-index health-check-path))] (fn start-scheduler-syncer-fn [scheduler-name get-service->instances-fn scheduler-state-chan scheduler-syncer-interval-secs] (let [timeout-chan (->> (t/seconds scheduler-syncer-interval-secs) (du/time-seq (t/now)) chime/chime-ch)] (scheduler/start-scheduler-syncer clock timeout-chan service-id->service-description-fn* available? failed-check-threshold scheduler-name get-service->instances-fn scheduler-state-chan)))))}) (def routines {:allowed-to-manage-service?-fn (pc/fnk [[:curator kv-store] [:state entitlement-manager]] (fn allowed-to-manage-service? [service-id auth-user] ; Returns whether the authenticated user is allowed to manage the service. ; Either she can run as the waiter user or the run-as-user of the service description." (sd/can-manage-service? kv-store entitlement-manager service-id auth-user))) :assoc-run-as-user-approved? (pc/fnk [[:settings consent-expiry-days] [:state clock passwords] token->token-metadata] (fn assoc-run-as-user-approved? [{:keys [headers]} service-id] (let [{:strs [cookie host]} headers token (when-not (headers/contains-waiter-header headers sd/on-the-fly-service-description-keys) (utils/authority->host host)) token-metadata (when token (token->token-metadata token)) service-consent-cookie (cookie-support/cookie-value cookie "x-waiter-consent") decoded-cookie (when service-consent-cookie (some #(cookie-support/decode-cookie-cached service-consent-cookie %1) passwords))] (sd/assoc-run-as-user-approved? clock consent-expiry-days service-id token token-metadata decoded-cookie)))) :async-request-terminate-fn (pc/fnk [[:state async-request-store-atom]] (fn async-request-terminate [request-id] (async-req/async-request-terminate async-request-store-atom request-id))) :async-trigger-terminate-fn (pc/fnk [[:state router-id] async-request-terminate-fn make-inter-router-requests-sync-fn] (fn async-trigger-terminate-fn [target-router-id service-id request-id] (async-req/async-trigger-terminate async-request-terminate-fn make-inter-router-requests-sync-fn router-id target-router-id service-id request-id))) :authentication-method-wrapper-fn (pc/fnk [[:state authenticator]] (fn authentication-method-wrapper [request-handler] (let [auth-handler (auth/wrap-auth-handler authenticator request-handler)] (fn authenticate-request [request] (if (:skip-authentication request) (do (log/info "skipping authentication for request") (request-handler request)) (auth-handler request)))))) :can-run-as?-fn (pc/fnk [[:state entitlement-manager]] (fn can-run-as [auth-user run-as-user] (authz/run-as? entitlement-manager auth-user run-as-user))) :crypt-helpers (pc/fnk [[:state passwords]] (let [password (first passwords)] {:bytes-decryptor (fn bytes-decryptor [data] (utils/compressed-bytes->map data password)) :bytes-encryptor (fn bytes-encryptor [data] (utils/map->compressed-bytes data password))})) :delegate-instance-kill-request-fn (pc/fnk [[:curator discovery] [:state router-id] make-inter-router-requests-sync-fn] (fn delegate-instance-kill-request-fn [service-id] (delegate-instance-kill-request service-id (discovery/router-ids discovery :exclude-set #{router-id}) (partial make-kill-instance-request make-inter-router-requests-sync-fn service-id)))) :determine-priority-fn (pc/fnk [] (let [position-generator-atom (atom 0)] (fn determine-priority-fn [waiter-headers] (pr/determine-priority position-generator-atom waiter-headers)))) :generate-log-url-fn (pc/fnk [prepend-waiter-url] (partial handler/generate-log-url prepend-waiter-url)) :list-tokens-fn (pc/fnk [[:curator curator] [:settings [:zookeeper base-path] kv-config]] (fn list-tokens-fn [] (let [{:keys [relative-path]} kv-config] (->> (kv/zk-keys curator (str base-path "/" relative-path)) (filter (fn [k] (not (str/starts-with? k "^")))))))) :make-basic-auth-fn (pc/fnk [] (fn make-basic-auth-fn [uri username password] (BasicAuthentication$BasicResult. (URI. uri) username password))) :make-http-request-fn (pc/fnk [[:settings instance-request-properties] [:state http-clients] make-basic-auth-fn service-id->password-fn] (handler/async-make-request-helper http-clients instance-request-properties make-basic-auth-fn service-id->password-fn pr/prepare-request-properties pr/make-request)) :make-inter-router-requests-async-fn (pc/fnk [[:curator discovery] [:settings [:instance-request-properties initial-socket-timeout-ms]] [:state http-clients passwords router-id] make-basic-auth-fn] (let [http-client (http-utils/select-http-client "http" http-clients) make-request-async-fn (fn make-request-async-fn [method endpoint-url auth body config] (make-request-async http-client initial-socket-timeout-ms method endpoint-url auth body config))] (fn make-inter-router-requests-async-fn [endpoint & args] (apply make-inter-router-requests make-request-async-fn make-basic-auth-fn router-id discovery passwords endpoint args)))) :make-inter-router-requests-sync-fn (pc/fnk [[:curator discovery] [:settings [:instance-request-properties initial-socket-timeout-ms]] [:state http-clients passwords router-id] make-basic-auth-fn] (let [http-client (http-utils/select-http-client "http" http-clients) make-request-sync-fn (fn make-request-sync-fn [method endpoint-url auth body config] (make-request-sync http-client initial-socket-timeout-ms method endpoint-url auth body config))] (fn make-inter-router-requests-sync-fn [endpoint & args] (apply make-inter-router-requests make-request-sync-fn make-basic-auth-fn router-id discovery passwords endpoint args)))) :peers-acknowledged-blacklist-requests-fn (pc/fnk [[:curator discovery] [:state router-id] make-inter-router-requests-sync-fn] (fn peers-acknowledged-blacklist-requests [instance short-circuit? blacklist-period-ms reason] (let [router-ids (discovery/router-ids discovery :exclude-set #{router-id})] (peers-acknowledged-blacklist-requests? instance short-circuit? router-ids "blacklist" (partial make-blacklist-request make-inter-router-requests-sync-fn blacklist-period-ms) reason)))) :post-process-async-request-response-fn (pc/fnk [[:state async-request-store-atom instance-rpc-chan router-id] make-http-request-fn] (fn post-process-async-request-response-wrapper [response service-id metric-group backend-proto instance _ reason-map request-properties location query-string] (async-req/post-process-async-request-response router-id async-request-store-atom make-http-request-fn instance-rpc-chan response service-id metric-group backend-proto instance reason-map request-properties location query-string))) :prepend-waiter-url (pc/fnk [[:settings port hostname]] (let [hostname (if (sequential? hostname) (first hostname) hostname)] (fn [endpoint-url] (if (str/blank? endpoint-url) endpoint-url (str "http://" hostname ":" port endpoint-url))))) :refresh-service-descriptions-fn (pc/fnk [[:curator kv-store]] (fn refresh-service-descriptions-fn [service-ids] (sd/refresh-service-descriptions kv-store service-ids))) :request->descriptor-fn (pc/fnk [[:curator kv-store] [:settings [:token-config history-length token-defaults] metric-group-mappings service-description-defaults] [:state fallback-state-atom service-description-builder service-id-prefix waiter-hostnames] assoc-run-as-user-approved? can-run-as?-fn store-source-tokens-fn] (fn request->descriptor-fn [request] (let [{:keys [latest-descriptor] :as result} (descriptor/request->descriptor assoc-run-as-user-approved? can-run-as?-fn fallback-state-atom kv-store metric-group-mappings history-length service-description-builder service-description-defaults service-id-prefix token-defaults waiter-hostnames request)] (when-let [source-tokens (-> latest-descriptor :source-tokens seq)] (store-source-tokens-fn (:service-id latest-descriptor) source-tokens)) result))) :router-metrics-helpers (pc/fnk [[:state passwords router-metrics-agent]] (let [password (first passwords)] {:decryptor (fn router-metrics-decryptor [data] (utils/compressed-bytes->map data password)) :encryptor (fn router-metrics-encryptor [data] (utils/map->compressed-bytes data password)) :router-metrics-state-fn (fn router-metrics-state [] @router-metrics-agent) :service-id->metrics-fn (fn service-id->metrics [] (metrics-sync/agent->service-id->metrics router-metrics-agent)) :service-id->router-id->metrics (fn service-id->router-id->metrics [service-id] (metrics-sync/agent->service-id->router-id->metrics router-metrics-agent service-id))})) :service-description->service-id (pc/fnk [[:state service-id-prefix]] (fn service-description->service-id [service-description] (sd/service-description->service-id service-id-prefix service-description))) :service-id->idle-timeout (pc/fnk [[:settings [:token-config token-defaults]] service-id->service-description-fn service-id->source-tokens-entries-fn token->token-hash token->token-metadata] (fn service-id->idle-timeout [service-id] (sd/service-id->idle-timeout service-id->service-description-fn service-id->source-tokens-entries-fn token->token-hash token->token-metadata token-defaults service-id))) :service-id->password-fn (pc/fnk [[:scheduler service-id->password-fn*]] service-id->password-fn*) :service-id->service-description-fn (pc/fnk [[:scheduler service-id->service-description-fn*]] service-id->service-description-fn*) :service-id->source-tokens-entries-fn (pc/fnk [[:curator kv-store]] (partial sd/service-id->source-tokens-entries kv-store)) :start-new-service-fn (pc/fnk [[:scheduler scheduler] [:state start-service-cache scheduler-interactions-thread-pool] store-service-description-fn] (fn start-new-service [{:keys [service-id] :as descriptor}] (store-service-description-fn descriptor) (scheduler/validate-service scheduler service-id) (service/start-new-service scheduler descriptor start-service-cache scheduler-interactions-thread-pool))) :start-work-stealing-balancer-fn (pc/fnk [[:settings [:work-stealing offer-help-interval-ms reserve-timeout-ms]] [:state instance-rpc-chan router-id] make-inter-router-requests-async-fn router-metrics-helpers] (fn start-work-stealing-balancer [service-id] (let [{:keys [service-id->router-id->metrics]} router-metrics-helpers] (work-stealing/start-work-stealing-balancer instance-rpc-chan reserve-timeout-ms offer-help-interval-ms service-id->router-id->metrics make-inter-router-requests-async-fn router-id service-id)))) :stop-work-stealing-balancer-fn (pc/fnk [] (fn stop-work-stealing-balancer [service-id work-stealing-chan-map] (log/info "stopping work-stealing balancer for" service-id) (async/go (when-let [exit-chan (get work-stealing-chan-map [:exit-chan])] (async/>! exit-chan :exit))))) :store-service-description-fn (pc/fnk [[:curator kv-store] validate-service-description-fn] (fn store-service-description [{:keys [core-service-description service-id]}] (sd/store-core kv-store service-id core-service-description validate-service-description-fn))) :store-source-tokens-fn (pc/fnk [[:curator kv-store] synchronize-fn] (fn store-source-tokens-fn [service-id source-tokens] (sd/store-source-tokens! synchronize-fn kv-store service-id source-tokens))) :synchronize-fn (pc/fnk [[:curator curator] [:settings [:zookeeper base-path mutex-timeout-ms]]] (fn synchronize-fn [path f] (let [lock-path (str base-path "/" path)] (curator/synchronize curator lock-path mutex-timeout-ms f)))) :token->service-description-template (pc/fnk [[:curator kv-store]] (fn token->service-description-template [token] (sd/token->service-description-template kv-store token :error-on-missing false))) :token->token-hash (pc/fnk [[:curator kv-store]] (fn token->token-hash [token] (sd/token->token-hash kv-store token))) :token->token-metadata (pc/fnk [[:curator kv-store]] (fn token->token-metadata [token] (sd/token->token-metadata kv-store token :error-on-missing false))) :validate-service-description-fn (pc/fnk [[:state service-description-builder]] (fn validate-service-description [service-description] (sd/validate service-description-builder service-description {}))) :waiter-request?-fn (pc/fnk [[:state waiter-hostnames]] (let [local-router (InetAddress/getLocalHost) waiter-router-hostname (.getCanonicalHostName local-router) waiter-router-ip (.getHostAddress local-router) hostnames (conj waiter-hostnames waiter-router-hostname waiter-router-ip)] (waiter-request?-factory hostnames))) :websocket-request-auth-cookie-attacher (pc/fnk [[:state passwords router-id]] (fn websocket-request-auth-cookie-attacher [request] (ws/inter-router-request-middleware router-id (first passwords) request))) :websocket-request-acceptor (pc/fnk [[:state passwords]] (fn websocket-request-acceptor [^ServletUpgradeRequest request ^ServletUpgradeResponse response] (.setHeader response "x-cid" (cid/get-correlation-id)) (if (ws/request-authenticator (first passwords) request response) (ws/request-subprotocol-acceptor request response) false)))}) (def daemons {:autoscaler (pc/fnk [[:curator leader?-fn] [:routines router-metrics-helpers service-id->service-description-fn] [:scheduler scheduler] [:settings [:scaling autoscaler-interval-ms]] [:state scheduler-interactions-thread-pool] autoscaling-multiplexer router-state-maintainer] (let [service-id->metrics-fn (:service-id->metrics-fn router-metrics-helpers) {{:keys [router-state-push-mult]} :maintainer} router-state-maintainer {:keys [executor-multiplexer-chan]} autoscaling-multiplexer] (scaling/autoscaler-goroutine {} leader?-fn service-id->metrics-fn executor-multiplexer-chan scheduler autoscaler-interval-ms scaling/scale-service service-id->service-description-fn router-state-push-mult scheduler-interactions-thread-pool))) :autoscaling-multiplexer (pc/fnk [[:routines delegate-instance-kill-request-fn peers-acknowledged-blacklist-requests-fn service-id->service-description-fn] [:scheduler scheduler] [:settings [:scaling quanta-constraints]] [:state instance-rpc-chan scheduler-interactions-thread-pool scaling-timeout-config] router-state-maintainer] (let [{{:keys [notify-instance-killed-fn]} :maintainer} router-state-maintainer] (scaling/service-scaling-multiplexer (fn scaling-executor-factory [service-id] (scaling/service-scaling-executor notify-instance-killed-fn peers-acknowledged-blacklist-requests-fn delegate-instance-kill-request-fn service-id->service-description-fn scheduler instance-rpc-chan quanta-constraints scaling-timeout-config scheduler-interactions-thread-pool service-id)) {}))) :codahale-reporters (pc/fnk [[:settings [:metrics-config codahale-reporters]]] (pc/map-vals (fn make-codahale-reporter [{:keys [factory-fn] :as reporter-config}] (let [resolved-factory-fn (utils/resolve-symbol! factory-fn) reporter-instance (resolved-factory-fn reporter-config)] (when-not (satisfies? reporter/CodahaleReporter reporter-instance) (throw (ex-info "Reporter factory did not create an instance of CodahaleReporter" {:reporter-config reporter-config :reporter-instance reporter-instance :resolved-factory-fn resolved-factory-fn}))) reporter-instance)) codahale-reporters)) :fallback-maintainer (pc/fnk [[:state fallback-state-atom] router-state-maintainer] (let [{{:keys [router-state-push-mult]} :maintainer} router-state-maintainer router-state-chan (async/tap router-state-push-mult (au/latest-chan))] (descriptor/fallback-maintainer router-state-chan fallback-state-atom))) :gc-for-transient-metrics (pc/fnk [[:routines router-metrics-helpers] [:settings metrics-config] [:state clock local-usage-agent] router-state-maintainer] (let [state-store-atom (atom {}) read-state-fn (fn read-state [_] @state-store-atom) write-state-fn (fn write-state [_ state] (reset! state-store-atom state)) leader?-fn (constantly true) service-gc-go-routine (partial service-gc-go-routine read-state-fn write-state-fn leader?-fn clock) {{:keys [query-state-fn]} :maintainer} router-state-maintainer {:keys [service-id->metrics-fn]} router-metrics-helpers {:keys [service-id->metrics-chan] :as metrics-gc-chans} (metrics/transient-metrics-gc query-state-fn local-usage-agent service-gc-go-routine metrics-config)] (metrics/transient-metrics-data-producer service-id->metrics-chan service-id->metrics-fn metrics-config) metrics-gc-chans)) :interstitial-maintainer (pc/fnk [[:routines service-id->service-description-fn] [:state interstitial-state-atom] router-state-maintainer] (let [{{:keys [router-state-push-mult]} :maintainer} router-state-maintainer router-state-chan (async/tap router-state-push-mult (au/latest-chan)) initial-state {}] (interstitial/interstitial-maintainer service-id->service-description-fn router-state-chan interstitial-state-atom initial-state))) :launch-metrics-maintainer (pc/fnk [[:curator leader?-fn] [:routines service-id->service-description-fn] router-state-maintainer] (let [{{:keys [router-state-push-mult]} :maintainer} router-state-maintainer] (scheduler/start-launch-metrics-maintainer (async/tap router-state-push-mult (au/latest-chan)) leader?-fn service-id->service-description-fn))) :messages (pc/fnk [[:settings {messages nil}]] (when messages (utils/load-messages messages))) :router-list-maintainer (pc/fnk [[:curator discovery] [:settings router-syncer]] (let [{:keys [delay-ms interval-ms]} router-syncer router-chan (au/latest-chan) router-mult-chan (async/mult router-chan)] (state/start-router-syncer discovery router-chan interval-ms delay-ms) {:router-mult-chan router-mult-chan})) :router-metrics-syncer (pc/fnk [[:routines crypt-helpers websocket-request-auth-cookie-attacher] [:settings [:metrics-config inter-router-metrics-idle-timeout-ms metrics-sync-interval-ms router-update-interval-ms]] [:state local-usage-agent router-metrics-agent websocket-client] router-list-maintainer] (let [{:keys [bytes-encryptor]} crypt-helpers router-chan (async/tap (:router-mult-chan router-list-maintainer) (au/latest-chan))] {:metrics-syncer (metrics-sync/setup-metrics-syncer router-metrics-agent local-usage-agent metrics-sync-interval-ms bytes-encryptor) :router-syncer (metrics-sync/setup-router-syncer router-chan router-metrics-agent router-update-interval-ms inter-router-metrics-idle-timeout-ms metrics-sync-interval-ms websocket-client bytes-encryptor websocket-request-auth-cookie-attacher)})) :router-state-maintainer (pc/fnk [[:routines refresh-service-descriptions-fn service-id->service-description-fn] [:scheduler scheduler] [:settings deployment-error-config] [:state router-id scheduler-state-chan] router-list-maintainer] (let [exit-chan (async/chan) router-chan (async/tap (:router-mult-chan router-list-maintainer) (au/latest-chan)) service-id->deployment-error-config-fn #(scheduler/deployment-error-config scheduler %) maintainer (state/start-router-state-maintainer scheduler-state-chan router-chan router-id exit-chan service-id->service-description-fn refresh-service-descriptions-fn service-id->deployment-error-config-fn deployment-error-config)] {:exit-chan exit-chan :maintainer maintainer})) :scheduler-broken-services-gc (pc/fnk [[:curator gc-state-reader-fn gc-state-writer-fn leader?-fn] [:scheduler scheduler] [:settings scheduler-gc-config] [:state clock] router-state-maintainer] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer service-gc-go-routine (partial service-gc-go-routine gc-state-reader-fn gc-state-writer-fn leader?-fn clock)] (scheduler/scheduler-broken-services-gc service-gc-go-routine query-state-fn scheduler scheduler-gc-config))) :scheduler-services-gc (pc/fnk [[:curator gc-state-reader-fn gc-state-writer-fn leader?-fn] [:routines router-metrics-helpers service-id->idle-timeout] [:scheduler scheduler] [:settings scheduler-gc-config] [:state clock] router-state-maintainer] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer {:keys [service-id->metrics-fn]} router-metrics-helpers service-gc-go-routine (partial service-gc-go-routine gc-state-reader-fn gc-state-writer-fn leader?-fn clock)] (scheduler/scheduler-services-gc scheduler query-state-fn service-id->metrics-fn scheduler-gc-config service-gc-go-routine service-id->idle-timeout))) :service-chan-maintainer (pc/fnk [[:routines start-work-stealing-balancer-fn stop-work-stealing-balancer-fn] [:settings blacklist-config instance-request-properties] [:state instance-rpc-chan query-service-maintainer-chan] router-state-maintainer] (let [start-service (fn start-service [service-id] (let [maintainer-chan-map (state/prepare-and-start-service-chan-responder service-id instance-request-properties blacklist-config) workstealing-chan-map (start-work-stealing-balancer-fn service-id)] {:maintainer-chan-map maintainer-chan-map :work-stealing-chan-map workstealing-chan-map})) remove-service (fn remove-service [service-id {:keys [maintainer-chan-map work-stealing-chan-map]}] (state/close-update-state-channel service-id maintainer-chan-map) (stop-work-stealing-balancer-fn service-id work-stealing-chan-map)) retrieve-channel (fn retrieve-channel [channel-map method] (let [method-chan (case method :blacklist [:maintainer-chan-map :blacklist-instance-chan] :kill [:maintainer-chan-map :kill-instance-chan] :offer [:maintainer-chan-map :work-stealing-chan] :query-state [:maintainer-chan-map :query-state-chan] :query-work-stealing [:work-stealing-chan-map :query-chan] :release [:maintainer-chan-map :release-instance-chan] :reserve [:maintainer-chan-map :reserve-instance-chan-in] :update-state [:maintainer-chan-map :update-state-chan])] (get-in channel-map method-chan))) {{:keys [router-state-push-mult]} :maintainer} router-state-maintainer state-chan (au/latest-chan)] (async/tap router-state-push-mult state-chan) (state/start-service-chan-maintainer {} instance-rpc-chan state-chan query-service-maintainer-chan start-service remove-service retrieve-channel))) :state-sources (pc/fnk [[:scheduler scheduler] [:state query-service-maintainer-chan] autoscaler autoscaling-multiplexer gc-for-transient-metrics interstitial-maintainer scheduler-broken-services-gc scheduler-services-gc] {:autoscaler-state (:query-service-state-fn autoscaler) :autoscaling-multiplexer-state (:query-chan autoscaling-multiplexer) :interstitial-maintainer-state (:query-chan interstitial-maintainer) :scheduler-broken-services-gc-state (:query-service-state-fn scheduler-broken-services-gc) :scheduler-services-gc-state (:query-service-state-fn scheduler-services-gc) :scheduler-state (fn scheduler-state-fn [service-id] (scheduler/service-id->state scheduler service-id)) :service-maintainer-state query-service-maintainer-chan :transient-metrics-gc-state (:query-service-state-fn gc-for-transient-metrics)}) :statsd (pc/fnk [[:routines service-id->service-description-fn] [:settings statsd] router-state-maintainer] (when (not= statsd :disabled) (statsd/setup statsd) (let [{:keys [sync-instances-interval-ms]} statsd {{:keys [query-state-fn]} :maintainer} router-state-maintainer] (statsd/start-service-instance-metrics-publisher service-id->service-description-fn query-state-fn sync-instances-interval-ms))))}) (def request-handlers {:app-name-handler-fn (pc/fnk [service-id-handler-fn] service-id-handler-fn) :async-complete-handler-fn (pc/fnk [[:routines async-request-terminate-fn] wrap-router-auth-fn] (wrap-router-auth-fn (fn async-complete-handler-fn [request] (handler/complete-async-handler async-request-terminate-fn request)))) :async-result-handler-fn (pc/fnk [[:routines async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn async-result-handler-fn [request] (handler/async-result-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request)))) :async-status-handler-fn (pc/fnk [[:routines async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn async-status-handler-fn [request] (handler/async-status-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request)))) :blacklist-instance-handler-fn (pc/fnk [[:daemons router-state-maintainer] [:state instance-rpc-chan] wrap-router-auth-fn] (let [{{:keys [notify-instance-killed-fn]} :maintainer} router-state-maintainer] (wrap-router-auth-fn (fn blacklist-instance-handler-fn [request] (handler/blacklist-instance notify-instance-killed-fn instance-rpc-chan request))))) :blacklisted-instances-list-handler-fn (pc/fnk [[:state instance-rpc-chan]] (fn blacklisted-instances-list-handler-fn [{{:keys [service-id]} :route-params :as request}] (handler/get-blacklisted-instances instance-rpc-chan service-id request))) :default-websocket-handler-fn (pc/fnk [[:routines determine-priority-fn service-id->password-fn start-new-service-fn] [:settings instance-request-properties] [:state instance-rpc-chan local-usage-agent passwords websocket-client] wrap-descriptor-fn] (fn default-websocket-handler-fn [request] (let [password (first passwords) make-request-fn (fn make-ws-request [instance request request-properties passthrough-headers end-route metric-group backend-proto proto-version] (ws/make-request websocket-client service-id->password-fn instance request request-properties passthrough-headers end-route metric-group backend-proto proto-version)) process-request-fn (fn process-request-fn [request] (pr/process make-request-fn instance-rpc-chan start-new-service-fn instance-request-properties determine-priority-fn ws/process-response! ws/abort-request-callback-factory local-usage-agent request)) handler (-> process-request-fn (ws/wrap-ws-close-on-error) wrap-descriptor-fn)] (ws/request-handler password handler request)))) :display-settings-handler-fn (pc/fnk [wrap-secure-request-fn settings] (wrap-secure-request-fn (fn display-settings-handler-fn [_] (settings/display-settings settings)))) :favicon-handler-fn (pc/fnk [] (fn favicon-handler-fn [_] {:body (io/input-stream (io/resource "web/favicon.ico")) :content-type "image/png"})) :kill-instance-handler-fn (pc/fnk [[:daemons router-state-maintainer] [:routines peers-acknowledged-blacklist-requests-fn] [:scheduler scheduler] [:state instance-rpc-chan scaling-timeout-config scheduler-interactions-thread-pool] wrap-router-auth-fn] (let [{{:keys [notify-instance-killed-fn]} :maintainer} router-state-maintainer] (wrap-router-auth-fn (fn kill-instance-handler-fn [request] (scaling/kill-instance-handler notify-instance-killed-fn peers-acknowledged-blacklist-requests-fn scheduler instance-rpc-chan scaling-timeout-config scheduler-interactions-thread-pool request))))) :metrics-request-handler-fn (pc/fnk [] (fn metrics-request-handler-fn [request] (handler/metrics-request-handler request))) :not-found-handler-fn (pc/fnk [] handler/not-found-handler) :process-request-fn (pc/fnk [[:routines determine-priority-fn make-basic-auth-fn post-process-async-request-response-fn service-id->password-fn start-new-service-fn] [:settings instance-request-properties] [:state http-clients instance-rpc-chan local-usage-agent interstitial-state-atom] wrap-auth-bypass-fn wrap-descriptor-fn wrap-https-redirect-fn wrap-secure-request-fn wrap-service-discovery-fn] (let [make-request-fn (fn [instance request request-properties passthrough-headers end-route metric-group backend-proto proto-version] (pr/make-request http-clients make-basic-auth-fn service-id->password-fn instance request request-properties passthrough-headers end-route metric-group backend-proto proto-version)) process-response-fn (partial pr/process-http-response post-process-async-request-response-fn) inner-process-request-fn (fn inner-process-request [request] (pr/process make-request-fn instance-rpc-chan start-new-service-fn instance-request-properties determine-priority-fn process-response-fn pr/abort-http-request-callback-factory local-usage-agent request))] (-> inner-process-request-fn pr/wrap-too-many-requests pr/wrap-suspended-service pr/wrap-response-status-metrics (interstitial/wrap-interstitial interstitial-state-atom) wrap-descriptor-fn wrap-secure-request-fn wrap-auth-bypass-fn wrap-https-redirect-fn wrap-service-discovery-fn))) :router-metrics-handler-fn (pc/fnk [[:routines crypt-helpers] [:settings [:metrics-config metrics-sync-interval-ms]] [:state router-metrics-agent]] (let [{:keys [bytes-decryptor bytes-encryptor]} crypt-helpers] (fn router-metrics-handler-fn [request] (metrics-sync/incoming-router-metrics-handler router-metrics-agent metrics-sync-interval-ms bytes-encryptor bytes-decryptor request)))) :service-handler-fn (pc/fnk [[:curator kv-store] [:daemons router-state-maintainer] [:routines allowed-to-manage-service?-fn generate-log-url-fn make-inter-router-requests-sync-fn router-metrics-helpers service-id->service-description-fn service-id->source-tokens-entries-fn] [:scheduler scheduler] [:state router-id scheduler-interactions-thread-pool] wrap-secure-request-fn] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer {:keys [service-id->metrics-fn]} router-metrics-helpers] (wrap-secure-request-fn (fn service-handler-fn [{:as request {:keys [service-id]} :route-params}] (handler/service-handler router-id service-id scheduler kv-store allowed-to-manage-service?-fn generate-log-url-fn make-inter-router-requests-sync-fn service-id->service-description-fn service-id->source-tokens-entries-fn query-state-fn service-id->metrics-fn scheduler-interactions-thread-pool request))))) :service-id-handler-fn (pc/fnk [[:curator kv-store] [:routines store-service-description-fn] wrap-descriptor-fn wrap-secure-request-fn] (-> (fn service-id-handler-fn [request] (handler/service-id-handler request kv-store store-service-description-fn)) wrap-descriptor-fn wrap-secure-request-fn)) :service-list-handler-fn (pc/fnk [[:daemons router-state-maintainer] [:routines prepend-waiter-url router-metrics-helpers service-id->service-description-fn service-id->source-tokens-entries-fn] [:state entitlement-manager] wrap-secure-request-fn] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer {:keys [service-id->metrics-fn]} router-metrics-helpers] (wrap-secure-request-fn (fn service-list-handler-fn [request] (handler/list-services-handler entitlement-manager query-state-fn prepend-waiter-url service-id->service-description-fn service-id->metrics-fn service-id->source-tokens-entries-fn request))))) :service-override-handler-fn (pc/fnk [[:curator kv-store] [:routines allowed-to-manage-service?-fn make-inter-router-requests-sync-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn service-override-handler-fn [{:as request {:keys [service-id]} :route-params}] (handler/override-service-handler kv-store allowed-to-manage-service?-fn make-inter-router-requests-sync-fn service-id request)))) :service-refresh-handler-fn (pc/fnk [[:curator kv-store] wrap-router-auth-fn] (wrap-router-auth-fn (fn service-refresh-handler [{{:keys [service-id]} :route-params {:keys [src-router-id]} :basic-authentication}] (log/info service-id "refresh triggered by router" src-router-id) (sd/fetch-core kv-store service-id :refresh true) (sd/service-id->suspended-state kv-store service-id :refresh true) (sd/service-id->overrides kv-store service-id :refresh true)))) :service-resume-handler-fn (pc/fnk [[:curator kv-store] [:routines allowed-to-manage-service?-fn make-inter-router-requests-sync-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn service-resume-handler-fn [{:as request {:keys [service-id]} :route-params}] (handler/suspend-or-resume-service-handler kv-store allowed-to-manage-service?-fn make-inter-router-requests-sync-fn service-id :resume request)))) :service-suspend-handler-fn (pc/fnk [[:curator kv-store] [:routines allowed-to-manage-service?-fn make-inter-router-requests-sync-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn service-suspend-handler-fn [{:as request {:keys [service-id]} :route-params}] (handler/suspend-or-resume-service-handler kv-store allowed-to-manage-service?-fn make-inter-router-requests-sync-fn service-id :suspend request)))) :service-view-logs-handler-fn (pc/fnk [[:routines generate-log-url-fn] [:scheduler scheduler] wrap-secure-request-fn] (wrap-secure-request-fn (fn service-view-logs-handler-fn [{:as request {:keys [service-id]} :route-params}] (handler/service-view-logs-handler scheduler service-id generate-log-url-fn request)))) :sim-request-handler (pc/fnk [] simulator/handle-sim-request) :state-all-handler-fn (pc/fnk [[:daemons router-state-maintainer] [:state router-id] wrap-secure-request-fn] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer] (wrap-secure-request-fn (fn state-all-handler-fn [request] (handler/get-router-state router-id query-state-fn request))))) :state-autoscaler-handler-fn (pc/fnk [[:daemons autoscaler] [:state router-id] wrap-secure-request-fn] (let [{:keys [query-state-fn]} autoscaler] (wrap-secure-request-fn (fn state-autoscaler-handler-fn [request] (handler/get-query-fn-state router-id query-state-fn request))))) :state-autoscaling-multiplexer-handler-fn (pc/fnk [[:daemons autoscaling-multiplexer] [:state router-id] wrap-secure-request-fn] (let [{:keys [query-chan]} autoscaling-multiplexer] (wrap-secure-request-fn (fn state-autoscaling-multiplexer-handler-fn [request] (handler/get-query-chan-state-handler router-id query-chan request))))) :state-codahale-reporters-handler-fn (pc/fnk [[:daemons codahale-reporters] [:state router-id]] (fn codahale-reporter-state-handler-fn [request] (handler/get-query-fn-state router-id #(pc/map-vals reporter/state codahale-reporters) request))) :state-fallback-handler-fn (pc/fnk [[:daemons fallback-maintainer] [:state router-id] wrap-secure-request-fn] (let [fallback-query-chan (:query-chan fallback-maintainer)] (wrap-secure-request-fn (fn state-fallback-handler-fn [request] (handler/get-query-chan-state-handler router-id fallback-query-chan request))))) :state-gc-for-broken-services (pc/fnk [[:daemons scheduler-broken-services-gc] [:state router-id] wrap-secure-request-fn] (let [{:keys [query-state-fn]} scheduler-broken-services-gc] (wrap-secure-request-fn (fn state-autoscaler-handler-fn [request] (handler/get-query-fn-state router-id query-state-fn request))))) :state-gc-for-services (pc/fnk [[:daemons scheduler-services-gc] [:state router-id] wrap-secure-request-fn] (let [{:keys [query-state-fn]} scheduler-services-gc] (wrap-secure-request-fn (fn state-autoscaler-handler-fn [request] (handler/get-query-fn-state router-id query-state-fn request))))) :state-gc-for-transient-metrics (pc/fnk [[:daemons gc-for-transient-metrics] [:state router-id] wrap-secure-request-fn] (let [{:keys [query<KEY>-state<KEY>-fn]} gc-for-transient-metrics] (wrap-secure-request-fn (fn state-autoscaler-handler-fn [request] (handler/get-query-fn-state router-id query-state-fn request))))) :state-interstitial-handler-fn (pc/fnk [[:daemons interstitial-maintainer] [:state router-id] wrap-secure-request-fn] (let [interstitial-query-chan (:query-chan interstitial-maintainer)] (wrap-secure-request-fn (fn state-interstitial-handler-fn [request] (handler/get-query-chan-state-handler router-id interstitial-query-chan request))))) :state-launch-metrics-handler-fn (pc/fnk [[:daemons launch-metrics-maintainer] [:state router-id] wrap-secure-request-fn] (let [query-chan (:query-chan launch-metrics-maintainer)] (wrap-secure-request-fn (fn state-launch-metrics-handler-fn [request] (handler/get-query-chan-state-handler router-id query-chan request))))) :state-kv-store-handler-fn (pc/fnk [[:curator kv-store] [:state router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn kv-store-state-handler-fn [request] (handler/get-kv-store-state router-id kv-store request)))) :state-leader-handler-fn (pc/fnk [[:curator leader?-fn leader-id-fn] [:state router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn leader-state-handler-fn [request] (handler/get-leader-state router-id leader?-fn leader-id-fn request)))) :state-local-usage-handler-fn (pc/fnk [[:state local-usage-agent router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn local-usage-state-handler-fn [request] (handler/get-local-usage-state router-id local-usage-agent request)))) :state-maintainer-handler-fn (pc/fnk [[:daemons router-state-maintainer] [:state router-id] wrap-secure-request-fn] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer] (wrap-secure-request-fn (fn maintainer-state-handler-fn [request] (handler/get-chan-latest-state-handler router-id query-state-fn request))))) :state-router-metrics-handler-fn (pc/fnk [[:routines router-metrics-helpers] [:state router-id] wrap-secure-request-fn] (let [router-metrics-state-fn (:router-metrics-state-fn router-metrics-helpers)] (wrap-secure-request-fn (fn r-router-metrics-state-handler-fn [request] (handler/get-router-metrics-state router-id router-metrics-state-fn request))))) :state-scheduler-handler-fn (pc/fnk [[:scheduler scheduler] [:state router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn scheduler-state-handler-fn [request] (handler/get-scheduler-state router-id scheduler request)))) :state-service-handler-fn (pc/fnk [[:daemons state-sources] [:state instance-rpc-chan local-usage-agent router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn service-state-handler-fn [{{:keys [service-id]} :route-params :as request}] (handler/get-service-state router-id instance-rpc-chan local-usage-agent service-id state-sources request)))) :state-statsd-handler-fn (pc/fnk [[:state router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn state-statsd-handler-fn [request] (handler/get-statsd-state router-id request)))) :status-handler-fn (pc/fnk [] handler/status-handler) :token-handler-fn (pc/fnk [[:curator kv-store] [:routines make-inter-router-requests-sync-fn synchronize-fn validate-service-description-fn] [:settings [:token-config history-length limit-per-owner]] [:state clock entitlement-manager token-cluster-calculator token-root waiter-hostnames] wrap-secure-request-fn] (wrap-secure-request-fn (fn token-handler-fn [request] (token/handle-token-request clock synchronize-fn kv-store token-cluster-calculator token-root history-length limit-per-owner waiter-hostnames entitlement-manager make-inter-router-requests-sync-fn validate-service-description-fn request)))) :token-list-handler-fn (pc/fnk [[:curator kv-store] [:state entitlement-manager] wrap-secure-request-fn] (wrap-secure-request-fn (fn token-handler-fn [request] (token/handle-list-tokens-request kv-store entitlement-manager request)))) :token-owners-handler-fn (pc/fnk [[:curator kv-store] wrap-secure-request-fn] (wrap-secure-request-fn (fn token-owners-handler-fn [request] (token/handle-list-token-owners-request kv-store request)))) :token-refresh-handler-fn (pc/fnk [[:curator kv-store] wrap-router-auth-fn] (wrap-router-auth-fn (fn token-refresh-handler-fn [request] (token/handle-refresh-token-request kv-store request)))) :token-reindex-handler-fn (pc/fnk [[:curator kv-store] [:routines list-tokens-fn make-inter-router-requests-sync-fn synchronize-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn token-handler-fn [request] (token/handle-reindex-tokens-request synchronize-fn make-inter-router-requests-sync-fn kv-store list-tokens-fn request)))) :waiter-auth-handler-fn (pc/fnk [wrap-secure-request-fn] (wrap-secure-request-fn (fn waiter-auth-handler-fn [request] {:body (str (:authorization/user request)), :status 200}))) :waiter-acknowledge-consent-handler-fn (pc/fnk [[:routines service-description->service-id token->service-description-template token->token-metadata] [:settings consent-expiry-days] [:state clock passwords] wrap-secure-request-fn] (let [password (first passwords)] (letfn [(add-encoded-cookie [response cookie-name value expiry-days] (cookie-support/add-encoded-cookie response password cookie-name value expiry-days)) (consent-cookie-value [mode service-id token token-metadata] (sd/consent-cookie-value clock mode service-id token token-metadata))] (wrap-secure-request-fn (fn inner-waiter-acknowledge-consent-handler-fn [request] (handler/acknowledge-consent-handler token->service-description-template token->token-metadata service-description->service-id consent-cookie-value add-encoded-cookie consent-expiry-days request)))))) :waiter-request-consent-handler-fn (pc/fnk [[:routines service-description->service-id token->service-description-template] [:settings consent-expiry-days] wrap-secure-request-fn] (wrap-secure-request-fn (fn waiter-request-consent-handler-fn [request] (handler/request-consent-handler token->service-description-template service-description->service-id consent-expiry-days request)))) :waiter-request-interstitial-handler-fn (pc/fnk [wrap-secure-request-fn] (wrap-secure-request-fn (fn waiter-request-interstitial-handler-fn [request] (interstitial/display-interstitial-handler request)))) :welcome-handler-fn (pc/fnk [settings] (partial handler/welcome-handler settings)) :work-stealing-handler-fn (pc/fnk [[:state instance-rpc-chan] wrap-router-auth-fn] (wrap-router-auth-fn (fn [request] (handler/work-stealing-handler instance-rpc-chan request)))) :wrap-auth-bypass-fn (pc/fnk [] (fn wrap-auth-bypass-fn [handler] (fn [{:keys [waiter-discovery] :as request}] (let [{:keys [service-parameter-template token waiter-headers]} waiter-discovery {:strs [authentication] :as service-description} service-parameter-template authentication-disabled? (= authentication "disabled")] (cond (contains? waiter-headers "x-waiter-authentication") (do (log/info "x-waiter-authentication is not supported as an on-the-fly header" {:service-description service-description, :token token}) (utils/clj->json-response {:error "An authentication parameter is not supported for on-the-fly headers"} :status 400)) ;; ensure service description formed comes entirely from the token by ensuring absence of on-the-fly headers (and authentication-disabled? (some sd/service-parameter-keys (-> waiter-headers headers/drop-waiter-header-prefix keys))) (do (log/info "request cannot proceed as it is mixing an authentication disabled token with on-the-fly headers" {:service-description service-description, :token token}) (utils/clj->json-response {:error "An authentication disabled token may not be combined with on-the-fly headers"} :status 400)) authentication-disabled? (do (log/info "request configured to skip authentication") (handler (assoc request :skip-authentication true))) :else (handler request)))))) :wrap-descriptor-fn (pc/fnk [[:routines request->descriptor-fn start-new-service-fn] [:state fallback-state-atom]] (fn wrap-descriptor-fn [handler] (descriptor/wrap-descriptor handler request->descriptor-fn start-new-service-fn fallback-state-atom))) :wrap-https-redirect-fn (pc/fnk [] (fn wrap-https-redirect-fn [handler] (fn [request] (cond (and (get-in request [:waiter-discovery :token-metadata "https-redirect"]) ;; ignore websocket requests (= :http (utils/request->scheme request))) (do (log/info "triggering ssl redirect") (-> (ssl/ssl-redirect-response request {}) (rr/header "server" (utils/get-current-server-name)))) :else (handler request))))) :wrap-router-auth-fn (pc/fnk [[:state passwords router-id]] (fn wrap-router-auth-fn [handler] (fn [request] (let [router-comm-authenticated? (fn router-comm-authenticated? [source-id secret-word] (let [expected-word (utils/generate-secret-word source-id router-id passwords) authenticated? (= expected-word secret-word)] (log/info "Authenticating inter-router communication from" source-id) (if-not authenticated? (log/info "inter-router request authentication failed!" {:actual secret-word, :expected expected-word}) {:src-router-id source-id}))) basic-auth-handler (basic-authentication/wrap-basic-authentication handler router-comm-authenticated?)] (basic-auth-handler request))))) :wrap-secure-request-fn (pc/fnk [[:routines authentication-method-wrapper-fn waiter-request?-fn] [:settings cors-config] [:state cors-validator]] (let [{:keys [exposed-headers]} cors-config] (fn wrap-secure-request-fn [handler] (let [handler (-> handler (cors/wrap-cors-request cors-validator waiter-request?-fn exposed-headers) authentication-method-wrapper-fn)] (fn inner-wrap-secure-request-fn [{:keys [uri] :as request}] (log/debug "secure request received at" uri) (handler request)))))) :wrap-service-discovery-fn (pc/fnk [[:curator kv-store] [:settings [:token-config token-defaults]] [:state waiter-hostnames]] (fn wrap-service-discovery-fn [handler] (fn [{:keys [headers] :as request}] ;; TODO optimization opportunity to avoid this re-computation later in the chain (let [discovered-parameters (sd/discover-service-parameters kv-store token-defaults waiter-hostnames headers)] (handler (assoc request :waiter-discovery discovered-parameters))))))})
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.core (:require [bidi.bidi :as bidi] [clj-time.core :as t] [clojure.core.async :as async] [clojure.java.io :as io] [clojure.set :as set] [clojure.string :as str] [clojure.tools.logging :as log] [digest] [full.async :refer (<?? <? go-try)] [metrics.core] [metrics.counters :as counters] [metrics.timers :as timers] [plumbing.core :as pc] [qbits.jet.client.http :as http] [ring.middleware.basic-authentication :as basic-authentication] [ring.middleware.ssl :as ssl] [ring.util.response :as rr] [slingshot.slingshot :refer [try+]] [waiter.async-request :as async-req] [waiter.auth.authentication :as auth] [waiter.authorization :as authz] [waiter.cookie-support :as cookie-support] [waiter.correlation-id :as cid] [waiter.cors :as cors] [waiter.curator :as curator] [waiter.descriptor :as descriptor] [waiter.discovery :as discovery] [waiter.handler :as handler] [waiter.headers :as headers] [waiter.interstitial :as interstitial] [waiter.kv :as kv] [waiter.metrics :as metrics] [waiter.metrics-sync :as metrics-sync] [waiter.password-store :as password-store] [waiter.process-request :as pr] [waiter.reporter :as reporter] [waiter.scaling :as scaling] [waiter.scheduler :as scheduler] [waiter.service :as service] [waiter.service-description :as sd] [waiter.settings :as settings] [waiter.simulator :as simulator] [waiter.state :as state] [waiter.statsd :as statsd] [waiter.token :as token] [waiter.util.async-utils :as au] [waiter.util.cache-utils :as cu] [waiter.util.date-utils :as du] [waiter.util.http-utils :as http-utils] [waiter.util.ring-utils :as ru] [waiter.util.utils :as utils] [waiter.websocket :as ws] [waiter.work-stealing :as work-stealing]) (:import (java.net InetAddress URI) java.util.concurrent.Executors (javax.servlet ServletRequest) org.apache.curator.framework.CuratorFrameworkFactory org.apache.curator.framework.api.CuratorEventType org.apache.curator.framework.api.CuratorListener org.apache.curator.framework.recipes.leader.LeaderLatch org.apache.curator.retry.BoundedExponentialBackoffRetry org.eclipse.jetty.client.HttpClient org.eclipse.jetty.client.util.BasicAuthentication$BasicResult org.eclipse.jetty.websocket.client.WebSocketClient (org.eclipse.jetty.websocket.servlet ServletUpgradeResponse ServletUpgradeRequest))) (defn routes-mapper "Returns a map containing a keyword handler and the parsed route-params based on the request uri." ;; Please include/update a corresponding unit test anytime the routes data structure is modified [{:keys [uri]}] (let [routes ["/" {"" :welcome-handler-fn "app-name" :app-name-handler-fn "apps" {"" :service-list-handler-fn ["/" :service-id] :service-handler-fn ["/" :service-id "/logs"] :service-view-logs-handler-fn ["/" :service-id "/override"] :service-override-handler-fn ["/" :service-id "/refresh"] :service-refresh-handler-fn ["/" :service-id "/resume"] :service-resume-handler-fn ["/" :service-id "/suspend"] :service-suspend-handler-fn} "blacklist" {"" :blacklist-instance-handler-fn ["/" :service-id] :blacklisted-instances-list-handler-fn} "favicon.ico" :favicon-handler-fn "metrics" :metrics-request-handler-fn "service-id" :service-id-handler-fn "settings" :display-settings-handler-fn "sim" :sim-request-handler "state" [["" :state-all-handler-fn] ["/autoscaler" :state-autoscaler-handler-fn] ["/autoscaling-multiplexer" :state-autoscaling-multiplexer-handler-fn] ["/codahale-reporters" :state-codahale-reporters-handler-fn] ["/fallback" :state-fallback-handler-fn] ["/gc-broken-services" :state-gc-for-broken-services] ["/gc-services" :state-gc-for-services] ["/gc-transient-metrics" :state-gc-for-transient-metrics] ["/interstitial" :state-interstitial-handler-fn] ["/launch-metrics" :state-launch-metrics-handler-fn] ["/kv-store" :state-kv-store-handler-fn] ["/leader" :state-leader-handler-fn] ["/local-usage" :state-local-usage-handler-fn] ["/maintainer" :state-maintainer-handler-fn] ["/router-metrics" :state-router-metrics-handler-fn] ["/scheduler" :state-scheduler-handler-fn] ["/statsd" :state-statsd-handler-fn] [["/" :service-id] :state-service-handler-fn]] "status" :status-handler-fn "token" :token-handler-fn "tokens" {"" :token-list-handler-fn "/owners" :token-owners-handler-fn "/refresh" :token-refresh-handler-fn "/reindex" :token-reindex-handler-fn} "waiter-async" {["/complete/" :request-id "/" :service-id] :async-complete-handler-fn ["/result/" :request-id "/" :router-id "/" :service-id "/" :host "/" :port "/" [#".+" :location]] :async-result-handler-fn ["/status/" :request-id "/" :router-id "/" :service-id "/" :host "/" :port "/" [#".+" :location]] :async-status-handler-fn} "waiter-auth" :waiter-auth-handler-fn "waiter-consent" {"" :waiter-acknowledge-consent-handler-fn ["/" [#".*" :path]] :waiter-request-consent-handler-fn} "waiter-interstitial" {["/" [#".*" :path]] :waiter-request-interstitial-handler-fn} "waiter-kill-instance" {["/" :service-id] :kill-instance-handler-fn} "work-stealing" :work-stealing-handler-fn}]] (or (bidi/match-route routes uri) {:handler :not-found-handler-fn}))) (defn ring-handler-factory "Creates the handler for processing http requests." [waiter-request?-fn {:keys [process-request-fn] :as handlers}] (fn http-handler [{:keys [uri] :as request}] (if-not (waiter-request?-fn request) (do (counters/inc! (metrics/waiter-counter "requests" "service-request")) (process-request-fn request)) (let [{:keys [handler route-params]} (routes-mapper request) request (assoc request :route-params (or route-params {})) handler-fn (get handlers handler process-request-fn)] (when (and (not= handler :process-request-fn) (= handler-fn process-request-fn)) (log/warn "using default handler as no mapping found for" handler "at uri" uri)) (when handler (counters/inc! (metrics/waiter-counter "requests" (name handler)))) (handler-fn request))))) (defn websocket-handler-factory "Creates the handler for processing websocket requests. Websockets are currently used for inter-router metrics syncing." [{:keys [default-websocket-handler-fn router-metrics-handler-fn]}] (fn websocket-handler [{:keys [uri] :as request}] (case uri "/waiter-router-metrics" (router-metrics-handler-fn request) (default-websocket-handler-fn request)))) (defn correlation-id-middleware "Attaches an x-cid header to the request and response if one is not already provided." [handler] (fn correlation-id-middleware-fn [request] (let [request (cid/ensure-correlation-id request utils/unique-identifier) request-cid (cid/http-object->correlation-id request)] (cid/with-correlation-id request-cid (log/info "request received:" (-> (dissoc request :body :ctrl :in :out :request-time :server-name :server-port :servlet-request :ssl-client-cert :support-info :trailers-fn) (update :headers headers/truncate-header-values))) (let [response (handler request) get-request-cid (fn get-request-cid [] request-cid)] (if (map? response) (cid/ensure-correlation-id response get-request-cid) (async/go (let [nested-response (async/<! response)] (if (map? nested-response) ;; websocket responses may be another channel (cid/ensure-correlation-id nested-response get-request-cid) nested-response))))))))) (defn request->protocol "Determines the protocol and version used by the request. For HTTP requests, it returns values like HTTP/1.0, HTTP/1.1, HTTP/2. For WebSocket requests, it returns values like WS/8, WS/13." [{:keys [headers scheme ^ServletRequest servlet-request]}] (if servlet-request (or (some-> headers (get "x-forwarded-proto-version") str/upper-case) (.getProtocol servlet-request)) (when scheme (str/upper-case ;; currently, only websockets need this branch to determine version (if-let [version (get headers "sec-websocket-version")] (str (name scheme) "/" version) (name scheme)))))) (defn wrap-request-info "Attaches request info to the request." [handler router-id support-info] (fn wrap-request-info-fn [{:keys [servlet-request] :as request}] (-> request (assoc :client-protocol (request->protocol request) :internal-protocol (some-> servlet-request .getProtocol) :request-id (str (utils/unique-identifier) "-" (-> request utils/request->scheme name)) :request-time (t/now) :router-id router-id :support-info support-info) handler))) (defn wrap-debug "Attaches debugging headers to requests when enabled." [handler generate-log-url-fn] (fn wrap-debug-fn [{:keys [request-id request-time router-id] :as request}] (if (utils/request->debug-enabled? request) (let [response (handler request) add-headers (fn [{:keys [descriptor instance] :as response}] (let [{:strs [backend-proto]} (:service-description descriptor) backend-directory (:log-directory instance) backend-log-url (when backend-directory (generate-log-url-fn instance)) request-date (when request-time (du/date-to-str request-time du/formatter-rfc822))] (update response :headers (fn [headers] (cond-> headers request-time (assoc "x-waiter-request-date" request-date) request-id (assoc "x-waiter-request-id" request-id) router-id (assoc "x-waiter-router-id" router-id) descriptor (assoc "x-waiter-service-id" (:service-id descriptor)) instance (assoc "x-waiter-backend-id" (:id instance) "x-waiter-backend-host" (:host instance) "x-waiter-backend-port" (str (:port instance)) "x-waiter-backend-proto" backend-proto) backend-directory (assoc "x-waiter-backend-directory" backend-directory "x-waiter-backend-log-url" backend-log-url))))))] (ru/update-response response add-headers)) (handler request)))) (defn wrap-error-handling "Catches any uncaught exceptions and returns an error response." [handler] (fn wrap-error-handling-fn [request] (try (let [response (handler request)] (if (au/chan? response) (async/go (try (<? response) (catch Exception e (utils/exception->response e request)))) response)) (catch Exception e (utils/exception->response e request))))) (defn- make-blacklist-request [make-inter-router-requests-fn blacklist-period-ms dest-router-id dest-endpoint {:keys [id] :as instance} reason] (log/info "peer communication requesting" dest-router-id "to blacklist" id "via endpoint" dest-endpoint) (try (-> (make-inter-router-requests-fn dest-endpoint :acceptable-router? #(= dest-router-id %) :body (utils/clj->json {:instance instance :period-in-ms blacklist-period-ms :reason reason}) :method :post) (get dest-router-id)) (catch Exception e (log/error e "error in making blacklist request" {:instance instance :period-in-ms blacklist-period-ms :reason reason})))) (defn peers-acknowledged-blacklist-requests? "Note that the ids used in here are internal ids generated by the curator api." [{:keys [id] :as instance} short-circuit? router-ids endpoint make-blacklist-request-fn reason] (if (seq router-ids) (loop [[dest-router-id & remaining-peer-ids] (seq router-ids) blacklist-successful? true] (log/info {:dest-id dest-router-id, :blacklist-successful? blacklist-successful?}, :reason reason) (let [response (make-blacklist-request-fn dest-router-id endpoint instance reason) response-successful? (= 200 (:status response)) blacklist-successful? (and blacklist-successful? response-successful?)] (when (and short-circuit? (not response-successful?)) (log/info "peer communication" dest-router-id "veto-ed killing of" id {:http-status (:status response)})) (when (and short-circuit? response-successful?) (log/info "peer communication" dest-router-id "approves killing of" id)) (if (and remaining-peer-ids (or (not short-circuit?) response-successful?)) (recur remaining-peer-ids blacklist-successful?) blacklist-successful?))) (do (log/warn "no peer routers found to acknowledge blacklist request!") true))) (defn make-kill-instance-request "Makes a request to a peer router to kill an instance of a service." [make-inter-router-requests-fn service-id dest-router-id kill-instance-endpoint] (log/info "peer communication requesting" dest-router-id "to kill an instance of" service-id "via endpoint" kill-instance-endpoint) (try (-> (make-inter-router-requests-fn kill-instance-endpoint :acceptable-router? #(= dest-router-id %) :method :post) (get dest-router-id)) (catch Exception e (log/error e "error in killing instance of" service-id)))) (defn delegate-instance-kill-request "Delegates requests to kill an instance of a service to peer routers." [service-id router-ids make-kill-instance-request-fn] (if (not-empty router-ids) (loop [[dest-router-id & remaining-router-ids] (seq router-ids)] (let [dest-endpoint (str "waiter-kill-instance/" service-id) {:keys [body status]} (make-kill-instance-request-fn dest-router-id dest-endpoint) kill-successful? (= 200 status)] (when kill-successful? (log/info "peer communication" dest-router-id "killed instance of" service-id body)) (if (and remaining-router-ids (not kill-successful?)) (recur remaining-router-ids) kill-successful?))) (do (log/warn "no peer routers found! Unable to delegate call to kill instance of" service-id) false))) (defn service-gc-go-routine "Go-routine that performs GC of services. Only the leader gets to perform the GC operations. Other routers keep looping waiting for their turn to become a leader. Parameters: `read-state-fn`: (fn [name] ...) used to read the current state. `write-state-fn`: (fn [name state] ...) used to write the current state which potentially is used by the read. `leader?`: Returns true if the router is currently the leader, only the leader writes state into persistent store at `(str base-path '/' gc-relative-path '/' name`. `clock` (fn [] ...) returns the current time. `name`: Name of the go-routine. `service->raw-data-source`: A channel or a no-args function which produces service data. `timeout-interval-ms`: Timeout interval used as a refractory period while listening for data from `service-data-mult-chan` to allow effects of any GC run to propagate through the system. `in-exit-chan`: The exit signal channel. `sanitize-state-fn`: (fn [prev-service->state cur-services] ...). Sanitizes the previous state based on services available currently. `service->state-fn`: (fn [service cur-state data] ...). Transforms `data` into state to be used by the gc-service? function. `gc-service?`: (fn [service {:keys [state last-modified-time]} cur-time] ...). Predicate function that returns true for apps that need to be gc-ed. `perform-gc-fn`: (fn [service] ...). Function that performs GC of the service. It must return a truth-y value when successful." [read-state-fn write-state-fn leader? clock name service->raw-data-source timeout-interval-ms sanitize-state-fn service->state-fn gc-service? perform-gc-fn] {:pre (pos? timeout-interval-ms)} (let [query-chan (async/chan 10) state-cache (cu/cache-factory {:ttl (/ timeout-interval-ms 2)}) query-state-fn (fn query-state-fn [] (cu/cache-get-or-load state-cache name #(read-state-fn name))) query-service-state-fn (fn query-service-state-fn [{:keys [service-id]}] (-> (query-state-fn) (get service-id) (or {}))) exit-chan (async/chan 1)] (cid/with-correlation-id name (async/go-loop [iter 0 timeout-chan (async/timeout timeout-interval-ms)] (let [[chan args] (async/alt! exit-chan ([_] [:exit]) query-chan ([args] [:query args]) timeout-chan ([_] [:continue]) :priority true)] (case chan :exit (log/info "[service-gc-go-routine] exiting" name) :query (let [{:keys [response-chan]} args state (query-service-state-fn args)] (async/>! response-chan (or state {})) (recur (inc iter) timeout-chan)) :continue (do (when (leader?) (let [service->raw-data (if (fn? service->raw-data-source) (service->raw-data-source) (async/<! service->raw-data-source))] (timers/start-stop-time! (metrics/waiter-timer "gc" name "iteration-duration") (try (let [service->state (or (read-state-fn name) {}) current-time (clock) service->state' (apply merge (sanitize-state-fn service->state (keys service->raw-data)) (map (fn [[service raw-data]] (let [cur-state (get service->state service) new-state (service->state-fn service (:state cur-state) raw-data)] (if (= (:state cur-state) new-state) [service cur-state] [service {:state new-state :last-modified-time current-time}]))) service->raw-data)) apps-to-gc (map first (filter (fn [[service state]] (when-let [gc-service (gc-service? service state current-time)] (log/info service "with state" (:state state) "and last modified time" (du/date-to-str (:last-modified-time state)) "marked for deletion") gc-service)) service->state')) apps-successfully-gced (filter (fn [service] (try (when (leader?) ; check to ensure still the leader (perform-gc-fn service)) (catch Exception e (log/error e "error in deleting:" service)))) apps-to-gc) apps-failed-to-delete (apply disj (set apps-to-gc) apps-successfully-gced) service->state'' (apply dissoc service->state' apps-successfully-gced)] (when (or (not= (set (keys service->state'')) (set (keys service->raw-data))) (not= (set (keys service->state'')) (set (keys service->state)))) (log/info "state has" (count service->state'') "active services, received" (count service->raw-data) "services in latest update.")) (when (not-empty apps-failed-to-delete) (log/warn "unable to delete services:" apps-failed-to-delete)) (write-state-fn name service->state'') (cu/cache-evict state-cache name)) (catch Exception e (log/error e "error in" name {:iteration iter})))))) (recur (inc iter) (async/timeout timeout-interval-ms))))))) {:exit exit-chan :query query-chan :query-service-state-fn query-service-state-fn :query-state-fn query-state-fn})) (defn make-inter-router-requests "Helper function to make inter-router requests with basic authentication. It assumes that the response from inter-router communication always supports json." [make-request-fn make-basic-auth-fn my-router-id discovery passwords endpoint & {:keys [acceptable-router? body config method] :or {acceptable-router? (constantly true) body "" config {} method :get}}] (let [router-id->endpoint-url (discovery/router-id->endpoint-url discovery "http" endpoint :exclude-set #{my-router-id}) router-id->endpoint-url' (filter (fn [[router-id _]] (acceptable-router? router-id)) router-id->endpoint-url) request-config (update config :headers (fn prepare-inter-router-requests-headers [headers] (-> headers (assoc "accept" "application/json") (update "x-cid" (fn attach-inter-router-cid [provided-cid] (or provided-cid (let [current-cid (cid/get-correlation-id) cid-prefix (if (or (nil? current-cid) (= cid/default-correlation-id current-cid)) "waiter" current-cid)] (str cid-prefix "." (utils/unique-identifier)))))))))] (when (and (empty? router-id->endpoint-url') (not-empty router-id->endpoint-url)) (log/info "no acceptable routers found to make request!")) (loop [[[dest-router-id endpoint-url] & remaining-items] router-id->endpoint-url' router-id->response {}] (if dest-router-id (let [secret-word (utils/generate-secret-word my-router-id dest-router-id passwords) auth (make-basic-auth-fn endpoint-url my-router-id secret-word) response (make-request-fn method endpoint-url auth body request-config)] (recur remaining-items (assoc router-id->response dest-router-id response))) router-id->response)))) (defn make-request-async "Makes an asynchronous request to the endpoint using the provided authentication scheme. Returns a core.async channel that will return the response map." [http-client idle-timeout method endpoint-url auth body config] (http/request http-client (merge {:auth auth :body body :follow-redirects? false :idle-timeout idle-timeout :method method :url endpoint-url} config))) (defn make-request-sync "Makes a synchronous request to the endpoint using the provided authentication scheme. Returns a response map with the body, status and headers populated." [http-client idle-timeout method endpoint-url auth body config] (let [resp-chan (make-request-async http-client idle-timeout method endpoint-url auth body config) {:keys [body error] :as response} (async/<!! resp-chan)] (if error (log/error error "Error in communicating at" endpoint-url) (let [body-response (async/<!! body)] ;; response has been read, close as we do not use chunked encoding in inter-router (async/close! body) (assoc response :body body-response))))) (defn waiter-request?-factory "Creates a function that determines for a given request whether or not the request is intended for Waiter itself or a service of Waiter." [valid-waiter-hostnames] (let [valid-waiter-hostnames (set/union valid-waiter-hostnames #{"localhost" "127.0.0.1"})] (fn waiter-request? [{:keys [uri headers]}] (let [{:strs [host]} headers] (or (#{"/app-name" "/service-id" "/token"} uri) ; special urls that are always for Waiter (FIXME) (some #(str/starts-with? (str uri) %) ["/waiter-async/complete/" "/waiter-async/result/" "/waiter-async/status/" "/waiter-consent" "/waiter-interstitial"]) (and (or (str/blank? host) (valid-waiter-hostnames (-> host (str/split #":") first))) (not-any? #(str/starts-with? (key %) headers/waiter-header-prefix) (remove #(= "x-waiter-debug" (key %)) headers)))))))) (defn leader-fn-factory "Creates the leader? function. Leadership is decided by the leader latch and presence of at least `min-cluster-routers` peers." [router-id has-leadership? discovery min-cluster-routers] #(and (has-leadership?) ; no one gets to be the leader if there aren't at least min-cluster-routers in the clique (let [num-routers (discovery/cluster-size discovery)] (when (< num-routers min-cluster-routers) (log/info router-id "relinquishing leadership as there are too few routers in cluster:" num-routers)) (>= num-routers min-cluster-routers)))) ;; PRIVATE API (def state {:async-request-store-atom (pc/fnk [] (atom {})) :authenticator (pc/fnk [[:settings authenticator-config] passwords] (utils/create-component authenticator-config :context {:password (first passwords)})) :clock (pc/fnk [] t/now) :cors-validator (pc/fnk [[:settings cors-config]] (utils/create-component cors-config)) :entitlement-manager (pc/fnk [[:settings entitlement-config]] (utils/create-component entitlement-config)) :fallback-state-atom (pc/fnk [] (atom {:available-service-ids #{} :healthy-service-ids #{}})) :http-clients (pc/fnk [[:settings [:instance-request-properties connection-timeout-ms]] server-name] (http-utils/prepare-http-clients {:conn-timeout connection-timeout-ms :follow-redirects? false :user-agent server-name})) :instance-rpc-chan (pc/fnk [] (async/chan 1024)) ; TODO move to service-chan-maintainer :interstitial-state-atom (pc/fnk [] (atom {:initialized? false :service-id->interstitial-promise {}})) :local-usage-agent (pc/fnk [] (agent {})) :passwords (pc/fnk [[:settings password-store-config]] (let [password-provider (utils/create-component password-store-config) passwords (password-store/retrieve-passwords password-provider) _ (password-store/check-empty-passwords passwords) processed-passwords (mapv #(vector :cached %) passwords)] processed-passwords)) :query-service-maintainer-chan (pc/fnk [] (au/latest-chan)) ; TODO move to service-chan-maintainer :router-metrics-agent (pc/fnk [router-id] (metrics-sync/new-router-metrics-agent router-id {})) :router-id (pc/fnk [[:settings router-id-prefix]] (cond->> (utils/unique-identifier) (not (str/blank? router-id-prefix)) (str (str/replace router-id-prefix #"[@.]" "-") "-"))) :scaling-timeout-config (pc/fnk [[:settings [:blacklist-config blacklist-backoff-base-time-ms max-blacklist-time-ms] [:scaling inter-kill-request-wait-time-ms]]] {:blacklist-backoff-base-time-ms blacklist-backoff-base-time-ms :inter-kill-request-wait-time-ms inter-kill-request-wait-time-ms :max-blacklist-time-ms max-blacklist-time-ms}) :scheduler-interactions-thread-pool (pc/fnk [] (Executors/newFixedThreadPool 20)) :scheduler-state-chan (pc/fnk [] (au/latest-chan)) :server-name (pc/fnk [[:settings git-version]] (let [server-name (str "waiter/" (str/join (take 7 git-version)))] (utils/reset-server-name-atom! server-name) server-name)) :service-description-builder (pc/fnk [[:settings service-description-builder-config service-description-constraints]] (when-let [unknown-keys (-> service-description-constraints keys set (set/difference sd/service-parameter-keys) seq)] (throw (ex-info "Unsupported keys present in the service description constraints" {:service-description-constraints service-description-constraints :unsupported-keys (-> unknown-keys vec sort)}))) (utils/create-component service-description-builder-config :context {:constraints service-description-constraints})) :service-id-prefix (pc/fnk [[:settings [:cluster-config service-prefix]]] service-prefix) :start-service-cache (pc/fnk [] (cu/cache-factory {:threshold 100 :ttl (-> 1 t/minutes t/in-millis)})) :token-cluster-calculator (pc/fnk [[:settings [:cluster-config name] [:token-config cluster-calculator]]] (utils/create-component cluster-calculator :context {:default-cluster name})) :token-root (pc/fnk [[:settings [:cluster-config name]]] name) :waiter-hostnames (pc/fnk [[:settings hostname]] (set (if (sequential? hostname) hostname [hostname]))) :websocket-client (pc/fnk [[:settings [:websocket-config ws-max-binary-message-size ws-max-text-message-size]] http-clients] (let [http-client (http-utils/select-http-client "http" http-clients) websocket-client (WebSocketClient. ^HttpClient http-client)] (doto (.getPolicy websocket-client) (.setMaxBinaryMessageSize ws-max-binary-message-size) (.setMaxTextMessageSize ws-max-text-message-size)) websocket-client))}) (def curator {:curator (pc/fnk [[:settings [:zookeeper [:curator-retry-policy base-sleep-time-ms max-retries max-sleep-time-ms] connect-string]]] (let [retry-policy (BoundedExponentialBackoffRetry. base-sleep-time-ms max-sleep-time-ms max-retries) zk-connection-string (if (= :in-process connect-string) (:zk-connection-string (curator/start-in-process-zookeeper)) connect-string) curator (CuratorFrameworkFactory/newClient zk-connection-string 5000 5000 retry-policy)] (.start curator) ; register listener that notifies of sync call completions (.addListener (.getCuratorListenable curator) (reify CuratorListener (eventReceived [_ _ event] (when (= CuratorEventType/SYNC (.getType event)) (log/info "received SYNC event for" (.getPath event)) (when-let [response-promise (.getContext event)] (log/info "releasing response promise provided for" (.getPath event)) (deliver response-promise :release)))))) curator)) :curator-base-init (pc/fnk [curator [:settings [:zookeeper base-path]]] (curator/create-path curator base-path :create-parent-zknodes? true)) :discovery (pc/fnk [[:settings [:cluster-config name] [:zookeeper base-path discovery-relative-path] host port] [:state router-id] curator] (discovery/register router-id curator name (str base-path "/" discovery-relative-path) {:host host :port port})) :gc-base-path (pc/fnk [[:settings [:zookeeper base-path gc-relative-path]]] (str base-path "/" gc-relative-path)) :gc-state-reader-fn (pc/fnk [curator gc-base-path] (fn read-gc-state [name] (:data (curator/read-path curator (str gc-base-path "/" name) :nil-on-missing? true :serializer :nippy)))) :gc-state-writer-fn (pc/fnk [curator gc-base-path] (fn write-gc-state [name state] (curator/write-path curator (str gc-base-path "/" name) state :serializer :nippy :create-parent-zknodes? true))) :kv-store (pc/fnk [[:settings [:zookeeper base-path] kv-config] [:state passwords] curator] (kv/new-kv-store kv-config curator base-path passwords)) :leader?-fn (pc/fnk [[:settings [:cluster-config min-routers]] [:state router-id] discovery leader-latch] (let [has-leadership? #(.hasLeadership leader-latch)] (leader-fn-factory router-id has-leadership? discovery min-routers))) :leader-id-fn (pc/fnk [leader-latch] #(try (-> leader-latch .getLeader .getId) (catch Exception ex (log/error ex "unable to retrieve leader id")))) :leader-latch (pc/fnk [[:settings [:zookeeper base-path leader-latch-relative-path]] [:state router-id] curator] (let [leader-latch-path (str base-path "/" leader-latch-relative-path) latch (LeaderLatch. curator leader-latch-path router-id)] (.start latch) latch))}) (def scheduler {:scheduler (pc/fnk [[:curator leader?-fn] [:settings scheduler-config scheduler-syncer-interval-secs] [:state scheduler-state-chan service-id-prefix] service-id->password-fn* service-id->service-description-fn* start-scheduler-syncer-fn] (let [is-waiter-service?-fn (fn is-waiter-service? [^String service-id] (str/starts-with? service-id service-id-prefix)) scheduler-context {:is-waiter-service?-fn is-waiter-service?-fn :leader?-fn leader?-fn :scheduler-name (-> scheduler-config :kind utils/keyword->str) :scheduler-state-chan scheduler-state-chan ;; TODO scheduler-syncer-interval-secs should be inside the scheduler's config :scheduler-syncer-interval-secs scheduler-syncer-interval-secs :service-id->password-fn service-id->password-fn* :service-id->service-description-fn service-id->service-description-fn* :start-scheduler-syncer-fn start-scheduler-syncer-fn}] (utils/create-component scheduler-config :context scheduler-context))) ; This function is only included here for initializing the scheduler above. ; Prefer accessing the non-starred version of this function through the routines map. :service-id->password-fn* (pc/fnk [[:state passwords]] (fn service-id->password [service-id] (log/debug "generating password for" service-id) (digest/md5 (str service-id (first passwords))))) ; This function is only included here for initializing the scheduler above. ; Prefer accessing the non-starred version of this function through the routines map. :service-id->service-description-fn* (pc/fnk [[:curator kv-store] [:settings service-description-defaults metric-group-mappings]] (fn service-id->service-description [service-id & {:keys [effective?] :or {effective? true}}] (sd/service-id->service-description kv-store service-id service-description-defaults metric-group-mappings :effective? effective?))) :start-scheduler-syncer-fn (pc/fnk [[:settings [:health-check-config health-check-timeout-ms failed-check-threshold] git-version] [:state clock] service-id->service-description-fn*] (let [http-client (http-utils/http-client-factory {:conn-timeout health-check-timeout-ms :socket-timeout health-check-timeout-ms :user-agent (str "waiter-syncer/" (str/join (take 7 git-version)))}) available? (fn scheduler-available? [scheduler-name service-instance health-check-proto health-check-port-index health-check-path] (scheduler/available? http-client scheduler-name service-instance health-check-proto health-check-port-index health-check-path))] (fn start-scheduler-syncer-fn [scheduler-name get-service->instances-fn scheduler-state-chan scheduler-syncer-interval-secs] (let [timeout-chan (->> (t/seconds scheduler-syncer-interval-secs) (du/time-seq (t/now)) chime/chime-ch)] (scheduler/start-scheduler-syncer clock timeout-chan service-id->service-description-fn* available? failed-check-threshold scheduler-name get-service->instances-fn scheduler-state-chan)))))}) (def routines {:allowed-to-manage-service?-fn (pc/fnk [[:curator kv-store] [:state entitlement-manager]] (fn allowed-to-manage-service? [service-id auth-user] ; Returns whether the authenticated user is allowed to manage the service. ; Either she can run as the waiter user or the run-as-user of the service description." (sd/can-manage-service? kv-store entitlement-manager service-id auth-user))) :assoc-run-as-user-approved? (pc/fnk [[:settings consent-expiry-days] [:state clock passwords] token->token-metadata] (fn assoc-run-as-user-approved? [{:keys [headers]} service-id] (let [{:strs [cookie host]} headers token (when-not (headers/contains-waiter-header headers sd/on-the-fly-service-description-keys) (utils/authority->host host)) token-metadata (when token (token->token-metadata token)) service-consent-cookie (cookie-support/cookie-value cookie "x-waiter-consent") decoded-cookie (when service-consent-cookie (some #(cookie-support/decode-cookie-cached service-consent-cookie %1) passwords))] (sd/assoc-run-as-user-approved? clock consent-expiry-days service-id token token-metadata decoded-cookie)))) :async-request-terminate-fn (pc/fnk [[:state async-request-store-atom]] (fn async-request-terminate [request-id] (async-req/async-request-terminate async-request-store-atom request-id))) :async-trigger-terminate-fn (pc/fnk [[:state router-id] async-request-terminate-fn make-inter-router-requests-sync-fn] (fn async-trigger-terminate-fn [target-router-id service-id request-id] (async-req/async-trigger-terminate async-request-terminate-fn make-inter-router-requests-sync-fn router-id target-router-id service-id request-id))) :authentication-method-wrapper-fn (pc/fnk [[:state authenticator]] (fn authentication-method-wrapper [request-handler] (let [auth-handler (auth/wrap-auth-handler authenticator request-handler)] (fn authenticate-request [request] (if (:skip-authentication request) (do (log/info "skipping authentication for request") (request-handler request)) (auth-handler request)))))) :can-run-as?-fn (pc/fnk [[:state entitlement-manager]] (fn can-run-as [auth-user run-as-user] (authz/run-as? entitlement-manager auth-user run-as-user))) :crypt-helpers (pc/fnk [[:state passwords]] (let [password (first passwords)] {:bytes-decryptor (fn bytes-decryptor [data] (utils/compressed-bytes->map data password)) :bytes-encryptor (fn bytes-encryptor [data] (utils/map->compressed-bytes data password))})) :delegate-instance-kill-request-fn (pc/fnk [[:curator discovery] [:state router-id] make-inter-router-requests-sync-fn] (fn delegate-instance-kill-request-fn [service-id] (delegate-instance-kill-request service-id (discovery/router-ids discovery :exclude-set #{router-id}) (partial make-kill-instance-request make-inter-router-requests-sync-fn service-id)))) :determine-priority-fn (pc/fnk [] (let [position-generator-atom (atom 0)] (fn determine-priority-fn [waiter-headers] (pr/determine-priority position-generator-atom waiter-headers)))) :generate-log-url-fn (pc/fnk [prepend-waiter-url] (partial handler/generate-log-url prepend-waiter-url)) :list-tokens-fn (pc/fnk [[:curator curator] [:settings [:zookeeper base-path] kv-config]] (fn list-tokens-fn [] (let [{:keys [relative-path]} kv-config] (->> (kv/zk-keys curator (str base-path "/" relative-path)) (filter (fn [k] (not (str/starts-with? k "^")))))))) :make-basic-auth-fn (pc/fnk [] (fn make-basic-auth-fn [uri username password] (BasicAuthentication$BasicResult. (URI. uri) username password))) :make-http-request-fn (pc/fnk [[:settings instance-request-properties] [:state http-clients] make-basic-auth-fn service-id->password-fn] (handler/async-make-request-helper http-clients instance-request-properties make-basic-auth-fn service-id->password-fn pr/prepare-request-properties pr/make-request)) :make-inter-router-requests-async-fn (pc/fnk [[:curator discovery] [:settings [:instance-request-properties initial-socket-timeout-ms]] [:state http-clients passwords router-id] make-basic-auth-fn] (let [http-client (http-utils/select-http-client "http" http-clients) make-request-async-fn (fn make-request-async-fn [method endpoint-url auth body config] (make-request-async http-client initial-socket-timeout-ms method endpoint-url auth body config))] (fn make-inter-router-requests-async-fn [endpoint & args] (apply make-inter-router-requests make-request-async-fn make-basic-auth-fn router-id discovery passwords endpoint args)))) :make-inter-router-requests-sync-fn (pc/fnk [[:curator discovery] [:settings [:instance-request-properties initial-socket-timeout-ms]] [:state http-clients passwords router-id] make-basic-auth-fn] (let [http-client (http-utils/select-http-client "http" http-clients) make-request-sync-fn (fn make-request-sync-fn [method endpoint-url auth body config] (make-request-sync http-client initial-socket-timeout-ms method endpoint-url auth body config))] (fn make-inter-router-requests-sync-fn [endpoint & args] (apply make-inter-router-requests make-request-sync-fn make-basic-auth-fn router-id discovery passwords endpoint args)))) :peers-acknowledged-blacklist-requests-fn (pc/fnk [[:curator discovery] [:state router-id] make-inter-router-requests-sync-fn] (fn peers-acknowledged-blacklist-requests [instance short-circuit? blacklist-period-ms reason] (let [router-ids (discovery/router-ids discovery :exclude-set #{router-id})] (peers-acknowledged-blacklist-requests? instance short-circuit? router-ids "blacklist" (partial make-blacklist-request make-inter-router-requests-sync-fn blacklist-period-ms) reason)))) :post-process-async-request-response-fn (pc/fnk [[:state async-request-store-atom instance-rpc-chan router-id] make-http-request-fn] (fn post-process-async-request-response-wrapper [response service-id metric-group backend-proto instance _ reason-map request-properties location query-string] (async-req/post-process-async-request-response router-id async-request-store-atom make-http-request-fn instance-rpc-chan response service-id metric-group backend-proto instance reason-map request-properties location query-string))) :prepend-waiter-url (pc/fnk [[:settings port hostname]] (let [hostname (if (sequential? hostname) (first hostname) hostname)] (fn [endpoint-url] (if (str/blank? endpoint-url) endpoint-url (str "http://" hostname ":" port endpoint-url))))) :refresh-service-descriptions-fn (pc/fnk [[:curator kv-store]] (fn refresh-service-descriptions-fn [service-ids] (sd/refresh-service-descriptions kv-store service-ids))) :request->descriptor-fn (pc/fnk [[:curator kv-store] [:settings [:token-config history-length token-defaults] metric-group-mappings service-description-defaults] [:state fallback-state-atom service-description-builder service-id-prefix waiter-hostnames] assoc-run-as-user-approved? can-run-as?-fn store-source-tokens-fn] (fn request->descriptor-fn [request] (let [{:keys [latest-descriptor] :as result} (descriptor/request->descriptor assoc-run-as-user-approved? can-run-as?-fn fallback-state-atom kv-store metric-group-mappings history-length service-description-builder service-description-defaults service-id-prefix token-defaults waiter-hostnames request)] (when-let [source-tokens (-> latest-descriptor :source-tokens seq)] (store-source-tokens-fn (:service-id latest-descriptor) source-tokens)) result))) :router-metrics-helpers (pc/fnk [[:state passwords router-metrics-agent]] (let [password (first passwords)] {:decryptor (fn router-metrics-decryptor [data] (utils/compressed-bytes->map data password)) :encryptor (fn router-metrics-encryptor [data] (utils/map->compressed-bytes data password)) :router-metrics-state-fn (fn router-metrics-state [] @router-metrics-agent) :service-id->metrics-fn (fn service-id->metrics [] (metrics-sync/agent->service-id->metrics router-metrics-agent)) :service-id->router-id->metrics (fn service-id->router-id->metrics [service-id] (metrics-sync/agent->service-id->router-id->metrics router-metrics-agent service-id))})) :service-description->service-id (pc/fnk [[:state service-id-prefix]] (fn service-description->service-id [service-description] (sd/service-description->service-id service-id-prefix service-description))) :service-id->idle-timeout (pc/fnk [[:settings [:token-config token-defaults]] service-id->service-description-fn service-id->source-tokens-entries-fn token->token-hash token->token-metadata] (fn service-id->idle-timeout [service-id] (sd/service-id->idle-timeout service-id->service-description-fn service-id->source-tokens-entries-fn token->token-hash token->token-metadata token-defaults service-id))) :service-id->password-fn (pc/fnk [[:scheduler service-id->password-fn*]] service-id->password-fn*) :service-id->service-description-fn (pc/fnk [[:scheduler service-id->service-description-fn*]] service-id->service-description-fn*) :service-id->source-tokens-entries-fn (pc/fnk [[:curator kv-store]] (partial sd/service-id->source-tokens-entries kv-store)) :start-new-service-fn (pc/fnk [[:scheduler scheduler] [:state start-service-cache scheduler-interactions-thread-pool] store-service-description-fn] (fn start-new-service [{:keys [service-id] :as descriptor}] (store-service-description-fn descriptor) (scheduler/validate-service scheduler service-id) (service/start-new-service scheduler descriptor start-service-cache scheduler-interactions-thread-pool))) :start-work-stealing-balancer-fn (pc/fnk [[:settings [:work-stealing offer-help-interval-ms reserve-timeout-ms]] [:state instance-rpc-chan router-id] make-inter-router-requests-async-fn router-metrics-helpers] (fn start-work-stealing-balancer [service-id] (let [{:keys [service-id->router-id->metrics]} router-metrics-helpers] (work-stealing/start-work-stealing-balancer instance-rpc-chan reserve-timeout-ms offer-help-interval-ms service-id->router-id->metrics make-inter-router-requests-async-fn router-id service-id)))) :stop-work-stealing-balancer-fn (pc/fnk [] (fn stop-work-stealing-balancer [service-id work-stealing-chan-map] (log/info "stopping work-stealing balancer for" service-id) (async/go (when-let [exit-chan (get work-stealing-chan-map [:exit-chan])] (async/>! exit-chan :exit))))) :store-service-description-fn (pc/fnk [[:curator kv-store] validate-service-description-fn] (fn store-service-description [{:keys [core-service-description service-id]}] (sd/store-core kv-store service-id core-service-description validate-service-description-fn))) :store-source-tokens-fn (pc/fnk [[:curator kv-store] synchronize-fn] (fn store-source-tokens-fn [service-id source-tokens] (sd/store-source-tokens! synchronize-fn kv-store service-id source-tokens))) :synchronize-fn (pc/fnk [[:curator curator] [:settings [:zookeeper base-path mutex-timeout-ms]]] (fn synchronize-fn [path f] (let [lock-path (str base-path "/" path)] (curator/synchronize curator lock-path mutex-timeout-ms f)))) :token->service-description-template (pc/fnk [[:curator kv-store]] (fn token->service-description-template [token] (sd/token->service-description-template kv-store token :error-on-missing false))) :token->token-hash (pc/fnk [[:curator kv-store]] (fn token->token-hash [token] (sd/token->token-hash kv-store token))) :token->token-metadata (pc/fnk [[:curator kv-store]] (fn token->token-metadata [token] (sd/token->token-metadata kv-store token :error-on-missing false))) :validate-service-description-fn (pc/fnk [[:state service-description-builder]] (fn validate-service-description [service-description] (sd/validate service-description-builder service-description {}))) :waiter-request?-fn (pc/fnk [[:state waiter-hostnames]] (let [local-router (InetAddress/getLocalHost) waiter-router-hostname (.getCanonicalHostName local-router) waiter-router-ip (.getHostAddress local-router) hostnames (conj waiter-hostnames waiter-router-hostname waiter-router-ip)] (waiter-request?-factory hostnames))) :websocket-request-auth-cookie-attacher (pc/fnk [[:state passwords router-id]] (fn websocket-request-auth-cookie-attacher [request] (ws/inter-router-request-middleware router-id (first passwords) request))) :websocket-request-acceptor (pc/fnk [[:state passwords]] (fn websocket-request-acceptor [^ServletUpgradeRequest request ^ServletUpgradeResponse response] (.setHeader response "x-cid" (cid/get-correlation-id)) (if (ws/request-authenticator (first passwords) request response) (ws/request-subprotocol-acceptor request response) false)))}) (def daemons {:autoscaler (pc/fnk [[:curator leader?-fn] [:routines router-metrics-helpers service-id->service-description-fn] [:scheduler scheduler] [:settings [:scaling autoscaler-interval-ms]] [:state scheduler-interactions-thread-pool] autoscaling-multiplexer router-state-maintainer] (let [service-id->metrics-fn (:service-id->metrics-fn router-metrics-helpers) {{:keys [router-state-push-mult]} :maintainer} router-state-maintainer {:keys [executor-multiplexer-chan]} autoscaling-multiplexer] (scaling/autoscaler-goroutine {} leader?-fn service-id->metrics-fn executor-multiplexer-chan scheduler autoscaler-interval-ms scaling/scale-service service-id->service-description-fn router-state-push-mult scheduler-interactions-thread-pool))) :autoscaling-multiplexer (pc/fnk [[:routines delegate-instance-kill-request-fn peers-acknowledged-blacklist-requests-fn service-id->service-description-fn] [:scheduler scheduler] [:settings [:scaling quanta-constraints]] [:state instance-rpc-chan scheduler-interactions-thread-pool scaling-timeout-config] router-state-maintainer] (let [{{:keys [notify-instance-killed-fn]} :maintainer} router-state-maintainer] (scaling/service-scaling-multiplexer (fn scaling-executor-factory [service-id] (scaling/service-scaling-executor notify-instance-killed-fn peers-acknowledged-blacklist-requests-fn delegate-instance-kill-request-fn service-id->service-description-fn scheduler instance-rpc-chan quanta-constraints scaling-timeout-config scheduler-interactions-thread-pool service-id)) {}))) :codahale-reporters (pc/fnk [[:settings [:metrics-config codahale-reporters]]] (pc/map-vals (fn make-codahale-reporter [{:keys [factory-fn] :as reporter-config}] (let [resolved-factory-fn (utils/resolve-symbol! factory-fn) reporter-instance (resolved-factory-fn reporter-config)] (when-not (satisfies? reporter/CodahaleReporter reporter-instance) (throw (ex-info "Reporter factory did not create an instance of CodahaleReporter" {:reporter-config reporter-config :reporter-instance reporter-instance :resolved-factory-fn resolved-factory-fn}))) reporter-instance)) codahale-reporters)) :fallback-maintainer (pc/fnk [[:state fallback-state-atom] router-state-maintainer] (let [{{:keys [router-state-push-mult]} :maintainer} router-state-maintainer router-state-chan (async/tap router-state-push-mult (au/latest-chan))] (descriptor/fallback-maintainer router-state-chan fallback-state-atom))) :gc-for-transient-metrics (pc/fnk [[:routines router-metrics-helpers] [:settings metrics-config] [:state clock local-usage-agent] router-state-maintainer] (let [state-store-atom (atom {}) read-state-fn (fn read-state [_] @state-store-atom) write-state-fn (fn write-state [_ state] (reset! state-store-atom state)) leader?-fn (constantly true) service-gc-go-routine (partial service-gc-go-routine read-state-fn write-state-fn leader?-fn clock) {{:keys [query-state-fn]} :maintainer} router-state-maintainer {:keys [service-id->metrics-fn]} router-metrics-helpers {:keys [service-id->metrics-chan] :as metrics-gc-chans} (metrics/transient-metrics-gc query-state-fn local-usage-agent service-gc-go-routine metrics-config)] (metrics/transient-metrics-data-producer service-id->metrics-chan service-id->metrics-fn metrics-config) metrics-gc-chans)) :interstitial-maintainer (pc/fnk [[:routines service-id->service-description-fn] [:state interstitial-state-atom] router-state-maintainer] (let [{{:keys [router-state-push-mult]} :maintainer} router-state-maintainer router-state-chan (async/tap router-state-push-mult (au/latest-chan)) initial-state {}] (interstitial/interstitial-maintainer service-id->service-description-fn router-state-chan interstitial-state-atom initial-state))) :launch-metrics-maintainer (pc/fnk [[:curator leader?-fn] [:routines service-id->service-description-fn] router-state-maintainer] (let [{{:keys [router-state-push-mult]} :maintainer} router-state-maintainer] (scheduler/start-launch-metrics-maintainer (async/tap router-state-push-mult (au/latest-chan)) leader?-fn service-id->service-description-fn))) :messages (pc/fnk [[:settings {messages nil}]] (when messages (utils/load-messages messages))) :router-list-maintainer (pc/fnk [[:curator discovery] [:settings router-syncer]] (let [{:keys [delay-ms interval-ms]} router-syncer router-chan (au/latest-chan) router-mult-chan (async/mult router-chan)] (state/start-router-syncer discovery router-chan interval-ms delay-ms) {:router-mult-chan router-mult-chan})) :router-metrics-syncer (pc/fnk [[:routines crypt-helpers websocket-request-auth-cookie-attacher] [:settings [:metrics-config inter-router-metrics-idle-timeout-ms metrics-sync-interval-ms router-update-interval-ms]] [:state local-usage-agent router-metrics-agent websocket-client] router-list-maintainer] (let [{:keys [bytes-encryptor]} crypt-helpers router-chan (async/tap (:router-mult-chan router-list-maintainer) (au/latest-chan))] {:metrics-syncer (metrics-sync/setup-metrics-syncer router-metrics-agent local-usage-agent metrics-sync-interval-ms bytes-encryptor) :router-syncer (metrics-sync/setup-router-syncer router-chan router-metrics-agent router-update-interval-ms inter-router-metrics-idle-timeout-ms metrics-sync-interval-ms websocket-client bytes-encryptor websocket-request-auth-cookie-attacher)})) :router-state-maintainer (pc/fnk [[:routines refresh-service-descriptions-fn service-id->service-description-fn] [:scheduler scheduler] [:settings deployment-error-config] [:state router-id scheduler-state-chan] router-list-maintainer] (let [exit-chan (async/chan) router-chan (async/tap (:router-mult-chan router-list-maintainer) (au/latest-chan)) service-id->deployment-error-config-fn #(scheduler/deployment-error-config scheduler %) maintainer (state/start-router-state-maintainer scheduler-state-chan router-chan router-id exit-chan service-id->service-description-fn refresh-service-descriptions-fn service-id->deployment-error-config-fn deployment-error-config)] {:exit-chan exit-chan :maintainer maintainer})) :scheduler-broken-services-gc (pc/fnk [[:curator gc-state-reader-fn gc-state-writer-fn leader?-fn] [:scheduler scheduler] [:settings scheduler-gc-config] [:state clock] router-state-maintainer] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer service-gc-go-routine (partial service-gc-go-routine gc-state-reader-fn gc-state-writer-fn leader?-fn clock)] (scheduler/scheduler-broken-services-gc service-gc-go-routine query-state-fn scheduler scheduler-gc-config))) :scheduler-services-gc (pc/fnk [[:curator gc-state-reader-fn gc-state-writer-fn leader?-fn] [:routines router-metrics-helpers service-id->idle-timeout] [:scheduler scheduler] [:settings scheduler-gc-config] [:state clock] router-state-maintainer] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer {:keys [service-id->metrics-fn]} router-metrics-helpers service-gc-go-routine (partial service-gc-go-routine gc-state-reader-fn gc-state-writer-fn leader?-fn clock)] (scheduler/scheduler-services-gc scheduler query-state-fn service-id->metrics-fn scheduler-gc-config service-gc-go-routine service-id->idle-timeout))) :service-chan-maintainer (pc/fnk [[:routines start-work-stealing-balancer-fn stop-work-stealing-balancer-fn] [:settings blacklist-config instance-request-properties] [:state instance-rpc-chan query-service-maintainer-chan] router-state-maintainer] (let [start-service (fn start-service [service-id] (let [maintainer-chan-map (state/prepare-and-start-service-chan-responder service-id instance-request-properties blacklist-config) workstealing-chan-map (start-work-stealing-balancer-fn service-id)] {:maintainer-chan-map maintainer-chan-map :work-stealing-chan-map workstealing-chan-map})) remove-service (fn remove-service [service-id {:keys [maintainer-chan-map work-stealing-chan-map]}] (state/close-update-state-channel service-id maintainer-chan-map) (stop-work-stealing-balancer-fn service-id work-stealing-chan-map)) retrieve-channel (fn retrieve-channel [channel-map method] (let [method-chan (case method :blacklist [:maintainer-chan-map :blacklist-instance-chan] :kill [:maintainer-chan-map :kill-instance-chan] :offer [:maintainer-chan-map :work-stealing-chan] :query-state [:maintainer-chan-map :query-state-chan] :query-work-stealing [:work-stealing-chan-map :query-chan] :release [:maintainer-chan-map :release-instance-chan] :reserve [:maintainer-chan-map :reserve-instance-chan-in] :update-state [:maintainer-chan-map :update-state-chan])] (get-in channel-map method-chan))) {{:keys [router-state-push-mult]} :maintainer} router-state-maintainer state-chan (au/latest-chan)] (async/tap router-state-push-mult state-chan) (state/start-service-chan-maintainer {} instance-rpc-chan state-chan query-service-maintainer-chan start-service remove-service retrieve-channel))) :state-sources (pc/fnk [[:scheduler scheduler] [:state query-service-maintainer-chan] autoscaler autoscaling-multiplexer gc-for-transient-metrics interstitial-maintainer scheduler-broken-services-gc scheduler-services-gc] {:autoscaler-state (:query-service-state-fn autoscaler) :autoscaling-multiplexer-state (:query-chan autoscaling-multiplexer) :interstitial-maintainer-state (:query-chan interstitial-maintainer) :scheduler-broken-services-gc-state (:query-service-state-fn scheduler-broken-services-gc) :scheduler-services-gc-state (:query-service-state-fn scheduler-services-gc) :scheduler-state (fn scheduler-state-fn [service-id] (scheduler/service-id->state scheduler service-id)) :service-maintainer-state query-service-maintainer-chan :transient-metrics-gc-state (:query-service-state-fn gc-for-transient-metrics)}) :statsd (pc/fnk [[:routines service-id->service-description-fn] [:settings statsd] router-state-maintainer] (when (not= statsd :disabled) (statsd/setup statsd) (let [{:keys [sync-instances-interval-ms]} statsd {{:keys [query-state-fn]} :maintainer} router-state-maintainer] (statsd/start-service-instance-metrics-publisher service-id->service-description-fn query-state-fn sync-instances-interval-ms))))}) (def request-handlers {:app-name-handler-fn (pc/fnk [service-id-handler-fn] service-id-handler-fn) :async-complete-handler-fn (pc/fnk [[:routines async-request-terminate-fn] wrap-router-auth-fn] (wrap-router-auth-fn (fn async-complete-handler-fn [request] (handler/complete-async-handler async-request-terminate-fn request)))) :async-result-handler-fn (pc/fnk [[:routines async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn async-result-handler-fn [request] (handler/async-result-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request)))) :async-status-handler-fn (pc/fnk [[:routines async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn async-status-handler-fn [request] (handler/async-status-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request)))) :blacklist-instance-handler-fn (pc/fnk [[:daemons router-state-maintainer] [:state instance-rpc-chan] wrap-router-auth-fn] (let [{{:keys [notify-instance-killed-fn]} :maintainer} router-state-maintainer] (wrap-router-auth-fn (fn blacklist-instance-handler-fn [request] (handler/blacklist-instance notify-instance-killed-fn instance-rpc-chan request))))) :blacklisted-instances-list-handler-fn (pc/fnk [[:state instance-rpc-chan]] (fn blacklisted-instances-list-handler-fn [{{:keys [service-id]} :route-params :as request}] (handler/get-blacklisted-instances instance-rpc-chan service-id request))) :default-websocket-handler-fn (pc/fnk [[:routines determine-priority-fn service-id->password-fn start-new-service-fn] [:settings instance-request-properties] [:state instance-rpc-chan local-usage-agent passwords websocket-client] wrap-descriptor-fn] (fn default-websocket-handler-fn [request] (let [password (first passwords) make-request-fn (fn make-ws-request [instance request request-properties passthrough-headers end-route metric-group backend-proto proto-version] (ws/make-request websocket-client service-id->password-fn instance request request-properties passthrough-headers end-route metric-group backend-proto proto-version)) process-request-fn (fn process-request-fn [request] (pr/process make-request-fn instance-rpc-chan start-new-service-fn instance-request-properties determine-priority-fn ws/process-response! ws/abort-request-callback-factory local-usage-agent request)) handler (-> process-request-fn (ws/wrap-ws-close-on-error) wrap-descriptor-fn)] (ws/request-handler password handler request)))) :display-settings-handler-fn (pc/fnk [wrap-secure-request-fn settings] (wrap-secure-request-fn (fn display-settings-handler-fn [_] (settings/display-settings settings)))) :favicon-handler-fn (pc/fnk [] (fn favicon-handler-fn [_] {:body (io/input-stream (io/resource "web/favicon.ico")) :content-type "image/png"})) :kill-instance-handler-fn (pc/fnk [[:daemons router-state-maintainer] [:routines peers-acknowledged-blacklist-requests-fn] [:scheduler scheduler] [:state instance-rpc-chan scaling-timeout-config scheduler-interactions-thread-pool] wrap-router-auth-fn] (let [{{:keys [notify-instance-killed-fn]} :maintainer} router-state-maintainer] (wrap-router-auth-fn (fn kill-instance-handler-fn [request] (scaling/kill-instance-handler notify-instance-killed-fn peers-acknowledged-blacklist-requests-fn scheduler instance-rpc-chan scaling-timeout-config scheduler-interactions-thread-pool request))))) :metrics-request-handler-fn (pc/fnk [] (fn metrics-request-handler-fn [request] (handler/metrics-request-handler request))) :not-found-handler-fn (pc/fnk [] handler/not-found-handler) :process-request-fn (pc/fnk [[:routines determine-priority-fn make-basic-auth-fn post-process-async-request-response-fn service-id->password-fn start-new-service-fn] [:settings instance-request-properties] [:state http-clients instance-rpc-chan local-usage-agent interstitial-state-atom] wrap-auth-bypass-fn wrap-descriptor-fn wrap-https-redirect-fn wrap-secure-request-fn wrap-service-discovery-fn] (let [make-request-fn (fn [instance request request-properties passthrough-headers end-route metric-group backend-proto proto-version] (pr/make-request http-clients make-basic-auth-fn service-id->password-fn instance request request-properties passthrough-headers end-route metric-group backend-proto proto-version)) process-response-fn (partial pr/process-http-response post-process-async-request-response-fn) inner-process-request-fn (fn inner-process-request [request] (pr/process make-request-fn instance-rpc-chan start-new-service-fn instance-request-properties determine-priority-fn process-response-fn pr/abort-http-request-callback-factory local-usage-agent request))] (-> inner-process-request-fn pr/wrap-too-many-requests pr/wrap-suspended-service pr/wrap-response-status-metrics (interstitial/wrap-interstitial interstitial-state-atom) wrap-descriptor-fn wrap-secure-request-fn wrap-auth-bypass-fn wrap-https-redirect-fn wrap-service-discovery-fn))) :router-metrics-handler-fn (pc/fnk [[:routines crypt-helpers] [:settings [:metrics-config metrics-sync-interval-ms]] [:state router-metrics-agent]] (let [{:keys [bytes-decryptor bytes-encryptor]} crypt-helpers] (fn router-metrics-handler-fn [request] (metrics-sync/incoming-router-metrics-handler router-metrics-agent metrics-sync-interval-ms bytes-encryptor bytes-decryptor request)))) :service-handler-fn (pc/fnk [[:curator kv-store] [:daemons router-state-maintainer] [:routines allowed-to-manage-service?-fn generate-log-url-fn make-inter-router-requests-sync-fn router-metrics-helpers service-id->service-description-fn service-id->source-tokens-entries-fn] [:scheduler scheduler] [:state router-id scheduler-interactions-thread-pool] wrap-secure-request-fn] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer {:keys [service-id->metrics-fn]} router-metrics-helpers] (wrap-secure-request-fn (fn service-handler-fn [{:as request {:keys [service-id]} :route-params}] (handler/service-handler router-id service-id scheduler kv-store allowed-to-manage-service?-fn generate-log-url-fn make-inter-router-requests-sync-fn service-id->service-description-fn service-id->source-tokens-entries-fn query-state-fn service-id->metrics-fn scheduler-interactions-thread-pool request))))) :service-id-handler-fn (pc/fnk [[:curator kv-store] [:routines store-service-description-fn] wrap-descriptor-fn wrap-secure-request-fn] (-> (fn service-id-handler-fn [request] (handler/service-id-handler request kv-store store-service-description-fn)) wrap-descriptor-fn wrap-secure-request-fn)) :service-list-handler-fn (pc/fnk [[:daemons router-state-maintainer] [:routines prepend-waiter-url router-metrics-helpers service-id->service-description-fn service-id->source-tokens-entries-fn] [:state entitlement-manager] wrap-secure-request-fn] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer {:keys [service-id->metrics-fn]} router-metrics-helpers] (wrap-secure-request-fn (fn service-list-handler-fn [request] (handler/list-services-handler entitlement-manager query-state-fn prepend-waiter-url service-id->service-description-fn service-id->metrics-fn service-id->source-tokens-entries-fn request))))) :service-override-handler-fn (pc/fnk [[:curator kv-store] [:routines allowed-to-manage-service?-fn make-inter-router-requests-sync-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn service-override-handler-fn [{:as request {:keys [service-id]} :route-params}] (handler/override-service-handler kv-store allowed-to-manage-service?-fn make-inter-router-requests-sync-fn service-id request)))) :service-refresh-handler-fn (pc/fnk [[:curator kv-store] wrap-router-auth-fn] (wrap-router-auth-fn (fn service-refresh-handler [{{:keys [service-id]} :route-params {:keys [src-router-id]} :basic-authentication}] (log/info service-id "refresh triggered by router" src-router-id) (sd/fetch-core kv-store service-id :refresh true) (sd/service-id->suspended-state kv-store service-id :refresh true) (sd/service-id->overrides kv-store service-id :refresh true)))) :service-resume-handler-fn (pc/fnk [[:curator kv-store] [:routines allowed-to-manage-service?-fn make-inter-router-requests-sync-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn service-resume-handler-fn [{:as request {:keys [service-id]} :route-params}] (handler/suspend-or-resume-service-handler kv-store allowed-to-manage-service?-fn make-inter-router-requests-sync-fn service-id :resume request)))) :service-suspend-handler-fn (pc/fnk [[:curator kv-store] [:routines allowed-to-manage-service?-fn make-inter-router-requests-sync-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn service-suspend-handler-fn [{:as request {:keys [service-id]} :route-params}] (handler/suspend-or-resume-service-handler kv-store allowed-to-manage-service?-fn make-inter-router-requests-sync-fn service-id :suspend request)))) :service-view-logs-handler-fn (pc/fnk [[:routines generate-log-url-fn] [:scheduler scheduler] wrap-secure-request-fn] (wrap-secure-request-fn (fn service-view-logs-handler-fn [{:as request {:keys [service-id]} :route-params}] (handler/service-view-logs-handler scheduler service-id generate-log-url-fn request)))) :sim-request-handler (pc/fnk [] simulator/handle-sim-request) :state-all-handler-fn (pc/fnk [[:daemons router-state-maintainer] [:state router-id] wrap-secure-request-fn] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer] (wrap-secure-request-fn (fn state-all-handler-fn [request] (handler/get-router-state router-id query-state-fn request))))) :state-autoscaler-handler-fn (pc/fnk [[:daemons autoscaler] [:state router-id] wrap-secure-request-fn] (let [{:keys [query-state-fn]} autoscaler] (wrap-secure-request-fn (fn state-autoscaler-handler-fn [request] (handler/get-query-fn-state router-id query-state-fn request))))) :state-autoscaling-multiplexer-handler-fn (pc/fnk [[:daemons autoscaling-multiplexer] [:state router-id] wrap-secure-request-fn] (let [{:keys [query-chan]} autoscaling-multiplexer] (wrap-secure-request-fn (fn state-autoscaling-multiplexer-handler-fn [request] (handler/get-query-chan-state-handler router-id query-chan request))))) :state-codahale-reporters-handler-fn (pc/fnk [[:daemons codahale-reporters] [:state router-id]] (fn codahale-reporter-state-handler-fn [request] (handler/get-query-fn-state router-id #(pc/map-vals reporter/state codahale-reporters) request))) :state-fallback-handler-fn (pc/fnk [[:daemons fallback-maintainer] [:state router-id] wrap-secure-request-fn] (let [fallback-query-chan (:query-chan fallback-maintainer)] (wrap-secure-request-fn (fn state-fallback-handler-fn [request] (handler/get-query-chan-state-handler router-id fallback-query-chan request))))) :state-gc-for-broken-services (pc/fnk [[:daemons scheduler-broken-services-gc] [:state router-id] wrap-secure-request-fn] (let [{:keys [query-state-fn]} scheduler-broken-services-gc] (wrap-secure-request-fn (fn state-autoscaler-handler-fn [request] (handler/get-query-fn-state router-id query-state-fn request))))) :state-gc-for-services (pc/fnk [[:daemons scheduler-services-gc] [:state router-id] wrap-secure-request-fn] (let [{:keys [query-state-fn]} scheduler-services-gc] (wrap-secure-request-fn (fn state-autoscaler-handler-fn [request] (handler/get-query-fn-state router-id query-state-fn request))))) :state-gc-for-transient-metrics (pc/fnk [[:daemons gc-for-transient-metrics] [:state router-id] wrap-secure-request-fn] (let [{:keys [queryPI:KEY:<KEY>END_PI-statePI:KEY:<KEY>END_PI-fn]} gc-for-transient-metrics] (wrap-secure-request-fn (fn state-autoscaler-handler-fn [request] (handler/get-query-fn-state router-id query-state-fn request))))) :state-interstitial-handler-fn (pc/fnk [[:daemons interstitial-maintainer] [:state router-id] wrap-secure-request-fn] (let [interstitial-query-chan (:query-chan interstitial-maintainer)] (wrap-secure-request-fn (fn state-interstitial-handler-fn [request] (handler/get-query-chan-state-handler router-id interstitial-query-chan request))))) :state-launch-metrics-handler-fn (pc/fnk [[:daemons launch-metrics-maintainer] [:state router-id] wrap-secure-request-fn] (let [query-chan (:query-chan launch-metrics-maintainer)] (wrap-secure-request-fn (fn state-launch-metrics-handler-fn [request] (handler/get-query-chan-state-handler router-id query-chan request))))) :state-kv-store-handler-fn (pc/fnk [[:curator kv-store] [:state router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn kv-store-state-handler-fn [request] (handler/get-kv-store-state router-id kv-store request)))) :state-leader-handler-fn (pc/fnk [[:curator leader?-fn leader-id-fn] [:state router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn leader-state-handler-fn [request] (handler/get-leader-state router-id leader?-fn leader-id-fn request)))) :state-local-usage-handler-fn (pc/fnk [[:state local-usage-agent router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn local-usage-state-handler-fn [request] (handler/get-local-usage-state router-id local-usage-agent request)))) :state-maintainer-handler-fn (pc/fnk [[:daemons router-state-maintainer] [:state router-id] wrap-secure-request-fn] (let [{{:keys [query-state-fn]} :maintainer} router-state-maintainer] (wrap-secure-request-fn (fn maintainer-state-handler-fn [request] (handler/get-chan-latest-state-handler router-id query-state-fn request))))) :state-router-metrics-handler-fn (pc/fnk [[:routines router-metrics-helpers] [:state router-id] wrap-secure-request-fn] (let [router-metrics-state-fn (:router-metrics-state-fn router-metrics-helpers)] (wrap-secure-request-fn (fn r-router-metrics-state-handler-fn [request] (handler/get-router-metrics-state router-id router-metrics-state-fn request))))) :state-scheduler-handler-fn (pc/fnk [[:scheduler scheduler] [:state router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn scheduler-state-handler-fn [request] (handler/get-scheduler-state router-id scheduler request)))) :state-service-handler-fn (pc/fnk [[:daemons state-sources] [:state instance-rpc-chan local-usage-agent router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn service-state-handler-fn [{{:keys [service-id]} :route-params :as request}] (handler/get-service-state router-id instance-rpc-chan local-usage-agent service-id state-sources request)))) :state-statsd-handler-fn (pc/fnk [[:state router-id] wrap-secure-request-fn] (wrap-secure-request-fn (fn state-statsd-handler-fn [request] (handler/get-statsd-state router-id request)))) :status-handler-fn (pc/fnk [] handler/status-handler) :token-handler-fn (pc/fnk [[:curator kv-store] [:routines make-inter-router-requests-sync-fn synchronize-fn validate-service-description-fn] [:settings [:token-config history-length limit-per-owner]] [:state clock entitlement-manager token-cluster-calculator token-root waiter-hostnames] wrap-secure-request-fn] (wrap-secure-request-fn (fn token-handler-fn [request] (token/handle-token-request clock synchronize-fn kv-store token-cluster-calculator token-root history-length limit-per-owner waiter-hostnames entitlement-manager make-inter-router-requests-sync-fn validate-service-description-fn request)))) :token-list-handler-fn (pc/fnk [[:curator kv-store] [:state entitlement-manager] wrap-secure-request-fn] (wrap-secure-request-fn (fn token-handler-fn [request] (token/handle-list-tokens-request kv-store entitlement-manager request)))) :token-owners-handler-fn (pc/fnk [[:curator kv-store] wrap-secure-request-fn] (wrap-secure-request-fn (fn token-owners-handler-fn [request] (token/handle-list-token-owners-request kv-store request)))) :token-refresh-handler-fn (pc/fnk [[:curator kv-store] wrap-router-auth-fn] (wrap-router-auth-fn (fn token-refresh-handler-fn [request] (token/handle-refresh-token-request kv-store request)))) :token-reindex-handler-fn (pc/fnk [[:curator kv-store] [:routines list-tokens-fn make-inter-router-requests-sync-fn synchronize-fn] wrap-secure-request-fn] (wrap-secure-request-fn (fn token-handler-fn [request] (token/handle-reindex-tokens-request synchronize-fn make-inter-router-requests-sync-fn kv-store list-tokens-fn request)))) :waiter-auth-handler-fn (pc/fnk [wrap-secure-request-fn] (wrap-secure-request-fn (fn waiter-auth-handler-fn [request] {:body (str (:authorization/user request)), :status 200}))) :waiter-acknowledge-consent-handler-fn (pc/fnk [[:routines service-description->service-id token->service-description-template token->token-metadata] [:settings consent-expiry-days] [:state clock passwords] wrap-secure-request-fn] (let [password (first passwords)] (letfn [(add-encoded-cookie [response cookie-name value expiry-days] (cookie-support/add-encoded-cookie response password cookie-name value expiry-days)) (consent-cookie-value [mode service-id token token-metadata] (sd/consent-cookie-value clock mode service-id token token-metadata))] (wrap-secure-request-fn (fn inner-waiter-acknowledge-consent-handler-fn [request] (handler/acknowledge-consent-handler token->service-description-template token->token-metadata service-description->service-id consent-cookie-value add-encoded-cookie consent-expiry-days request)))))) :waiter-request-consent-handler-fn (pc/fnk [[:routines service-description->service-id token->service-description-template] [:settings consent-expiry-days] wrap-secure-request-fn] (wrap-secure-request-fn (fn waiter-request-consent-handler-fn [request] (handler/request-consent-handler token->service-description-template service-description->service-id consent-expiry-days request)))) :waiter-request-interstitial-handler-fn (pc/fnk [wrap-secure-request-fn] (wrap-secure-request-fn (fn waiter-request-interstitial-handler-fn [request] (interstitial/display-interstitial-handler request)))) :welcome-handler-fn (pc/fnk [settings] (partial handler/welcome-handler settings)) :work-stealing-handler-fn (pc/fnk [[:state instance-rpc-chan] wrap-router-auth-fn] (wrap-router-auth-fn (fn [request] (handler/work-stealing-handler instance-rpc-chan request)))) :wrap-auth-bypass-fn (pc/fnk [] (fn wrap-auth-bypass-fn [handler] (fn [{:keys [waiter-discovery] :as request}] (let [{:keys [service-parameter-template token waiter-headers]} waiter-discovery {:strs [authentication] :as service-description} service-parameter-template authentication-disabled? (= authentication "disabled")] (cond (contains? waiter-headers "x-waiter-authentication") (do (log/info "x-waiter-authentication is not supported as an on-the-fly header" {:service-description service-description, :token token}) (utils/clj->json-response {:error "An authentication parameter is not supported for on-the-fly headers"} :status 400)) ;; ensure service description formed comes entirely from the token by ensuring absence of on-the-fly headers (and authentication-disabled? (some sd/service-parameter-keys (-> waiter-headers headers/drop-waiter-header-prefix keys))) (do (log/info "request cannot proceed as it is mixing an authentication disabled token with on-the-fly headers" {:service-description service-description, :token token}) (utils/clj->json-response {:error "An authentication disabled token may not be combined with on-the-fly headers"} :status 400)) authentication-disabled? (do (log/info "request configured to skip authentication") (handler (assoc request :skip-authentication true))) :else (handler request)))))) :wrap-descriptor-fn (pc/fnk [[:routines request->descriptor-fn start-new-service-fn] [:state fallback-state-atom]] (fn wrap-descriptor-fn [handler] (descriptor/wrap-descriptor handler request->descriptor-fn start-new-service-fn fallback-state-atom))) :wrap-https-redirect-fn (pc/fnk [] (fn wrap-https-redirect-fn [handler] (fn [request] (cond (and (get-in request [:waiter-discovery :token-metadata "https-redirect"]) ;; ignore websocket requests (= :http (utils/request->scheme request))) (do (log/info "triggering ssl redirect") (-> (ssl/ssl-redirect-response request {}) (rr/header "server" (utils/get-current-server-name)))) :else (handler request))))) :wrap-router-auth-fn (pc/fnk [[:state passwords router-id]] (fn wrap-router-auth-fn [handler] (fn [request] (let [router-comm-authenticated? (fn router-comm-authenticated? [source-id secret-word] (let [expected-word (utils/generate-secret-word source-id router-id passwords) authenticated? (= expected-word secret-word)] (log/info "Authenticating inter-router communication from" source-id) (if-not authenticated? (log/info "inter-router request authentication failed!" {:actual secret-word, :expected expected-word}) {:src-router-id source-id}))) basic-auth-handler (basic-authentication/wrap-basic-authentication handler router-comm-authenticated?)] (basic-auth-handler request))))) :wrap-secure-request-fn (pc/fnk [[:routines authentication-method-wrapper-fn waiter-request?-fn] [:settings cors-config] [:state cors-validator]] (let [{:keys [exposed-headers]} cors-config] (fn wrap-secure-request-fn [handler] (let [handler (-> handler (cors/wrap-cors-request cors-validator waiter-request?-fn exposed-headers) authentication-method-wrapper-fn)] (fn inner-wrap-secure-request-fn [{:keys [uri] :as request}] (log/debug "secure request received at" uri) (handler request)))))) :wrap-service-discovery-fn (pc/fnk [[:curator kv-store] [:settings [:token-config token-defaults]] [:state waiter-hostnames]] (fn wrap-service-discovery-fn [handler] (fn [{:keys [headers] :as request}] ;; TODO optimization opportunity to avoid this re-computation later in the chain (let [discovered-parameters (sd/discover-service-parameters kv-store token-defaults waiter-hostnames headers)] (handler (assoc request :waiter-discovery discovered-parameters))))))})
[ { "context": "all]))\n\n\n(defn setup\n []\n (h/create-test-user! \"success+2@simulator.amazonses.com\")\n (h/delete-test-user! \"success+2@simulator.ama", "end": 401, "score": 0.9999274611473083, "start": 368, "tag": "EMAIL", "value": "success+2@simulator.amazonses.com" }, { "context": "simulator.amazonses.com\")\n (h/delete-test-user! \"success+2@simulator.amazonses.com\")\n (h/create-test-user! \"success+3@simulator.ama", "end": 461, "score": 0.9999282360076904, "start": 428, "tag": "EMAIL", "value": "success+2@simulator.amazonses.com" }, { "context": "simulator.amazonses.com\")\n (h/create-test-user! \"success+3@simulator.amazonses.com\")\n (h/create-test-user! \"success+4@simulator.ama", "end": 521, "score": 0.999926745891571, "start": 488, "tag": "EMAIL", "value": "success+3@simulator.amazonses.com" }, { "context": "simulator.amazonses.com\")\n (h/create-test-user! \"success+4@simulator.amazonses.com\")\n (h/create-test-user! \"success+5@simulator.ama", "end": 581, "score": 0.9999262094497681, "start": 548, "tag": "EMAIL", "value": "success+4@simulator.amazonses.com" }, { "context": "simulator.amazonses.com\")\n (h/create-test-user! \"success+5@simulator.amazonses.com\")\n (h/create-test-user! \"success+6@simulator.ama", "end": 641, "score": 0.9999242424964905, "start": 608, "tag": "EMAIL", "value": "success+5@simulator.amazonses.com" }, { "context": "simulator.amazonses.com\")\n (h/create-test-user! \"success+6@simulator.amazonses.com\"))\n\n(defn fixture [test]\n (h/ensure-empty-table)", "end": 701, "score": 0.9999242424964905, "start": 668, "tag": "EMAIL", "value": "success+6@simulator.amazonses.com" }, { "context": " {:user/email-address \"success+1@simulator.amazonses.com\"}}})\n user-id (user/id \"success+1@simula", "end": 1247, "score": 0.9999257922172546, "start": 1214, "tag": "EMAIL", "value": "success+1@simulator.amazonses.com" }, { "context": "or.amazonses.com\"}}})\n user-id (user/id \"success+1@simulator.amazonses.com\")\n user (user/fetch user-id)\n a", "end": 1314, "score": 0.9999247193336487, "start": 1281, "tag": "EMAIL", "value": "success+1@simulator.amazonses.com" }, { "context": " {:user/email-address \"success+2@simulator.amazonses.com\"}}})\n user-id (user/id \"success+2@simula", "end": 2286, "score": 0.999924898147583, "start": 2253, "tag": "EMAIL", "value": "success+2@simulator.amazonses.com" }, { "context": "or.amazonses.com\"}}})\n user-id (user/id \"success+2@simulator.amazonses.com\")\n user (user/fetch user-id)\n a", "end": 2353, "score": 0.9999175667762756, "start": 2320, "tag": "EMAIL", "value": "success+2@simulator.amazonses.com" }, { "context": " {:user/email-address \"success+3@simulator.amazonses.com\"}}})\n user-id (user/id \"success+3@simula", "end": 3274, "score": 0.9999242424964905, "start": 3241, "tag": "EMAIL", "value": "success+3@simulator.amazonses.com" }, { "context": "or.amazonses.com\"}}})\n user-id (user/id \"success+3@simulator.amazonses.com\")\n user (user/fetch user-id)\n a", "end": 3341, "score": 0.9999191164970398, "start": 3308, "tag": "EMAIL", "value": "success+3@simulator.amazonses.com" }, { "context": " {:user/email-address \"success+4@simulator.amazonses.com\"}}})\n user-id (user/id \"success+4@simula", "end": 4328, "score": 0.9999269247055054, "start": 4295, "tag": "EMAIL", "value": "success+4@simulator.amazonses.com" }, { "context": "or.amazonses.com\"}}})\n user-id (user/id \"success+4@simulator.amazonses.com\")\n user (user/fetch user-id)\n a", "end": 4395, "score": 0.9999225735664368, "start": 4362, "tag": "EMAIL", "value": "success+4@simulator.amazonses.com" }, { "context": "[request (h/request\n {:session \"success+5@simulator.amazonses.com\"\n :command {:initialise-author", "end": 5387, "score": 0.9999173879623413, "start": 5354, "tag": "EMAIL", "value": "success+5@simulator.amazonses.com" }, { "context": " {:user/email-address \"success+5@simulator.amazonses.com\"}}})\n user-id (user/id \"success+5@simula", "end": 5538, "score": 0.999922513961792, "start": 5505, "tag": "EMAIL", "value": "success+5@simulator.amazonses.com" }, { "context": "or.amazonses.com\"}}})\n user-id (user/id \"success+5@simulator.amazonses.com\")\n user (user/fetch user-id)\n a", "end": 5605, "score": 0.999921441078186, "start": 5572, "tag": "EMAIL", "value": "success+5@simulator.amazonses.com" }, { "context": "[request (h/request\n {:session \"success+5@simulator.amazonses.com\"\n :command {:initialise-author", "end": 6599, "score": 0.9999239444732666, "start": 6566, "tag": "EMAIL", "value": "success+5@simulator.amazonses.com" }, { "context": " {:user/email-address \"success+6@simulator.amazonses.com\"}}})\n user-id (user/id \"success+6@simula", "end": 6750, "score": 0.9999262094497681, "start": 6717, "tag": "EMAIL", "value": "success+6@simulator.amazonses.com" }, { "context": "or.amazonses.com\"}}})\n user-id (user/id \"success+6@simulator.amazonses.com\")\n user (user/fetch user-id)\n a", "end": 6817, "score": 0.9999217391014099, "start": 6784, "tag": "EMAIL", "value": "success+6@simulator.amazonses.com" }, { "context": " :session {:current-user-id (user/id \"success+5@simulator.amazonses.com\")}}\n (h/decode :transit body)))\n ", "end": 7284, "score": 0.9999206066131592, "start": 7251, "tag": "EMAIL", "value": "success+5@simulator.amazonses.com" } ]
api/test/feature/flow/command/initialise_authorisation_attempt_test.clj
kgxsz/flow
0
(ns flow.command.initialise-authorisation-attempt-test (:require [flow.core :refer :all] [flow.entity.authorisation :as authorisation] [flow.entity.user :as user] [flow.domain.user-management :as user-management] [flow.helpers :as h] [clojure.test :refer :all])) (defn setup [] (h/create-test-user! "success+2@simulator.amazonses.com") (h/delete-test-user! "success+2@simulator.amazonses.com") (h/create-test-user! "success+3@simulator.amazonses.com") (h/create-test-user! "success+4@simulator.amazonses.com") (h/create-test-user! "success+5@simulator.amazonses.com") (h/create-test-user! "success+6@simulator.amazonses.com")) (defn fixture [test] (h/ensure-empty-table) (setup) (test) (h/ensure-empty-table)) (use-fixtures :each fixture) (deftest test-initialise-authorisation-attempt (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for a non-existent user." (let [request (h/request {:session :unauthorised :command {:initialise-authorisation-attempt {:user/email-address "success+1@simulator.amazonses.com"}}}) user-id (user/id "success+1@simulator.amazonses.com") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))) (is (= nil user user')) (is (empty? authorisations)) (is (empty? authorisations')))) (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for an existing user who has prevously been deleted." (let [request (h/request {:session :unauthorised :command {:initialise-authorisation-attempt {:user/email-address "success+2@simulator.amazonses.com"}}}) user-id (user/id "success+2@simulator.amazonses.com") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))) (is (= user user')) (is (empty? authorisations)) (is (empty? authorisations')))) (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for an existing user and no session is provided." (let [request (h/request {:command {:initialise-authorisation-attempt {:user/email-address "success+3@simulator.amazonses.com"}}}) user-id (user/id "success+3@simulator.amazonses.com") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))) (is (= user user')) (is (= 0 (count authorisations))) (is (= 1 (count authorisations'))))) (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for an existing user and an unauthorised session is provided." (let [request (h/request {:session :unauthorised :command {:initialise-authorisation-attempt {:user/email-address "success+4@simulator.amazonses.com"}}}) user-id (user/id "success+4@simulator.amazonses.com") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))) (is (= user user')) (is (= 0 (count authorisations))) (is (= 1 (count authorisations'))))) (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for an existing user and an authorised session is provided, where the authorised user happens to be the same user upon whom the authorisation attempt is being initialised." (let [request (h/request {:session "success+5@simulator.amazonses.com" :command {:initialise-authorisation-attempt {:user/email-address "success+5@simulator.amazonses.com"}}}) user-id (user/id "success+5@simulator.amazonses.com") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id user-id}} (h/decode :transit body))) (is (= user user')) (is (= 0 (count authorisations))) (is (= 1 (count authorisations'))))) (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for an existing user and an authorised session is provided, where the authorised user is distinct from the user upon whom the authorisation attempt is being initialised." (let [request (h/request {:session "success+5@simulator.amazonses.com" :command {:initialise-authorisation-attempt {:user/email-address "success+6@simulator.amazonses.com"}}}) user-id (user/id "success+6@simulator.amazonses.com") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id (user/id "success+5@simulator.amazonses.com")}} (h/decode :transit body))) (is (= user user')) (is (= 0 (count authorisations))) (is (= 1 (count authorisations'))))) )
98366
(ns flow.command.initialise-authorisation-attempt-test (:require [flow.core :refer :all] [flow.entity.authorisation :as authorisation] [flow.entity.user :as user] [flow.domain.user-management :as user-management] [flow.helpers :as h] [clojure.test :refer :all])) (defn setup [] (h/create-test-user! "<EMAIL>") (h/delete-test-user! "<EMAIL>") (h/create-test-user! "<EMAIL>") (h/create-test-user! "<EMAIL>") (h/create-test-user! "<EMAIL>") (h/create-test-user! "<EMAIL>")) (defn fixture [test] (h/ensure-empty-table) (setup) (test) (h/ensure-empty-table)) (use-fixtures :each fixture) (deftest test-initialise-authorisation-attempt (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for a non-existent user." (let [request (h/request {:session :unauthorised :command {:initialise-authorisation-attempt {:user/email-address "<EMAIL>"}}}) user-id (user/id "<EMAIL>") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))) (is (= nil user user')) (is (empty? authorisations)) (is (empty? authorisations')))) (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for an existing user who has prevously been deleted." (let [request (h/request {:session :unauthorised :command {:initialise-authorisation-attempt {:user/email-address "<EMAIL>"}}}) user-id (user/id "<EMAIL>") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))) (is (= user user')) (is (empty? authorisations)) (is (empty? authorisations')))) (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for an existing user and no session is provided." (let [request (h/request {:command {:initialise-authorisation-attempt {:user/email-address "<EMAIL>"}}}) user-id (user/id "<EMAIL>") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))) (is (= user user')) (is (= 0 (count authorisations))) (is (= 1 (count authorisations'))))) (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for an existing user and an unauthorised session is provided." (let [request (h/request {:session :unauthorised :command {:initialise-authorisation-attempt {:user/email-address "<EMAIL>"}}}) user-id (user/id "<EMAIL>") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))) (is (= user user')) (is (= 0 (count authorisations))) (is (= 1 (count authorisations'))))) (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for an existing user and an authorised session is provided, where the authorised user happens to be the same user upon whom the authorisation attempt is being initialised." (let [request (h/request {:session "<EMAIL>" :command {:initialise-authorisation-attempt {:user/email-address "<EMAIL>"}}}) user-id (user/id "<EMAIL>") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id user-id}} (h/decode :transit body))) (is (= user user')) (is (= 0 (count authorisations))) (is (= 1 (count authorisations'))))) (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for an existing user and an authorised session is provided, where the authorised user is distinct from the user upon whom the authorisation attempt is being initialised." (let [request (h/request {:session "<EMAIL>" :command {:initialise-authorisation-attempt {:user/email-address "<EMAIL>"}}}) user-id (user/id "<EMAIL>") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id (user/id "<EMAIL>")}} (h/decode :transit body))) (is (= user user')) (is (= 0 (count authorisations))) (is (= 1 (count authorisations'))))) )
true
(ns flow.command.initialise-authorisation-attempt-test (:require [flow.core :refer :all] [flow.entity.authorisation :as authorisation] [flow.entity.user :as user] [flow.domain.user-management :as user-management] [flow.helpers :as h] [clojure.test :refer :all])) (defn setup [] (h/create-test-user! "PI:EMAIL:<EMAIL>END_PI") (h/delete-test-user! "PI:EMAIL:<EMAIL>END_PI") (h/create-test-user! "PI:EMAIL:<EMAIL>END_PI") (h/create-test-user! "PI:EMAIL:<EMAIL>END_PI") (h/create-test-user! "PI:EMAIL:<EMAIL>END_PI") (h/create-test-user! "PI:EMAIL:<EMAIL>END_PI")) (defn fixture [test] (h/ensure-empty-table) (setup) (test) (h/ensure-empty-table)) (use-fixtures :each fixture) (deftest test-initialise-authorisation-attempt (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for a non-existent user." (let [request (h/request {:session :unauthorised :command {:initialise-authorisation-attempt {:user/email-address "PI:EMAIL:<EMAIL>END_PI"}}}) user-id (user/id "PI:EMAIL:<EMAIL>END_PI") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))) (is (= nil user user')) (is (empty? authorisations)) (is (empty? authorisations')))) (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for an existing user who has prevously been deleted." (let [request (h/request {:session :unauthorised :command {:initialise-authorisation-attempt {:user/email-address "PI:EMAIL:<EMAIL>END_PI"}}}) user-id (user/id "PI:EMAIL:<EMAIL>END_PI") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))) (is (= user user')) (is (empty? authorisations)) (is (empty? authorisations')))) (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for an existing user and no session is provided." (let [request (h/request {:command {:initialise-authorisation-attempt {:user/email-address "PI:EMAIL:<EMAIL>END_PI"}}}) user-id (user/id "PI:EMAIL:<EMAIL>END_PI") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))) (is (= user user')) (is (= 0 (count authorisations))) (is (= 1 (count authorisations'))))) (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for an existing user and an unauthorised session is provided." (let [request (h/request {:session :unauthorised :command {:initialise-authorisation-attempt {:user/email-address "PI:EMAIL:<EMAIL>END_PI"}}}) user-id (user/id "PI:EMAIL:<EMAIL>END_PI") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))) (is (= user user')) (is (= 0 (count authorisations))) (is (= 1 (count authorisations'))))) (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for an existing user and an authorised session is provided, where the authorised user happens to be the same user upon whom the authorisation attempt is being initialised." (let [request (h/request {:session "PI:EMAIL:<EMAIL>END_PI" :command {:initialise-authorisation-attempt {:user/email-address "PI:EMAIL:<EMAIL>END_PI"}}}) user-id (user/id "PI:EMAIL:<EMAIL>END_PI") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id user-id}} (h/decode :transit body))) (is (= user user')) (is (= 0 (count authorisations))) (is (= 1 (count authorisations'))))) (testing "The handler negotiates the initialise-authorisation-attempt command when the command is being made for an existing user and an authorised session is provided, where the authorised user is distinct from the user upon whom the authorisation attempt is being initialised." (let [request (h/request {:session "PI:EMAIL:<EMAIL>END_PI" :command {:initialise-authorisation-attempt {:user/email-address "PI:EMAIL:<EMAIL>END_PI"}}}) user-id (user/id "PI:EMAIL:<EMAIL>END_PI") user (user/fetch user-id) authorisations (h/find-test-authorisations user-id) {:keys [status headers body] :as response} (handler request) user' (user/fetch user-id) authorisations' (h/find-test-authorisations user-id)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id (user/id "PI:EMAIL:<EMAIL>END_PI")}} (h/decode :transit body))) (is (= user user')) (is (= 0 (count authorisations))) (is (= 1 (count authorisations'))))) )
[ { "context": "nerate gen/string-alphanumeric 10)\n key \"message\"\n value \"Hello World!!\"]\n (send :de", "end": 1498, "score": 0.9915332198143005, "start": 1491, "tag": "KEY", "value": "message" }, { "context": "nerate gen/string-alphanumeric 10)\n key \"message\"\n value \"Hello World!!\"\n partit", "end": 1972, "score": 0.9913157224655151, "start": 1965, "tag": "KEY", "value": "message" } ]
test/ziggurat/producer_test.clj
led/ziggurat
0
(ns ziggurat.producer-test (:require [clojure.test :refer :all] [ziggurat.streams :refer [start-streams stop-streams]] [ziggurat.fixtures :as fix :refer [*producer-properties* *consumer-properties*]] [ziggurat.config :refer [ziggurat-config]] [ziggurat.producer :refer [producer-properties-map send kafka-producers]] [clojure.test.check.generators :as gen]) (:import (org.apache.kafka.streams.integration.utils IntegrationTestUtils) (org.apache.kafka.clients.producer KafkaProducer))) (use-fixtures :once fix/mount-only-config-and-producer) (defn stream-router-config-without-producer []) (:stream-router {:default {:application-id "test" :bootstrap-servers "localhost:9092" :stream-threads-count [1 :int] :origin-topic "topic" :proto-class "flatland.protobuf.test.Example$Photo" :channels {:channel-1 {:worker-count [10 :int] :retry {:count [5 :int] :enabled [true :bool]}}}}}) (deftest send-data-with-topic-and-value-test (with-redefs [kafka-producers (hash-map :default (KafkaProducer. *producer-properties*))] (let [topic (gen/generate gen/string-alphanumeric 10) key "message" value "Hello World!!"] (send :default topic key value) (let [result (IntegrationTestUtils/waitUntilMinKeyValueRecordsReceived *consumer-properties* topic 1 2000)] (is (= value (.value (first result)))))))) (deftest send-data-with-topic-key-partition-and-value-test (with-redefs [kafka-producers (hash-map :default (KafkaProducer. *producer-properties*))] (let [topic (gen/generate gen/string-alphanumeric 10) key "message" value "Hello World!!" partition (int 0)] (send :default topic partition key value) (let [result (IntegrationTestUtils/waitUntilMinKeyValueRecordsReceived *consumer-properties* topic 1 2000)] (is (= value (.value (first result)))))))) (deftest send-throws-exception-when-no-producers-are-configured (with-redefs [kafka-producers {}] (let [topic "test-topic" key "message" value "Hello World!! from non-existant Kafka Producers"] (is (not-empty (try (send :default topic key value) (catch Exception e (ex-data e)))))))) (deftest producer-properties-map-is-empty-if-no-producers-configured ; Here ziggurat-config has been substituted with a custom map which ; does not have any valid producer configs. (with-redefs [ziggurat-config stream-router-config-without-producer] (is (empty? (producer-properties-map))))) (deftest producer-properties-map-is-not-empty-if-producers-are-configured ; Here the config is read from config.test.edn which contains ; valid producer configs. (is (seq (producer-properties-map))))
36098
(ns ziggurat.producer-test (:require [clojure.test :refer :all] [ziggurat.streams :refer [start-streams stop-streams]] [ziggurat.fixtures :as fix :refer [*producer-properties* *consumer-properties*]] [ziggurat.config :refer [ziggurat-config]] [ziggurat.producer :refer [producer-properties-map send kafka-producers]] [clojure.test.check.generators :as gen]) (:import (org.apache.kafka.streams.integration.utils IntegrationTestUtils) (org.apache.kafka.clients.producer KafkaProducer))) (use-fixtures :once fix/mount-only-config-and-producer) (defn stream-router-config-without-producer []) (:stream-router {:default {:application-id "test" :bootstrap-servers "localhost:9092" :stream-threads-count [1 :int] :origin-topic "topic" :proto-class "flatland.protobuf.test.Example$Photo" :channels {:channel-1 {:worker-count [10 :int] :retry {:count [5 :int] :enabled [true :bool]}}}}}) (deftest send-data-with-topic-and-value-test (with-redefs [kafka-producers (hash-map :default (KafkaProducer. *producer-properties*))] (let [topic (gen/generate gen/string-alphanumeric 10) key "<KEY>" value "Hello World!!"] (send :default topic key value) (let [result (IntegrationTestUtils/waitUntilMinKeyValueRecordsReceived *consumer-properties* topic 1 2000)] (is (= value (.value (first result)))))))) (deftest send-data-with-topic-key-partition-and-value-test (with-redefs [kafka-producers (hash-map :default (KafkaProducer. *producer-properties*))] (let [topic (gen/generate gen/string-alphanumeric 10) key "<KEY>" value "Hello World!!" partition (int 0)] (send :default topic partition key value) (let [result (IntegrationTestUtils/waitUntilMinKeyValueRecordsReceived *consumer-properties* topic 1 2000)] (is (= value (.value (first result)))))))) (deftest send-throws-exception-when-no-producers-are-configured (with-redefs [kafka-producers {}] (let [topic "test-topic" key "message" value "Hello World!! from non-existant Kafka Producers"] (is (not-empty (try (send :default topic key value) (catch Exception e (ex-data e)))))))) (deftest producer-properties-map-is-empty-if-no-producers-configured ; Here ziggurat-config has been substituted with a custom map which ; does not have any valid producer configs. (with-redefs [ziggurat-config stream-router-config-without-producer] (is (empty? (producer-properties-map))))) (deftest producer-properties-map-is-not-empty-if-producers-are-configured ; Here the config is read from config.test.edn which contains ; valid producer configs. (is (seq (producer-properties-map))))
true
(ns ziggurat.producer-test (:require [clojure.test :refer :all] [ziggurat.streams :refer [start-streams stop-streams]] [ziggurat.fixtures :as fix :refer [*producer-properties* *consumer-properties*]] [ziggurat.config :refer [ziggurat-config]] [ziggurat.producer :refer [producer-properties-map send kafka-producers]] [clojure.test.check.generators :as gen]) (:import (org.apache.kafka.streams.integration.utils IntegrationTestUtils) (org.apache.kafka.clients.producer KafkaProducer))) (use-fixtures :once fix/mount-only-config-and-producer) (defn stream-router-config-without-producer []) (:stream-router {:default {:application-id "test" :bootstrap-servers "localhost:9092" :stream-threads-count [1 :int] :origin-topic "topic" :proto-class "flatland.protobuf.test.Example$Photo" :channels {:channel-1 {:worker-count [10 :int] :retry {:count [5 :int] :enabled [true :bool]}}}}}) (deftest send-data-with-topic-and-value-test (with-redefs [kafka-producers (hash-map :default (KafkaProducer. *producer-properties*))] (let [topic (gen/generate gen/string-alphanumeric 10) key "PI:KEY:<KEY>END_PI" value "Hello World!!"] (send :default topic key value) (let [result (IntegrationTestUtils/waitUntilMinKeyValueRecordsReceived *consumer-properties* topic 1 2000)] (is (= value (.value (first result)))))))) (deftest send-data-with-topic-key-partition-and-value-test (with-redefs [kafka-producers (hash-map :default (KafkaProducer. *producer-properties*))] (let [topic (gen/generate gen/string-alphanumeric 10) key "PI:KEY:<KEY>END_PI" value "Hello World!!" partition (int 0)] (send :default topic partition key value) (let [result (IntegrationTestUtils/waitUntilMinKeyValueRecordsReceived *consumer-properties* topic 1 2000)] (is (= value (.value (first result)))))))) (deftest send-throws-exception-when-no-producers-are-configured (with-redefs [kafka-producers {}] (let [topic "test-topic" key "message" value "Hello World!! from non-existant Kafka Producers"] (is (not-empty (try (send :default topic key value) (catch Exception e (ex-data e)))))))) (deftest producer-properties-map-is-empty-if-no-producers-configured ; Here ziggurat-config has been substituted with a custom map which ; does not have any valid producer configs. (with-redefs [ziggurat-config stream-router-config-without-producer] (is (empty? (producer-properties-map))))) (deftest producer-properties-map-is-not-empty-if-producers-are-configured ; Here the config is read from config.test.edn which contains ; valid producer configs. (is (seq (producer-properties-map))))
[ { "context": "o\n I modified the Apache-licensed code I found by Adam Ashenfelter:\n https://gist.github.com/ashenfad/2969087\"\n [s", "end": 588, "score": 0.9997832775115967, "start": 572, "tag": "NAME", "value": "Adam Ashenfelter" }, { "context": "nd by Adam Ashenfelter:\n https://gist.github.com/ashenfad/2969087\"\n [size]\n (with-meta [] {:size size :n ", "end": 624, "score": 0.9997256398200989, "start": 616, "tag": "USERNAME", "value": "ashenfad" } ]
src/fountain_codes/sample.clj
hausdorff/fountain-codes
4
(ns fountain-codes.sample "Simple package for sampling data" (:use [fountain-codes.lazy-rand :as lazy-rand])) (defn- rs-create "The reservoir sampler is a data structure allowing selection of a uniformly-likely k-sample of an n-element list in O(n) time and space. Specified in Algorithm R of Vitter 1985. `size` metadatum reflects total capacity of sampler; `n` reflects the current number of times `insert` has been called. NOTE: I couldn't find standard library to actually do reservoir sampling, so I modified the Apache-licensed code I found by Adam Ashenfelter: https://gist.github.com/ashenfad/2969087" [size] (with-meta [] {:size size :n 0})) (defn- rs-insert "Inserts value into reservoir sampler (created using `rs-create`)." [sampler v r] (let [{:keys [size n]} (meta sampler) n' (inc n) index (lazy-rand/nint r n')] (with-meta (cond (<= n' size) (conj sampler v) (< index size) (assoc sampler index v) :else sampler) {:size size :n n'}))) (defn uniform-k-sample "Takes a uniformly-likely k-sample of some n-element list in O(n) time/space" [arr k seed] (let [r (lazy-rand/newrand seed)] (reduce (fn [sampler v] (rs-insert sampler v r)) (rs-create k) arr)))
109753
(ns fountain-codes.sample "Simple package for sampling data" (:use [fountain-codes.lazy-rand :as lazy-rand])) (defn- rs-create "The reservoir sampler is a data structure allowing selection of a uniformly-likely k-sample of an n-element list in O(n) time and space. Specified in Algorithm R of Vitter 1985. `size` metadatum reflects total capacity of sampler; `n` reflects the current number of times `insert` has been called. NOTE: I couldn't find standard library to actually do reservoir sampling, so I modified the Apache-licensed code I found by <NAME>: https://gist.github.com/ashenfad/2969087" [size] (with-meta [] {:size size :n 0})) (defn- rs-insert "Inserts value into reservoir sampler (created using `rs-create`)." [sampler v r] (let [{:keys [size n]} (meta sampler) n' (inc n) index (lazy-rand/nint r n')] (with-meta (cond (<= n' size) (conj sampler v) (< index size) (assoc sampler index v) :else sampler) {:size size :n n'}))) (defn uniform-k-sample "Takes a uniformly-likely k-sample of some n-element list in O(n) time/space" [arr k seed] (let [r (lazy-rand/newrand seed)] (reduce (fn [sampler v] (rs-insert sampler v r)) (rs-create k) arr)))
true
(ns fountain-codes.sample "Simple package for sampling data" (:use [fountain-codes.lazy-rand :as lazy-rand])) (defn- rs-create "The reservoir sampler is a data structure allowing selection of a uniformly-likely k-sample of an n-element list in O(n) time and space. Specified in Algorithm R of Vitter 1985. `size` metadatum reflects total capacity of sampler; `n` reflects the current number of times `insert` has been called. NOTE: I couldn't find standard library to actually do reservoir sampling, so I modified the Apache-licensed code I found by PI:NAME:<NAME>END_PI: https://gist.github.com/ashenfad/2969087" [size] (with-meta [] {:size size :n 0})) (defn- rs-insert "Inserts value into reservoir sampler (created using `rs-create`)." [sampler v r] (let [{:keys [size n]} (meta sampler) n' (inc n) index (lazy-rand/nint r n')] (with-meta (cond (<= n' size) (conj sampler v) (< index size) (assoc sampler index v) :else sampler) {:size size :n n'}))) (defn uniform-k-sample "Takes a uniformly-likely k-sample of some n-element list in O(n) time/space" [arr k seed] (let [r (lazy-rand/newrand seed)] (reduce (fn [sampler v] (rs-insert sampler v r)) (rs-create k) arr)))
[ { "context": "or injection attacks...\n;; See https://github.com/lightningnetwork/lightning-rfc/blob/master/11-payment-encoding.md#", "end": 166, "score": 0.9955760836601257, "start": 150, "tag": "USERNAME", "value": "lightningnetwork" }, { "context": "http://lnd.fun/newinvoice\n\n(def test-private-key \"e126f68f7eafcc8b74f54d269fe206be715000f94dac067d1c04a8ca3b2db734\")\n\n(def test-payment-hash \"56508716f097b609ad53c3", "end": 447, "score": 0.9997208118438721, "start": 383, "tag": "KEY", "value": "e126f68f7eafcc8b74f54d269fe206be715000f94dac067d1c04a8ca3b2db734" } ]
src/app/lib/bolt11.cljs
person8org/person8
4
(ns app.lib.bolt11 (:require ["bolt11" :as bolt11])) ;; IMPORTANT: Decoded invoices may open for injection attacks... ;; See https://github.com/lightningnetwork/lightning-rfc/blob/master/11-payment-encoding.md#security-considerations-for-payment-descriptions (def default-address "2MvznU28V9Zzi35p9m1aSB4qmvMZQGLVHt8") ; from http://lnd.fun/newinvoice (def test-private-key "e126f68f7eafcc8b74f54d269fe206be715000f94dac067d1c04a8ca3b2db734") (def test-payment-hash "56508716f097b609ad53c37a84f56f924a9625937929dba4fc06f6052c101068") ;; bogus/generated (def invoice-template-encoded "lntb1u1pw0eymcpp5lv0peqg97a7a78qrawtlfjpyk5t0859890k76f9yaqx8qm7s2lwqdqcf35hv6twvusx27rsv4h8xetncqzpg664s6xjgkjhf5at0es52p3pfallkfglj3js5332yk53w0jmetma9h69esrlg03wx7ksvll6amt5kzgjx0gn238vazjzm4mer7lpwg7sqma2s7q") (def invoice-template-decoded-js (memoize (fn [] (bolt11/decode invoice-template-encoded)))) #_ (invoice-template-decoded-js) (defn mock-encode-invoice [{:keys [address amount memo timestamp]}] ; https://www.npmjs.com/package/bolt11 (-> (js/Object.assign #js{} #js{:coinType "testnet" :address address :millisatoshis (* amount 1000) :description memo :timestamp timestamp} (invoice-template-decoded-js)) (bolt11/encode) (.-paymentRequest))) (defn encode-invoice [{:keys [private-key address amount memo payment-hash timestamp tags] :or {payment-hash test-payment-hash memo ""}}] ; https://www.npmjs.com/package/bolt11 (bolt11/encode (js/Object.assign #js{} #js{:coinType "testnet" :address address :satoshis amount :timestamp timestamp :tags (clj->js (or tags [#js{:tagName "payment_hash" :data payment-hash} #js{:tagName "description" :data memo}]))}))) (defn sign [encoded private-key] (bolt11/sign encoded private-key)) (def test-payment-hash-tag #js{"tagName" "payment_hash", "data" "0001020304050607080900010203040506070809000102030405060708090102"}) #_ (-> (encode-invoice {:address default-address :amount 200 :memo "Need funds asap" :timestamp (js/Date.now) :tags [test-payment-hash-tag]}) (sign test-private-key) (.-paymentRequest))
1381
(ns app.lib.bolt11 (:require ["bolt11" :as bolt11])) ;; IMPORTANT: Decoded invoices may open for injection attacks... ;; See https://github.com/lightningnetwork/lightning-rfc/blob/master/11-payment-encoding.md#security-considerations-for-payment-descriptions (def default-address "2MvznU28V9Zzi35p9m1aSB4qmvMZQGLVHt8") ; from http://lnd.fun/newinvoice (def test-private-key "<KEY>") (def test-payment-hash "56508716f097b609ad53c37a84f56f924a9625937929dba4fc06f6052c101068") ;; bogus/generated (def invoice-template-encoded "lntb1u1pw0eymcpp5lv0peqg97a7a78qrawtlfjpyk5t0859890k76f9yaqx8qm7s2lwqdqcf35hv6twvusx27rsv4h8xetncqzpg664s6xjgkjhf5at0es52p3pfallkfglj3js5332yk53w0jmetma9h69esrlg03wx7ksvll6amt5kzgjx0gn238vazjzm4mer7lpwg7sqma2s7q") (def invoice-template-decoded-js (memoize (fn [] (bolt11/decode invoice-template-encoded)))) #_ (invoice-template-decoded-js) (defn mock-encode-invoice [{:keys [address amount memo timestamp]}] ; https://www.npmjs.com/package/bolt11 (-> (js/Object.assign #js{} #js{:coinType "testnet" :address address :millisatoshis (* amount 1000) :description memo :timestamp timestamp} (invoice-template-decoded-js)) (bolt11/encode) (.-paymentRequest))) (defn encode-invoice [{:keys [private-key address amount memo payment-hash timestamp tags] :or {payment-hash test-payment-hash memo ""}}] ; https://www.npmjs.com/package/bolt11 (bolt11/encode (js/Object.assign #js{} #js{:coinType "testnet" :address address :satoshis amount :timestamp timestamp :tags (clj->js (or tags [#js{:tagName "payment_hash" :data payment-hash} #js{:tagName "description" :data memo}]))}))) (defn sign [encoded private-key] (bolt11/sign encoded private-key)) (def test-payment-hash-tag #js{"tagName" "payment_hash", "data" "0001020304050607080900010203040506070809000102030405060708090102"}) #_ (-> (encode-invoice {:address default-address :amount 200 :memo "Need funds asap" :timestamp (js/Date.now) :tags [test-payment-hash-tag]}) (sign test-private-key) (.-paymentRequest))
true
(ns app.lib.bolt11 (:require ["bolt11" :as bolt11])) ;; IMPORTANT: Decoded invoices may open for injection attacks... ;; See https://github.com/lightningnetwork/lightning-rfc/blob/master/11-payment-encoding.md#security-considerations-for-payment-descriptions (def default-address "2MvznU28V9Zzi35p9m1aSB4qmvMZQGLVHt8") ; from http://lnd.fun/newinvoice (def test-private-key "PI:KEY:<KEY>END_PI") (def test-payment-hash "56508716f097b609ad53c37a84f56f924a9625937929dba4fc06f6052c101068") ;; bogus/generated (def invoice-template-encoded "lntb1u1pw0eymcpp5lv0peqg97a7a78qrawtlfjpyk5t0859890k76f9yaqx8qm7s2lwqdqcf35hv6twvusx27rsv4h8xetncqzpg664s6xjgkjhf5at0es52p3pfallkfglj3js5332yk53w0jmetma9h69esrlg03wx7ksvll6amt5kzgjx0gn238vazjzm4mer7lpwg7sqma2s7q") (def invoice-template-decoded-js (memoize (fn [] (bolt11/decode invoice-template-encoded)))) #_ (invoice-template-decoded-js) (defn mock-encode-invoice [{:keys [address amount memo timestamp]}] ; https://www.npmjs.com/package/bolt11 (-> (js/Object.assign #js{} #js{:coinType "testnet" :address address :millisatoshis (* amount 1000) :description memo :timestamp timestamp} (invoice-template-decoded-js)) (bolt11/encode) (.-paymentRequest))) (defn encode-invoice [{:keys [private-key address amount memo payment-hash timestamp tags] :or {payment-hash test-payment-hash memo ""}}] ; https://www.npmjs.com/package/bolt11 (bolt11/encode (js/Object.assign #js{} #js{:coinType "testnet" :address address :satoshis amount :timestamp timestamp :tags (clj->js (or tags [#js{:tagName "payment_hash" :data payment-hash} #js{:tagName "description" :data memo}]))}))) (defn sign [encoded private-key] (bolt11/sign encoded private-key)) (def test-payment-hash-tag #js{"tagName" "payment_hash", "data" "0001020304050607080900010203040506070809000102030405060708090102"}) #_ (-> (encode-invoice {:address default-address :amount 200 :memo "Need funds asap" :timestamp (js/Date.now) :tags [test-payment-hash-tag]}) (sign test-private-key) (.-paymentRequest))
[ { "context": "nt\"}]\n :frames [{:examples [\"Harry sees Sally.\"]\n :sy", "end": 1446, "score": 0.9954836964607239, "start": 1441, "tag": "NAME", "value": "Harry" }, { "context": " :frames [{:examples [\"Harry sees Sally.\"]\n :syntax [{:p", "end": 1457, "score": 0.9896465539932251, "start": 1452, "tag": "NAME", "value": "Sally" }, { "context": "nt\"}]\n :frames [{:examples [\"Nike provides comfort.\"]\n ", "end": 1962, "score": 0.8490146398544312, "start": 1958, "tag": "NAME", "value": "Nike" } ]
api/test/data/amr_test.clj
zorrock/accelerated-text
1
(ns data.amr-test (:require [clojure.java.io :as io] [clojure.test :refer [deftest is]] [data.entities.amr :as amr] [data.entities.dictionary :as dictionary])) (deftest amr-reading (is (= {:id "author" :dictionary-item-id "author" :thematic-roles [{:type "Agent"} {:type "co-Agent"}] :frames [{:examples ["X is the author of Y"] :syntax [{:pos :NP :role "Agent"} {:pos :AUX :value "is"} {:pos :LEX :value "the author of"} {:pos :NP :role "co-Agent"}]} {:examples ["Y is written by X"] :syntax [{:pos :NP :role "co-Agent"} {:pos :AUX :value "is"} {:pos :VERB} {:pos :ADP :value "by"} {:pos :NP :role "Agent"}]}]} (amr/read-amr (io/file "test/resources/grammar/library/author.yaml")))) (is (= {:id "see" :dictionary-item-id "see" :thematic-roles [{:type "Agent"} {:type "co-Agent"}] :frames [{:examples ["Harry sees Sally."] :syntax [{:pos :NP :role "Agent"} {:pos :VERB} {:pos :NP :role "co-Agent"}]}]} (amr/read-amr (io/file "test/resources/grammar/other/see.yaml")))) (is (= {:id "provide" :dictionary-item-id "provide" :thematic-roles [{:type "Agent"} {:type "co-Agent"}] :frames [{:examples ["Nike provides comfort."] :syntax [{:pos :NP :role "Agent"} {:pos :VERB} {:pos :NP :role "co-Agent"}]}]} (amr/read-amr (io/file "test/resources/grammar/other/provide.yaml")))) (is (= {:id "cut" :dictionary-item-id "cut" :thematic-roles [{:type "Agent"} {:type "Patient"} {:type "Instrument"} {:type "Source"} {:type "Result"}] :frames [{:examples ["Carol cut the envelope into pieces with a knife."] :syntax [{:pos :NP :role "Agent"} {:pos :VERB} {:pos :NP :role "Patient"} {:pos :ADP :value "into"} {:pos :NP :role "Result"} {:pos :ADP :value "with"} {:pos :NP :role "Instrument"}]}]} (amr/read-amr (io/file "test/resources/grammar/other/cut.yaml")))) (is (= {:id "author-with-params" :dictionary-item-id "author-with-params" :thematic-roles [{:type "Agent"} {:type "co-Agent"}] :frames [{:examples ["Y was written by X"] :syntax [{:pos :NP :role "co-Agent"} {:pos :AUX :value "is"} {:pos :VERB :number :singular :tense :past} {:pos :ADP :value "by"} {:pos :NP :role "Agent"}]}]} (amr/read-amr (io/file "test/resources/grammar/other/author-with-params.yaml"))))) (deftest ^:integration amr-init (is (nil? (dictionary/get-dictionary-item "release"))) (amr/initialize) (is (dictionary/get-dictionary-item "release")))
1588
(ns data.amr-test (:require [clojure.java.io :as io] [clojure.test :refer [deftest is]] [data.entities.amr :as amr] [data.entities.dictionary :as dictionary])) (deftest amr-reading (is (= {:id "author" :dictionary-item-id "author" :thematic-roles [{:type "Agent"} {:type "co-Agent"}] :frames [{:examples ["X is the author of Y"] :syntax [{:pos :NP :role "Agent"} {:pos :AUX :value "is"} {:pos :LEX :value "the author of"} {:pos :NP :role "co-Agent"}]} {:examples ["Y is written by X"] :syntax [{:pos :NP :role "co-Agent"} {:pos :AUX :value "is"} {:pos :VERB} {:pos :ADP :value "by"} {:pos :NP :role "Agent"}]}]} (amr/read-amr (io/file "test/resources/grammar/library/author.yaml")))) (is (= {:id "see" :dictionary-item-id "see" :thematic-roles [{:type "Agent"} {:type "co-Agent"}] :frames [{:examples ["<NAME> sees <NAME>."] :syntax [{:pos :NP :role "Agent"} {:pos :VERB} {:pos :NP :role "co-Agent"}]}]} (amr/read-amr (io/file "test/resources/grammar/other/see.yaml")))) (is (= {:id "provide" :dictionary-item-id "provide" :thematic-roles [{:type "Agent"} {:type "co-Agent"}] :frames [{:examples ["<NAME> provides comfort."] :syntax [{:pos :NP :role "Agent"} {:pos :VERB} {:pos :NP :role "co-Agent"}]}]} (amr/read-amr (io/file "test/resources/grammar/other/provide.yaml")))) (is (= {:id "cut" :dictionary-item-id "cut" :thematic-roles [{:type "Agent"} {:type "Patient"} {:type "Instrument"} {:type "Source"} {:type "Result"}] :frames [{:examples ["Carol cut the envelope into pieces with a knife."] :syntax [{:pos :NP :role "Agent"} {:pos :VERB} {:pos :NP :role "Patient"} {:pos :ADP :value "into"} {:pos :NP :role "Result"} {:pos :ADP :value "with"} {:pos :NP :role "Instrument"}]}]} (amr/read-amr (io/file "test/resources/grammar/other/cut.yaml")))) (is (= {:id "author-with-params" :dictionary-item-id "author-with-params" :thematic-roles [{:type "Agent"} {:type "co-Agent"}] :frames [{:examples ["Y was written by X"] :syntax [{:pos :NP :role "co-Agent"} {:pos :AUX :value "is"} {:pos :VERB :number :singular :tense :past} {:pos :ADP :value "by"} {:pos :NP :role "Agent"}]}]} (amr/read-amr (io/file "test/resources/grammar/other/author-with-params.yaml"))))) (deftest ^:integration amr-init (is (nil? (dictionary/get-dictionary-item "release"))) (amr/initialize) (is (dictionary/get-dictionary-item "release")))
true
(ns data.amr-test (:require [clojure.java.io :as io] [clojure.test :refer [deftest is]] [data.entities.amr :as amr] [data.entities.dictionary :as dictionary])) (deftest amr-reading (is (= {:id "author" :dictionary-item-id "author" :thematic-roles [{:type "Agent"} {:type "co-Agent"}] :frames [{:examples ["X is the author of Y"] :syntax [{:pos :NP :role "Agent"} {:pos :AUX :value "is"} {:pos :LEX :value "the author of"} {:pos :NP :role "co-Agent"}]} {:examples ["Y is written by X"] :syntax [{:pos :NP :role "co-Agent"} {:pos :AUX :value "is"} {:pos :VERB} {:pos :ADP :value "by"} {:pos :NP :role "Agent"}]}]} (amr/read-amr (io/file "test/resources/grammar/library/author.yaml")))) (is (= {:id "see" :dictionary-item-id "see" :thematic-roles [{:type "Agent"} {:type "co-Agent"}] :frames [{:examples ["PI:NAME:<NAME>END_PI sees PI:NAME:<NAME>END_PI."] :syntax [{:pos :NP :role "Agent"} {:pos :VERB} {:pos :NP :role "co-Agent"}]}]} (amr/read-amr (io/file "test/resources/grammar/other/see.yaml")))) (is (= {:id "provide" :dictionary-item-id "provide" :thematic-roles [{:type "Agent"} {:type "co-Agent"}] :frames [{:examples ["PI:NAME:<NAME>END_PI provides comfort."] :syntax [{:pos :NP :role "Agent"} {:pos :VERB} {:pos :NP :role "co-Agent"}]}]} (amr/read-amr (io/file "test/resources/grammar/other/provide.yaml")))) (is (= {:id "cut" :dictionary-item-id "cut" :thematic-roles [{:type "Agent"} {:type "Patient"} {:type "Instrument"} {:type "Source"} {:type "Result"}] :frames [{:examples ["Carol cut the envelope into pieces with a knife."] :syntax [{:pos :NP :role "Agent"} {:pos :VERB} {:pos :NP :role "Patient"} {:pos :ADP :value "into"} {:pos :NP :role "Result"} {:pos :ADP :value "with"} {:pos :NP :role "Instrument"}]}]} (amr/read-amr (io/file "test/resources/grammar/other/cut.yaml")))) (is (= {:id "author-with-params" :dictionary-item-id "author-with-params" :thematic-roles [{:type "Agent"} {:type "co-Agent"}] :frames [{:examples ["Y was written by X"] :syntax [{:pos :NP :role "co-Agent"} {:pos :AUX :value "is"} {:pos :VERB :number :singular :tense :past} {:pos :ADP :value "by"} {:pos :NP :role "Agent"}]}]} (amr/read-amr (io/file "test/resources/grammar/other/author-with-params.yaml"))))) (deftest ^:integration amr-init (is (nil? (dictionary/get-dictionary-item "release"))) (amr/initialize) (is (dictionary/get-dictionary-item "release")))
[ { "context": "; Copyright (c) Chris Houser, Sep 2008-Jan 2009. All rights reserved.\n; The ", "end": 30, "score": 0.9997715950012207, "start": 18, "tag": "NAME", "value": "Chris Houser" } ]
ThirdParty/clojure-contrib-1.1.0/clojurescript/src/clojure/contrib/clojurescript/cli.clj
allertonm/Couverjure
3
; Copyright (c) Chris Houser, Sep 2008-Jan 2009. 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. ; Command Line Interface for generating JavaScript from Clojure code. (ns clojure.contrib.clojurescript.cli (:import (java.io PrintWriter StringReader) (java.net URLDecoder)) (:use [clojure.contrib.command-line :only (with-command-line)] [clojure.contrib.clojurescript :only (formtojs filetojs)]) (:require [clojure.contrib.duck-streams :as ds])) (defn mkcore [] (binding [*out* (ds/writer "core.js")] (doseq [file ["clojure/core.clj" "clojure/core_print.clj"]] (filetojs (.getResourceAsStream (clojure.lang.RT/baseLoader) file))))) (defn simple-tests [] (println (formtojs '(defn foo ([a b c & d] (prn 3 a b c)) ([c] ;(String/asd "hello") ;(.foo 55) (let [[a b] [1 2]] (prn a b c) "hi"))))) (println (formtojs '(defn foo [a] (prn "hi") (let [a 5] (let [a 10] (prn "yo") (prn a)) (prn a)) (prn a)))) (println (formtojs '(defn x [] (conj [] (loop [i 5] (if (pos? i) (recur (- i 2)) i)))))) ;(println (formtojs '(binding [*out* 5] (set! *out* 10)))) (println (formtojs '(.replace "a/b/c" "/" "."))) (println (formtojs '(.getName ":foo"))) (println (formtojs '(list '(1 "str" 'sym :key) 4 "str2" 6 #{:set 9 8}))) (println (formtojs '(fn forever[] (forever)))) (println (formtojs '(fn forever[] (loop [] (recur)))))) (when-not *compile-files* (with-command-line *command-line-args* "clojurescript.cli -- Compile ClojureScript to JavaScript" [[simple? "Runs some simple built-in tests"] [mkcore? "Generates a core.js file"] [v? verbose? "Includes extra fn names and comments in js"] filenames] (cond simple? (simple-tests) mkcore? (mkcore) :else (doseq [filename filenames] (filetojs filename :debug-fn-names v? :debug-comments v?)))))
91553
; Copyright (c) <NAME>, Sep 2008-Jan 2009. 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. ; Command Line Interface for generating JavaScript from Clojure code. (ns clojure.contrib.clojurescript.cli (:import (java.io PrintWriter StringReader) (java.net URLDecoder)) (:use [clojure.contrib.command-line :only (with-command-line)] [clojure.contrib.clojurescript :only (formtojs filetojs)]) (:require [clojure.contrib.duck-streams :as ds])) (defn mkcore [] (binding [*out* (ds/writer "core.js")] (doseq [file ["clojure/core.clj" "clojure/core_print.clj"]] (filetojs (.getResourceAsStream (clojure.lang.RT/baseLoader) file))))) (defn simple-tests [] (println (formtojs '(defn foo ([a b c & d] (prn 3 a b c)) ([c] ;(String/asd "hello") ;(.foo 55) (let [[a b] [1 2]] (prn a b c) "hi"))))) (println (formtojs '(defn foo [a] (prn "hi") (let [a 5] (let [a 10] (prn "yo") (prn a)) (prn a)) (prn a)))) (println (formtojs '(defn x [] (conj [] (loop [i 5] (if (pos? i) (recur (- i 2)) i)))))) ;(println (formtojs '(binding [*out* 5] (set! *out* 10)))) (println (formtojs '(.replace "a/b/c" "/" "."))) (println (formtojs '(.getName ":foo"))) (println (formtojs '(list '(1 "str" 'sym :key) 4 "str2" 6 #{:set 9 8}))) (println (formtojs '(fn forever[] (forever)))) (println (formtojs '(fn forever[] (loop [] (recur)))))) (when-not *compile-files* (with-command-line *command-line-args* "clojurescript.cli -- Compile ClojureScript to JavaScript" [[simple? "Runs some simple built-in tests"] [mkcore? "Generates a core.js file"] [v? verbose? "Includes extra fn names and comments in js"] filenames] (cond simple? (simple-tests) mkcore? (mkcore) :else (doseq [filename filenames] (filetojs filename :debug-fn-names v? :debug-comments v?)))))
true
; Copyright (c) PI:NAME:<NAME>END_PI, Sep 2008-Jan 2009. 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. ; Command Line Interface for generating JavaScript from Clojure code. (ns clojure.contrib.clojurescript.cli (:import (java.io PrintWriter StringReader) (java.net URLDecoder)) (:use [clojure.contrib.command-line :only (with-command-line)] [clojure.contrib.clojurescript :only (formtojs filetojs)]) (:require [clojure.contrib.duck-streams :as ds])) (defn mkcore [] (binding [*out* (ds/writer "core.js")] (doseq [file ["clojure/core.clj" "clojure/core_print.clj"]] (filetojs (.getResourceAsStream (clojure.lang.RT/baseLoader) file))))) (defn simple-tests [] (println (formtojs '(defn foo ([a b c & d] (prn 3 a b c)) ([c] ;(String/asd "hello") ;(.foo 55) (let [[a b] [1 2]] (prn a b c) "hi"))))) (println (formtojs '(defn foo [a] (prn "hi") (let [a 5] (let [a 10] (prn "yo") (prn a)) (prn a)) (prn a)))) (println (formtojs '(defn x [] (conj [] (loop [i 5] (if (pos? i) (recur (- i 2)) i)))))) ;(println (formtojs '(binding [*out* 5] (set! *out* 10)))) (println (formtojs '(.replace "a/b/c" "/" "."))) (println (formtojs '(.getName ":foo"))) (println (formtojs '(list '(1 "str" 'sym :key) 4 "str2" 6 #{:set 9 8}))) (println (formtojs '(fn forever[] (forever)))) (println (formtojs '(fn forever[] (loop [] (recur)))))) (when-not *compile-files* (with-command-line *command-line-args* "clojurescript.cli -- Compile ClojureScript to JavaScript" [[simple? "Runs some simple built-in tests"] [mkcore? "Generates a core.js file"] [v? verbose? "Includes extra fn names and comments in js"] filenames] (cond simple? (simple-tests) mkcore? (mkcore) :else (doseq [filename filenames] (filetojs filename :debug-fn-names v? :debug-comments v?)))))
[ { "context": "result)))\n #{{:family \"Carberry\" :given \"Josiah\"}\n {:family \"Puddleduck\" :given \"Jemim", "end": 1365, "score": 0.7070618271827698, "start": 1359, "tag": "NAME", "value": "Josiah" } ]
test/crossmark/features/bibliographic_test.clj
CrossRef/crossmark
2
(ns crossmark.features.bibliographic-test (:require [clojure.test :refer :all] [crossref.util.date :as cr-date] [crossmark.test-util :as test-util] [crossmark.features.bibliographic :as bibliographic])) (deftest decorate-work-info (testing "Bibliographic work information should be retrieved from API response" (let [base (test-util/base "test/10.5555-up-up.json" {}) result (bibliographic/decorate-work-info base)] (is (= (:title result) "Trebuchets: Up up and Away") "First title should be chosen.") (is (= (:publication result) "Journal of Trebuchets and Lesser Siege Engines") "First container-title should be chosen as the publication name.") (is (= (:published-date result) (cr-date/crossref-date 1986 2 1)) "Published date should be taken from published-print") (is (= (:update-policy result) "http://dx.doi.org/10.5555/crossmark_policy") "Crossmark Update Policy should be taken.") (is (= (:publisher result) "Oversize Weapons Inc"))))) (deftest decorate-author (let [base (test-util/base "test/10.5555-up-up.json" {}) result (bibliographic/decorate-author base)] (testing "decorate-author should select all authors" (is (= (set (map #(select-keys % [:family :given]) (:author result))) #{{:family "Carberry" :given "Josiah"} {:family "Puddleduck" :given "Jemima"}}) "All first and given names should be selected") (is (true? (:has-author result))))) (let [base (test-util/base "test/10.5555-catapult.json" {}) result (bibliographic/decorate-author base)] (testing "decorate-author should represent when no authors" (is (false? (:has-author result))) (is (empty? (:authors result)))))) (deftest decorate-remove-orcid-authors (testing "decorate-author should ignore ORCID-based assertions, case insensitive" (let [base (test-util/base "test/10.5555-up-up.json" {}) result (bibliographic/decorate-remove-orcid-authors base)] ; There are 5 assertions in 10.5555/up-up ; 2 of them are ORCID assertions with different cases. (is (= 3 (count (-> result :from-md-api :assertion))) "Not all assertions should be removed") (is (every? #{"received" "accepted" "published"} (map :name (-> result :from-md-api :assertion))) "Non-ORCID assertions should not be altered"))))
72218
(ns crossmark.features.bibliographic-test (:require [clojure.test :refer :all] [crossref.util.date :as cr-date] [crossmark.test-util :as test-util] [crossmark.features.bibliographic :as bibliographic])) (deftest decorate-work-info (testing "Bibliographic work information should be retrieved from API response" (let [base (test-util/base "test/10.5555-up-up.json" {}) result (bibliographic/decorate-work-info base)] (is (= (:title result) "Trebuchets: Up up and Away") "First title should be chosen.") (is (= (:publication result) "Journal of Trebuchets and Lesser Siege Engines") "First container-title should be chosen as the publication name.") (is (= (:published-date result) (cr-date/crossref-date 1986 2 1)) "Published date should be taken from published-print") (is (= (:update-policy result) "http://dx.doi.org/10.5555/crossmark_policy") "Crossmark Update Policy should be taken.") (is (= (:publisher result) "Oversize Weapons Inc"))))) (deftest decorate-author (let [base (test-util/base "test/10.5555-up-up.json" {}) result (bibliographic/decorate-author base)] (testing "decorate-author should select all authors" (is (= (set (map #(select-keys % [:family :given]) (:author result))) #{{:family "Carberry" :given "<NAME>"} {:family "Puddleduck" :given "Jemima"}}) "All first and given names should be selected") (is (true? (:has-author result))))) (let [base (test-util/base "test/10.5555-catapult.json" {}) result (bibliographic/decorate-author base)] (testing "decorate-author should represent when no authors" (is (false? (:has-author result))) (is (empty? (:authors result)))))) (deftest decorate-remove-orcid-authors (testing "decorate-author should ignore ORCID-based assertions, case insensitive" (let [base (test-util/base "test/10.5555-up-up.json" {}) result (bibliographic/decorate-remove-orcid-authors base)] ; There are 5 assertions in 10.5555/up-up ; 2 of them are ORCID assertions with different cases. (is (= 3 (count (-> result :from-md-api :assertion))) "Not all assertions should be removed") (is (every? #{"received" "accepted" "published"} (map :name (-> result :from-md-api :assertion))) "Non-ORCID assertions should not be altered"))))
true
(ns crossmark.features.bibliographic-test (:require [clojure.test :refer :all] [crossref.util.date :as cr-date] [crossmark.test-util :as test-util] [crossmark.features.bibliographic :as bibliographic])) (deftest decorate-work-info (testing "Bibliographic work information should be retrieved from API response" (let [base (test-util/base "test/10.5555-up-up.json" {}) result (bibliographic/decorate-work-info base)] (is (= (:title result) "Trebuchets: Up up and Away") "First title should be chosen.") (is (= (:publication result) "Journal of Trebuchets and Lesser Siege Engines") "First container-title should be chosen as the publication name.") (is (= (:published-date result) (cr-date/crossref-date 1986 2 1)) "Published date should be taken from published-print") (is (= (:update-policy result) "http://dx.doi.org/10.5555/crossmark_policy") "Crossmark Update Policy should be taken.") (is (= (:publisher result) "Oversize Weapons Inc"))))) (deftest decorate-author (let [base (test-util/base "test/10.5555-up-up.json" {}) result (bibliographic/decorate-author base)] (testing "decorate-author should select all authors" (is (= (set (map #(select-keys % [:family :given]) (:author result))) #{{:family "Carberry" :given "PI:NAME:<NAME>END_PI"} {:family "Puddleduck" :given "Jemima"}}) "All first and given names should be selected") (is (true? (:has-author result))))) (let [base (test-util/base "test/10.5555-catapult.json" {}) result (bibliographic/decorate-author base)] (testing "decorate-author should represent when no authors" (is (false? (:has-author result))) (is (empty? (:authors result)))))) (deftest decorate-remove-orcid-authors (testing "decorate-author should ignore ORCID-based assertions, case insensitive" (let [base (test-util/base "test/10.5555-up-up.json" {}) result (bibliographic/decorate-remove-orcid-authors base)] ; There are 5 assertions in 10.5555/up-up ; 2 of them are ORCID assertions with different cases. (is (= 3 (count (-> result :from-md-api :assertion))) "Not all assertions should be removed") (is (every? #{"received" "accepted" "published"} (map :name (-> result :from-md-api :assertion))) "Non-ORCID assertions should not be altered"))))
[ { "context": "(def x (future (println \"tjosan!\")\n (+ 1 2)))\n\n(println @x) ; 3\n(println @x) ;", "end": 31, "score": 0.8526950478553772, "start": 25, "tag": "NAME", "value": "tjosan" } ]
Concurrency/ex04 - future/main.clj
hoppfull/Legacy-Clojure
0
(def x (future (println "tjosan!") (+ 1 2))) (println @x) ; 3 (println @x) ; 3 (println @x) ; 3 ; The future executes its body of code right away ; in a seperate thread. I think if there are multiple ; processor cores available, they will be used. Not ; sure how well they are utilized or in what manner. ; When dereferencing x, we get the value returned by ; the future body. Like with delays, the value is ; cached and will not be calculated again. ; If a thread try to dereference x before x is ; evaluated, that thread will block until x is ready. (def y (future (Thread/sleep 500) 3)) (def z (future (Thread/sleep 3000) 3)) (println (deref y 1000 5)) ; 3 (println (deref z 1000 5)) ; 5 ; A default value can be returned by deref if future ; takes too long to evaluate. In this case threads ; will sleep for a time and return 3. If it takes ; longer than 1000ms, 5 is returned instead. (System/exit 0) ; Make sure program isn't left hanging.
31097
(def x (future (println "<NAME>!") (+ 1 2))) (println @x) ; 3 (println @x) ; 3 (println @x) ; 3 ; The future executes its body of code right away ; in a seperate thread. I think if there are multiple ; processor cores available, they will be used. Not ; sure how well they are utilized or in what manner. ; When dereferencing x, we get the value returned by ; the future body. Like with delays, the value is ; cached and will not be calculated again. ; If a thread try to dereference x before x is ; evaluated, that thread will block until x is ready. (def y (future (Thread/sleep 500) 3)) (def z (future (Thread/sleep 3000) 3)) (println (deref y 1000 5)) ; 3 (println (deref z 1000 5)) ; 5 ; A default value can be returned by deref if future ; takes too long to evaluate. In this case threads ; will sleep for a time and return 3. If it takes ; longer than 1000ms, 5 is returned instead. (System/exit 0) ; Make sure program isn't left hanging.
true
(def x (future (println "PI:NAME:<NAME>END_PI!") (+ 1 2))) (println @x) ; 3 (println @x) ; 3 (println @x) ; 3 ; The future executes its body of code right away ; in a seperate thread. I think if there are multiple ; processor cores available, they will be used. Not ; sure how well they are utilized or in what manner. ; When dereferencing x, we get the value returned by ; the future body. Like with delays, the value is ; cached and will not be calculated again. ; If a thread try to dereference x before x is ; evaluated, that thread will block until x is ready. (def y (future (Thread/sleep 500) 3)) (def z (future (Thread/sleep 3000) 3)) (println (deref y 1000 5)) ; 3 (println (deref z 1000 5)) ; 5 ; A default value can be returned by deref if future ; takes too long to evaluate. In this case threads ; will sleep for a time and return 3. If it takes ; longer than 1000ms, 5 is returned instead. (System/exit 0) ; Make sure program isn't left hanging.
[ { "context": "the command line from user input.\"\n :author \"Paul Landes\"}\n zensols.cisql.process-query\n (:import (jav", "end": 90, "score": 0.9998685717582703, "start": 79, "tag": "NAME", "value": "Paul Landes" } ]
src/clojure/zensols/cisql/process_query.clj
plandes/cisql
12
(ns ^{:doc "Process query at the command line from user input." :author "Paul Landes"} zensols.cisql.process-query (:import (java.io BufferedReader InputStreamReader StringReader)) (:require [clojure.tools.logging :as log] [clojure.java.io :as io] [clojure.string :as str] [zensols.actioncli.log4j2 :as lu] [zensols.actioncli.util :refer (trunc)] [zensols.actioncli.parse :as parse :refer (with-exception)] [zensols.cisql.conf :as conf] [zensols.cisql.db-access :as db] [zensols.cisql.read :as r] [zensols.cisql.directive :as di])) (def ^:private last-query (atom nil)) (def ^:private init-file (-> (System/getProperty "user.home") (io/file ".cisql"))) (declare ^:private run-file) (declare ^:private run-reader) (defn- invoke "Invoke the directive or command-event-loop function and handle errors." [handle-fn query-data & args] (log/debugf "invoke: %s <%s>" handle-fn (pr-str query-data)) (binding [parse/*dump-jvm-on-error* false parse/*rethrow-error* (conf/config :prex) parse/*include-program-in-errors* false] (with-exception (apply handle-fn query-data args)))) (defn- process-query "Process the query data, which is a query or directive processing." [dir-fn query-data directive directives] (cond dir-fn (invoke dir-fn query-data) (map? directive) (let [{:keys [name args]} directive {:keys [fn]} (get directives (clojure.core/name name))] (log/tracef "name %s -> fn %s (%s)" name fn directive) (if-not fn (-> (pr-str directive) (#(format "no function defined for directive %s: %s" name %)) (ex-info {:directive directive :query-data query-data}) throw)) (let [context (assoc query-data :last-query @last-query)] (log/debugf "context: <%s>" (pr-str context)) (invoke fn context args))) true (-> (format "unknown query--probably missing query terminator (%s): %s" :linesep (trunc (pr-str query-data))) (ex-info {:query-data (trunc query-data)}) throw))) (defn process-queries "Process a line of user input and use callback functions **dir-fns**, which is a map of functions that are called by key based on the following actions: * **:end-query** called when the user is completed her input and wants to send it to be processed * **:end-session** the user has given the exit command * **:end-file** the user has hit the end of file sequence (CTRL-D)" ([dir-fns] (process-queries dir-fns nil)) ([dir-fns query-data] (log/debugf "entry query-data: %s" query-data) (let [one-shot? (not (nil? query-data))] (loop [query-data (or query-data (r/read-query))] (log/debugf "query data: %s" query-data) (let [{:keys [directive]} query-data dir-fn (get dir-fns directive) directives (di/directives-by-name)] (log/tracef "directive: %s" directive) (let [res (process-query dir-fn query-data directive directives)] (when (map? res) (cond (contains? res :eval) (doseq [user-input (:eval res)] (with-open [reader (-> (StringReader. user-input) (BufferedReader.))] (run-reader reader))) (contains? res :run) (doseq [file (:run res)] (run-file file))))) (when (and (not one-shot?) (= :end-of-query directive)) (log/debug "while read") (recur (r/read-query)))))) (log/debugf "leave query-data: %s" query-data))) (defn- init-thread-exception-handler "Configure a default exception handler so we swallow exceptions in forked threads." [] (Thread/setDefaultUncaughtExceptionHandler (reify Thread$UncaughtExceptionHandler (uncaughtException [_ thread ex] (log/error ex "Uncaught exception on" (.getName thread)))))) (defn- run-reader [reader] (binding [r/*std-in* reader r/*print-prompt* false] (let [loop-again (atom true)] (letfn [(stop-loop [_] (reset! loop-again false))] (while @loop-again (process-queries {:end-of-query (fn [{:keys [query]}] (db/assert-connection) (db/execute-query query)) :end-of-session stop-loop :end-file stop-loop})))))) (defn- run-file [file] (with-open [reader (io/reader file)] (run-reader reader))) (defn start-event-loop "Start the command event loop using standard in/out." [] (init-thread-exception-handler) (di/init-grammer) (db/configure-db-access) (try (if (.exists init-file) (run-file init-file)) (catch Exception e (log/error e))) (while true (try (binding [r/*std-in* (BufferedReader. (InputStreamReader. System/in))] (process-queries {:end-of-query (fn [{:keys [query]}] (db/assert-connection) (db/execute-query query) (if query (reset! last-query query))) :end-of-session (fn [_] (println "exiting...") (System/exit 0)) :end-file (fn [_] (System/exit 0))})) (catch Exception e (log/error e)))))
27409
(ns ^{:doc "Process query at the command line from user input." :author "<NAME>"} zensols.cisql.process-query (:import (java.io BufferedReader InputStreamReader StringReader)) (:require [clojure.tools.logging :as log] [clojure.java.io :as io] [clojure.string :as str] [zensols.actioncli.log4j2 :as lu] [zensols.actioncli.util :refer (trunc)] [zensols.actioncli.parse :as parse :refer (with-exception)] [zensols.cisql.conf :as conf] [zensols.cisql.db-access :as db] [zensols.cisql.read :as r] [zensols.cisql.directive :as di])) (def ^:private last-query (atom nil)) (def ^:private init-file (-> (System/getProperty "user.home") (io/file ".cisql"))) (declare ^:private run-file) (declare ^:private run-reader) (defn- invoke "Invoke the directive or command-event-loop function and handle errors." [handle-fn query-data & args] (log/debugf "invoke: %s <%s>" handle-fn (pr-str query-data)) (binding [parse/*dump-jvm-on-error* false parse/*rethrow-error* (conf/config :prex) parse/*include-program-in-errors* false] (with-exception (apply handle-fn query-data args)))) (defn- process-query "Process the query data, which is a query or directive processing." [dir-fn query-data directive directives] (cond dir-fn (invoke dir-fn query-data) (map? directive) (let [{:keys [name args]} directive {:keys [fn]} (get directives (clojure.core/name name))] (log/tracef "name %s -> fn %s (%s)" name fn directive) (if-not fn (-> (pr-str directive) (#(format "no function defined for directive %s: %s" name %)) (ex-info {:directive directive :query-data query-data}) throw)) (let [context (assoc query-data :last-query @last-query)] (log/debugf "context: <%s>" (pr-str context)) (invoke fn context args))) true (-> (format "unknown query--probably missing query terminator (%s): %s" :linesep (trunc (pr-str query-data))) (ex-info {:query-data (trunc query-data)}) throw))) (defn process-queries "Process a line of user input and use callback functions **dir-fns**, which is a map of functions that are called by key based on the following actions: * **:end-query** called when the user is completed her input and wants to send it to be processed * **:end-session** the user has given the exit command * **:end-file** the user has hit the end of file sequence (CTRL-D)" ([dir-fns] (process-queries dir-fns nil)) ([dir-fns query-data] (log/debugf "entry query-data: %s" query-data) (let [one-shot? (not (nil? query-data))] (loop [query-data (or query-data (r/read-query))] (log/debugf "query data: %s" query-data) (let [{:keys [directive]} query-data dir-fn (get dir-fns directive) directives (di/directives-by-name)] (log/tracef "directive: %s" directive) (let [res (process-query dir-fn query-data directive directives)] (when (map? res) (cond (contains? res :eval) (doseq [user-input (:eval res)] (with-open [reader (-> (StringReader. user-input) (BufferedReader.))] (run-reader reader))) (contains? res :run) (doseq [file (:run res)] (run-file file))))) (when (and (not one-shot?) (= :end-of-query directive)) (log/debug "while read") (recur (r/read-query)))))) (log/debugf "leave query-data: %s" query-data))) (defn- init-thread-exception-handler "Configure a default exception handler so we swallow exceptions in forked threads." [] (Thread/setDefaultUncaughtExceptionHandler (reify Thread$UncaughtExceptionHandler (uncaughtException [_ thread ex] (log/error ex "Uncaught exception on" (.getName thread)))))) (defn- run-reader [reader] (binding [r/*std-in* reader r/*print-prompt* false] (let [loop-again (atom true)] (letfn [(stop-loop [_] (reset! loop-again false))] (while @loop-again (process-queries {:end-of-query (fn [{:keys [query]}] (db/assert-connection) (db/execute-query query)) :end-of-session stop-loop :end-file stop-loop})))))) (defn- run-file [file] (with-open [reader (io/reader file)] (run-reader reader))) (defn start-event-loop "Start the command event loop using standard in/out." [] (init-thread-exception-handler) (di/init-grammer) (db/configure-db-access) (try (if (.exists init-file) (run-file init-file)) (catch Exception e (log/error e))) (while true (try (binding [r/*std-in* (BufferedReader. (InputStreamReader. System/in))] (process-queries {:end-of-query (fn [{:keys [query]}] (db/assert-connection) (db/execute-query query) (if query (reset! last-query query))) :end-of-session (fn [_] (println "exiting...") (System/exit 0)) :end-file (fn [_] (System/exit 0))})) (catch Exception e (log/error e)))))
true
(ns ^{:doc "Process query at the command line from user input." :author "PI:NAME:<NAME>END_PI"} zensols.cisql.process-query (:import (java.io BufferedReader InputStreamReader StringReader)) (:require [clojure.tools.logging :as log] [clojure.java.io :as io] [clojure.string :as str] [zensols.actioncli.log4j2 :as lu] [zensols.actioncli.util :refer (trunc)] [zensols.actioncli.parse :as parse :refer (with-exception)] [zensols.cisql.conf :as conf] [zensols.cisql.db-access :as db] [zensols.cisql.read :as r] [zensols.cisql.directive :as di])) (def ^:private last-query (atom nil)) (def ^:private init-file (-> (System/getProperty "user.home") (io/file ".cisql"))) (declare ^:private run-file) (declare ^:private run-reader) (defn- invoke "Invoke the directive or command-event-loop function and handle errors." [handle-fn query-data & args] (log/debugf "invoke: %s <%s>" handle-fn (pr-str query-data)) (binding [parse/*dump-jvm-on-error* false parse/*rethrow-error* (conf/config :prex) parse/*include-program-in-errors* false] (with-exception (apply handle-fn query-data args)))) (defn- process-query "Process the query data, which is a query or directive processing." [dir-fn query-data directive directives] (cond dir-fn (invoke dir-fn query-data) (map? directive) (let [{:keys [name args]} directive {:keys [fn]} (get directives (clojure.core/name name))] (log/tracef "name %s -> fn %s (%s)" name fn directive) (if-not fn (-> (pr-str directive) (#(format "no function defined for directive %s: %s" name %)) (ex-info {:directive directive :query-data query-data}) throw)) (let [context (assoc query-data :last-query @last-query)] (log/debugf "context: <%s>" (pr-str context)) (invoke fn context args))) true (-> (format "unknown query--probably missing query terminator (%s): %s" :linesep (trunc (pr-str query-data))) (ex-info {:query-data (trunc query-data)}) throw))) (defn process-queries "Process a line of user input and use callback functions **dir-fns**, which is a map of functions that are called by key based on the following actions: * **:end-query** called when the user is completed her input and wants to send it to be processed * **:end-session** the user has given the exit command * **:end-file** the user has hit the end of file sequence (CTRL-D)" ([dir-fns] (process-queries dir-fns nil)) ([dir-fns query-data] (log/debugf "entry query-data: %s" query-data) (let [one-shot? (not (nil? query-data))] (loop [query-data (or query-data (r/read-query))] (log/debugf "query data: %s" query-data) (let [{:keys [directive]} query-data dir-fn (get dir-fns directive) directives (di/directives-by-name)] (log/tracef "directive: %s" directive) (let [res (process-query dir-fn query-data directive directives)] (when (map? res) (cond (contains? res :eval) (doseq [user-input (:eval res)] (with-open [reader (-> (StringReader. user-input) (BufferedReader.))] (run-reader reader))) (contains? res :run) (doseq [file (:run res)] (run-file file))))) (when (and (not one-shot?) (= :end-of-query directive)) (log/debug "while read") (recur (r/read-query)))))) (log/debugf "leave query-data: %s" query-data))) (defn- init-thread-exception-handler "Configure a default exception handler so we swallow exceptions in forked threads." [] (Thread/setDefaultUncaughtExceptionHandler (reify Thread$UncaughtExceptionHandler (uncaughtException [_ thread ex] (log/error ex "Uncaught exception on" (.getName thread)))))) (defn- run-reader [reader] (binding [r/*std-in* reader r/*print-prompt* false] (let [loop-again (atom true)] (letfn [(stop-loop [_] (reset! loop-again false))] (while @loop-again (process-queries {:end-of-query (fn [{:keys [query]}] (db/assert-connection) (db/execute-query query)) :end-of-session stop-loop :end-file stop-loop})))))) (defn- run-file [file] (with-open [reader (io/reader file)] (run-reader reader))) (defn start-event-loop "Start the command event loop using standard in/out." [] (init-thread-exception-handler) (di/init-grammer) (db/configure-db-access) (try (if (.exists init-file) (run-file init-file)) (catch Exception e (log/error e))) (while true (try (binding [r/*std-in* (BufferedReader. (InputStreamReader. System/in))] (process-queries {:end-of-query (fn [{:keys [query]}] (db/assert-connection) (db/execute-query query) (if query (reset! last-query query))) :end-of-session (fn [_] (println "exiting...") (System/exit 0)) :end-file (fn [_] (System/exit 0))})) (catch Exception e (log/error e)))))
[ { "context": "; Copyright (c) 2013-2015 Tim Molderez.\n;\n; All rights reserved. This program and the ac", "end": 38, "score": 0.9998670816421509, "start": 26, "tag": "NAME", "value": "Tim Molderez" }, { "context": "ector Jay's graphical user interface\"\n {:author \"Tim Molderez\"}\n (:require\n [clojure.string :as s]\n [clo", "end": 387, "score": 0.9998829364776611, "start": 375, "tag": "NAME", "value": "Tim Molderez" } ]
src/inspector_jay/gui/gui.clj
kawas44/inspector-jay
69
; Copyright (c) 2013-2015 Tim Molderez. ; ; All rights reserved. This program and the accompanying materials ; are made available under the terms of the 3-Clause BSD License ; which accompanies this distribution, and is available at ; http://www.opensource.org/licenses/BSD-3-Clause (ns inspector-jay.gui.gui "Defines Inspector Jay's graphical user interface" {:author "Tim Molderez"} (:require [clojure.string :as s] [clojure.java [io :as io] [javadoc :as jdoc]] [seesaw [core :as seesaw] [color :as color] [border :as border] [font :as font]] [inspector-jay.gui [utils :as utils] [node-properties :as nprops]] [inspector-jay.model [tree-node :as node] [tree-model :as model]]) (:import [javax.swing Box JTextArea KeyStroke JFrame JPanel JTree JToolBar JComponent JToolBar$Separator UIManager JSplitPane JTabbedPane] [javax.swing.tree DefaultTreeCellRenderer] [javax.swing.event TreeSelectionListener TreeExpansionListener TreeWillExpandListener] [javax.swing.tree ExpandVetoException] [java.awt Rectangle Toolkit] [java.awt.event KeyEvent ActionListener ActionEvent InputEvent WindowEvent] [net.java.balloontip BalloonTip CustomBalloonTip] [net.java.balloontip.positioners LeftAbovePositioner LeftBelowPositioner] [net.java.balloontip.styles IsometricBalloonStyle] [net.java.balloontip.utils TimingUtils])) (seesaw/native!) ; Use the OS's native look and feel (def ^{:doc "When a new inspector is opened, these are the default options. You can customize these options via keyword arguments, e.g. (inspect an-object :sorted false :pause true)"} default-options {; Tree filtering options :sorted true ; Alphabetically sort members :methods true ; Show/hide methods :fields true :public true :protected false :private false :static true :inherited true ; Show/hide inherited members ; Miscellaneous options :window-name nil ; If given a name, the inspector is opened as a new tab in the window with that name. ; If that window does not exist yet, it will be created. This is useful if you want to ; divide your inspectors into groups. :new-window false ; If true, the inspector is opened in a new window. ; Otherwise, the inspector is opened as a new tab. ; This option is ignored if :window-name is used. :pause false ; If true, the current thread will be paused when opening an inspector. ; Execution will resume either when clicking the resume button, or closing the inspector tab/window. :vars nil ; You can use this to pass in any extra information to an inspector window. ; This is useful when invoking a method in the inspector, and you need to fill in some argument values. ; The value of :vars will then be available in the inspector under the variable named vars. }) (def ^{:doc "Inspectory Jay GUI options"} gui-options {:width 1024 :height 768 :font (font/font :name :sans-serif :style #{:plain}) :crumb-length 32 :max-tabs 64 :btip-style `(new IsometricBalloonStyle (UIManager/getColor "Panel.background") (color/color "#268bd2") 5) :btip-error-style `(new IsometricBalloonStyle (UIManager/getColor "Panel.background") (color/color "#d32e27") 3) :btip-positioner `(new LeftAbovePositioner 8 5)}) (declare inspector-window) ; Forward declaration ; Global variable! List of all open Inspector Jay windows (Each element is a map with keys :window and :name) (def jay-windows (atom [])) ; Global variable! Keeps track of the last selected tree node. (across all tabs/windows) (def last-selected-node (atom nil)) (defn- error "Show an error message near a given component" [^String message ^JComponent component] (TimingUtils/showTimedBalloon (new BalloonTip component (seesaw/label message) (eval (gui-options :btip-error-style)) (eval (gui-options :btip-positioner)) nil) 3000) (-> (Toolkit/getDefaultToolkit) .beep)) (defn- tree-renderer "Returns a cell renderer which defines what each tree node should look like" ^DefaultTreeCellRenderer [] (proxy [DefaultTreeCellRenderer] [] (getTreeCellRendererComponent [tree value selected expanded leaf row hasFocus] (proxy-super getTreeCellRendererComponent tree value selected expanded leaf row hasFocus) (-> this (.setText (nprops/to-string value))) (-> this (.setIcon (nprops/get-icon value))) this))) (defn last-selected-value "Retrieve the value of the tree node that was last selected. (An exception is thrown if we can't automatically obtain this value .. e.g. in case the value is not available yet and the last selected node is a method with parameters.)" [] (.getValue @last-selected-node)) (defn- tree-selection-listener "Whenever a tree node is selected, update the detailed information panel, the breadcrumbs, and the last-selected-value variable." ^TreeSelectionListener [info-panel crumbs-panel] (proxy [TreeSelectionListener] [] (valueChanged [event] (let [new-path (-> event .getNewLeadSelectionPath)] (if (not= new-path nil) (let [new-node (-> new-path .getLastPathComponent)] (swap! last-selected-node (fn [x] new-node)) (seesaw/config! info-panel :text (nprops/to-string-verbose new-node)) (seesaw/config! crumbs-panel :text (str "<html>" (s/join (interpose "<font color=\"#268bd2\"><b> &gt; </b></font>" (map (fn [x] (nprops/to-string-breadcrumb x (:crumb-length gui-options))) (-> new-path .getPath)))) "</html>")))))))) (defn- tree-expansion-listener "Updates the detailed information panel whenever a node is expanded." ^TreeExpansionListener [info-panel] (proxy [TreeExpansionListener] [] (treeExpanded [event] (seesaw/config! info-panel :text (nprops/to-string-verbose (-> event .getPath .getLastPathComponent)))) (treeCollapsed [event]))) (defn- tree-will-expand-listener "Displays a dialog if the user needs to enter some actual parameters to invoke a method." ^TreeWillExpandListener [shared-vars] (proxy [TreeWillExpandListener] [] (treeWillExpand [event] (let [jtree (-> event .getSource) node (-> event .getPath .getLastPathComponent)] (if (not (-> node .isValueAvailable)) (if (= 0 (count (-> node .getMethod .getParameterTypes))) ; No parameters needed; we can simply call .getValue to make the value available (-> node .getValue) ; Otherwise we'll need to ask the user to enter some parameter values (let [raw-types (-> node .getMethod .getParameterTypes) ; Swap Java's primitive types for their corresponding wrappers param-types (for [x raw-types] (let [type (-> x .toString)] (cond (= type "byte") java.lang.Byte (= type "short") java.lang.Short (= type "int") java.lang.Integer (= type "long") java.lang.Long (= type "float") java.lang.Float (= type "double") java.lang.Double (= type "boolean") java.lang.Boolean (= type "char") java.lang.Character :else x))) param-boxes (for [x param-types] (seesaw/text :tip (-> x .getSimpleName) :columns 32 )) params (seesaw/grid-panel :rows (inc (count param-types)) :columns 1) ok-button (seesaw/button :text "Call") cancel-button (seesaw/button :text "Cancel") buttons (seesaw/flow-panel) border-panel (seesaw/border-panel :center params :south buttons)] (-> buttons (.add ok-button)) (-> buttons (.add cancel-button)) (-> params (.add (seesaw/label "Enter parameter values to call this method:"))) (doseq [x param-boxes] (-> params (.add x))) (let [; Form to enter paramter values btip (new CustomBalloonTip jtree border-panel (-> jtree (.getPathBounds (-> event .getPath))) (eval (gui-options :btip-style)) (eval (gui-options :btip-positioner)) nil) ; Button to submit the form, and invoke the requested method ok-handler (fn [e] (try (let [args (for [i (range 0 (count param-boxes))] ; Try to evaluate the expression to obtain the current parameter's value (try (let [value (node/eval-arg (-> (nth param-boxes i) .getText) shared-vars) type (nth param-types i)] (cond ; Do primitive type conversion when necessary (= type java.lang.Short) (short value) ; Convert long to short (= type java.lang.Float) (float value) ; Convert double to float (= type java.lang.Integer) (int value) ; Convert long to int :else value)) (catch Exception e (do (error (-> e .getMessage) (nth param-boxes i)) (throw (Exception.))))))] (doseq [x args] x) ; If something went wrong with the arguments, this should trigger the exception before attempting an invocation.. (-> node (.invokeMethod args)) (-> btip .closeBalloon) (-> jtree (.expandPath (-> event .getPath))) (-> jtree (.setSelectionPath (-> event .getPath))) (-> jtree .requestFocus)) (catch Exception e ))) cancel-handler (fn [e] (-> btip .closeBalloon) (-> jtree .requestFocus)) key-handler (fn [e] (cond (= (-> e .getKeyCode) KeyEvent/VK_ENTER) (ok-handler e) (= (-> e .getKeyCode) KeyEvent/VK_ESCAPE) (cancel-handler e)))] (-> (first param-boxes) .requestFocus) (doseq [x param-boxes] (seesaw/listen x :key-pressed key-handler)) (seesaw/listen cancel-button :action (fn [e] (-> btip .closeBalloon) (-> jtree .requestFocus))) (seesaw/listen ok-button :action ok-handler)) (throw (new ExpandVetoException event))))))) ; Deny expanding the tree node; it will only be expanded once the value is available (treeWillCollapse [event]))) (defn- open-javadoc "Search Javadoc for the selected node (if present)" [jtree] (let [selection (-> jtree .getLastSelectedPathComponent)] (if (not= selection nil) (jdoc/javadoc (nprops/get-javadoc-class selection))))) (defn- inspect-node "Open the currently selected node in a new inspector" [jtree inspect-button] (let [selection (-> jtree .getLastSelectedPathComponent)] (if (-> selection .hasValue) (let [window (seesaw/to-root jtree) name (some (fn [w] (when (= (:window w) window) (:name w))) @jay-windows)] (inspector-window (-> selection .getValue) :window-name name)) (if (= (-> selection .getKind) :method) (error "Can't inspect the return value of this method. (Have you already called it?)" inspect-button) (error "Can't inspect this node; it doesn't have a value." inspect-button)))) ) (defn- reinvoke "(Re)invoke the selected method node" [jtree] (let [selection (-> jtree .getLastSelectedPathComponent) selection-path (-> jtree .getSelectionPath) selection-row (-> jtree (.getRowForPath selection-path))] (if (= (-> selection .getKind) :method) (do (-> jtree (.collapsePath selection-path)) (-> jtree .getModel (.valueForPathChanged selection-path (node/object-node (new Object)))) (-> jtree (.expandRow selection-row)) (-> jtree (.setSelectionRow selection-row)))))) (defn- resume-execution "Wake up any threads waiting for a lock object" [lock] (locking lock (.notify lock))) (defn- search-tree "Search a JTree for the first visible node whose value contains 'key', starting from the node at row 'start-row'. If 'forward' is true, we search going forward; otherwise backwards. If a matching node is found, its path is returned; otherwise nil is returned." [^JTree tree ^String key start-row forward include-current] (let [max-rows (-> tree .getRowCount) ukey (-> key .toUpperCase) increment (if forward 1 -1) start (if include-current start-row (mod (+ start-row increment max-rows) max-rows))] ; Keep looking through all rows until we either find a match, or we're back at the start (loop [row start] (let [path (-> tree (.getPathForRow row)) node (nprops/to-string (-> path .getLastPathComponent)) next-row (mod (+ row increment max-rows) max-rows)] (if (-> node .toUpperCase (.contains ukey)) path (if (not= next-row start) (recur next-row) nil)))))) (defn- search-tree-and-select "Search the inspector tree and select the node that was found, if any" [^JTree tree text forward include-current] (let [start-row (if (-> tree .isSelectionEmpty) 0 (-> tree .getLeadSelectionRow)) next-match (search-tree tree text start-row forward include-current)] (if (not= next-match nil) (doto tree (.setSelectionPath next-match) (.scrollPathToVisible next-match)) (-> (Toolkit/getDefaultToolkit) .beep)))) (defn- tool-panel "Create the toolbar of the Inspector Jay window" ^JToolBar [^Object object ^JTree jtree ^JSplitPane split-pane tree-options] (let [iconSize [24 :by 24] sort-button (seesaw/toggle :icon (seesaw/icon (io/resource "icons/alphab_sort_co.gif")) :size iconSize :selected? (tree-options :sorted)) filter-button (seesaw/button :icon (seesaw/icon (io/resource "icons/filter_history.gif")) :size iconSize) filter-methods (seesaw/checkbox :text "Methods" :selected? (tree-options :methods)) filter-fields (seesaw/checkbox :text "Fields" :selected? (tree-options :fields)) filter-public (seesaw/checkbox :text "Public" :selected? (tree-options :public)) filter-protected (seesaw/checkbox :text "Protected" :selected? (tree-options :protected)) filter-private (seesaw/checkbox :text "Private" :selected? (tree-options :private)) filter-static (seesaw/checkbox :text "Static" :selected? (tree-options :static)) filter-inherited (seesaw/checkbox :text "Inherited" :selected? (tree-options :inherited)) ; Function to refresh the inspector tree given the current options in the filter menu update-filters (fn [e] (-> jtree (.setModel (model/tree-model object {:sorted (-> sort-button .isSelected) :methods (-> filter-methods .isSelected) :fields (-> filter-fields .isSelected) :public (-> filter-public .isSelected) :protected (-> filter-protected .isSelected) :private (-> filter-private .isSelected) :static (-> filter-static .isSelected) :inherited (-> filter-inherited .isSelected)}))) (-> jtree (.setSelectionPath (-> jtree (.getPathForRow 0))))) filter-panel (seesaw/vertical-panel :items [filter-methods filter-fields (seesaw/separator) filter-public filter-protected filter-private (seesaw/separator) filter-static filter-inherited]) pane-button (seesaw/toggle :icon (seesaw/icon (io/resource "icons/details_view.gif")) :size iconSize :selected? true) inspect-button (seesaw/button :icon (seesaw/icon (io/resource "icons/insp_sbook.gif")) :size iconSize) doc-button (seesaw/button :icon (seesaw/icon (io/resource "icons/javadoc.gif")) :size iconSize) invoke-button (seesaw/button :icon (seesaw/icon (io/resource "icons/runlast_co.gif")) :size iconSize) refresh-button (seesaw/button :icon (seesaw/icon (io/resource "icons/nav_refresh.gif")) :size iconSize) filter-tip (delay (new BalloonTip ; Only create the filter menu once needed filter-button filter-panel (eval (gui-options :btip-style)) (eval (gui-options :btip-positioner)) nil)) resume-button (if (:pause tree-options) (seesaw/button :icon (seesaw/icon (io/resource "icons/resume_co.gif")) :size iconSize)) search-txt (seesaw/text :columns 20 :text "Search...") toolbar-items (remove nil? [sort-button filter-button pane-button inspect-button doc-button invoke-button refresh-button resume-button (Box/createHorizontalGlue) search-txt (Box/createHorizontalStrut 2)]) toolbar (seesaw/toolbar :items toolbar-items)] (doto toolbar (.setBorder (border/empty-border :thickness 1)) (.setFloatable false)) (-> search-txt (.setMaximumSize (-> search-txt .getPreferredSize))) ; Ditch the redundant dotted rectangle when a button is focused (-> sort-button (.setFocusPainted false)) (-> filter-button (.setFocusPainted false)) (-> pane-button (.setFocusPainted false)) (-> inspect-button (.setFocusPainted false)) (-> doc-button (.setFocusPainted false)) (-> invoke-button (.setFocusPainted false)) (-> refresh-button (.setFocusPainted false)) ; Set tooltips (-> sort-button (.setToolTipText "Sort alphabetically")) (-> filter-button (.setToolTipText "Filtering options...")) (-> pane-button (.setToolTipText "Toggle horizontal/vertical layout")) (-> inspect-button (.setToolTipText "Open selected node in new inspector")) (-> doc-button (.setToolTipText "Search Javadoc (F1)")) (-> invoke-button (.setToolTipText "(Re)invoke selected method (F4)")) (-> refresh-button (.setToolTipText "Refresh tree")) (-> search-txt (.setToolTipText "Search visible tree nodes (F3 / Shift-F3)")) ; Resume button (if (:pause tree-options) (do (-> resume-button (.setFocusPainted false)) (-> resume-button (.setToolTipText "Resume execution")) (seesaw/listen resume-button :action (fn [e] (resume-execution (.getParent toolbar)) (-> resume-button (.setEnabled false)) (-> resume-button (.setToolTipText "Resume execution (already resumed)")))))) ; Sort button (seesaw/listen sort-button :action update-filters) ; Open/close filter options menu (seesaw/listen filter-button :action (fn [e] (if (not (realized? filter-tip)) ; If opened for the first time, add a listener that hides the menu on mouse exit (seesaw/listen @filter-tip :mouse-exited (fn [e] (if (not (-> @filter-tip (.contains (-> e .getPoint)))) (-> @filter-tip (.setVisible false))))) (if (-> @filter-tip .isVisible) (-> @filter-tip (.setVisible false)) (-> @filter-tip (.setVisible true)))))) ; Filter checkboxes (seesaw/listen filter-methods :action update-filters) (seesaw/listen filter-fields :action update-filters) (seesaw/listen filter-public :action update-filters) (seesaw/listen filter-protected :action update-filters) (seesaw/listen filter-private :action update-filters) (seesaw/listen filter-static :action update-filters) (seesaw/listen filter-inherited :action update-filters) ; Toggle horizontal/vertical layout (seesaw/listen pane-button :action (fn [e] (if (-> pane-button .isSelected) (-> split-pane (.setOrientation 0)) (-> split-pane (.setOrientation 1))))) ; Open selected node in new inspector (seesaw/listen inspect-button :action (fn [e] (inspect-node jtree inspect-button))) ; Open javadoc of selected tree node (seesaw/listen doc-button :action (fn [e] (open-javadoc jtree))) ; (Re)invoke the selected method (seesaw/listen invoke-button :action (fn [e] (reinvoke jtree))) ; Refresh the tree (seesaw/listen refresh-button :action update-filters) ; Clear search field initially (seesaw/listen search-txt :focus-gained (fn [e] (-> search-txt (.setText "")) (-> search-txt (.removeFocusListener (last(-> search-txt (.getFocusListeners))))))) ; When typing in the search field, look for matches (seesaw/listen search-txt #{:remove-update :insert-update} (fn [e] (search-tree-and-select jtree (-> search-txt .getText) true true))) toolbar)) (defn- get-jtree "Retrieve the object tree from an inspector Jay panel" [^JPanel panel] (let [split-pane (nth (-> panel .getComponents) 2) scroll-pane (nth (-> split-pane .getComponents) 2) viewport (nth (-> scroll-pane .getComponents) 0) jtree (-> viewport .getView)] jtree)) (defn- get-search-field "Retrieve the search field from an inspector Jay panel" [^JPanel panel] (let [toolbar (nth (-> panel .getComponents) 0) idx (- (count (-> toolbar .getComponents)) 2) ; It's the second to last component in the toolbar.. search-field (nth (-> toolbar .getComponents) idx)] search-field)) (defn- get-selected-tab "Retrieve the currently selected tab of an inspector Jay window" ^JPanel [^JFrame window] (let [content (-> window .getContentPane)] (if (instance? JTabbedPane content) (-> content .getSelectedComponent) content))) (defn- close-tab "Close the currently selected tab in an Inspector Jay window" [window tab] (let [content (-> window .getContentPane) isTabbed (instance? JTabbedPane content)] (if (not isTabbed) ; Close the window if there only is one object opened (-> window (.dispatchEvent (new WindowEvent window WindowEvent/WINDOW_CLOSING))) ; Close the tab (do (resume-execution (-> content (.getComponentAt (-> content .getSelectedIndex)))) (-> content (.removeTabAt (-> content .getSelectedIndex))) ; Go back to an untabbed interface if there's only one tab left (if (= 1 (-> content .getTabCount)) (-> window (.setContentPane (-> content (.getSelectedComponent))))))))) (defn- bind-keys "Attach various key bindings to an Inspector Jay window" [frame] (let [f1-key (KeyStroke/getKeyStroke KeyEvent/VK_F1 0) f3-key (KeyStroke/getKeyStroke KeyEvent/VK_F3 0) f4-key (KeyStroke/getKeyStroke KeyEvent/VK_F4 0) shift-f3-key (KeyStroke/getKeyStroke KeyEvent/VK_F3 InputEvent/SHIFT_DOWN_MASK) ctrl-f-key (KeyStroke/getKeyStroke KeyEvent/VK_F (-> (Toolkit/getDefaultToolkit) .getMenuShortcutKeyMask)) ; Cmd on a Mac, Ctrl elsewhere ctrl-w-key (KeyStroke/getKeyStroke KeyEvent/VK_W (-> (Toolkit/getDefaultToolkit) .getMenuShortcutKeyMask))] ; Search javadoc for the currently selected node and open it in a browser window (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (open-javadoc (get-jtree (get-selected-tab frame))))) f1-key JComponent/WHEN_IN_FOCUSED_WINDOW)) ; (Re)invoke selected method (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (reinvoke (get-jtree (get-selected-tab frame))))) f4-key JComponent/WHEN_IN_FOCUSED_WINDOW)) ; Find next (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (let [tab (get-selected-tab frame)] (search-tree-and-select (get-jtree tab) (-> (get-search-field tab) .getText) true false)))) f3-key JComponent/WHEN_IN_FOCUSED_WINDOW)) ; Find previous (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (let [tab (get-selected-tab frame)] (search-tree-and-select (get-jtree tab) (-> (get-search-field tab) .getText) false false)))) shift-f3-key JComponent/WHEN_IN_FOCUSED_WINDOW)) ; Go to search field (or back to the tree) (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (let [tab (get-selected-tab frame) search-field (get-search-field tab)] (if (-> search-field .hasFocus) (-> (get-jtree tab) .requestFocus) (-> search-field .requestFocus))))) ctrl-f-key JComponent/WHEN_IN_FOCUSED_WINDOW)) ; Close the current tab (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (close-tab frame (get-selected-tab frame)))) ctrl-w-key JComponent/WHEN_IN_FOCUSED_WINDOW)))) (defn inspector-panel "Create and show an Inspector Jay window to inspect a given object. See default-options for more information on all available keyword arguments." ^JPanel [^Object object & {:as args}] (let [obj-info (seesaw/text :multi-line? true :editable? false :font (gui-options :font)) obj-tree (seesaw/tree :model (model/tree-model object args)) crumbs (seesaw/label :icon (seesaw/icon (io/resource "icons/toggle_breadcrumb.gif"))) obj-info-scroll (seesaw/scrollable obj-info) obj-tree-scroll (seesaw/scrollable obj-tree) split-pane (seesaw/top-bottom-split obj-info-scroll obj-tree-scroll :divider-location 1/5) toolbar (tool-panel object obj-tree split-pane args) main-panel (seesaw/border-panel :north toolbar :south crumbs :center split-pane)] (-> split-pane (.setDividerSize 9)) (-> obj-info-scroll (.setBorder (border/empty-border))) (-> obj-tree-scroll (.setBorder (border/empty-border))) (doto obj-tree (.setCellRenderer (tree-renderer)) (.addTreeSelectionListener (tree-selection-listener obj-info crumbs)) (.addTreeExpansionListener (tree-expansion-listener obj-info)) (.addTreeWillExpandListener (tree-will-expand-listener (:vars args))) (.setSelectionPath (-> obj-tree (.getPathForRow 0)))) main-panel)) (defn- close-window "Clean up when closing a window" [window] ; Resume any threads that might've been paused by inspectors in this window (let [content (-> window .getContentPane) isTabbed (instance? JTabbedPane content)] (if (not isTabbed) (resume-execution content) (doseq [x (range 0 (.getTabCount content))] (resume-execution (.getComponentAt content x))))) ; Clean up any resources associated with the window (swap! jay-windows (fn [x] (remove (fn [w] (= (:window w) window)) x))) (if (empty? @jay-windows) ; If all windows are closed, reset last-selected-node (swap! last-selected-node (fn [x] nil))) (node/clear-memoization-caches)) (defn- window-title "Compose a window's title" [window-name object] (let [prefix (if (nil? window-name) "Object inspector : " (str window-name " : "))] (str prefix (.toString object)))) (defn inspector-window "Show an Inspector Jay window to inspect a given object. See default-options for more information on all available keyword arguments." [object & {:as args}] (let [merged-args (merge default-options args) win-name (:window-name merged-args) panel (apply inspector-panel object (utils/map-to-keyword-args merged-args))] (seesaw/invoke-later (if (or ; Create a new window if: there are no windows yet, or :new-window is used, or a window with the given name hasn't been created yet. (= 0 (count @jay-windows)) (and (:new-window merged-args) (nil? win-name)) (and (not (nil? win-name)) (not-any? (fn [w] (= win-name (:name w))) @jay-windows))) ; Create a new window (let [window (seesaw/frame :title (window-title win-name object) :size [(gui-options :width) :by (gui-options :height)] :on-close :dispose)] (swap! jay-windows (fn [x] (conj x {:window window :name win-name}))) (seesaw/config! window :content panel) (bind-keys window) ; When the window is closed, remove the window from the list and clear caches (seesaw/listen window :window-closed (fn [e] (close-window window))) (-> window seesaw/show!) (-> (get-jtree panel) .requestFocus)) ; Otherwise, add a new tab (let [window (if (nil? win-name) (:window (last @jay-windows)) ; The most recently created window (some (fn [w] (when (= win-name (:name w)) (:window w))) @jay-windows)) content (-> window .getContentPane) isTabbed (instance? JTabbedPane content)] ; If the tabbed pane has not been created yet (if (not isTabbed) (let [tabs (seesaw/tabbed-panel) title (utils/truncate (-> (get-jtree content) .getModel .getRoot .getValue .toString) 20)] (-> tabs (.setBorder (border/empty-border :top 1 :left 2 :bottom 1 :right 0))) (-> tabs (.add title content)) (-> window (.setContentPane tabs)) ; When switching tabs, adjust the window title, and focus on the tree (seesaw/listen tabs :change (fn [e] (let [tree (get-jtree (get-selected-tab window)) title (window-title win-name (-> tree .getModel .getRoot .getValue))] (-> window (.setTitle title)) (-> tree .requestFocus)))))) (let [tabs (-> window .getContentPane)] ; Add the new tab (doto tabs (.add (utils/truncate (.toString object) 20) panel) (.setSelectedIndex (-> window .getContentPane (.indexOfComponent panel)))) ; Close the first tab, if going beyond the maximum number of tabs (if (> (-> tabs .getTabCount) (:max-tabs gui-options)) (close-tab window (-> tabs (.getComponentAt 0)))) (-> (get-jtree panel) .requestFocus))))) ; If desired, pause the current thread (while the GUI keeps running in a seperate thread) (if (:pause args) (locking panel (.wait panel)))))
47711
; Copyright (c) 2013-2015 <NAME>. ; ; All rights reserved. This program and the accompanying materials ; are made available under the terms of the 3-Clause BSD License ; which accompanies this distribution, and is available at ; http://www.opensource.org/licenses/BSD-3-Clause (ns inspector-jay.gui.gui "Defines Inspector Jay's graphical user interface" {:author "<NAME>"} (:require [clojure.string :as s] [clojure.java [io :as io] [javadoc :as jdoc]] [seesaw [core :as seesaw] [color :as color] [border :as border] [font :as font]] [inspector-jay.gui [utils :as utils] [node-properties :as nprops]] [inspector-jay.model [tree-node :as node] [tree-model :as model]]) (:import [javax.swing Box JTextArea KeyStroke JFrame JPanel JTree JToolBar JComponent JToolBar$Separator UIManager JSplitPane JTabbedPane] [javax.swing.tree DefaultTreeCellRenderer] [javax.swing.event TreeSelectionListener TreeExpansionListener TreeWillExpandListener] [javax.swing.tree ExpandVetoException] [java.awt Rectangle Toolkit] [java.awt.event KeyEvent ActionListener ActionEvent InputEvent WindowEvent] [net.java.balloontip BalloonTip CustomBalloonTip] [net.java.balloontip.positioners LeftAbovePositioner LeftBelowPositioner] [net.java.balloontip.styles IsometricBalloonStyle] [net.java.balloontip.utils TimingUtils])) (seesaw/native!) ; Use the OS's native look and feel (def ^{:doc "When a new inspector is opened, these are the default options. You can customize these options via keyword arguments, e.g. (inspect an-object :sorted false :pause true)"} default-options {; Tree filtering options :sorted true ; Alphabetically sort members :methods true ; Show/hide methods :fields true :public true :protected false :private false :static true :inherited true ; Show/hide inherited members ; Miscellaneous options :window-name nil ; If given a name, the inspector is opened as a new tab in the window with that name. ; If that window does not exist yet, it will be created. This is useful if you want to ; divide your inspectors into groups. :new-window false ; If true, the inspector is opened in a new window. ; Otherwise, the inspector is opened as a new tab. ; This option is ignored if :window-name is used. :pause false ; If true, the current thread will be paused when opening an inspector. ; Execution will resume either when clicking the resume button, or closing the inspector tab/window. :vars nil ; You can use this to pass in any extra information to an inspector window. ; This is useful when invoking a method in the inspector, and you need to fill in some argument values. ; The value of :vars will then be available in the inspector under the variable named vars. }) (def ^{:doc "Inspectory Jay GUI options"} gui-options {:width 1024 :height 768 :font (font/font :name :sans-serif :style #{:plain}) :crumb-length 32 :max-tabs 64 :btip-style `(new IsometricBalloonStyle (UIManager/getColor "Panel.background") (color/color "#268bd2") 5) :btip-error-style `(new IsometricBalloonStyle (UIManager/getColor "Panel.background") (color/color "#d32e27") 3) :btip-positioner `(new LeftAbovePositioner 8 5)}) (declare inspector-window) ; Forward declaration ; Global variable! List of all open Inspector Jay windows (Each element is a map with keys :window and :name) (def jay-windows (atom [])) ; Global variable! Keeps track of the last selected tree node. (across all tabs/windows) (def last-selected-node (atom nil)) (defn- error "Show an error message near a given component" [^String message ^JComponent component] (TimingUtils/showTimedBalloon (new BalloonTip component (seesaw/label message) (eval (gui-options :btip-error-style)) (eval (gui-options :btip-positioner)) nil) 3000) (-> (Toolkit/getDefaultToolkit) .beep)) (defn- tree-renderer "Returns a cell renderer which defines what each tree node should look like" ^DefaultTreeCellRenderer [] (proxy [DefaultTreeCellRenderer] [] (getTreeCellRendererComponent [tree value selected expanded leaf row hasFocus] (proxy-super getTreeCellRendererComponent tree value selected expanded leaf row hasFocus) (-> this (.setText (nprops/to-string value))) (-> this (.setIcon (nprops/get-icon value))) this))) (defn last-selected-value "Retrieve the value of the tree node that was last selected. (An exception is thrown if we can't automatically obtain this value .. e.g. in case the value is not available yet and the last selected node is a method with parameters.)" [] (.getValue @last-selected-node)) (defn- tree-selection-listener "Whenever a tree node is selected, update the detailed information panel, the breadcrumbs, and the last-selected-value variable." ^TreeSelectionListener [info-panel crumbs-panel] (proxy [TreeSelectionListener] [] (valueChanged [event] (let [new-path (-> event .getNewLeadSelectionPath)] (if (not= new-path nil) (let [new-node (-> new-path .getLastPathComponent)] (swap! last-selected-node (fn [x] new-node)) (seesaw/config! info-panel :text (nprops/to-string-verbose new-node)) (seesaw/config! crumbs-panel :text (str "<html>" (s/join (interpose "<font color=\"#268bd2\"><b> &gt; </b></font>" (map (fn [x] (nprops/to-string-breadcrumb x (:crumb-length gui-options))) (-> new-path .getPath)))) "</html>")))))))) (defn- tree-expansion-listener "Updates the detailed information panel whenever a node is expanded." ^TreeExpansionListener [info-panel] (proxy [TreeExpansionListener] [] (treeExpanded [event] (seesaw/config! info-panel :text (nprops/to-string-verbose (-> event .getPath .getLastPathComponent)))) (treeCollapsed [event]))) (defn- tree-will-expand-listener "Displays a dialog if the user needs to enter some actual parameters to invoke a method." ^TreeWillExpandListener [shared-vars] (proxy [TreeWillExpandListener] [] (treeWillExpand [event] (let [jtree (-> event .getSource) node (-> event .getPath .getLastPathComponent)] (if (not (-> node .isValueAvailable)) (if (= 0 (count (-> node .getMethod .getParameterTypes))) ; No parameters needed; we can simply call .getValue to make the value available (-> node .getValue) ; Otherwise we'll need to ask the user to enter some parameter values (let [raw-types (-> node .getMethod .getParameterTypes) ; Swap Java's primitive types for their corresponding wrappers param-types (for [x raw-types] (let [type (-> x .toString)] (cond (= type "byte") java.lang.Byte (= type "short") java.lang.Short (= type "int") java.lang.Integer (= type "long") java.lang.Long (= type "float") java.lang.Float (= type "double") java.lang.Double (= type "boolean") java.lang.Boolean (= type "char") java.lang.Character :else x))) param-boxes (for [x param-types] (seesaw/text :tip (-> x .getSimpleName) :columns 32 )) params (seesaw/grid-panel :rows (inc (count param-types)) :columns 1) ok-button (seesaw/button :text "Call") cancel-button (seesaw/button :text "Cancel") buttons (seesaw/flow-panel) border-panel (seesaw/border-panel :center params :south buttons)] (-> buttons (.add ok-button)) (-> buttons (.add cancel-button)) (-> params (.add (seesaw/label "Enter parameter values to call this method:"))) (doseq [x param-boxes] (-> params (.add x))) (let [; Form to enter paramter values btip (new CustomBalloonTip jtree border-panel (-> jtree (.getPathBounds (-> event .getPath))) (eval (gui-options :btip-style)) (eval (gui-options :btip-positioner)) nil) ; Button to submit the form, and invoke the requested method ok-handler (fn [e] (try (let [args (for [i (range 0 (count param-boxes))] ; Try to evaluate the expression to obtain the current parameter's value (try (let [value (node/eval-arg (-> (nth param-boxes i) .getText) shared-vars) type (nth param-types i)] (cond ; Do primitive type conversion when necessary (= type java.lang.Short) (short value) ; Convert long to short (= type java.lang.Float) (float value) ; Convert double to float (= type java.lang.Integer) (int value) ; Convert long to int :else value)) (catch Exception e (do (error (-> e .getMessage) (nth param-boxes i)) (throw (Exception.))))))] (doseq [x args] x) ; If something went wrong with the arguments, this should trigger the exception before attempting an invocation.. (-> node (.invokeMethod args)) (-> btip .closeBalloon) (-> jtree (.expandPath (-> event .getPath))) (-> jtree (.setSelectionPath (-> event .getPath))) (-> jtree .requestFocus)) (catch Exception e ))) cancel-handler (fn [e] (-> btip .closeBalloon) (-> jtree .requestFocus)) key-handler (fn [e] (cond (= (-> e .getKeyCode) KeyEvent/VK_ENTER) (ok-handler e) (= (-> e .getKeyCode) KeyEvent/VK_ESCAPE) (cancel-handler e)))] (-> (first param-boxes) .requestFocus) (doseq [x param-boxes] (seesaw/listen x :key-pressed key-handler)) (seesaw/listen cancel-button :action (fn [e] (-> btip .closeBalloon) (-> jtree .requestFocus))) (seesaw/listen ok-button :action ok-handler)) (throw (new ExpandVetoException event))))))) ; Deny expanding the tree node; it will only be expanded once the value is available (treeWillCollapse [event]))) (defn- open-javadoc "Search Javadoc for the selected node (if present)" [jtree] (let [selection (-> jtree .getLastSelectedPathComponent)] (if (not= selection nil) (jdoc/javadoc (nprops/get-javadoc-class selection))))) (defn- inspect-node "Open the currently selected node in a new inspector" [jtree inspect-button] (let [selection (-> jtree .getLastSelectedPathComponent)] (if (-> selection .hasValue) (let [window (seesaw/to-root jtree) name (some (fn [w] (when (= (:window w) window) (:name w))) @jay-windows)] (inspector-window (-> selection .getValue) :window-name name)) (if (= (-> selection .getKind) :method) (error "Can't inspect the return value of this method. (Have you already called it?)" inspect-button) (error "Can't inspect this node; it doesn't have a value." inspect-button)))) ) (defn- reinvoke "(Re)invoke the selected method node" [jtree] (let [selection (-> jtree .getLastSelectedPathComponent) selection-path (-> jtree .getSelectionPath) selection-row (-> jtree (.getRowForPath selection-path))] (if (= (-> selection .getKind) :method) (do (-> jtree (.collapsePath selection-path)) (-> jtree .getModel (.valueForPathChanged selection-path (node/object-node (new Object)))) (-> jtree (.expandRow selection-row)) (-> jtree (.setSelectionRow selection-row)))))) (defn- resume-execution "Wake up any threads waiting for a lock object" [lock] (locking lock (.notify lock))) (defn- search-tree "Search a JTree for the first visible node whose value contains 'key', starting from the node at row 'start-row'. If 'forward' is true, we search going forward; otherwise backwards. If a matching node is found, its path is returned; otherwise nil is returned." [^JTree tree ^String key start-row forward include-current] (let [max-rows (-> tree .getRowCount) ukey (-> key .toUpperCase) increment (if forward 1 -1) start (if include-current start-row (mod (+ start-row increment max-rows) max-rows))] ; Keep looking through all rows until we either find a match, or we're back at the start (loop [row start] (let [path (-> tree (.getPathForRow row)) node (nprops/to-string (-> path .getLastPathComponent)) next-row (mod (+ row increment max-rows) max-rows)] (if (-> node .toUpperCase (.contains ukey)) path (if (not= next-row start) (recur next-row) nil)))))) (defn- search-tree-and-select "Search the inspector tree and select the node that was found, if any" [^JTree tree text forward include-current] (let [start-row (if (-> tree .isSelectionEmpty) 0 (-> tree .getLeadSelectionRow)) next-match (search-tree tree text start-row forward include-current)] (if (not= next-match nil) (doto tree (.setSelectionPath next-match) (.scrollPathToVisible next-match)) (-> (Toolkit/getDefaultToolkit) .beep)))) (defn- tool-panel "Create the toolbar of the Inspector Jay window" ^JToolBar [^Object object ^JTree jtree ^JSplitPane split-pane tree-options] (let [iconSize [24 :by 24] sort-button (seesaw/toggle :icon (seesaw/icon (io/resource "icons/alphab_sort_co.gif")) :size iconSize :selected? (tree-options :sorted)) filter-button (seesaw/button :icon (seesaw/icon (io/resource "icons/filter_history.gif")) :size iconSize) filter-methods (seesaw/checkbox :text "Methods" :selected? (tree-options :methods)) filter-fields (seesaw/checkbox :text "Fields" :selected? (tree-options :fields)) filter-public (seesaw/checkbox :text "Public" :selected? (tree-options :public)) filter-protected (seesaw/checkbox :text "Protected" :selected? (tree-options :protected)) filter-private (seesaw/checkbox :text "Private" :selected? (tree-options :private)) filter-static (seesaw/checkbox :text "Static" :selected? (tree-options :static)) filter-inherited (seesaw/checkbox :text "Inherited" :selected? (tree-options :inherited)) ; Function to refresh the inspector tree given the current options in the filter menu update-filters (fn [e] (-> jtree (.setModel (model/tree-model object {:sorted (-> sort-button .isSelected) :methods (-> filter-methods .isSelected) :fields (-> filter-fields .isSelected) :public (-> filter-public .isSelected) :protected (-> filter-protected .isSelected) :private (-> filter-private .isSelected) :static (-> filter-static .isSelected) :inherited (-> filter-inherited .isSelected)}))) (-> jtree (.setSelectionPath (-> jtree (.getPathForRow 0))))) filter-panel (seesaw/vertical-panel :items [filter-methods filter-fields (seesaw/separator) filter-public filter-protected filter-private (seesaw/separator) filter-static filter-inherited]) pane-button (seesaw/toggle :icon (seesaw/icon (io/resource "icons/details_view.gif")) :size iconSize :selected? true) inspect-button (seesaw/button :icon (seesaw/icon (io/resource "icons/insp_sbook.gif")) :size iconSize) doc-button (seesaw/button :icon (seesaw/icon (io/resource "icons/javadoc.gif")) :size iconSize) invoke-button (seesaw/button :icon (seesaw/icon (io/resource "icons/runlast_co.gif")) :size iconSize) refresh-button (seesaw/button :icon (seesaw/icon (io/resource "icons/nav_refresh.gif")) :size iconSize) filter-tip (delay (new BalloonTip ; Only create the filter menu once needed filter-button filter-panel (eval (gui-options :btip-style)) (eval (gui-options :btip-positioner)) nil)) resume-button (if (:pause tree-options) (seesaw/button :icon (seesaw/icon (io/resource "icons/resume_co.gif")) :size iconSize)) search-txt (seesaw/text :columns 20 :text "Search...") toolbar-items (remove nil? [sort-button filter-button pane-button inspect-button doc-button invoke-button refresh-button resume-button (Box/createHorizontalGlue) search-txt (Box/createHorizontalStrut 2)]) toolbar (seesaw/toolbar :items toolbar-items)] (doto toolbar (.setBorder (border/empty-border :thickness 1)) (.setFloatable false)) (-> search-txt (.setMaximumSize (-> search-txt .getPreferredSize))) ; Ditch the redundant dotted rectangle when a button is focused (-> sort-button (.setFocusPainted false)) (-> filter-button (.setFocusPainted false)) (-> pane-button (.setFocusPainted false)) (-> inspect-button (.setFocusPainted false)) (-> doc-button (.setFocusPainted false)) (-> invoke-button (.setFocusPainted false)) (-> refresh-button (.setFocusPainted false)) ; Set tooltips (-> sort-button (.setToolTipText "Sort alphabetically")) (-> filter-button (.setToolTipText "Filtering options...")) (-> pane-button (.setToolTipText "Toggle horizontal/vertical layout")) (-> inspect-button (.setToolTipText "Open selected node in new inspector")) (-> doc-button (.setToolTipText "Search Javadoc (F1)")) (-> invoke-button (.setToolTipText "(Re)invoke selected method (F4)")) (-> refresh-button (.setToolTipText "Refresh tree")) (-> search-txt (.setToolTipText "Search visible tree nodes (F3 / Shift-F3)")) ; Resume button (if (:pause tree-options) (do (-> resume-button (.setFocusPainted false)) (-> resume-button (.setToolTipText "Resume execution")) (seesaw/listen resume-button :action (fn [e] (resume-execution (.getParent toolbar)) (-> resume-button (.setEnabled false)) (-> resume-button (.setToolTipText "Resume execution (already resumed)")))))) ; Sort button (seesaw/listen sort-button :action update-filters) ; Open/close filter options menu (seesaw/listen filter-button :action (fn [e] (if (not (realized? filter-tip)) ; If opened for the first time, add a listener that hides the menu on mouse exit (seesaw/listen @filter-tip :mouse-exited (fn [e] (if (not (-> @filter-tip (.contains (-> e .getPoint)))) (-> @filter-tip (.setVisible false))))) (if (-> @filter-tip .isVisible) (-> @filter-tip (.setVisible false)) (-> @filter-tip (.setVisible true)))))) ; Filter checkboxes (seesaw/listen filter-methods :action update-filters) (seesaw/listen filter-fields :action update-filters) (seesaw/listen filter-public :action update-filters) (seesaw/listen filter-protected :action update-filters) (seesaw/listen filter-private :action update-filters) (seesaw/listen filter-static :action update-filters) (seesaw/listen filter-inherited :action update-filters) ; Toggle horizontal/vertical layout (seesaw/listen pane-button :action (fn [e] (if (-> pane-button .isSelected) (-> split-pane (.setOrientation 0)) (-> split-pane (.setOrientation 1))))) ; Open selected node in new inspector (seesaw/listen inspect-button :action (fn [e] (inspect-node jtree inspect-button))) ; Open javadoc of selected tree node (seesaw/listen doc-button :action (fn [e] (open-javadoc jtree))) ; (Re)invoke the selected method (seesaw/listen invoke-button :action (fn [e] (reinvoke jtree))) ; Refresh the tree (seesaw/listen refresh-button :action update-filters) ; Clear search field initially (seesaw/listen search-txt :focus-gained (fn [e] (-> search-txt (.setText "")) (-> search-txt (.removeFocusListener (last(-> search-txt (.getFocusListeners))))))) ; When typing in the search field, look for matches (seesaw/listen search-txt #{:remove-update :insert-update} (fn [e] (search-tree-and-select jtree (-> search-txt .getText) true true))) toolbar)) (defn- get-jtree "Retrieve the object tree from an inspector Jay panel" [^JPanel panel] (let [split-pane (nth (-> panel .getComponents) 2) scroll-pane (nth (-> split-pane .getComponents) 2) viewport (nth (-> scroll-pane .getComponents) 0) jtree (-> viewport .getView)] jtree)) (defn- get-search-field "Retrieve the search field from an inspector Jay panel" [^JPanel panel] (let [toolbar (nth (-> panel .getComponents) 0) idx (- (count (-> toolbar .getComponents)) 2) ; It's the second to last component in the toolbar.. search-field (nth (-> toolbar .getComponents) idx)] search-field)) (defn- get-selected-tab "Retrieve the currently selected tab of an inspector Jay window" ^JPanel [^JFrame window] (let [content (-> window .getContentPane)] (if (instance? JTabbedPane content) (-> content .getSelectedComponent) content))) (defn- close-tab "Close the currently selected tab in an Inspector Jay window" [window tab] (let [content (-> window .getContentPane) isTabbed (instance? JTabbedPane content)] (if (not isTabbed) ; Close the window if there only is one object opened (-> window (.dispatchEvent (new WindowEvent window WindowEvent/WINDOW_CLOSING))) ; Close the tab (do (resume-execution (-> content (.getComponentAt (-> content .getSelectedIndex)))) (-> content (.removeTabAt (-> content .getSelectedIndex))) ; Go back to an untabbed interface if there's only one tab left (if (= 1 (-> content .getTabCount)) (-> window (.setContentPane (-> content (.getSelectedComponent))))))))) (defn- bind-keys "Attach various key bindings to an Inspector Jay window" [frame] (let [f1-key (KeyStroke/getKeyStroke KeyEvent/VK_F1 0) f3-key (KeyStroke/getKeyStroke KeyEvent/VK_F3 0) f4-key (KeyStroke/getKeyStroke KeyEvent/VK_F4 0) shift-f3-key (KeyStroke/getKeyStroke KeyEvent/VK_F3 InputEvent/SHIFT_DOWN_MASK) ctrl-f-key (KeyStroke/getKeyStroke KeyEvent/VK_F (-> (Toolkit/getDefaultToolkit) .getMenuShortcutKeyMask)) ; Cmd on a Mac, Ctrl elsewhere ctrl-w-key (KeyStroke/getKeyStroke KeyEvent/VK_W (-> (Toolkit/getDefaultToolkit) .getMenuShortcutKeyMask))] ; Search javadoc for the currently selected node and open it in a browser window (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (open-javadoc (get-jtree (get-selected-tab frame))))) f1-key JComponent/WHEN_IN_FOCUSED_WINDOW)) ; (Re)invoke selected method (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (reinvoke (get-jtree (get-selected-tab frame))))) f4-key JComponent/WHEN_IN_FOCUSED_WINDOW)) ; Find next (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (let [tab (get-selected-tab frame)] (search-tree-and-select (get-jtree tab) (-> (get-search-field tab) .getText) true false)))) f3-key JComponent/WHEN_IN_FOCUSED_WINDOW)) ; Find previous (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (let [tab (get-selected-tab frame)] (search-tree-and-select (get-jtree tab) (-> (get-search-field tab) .getText) false false)))) shift-f3-key JComponent/WHEN_IN_FOCUSED_WINDOW)) ; Go to search field (or back to the tree) (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (let [tab (get-selected-tab frame) search-field (get-search-field tab)] (if (-> search-field .hasFocus) (-> (get-jtree tab) .requestFocus) (-> search-field .requestFocus))))) ctrl-f-key JComponent/WHEN_IN_FOCUSED_WINDOW)) ; Close the current tab (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (close-tab frame (get-selected-tab frame)))) ctrl-w-key JComponent/WHEN_IN_FOCUSED_WINDOW)))) (defn inspector-panel "Create and show an Inspector Jay window to inspect a given object. See default-options for more information on all available keyword arguments." ^JPanel [^Object object & {:as args}] (let [obj-info (seesaw/text :multi-line? true :editable? false :font (gui-options :font)) obj-tree (seesaw/tree :model (model/tree-model object args)) crumbs (seesaw/label :icon (seesaw/icon (io/resource "icons/toggle_breadcrumb.gif"))) obj-info-scroll (seesaw/scrollable obj-info) obj-tree-scroll (seesaw/scrollable obj-tree) split-pane (seesaw/top-bottom-split obj-info-scroll obj-tree-scroll :divider-location 1/5) toolbar (tool-panel object obj-tree split-pane args) main-panel (seesaw/border-panel :north toolbar :south crumbs :center split-pane)] (-> split-pane (.setDividerSize 9)) (-> obj-info-scroll (.setBorder (border/empty-border))) (-> obj-tree-scroll (.setBorder (border/empty-border))) (doto obj-tree (.setCellRenderer (tree-renderer)) (.addTreeSelectionListener (tree-selection-listener obj-info crumbs)) (.addTreeExpansionListener (tree-expansion-listener obj-info)) (.addTreeWillExpandListener (tree-will-expand-listener (:vars args))) (.setSelectionPath (-> obj-tree (.getPathForRow 0)))) main-panel)) (defn- close-window "Clean up when closing a window" [window] ; Resume any threads that might've been paused by inspectors in this window (let [content (-> window .getContentPane) isTabbed (instance? JTabbedPane content)] (if (not isTabbed) (resume-execution content) (doseq [x (range 0 (.getTabCount content))] (resume-execution (.getComponentAt content x))))) ; Clean up any resources associated with the window (swap! jay-windows (fn [x] (remove (fn [w] (= (:window w) window)) x))) (if (empty? @jay-windows) ; If all windows are closed, reset last-selected-node (swap! last-selected-node (fn [x] nil))) (node/clear-memoization-caches)) (defn- window-title "Compose a window's title" [window-name object] (let [prefix (if (nil? window-name) "Object inspector : " (str window-name " : "))] (str prefix (.toString object)))) (defn inspector-window "Show an Inspector Jay window to inspect a given object. See default-options for more information on all available keyword arguments." [object & {:as args}] (let [merged-args (merge default-options args) win-name (:window-name merged-args) panel (apply inspector-panel object (utils/map-to-keyword-args merged-args))] (seesaw/invoke-later (if (or ; Create a new window if: there are no windows yet, or :new-window is used, or a window with the given name hasn't been created yet. (= 0 (count @jay-windows)) (and (:new-window merged-args) (nil? win-name)) (and (not (nil? win-name)) (not-any? (fn [w] (= win-name (:name w))) @jay-windows))) ; Create a new window (let [window (seesaw/frame :title (window-title win-name object) :size [(gui-options :width) :by (gui-options :height)] :on-close :dispose)] (swap! jay-windows (fn [x] (conj x {:window window :name win-name}))) (seesaw/config! window :content panel) (bind-keys window) ; When the window is closed, remove the window from the list and clear caches (seesaw/listen window :window-closed (fn [e] (close-window window))) (-> window seesaw/show!) (-> (get-jtree panel) .requestFocus)) ; Otherwise, add a new tab (let [window (if (nil? win-name) (:window (last @jay-windows)) ; The most recently created window (some (fn [w] (when (= win-name (:name w)) (:window w))) @jay-windows)) content (-> window .getContentPane) isTabbed (instance? JTabbedPane content)] ; If the tabbed pane has not been created yet (if (not isTabbed) (let [tabs (seesaw/tabbed-panel) title (utils/truncate (-> (get-jtree content) .getModel .getRoot .getValue .toString) 20)] (-> tabs (.setBorder (border/empty-border :top 1 :left 2 :bottom 1 :right 0))) (-> tabs (.add title content)) (-> window (.setContentPane tabs)) ; When switching tabs, adjust the window title, and focus on the tree (seesaw/listen tabs :change (fn [e] (let [tree (get-jtree (get-selected-tab window)) title (window-title win-name (-> tree .getModel .getRoot .getValue))] (-> window (.setTitle title)) (-> tree .requestFocus)))))) (let [tabs (-> window .getContentPane)] ; Add the new tab (doto tabs (.add (utils/truncate (.toString object) 20) panel) (.setSelectedIndex (-> window .getContentPane (.indexOfComponent panel)))) ; Close the first tab, if going beyond the maximum number of tabs (if (> (-> tabs .getTabCount) (:max-tabs gui-options)) (close-tab window (-> tabs (.getComponentAt 0)))) (-> (get-jtree panel) .requestFocus))))) ; If desired, pause the current thread (while the GUI keeps running in a seperate thread) (if (:pause args) (locking panel (.wait panel)))))
true
; Copyright (c) 2013-2015 PI:NAME:<NAME>END_PI. ; ; All rights reserved. This program and the accompanying materials ; are made available under the terms of the 3-Clause BSD License ; which accompanies this distribution, and is available at ; http://www.opensource.org/licenses/BSD-3-Clause (ns inspector-jay.gui.gui "Defines Inspector Jay's graphical user interface" {:author "PI:NAME:<NAME>END_PI"} (:require [clojure.string :as s] [clojure.java [io :as io] [javadoc :as jdoc]] [seesaw [core :as seesaw] [color :as color] [border :as border] [font :as font]] [inspector-jay.gui [utils :as utils] [node-properties :as nprops]] [inspector-jay.model [tree-node :as node] [tree-model :as model]]) (:import [javax.swing Box JTextArea KeyStroke JFrame JPanel JTree JToolBar JComponent JToolBar$Separator UIManager JSplitPane JTabbedPane] [javax.swing.tree DefaultTreeCellRenderer] [javax.swing.event TreeSelectionListener TreeExpansionListener TreeWillExpandListener] [javax.swing.tree ExpandVetoException] [java.awt Rectangle Toolkit] [java.awt.event KeyEvent ActionListener ActionEvent InputEvent WindowEvent] [net.java.balloontip BalloonTip CustomBalloonTip] [net.java.balloontip.positioners LeftAbovePositioner LeftBelowPositioner] [net.java.balloontip.styles IsometricBalloonStyle] [net.java.balloontip.utils TimingUtils])) (seesaw/native!) ; Use the OS's native look and feel (def ^{:doc "When a new inspector is opened, these are the default options. You can customize these options via keyword arguments, e.g. (inspect an-object :sorted false :pause true)"} default-options {; Tree filtering options :sorted true ; Alphabetically sort members :methods true ; Show/hide methods :fields true :public true :protected false :private false :static true :inherited true ; Show/hide inherited members ; Miscellaneous options :window-name nil ; If given a name, the inspector is opened as a new tab in the window with that name. ; If that window does not exist yet, it will be created. This is useful if you want to ; divide your inspectors into groups. :new-window false ; If true, the inspector is opened in a new window. ; Otherwise, the inspector is opened as a new tab. ; This option is ignored if :window-name is used. :pause false ; If true, the current thread will be paused when opening an inspector. ; Execution will resume either when clicking the resume button, or closing the inspector tab/window. :vars nil ; You can use this to pass in any extra information to an inspector window. ; This is useful when invoking a method in the inspector, and you need to fill in some argument values. ; The value of :vars will then be available in the inspector under the variable named vars. }) (def ^{:doc "Inspectory Jay GUI options"} gui-options {:width 1024 :height 768 :font (font/font :name :sans-serif :style #{:plain}) :crumb-length 32 :max-tabs 64 :btip-style `(new IsometricBalloonStyle (UIManager/getColor "Panel.background") (color/color "#268bd2") 5) :btip-error-style `(new IsometricBalloonStyle (UIManager/getColor "Panel.background") (color/color "#d32e27") 3) :btip-positioner `(new LeftAbovePositioner 8 5)}) (declare inspector-window) ; Forward declaration ; Global variable! List of all open Inspector Jay windows (Each element is a map with keys :window and :name) (def jay-windows (atom [])) ; Global variable! Keeps track of the last selected tree node. (across all tabs/windows) (def last-selected-node (atom nil)) (defn- error "Show an error message near a given component" [^String message ^JComponent component] (TimingUtils/showTimedBalloon (new BalloonTip component (seesaw/label message) (eval (gui-options :btip-error-style)) (eval (gui-options :btip-positioner)) nil) 3000) (-> (Toolkit/getDefaultToolkit) .beep)) (defn- tree-renderer "Returns a cell renderer which defines what each tree node should look like" ^DefaultTreeCellRenderer [] (proxy [DefaultTreeCellRenderer] [] (getTreeCellRendererComponent [tree value selected expanded leaf row hasFocus] (proxy-super getTreeCellRendererComponent tree value selected expanded leaf row hasFocus) (-> this (.setText (nprops/to-string value))) (-> this (.setIcon (nprops/get-icon value))) this))) (defn last-selected-value "Retrieve the value of the tree node that was last selected. (An exception is thrown if we can't automatically obtain this value .. e.g. in case the value is not available yet and the last selected node is a method with parameters.)" [] (.getValue @last-selected-node)) (defn- tree-selection-listener "Whenever a tree node is selected, update the detailed information panel, the breadcrumbs, and the last-selected-value variable." ^TreeSelectionListener [info-panel crumbs-panel] (proxy [TreeSelectionListener] [] (valueChanged [event] (let [new-path (-> event .getNewLeadSelectionPath)] (if (not= new-path nil) (let [new-node (-> new-path .getLastPathComponent)] (swap! last-selected-node (fn [x] new-node)) (seesaw/config! info-panel :text (nprops/to-string-verbose new-node)) (seesaw/config! crumbs-panel :text (str "<html>" (s/join (interpose "<font color=\"#268bd2\"><b> &gt; </b></font>" (map (fn [x] (nprops/to-string-breadcrumb x (:crumb-length gui-options))) (-> new-path .getPath)))) "</html>")))))))) (defn- tree-expansion-listener "Updates the detailed information panel whenever a node is expanded." ^TreeExpansionListener [info-panel] (proxy [TreeExpansionListener] [] (treeExpanded [event] (seesaw/config! info-panel :text (nprops/to-string-verbose (-> event .getPath .getLastPathComponent)))) (treeCollapsed [event]))) (defn- tree-will-expand-listener "Displays a dialog if the user needs to enter some actual parameters to invoke a method." ^TreeWillExpandListener [shared-vars] (proxy [TreeWillExpandListener] [] (treeWillExpand [event] (let [jtree (-> event .getSource) node (-> event .getPath .getLastPathComponent)] (if (not (-> node .isValueAvailable)) (if (= 0 (count (-> node .getMethod .getParameterTypes))) ; No parameters needed; we can simply call .getValue to make the value available (-> node .getValue) ; Otherwise we'll need to ask the user to enter some parameter values (let [raw-types (-> node .getMethod .getParameterTypes) ; Swap Java's primitive types for their corresponding wrappers param-types (for [x raw-types] (let [type (-> x .toString)] (cond (= type "byte") java.lang.Byte (= type "short") java.lang.Short (= type "int") java.lang.Integer (= type "long") java.lang.Long (= type "float") java.lang.Float (= type "double") java.lang.Double (= type "boolean") java.lang.Boolean (= type "char") java.lang.Character :else x))) param-boxes (for [x param-types] (seesaw/text :tip (-> x .getSimpleName) :columns 32 )) params (seesaw/grid-panel :rows (inc (count param-types)) :columns 1) ok-button (seesaw/button :text "Call") cancel-button (seesaw/button :text "Cancel") buttons (seesaw/flow-panel) border-panel (seesaw/border-panel :center params :south buttons)] (-> buttons (.add ok-button)) (-> buttons (.add cancel-button)) (-> params (.add (seesaw/label "Enter parameter values to call this method:"))) (doseq [x param-boxes] (-> params (.add x))) (let [; Form to enter paramter values btip (new CustomBalloonTip jtree border-panel (-> jtree (.getPathBounds (-> event .getPath))) (eval (gui-options :btip-style)) (eval (gui-options :btip-positioner)) nil) ; Button to submit the form, and invoke the requested method ok-handler (fn [e] (try (let [args (for [i (range 0 (count param-boxes))] ; Try to evaluate the expression to obtain the current parameter's value (try (let [value (node/eval-arg (-> (nth param-boxes i) .getText) shared-vars) type (nth param-types i)] (cond ; Do primitive type conversion when necessary (= type java.lang.Short) (short value) ; Convert long to short (= type java.lang.Float) (float value) ; Convert double to float (= type java.lang.Integer) (int value) ; Convert long to int :else value)) (catch Exception e (do (error (-> e .getMessage) (nth param-boxes i)) (throw (Exception.))))))] (doseq [x args] x) ; If something went wrong with the arguments, this should trigger the exception before attempting an invocation.. (-> node (.invokeMethod args)) (-> btip .closeBalloon) (-> jtree (.expandPath (-> event .getPath))) (-> jtree (.setSelectionPath (-> event .getPath))) (-> jtree .requestFocus)) (catch Exception e ))) cancel-handler (fn [e] (-> btip .closeBalloon) (-> jtree .requestFocus)) key-handler (fn [e] (cond (= (-> e .getKeyCode) KeyEvent/VK_ENTER) (ok-handler e) (= (-> e .getKeyCode) KeyEvent/VK_ESCAPE) (cancel-handler e)))] (-> (first param-boxes) .requestFocus) (doseq [x param-boxes] (seesaw/listen x :key-pressed key-handler)) (seesaw/listen cancel-button :action (fn [e] (-> btip .closeBalloon) (-> jtree .requestFocus))) (seesaw/listen ok-button :action ok-handler)) (throw (new ExpandVetoException event))))))) ; Deny expanding the tree node; it will only be expanded once the value is available (treeWillCollapse [event]))) (defn- open-javadoc "Search Javadoc for the selected node (if present)" [jtree] (let [selection (-> jtree .getLastSelectedPathComponent)] (if (not= selection nil) (jdoc/javadoc (nprops/get-javadoc-class selection))))) (defn- inspect-node "Open the currently selected node in a new inspector" [jtree inspect-button] (let [selection (-> jtree .getLastSelectedPathComponent)] (if (-> selection .hasValue) (let [window (seesaw/to-root jtree) name (some (fn [w] (when (= (:window w) window) (:name w))) @jay-windows)] (inspector-window (-> selection .getValue) :window-name name)) (if (= (-> selection .getKind) :method) (error "Can't inspect the return value of this method. (Have you already called it?)" inspect-button) (error "Can't inspect this node; it doesn't have a value." inspect-button)))) ) (defn- reinvoke "(Re)invoke the selected method node" [jtree] (let [selection (-> jtree .getLastSelectedPathComponent) selection-path (-> jtree .getSelectionPath) selection-row (-> jtree (.getRowForPath selection-path))] (if (= (-> selection .getKind) :method) (do (-> jtree (.collapsePath selection-path)) (-> jtree .getModel (.valueForPathChanged selection-path (node/object-node (new Object)))) (-> jtree (.expandRow selection-row)) (-> jtree (.setSelectionRow selection-row)))))) (defn- resume-execution "Wake up any threads waiting for a lock object" [lock] (locking lock (.notify lock))) (defn- search-tree "Search a JTree for the first visible node whose value contains 'key', starting from the node at row 'start-row'. If 'forward' is true, we search going forward; otherwise backwards. If a matching node is found, its path is returned; otherwise nil is returned." [^JTree tree ^String key start-row forward include-current] (let [max-rows (-> tree .getRowCount) ukey (-> key .toUpperCase) increment (if forward 1 -1) start (if include-current start-row (mod (+ start-row increment max-rows) max-rows))] ; Keep looking through all rows until we either find a match, or we're back at the start (loop [row start] (let [path (-> tree (.getPathForRow row)) node (nprops/to-string (-> path .getLastPathComponent)) next-row (mod (+ row increment max-rows) max-rows)] (if (-> node .toUpperCase (.contains ukey)) path (if (not= next-row start) (recur next-row) nil)))))) (defn- search-tree-and-select "Search the inspector tree and select the node that was found, if any" [^JTree tree text forward include-current] (let [start-row (if (-> tree .isSelectionEmpty) 0 (-> tree .getLeadSelectionRow)) next-match (search-tree tree text start-row forward include-current)] (if (not= next-match nil) (doto tree (.setSelectionPath next-match) (.scrollPathToVisible next-match)) (-> (Toolkit/getDefaultToolkit) .beep)))) (defn- tool-panel "Create the toolbar of the Inspector Jay window" ^JToolBar [^Object object ^JTree jtree ^JSplitPane split-pane tree-options] (let [iconSize [24 :by 24] sort-button (seesaw/toggle :icon (seesaw/icon (io/resource "icons/alphab_sort_co.gif")) :size iconSize :selected? (tree-options :sorted)) filter-button (seesaw/button :icon (seesaw/icon (io/resource "icons/filter_history.gif")) :size iconSize) filter-methods (seesaw/checkbox :text "Methods" :selected? (tree-options :methods)) filter-fields (seesaw/checkbox :text "Fields" :selected? (tree-options :fields)) filter-public (seesaw/checkbox :text "Public" :selected? (tree-options :public)) filter-protected (seesaw/checkbox :text "Protected" :selected? (tree-options :protected)) filter-private (seesaw/checkbox :text "Private" :selected? (tree-options :private)) filter-static (seesaw/checkbox :text "Static" :selected? (tree-options :static)) filter-inherited (seesaw/checkbox :text "Inherited" :selected? (tree-options :inherited)) ; Function to refresh the inspector tree given the current options in the filter menu update-filters (fn [e] (-> jtree (.setModel (model/tree-model object {:sorted (-> sort-button .isSelected) :methods (-> filter-methods .isSelected) :fields (-> filter-fields .isSelected) :public (-> filter-public .isSelected) :protected (-> filter-protected .isSelected) :private (-> filter-private .isSelected) :static (-> filter-static .isSelected) :inherited (-> filter-inherited .isSelected)}))) (-> jtree (.setSelectionPath (-> jtree (.getPathForRow 0))))) filter-panel (seesaw/vertical-panel :items [filter-methods filter-fields (seesaw/separator) filter-public filter-protected filter-private (seesaw/separator) filter-static filter-inherited]) pane-button (seesaw/toggle :icon (seesaw/icon (io/resource "icons/details_view.gif")) :size iconSize :selected? true) inspect-button (seesaw/button :icon (seesaw/icon (io/resource "icons/insp_sbook.gif")) :size iconSize) doc-button (seesaw/button :icon (seesaw/icon (io/resource "icons/javadoc.gif")) :size iconSize) invoke-button (seesaw/button :icon (seesaw/icon (io/resource "icons/runlast_co.gif")) :size iconSize) refresh-button (seesaw/button :icon (seesaw/icon (io/resource "icons/nav_refresh.gif")) :size iconSize) filter-tip (delay (new BalloonTip ; Only create the filter menu once needed filter-button filter-panel (eval (gui-options :btip-style)) (eval (gui-options :btip-positioner)) nil)) resume-button (if (:pause tree-options) (seesaw/button :icon (seesaw/icon (io/resource "icons/resume_co.gif")) :size iconSize)) search-txt (seesaw/text :columns 20 :text "Search...") toolbar-items (remove nil? [sort-button filter-button pane-button inspect-button doc-button invoke-button refresh-button resume-button (Box/createHorizontalGlue) search-txt (Box/createHorizontalStrut 2)]) toolbar (seesaw/toolbar :items toolbar-items)] (doto toolbar (.setBorder (border/empty-border :thickness 1)) (.setFloatable false)) (-> search-txt (.setMaximumSize (-> search-txt .getPreferredSize))) ; Ditch the redundant dotted rectangle when a button is focused (-> sort-button (.setFocusPainted false)) (-> filter-button (.setFocusPainted false)) (-> pane-button (.setFocusPainted false)) (-> inspect-button (.setFocusPainted false)) (-> doc-button (.setFocusPainted false)) (-> invoke-button (.setFocusPainted false)) (-> refresh-button (.setFocusPainted false)) ; Set tooltips (-> sort-button (.setToolTipText "Sort alphabetically")) (-> filter-button (.setToolTipText "Filtering options...")) (-> pane-button (.setToolTipText "Toggle horizontal/vertical layout")) (-> inspect-button (.setToolTipText "Open selected node in new inspector")) (-> doc-button (.setToolTipText "Search Javadoc (F1)")) (-> invoke-button (.setToolTipText "(Re)invoke selected method (F4)")) (-> refresh-button (.setToolTipText "Refresh tree")) (-> search-txt (.setToolTipText "Search visible tree nodes (F3 / Shift-F3)")) ; Resume button (if (:pause tree-options) (do (-> resume-button (.setFocusPainted false)) (-> resume-button (.setToolTipText "Resume execution")) (seesaw/listen resume-button :action (fn [e] (resume-execution (.getParent toolbar)) (-> resume-button (.setEnabled false)) (-> resume-button (.setToolTipText "Resume execution (already resumed)")))))) ; Sort button (seesaw/listen sort-button :action update-filters) ; Open/close filter options menu (seesaw/listen filter-button :action (fn [e] (if (not (realized? filter-tip)) ; If opened for the first time, add a listener that hides the menu on mouse exit (seesaw/listen @filter-tip :mouse-exited (fn [e] (if (not (-> @filter-tip (.contains (-> e .getPoint)))) (-> @filter-tip (.setVisible false))))) (if (-> @filter-tip .isVisible) (-> @filter-tip (.setVisible false)) (-> @filter-tip (.setVisible true)))))) ; Filter checkboxes (seesaw/listen filter-methods :action update-filters) (seesaw/listen filter-fields :action update-filters) (seesaw/listen filter-public :action update-filters) (seesaw/listen filter-protected :action update-filters) (seesaw/listen filter-private :action update-filters) (seesaw/listen filter-static :action update-filters) (seesaw/listen filter-inherited :action update-filters) ; Toggle horizontal/vertical layout (seesaw/listen pane-button :action (fn [e] (if (-> pane-button .isSelected) (-> split-pane (.setOrientation 0)) (-> split-pane (.setOrientation 1))))) ; Open selected node in new inspector (seesaw/listen inspect-button :action (fn [e] (inspect-node jtree inspect-button))) ; Open javadoc of selected tree node (seesaw/listen doc-button :action (fn [e] (open-javadoc jtree))) ; (Re)invoke the selected method (seesaw/listen invoke-button :action (fn [e] (reinvoke jtree))) ; Refresh the tree (seesaw/listen refresh-button :action update-filters) ; Clear search field initially (seesaw/listen search-txt :focus-gained (fn [e] (-> search-txt (.setText "")) (-> search-txt (.removeFocusListener (last(-> search-txt (.getFocusListeners))))))) ; When typing in the search field, look for matches (seesaw/listen search-txt #{:remove-update :insert-update} (fn [e] (search-tree-and-select jtree (-> search-txt .getText) true true))) toolbar)) (defn- get-jtree "Retrieve the object tree from an inspector Jay panel" [^JPanel panel] (let [split-pane (nth (-> panel .getComponents) 2) scroll-pane (nth (-> split-pane .getComponents) 2) viewport (nth (-> scroll-pane .getComponents) 0) jtree (-> viewport .getView)] jtree)) (defn- get-search-field "Retrieve the search field from an inspector Jay panel" [^JPanel panel] (let [toolbar (nth (-> panel .getComponents) 0) idx (- (count (-> toolbar .getComponents)) 2) ; It's the second to last component in the toolbar.. search-field (nth (-> toolbar .getComponents) idx)] search-field)) (defn- get-selected-tab "Retrieve the currently selected tab of an inspector Jay window" ^JPanel [^JFrame window] (let [content (-> window .getContentPane)] (if (instance? JTabbedPane content) (-> content .getSelectedComponent) content))) (defn- close-tab "Close the currently selected tab in an Inspector Jay window" [window tab] (let [content (-> window .getContentPane) isTabbed (instance? JTabbedPane content)] (if (not isTabbed) ; Close the window if there only is one object opened (-> window (.dispatchEvent (new WindowEvent window WindowEvent/WINDOW_CLOSING))) ; Close the tab (do (resume-execution (-> content (.getComponentAt (-> content .getSelectedIndex)))) (-> content (.removeTabAt (-> content .getSelectedIndex))) ; Go back to an untabbed interface if there's only one tab left (if (= 1 (-> content .getTabCount)) (-> window (.setContentPane (-> content (.getSelectedComponent))))))))) (defn- bind-keys "Attach various key bindings to an Inspector Jay window" [frame] (let [f1-key (KeyStroke/getKeyStroke KeyEvent/VK_F1 0) f3-key (KeyStroke/getKeyStroke KeyEvent/VK_F3 0) f4-key (KeyStroke/getKeyStroke KeyEvent/VK_F4 0) shift-f3-key (KeyStroke/getKeyStroke KeyEvent/VK_F3 InputEvent/SHIFT_DOWN_MASK) ctrl-f-key (KeyStroke/getKeyStroke KeyEvent/VK_F (-> (Toolkit/getDefaultToolkit) .getMenuShortcutKeyMask)) ; Cmd on a Mac, Ctrl elsewhere ctrl-w-key (KeyStroke/getKeyStroke KeyEvent/VK_W (-> (Toolkit/getDefaultToolkit) .getMenuShortcutKeyMask))] ; Search javadoc for the currently selected node and open it in a browser window (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (open-javadoc (get-jtree (get-selected-tab frame))))) f1-key JComponent/WHEN_IN_FOCUSED_WINDOW)) ; (Re)invoke selected method (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (reinvoke (get-jtree (get-selected-tab frame))))) f4-key JComponent/WHEN_IN_FOCUSED_WINDOW)) ; Find next (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (let [tab (get-selected-tab frame)] (search-tree-and-select (get-jtree tab) (-> (get-search-field tab) .getText) true false)))) f3-key JComponent/WHEN_IN_FOCUSED_WINDOW)) ; Find previous (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (let [tab (get-selected-tab frame)] (search-tree-and-select (get-jtree tab) (-> (get-search-field tab) .getText) false false)))) shift-f3-key JComponent/WHEN_IN_FOCUSED_WINDOW)) ; Go to search field (or back to the tree) (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (let [tab (get-selected-tab frame) search-field (get-search-field tab)] (if (-> search-field .hasFocus) (-> (get-jtree tab) .requestFocus) (-> search-field .requestFocus))))) ctrl-f-key JComponent/WHEN_IN_FOCUSED_WINDOW)) ; Close the current tab (-> frame .getRootPane (.registerKeyboardAction (proxy [ActionListener] [] (actionPerformed [e] (close-tab frame (get-selected-tab frame)))) ctrl-w-key JComponent/WHEN_IN_FOCUSED_WINDOW)))) (defn inspector-panel "Create and show an Inspector Jay window to inspect a given object. See default-options for more information on all available keyword arguments." ^JPanel [^Object object & {:as args}] (let [obj-info (seesaw/text :multi-line? true :editable? false :font (gui-options :font)) obj-tree (seesaw/tree :model (model/tree-model object args)) crumbs (seesaw/label :icon (seesaw/icon (io/resource "icons/toggle_breadcrumb.gif"))) obj-info-scroll (seesaw/scrollable obj-info) obj-tree-scroll (seesaw/scrollable obj-tree) split-pane (seesaw/top-bottom-split obj-info-scroll obj-tree-scroll :divider-location 1/5) toolbar (tool-panel object obj-tree split-pane args) main-panel (seesaw/border-panel :north toolbar :south crumbs :center split-pane)] (-> split-pane (.setDividerSize 9)) (-> obj-info-scroll (.setBorder (border/empty-border))) (-> obj-tree-scroll (.setBorder (border/empty-border))) (doto obj-tree (.setCellRenderer (tree-renderer)) (.addTreeSelectionListener (tree-selection-listener obj-info crumbs)) (.addTreeExpansionListener (tree-expansion-listener obj-info)) (.addTreeWillExpandListener (tree-will-expand-listener (:vars args))) (.setSelectionPath (-> obj-tree (.getPathForRow 0)))) main-panel)) (defn- close-window "Clean up when closing a window" [window] ; Resume any threads that might've been paused by inspectors in this window (let [content (-> window .getContentPane) isTabbed (instance? JTabbedPane content)] (if (not isTabbed) (resume-execution content) (doseq [x (range 0 (.getTabCount content))] (resume-execution (.getComponentAt content x))))) ; Clean up any resources associated with the window (swap! jay-windows (fn [x] (remove (fn [w] (= (:window w) window)) x))) (if (empty? @jay-windows) ; If all windows are closed, reset last-selected-node (swap! last-selected-node (fn [x] nil))) (node/clear-memoization-caches)) (defn- window-title "Compose a window's title" [window-name object] (let [prefix (if (nil? window-name) "Object inspector : " (str window-name " : "))] (str prefix (.toString object)))) (defn inspector-window "Show an Inspector Jay window to inspect a given object. See default-options for more information on all available keyword arguments." [object & {:as args}] (let [merged-args (merge default-options args) win-name (:window-name merged-args) panel (apply inspector-panel object (utils/map-to-keyword-args merged-args))] (seesaw/invoke-later (if (or ; Create a new window if: there are no windows yet, or :new-window is used, or a window with the given name hasn't been created yet. (= 0 (count @jay-windows)) (and (:new-window merged-args) (nil? win-name)) (and (not (nil? win-name)) (not-any? (fn [w] (= win-name (:name w))) @jay-windows))) ; Create a new window (let [window (seesaw/frame :title (window-title win-name object) :size [(gui-options :width) :by (gui-options :height)] :on-close :dispose)] (swap! jay-windows (fn [x] (conj x {:window window :name win-name}))) (seesaw/config! window :content panel) (bind-keys window) ; When the window is closed, remove the window from the list and clear caches (seesaw/listen window :window-closed (fn [e] (close-window window))) (-> window seesaw/show!) (-> (get-jtree panel) .requestFocus)) ; Otherwise, add a new tab (let [window (if (nil? win-name) (:window (last @jay-windows)) ; The most recently created window (some (fn [w] (when (= win-name (:name w)) (:window w))) @jay-windows)) content (-> window .getContentPane) isTabbed (instance? JTabbedPane content)] ; If the tabbed pane has not been created yet (if (not isTabbed) (let [tabs (seesaw/tabbed-panel) title (utils/truncate (-> (get-jtree content) .getModel .getRoot .getValue .toString) 20)] (-> tabs (.setBorder (border/empty-border :top 1 :left 2 :bottom 1 :right 0))) (-> tabs (.add title content)) (-> window (.setContentPane tabs)) ; When switching tabs, adjust the window title, and focus on the tree (seesaw/listen tabs :change (fn [e] (let [tree (get-jtree (get-selected-tab window)) title (window-title win-name (-> tree .getModel .getRoot .getValue))] (-> window (.setTitle title)) (-> tree .requestFocus)))))) (let [tabs (-> window .getContentPane)] ; Add the new tab (doto tabs (.add (utils/truncate (.toString object) 20) panel) (.setSelectedIndex (-> window .getContentPane (.indexOfComponent panel)))) ; Close the first tab, if going beyond the maximum number of tabs (if (> (-> tabs .getTabCount) (:max-tabs gui-options)) (close-tab window (-> tabs (.getComponentAt 0)))) (-> (get-jtree panel) .requestFocus))))) ; If desired, pause the current thread (while the GUI keeps running in a seperate thread) (if (:pause args) (locking panel (.wait panel)))))
[ { "context": "ignature [handler]\n (fn [request]\n (let [key \"12345\"\n their-signature (:signature (:params r", "end": 4255, "score": 0.9993686676025391, "start": 4250, "tag": "KEY", "value": "12345" }, { "context": "meters work in dev-appserver\n; https://github.com/gcv/appengine-magic/issues/28\n(def shist-app-handler\n", "end": 5045, "score": 0.9994499683380127, "start": 5042, "tag": "USERNAME", "value": "gcv" } ]
data/train/clojure/fc91af0b4cd4ae370d15934294690c2b0f24b335core.clj
harshp8l/deep-learning-lang-detection
84
(ns shist.core (:import [java.security MessageDigest] [org.apache.commons.codec.binary Hex]) (:use compojure.core hiccup.core shist.signatures [ring.middleware.params :only [wrap-params]] [ring.middleware.keyword-params :only [wrap-keyword-params]]) (:require [appengine-magic.core :as ae] [appengine-magic.services.datastore :as ds] [appengine-magic.services.user :as user] [clj-json.core :as json] [clojure.contrib.string :as cstr] )) (ds/defentity Command [ ^:key id, command, hostname, timestamp, tty, owner ]) (ds/defentity ApiKey [ ^:key key, owner ]) (defn md5 "Generate a md5 checksum for the given string" [token] (let [hash-bytes (doto (java.security.MessageDigest/getInstance "MD5") (.reset) (.update (.getBytes token)))] (.toString (new java.math.BigInteger 1 (.digest hash-bytes)) ; Positive and the size of the number 16))) ; Use base16 i.e. hex (defn manage-keys-ui [] (html [:div (str "Logged in as " (user/current-user))] [:div [:a {:href "/add_key"} "Add Key" ]] (for [x (ds/query :kind ApiKey :filter (= :owner (user/current-user))) ] [:div (str "Key: [" (:key x) "] [" (hmac "foobar" (:key x)) "]" )]) )) (defn parselong [s] (. Long parseLong s)) (def maxlong (. Long MAX_VALUE)) (defn unauthorized [request params] {:status 403 :body (str "403 Unauthorized.\nString to sign: " (signable-string (:request-method request) (:uri request) params))}) (defroutes shist-app-routes (GET "/" req {:status 200 :headers {"Content-Type" "text/plain"} :body "Hello, world! (updated 4)"}) ;; Insert a new command into the archive (POST "/commands/" [:as request & params] (if (not (:signature-valid params)) (unauthorized request params) (let [cmd (Command. (md5 (str (:host params) (:ts params))) (:cmd params) (:host params) (parselong (:ts params)) (:tty params) (:owner params))] (ds/save! cmd) "OK"))) ;; List all commands (GET "/commands/" [:as request & params] (if (:signature-valid params) (let [mints (if (nil? (:mints params)) 0 (parselong (:mints params))) maxts (if (nil? (:maxts params)) maxlong (parselong (:maxts params))) cmdfilter (if (nil? (:filter params)) "" (:filter params)) cmds (ds/query :kind Command :filter [(>= :timestamp mints) (<= :timestamp maxts)]) filtercmds (filter #(cstr/substring? cmdfilter (:command %)) cmds) ] (json/generate-string filtercmds)) (unauthorized request params))) ;; List one command (GET "/command/:cmdid" [cmdid :as request & params] (if (:signature-valid params) (let [cmd (ds/retrieve Command cmdid)] (if (nil? cmd) {:status 404 :body (str cmdid " not found sir.")} {:status 200 :body (json/generate-string cmd)})) (unauthorized request params))) ;; Non-REST interactive (key-management) UI (GET "/manage_keys*" [] (if (user/user-logged-in?) (manage-keys-ui) {:status 302 :headers {"Location" (user/login-url :destination "/manage_keys")} :body ""})) (GET "/add_key" [] (let [key (ApiKey. (gen-key) (user/current-user))] (ds/save! key) {:status 302 :headers {"Location" "/manage_keys"} :body ""})) (GET "/logout" [] {:status 302 :headers {"Location" (user/logout-url)} :body ""}) (ANY "/test" [& params] (if (:signature-valid params) (str "verified? [" (:signature-valid params) "] -> AUTHORIZED") (str "UNAUTHORIZED."))) ;; Chrome always asks for a favicon. This suppresses error traces (GET "/favicon.ico" [] { :status 404 }) (ANY "*" [] { :status 404 :body "404 NOT FOUND"}) ) (defn wrap-check-signature [handler] (fn [request] (let [key "12345" their-signature (:signature (:params request)) method (:request-method request) signable-params (dissoc (:params request) :signature) our-signature (sign key method (:uri request) signable-params) signature-valid (= their-signature our-signature) new-params (assoc (:params request) :signature-valid signature-valid)] (handler (assoc request :params new-params))))) ; Right now you need to make sure the header: ; Content-Type:application/x-www-form-urlencoded ; I think we might be able to omit that with something like ; (defn wrap-correct-content-type [handler] ; (fn [request] ; (handler (assoc request :content-type "application/json")))) ; Makes GET parameters work in dev-appserver ; https://github.com/gcv/appengine-magic/issues/28 (def shist-app-handler (-> #'shist-app-routes wrap-check-signature wrap-keyword-params wrap-params)) (ae/def-appengine-app shist-app #'shist-app-handler)
37736
(ns shist.core (:import [java.security MessageDigest] [org.apache.commons.codec.binary Hex]) (:use compojure.core hiccup.core shist.signatures [ring.middleware.params :only [wrap-params]] [ring.middleware.keyword-params :only [wrap-keyword-params]]) (:require [appengine-magic.core :as ae] [appengine-magic.services.datastore :as ds] [appengine-magic.services.user :as user] [clj-json.core :as json] [clojure.contrib.string :as cstr] )) (ds/defentity Command [ ^:key id, command, hostname, timestamp, tty, owner ]) (ds/defentity ApiKey [ ^:key key, owner ]) (defn md5 "Generate a md5 checksum for the given string" [token] (let [hash-bytes (doto (java.security.MessageDigest/getInstance "MD5") (.reset) (.update (.getBytes token)))] (.toString (new java.math.BigInteger 1 (.digest hash-bytes)) ; Positive and the size of the number 16))) ; Use base16 i.e. hex (defn manage-keys-ui [] (html [:div (str "Logged in as " (user/current-user))] [:div [:a {:href "/add_key"} "Add Key" ]] (for [x (ds/query :kind ApiKey :filter (= :owner (user/current-user))) ] [:div (str "Key: [" (:key x) "] [" (hmac "foobar" (:key x)) "]" )]) )) (defn parselong [s] (. Long parseLong s)) (def maxlong (. Long MAX_VALUE)) (defn unauthorized [request params] {:status 403 :body (str "403 Unauthorized.\nString to sign: " (signable-string (:request-method request) (:uri request) params))}) (defroutes shist-app-routes (GET "/" req {:status 200 :headers {"Content-Type" "text/plain"} :body "Hello, world! (updated 4)"}) ;; Insert a new command into the archive (POST "/commands/" [:as request & params] (if (not (:signature-valid params)) (unauthorized request params) (let [cmd (Command. (md5 (str (:host params) (:ts params))) (:cmd params) (:host params) (parselong (:ts params)) (:tty params) (:owner params))] (ds/save! cmd) "OK"))) ;; List all commands (GET "/commands/" [:as request & params] (if (:signature-valid params) (let [mints (if (nil? (:mints params)) 0 (parselong (:mints params))) maxts (if (nil? (:maxts params)) maxlong (parselong (:maxts params))) cmdfilter (if (nil? (:filter params)) "" (:filter params)) cmds (ds/query :kind Command :filter [(>= :timestamp mints) (<= :timestamp maxts)]) filtercmds (filter #(cstr/substring? cmdfilter (:command %)) cmds) ] (json/generate-string filtercmds)) (unauthorized request params))) ;; List one command (GET "/command/:cmdid" [cmdid :as request & params] (if (:signature-valid params) (let [cmd (ds/retrieve Command cmdid)] (if (nil? cmd) {:status 404 :body (str cmdid " not found sir.")} {:status 200 :body (json/generate-string cmd)})) (unauthorized request params))) ;; Non-REST interactive (key-management) UI (GET "/manage_keys*" [] (if (user/user-logged-in?) (manage-keys-ui) {:status 302 :headers {"Location" (user/login-url :destination "/manage_keys")} :body ""})) (GET "/add_key" [] (let [key (ApiKey. (gen-key) (user/current-user))] (ds/save! key) {:status 302 :headers {"Location" "/manage_keys"} :body ""})) (GET "/logout" [] {:status 302 :headers {"Location" (user/logout-url)} :body ""}) (ANY "/test" [& params] (if (:signature-valid params) (str "verified? [" (:signature-valid params) "] -> AUTHORIZED") (str "UNAUTHORIZED."))) ;; Chrome always asks for a favicon. This suppresses error traces (GET "/favicon.ico" [] { :status 404 }) (ANY "*" [] { :status 404 :body "404 NOT FOUND"}) ) (defn wrap-check-signature [handler] (fn [request] (let [key "<KEY>" their-signature (:signature (:params request)) method (:request-method request) signable-params (dissoc (:params request) :signature) our-signature (sign key method (:uri request) signable-params) signature-valid (= their-signature our-signature) new-params (assoc (:params request) :signature-valid signature-valid)] (handler (assoc request :params new-params))))) ; Right now you need to make sure the header: ; Content-Type:application/x-www-form-urlencoded ; I think we might be able to omit that with something like ; (defn wrap-correct-content-type [handler] ; (fn [request] ; (handler (assoc request :content-type "application/json")))) ; Makes GET parameters work in dev-appserver ; https://github.com/gcv/appengine-magic/issues/28 (def shist-app-handler (-> #'shist-app-routes wrap-check-signature wrap-keyword-params wrap-params)) (ae/def-appengine-app shist-app #'shist-app-handler)
true
(ns shist.core (:import [java.security MessageDigest] [org.apache.commons.codec.binary Hex]) (:use compojure.core hiccup.core shist.signatures [ring.middleware.params :only [wrap-params]] [ring.middleware.keyword-params :only [wrap-keyword-params]]) (:require [appengine-magic.core :as ae] [appengine-magic.services.datastore :as ds] [appengine-magic.services.user :as user] [clj-json.core :as json] [clojure.contrib.string :as cstr] )) (ds/defentity Command [ ^:key id, command, hostname, timestamp, tty, owner ]) (ds/defentity ApiKey [ ^:key key, owner ]) (defn md5 "Generate a md5 checksum for the given string" [token] (let [hash-bytes (doto (java.security.MessageDigest/getInstance "MD5") (.reset) (.update (.getBytes token)))] (.toString (new java.math.BigInteger 1 (.digest hash-bytes)) ; Positive and the size of the number 16))) ; Use base16 i.e. hex (defn manage-keys-ui [] (html [:div (str "Logged in as " (user/current-user))] [:div [:a {:href "/add_key"} "Add Key" ]] (for [x (ds/query :kind ApiKey :filter (= :owner (user/current-user))) ] [:div (str "Key: [" (:key x) "] [" (hmac "foobar" (:key x)) "]" )]) )) (defn parselong [s] (. Long parseLong s)) (def maxlong (. Long MAX_VALUE)) (defn unauthorized [request params] {:status 403 :body (str "403 Unauthorized.\nString to sign: " (signable-string (:request-method request) (:uri request) params))}) (defroutes shist-app-routes (GET "/" req {:status 200 :headers {"Content-Type" "text/plain"} :body "Hello, world! (updated 4)"}) ;; Insert a new command into the archive (POST "/commands/" [:as request & params] (if (not (:signature-valid params)) (unauthorized request params) (let [cmd (Command. (md5 (str (:host params) (:ts params))) (:cmd params) (:host params) (parselong (:ts params)) (:tty params) (:owner params))] (ds/save! cmd) "OK"))) ;; List all commands (GET "/commands/" [:as request & params] (if (:signature-valid params) (let [mints (if (nil? (:mints params)) 0 (parselong (:mints params))) maxts (if (nil? (:maxts params)) maxlong (parselong (:maxts params))) cmdfilter (if (nil? (:filter params)) "" (:filter params)) cmds (ds/query :kind Command :filter [(>= :timestamp mints) (<= :timestamp maxts)]) filtercmds (filter #(cstr/substring? cmdfilter (:command %)) cmds) ] (json/generate-string filtercmds)) (unauthorized request params))) ;; List one command (GET "/command/:cmdid" [cmdid :as request & params] (if (:signature-valid params) (let [cmd (ds/retrieve Command cmdid)] (if (nil? cmd) {:status 404 :body (str cmdid " not found sir.")} {:status 200 :body (json/generate-string cmd)})) (unauthorized request params))) ;; Non-REST interactive (key-management) UI (GET "/manage_keys*" [] (if (user/user-logged-in?) (manage-keys-ui) {:status 302 :headers {"Location" (user/login-url :destination "/manage_keys")} :body ""})) (GET "/add_key" [] (let [key (ApiKey. (gen-key) (user/current-user))] (ds/save! key) {:status 302 :headers {"Location" "/manage_keys"} :body ""})) (GET "/logout" [] {:status 302 :headers {"Location" (user/logout-url)} :body ""}) (ANY "/test" [& params] (if (:signature-valid params) (str "verified? [" (:signature-valid params) "] -> AUTHORIZED") (str "UNAUTHORIZED."))) ;; Chrome always asks for a favicon. This suppresses error traces (GET "/favicon.ico" [] { :status 404 }) (ANY "*" [] { :status 404 :body "404 NOT FOUND"}) ) (defn wrap-check-signature [handler] (fn [request] (let [key "PI:KEY:<KEY>END_PI" their-signature (:signature (:params request)) method (:request-method request) signable-params (dissoc (:params request) :signature) our-signature (sign key method (:uri request) signable-params) signature-valid (= their-signature our-signature) new-params (assoc (:params request) :signature-valid signature-valid)] (handler (assoc request :params new-params))))) ; Right now you need to make sure the header: ; Content-Type:application/x-www-form-urlencoded ; I think we might be able to omit that with something like ; (defn wrap-correct-content-type [handler] ; (fn [request] ; (handler (assoc request :content-type "application/json")))) ; Makes GET parameters work in dev-appserver ; https://github.com/gcv/appengine-magic/issues/28 (def shist-app-handler (-> #'shist-app-routes wrap-check-signature wrap-keyword-params wrap-params)) (ae/def-appengine-app shist-app #'shist-app-handler)
[ { "context": "----------------------------------------------\n\n;; Rich Hickey has designed Clojure to address the problems of m", "end": 259, "score": 0.9998592734336853, "start": 248, "tag": "NAME", "value": "Rich Hickey" }, { "context": "ith + current-state {:cuddle-hunger-level 1})))\n\n@fred\n; => {:cuddle-hunger-level 1, :percent-deteriorat", "end": 5810, "score": 0.7832809090614319, "start": 5806, "tag": "USERNAME", "value": "fred" }, { "context": " :percent-deteriorated 1})))\n\n@fred\n; => {:cudde-hunger-level 2, :percent-deteriorate", "end": 6039, "score": 0.7804440855979919, "start": 6035, "tag": "USERNAME", "value": "fred" }, { "context": "contexts.\n\n(def ^:dynamic *notification-address* \"dobby@elf.org\")\n\n;; To temporarily change the the value of dyna", "end": 19666, "score": 0.9998382925987244, "start": 19653, "tag": "EMAIL", "value": "dobby@elf.org" }, { "context": "sing `binding`:\n(binding [*notification-address* \"test@elf.org\"]\n *notification-address*)\n; => \"test@elf.org\"\n\n", "end": 19791, "score": 0.9999041557312012, "start": 19779, "tag": "EMAIL", "value": "test@elf.org" }, { "context": "* \"test@elf.org\"]\n *notification-address*)\n; => \"test@elf.org\"\n\n;; You can also stack bindings (like with `let`", "end": 19838, "score": 0.9999057054519653, "start": 19826, "tag": "EMAIL", "value": "test@elf.org" }, { "context": "ke with `let`):\n(binding [*notification-address* \"test1@elf.org\"]\n (println *notification-address*)\n (binding [", "end": 19938, "score": 0.9998952746391296, "start": 19925, "tag": "EMAIL", "value": "test1@elf.org" }, { "context": "ion-address*)\n (binding [*notification-address* \"test2@elf.org\"]\n (println *notification-address*))\n (printl", "end": 20025, "score": 0.9999017715454102, "start": 20012, "tag": "EMAIL", "value": "test2@elf.org" }, { "context": "-address*))\n (println *notification-address*))\n;; test1@elf.org\n;; test2@elf.org\n;; test1@elf.org\n\n;; Here's a re", "end": 20118, "score": 0.9999142289161682, "start": 20105, "tag": "EMAIL", "value": "test1@elf.org" }, { "context": "intln *notification-address*))\n;; test1@elf.org\n;; test2@elf.org\n;; test1@elf.org\n\n;; Here's a real-world use case", "end": 20135, "score": 0.999913215637207, "start": 20122, "tag": "EMAIL", "value": "test2@elf.org" }, { "context": "on-address*))\n;; test1@elf.org\n;; test2@elf.org\n;; test1@elf.org\n\n;; Here's a real-world use case:\n(defn notify\n ", "end": 20152, "score": 0.999903678894043, "start": 20139, "tag": "EMAIL", "value": "test1@elf.org" }, { "context": "\"MESSAGE: \" message))\n(notify \"I fell.\")\n; => \"TO: dobby@elf.org\\nMESSAGE: I fell.\"\n\n(binding [*notification-addre", "end": 20325, "score": 0.9995408058166504, "start": 20312, "tag": "EMAIL", "value": "dobby@elf.org" }, { "context": "SAGE: I fell.\"\n\n(binding [*notification-address* \"test@elf.org\"]\n (notify \"test!\"))\n; => \"TO: test@elf.org\\nMES", "end": 20392, "score": 0.999864935874939, "start": 20380, "tag": "EMAIL", "value": "test@elf.org" }, { "context": "ess* \"test@elf.org\"]\n (notify \"test!\"))\n; => \"TO: test@elf.org\\nMESSAGE: test!\"\n\n;; Here, we could have just mod", "end": 20437, "score": 0.9968376159667969, "start": 20425, "tag": "EMAIL", "value": "test@elf.org" }, { "context": " learns\nsomething he can learn in no other way.\n-- Mark Twain\"))\n\n(slurp \"print-output\")\n; => A man who carries", "end": 21138, "score": 0.9998490214347839, "start": 21128, "tag": "NAME", "value": "Mark Twain" }, { "context": " something he can learn in no other way\n; -- Mark Twain\n\n;; Dynamic vars are also useful for configuratio", "end": 21276, "score": 0.9998763203620911, "start": 21266, "tag": "NAME", "value": "Mark Twain" } ]
Clojure-Metaphysics-Atoms-Refs-Vars/atoms_refs_vars.clj
bashhack/BraveClojure
0
;;;; --------------------------------------------------------------------------- ;;;; ------------------ Concurrent and Parallel Programming -------------------- ;;;; --------------------------------------------------------------------------- ;; Rich Hickey has designed Clojure to address the problems of mutable state, ;; in fact, Clojure embodies a clear conception of state that makes it ;; inherently safer for concurrency than most other programming languages. ;; Why? ;; To answer this, we must explore Clojure's underlying metaphysics, which we'll ;; do in comparison to that of object-oriented (OOP) languages. Learning about ;; the philosophy behind Clojure will help us handle the remaining concurrency ;; tools, the `atom` `ref` and `var` reference types (Clojure has one additional ;; reference type, `agents` which we don't cover). Each of these allow us to ;; safely perform state-modifying operations concurrently. ;; To illustrate the difference between Clojure and OO languages, we'll model ;; a zombie, a cuddle zombie. ;; Let's code it up in Ruby: class CuddleZombie # attr_accessor is just a shorthand way for creating getters and # setters for the listed instance variables attr_accessor :cuddle_hunger_level, :percent_deteriorated def initialize (cuddle_hunger_level = 1, percent_deteriorated = 0) self.cuddle_hunger_level = cuddle_hunger_level self.percent_deteriorated = percent_deteriorated end end fred = CuddleZombie.new(2, 3) fred.cuddle_hunger_level # => 2 fred.percent_deteriorated # => 3 fred.cuddle_hunger_level = 3 fred.cuddle_hunger_level # => 3 if fred.percent_deteriorated >= 50 Thread.new { database_logger.log(fred.cuddle_hunger_level) } end ;; The problem here is that another thread could change `fred` before the write ;; actually takes place. ;; Further, in order for us to change the `cuddle_hunger_level` and ;; `percent_deteriorated` simultaneously, you have to be extra careful! ;; It's possible that the value of `fred` is being operated upon/viewed ;; in an inconsistent state, because another thread might `read` the `fred` ;; object in between the two changes: fred.cuddle_hunger_level = fred.cuddle_hunger_level + 1 # At this time, another thread could read fred's attributes and # "perceive" fred in an inconsistent state unless you use a mutex fred.percent_deteriorated = fred.percent_deteriorated + 1 ;; Of course, this is another version of the mutual exclusion problem. In OOP ;; languages, we can work around this problem with a mutex, ensuring that ;; only one thread can access a resource at a time. ;; Objects are never truly stable, yet we build our programs with them as ;; the basis - this conforms to our intuitive sense of the world, in a sense. ;; Object in OOP also are the ones doing things, they act on each other, ;; serving as the engines of state change. ; ------------------------------------------------------------------------------ ; Clojure Metaphysics ;; In Clojure, we would say that we never meet the same cuddle zombie twice. ;; Our metaphysics as Clojurists and functional programmers informs us that ;; a cuddle zombie is not a discrete thing that exists in the world apart ;; from its mutations, it's really just a succession of values. ;; We use this term, "value," frequently in Clojure. Values are "atomic," in the ;; sense that they form a single irreducible unit in a larger system. They are ;; indivisble, unchanging, stable entities. ;; Numbers are values, for example, as it wouldn't make sense for a number like ;; `15` to mutate into some other number. When we add and subtract, we do not ;; change `15`, we just wind up with another number. ;; Clojure's data structures are also values because they're immutable - ;; remember, when you perform an action like `assoc` on a map, we are not ;; losing the original map, we derive a new map. ;; We simply apply a process to a value which produces a new value. ;; In OOP, we think of "identity" as something inherent to a changing ;; object - but in Clojure, identity is something we impose on a series ;; of unchanging values produced by a process over time. We use "names" ;; to designate identities, when we reference our object `fred` we ;; are referring to a series of individual states f1, f2, f3, and so on. ;; From this viewpoint, there's no such thing as mutable state. There ;; is only state as the value of an identity at a point in time. ;; That is, change only ever occurs when (1) a process generates a new value ;; and/or (2) we choose to associate the identity with the new value. ;; To handle this sort of change, Clojure uses "reference types." These help ;; us manage identities in Clojure and through using them, you can name ;; an identity and retrieve its state. The simplest of these is the "atom." ; ------------------------------------------------------------------------------ ; Atoms ;; The "atom" reference allows us to endow a succession of related values with ;; an identity, here's how to create one: (def fred (atom {:cuddle-hunger-level 0 :percent-deteriorated 0})) @fred ; => {:cuddle-hunger-level 0, :percent-deteriorated 0} ;; Unlike futures, delays, and promises, dereferencing an atom will never block. ;; To log the state of our zombie (free of the danger we saw in the Ruby example ;; where the object data could change while trying to log it), we would write: (let [zombie-state @fred] (if (>= (:percent-deteriorated zombie-state) 50) (future (println (:cuddle-hunger-level zombie-state))))) ;; To update an atom so that it refers to a new state, we use `swap!`: (swap! atom f) (swap! atom f x) (swap! atom f x y) (swap! atom f x y & args) (swap! fred (fn [current-state] (merge-with + current-state {:cuddle-hunger-level 1}))) @fred ; => {:cuddle-hunger-level 1, :percent-deteriorated 0} (swap! fred (fn [current-state] (merge-with + current-state {:cuddle-hunger-level 1 :percent-deteriorated 1}))) @fred ; => {:cudde-hunger-level 2, :percent-deteriorated 1} (defn increase-cuddle-hunger-level [zombie-state increase-by] (merge-with + zombie-state {:cuddle-hunger-level increase-by})) (increase-cuddle-hunger-level @fred 10) ; => {:cuddle-hunger-level 12, :percent-deteriorated 1} ;; NOTE: Not actually updating `fred`, because it is not ;; using `swap!` - we're just making a normal function ;; call which returns a result (swap! fred increase-cuddle-hunger-level 10) ; => {:cuddle-hunger-level 12, :percent-deteriorated 1} ;; NOTE: Here, we used `swap!`, so `fred` was updated ;; This is all fine and good, but we could express this all in ;; terms of a built-in Clojure function: `update-in` ... a ;; function which takes three params: a coll, a vector identifying ;; the value to update, and a function to update that value (update-in {:a {:b 3}} [:a :b] inc) ; => {:a {:b 4}} (update-in {:a {:b 3}} [:a :b] + 10) ; => {:a {:b 13}} (swap! fred update-in [:cuddle-hunger-level] + 10) ; => {:cuddle-hunger-level 22, :percent-deteriorated 1} ;; Using atoms, we can retain a past state, you can dereference ;; to retrieve State 1, update the atom -- in effect, creating ;; State 2, and still use State 1: (let [num (atom 1) s1 @num] (swap! num inc) (println "State 1:" s1) (println "Current status:" @num)) ; => State 1: 1 ; => Current state: 2 ;; `swap!` implements "compare-and-set" semantics, meaning that ;; if two separate threads call a `swap!` function, there is ;; no risk of one of the increments getting lost the way it did ;; in the Ruby example because behind the scenes `swap!`: ;; 1) reads the current state of the atom ;; 2) then applies the update function to that state ;; 3) next, it checks whether the value it read in step 1 is identical ;; to the atom's current value ;; 4) if it is, then `swap!` updates the atom to refer to the result ;; of step 2 ;; 5) if it isn't, then `swap!` retries, going through the ;; process again with step 1 ;; Further, the atom updates `swap!` triggers happen synchronously, ;; that is, they block the thread. ;; Sometimes, though, you may want to update an atom without ;; checking its current value - for this, we can use the `reset!` ;; function: (reset! fred {:cuddle-hunger-level 0 :percent-deteriorated 0}) ; ------------------------------------------------------------------------------ ; Watches and Validators ;; Watches allow us to check changes in our reference types, while ;; validators allow us to restrict what states are allowable - both ;; are simply functions. ; ------- ; Watches ; ------- (defn shuffle-speed [zombie] (* (:cuddle-hunger-level zombie) (- 100 (:percent-deteriorated zombie)))) ;; Now, we'll create a watch function (these take four args: a key ;; used for reporting, the atom being watched, the state of the atom ;; before its update, and the state of the atom after the update (defn shuffle-alert [key watched old-state new-state] (let [sph (shuffle-speed new-state)] (if (> sph 5000) (do (println "Run, you fool!") (println "The zombie's SPH is now " sph) (println "This message brought to you, courtesy of " key)) (do (println "All's well with " key) (println "Cuddle hunger: " (:cuddle-hunger-level new-state)) (println "Percent deteriorated: " (:percent-deteriorated new-state)) (println "SPH: " sph))))) ;; We attach this new function to our atom `fred` with `add-watch`. ;; The general form of `add-watch` is: (add-watch ref key watch-fn) (reset! fred {:cuddle-hunger-level 22 :percent-deteriorated 2}) (add-watch fred :fred-shuffle-alert shuffle-alert) (swap! fred update-in [:percent-deteriorated] + 1) ; => All's well with :fred-shuffle-alert ; => Cuddle hunger: 22 ; => Percent deteriorated: 3 ; => SPH: 2134 (swap! fred update-in [:cuddle-hunger-level] + 30) ; => Run, you fool! ; => The zombie's SPH is now 5044 ; => This message brought to you, courtesy of :fred-shuffle-alert ; ---------- ; Validators ; ---------- ;; Validators let us specify what states are allowable for a reference. ;; We could use a validator to ensure that `:percent-deteriorated` is ;; between 0 and 100 (defn percent-deteriorated-validator [{:keys [percent-deteriorated]}] (and (>= percent-deteriorated 0) (<= percent-deteriorated 100))) ;; If the validator fails by returning `false` or throwing an exception, ;; the reference won't change to point to the new value. ;; We can attach a validator during atom creation: (def bobby (atom {:cuddle-hunger-level 0 :percent-deteriorated 0} :validator percent-deteriorated-validator)) (swap! bobby update-in [:percent-deteriorated] + 200) ; => This throws "Invalid reference state" ;; We can get a more descriptive, custom error message: (defn percent-deteriorated-validator [{:keys [percent-deteriorated]}] (or (and (>= percent-deteriorated 0) (<= percent-deteriorated 100)) (throw (IllegalStateException. "That's not mathy!")))) (def bobby (atom {:cuddle-hunger-level 0 :percent-deteriorated 0} :validator percent-deteriorated-validator)) (swap! bobby update-in [:percent-deteriorated] + 200) ; This throws "IllegalStateException: That's not mathy!" ;; Atoms are great for managing the state of independent identities. ;; Sometimes, we need to express that an event should update the ;; state of more than one identity simultaneously - for this, ;; `refs` are the perfect tool! ; ------------------------------------------------------------------------------ ; Modeling Sock Transfers ;; Refs have three primary features: ;; 1) They are "atomic," meaning that all refs are updated or none of them are ;; 2) They are "consistent," meaning that the refs always appear to have valid ;; states. In this example, a sock will always belong to a dryer or a gnome, ;; but never both or neither. ;; 3) They are "isolated," meaning that transactions behave as if they executed ;; serially; if two threads are simultaneously running transactions that alter ;; the same ref, one transaction will retry. This is similar to the ;; compare-and-set semantics of atoms. ;; NOTE: These are the A, C, and I in the ACID properites of database ;; transactions. `Refs` give us the same concurrency safety as ;; database transactions, only with in-memory data. ;; To implement this behavior, Clojure uses "software transactional memory" ;; (STM). ;; Let's create some sock and gnome generators: (def sock-varieties #{"darned" "argyle" "wool" "horsehair" "mulleted" "passive-aggressive" "striped" "polka-dotted" "athletic" "business" "power" "invisible" "gollumed"}) (defn sock-count [sock-variety count] {:variety sock-variety :count count}) (defn generate-sock-gnome "Create an initial sock gnome state with no socks" [name] {:name name :socks #{}}) ;; Now, we create our actual refs: (def sock-gnome (ref (generate-sock-gnome "Barumpharumph"))) (def dryer (ref {:name "LG 1337" :socks (set (map #(sock-count % 2) sock-varieties))})) ;; Just like dereferencing `atoms` we can dereference `refs`: (:socks @dryer) ; => #{{:variety "passive-aggressive", :count 2} {:variety "power", :count 2} ; => {:variety "athletic", :count 2} {:variety "business", :count 2} ; => {:variety "argyle", :count 2} {:variety "horsehair", :count 2} ; => {:variety "gollumed", :count 2} {:variety "darned", :count 2} ; => {:variety "polka-dotted", :count 2} {:variety "wool", :count 2} ; => {:variety "mulleted", :count 2} {:variety "striped", :count 2} ; => {:variety "invisible", :count 2}} ;; We are ready to perform the transfer, but we need to modify the `sock-gnome` ;; ref to show that it has gained a sock and modify the `dryer` ref ;; to show that it's lost a sock. To modify `refs` we use `alter` and you ;; must use `alter` within a transaction. ;; NOTE: `dosync` inities a transaction, all transaction operations must ;; go in its body. (defn steal-sock [gnome dryer] (dosync (when-let [pair (some #(if (= (:count %) 2) %) (:socks @dryer))] (let [updated-count (sock-count (:variety pair) 1)] (alter gnome update-in [:socks] conj updated-count) (alter dryer update-in [:socks] disj pair) (alter dryer update-in [:socks] conj updated-count))))) ;; NOTE: `disj` - disjoin - returns a new set of the same (hashed/sorted) ;; type, that does not contain key(s) ;; (disj set) ;; (disj set key) ;; (disj set key & ks) ;; (disj #{1 2 3}) ; disjoin nothing ;; ; => #{1 2 3} ;; (disj #{1 2 3} 2) ; disjoin 2 ;; ; => #{1 3} ;; (disj #{1 2 3} 4) ; disjoin non-existent item ;; ; => #{1 2 3} ;; (disj #{1 2 3} 1 3) ; disjoin several items at once ;; ; => #{2} (steal-sock sock-gnome dryer) (:socks @sock-gnome) ; => #{{:variety "passive-aggressive", :count 1}} (defn similar-socks [target-sock sock-set] (filter #(= (:variety %) (:variety target-sock)) sock-set)) (similar-socks (first (:socks @sock-gnome)) (:socks @dryer)) ; => ({:variety "passive-aggressive", :count 1}) ;; A couple quick points about this...when you `alter` a ref, the change ;; isn't immediately visible outside of the current transaction. This is ;; what lets you `alter` on the `dryer` twice within a transaction without ;; worrying about whether or not `dryer` will be read in an inconsistent ;; state. If you `alter` a ref and then `deref` it in the same transaction, ;; the `deref` will return the new state. ;; Here's an example of this in-transaction state: (def counter (ref 0)) (future (dosync (alter counter inc) (println @counter) (Thread/sleep 500) (alter counter inc) (println @counter))) (Thread/sleep 250) (println @counter) ; => 1 -- future creates new thread for the transaction, counter incremented ; => 0 -- on the main thread, a wait of 250ms, and counter value printed as 0 ; -- because the value has never changed yet - the transaction creates ; -- its own scope and the previous increment action has never ; -- occured outside of it ; => 2 -- after the wait of 500ms on transaction's thread, counter incremented ; --------- ; `commute` ; --------- ;; `commute` allows you to update a ref's state within a transaction, just like ;; `alter` - however, its behavior at commit time is completely different. ;; `alter` ;; ------- ;; 1) Reach outside the transaction and read the ref's current state ;; 2) Compare the current state to the state the ref started with within ;; the transaction ;; 3) If the two differ, make the transaction retry ;; 4) Otherwise, commit the altered ref state ;; `commute` ;; --------- ;; 1) Reach outside the transaction and read the ref's current state ;; 2) Run the `commute` function again using the current state ;; 3) Commit the result ;; Because the transaction retry does not in `commute` this can help improve ;; performance, but one should only use `commute` when it is certain that ;; it's not possible for your refs to end up in an invalid state. ;; `commute` ;; (commute ref fun & args) ;; Must be called in transaction - ;; Sets the in-transaction value of ref to: ;; (apply fun in-transaction-value-of-ref args) ;; At commit point, sets the value of ref to be: ;; (apply fun most-recently-committed-value-of-ref args) ;; "safe" `commute`: (defn sleep-print-update [sleep-time thread-name update-fn] (fn [state] (Thread/sleep sleep-time) (println (str thread-name ": " state)) (update-in state))) (def counter (ref 0)) (future (dosync (commute counter (sleep-print-update 100 "Thread A" inc)))) (future (dosync (commute counter (sleep-print-update 150 "Thread B" inc)))) ;; Thread A: 0 | 100ms ;; Thread B: 0 | 150ms ;; Thread A: 0 | 200ms ;; Thread B: 1 | 300ms ;; "unsafe" `commute`: (def receiver-a (ref #{})) (def receiver-b (ref #{})) (def giver (ref #{1})) (do (future (dosync (let [gift (first @giver)] (Thread/sleep 10) (commute receiver-a conj gift) (commute giver disj gift)))) (future (dosync (let [gift (first @giver)] (Thread/sleep 50) (commute receiver-b conj gift) (commute giver disj gift))))) @receiver-a ; => #{1} @receiver-b ; => #{1} @giver ; => #{} ;; The `1` ws given to both `receiver-a` and `receiver-b`, and you've ended up ;; with two instances of `1`, which isn't valid for this program. ;; What's different about this program is that the functions that are applied, ;; essentially #(conj % gift) and #(disj % gift), are derived from the state of ;; `giver`. Once `giver` changes, the derived functions produce an invalid state ;; but `commute` doesn't care that the resulting state is invalid and commits the ;; result anyway. ; ------------------------------------------------------------------------------ ; Vars ;; We've already worked with `vars` but to review: `vars` are associations ;; between symbols and objects, new vars are created with `def` ;; Although `vars` are not used to manage state in the way `atoms` and `refs`, ;; we can use dynamic binding and the ability to alter their roots when ;; dealing with issues of concurrency ; --------------- ; Dynamic Binding ; --------------- ;; Usually we think of using `def` like defining a constant, but we can ;; create a dynamic `var` whose binding can be changed. ;; Dynamic bindings are useful for creating a global name that should refer ;; to different values in different contexts. (def ^:dynamic *notification-address* "dobby@elf.org") ;; To temporarily change the the value of dynamic vars by using `binding`: (binding [*notification-address* "test@elf.org"] *notification-address*) ; => "test@elf.org" ;; You can also stack bindings (like with `let`): (binding [*notification-address* "test1@elf.org"] (println *notification-address*) (binding [*notification-address* "test2@elf.org"] (println *notification-address*)) (println *notification-address*)) ;; test1@elf.org ;; test2@elf.org ;; test1@elf.org ;; Here's a real-world use case: (defn notify [message] (str "TO: " *notification-address* "\n" "MESSAGE: " message)) (notify "I fell.") ; => "TO: dobby@elf.org\nMESSAGE: I fell." (binding [*notification-address* "test@elf.org"] (notify "test!")) ; => "TO: test@elf.org\nMESSAGE: test!" ;; Here, we could have just modified `notify` to take an email address, ;; of course, so why would we want to use dynamic vars instead? ;; Dynamic vars are most often applicable to name a resource that one or ;; more functions target. In the previous example, we can imagine ;; the email address as a resource that we write to. This type of action ;; is so common that Clojure provides us with a number of built-in functions ;; like `*out*` - a function that represents the standard output for ;; print operations. (binding [*out* (clojure.java.io/writer "print-output")] (println "A man who carries a cat by the tail learns something he can learn in no other way. -- Mark Twain")) (slurp "print-output") ; => A man who carries a cat by the tail learns ; something he can learn in no other way ; -- Mark Twain ;; Dynamic vars are also useful for configuration, for instance, here is ;; the built-in `*print-lenth*` which lets us define how many items ;; in a collection will be printed: (binding [*print-length* 1] (println ["Print" "just" "one!"])) ; => [Print ...] ;; NOTE: We can also `set!` dynamic vars that have been bound. It allows ;; us to convey information "out" of a function without having to ;; return it as an argument (def ^:dynamic *troll-thought* nil) (defn troll-riddle [your-answer] (let [number "man meat"] (when (thread-bound? #'*troll-thought*) (set! *troll-thought* number)) (if (= number your-answer) "TROLL: You can cross the bridge!" "TROLL: Time to eat you, succulent human!"))) (binding [*troll-thought* nil] (println (troll-riddle 2)) (println "SUCCULENT HUMAN: Oooooh! The answer was" *troll-thought*) (println (troll-riddle "man meat")) (println "SUCCULENT HUMAN: Oooooh! The answer was" *troll-thought*)) ;; TROLL: Time to eat you, succulent human! ;; SUCCULENT HUMAN: Oooooh! The answer was man meat ;; TROLL: You can cross the bridge! ;; SUCCULENT HUMAN: Oooooh! The answer was man meat ;; Lastly, if you access a dynamically bound var from within a manually ;; created thread, the var will evaluate to the original value. (.write *out* "prints to repl") ; => prints to repl ;; The following won't print to REPL, because `*out*` is not bound to the REPL: (.start (Thread. #(.write *out* "prints to standard out"))) ;; We can work around this using the following two techniques: (let [out *out*] (.start (Thread. #(binding [*out* out] (.write *out* "prints to repl from thread"))))) ;; The `let` binding captures `*out*` so we can rebind it in our manually ;; generated child thread. Though bindings don't get passed to manually ;; created threads, they do get passed to futures. This is called ;; "binding conveyance." ; --------------------- ; Altering the Var Root ; --------------------- ;; When we create a new var, we assume its initial value that we supply ;; is its "root." (def power-source "hair") ;; Here, we understand that "hair" is the root value of `power-source` (alter-var-root #'power-source (fn [_] "7-eleven parking lot")) power-source ; => "7-eleven parking lot" ;; Also, if at all possible, don't do this! Use functional programming ;; techniques instead, as this goes against Clojure's core philosophy ;; of immutable data! ; ------------------------------------------------------------------------------ ; Stateless Concurrency and Parallelism with `pmap` ;; `pmap` is a parallel map function which makes it easy to achieve ;; stateless concurrency (defn always-1 [] 1) (take 5 (repeatedly always-1)) ; => (1 1 1 1 1) (take 5 (repeatedly (partial rand-int 10))) ; => (1 5 0 3 4) (def alphabet-length 26) (def letters "Vector of chars, A-Z" (mapv (comp str char (partial + 65)) (range alphabet-length))) (println letters) ; => [A B C D E F G H I J K L M N O P Q R S T U V W X Y Z] (defn random-string "Returns a random string of specified length" [length] (apply str (take length (repeatedly #(rand-nth letters))))) (println (random-string 18)) ; => SJMUEJPOMDJENPHSVQ (defn random-string-list [list-length string-length] (doall (take list-length (repeatedly (partial random-string string-length))))) (def orc-names (random-string-list 3000 7000)) ;; (time (dorun (map clojure.string/lower-case orc-names))) ; => "Elapsed time: 261.930982 msecs" ;; (time (dorun (pmap clojure.string/lower-case orc-names))) ; => "Elapsed time: 88.05338 msecs" ;; Wow! That's a crazy increase in performance - but `pmap` isn't always ;; the right answer. There is some overhead involved in the creation ;; and coordination of threads, so it is possible that this overhead could ;; surpass the time of each function application. ;; We can see this here in action: (def orc-name-abbrevs (random-string-list 20000 300)) (time (dorun (map clojure.string/lower-case orc-name-abbrevs))) ; => "Elapsed time: 79.033944 msecs" (time (dorun (pmap clojure.string/lower-case orc-name-abbrevs))) ; => "Elapsed time: 68.134221 msecs" ;; Here, the performance gap is much less pronounced - the issue here ;; is that the "grain size" or amount of work done by each parallelized ;; task is too small compared to the overhead of `pmap` ;; To increase the "grain size" as it were, we could apply ;; `clojure.string/lower-case` to multiple elements instead of only one, ;; using `partition-all` (def numbers [1 2 3 4 5 6 7 8 9 10]) (partition-all 3 numbers) ; => ((1 2 3) (4 5 6) (7 8 9) (10)) (pmap inc numbers) ; => grain size of one (pmap (fn [number-group] (doall (map inc number-group))) (partition-all 3 numbers)) ; => ((2 3 4) (5 6 7) (8 9 10) (11)) (apply concat (pmap (fn [number-group] (doall (map inc number-group))) (partition-all 3 numbers))) ; => (2 3 4 5 6 7 8 9 10 11) (time (dorun (apply concat (pmap (fn [name] (doall (map clojure.string/lower-case name))) (partition-all 1000 orc-name-abbrevs))))) ; => "Elapsed time: 28.466121 msecs" ;; Now, we're back to that performance gain we're expecting! ;; Let's generalize this technique into a function called `ppmap`, ;; for "partitioned pmap" (defn ppmap "Partitioned pmap, for grouping map ops together to make parallel overhead worthwhile" [grain-size f & colls] (apply concat (apply pmap (fn [& pgroups] (doall (apply map f pgroups))) (map (partial partition-all grain-size) colls)))) (time (dorun (ppmap 1000 clojure.string/lower-case orc-name-abbrevs))) ; => "Elapsed time: 28.03561msecs" ;; For more like this chapter, check out clojure.core.reducers library, ;; `http://clojure.org/reducers/` - which provides alternative ;; implementations of seq functions like `map` and `reduce` that ;; are usually faster than their `clojure.core` counterparts - however, ;; these functions are not lazy!
73003
;;;; --------------------------------------------------------------------------- ;;;; ------------------ Concurrent and Parallel Programming -------------------- ;;;; --------------------------------------------------------------------------- ;; <NAME> has designed Clojure to address the problems of mutable state, ;; in fact, Clojure embodies a clear conception of state that makes it ;; inherently safer for concurrency than most other programming languages. ;; Why? ;; To answer this, we must explore Clojure's underlying metaphysics, which we'll ;; do in comparison to that of object-oriented (OOP) languages. Learning about ;; the philosophy behind Clojure will help us handle the remaining concurrency ;; tools, the `atom` `ref` and `var` reference types (Clojure has one additional ;; reference type, `agents` which we don't cover). Each of these allow us to ;; safely perform state-modifying operations concurrently. ;; To illustrate the difference between Clojure and OO languages, we'll model ;; a zombie, a cuddle zombie. ;; Let's code it up in Ruby: class CuddleZombie # attr_accessor is just a shorthand way for creating getters and # setters for the listed instance variables attr_accessor :cuddle_hunger_level, :percent_deteriorated def initialize (cuddle_hunger_level = 1, percent_deteriorated = 0) self.cuddle_hunger_level = cuddle_hunger_level self.percent_deteriorated = percent_deteriorated end end fred = CuddleZombie.new(2, 3) fred.cuddle_hunger_level # => 2 fred.percent_deteriorated # => 3 fred.cuddle_hunger_level = 3 fred.cuddle_hunger_level # => 3 if fred.percent_deteriorated >= 50 Thread.new { database_logger.log(fred.cuddle_hunger_level) } end ;; The problem here is that another thread could change `fred` before the write ;; actually takes place. ;; Further, in order for us to change the `cuddle_hunger_level` and ;; `percent_deteriorated` simultaneously, you have to be extra careful! ;; It's possible that the value of `fred` is being operated upon/viewed ;; in an inconsistent state, because another thread might `read` the `fred` ;; object in between the two changes: fred.cuddle_hunger_level = fred.cuddle_hunger_level + 1 # At this time, another thread could read fred's attributes and # "perceive" fred in an inconsistent state unless you use a mutex fred.percent_deteriorated = fred.percent_deteriorated + 1 ;; Of course, this is another version of the mutual exclusion problem. In OOP ;; languages, we can work around this problem with a mutex, ensuring that ;; only one thread can access a resource at a time. ;; Objects are never truly stable, yet we build our programs with them as ;; the basis - this conforms to our intuitive sense of the world, in a sense. ;; Object in OOP also are the ones doing things, they act on each other, ;; serving as the engines of state change. ; ------------------------------------------------------------------------------ ; Clojure Metaphysics ;; In Clojure, we would say that we never meet the same cuddle zombie twice. ;; Our metaphysics as Clojurists and functional programmers informs us that ;; a cuddle zombie is not a discrete thing that exists in the world apart ;; from its mutations, it's really just a succession of values. ;; We use this term, "value," frequently in Clojure. Values are "atomic," in the ;; sense that they form a single irreducible unit in a larger system. They are ;; indivisble, unchanging, stable entities. ;; Numbers are values, for example, as it wouldn't make sense for a number like ;; `15` to mutate into some other number. When we add and subtract, we do not ;; change `15`, we just wind up with another number. ;; Clojure's data structures are also values because they're immutable - ;; remember, when you perform an action like `assoc` on a map, we are not ;; losing the original map, we derive a new map. ;; We simply apply a process to a value which produces a new value. ;; In OOP, we think of "identity" as something inherent to a changing ;; object - but in Clojure, identity is something we impose on a series ;; of unchanging values produced by a process over time. We use "names" ;; to designate identities, when we reference our object `fred` we ;; are referring to a series of individual states f1, f2, f3, and so on. ;; From this viewpoint, there's no such thing as mutable state. There ;; is only state as the value of an identity at a point in time. ;; That is, change only ever occurs when (1) a process generates a new value ;; and/or (2) we choose to associate the identity with the new value. ;; To handle this sort of change, Clojure uses "reference types." These help ;; us manage identities in Clojure and through using them, you can name ;; an identity and retrieve its state. The simplest of these is the "atom." ; ------------------------------------------------------------------------------ ; Atoms ;; The "atom" reference allows us to endow a succession of related values with ;; an identity, here's how to create one: (def fred (atom {:cuddle-hunger-level 0 :percent-deteriorated 0})) @fred ; => {:cuddle-hunger-level 0, :percent-deteriorated 0} ;; Unlike futures, delays, and promises, dereferencing an atom will never block. ;; To log the state of our zombie (free of the danger we saw in the Ruby example ;; where the object data could change while trying to log it), we would write: (let [zombie-state @fred] (if (>= (:percent-deteriorated zombie-state) 50) (future (println (:cuddle-hunger-level zombie-state))))) ;; To update an atom so that it refers to a new state, we use `swap!`: (swap! atom f) (swap! atom f x) (swap! atom f x y) (swap! atom f x y & args) (swap! fred (fn [current-state] (merge-with + current-state {:cuddle-hunger-level 1}))) @fred ; => {:cuddle-hunger-level 1, :percent-deteriorated 0} (swap! fred (fn [current-state] (merge-with + current-state {:cuddle-hunger-level 1 :percent-deteriorated 1}))) @fred ; => {:cudde-hunger-level 2, :percent-deteriorated 1} (defn increase-cuddle-hunger-level [zombie-state increase-by] (merge-with + zombie-state {:cuddle-hunger-level increase-by})) (increase-cuddle-hunger-level @fred 10) ; => {:cuddle-hunger-level 12, :percent-deteriorated 1} ;; NOTE: Not actually updating `fred`, because it is not ;; using `swap!` - we're just making a normal function ;; call which returns a result (swap! fred increase-cuddle-hunger-level 10) ; => {:cuddle-hunger-level 12, :percent-deteriorated 1} ;; NOTE: Here, we used `swap!`, so `fred` was updated ;; This is all fine and good, but we could express this all in ;; terms of a built-in Clojure function: `update-in` ... a ;; function which takes three params: a coll, a vector identifying ;; the value to update, and a function to update that value (update-in {:a {:b 3}} [:a :b] inc) ; => {:a {:b 4}} (update-in {:a {:b 3}} [:a :b] + 10) ; => {:a {:b 13}} (swap! fred update-in [:cuddle-hunger-level] + 10) ; => {:cuddle-hunger-level 22, :percent-deteriorated 1} ;; Using atoms, we can retain a past state, you can dereference ;; to retrieve State 1, update the atom -- in effect, creating ;; State 2, and still use State 1: (let [num (atom 1) s1 @num] (swap! num inc) (println "State 1:" s1) (println "Current status:" @num)) ; => State 1: 1 ; => Current state: 2 ;; `swap!` implements "compare-and-set" semantics, meaning that ;; if two separate threads call a `swap!` function, there is ;; no risk of one of the increments getting lost the way it did ;; in the Ruby example because behind the scenes `swap!`: ;; 1) reads the current state of the atom ;; 2) then applies the update function to that state ;; 3) next, it checks whether the value it read in step 1 is identical ;; to the atom's current value ;; 4) if it is, then `swap!` updates the atom to refer to the result ;; of step 2 ;; 5) if it isn't, then `swap!` retries, going through the ;; process again with step 1 ;; Further, the atom updates `swap!` triggers happen synchronously, ;; that is, they block the thread. ;; Sometimes, though, you may want to update an atom without ;; checking its current value - for this, we can use the `reset!` ;; function: (reset! fred {:cuddle-hunger-level 0 :percent-deteriorated 0}) ; ------------------------------------------------------------------------------ ; Watches and Validators ;; Watches allow us to check changes in our reference types, while ;; validators allow us to restrict what states are allowable - both ;; are simply functions. ; ------- ; Watches ; ------- (defn shuffle-speed [zombie] (* (:cuddle-hunger-level zombie) (- 100 (:percent-deteriorated zombie)))) ;; Now, we'll create a watch function (these take four args: a key ;; used for reporting, the atom being watched, the state of the atom ;; before its update, and the state of the atom after the update (defn shuffle-alert [key watched old-state new-state] (let [sph (shuffle-speed new-state)] (if (> sph 5000) (do (println "Run, you fool!") (println "The zombie's SPH is now " sph) (println "This message brought to you, courtesy of " key)) (do (println "All's well with " key) (println "Cuddle hunger: " (:cuddle-hunger-level new-state)) (println "Percent deteriorated: " (:percent-deteriorated new-state)) (println "SPH: " sph))))) ;; We attach this new function to our atom `fred` with `add-watch`. ;; The general form of `add-watch` is: (add-watch ref key watch-fn) (reset! fred {:cuddle-hunger-level 22 :percent-deteriorated 2}) (add-watch fred :fred-shuffle-alert shuffle-alert) (swap! fred update-in [:percent-deteriorated] + 1) ; => All's well with :fred-shuffle-alert ; => Cuddle hunger: 22 ; => Percent deteriorated: 3 ; => SPH: 2134 (swap! fred update-in [:cuddle-hunger-level] + 30) ; => Run, you fool! ; => The zombie's SPH is now 5044 ; => This message brought to you, courtesy of :fred-shuffle-alert ; ---------- ; Validators ; ---------- ;; Validators let us specify what states are allowable for a reference. ;; We could use a validator to ensure that `:percent-deteriorated` is ;; between 0 and 100 (defn percent-deteriorated-validator [{:keys [percent-deteriorated]}] (and (>= percent-deteriorated 0) (<= percent-deteriorated 100))) ;; If the validator fails by returning `false` or throwing an exception, ;; the reference won't change to point to the new value. ;; We can attach a validator during atom creation: (def bobby (atom {:cuddle-hunger-level 0 :percent-deteriorated 0} :validator percent-deteriorated-validator)) (swap! bobby update-in [:percent-deteriorated] + 200) ; => This throws "Invalid reference state" ;; We can get a more descriptive, custom error message: (defn percent-deteriorated-validator [{:keys [percent-deteriorated]}] (or (and (>= percent-deteriorated 0) (<= percent-deteriorated 100)) (throw (IllegalStateException. "That's not mathy!")))) (def bobby (atom {:cuddle-hunger-level 0 :percent-deteriorated 0} :validator percent-deteriorated-validator)) (swap! bobby update-in [:percent-deteriorated] + 200) ; This throws "IllegalStateException: That's not mathy!" ;; Atoms are great for managing the state of independent identities. ;; Sometimes, we need to express that an event should update the ;; state of more than one identity simultaneously - for this, ;; `refs` are the perfect tool! ; ------------------------------------------------------------------------------ ; Modeling Sock Transfers ;; Refs have three primary features: ;; 1) They are "atomic," meaning that all refs are updated or none of them are ;; 2) They are "consistent," meaning that the refs always appear to have valid ;; states. In this example, a sock will always belong to a dryer or a gnome, ;; but never both or neither. ;; 3) They are "isolated," meaning that transactions behave as if they executed ;; serially; if two threads are simultaneously running transactions that alter ;; the same ref, one transaction will retry. This is similar to the ;; compare-and-set semantics of atoms. ;; NOTE: These are the A, C, and I in the ACID properites of database ;; transactions. `Refs` give us the same concurrency safety as ;; database transactions, only with in-memory data. ;; To implement this behavior, Clojure uses "software transactional memory" ;; (STM). ;; Let's create some sock and gnome generators: (def sock-varieties #{"darned" "argyle" "wool" "horsehair" "mulleted" "passive-aggressive" "striped" "polka-dotted" "athletic" "business" "power" "invisible" "gollumed"}) (defn sock-count [sock-variety count] {:variety sock-variety :count count}) (defn generate-sock-gnome "Create an initial sock gnome state with no socks" [name] {:name name :socks #{}}) ;; Now, we create our actual refs: (def sock-gnome (ref (generate-sock-gnome "Barumpharumph"))) (def dryer (ref {:name "LG 1337" :socks (set (map #(sock-count % 2) sock-varieties))})) ;; Just like dereferencing `atoms` we can dereference `refs`: (:socks @dryer) ; => #{{:variety "passive-aggressive", :count 2} {:variety "power", :count 2} ; => {:variety "athletic", :count 2} {:variety "business", :count 2} ; => {:variety "argyle", :count 2} {:variety "horsehair", :count 2} ; => {:variety "gollumed", :count 2} {:variety "darned", :count 2} ; => {:variety "polka-dotted", :count 2} {:variety "wool", :count 2} ; => {:variety "mulleted", :count 2} {:variety "striped", :count 2} ; => {:variety "invisible", :count 2}} ;; We are ready to perform the transfer, but we need to modify the `sock-gnome` ;; ref to show that it has gained a sock and modify the `dryer` ref ;; to show that it's lost a sock. To modify `refs` we use `alter` and you ;; must use `alter` within a transaction. ;; NOTE: `dosync` inities a transaction, all transaction operations must ;; go in its body. (defn steal-sock [gnome dryer] (dosync (when-let [pair (some #(if (= (:count %) 2) %) (:socks @dryer))] (let [updated-count (sock-count (:variety pair) 1)] (alter gnome update-in [:socks] conj updated-count) (alter dryer update-in [:socks] disj pair) (alter dryer update-in [:socks] conj updated-count))))) ;; NOTE: `disj` - disjoin - returns a new set of the same (hashed/sorted) ;; type, that does not contain key(s) ;; (disj set) ;; (disj set key) ;; (disj set key & ks) ;; (disj #{1 2 3}) ; disjoin nothing ;; ; => #{1 2 3} ;; (disj #{1 2 3} 2) ; disjoin 2 ;; ; => #{1 3} ;; (disj #{1 2 3} 4) ; disjoin non-existent item ;; ; => #{1 2 3} ;; (disj #{1 2 3} 1 3) ; disjoin several items at once ;; ; => #{2} (steal-sock sock-gnome dryer) (:socks @sock-gnome) ; => #{{:variety "passive-aggressive", :count 1}} (defn similar-socks [target-sock sock-set] (filter #(= (:variety %) (:variety target-sock)) sock-set)) (similar-socks (first (:socks @sock-gnome)) (:socks @dryer)) ; => ({:variety "passive-aggressive", :count 1}) ;; A couple quick points about this...when you `alter` a ref, the change ;; isn't immediately visible outside of the current transaction. This is ;; what lets you `alter` on the `dryer` twice within a transaction without ;; worrying about whether or not `dryer` will be read in an inconsistent ;; state. If you `alter` a ref and then `deref` it in the same transaction, ;; the `deref` will return the new state. ;; Here's an example of this in-transaction state: (def counter (ref 0)) (future (dosync (alter counter inc) (println @counter) (Thread/sleep 500) (alter counter inc) (println @counter))) (Thread/sleep 250) (println @counter) ; => 1 -- future creates new thread for the transaction, counter incremented ; => 0 -- on the main thread, a wait of 250ms, and counter value printed as 0 ; -- because the value has never changed yet - the transaction creates ; -- its own scope and the previous increment action has never ; -- occured outside of it ; => 2 -- after the wait of 500ms on transaction's thread, counter incremented ; --------- ; `commute` ; --------- ;; `commute` allows you to update a ref's state within a transaction, just like ;; `alter` - however, its behavior at commit time is completely different. ;; `alter` ;; ------- ;; 1) Reach outside the transaction and read the ref's current state ;; 2) Compare the current state to the state the ref started with within ;; the transaction ;; 3) If the two differ, make the transaction retry ;; 4) Otherwise, commit the altered ref state ;; `commute` ;; --------- ;; 1) Reach outside the transaction and read the ref's current state ;; 2) Run the `commute` function again using the current state ;; 3) Commit the result ;; Because the transaction retry does not in `commute` this can help improve ;; performance, but one should only use `commute` when it is certain that ;; it's not possible for your refs to end up in an invalid state. ;; `commute` ;; (commute ref fun & args) ;; Must be called in transaction - ;; Sets the in-transaction value of ref to: ;; (apply fun in-transaction-value-of-ref args) ;; At commit point, sets the value of ref to be: ;; (apply fun most-recently-committed-value-of-ref args) ;; "safe" `commute`: (defn sleep-print-update [sleep-time thread-name update-fn] (fn [state] (Thread/sleep sleep-time) (println (str thread-name ": " state)) (update-in state))) (def counter (ref 0)) (future (dosync (commute counter (sleep-print-update 100 "Thread A" inc)))) (future (dosync (commute counter (sleep-print-update 150 "Thread B" inc)))) ;; Thread A: 0 | 100ms ;; Thread B: 0 | 150ms ;; Thread A: 0 | 200ms ;; Thread B: 1 | 300ms ;; "unsafe" `commute`: (def receiver-a (ref #{})) (def receiver-b (ref #{})) (def giver (ref #{1})) (do (future (dosync (let [gift (first @giver)] (Thread/sleep 10) (commute receiver-a conj gift) (commute giver disj gift)))) (future (dosync (let [gift (first @giver)] (Thread/sleep 50) (commute receiver-b conj gift) (commute giver disj gift))))) @receiver-a ; => #{1} @receiver-b ; => #{1} @giver ; => #{} ;; The `1` ws given to both `receiver-a` and `receiver-b`, and you've ended up ;; with two instances of `1`, which isn't valid for this program. ;; What's different about this program is that the functions that are applied, ;; essentially #(conj % gift) and #(disj % gift), are derived from the state of ;; `giver`. Once `giver` changes, the derived functions produce an invalid state ;; but `commute` doesn't care that the resulting state is invalid and commits the ;; result anyway. ; ------------------------------------------------------------------------------ ; Vars ;; We've already worked with `vars` but to review: `vars` are associations ;; between symbols and objects, new vars are created with `def` ;; Although `vars` are not used to manage state in the way `atoms` and `refs`, ;; we can use dynamic binding and the ability to alter their roots when ;; dealing with issues of concurrency ; --------------- ; Dynamic Binding ; --------------- ;; Usually we think of using `def` like defining a constant, but we can ;; create a dynamic `var` whose binding can be changed. ;; Dynamic bindings are useful for creating a global name that should refer ;; to different values in different contexts. (def ^:dynamic *notification-address* "<EMAIL>") ;; To temporarily change the the value of dynamic vars by using `binding`: (binding [*notification-address* "<EMAIL>"] *notification-address*) ; => "<EMAIL>" ;; You can also stack bindings (like with `let`): (binding [*notification-address* "<EMAIL>"] (println *notification-address*) (binding [*notification-address* "<EMAIL>"] (println *notification-address*)) (println *notification-address*)) ;; <EMAIL> ;; <EMAIL> ;; <EMAIL> ;; Here's a real-world use case: (defn notify [message] (str "TO: " *notification-address* "\n" "MESSAGE: " message)) (notify "I fell.") ; => "TO: <EMAIL>\nMESSAGE: I fell." (binding [*notification-address* "<EMAIL>"] (notify "test!")) ; => "TO: <EMAIL>\nMESSAGE: test!" ;; Here, we could have just modified `notify` to take an email address, ;; of course, so why would we want to use dynamic vars instead? ;; Dynamic vars are most often applicable to name a resource that one or ;; more functions target. In the previous example, we can imagine ;; the email address as a resource that we write to. This type of action ;; is so common that Clojure provides us with a number of built-in functions ;; like `*out*` - a function that represents the standard output for ;; print operations. (binding [*out* (clojure.java.io/writer "print-output")] (println "A man who carries a cat by the tail learns something he can learn in no other way. -- <NAME>")) (slurp "print-output") ; => A man who carries a cat by the tail learns ; something he can learn in no other way ; -- <NAME> ;; Dynamic vars are also useful for configuration, for instance, here is ;; the built-in `*print-lenth*` which lets us define how many items ;; in a collection will be printed: (binding [*print-length* 1] (println ["Print" "just" "one!"])) ; => [Print ...] ;; NOTE: We can also `set!` dynamic vars that have been bound. It allows ;; us to convey information "out" of a function without having to ;; return it as an argument (def ^:dynamic *troll-thought* nil) (defn troll-riddle [your-answer] (let [number "man meat"] (when (thread-bound? #'*troll-thought*) (set! *troll-thought* number)) (if (= number your-answer) "TROLL: You can cross the bridge!" "TROLL: Time to eat you, succulent human!"))) (binding [*troll-thought* nil] (println (troll-riddle 2)) (println "SUCCULENT HUMAN: Oooooh! The answer was" *troll-thought*) (println (troll-riddle "man meat")) (println "SUCCULENT HUMAN: Oooooh! The answer was" *troll-thought*)) ;; TROLL: Time to eat you, succulent human! ;; SUCCULENT HUMAN: Oooooh! The answer was man meat ;; TROLL: You can cross the bridge! ;; SUCCULENT HUMAN: Oooooh! The answer was man meat ;; Lastly, if you access a dynamically bound var from within a manually ;; created thread, the var will evaluate to the original value. (.write *out* "prints to repl") ; => prints to repl ;; The following won't print to REPL, because `*out*` is not bound to the REPL: (.start (Thread. #(.write *out* "prints to standard out"))) ;; We can work around this using the following two techniques: (let [out *out*] (.start (Thread. #(binding [*out* out] (.write *out* "prints to repl from thread"))))) ;; The `let` binding captures `*out*` so we can rebind it in our manually ;; generated child thread. Though bindings don't get passed to manually ;; created threads, they do get passed to futures. This is called ;; "binding conveyance." ; --------------------- ; Altering the Var Root ; --------------------- ;; When we create a new var, we assume its initial value that we supply ;; is its "root." (def power-source "hair") ;; Here, we understand that "hair" is the root value of `power-source` (alter-var-root #'power-source (fn [_] "7-eleven parking lot")) power-source ; => "7-eleven parking lot" ;; Also, if at all possible, don't do this! Use functional programming ;; techniques instead, as this goes against Clojure's core philosophy ;; of immutable data! ; ------------------------------------------------------------------------------ ; Stateless Concurrency and Parallelism with `pmap` ;; `pmap` is a parallel map function which makes it easy to achieve ;; stateless concurrency (defn always-1 [] 1) (take 5 (repeatedly always-1)) ; => (1 1 1 1 1) (take 5 (repeatedly (partial rand-int 10))) ; => (1 5 0 3 4) (def alphabet-length 26) (def letters "Vector of chars, A-Z" (mapv (comp str char (partial + 65)) (range alphabet-length))) (println letters) ; => [A B C D E F G H I J K L M N O P Q R S T U V W X Y Z] (defn random-string "Returns a random string of specified length" [length] (apply str (take length (repeatedly #(rand-nth letters))))) (println (random-string 18)) ; => SJMUEJPOMDJENPHSVQ (defn random-string-list [list-length string-length] (doall (take list-length (repeatedly (partial random-string string-length))))) (def orc-names (random-string-list 3000 7000)) ;; (time (dorun (map clojure.string/lower-case orc-names))) ; => "Elapsed time: 261.930982 msecs" ;; (time (dorun (pmap clojure.string/lower-case orc-names))) ; => "Elapsed time: 88.05338 msecs" ;; Wow! That's a crazy increase in performance - but `pmap` isn't always ;; the right answer. There is some overhead involved in the creation ;; and coordination of threads, so it is possible that this overhead could ;; surpass the time of each function application. ;; We can see this here in action: (def orc-name-abbrevs (random-string-list 20000 300)) (time (dorun (map clojure.string/lower-case orc-name-abbrevs))) ; => "Elapsed time: 79.033944 msecs" (time (dorun (pmap clojure.string/lower-case orc-name-abbrevs))) ; => "Elapsed time: 68.134221 msecs" ;; Here, the performance gap is much less pronounced - the issue here ;; is that the "grain size" or amount of work done by each parallelized ;; task is too small compared to the overhead of `pmap` ;; To increase the "grain size" as it were, we could apply ;; `clojure.string/lower-case` to multiple elements instead of only one, ;; using `partition-all` (def numbers [1 2 3 4 5 6 7 8 9 10]) (partition-all 3 numbers) ; => ((1 2 3) (4 5 6) (7 8 9) (10)) (pmap inc numbers) ; => grain size of one (pmap (fn [number-group] (doall (map inc number-group))) (partition-all 3 numbers)) ; => ((2 3 4) (5 6 7) (8 9 10) (11)) (apply concat (pmap (fn [number-group] (doall (map inc number-group))) (partition-all 3 numbers))) ; => (2 3 4 5 6 7 8 9 10 11) (time (dorun (apply concat (pmap (fn [name] (doall (map clojure.string/lower-case name))) (partition-all 1000 orc-name-abbrevs))))) ; => "Elapsed time: 28.466121 msecs" ;; Now, we're back to that performance gain we're expecting! ;; Let's generalize this technique into a function called `ppmap`, ;; for "partitioned pmap" (defn ppmap "Partitioned pmap, for grouping map ops together to make parallel overhead worthwhile" [grain-size f & colls] (apply concat (apply pmap (fn [& pgroups] (doall (apply map f pgroups))) (map (partial partition-all grain-size) colls)))) (time (dorun (ppmap 1000 clojure.string/lower-case orc-name-abbrevs))) ; => "Elapsed time: 28.03561msecs" ;; For more like this chapter, check out clojure.core.reducers library, ;; `http://clojure.org/reducers/` - which provides alternative ;; implementations of seq functions like `map` and `reduce` that ;; are usually faster than their `clojure.core` counterparts - however, ;; these functions are not lazy!
true
;;;; --------------------------------------------------------------------------- ;;;; ------------------ Concurrent and Parallel Programming -------------------- ;;;; --------------------------------------------------------------------------- ;; PI:NAME:<NAME>END_PI has designed Clojure to address the problems of mutable state, ;; in fact, Clojure embodies a clear conception of state that makes it ;; inherently safer for concurrency than most other programming languages. ;; Why? ;; To answer this, we must explore Clojure's underlying metaphysics, which we'll ;; do in comparison to that of object-oriented (OOP) languages. Learning about ;; the philosophy behind Clojure will help us handle the remaining concurrency ;; tools, the `atom` `ref` and `var` reference types (Clojure has one additional ;; reference type, `agents` which we don't cover). Each of these allow us to ;; safely perform state-modifying operations concurrently. ;; To illustrate the difference between Clojure and OO languages, we'll model ;; a zombie, a cuddle zombie. ;; Let's code it up in Ruby: class CuddleZombie # attr_accessor is just a shorthand way for creating getters and # setters for the listed instance variables attr_accessor :cuddle_hunger_level, :percent_deteriorated def initialize (cuddle_hunger_level = 1, percent_deteriorated = 0) self.cuddle_hunger_level = cuddle_hunger_level self.percent_deteriorated = percent_deteriorated end end fred = CuddleZombie.new(2, 3) fred.cuddle_hunger_level # => 2 fred.percent_deteriorated # => 3 fred.cuddle_hunger_level = 3 fred.cuddle_hunger_level # => 3 if fred.percent_deteriorated >= 50 Thread.new { database_logger.log(fred.cuddle_hunger_level) } end ;; The problem here is that another thread could change `fred` before the write ;; actually takes place. ;; Further, in order for us to change the `cuddle_hunger_level` and ;; `percent_deteriorated` simultaneously, you have to be extra careful! ;; It's possible that the value of `fred` is being operated upon/viewed ;; in an inconsistent state, because another thread might `read` the `fred` ;; object in between the two changes: fred.cuddle_hunger_level = fred.cuddle_hunger_level + 1 # At this time, another thread could read fred's attributes and # "perceive" fred in an inconsistent state unless you use a mutex fred.percent_deteriorated = fred.percent_deteriorated + 1 ;; Of course, this is another version of the mutual exclusion problem. In OOP ;; languages, we can work around this problem with a mutex, ensuring that ;; only one thread can access a resource at a time. ;; Objects are never truly stable, yet we build our programs with them as ;; the basis - this conforms to our intuitive sense of the world, in a sense. ;; Object in OOP also are the ones doing things, they act on each other, ;; serving as the engines of state change. ; ------------------------------------------------------------------------------ ; Clojure Metaphysics ;; In Clojure, we would say that we never meet the same cuddle zombie twice. ;; Our metaphysics as Clojurists and functional programmers informs us that ;; a cuddle zombie is not a discrete thing that exists in the world apart ;; from its mutations, it's really just a succession of values. ;; We use this term, "value," frequently in Clojure. Values are "atomic," in the ;; sense that they form a single irreducible unit in a larger system. They are ;; indivisble, unchanging, stable entities. ;; Numbers are values, for example, as it wouldn't make sense for a number like ;; `15` to mutate into some other number. When we add and subtract, we do not ;; change `15`, we just wind up with another number. ;; Clojure's data structures are also values because they're immutable - ;; remember, when you perform an action like `assoc` on a map, we are not ;; losing the original map, we derive a new map. ;; We simply apply a process to a value which produces a new value. ;; In OOP, we think of "identity" as something inherent to a changing ;; object - but in Clojure, identity is something we impose on a series ;; of unchanging values produced by a process over time. We use "names" ;; to designate identities, when we reference our object `fred` we ;; are referring to a series of individual states f1, f2, f3, and so on. ;; From this viewpoint, there's no such thing as mutable state. There ;; is only state as the value of an identity at a point in time. ;; That is, change only ever occurs when (1) a process generates a new value ;; and/or (2) we choose to associate the identity with the new value. ;; To handle this sort of change, Clojure uses "reference types." These help ;; us manage identities in Clojure and through using them, you can name ;; an identity and retrieve its state. The simplest of these is the "atom." ; ------------------------------------------------------------------------------ ; Atoms ;; The "atom" reference allows us to endow a succession of related values with ;; an identity, here's how to create one: (def fred (atom {:cuddle-hunger-level 0 :percent-deteriorated 0})) @fred ; => {:cuddle-hunger-level 0, :percent-deteriorated 0} ;; Unlike futures, delays, and promises, dereferencing an atom will never block. ;; To log the state of our zombie (free of the danger we saw in the Ruby example ;; where the object data could change while trying to log it), we would write: (let [zombie-state @fred] (if (>= (:percent-deteriorated zombie-state) 50) (future (println (:cuddle-hunger-level zombie-state))))) ;; To update an atom so that it refers to a new state, we use `swap!`: (swap! atom f) (swap! atom f x) (swap! atom f x y) (swap! atom f x y & args) (swap! fred (fn [current-state] (merge-with + current-state {:cuddle-hunger-level 1}))) @fred ; => {:cuddle-hunger-level 1, :percent-deteriorated 0} (swap! fred (fn [current-state] (merge-with + current-state {:cuddle-hunger-level 1 :percent-deteriorated 1}))) @fred ; => {:cudde-hunger-level 2, :percent-deteriorated 1} (defn increase-cuddle-hunger-level [zombie-state increase-by] (merge-with + zombie-state {:cuddle-hunger-level increase-by})) (increase-cuddle-hunger-level @fred 10) ; => {:cuddle-hunger-level 12, :percent-deteriorated 1} ;; NOTE: Not actually updating `fred`, because it is not ;; using `swap!` - we're just making a normal function ;; call which returns a result (swap! fred increase-cuddle-hunger-level 10) ; => {:cuddle-hunger-level 12, :percent-deteriorated 1} ;; NOTE: Here, we used `swap!`, so `fred` was updated ;; This is all fine and good, but we could express this all in ;; terms of a built-in Clojure function: `update-in` ... a ;; function which takes three params: a coll, a vector identifying ;; the value to update, and a function to update that value (update-in {:a {:b 3}} [:a :b] inc) ; => {:a {:b 4}} (update-in {:a {:b 3}} [:a :b] + 10) ; => {:a {:b 13}} (swap! fred update-in [:cuddle-hunger-level] + 10) ; => {:cuddle-hunger-level 22, :percent-deteriorated 1} ;; Using atoms, we can retain a past state, you can dereference ;; to retrieve State 1, update the atom -- in effect, creating ;; State 2, and still use State 1: (let [num (atom 1) s1 @num] (swap! num inc) (println "State 1:" s1) (println "Current status:" @num)) ; => State 1: 1 ; => Current state: 2 ;; `swap!` implements "compare-and-set" semantics, meaning that ;; if two separate threads call a `swap!` function, there is ;; no risk of one of the increments getting lost the way it did ;; in the Ruby example because behind the scenes `swap!`: ;; 1) reads the current state of the atom ;; 2) then applies the update function to that state ;; 3) next, it checks whether the value it read in step 1 is identical ;; to the atom's current value ;; 4) if it is, then `swap!` updates the atom to refer to the result ;; of step 2 ;; 5) if it isn't, then `swap!` retries, going through the ;; process again with step 1 ;; Further, the atom updates `swap!` triggers happen synchronously, ;; that is, they block the thread. ;; Sometimes, though, you may want to update an atom without ;; checking its current value - for this, we can use the `reset!` ;; function: (reset! fred {:cuddle-hunger-level 0 :percent-deteriorated 0}) ; ------------------------------------------------------------------------------ ; Watches and Validators ;; Watches allow us to check changes in our reference types, while ;; validators allow us to restrict what states are allowable - both ;; are simply functions. ; ------- ; Watches ; ------- (defn shuffle-speed [zombie] (* (:cuddle-hunger-level zombie) (- 100 (:percent-deteriorated zombie)))) ;; Now, we'll create a watch function (these take four args: a key ;; used for reporting, the atom being watched, the state of the atom ;; before its update, and the state of the atom after the update (defn shuffle-alert [key watched old-state new-state] (let [sph (shuffle-speed new-state)] (if (> sph 5000) (do (println "Run, you fool!") (println "The zombie's SPH is now " sph) (println "This message brought to you, courtesy of " key)) (do (println "All's well with " key) (println "Cuddle hunger: " (:cuddle-hunger-level new-state)) (println "Percent deteriorated: " (:percent-deteriorated new-state)) (println "SPH: " sph))))) ;; We attach this new function to our atom `fred` with `add-watch`. ;; The general form of `add-watch` is: (add-watch ref key watch-fn) (reset! fred {:cuddle-hunger-level 22 :percent-deteriorated 2}) (add-watch fred :fred-shuffle-alert shuffle-alert) (swap! fred update-in [:percent-deteriorated] + 1) ; => All's well with :fred-shuffle-alert ; => Cuddle hunger: 22 ; => Percent deteriorated: 3 ; => SPH: 2134 (swap! fred update-in [:cuddle-hunger-level] + 30) ; => Run, you fool! ; => The zombie's SPH is now 5044 ; => This message brought to you, courtesy of :fred-shuffle-alert ; ---------- ; Validators ; ---------- ;; Validators let us specify what states are allowable for a reference. ;; We could use a validator to ensure that `:percent-deteriorated` is ;; between 0 and 100 (defn percent-deteriorated-validator [{:keys [percent-deteriorated]}] (and (>= percent-deteriorated 0) (<= percent-deteriorated 100))) ;; If the validator fails by returning `false` or throwing an exception, ;; the reference won't change to point to the new value. ;; We can attach a validator during atom creation: (def bobby (atom {:cuddle-hunger-level 0 :percent-deteriorated 0} :validator percent-deteriorated-validator)) (swap! bobby update-in [:percent-deteriorated] + 200) ; => This throws "Invalid reference state" ;; We can get a more descriptive, custom error message: (defn percent-deteriorated-validator [{:keys [percent-deteriorated]}] (or (and (>= percent-deteriorated 0) (<= percent-deteriorated 100)) (throw (IllegalStateException. "That's not mathy!")))) (def bobby (atom {:cuddle-hunger-level 0 :percent-deteriorated 0} :validator percent-deteriorated-validator)) (swap! bobby update-in [:percent-deteriorated] + 200) ; This throws "IllegalStateException: That's not mathy!" ;; Atoms are great for managing the state of independent identities. ;; Sometimes, we need to express that an event should update the ;; state of more than one identity simultaneously - for this, ;; `refs` are the perfect tool! ; ------------------------------------------------------------------------------ ; Modeling Sock Transfers ;; Refs have three primary features: ;; 1) They are "atomic," meaning that all refs are updated or none of them are ;; 2) They are "consistent," meaning that the refs always appear to have valid ;; states. In this example, a sock will always belong to a dryer or a gnome, ;; but never both or neither. ;; 3) They are "isolated," meaning that transactions behave as if they executed ;; serially; if two threads are simultaneously running transactions that alter ;; the same ref, one transaction will retry. This is similar to the ;; compare-and-set semantics of atoms. ;; NOTE: These are the A, C, and I in the ACID properites of database ;; transactions. `Refs` give us the same concurrency safety as ;; database transactions, only with in-memory data. ;; To implement this behavior, Clojure uses "software transactional memory" ;; (STM). ;; Let's create some sock and gnome generators: (def sock-varieties #{"darned" "argyle" "wool" "horsehair" "mulleted" "passive-aggressive" "striped" "polka-dotted" "athletic" "business" "power" "invisible" "gollumed"}) (defn sock-count [sock-variety count] {:variety sock-variety :count count}) (defn generate-sock-gnome "Create an initial sock gnome state with no socks" [name] {:name name :socks #{}}) ;; Now, we create our actual refs: (def sock-gnome (ref (generate-sock-gnome "Barumpharumph"))) (def dryer (ref {:name "LG 1337" :socks (set (map #(sock-count % 2) sock-varieties))})) ;; Just like dereferencing `atoms` we can dereference `refs`: (:socks @dryer) ; => #{{:variety "passive-aggressive", :count 2} {:variety "power", :count 2} ; => {:variety "athletic", :count 2} {:variety "business", :count 2} ; => {:variety "argyle", :count 2} {:variety "horsehair", :count 2} ; => {:variety "gollumed", :count 2} {:variety "darned", :count 2} ; => {:variety "polka-dotted", :count 2} {:variety "wool", :count 2} ; => {:variety "mulleted", :count 2} {:variety "striped", :count 2} ; => {:variety "invisible", :count 2}} ;; We are ready to perform the transfer, but we need to modify the `sock-gnome` ;; ref to show that it has gained a sock and modify the `dryer` ref ;; to show that it's lost a sock. To modify `refs` we use `alter` and you ;; must use `alter` within a transaction. ;; NOTE: `dosync` inities a transaction, all transaction operations must ;; go in its body. (defn steal-sock [gnome dryer] (dosync (when-let [pair (some #(if (= (:count %) 2) %) (:socks @dryer))] (let [updated-count (sock-count (:variety pair) 1)] (alter gnome update-in [:socks] conj updated-count) (alter dryer update-in [:socks] disj pair) (alter dryer update-in [:socks] conj updated-count))))) ;; NOTE: `disj` - disjoin - returns a new set of the same (hashed/sorted) ;; type, that does not contain key(s) ;; (disj set) ;; (disj set key) ;; (disj set key & ks) ;; (disj #{1 2 3}) ; disjoin nothing ;; ; => #{1 2 3} ;; (disj #{1 2 3} 2) ; disjoin 2 ;; ; => #{1 3} ;; (disj #{1 2 3} 4) ; disjoin non-existent item ;; ; => #{1 2 3} ;; (disj #{1 2 3} 1 3) ; disjoin several items at once ;; ; => #{2} (steal-sock sock-gnome dryer) (:socks @sock-gnome) ; => #{{:variety "passive-aggressive", :count 1}} (defn similar-socks [target-sock sock-set] (filter #(= (:variety %) (:variety target-sock)) sock-set)) (similar-socks (first (:socks @sock-gnome)) (:socks @dryer)) ; => ({:variety "passive-aggressive", :count 1}) ;; A couple quick points about this...when you `alter` a ref, the change ;; isn't immediately visible outside of the current transaction. This is ;; what lets you `alter` on the `dryer` twice within a transaction without ;; worrying about whether or not `dryer` will be read in an inconsistent ;; state. If you `alter` a ref and then `deref` it in the same transaction, ;; the `deref` will return the new state. ;; Here's an example of this in-transaction state: (def counter (ref 0)) (future (dosync (alter counter inc) (println @counter) (Thread/sleep 500) (alter counter inc) (println @counter))) (Thread/sleep 250) (println @counter) ; => 1 -- future creates new thread for the transaction, counter incremented ; => 0 -- on the main thread, a wait of 250ms, and counter value printed as 0 ; -- because the value has never changed yet - the transaction creates ; -- its own scope and the previous increment action has never ; -- occured outside of it ; => 2 -- after the wait of 500ms on transaction's thread, counter incremented ; --------- ; `commute` ; --------- ;; `commute` allows you to update a ref's state within a transaction, just like ;; `alter` - however, its behavior at commit time is completely different. ;; `alter` ;; ------- ;; 1) Reach outside the transaction and read the ref's current state ;; 2) Compare the current state to the state the ref started with within ;; the transaction ;; 3) If the two differ, make the transaction retry ;; 4) Otherwise, commit the altered ref state ;; `commute` ;; --------- ;; 1) Reach outside the transaction and read the ref's current state ;; 2) Run the `commute` function again using the current state ;; 3) Commit the result ;; Because the transaction retry does not in `commute` this can help improve ;; performance, but one should only use `commute` when it is certain that ;; it's not possible for your refs to end up in an invalid state. ;; `commute` ;; (commute ref fun & args) ;; Must be called in transaction - ;; Sets the in-transaction value of ref to: ;; (apply fun in-transaction-value-of-ref args) ;; At commit point, sets the value of ref to be: ;; (apply fun most-recently-committed-value-of-ref args) ;; "safe" `commute`: (defn sleep-print-update [sleep-time thread-name update-fn] (fn [state] (Thread/sleep sleep-time) (println (str thread-name ": " state)) (update-in state))) (def counter (ref 0)) (future (dosync (commute counter (sleep-print-update 100 "Thread A" inc)))) (future (dosync (commute counter (sleep-print-update 150 "Thread B" inc)))) ;; Thread A: 0 | 100ms ;; Thread B: 0 | 150ms ;; Thread A: 0 | 200ms ;; Thread B: 1 | 300ms ;; "unsafe" `commute`: (def receiver-a (ref #{})) (def receiver-b (ref #{})) (def giver (ref #{1})) (do (future (dosync (let [gift (first @giver)] (Thread/sleep 10) (commute receiver-a conj gift) (commute giver disj gift)))) (future (dosync (let [gift (first @giver)] (Thread/sleep 50) (commute receiver-b conj gift) (commute giver disj gift))))) @receiver-a ; => #{1} @receiver-b ; => #{1} @giver ; => #{} ;; The `1` ws given to both `receiver-a` and `receiver-b`, and you've ended up ;; with two instances of `1`, which isn't valid for this program. ;; What's different about this program is that the functions that are applied, ;; essentially #(conj % gift) and #(disj % gift), are derived from the state of ;; `giver`. Once `giver` changes, the derived functions produce an invalid state ;; but `commute` doesn't care that the resulting state is invalid and commits the ;; result anyway. ; ------------------------------------------------------------------------------ ; Vars ;; We've already worked with `vars` but to review: `vars` are associations ;; between symbols and objects, new vars are created with `def` ;; Although `vars` are not used to manage state in the way `atoms` and `refs`, ;; we can use dynamic binding and the ability to alter their roots when ;; dealing with issues of concurrency ; --------------- ; Dynamic Binding ; --------------- ;; Usually we think of using `def` like defining a constant, but we can ;; create a dynamic `var` whose binding can be changed. ;; Dynamic bindings are useful for creating a global name that should refer ;; to different values in different contexts. (def ^:dynamic *notification-address* "PI:EMAIL:<EMAIL>END_PI") ;; To temporarily change the the value of dynamic vars by using `binding`: (binding [*notification-address* "PI:EMAIL:<EMAIL>END_PI"] *notification-address*) ; => "PI:EMAIL:<EMAIL>END_PI" ;; You can also stack bindings (like with `let`): (binding [*notification-address* "PI:EMAIL:<EMAIL>END_PI"] (println *notification-address*) (binding [*notification-address* "PI:EMAIL:<EMAIL>END_PI"] (println *notification-address*)) (println *notification-address*)) ;; PI:EMAIL:<EMAIL>END_PI ;; PI:EMAIL:<EMAIL>END_PI ;; PI:EMAIL:<EMAIL>END_PI ;; Here's a real-world use case: (defn notify [message] (str "TO: " *notification-address* "\n" "MESSAGE: " message)) (notify "I fell.") ; => "TO: PI:EMAIL:<EMAIL>END_PI\nMESSAGE: I fell." (binding [*notification-address* "PI:EMAIL:<EMAIL>END_PI"] (notify "test!")) ; => "TO: PI:EMAIL:<EMAIL>END_PI\nMESSAGE: test!" ;; Here, we could have just modified `notify` to take an email address, ;; of course, so why would we want to use dynamic vars instead? ;; Dynamic vars are most often applicable to name a resource that one or ;; more functions target. In the previous example, we can imagine ;; the email address as a resource that we write to. This type of action ;; is so common that Clojure provides us with a number of built-in functions ;; like `*out*` - a function that represents the standard output for ;; print operations. (binding [*out* (clojure.java.io/writer "print-output")] (println "A man who carries a cat by the tail learns something he can learn in no other way. -- PI:NAME:<NAME>END_PI")) (slurp "print-output") ; => A man who carries a cat by the tail learns ; something he can learn in no other way ; -- PI:NAME:<NAME>END_PI ;; Dynamic vars are also useful for configuration, for instance, here is ;; the built-in `*print-lenth*` which lets us define how many items ;; in a collection will be printed: (binding [*print-length* 1] (println ["Print" "just" "one!"])) ; => [Print ...] ;; NOTE: We can also `set!` dynamic vars that have been bound. It allows ;; us to convey information "out" of a function without having to ;; return it as an argument (def ^:dynamic *troll-thought* nil) (defn troll-riddle [your-answer] (let [number "man meat"] (when (thread-bound? #'*troll-thought*) (set! *troll-thought* number)) (if (= number your-answer) "TROLL: You can cross the bridge!" "TROLL: Time to eat you, succulent human!"))) (binding [*troll-thought* nil] (println (troll-riddle 2)) (println "SUCCULENT HUMAN: Oooooh! The answer was" *troll-thought*) (println (troll-riddle "man meat")) (println "SUCCULENT HUMAN: Oooooh! The answer was" *troll-thought*)) ;; TROLL: Time to eat you, succulent human! ;; SUCCULENT HUMAN: Oooooh! The answer was man meat ;; TROLL: You can cross the bridge! ;; SUCCULENT HUMAN: Oooooh! The answer was man meat ;; Lastly, if you access a dynamically bound var from within a manually ;; created thread, the var will evaluate to the original value. (.write *out* "prints to repl") ; => prints to repl ;; The following won't print to REPL, because `*out*` is not bound to the REPL: (.start (Thread. #(.write *out* "prints to standard out"))) ;; We can work around this using the following two techniques: (let [out *out*] (.start (Thread. #(binding [*out* out] (.write *out* "prints to repl from thread"))))) ;; The `let` binding captures `*out*` so we can rebind it in our manually ;; generated child thread. Though bindings don't get passed to manually ;; created threads, they do get passed to futures. This is called ;; "binding conveyance." ; --------------------- ; Altering the Var Root ; --------------------- ;; When we create a new var, we assume its initial value that we supply ;; is its "root." (def power-source "hair") ;; Here, we understand that "hair" is the root value of `power-source` (alter-var-root #'power-source (fn [_] "7-eleven parking lot")) power-source ; => "7-eleven parking lot" ;; Also, if at all possible, don't do this! Use functional programming ;; techniques instead, as this goes against Clojure's core philosophy ;; of immutable data! ; ------------------------------------------------------------------------------ ; Stateless Concurrency and Parallelism with `pmap` ;; `pmap` is a parallel map function which makes it easy to achieve ;; stateless concurrency (defn always-1 [] 1) (take 5 (repeatedly always-1)) ; => (1 1 1 1 1) (take 5 (repeatedly (partial rand-int 10))) ; => (1 5 0 3 4) (def alphabet-length 26) (def letters "Vector of chars, A-Z" (mapv (comp str char (partial + 65)) (range alphabet-length))) (println letters) ; => [A B C D E F G H I J K L M N O P Q R S T U V W X Y Z] (defn random-string "Returns a random string of specified length" [length] (apply str (take length (repeatedly #(rand-nth letters))))) (println (random-string 18)) ; => SJMUEJPOMDJENPHSVQ (defn random-string-list [list-length string-length] (doall (take list-length (repeatedly (partial random-string string-length))))) (def orc-names (random-string-list 3000 7000)) ;; (time (dorun (map clojure.string/lower-case orc-names))) ; => "Elapsed time: 261.930982 msecs" ;; (time (dorun (pmap clojure.string/lower-case orc-names))) ; => "Elapsed time: 88.05338 msecs" ;; Wow! That's a crazy increase in performance - but `pmap` isn't always ;; the right answer. There is some overhead involved in the creation ;; and coordination of threads, so it is possible that this overhead could ;; surpass the time of each function application. ;; We can see this here in action: (def orc-name-abbrevs (random-string-list 20000 300)) (time (dorun (map clojure.string/lower-case orc-name-abbrevs))) ; => "Elapsed time: 79.033944 msecs" (time (dorun (pmap clojure.string/lower-case orc-name-abbrevs))) ; => "Elapsed time: 68.134221 msecs" ;; Here, the performance gap is much less pronounced - the issue here ;; is that the "grain size" or amount of work done by each parallelized ;; task is too small compared to the overhead of `pmap` ;; To increase the "grain size" as it were, we could apply ;; `clojure.string/lower-case` to multiple elements instead of only one, ;; using `partition-all` (def numbers [1 2 3 4 5 6 7 8 9 10]) (partition-all 3 numbers) ; => ((1 2 3) (4 5 6) (7 8 9) (10)) (pmap inc numbers) ; => grain size of one (pmap (fn [number-group] (doall (map inc number-group))) (partition-all 3 numbers)) ; => ((2 3 4) (5 6 7) (8 9 10) (11)) (apply concat (pmap (fn [number-group] (doall (map inc number-group))) (partition-all 3 numbers))) ; => (2 3 4 5 6 7 8 9 10 11) (time (dorun (apply concat (pmap (fn [name] (doall (map clojure.string/lower-case name))) (partition-all 1000 orc-name-abbrevs))))) ; => "Elapsed time: 28.466121 msecs" ;; Now, we're back to that performance gain we're expecting! ;; Let's generalize this technique into a function called `ppmap`, ;; for "partitioned pmap" (defn ppmap "Partitioned pmap, for grouping map ops together to make parallel overhead worthwhile" [grain-size f & colls] (apply concat (apply pmap (fn [& pgroups] (doall (apply map f pgroups))) (map (partial partition-all grain-size) colls)))) (time (dorun (ppmap 1000 clojure.string/lower-case orc-name-abbrevs))) ; => "Elapsed time: 28.03561msecs" ;; For more like this chapter, check out clojure.core.reducers library, ;; `http://clojure.org/reducers/` - which provides alternative ;; implementations of seq functions like `map` and `reduce` that ;; are usually faster than their `clojure.core` counterparts - however, ;; these functions are not lazy!
[ { "context": "bject constructor\"\n \n (write/from-empty {:name \"chris\" :pet \"dog\"}\n (fn [] (java.uti", "end": 2116, "score": 0.9974005818367004, "start": 2111, "tag": "NAME", "value": "chris" }, { "context": " {}))\n ;;=> #test.Cat{:name \"spike\", :species \"cat\"}\n)\n\n^{:refer hara.object.framewo", "end": 2907, "score": 0.5525418519973755, "start": 2902, "tag": "NAME", "value": "spike" }, { "context": " \"creates the object from a map\"\n \n (-> {:name \"chris\" :age 30 :pets [{:name \"slurp\" :species \"dog\"}\n ", "end": 3049, "score": 0.9987980723381042, "start": 3044, "tag": "NAME", "value": "chris" }, { "context": "\n \n (-> {:name \"chris\" :age 30 :pets [{:name \"slurp\" :species \"dog\"}\n ", "end": 3079, "score": 0.8635854125022888, "start": 3076, "tag": "NAME", "value": "urp" }, { "context": " (read/to-data))\n => (contains-in\n {:name \"chris\",\n :age 30,\n :pets [{:name \"slurp\"}\n ", "end": 3260, "score": 0.998921275138855, "start": 3255, "tag": "NAME", "value": "chris" } ]
test/hara/object/framework/write_test.clj
zcaudate/hara
309
(ns hara.object.framework.write-test (:use hara.test) (:require [hara.object.framework.read :as read] [hara.object.framework.write :as write] [hara.protocol.object :as object] [hara.object.query :as reflect] [hara.object.framework.base-test]) (:import [test PersonBuilder Person Dog DogBuilder Cat Pet])) ^{:refer hara.object.framework.write/meta-write :added "3.0"} (fact "access read-attributes with caching" (write/meta-write DogBuilder) => (contains {:class test.DogBuilder :empty fn?, :methods (contains {:name (contains {:type java.lang.String, :fn fn?})})})) ^{:refer hara.object.framework.write/write-fields :added "3.0"} (fact "write fields of an object from reflection" (-> (write/write-fields Dog) keys) => [:name :species]) ^{:refer hara.object.framework.write/write-all-fields :added "3.0"} (fact "all write fields of an object from reflection" (-> (write/write-all-fields {}) keys) => [:-hash :-hasheq :-meta :array]) ^{:refer hara.object.framework.write/create-write-method :added "3.0"} (fact "create a write method from the template" (-> ((-> (write/create-write-method (reflect/query-class Cat ["setName" :#]) "set" write/+write-template+) second :fn) (test.Cat. "spike") "fluffy") (.getName)) => "fluffy") ^{:refer hara.object.framework.write/write-setters :added "3.0"} (fact "write fields of an object through setter methods" (write/write-setters Dog) => {} (keys (write/write-setters DogBuilder)) => [:name]) ^{:refer hara.object.framework.write/write-all-setters :added "3.0"} (fact "write all setters of an object and base classes" (write/write-all-setters Dog) => {} (keys (write/write-all-setters DogBuilder)) => [:name]) ^{:refer hara.object.framework.write/from-empty :added "3.0"} (fact "creates the object from an empty object constructor" (write/from-empty {:name "chris" :pet "dog"} (fn [] (java.util.Hashtable.)) {:name {:type String :fn (fn [obj v] (.put obj "hello" (keyword v)) obj)} :pet {:type String :fn (fn [obj v] (.put obj "pet" (keyword v)) obj)}}) => {"pet" :dog, "hello" :chris}) ^{:refer hara.object.framework.write/from-constructor :added "3.0"} (fact "creates the object from a constructor" (-> {:name "spike"} (write/from-constructor {:fn (fn [name] (Cat. name)) :params [:name]} {})) ;;=> #test.Cat{:name "spike", :species "cat"} ) ^{:refer hara.object.framework.write/from-map :added "3.0"} (fact "creates the object from a map" (-> {:name "chris" :age 30 :pets [{:name "slurp" :species "dog"} {:name "happy" :species "cat"}]} (write/from-map test.Person) (read/to-data)) => (contains-in {:name "chris", :age 30, :pets [{:name "slurp"} {:name "happy"}]})) ^{:refer hara.object.framework.write/from-data :added "3.0"} (fact "creates the object from data" (-> (write/from-data ["hello"] (Class/forName "[Ljava.lang.String;")) seq) => ["hello"]) (comment (./import))
6990
(ns hara.object.framework.write-test (:use hara.test) (:require [hara.object.framework.read :as read] [hara.object.framework.write :as write] [hara.protocol.object :as object] [hara.object.query :as reflect] [hara.object.framework.base-test]) (:import [test PersonBuilder Person Dog DogBuilder Cat Pet])) ^{:refer hara.object.framework.write/meta-write :added "3.0"} (fact "access read-attributes with caching" (write/meta-write DogBuilder) => (contains {:class test.DogBuilder :empty fn?, :methods (contains {:name (contains {:type java.lang.String, :fn fn?})})})) ^{:refer hara.object.framework.write/write-fields :added "3.0"} (fact "write fields of an object from reflection" (-> (write/write-fields Dog) keys) => [:name :species]) ^{:refer hara.object.framework.write/write-all-fields :added "3.0"} (fact "all write fields of an object from reflection" (-> (write/write-all-fields {}) keys) => [:-hash :-hasheq :-meta :array]) ^{:refer hara.object.framework.write/create-write-method :added "3.0"} (fact "create a write method from the template" (-> ((-> (write/create-write-method (reflect/query-class Cat ["setName" :#]) "set" write/+write-template+) second :fn) (test.Cat. "spike") "fluffy") (.getName)) => "fluffy") ^{:refer hara.object.framework.write/write-setters :added "3.0"} (fact "write fields of an object through setter methods" (write/write-setters Dog) => {} (keys (write/write-setters DogBuilder)) => [:name]) ^{:refer hara.object.framework.write/write-all-setters :added "3.0"} (fact "write all setters of an object and base classes" (write/write-all-setters Dog) => {} (keys (write/write-all-setters DogBuilder)) => [:name]) ^{:refer hara.object.framework.write/from-empty :added "3.0"} (fact "creates the object from an empty object constructor" (write/from-empty {:name "<NAME>" :pet "dog"} (fn [] (java.util.Hashtable.)) {:name {:type String :fn (fn [obj v] (.put obj "hello" (keyword v)) obj)} :pet {:type String :fn (fn [obj v] (.put obj "pet" (keyword v)) obj)}}) => {"pet" :dog, "hello" :chris}) ^{:refer hara.object.framework.write/from-constructor :added "3.0"} (fact "creates the object from a constructor" (-> {:name "spike"} (write/from-constructor {:fn (fn [name] (Cat. name)) :params [:name]} {})) ;;=> #test.Cat{:name "<NAME>", :species "cat"} ) ^{:refer hara.object.framework.write/from-map :added "3.0"} (fact "creates the object from a map" (-> {:name "<NAME>" :age 30 :pets [{:name "sl<NAME>" :species "dog"} {:name "happy" :species "cat"}]} (write/from-map test.Person) (read/to-data)) => (contains-in {:name "<NAME>", :age 30, :pets [{:name "slurp"} {:name "happy"}]})) ^{:refer hara.object.framework.write/from-data :added "3.0"} (fact "creates the object from data" (-> (write/from-data ["hello"] (Class/forName "[Ljava.lang.String;")) seq) => ["hello"]) (comment (./import))
true
(ns hara.object.framework.write-test (:use hara.test) (:require [hara.object.framework.read :as read] [hara.object.framework.write :as write] [hara.protocol.object :as object] [hara.object.query :as reflect] [hara.object.framework.base-test]) (:import [test PersonBuilder Person Dog DogBuilder Cat Pet])) ^{:refer hara.object.framework.write/meta-write :added "3.0"} (fact "access read-attributes with caching" (write/meta-write DogBuilder) => (contains {:class test.DogBuilder :empty fn?, :methods (contains {:name (contains {:type java.lang.String, :fn fn?})})})) ^{:refer hara.object.framework.write/write-fields :added "3.0"} (fact "write fields of an object from reflection" (-> (write/write-fields Dog) keys) => [:name :species]) ^{:refer hara.object.framework.write/write-all-fields :added "3.0"} (fact "all write fields of an object from reflection" (-> (write/write-all-fields {}) keys) => [:-hash :-hasheq :-meta :array]) ^{:refer hara.object.framework.write/create-write-method :added "3.0"} (fact "create a write method from the template" (-> ((-> (write/create-write-method (reflect/query-class Cat ["setName" :#]) "set" write/+write-template+) second :fn) (test.Cat. "spike") "fluffy") (.getName)) => "fluffy") ^{:refer hara.object.framework.write/write-setters :added "3.0"} (fact "write fields of an object through setter methods" (write/write-setters Dog) => {} (keys (write/write-setters DogBuilder)) => [:name]) ^{:refer hara.object.framework.write/write-all-setters :added "3.0"} (fact "write all setters of an object and base classes" (write/write-all-setters Dog) => {} (keys (write/write-all-setters DogBuilder)) => [:name]) ^{:refer hara.object.framework.write/from-empty :added "3.0"} (fact "creates the object from an empty object constructor" (write/from-empty {:name "PI:NAME:<NAME>END_PI" :pet "dog"} (fn [] (java.util.Hashtable.)) {:name {:type String :fn (fn [obj v] (.put obj "hello" (keyword v)) obj)} :pet {:type String :fn (fn [obj v] (.put obj "pet" (keyword v)) obj)}}) => {"pet" :dog, "hello" :chris}) ^{:refer hara.object.framework.write/from-constructor :added "3.0"} (fact "creates the object from a constructor" (-> {:name "spike"} (write/from-constructor {:fn (fn [name] (Cat. name)) :params [:name]} {})) ;;=> #test.Cat{:name "PI:NAME:<NAME>END_PI", :species "cat"} ) ^{:refer hara.object.framework.write/from-map :added "3.0"} (fact "creates the object from a map" (-> {:name "PI:NAME:<NAME>END_PI" :age 30 :pets [{:name "slPI:NAME:<NAME>END_PI" :species "dog"} {:name "happy" :species "cat"}]} (write/from-map test.Person) (read/to-data)) => (contains-in {:name "PI:NAME:<NAME>END_PI", :age 30, :pets [{:name "slurp"} {:name "happy"}]})) ^{:refer hara.object.framework.write/from-data :added "3.0"} (fact "creates the object from data" (-> (write/from-data ["hello"] (Class/forName "[Ljava.lang.String;")) seq) => ["hello"]) (comment (./import))
[ { "context": "ns\n ^{:doc \"reduce(rs) support.\"\n :author \"Vladimir Tsanev\"}\n reactor-core.reducers\n (:refer-clojure :excl", "end": 666, "score": 0.9990719556808472, "start": 651, "tag": "NAME", "value": "Vladimir Tsanev" } ]
src/reactor_core/reducers.cljc
jaju/reactor-core-clojure
2
; ; Copyright 2018 the original author or authors. ; ; 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 ^{:doc "reduce(rs) support." :author "Vladimir Tsanev"} reactor-core.reducers (:refer-clojure :exclude [reduce]) (:require [reactor-core.publisher :refer [reduce]] #?(:cljs ["reactor-core-js/flux" :refer [Flux]])) #?(:clj (:import (reactor.core.publisher Flux)))) #?(:cljs (extend-protocol IReduce Flux (-reduce ([this f] (reduce f this)) ([this f start] (reduce f start this)))) :clj (extend-protocol clojure.core.protocols/CollReduce Flux (coll-reduce ([this f] (reduce f this)) ([this f start] (reduce f start this)))))
27186
; ; Copyright 2018 the original author or authors. ; ; 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 ^{:doc "reduce(rs) support." :author "<NAME>"} reactor-core.reducers (:refer-clojure :exclude [reduce]) (:require [reactor-core.publisher :refer [reduce]] #?(:cljs ["reactor-core-js/flux" :refer [Flux]])) #?(:clj (:import (reactor.core.publisher Flux)))) #?(:cljs (extend-protocol IReduce Flux (-reduce ([this f] (reduce f this)) ([this f start] (reduce f start this)))) :clj (extend-protocol clojure.core.protocols/CollReduce Flux (coll-reduce ([this f] (reduce f this)) ([this f start] (reduce f start this)))))
true
; ; Copyright 2018 the original author or authors. ; ; 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 ^{:doc "reduce(rs) support." :author "PI:NAME:<NAME>END_PI"} reactor-core.reducers (:refer-clojure :exclude [reduce]) (:require [reactor-core.publisher :refer [reduce]] #?(:cljs ["reactor-core-js/flux" :refer [Flux]])) #?(:clj (:import (reactor.core.publisher Flux)))) #?(:cljs (extend-protocol IReduce Flux (-reduce ([this f] (reduce f this)) ([this f start] (reduce f start this)))) :clj (extend-protocol clojure.core.protocols/CollReduce Flux (coll-reduce ([this f] (reduce f this)) ([this f start] (reduce f start this)))))
[ { "context": " ;16\n(def map-in-vector [\"Edgar\" {:birthday (java.util.Date. 73 1 6)}])\n(let [[na", "end": 3713, "score": 0.9993023872375488, "start": 3708, "tag": "NAME", "value": "Edgar" }, { "context": "\" was born on \" bd)) ;\"Edgar was born on Tue Feb 06 00:00:00 CST 1973\"\n;保持被解构的", "end": 3864, "score": 0.9989889860153198, "start": 3859, "tag": "NAME", "value": "Edgar" }, { "context": ":as original-map} m]\n (assoc original-map :name \"Edgar\")) ;{\"foo\" 88, :name \"Edgar", "end": 3984, "score": 0.9994749426841736, "start": 3979, "tag": "NAME", "value": "Edgar" }, { "context": "Edgar\")) ;{\"foo\" 88, :name \"Edgar\", :c [7 8 9], :b 6, :d {:e 10, :f 11}, 42 false, ", "end": 4034, "score": 0.9997498989105225, "start": 4029, "tag": "NAME", "value": "Edgar" }, { "context": "t2 opt2})\n;绑定符号到map中同名关键字所对应的元素\n(def chas {:name \"Chas\" :age 31 :location \"Mass\"})\n(let [{name :name age", "end": 4561, "score": 0.9981871843338013, "start": 4557, "tag": "NAME", "value": "Chas" }, { "context": " lives in British\"\n;:syms\n(def christophe {'name \"Christophe\" 'age 33 'location \"Rhone\"})\n(let [{:syms [name a", "end": 5237, "score": 0.9994542002677917, "start": 5227, "tag": "NAME", "value": "Christophe" }, { "context": " years old and lives in %s\" name age location)) ;\"Christophe is 33 years old and lives in Rhone\"\n;对顺序集合的“剩余”部分", "end": 5392, "score": 0.9987082481384277, "start": 5382, "tag": "NAME", "value": "Christophe" }, { "context": "s in Rhone\"\n;对顺序集合的“剩余”部分使用map解构\n(def user-info [\"robert8990\" 2011 :name \"Bob\" :city \"Boston\"])\n(let [[usernam", "end": 5477, "score": 0.9992725253105164, "start": 5467, "tag": "USERNAME", "value": "robert8990" }, { "context": "分使用map解构\n(def user-info [\"robert8990\" 2011 :name \"Bob\" :city \"Boston\"])\n(let [[username account-year & ", "end": 5494, "score": 0.9997283220291138, "start": 5491, "tag": "NAME", "value": "Bob" }, { "context": "s is in %s\" name city)) ;\"Bob is in Boston\"\n;Clojure可以直接使用map解构来解构集合的剩余部分——如果沈阳", "end": 5684, "score": 0.9995520710945129, "start": 5681, "tag": "NAME", "value": "Bob" }, { "context": "s is in %s\" name city)) ;\"Bob is in Boston\"\n\n;定义函数:fn\n(fn [x]\n (+ x 10))\n;函数定义", "end": 5897, "score": 0.9997116923332214, "start": 5894, "tag": "NAME", "value": "Bob" }, { "context": "d6a0e-36e2-4e1b-91c4-b7a822964073\"}\n(make-user \"Edgar\") ;{:user", "end": 7041, "score": 0.61698979139328, "start": 7038, "tag": "NAME", "value": "gar" }, { "context": "oin-date join-date\n :email email})\n(make-user2 \"Bobby\") ;{:usern", "end": 7386, "score": 0.9866234064102173, "start": 7381, "tag": "USERNAME", "value": "Bobby" }, { "context": " ;{:username \"Bobby\", :join-date #inst \"2015-03-26T13:52:50.037-00:00", "end": 7446, "score": 0.9995549917221069, "start": 7441, "tag": "USERNAME", "value": "Bobby" }, { "context": "-26T13:52:50.037-00:00\", :email nil}\n(make-user2 \"Bobby\"\n :join-date (java.util.Date.)\n ", "end": 7529, "score": 0.9784444570541382, "start": 7524, "tag": "USERNAME", "value": "Bobby" }, { "context": " :join-date (java.util.Date.)\n :email \"edgar615@gmail.com\") ;{:username \"Bobby\", :join-d", "end": 7610, "score": 0.9999234676361084, "start": 7592, "tag": "EMAIL", "value": "edgar615@gmail.com" }, { "context": "ar615@gmail.com\") ;{:username \"Bobby\", :join-date #inst \"2015-03-26T13:52:58.720-00:00", "end": 7650, "score": 0.9995492696762085, "start": 7645, "tag": "USERNAME", "value": "Bobby" }, { "context": "te #inst \"2015-03-26T13:52:58.720-00:00\", :email \"edgar615@gmail.com\"}\n;前置条件和后置条件\n;函数字面量,匿名函数\n(fn [x y] (Math/pow x y)", "end": 7729, "score": 0.9999234080314636, "start": 7711, "tag": "EMAIL", "value": "edgar615@gmail.com" } ]
src/clojure_tutorial/start/form.clj
edgar615/clojure-tutorial
1
(ns clojure-tutorial.start.form) ;阻止求值:quote ;quote阻止Clojure表达式的求值 (quote x) (symbol? (quote x)) ;quote有对应的reader语法:单引号'。reader在求值到单引号的时候会把它解析成一个quote 'x ;任何Clojure形式都可以被quote,包括数据结构。如果使用数据结构,那么返回的是数据结构本身(数据结构内的表达式将不作求值操作) '(+ x x) ;(+ x x) (list? '(+ x x)) ;true (list '+ 'x 'x) ;(+ x x) ;quote的一个有趣应用就是探查reader对于任意一个形式的求值结果 ''x ;(quote x) '@x ;(clojure.core/deref x) '#(+ % %) ;(fn* [p1__786#] (+ p1__786# p1__786#)) '`(a b ~c) ;(clojure.core/seq (clojure.core/concat (clojure.core/list (quote user/a)) (clojure.core/list (quote user/b)) (clojure.core/list c))) ;代码块do ;do会依次求值你传进来的所有表达式,并且把最后一个表达式的结果作为返回值 (do (println "hi") (apply * [4 5 6])) ;hi ;120 ;这些表达式的值除了最后一个都被丢弃了,但是它们的副作用还是发生了。 ;很多其他形式,包括fn、let、loop、try、defn以及这些形式的变种都隐式地使用了do形式 (let [a (inc (rand-int 10)) b (inc (rand-int 10))] (println (format "You rooled a %s and a %s" a b))) ;定义Var:def ;def的作用是在当前命名空间里定义(或重定义)一个var(你可以同时给它赋一个值,也可以不赋值) (def p "foo") p ;本地绑定:let (defn hypot [x y] (let [x2 (* x x) y2 (* y y)] (Math/sqrt (+ x2 y2)))) ;在任何需要本地绑定的地方都间接地使用了let。比如fn使用let来绑定函数参数作为函数体内的本地绑定 ;我们会在let的绑定数组里面对一个表达式求值,但是我们对于表达式的值并不关系,也不会去使用这个值。 在这种情况下,通常使用_来指定这个绑定的名字 ;解构 ;定义一个vector (def v [42 "foo" 99.2 [5 12]]) (first v) ;42 (second v) ;"foo" (last v) ;[5 12] (nth v 2) ;99.2 (v 2) ;99.2 (.get v 2) ;99.2 ;顺序解构 ;顺序解构可以对任何顺序集合近线解构 ;Clojure原生的list、vector以及seq ;任何实现了java.util.List接口的集合(比如ArrayList和LinkedList) ;java数组 ;字符串,对它解构的结果是一个个字符 (def v [42 "foo" 99.2 [5 12]]) (let [[x y z] v] (+ x z)) ;141.2 (let [x (nth v 0) y (nth v 1) z (nth v 2)] (+ x z)) ;142.2 ;解构的形式还支持嵌套的解构形式 (let [[x _ _ [y z]] v] (+ x y z)) ;59 ;保持剩下的元素 ;可以使用&符号来保持解构剩下的那些元素 (let [[x & rest] v] rest) ;("foo" 99.2 [5 12]) ;rest是一个序列,而不是vector,虽然被解构的参数v是一个vector ;保持被解构的值 ;可以在解构形式中指定:as选项来把被解构的原始集合绑定到一个本地绑定 (let [[x _ z :as original-vector] v] (conj original-vector (+ x z))) ;[42 "foo" 99.2 [5 12] 141.2] ;这里的original-vector被绑定到未做修改的集合v ;map解构 ;map解构对于下面的几种数据结构有效 ;Clojure原生的hash-map、array-map,以及记录类型 ;任何实现了java.util.Map的对象 ;get方法所支持的任何对象,比如:Clojure原生vector,字符串、数组 ;map解构 (def m {:a 5 :b 6 :c [7 8 9] :d {:e 10 :f 11} "foo" 88 42 false}) (let [{a :a b :b} m] (+ a b)) ;11 ;可以在map解构中用做key的不止是关键字,可以是任何类型的值,比如字符串 (let [{f "foo"} m] (+ f 12)) ;100 (let [{v 42} m] (if v 1 0)) ;0 ;如果要进行map解构的是vector,字符串或者数组的话,那么解构的则是数字类型的数组下标。 (let [{x 3 y 8} [12 0 0 -18 44 6 0 0 1]] (+ x y)) ;-17 ;map解构也可以处理内嵌map (let [{{e :e} :d} m] (* 2 e)) ;20 ;可以把顺序解构和map解构结合起来 (let [{[x _ y] :c} m] (+ x y)) ;16 (def map-in-vector ["Edgar" {:birthday (java.util.Date. 73 1 6)}]) (let [[name {bd :birthday}] map-in-vector] (str name " was born on " bd)) ;"Edgar was born on Tue Feb 06 00:00:00 CST 1973" ;保持被解构的集合 (let [{a :a :as original-map} m] (assoc original-map :name "Edgar")) ;{"foo" 88, :name "Edgar", :c [7 8 9], :b 6, :d {:e 10, :f 11}, 42 false, :a 5} ;默认值 ;可以使用:or来提供一个默认的map,如果要解构的key在集合中没有的话,那么默认map中的值会作为默认值绑定到我们的解构符号上去 (let [{k :unknown x :a :or {k 50}} m] (+ k x)) ;55 ;上述代码等同于 (let [{k :unknown x :a} m k (or k 50)] (+ k x)) ;:or能区分到底是美柚赋值,还是赋给的值就是逻辑false(nil或者false) (let [{opt1 :option} {:option false} opt1 (or opt1 true) {opt2 :option :or {:opt2 true}} {:option false}] {:opt1 opt1 :opt2 opt2}) ;绑定符号到map中同名关键字所对应的元素 (def chas {:name "Chas" :age 31 :location "Mass"}) (let [{name :name age :age location :location} chas] (format "%s is %s years old and lives in %s" name age location)) ;"Chas is 31 years old and lives in Mass" ;上述代码很冗长,这种情况下,Clojure提供了:keys、:strs和:syms来指定map中key的类型 ;:keys表示key的类型是关键字,:strs表示key的类型是字符串,:syms表示key的类型是符号 ;:keys (let [{:keys [name age location]} chas] (format "%s is %s years old and lives in %s" name age location)) ;:strs (def brian {"name" "Brain" "age" 31 "location" "British"}) (let [{:strs [name age location]} brian] (format "%s is %s years old and lives in %s" name age location)) ;"Brain is 31 years old and lives in British" ;:syms (def christophe {'name "Christophe" 'age 33 'location "Rhone"}) (let [{:syms [name age location]} christophe] (format "%s is %s years old and lives in %s" name age location)) ;"Christophe is 33 years old and lives in Rhone" ;对顺序集合的“剩余”部分使用map解构 (def user-info ["robert8990" 2011 :name "Bob" :city "Boston"]) (let [[username account-year & exra-info] user-info {:keys [name city]} (apply hash-map exra-info)] (format "%s is in %s" name city)) ;"Bob is in Boston" ;Clojure可以直接使用map解构来解构集合的剩余部分——如果沈阳部分的元素格式是偶数的话,顺序解构会把剩余的部分当做一个map来处理 (let [[username account-year & {:keys [name city]}] user-info] (format "%s is in %s" name city)) ;"Bob is in Boston" ;定义函数:fn (fn [x] (+ x 10)) ;函数定义时的参数与调用函数时实际传递的参数之间的对应是通过参数位置来完成的: ((fn [x] (+ x 10)) 8) ;18 ;也可以定义接受多个参数的函数 ((fn [x y z] (+ x y z)) 3 4 12) ;19 ;函数还可以又多个参数列表 (def strange-adder (fn adder-self-refrence ([x] (adder-self-refrence x 1)) ([x y] (+ x y)))) (strange-adder 10) ;11 (strange-adder 10 50) ;60 ;defn (defn strange-adder ([x] (strange-adder x 1)) ([x y] (+ x y))) (def redundant-adder (fn redundant-adder [x y z] (+ x y z))) ;等价于 (defn redundant-adder [x y z] (+ x y z)) ;解构函数参数 ;可变参函数 (defn concat-rest [x & rest] (apply str (butlast rest))) (concat-rest 0 1 2 3 4) ;123 ;“剩余参数”列表可以像其他序列一样进行解构 (defn make-user [& [user-id]] {:user-id (or user-id (str (java.util.UUID/randomUUID)))}) (make-user) ;{:user-id "b4ad6a0e-36e2-4e1b-91c4-b7a822964073"} (make-user "Edgar") ;{:user-id "Edgar"} ;关键字参数,关键字参数是构建在let对于剩余参数的map解构的基础上的。 ;定义一个接受很多参数的函数时通常又一些参数不是必选的,有一些参数可能又默认值,而且有时候魏蔓希望函数的使用者不必按照某个特定的顺序来传参 (defn make-user2 [username & {:keys [email join-date] :or {join-date (java.util.Date.)}}] {:username username :join-date join-date :email email}) (make-user2 "Bobby") ;{:username "Bobby", :join-date #inst "2015-03-26T13:52:50.037-00:00", :email nil} (make-user2 "Bobby" :join-date (java.util.Date.) :email "edgar615@gmail.com") ;{:username "Bobby", :join-date #inst "2015-03-26T13:52:58.720-00:00", :email "edgar615@gmail.com"} ;前置条件和后置条件 ;函数字面量,匿名函数 (fn [x y] (Math/pow x y)) #(Math/pow %1 %2) (read-string "#(Math/pow %1 %2)") ;(fn* [p1__828# p2__829#] (Math/pow p1__828# p2__829#)) ;函数字面量没有隐式地使用do ;普通的fn(以及由它引申出来的所有变种)把它的函数体放在一个隐式的do里面,因此我们可以定义下面的函数: (fn [x y] (println (str x \^ y)) (Math/pow x y)) ;如果使用函数字面量,需要显示地使用一个do形式 #(do (println (str %1 \^ %2)) (Math/pow %1 %2)) ;因为很多函数字面量都只接受一个参数,所以可以简单地使用%来引用它的第一个函数, #(Math/pow % %2) ;等价于 #(Math/pow %1 %2) ;可以定义不定参数的函数,并且通过%&来引用那些剩余函数 (fn [x & rest] (- x (apply + rest))) ;等价于 #(- % (apply + %&)) ;注意fn可以嵌套使用,但是函数字面量不能嵌套使用 ;defn的语法 ;(defn function-name doc-string? attr-map? [parameter-list] ; conditions-map? ; (expressions)) ;增加文档:doc-string? (defn total-cost "return line-item total of the item and quantity provided" [item-cost number-of-items] (* item-cost number-of-items)) (doc total-cost) ;conditions-map ;:pre 运行前检查 ;:post 运行后检查 (defn item-total [price quantity] {:pre [(> price 0) (> quantity 0)] :post [(> % 0)]} (* price quantity)) (item-total 20 1) ;;20 (item-total 20 0) ;;AssertionError Assert failed: (> quantity 0) (item-total 0 1) ;;AssertionError Assert failed: (> price 0) ;%用来表示函数的返回值 ;条件判断if ;如果if的第一个表达式的值是逻辑true的话,那么整个if的值就是第二个表达式的值 ;Clojure的条件判断把任何非nil或非false的值都判断为true (if "hi" \t) ;\t (if 42 \t) ;\t (if nil "unevaluated" \t) ;\t (if false "unevaluated" \t) ;\t (if (not true) \t) ;nil ;true?、false?检查所给的参数是不是布尔值true和false,而不是逻辑上的true和false ;循环:loop和recur ;Clojure提供了好几个有用的循环函数,包括doseq和dotimes,它们抖森构建在recur的基础之上 ;recur能够在不消耗堆栈空间的情况下把程序执行转到离本地上下文最近的loop头那里去,这个loop头可以是loop定义的,也可以是一个函数定义的。 (loop [x 5] (if (neg? x) x (recur (dec x)))) ;-1 ;函数也可以建立loop头,如果是函数建立loop头的话,那么recur所带的值则会绑定到函数的参数上面去 (defn countdown [x] (if (zero? x) :blastoff! (do (println x) (recur (dec x))))) (countdown 5) ;引用var:var ;命名一个var的符号求值成var所对应的值 (def x 5) x ;5 ;如果你想获得指向var本身的引用,而不是var的值,var这个特殊形式就是用来做这个的 (var x) ;#'user/x ;和java的互操作:.和new ;对象初始化 (java.util.ArrayList. 100) ;调用静态函数 (Math/pow 2 10) ;调用实例方法 (.substring "hello" 1 3) ;访问静态程爷变量 Integer/MAX_VALUE ;访问实例成员变量 ;(.someField someObject) ;异常处理:try、throw ;语法 (try expr* catch-clause* finally-clause?) ;状态修改:set! ;虽然Clojure强调使用不可变的数据结构和值,但是还是有一些场景中我们需要对一个状态进行改变 ;最常见的情况是调用一个java对象的set方法或者任意一个改变对象状态的方法,而对于剩下的那些场景,Clojure提供了函数:set!,它可以 ;1.设置那些没有根绑定的线程本地值 ;2.设置一个java的字段 ;3.设置由deftype定义的对象的可修改字段 ;锁的原语:monitor-enter和monitor-exit ;这两个是Clojure提供的锁原语,用来同步每个java对象上都有的monitor ;通常,不应该直接使用这两个原语,因为Clojure提供了一个宏:locking,它能够保证进行更合适的锁获取和锁释放
33003
(ns clojure-tutorial.start.form) ;阻止求值:quote ;quote阻止Clojure表达式的求值 (quote x) (symbol? (quote x)) ;quote有对应的reader语法:单引号'。reader在求值到单引号的时候会把它解析成一个quote 'x ;任何Clojure形式都可以被quote,包括数据结构。如果使用数据结构,那么返回的是数据结构本身(数据结构内的表达式将不作求值操作) '(+ x x) ;(+ x x) (list? '(+ x x)) ;true (list '+ 'x 'x) ;(+ x x) ;quote的一个有趣应用就是探查reader对于任意一个形式的求值结果 ''x ;(quote x) '@x ;(clojure.core/deref x) '#(+ % %) ;(fn* [p1__786#] (+ p1__786# p1__786#)) '`(a b ~c) ;(clojure.core/seq (clojure.core/concat (clojure.core/list (quote user/a)) (clojure.core/list (quote user/b)) (clojure.core/list c))) ;代码块do ;do会依次求值你传进来的所有表达式,并且把最后一个表达式的结果作为返回值 (do (println "hi") (apply * [4 5 6])) ;hi ;120 ;这些表达式的值除了最后一个都被丢弃了,但是它们的副作用还是发生了。 ;很多其他形式,包括fn、let、loop、try、defn以及这些形式的变种都隐式地使用了do形式 (let [a (inc (rand-int 10)) b (inc (rand-int 10))] (println (format "You rooled a %s and a %s" a b))) ;定义Var:def ;def的作用是在当前命名空间里定义(或重定义)一个var(你可以同时给它赋一个值,也可以不赋值) (def p "foo") p ;本地绑定:let (defn hypot [x y] (let [x2 (* x x) y2 (* y y)] (Math/sqrt (+ x2 y2)))) ;在任何需要本地绑定的地方都间接地使用了let。比如fn使用let来绑定函数参数作为函数体内的本地绑定 ;我们会在let的绑定数组里面对一个表达式求值,但是我们对于表达式的值并不关系,也不会去使用这个值。 在这种情况下,通常使用_来指定这个绑定的名字 ;解构 ;定义一个vector (def v [42 "foo" 99.2 [5 12]]) (first v) ;42 (second v) ;"foo" (last v) ;[5 12] (nth v 2) ;99.2 (v 2) ;99.2 (.get v 2) ;99.2 ;顺序解构 ;顺序解构可以对任何顺序集合近线解构 ;Clojure原生的list、vector以及seq ;任何实现了java.util.List接口的集合(比如ArrayList和LinkedList) ;java数组 ;字符串,对它解构的结果是一个个字符 (def v [42 "foo" 99.2 [5 12]]) (let [[x y z] v] (+ x z)) ;141.2 (let [x (nth v 0) y (nth v 1) z (nth v 2)] (+ x z)) ;142.2 ;解构的形式还支持嵌套的解构形式 (let [[x _ _ [y z]] v] (+ x y z)) ;59 ;保持剩下的元素 ;可以使用&符号来保持解构剩下的那些元素 (let [[x & rest] v] rest) ;("foo" 99.2 [5 12]) ;rest是一个序列,而不是vector,虽然被解构的参数v是一个vector ;保持被解构的值 ;可以在解构形式中指定:as选项来把被解构的原始集合绑定到一个本地绑定 (let [[x _ z :as original-vector] v] (conj original-vector (+ x z))) ;[42 "foo" 99.2 [5 12] 141.2] ;这里的original-vector被绑定到未做修改的集合v ;map解构 ;map解构对于下面的几种数据结构有效 ;Clojure原生的hash-map、array-map,以及记录类型 ;任何实现了java.util.Map的对象 ;get方法所支持的任何对象,比如:Clojure原生vector,字符串、数组 ;map解构 (def m {:a 5 :b 6 :c [7 8 9] :d {:e 10 :f 11} "foo" 88 42 false}) (let [{a :a b :b} m] (+ a b)) ;11 ;可以在map解构中用做key的不止是关键字,可以是任何类型的值,比如字符串 (let [{f "foo"} m] (+ f 12)) ;100 (let [{v 42} m] (if v 1 0)) ;0 ;如果要进行map解构的是vector,字符串或者数组的话,那么解构的则是数字类型的数组下标。 (let [{x 3 y 8} [12 0 0 -18 44 6 0 0 1]] (+ x y)) ;-17 ;map解构也可以处理内嵌map (let [{{e :e} :d} m] (* 2 e)) ;20 ;可以把顺序解构和map解构结合起来 (let [{[x _ y] :c} m] (+ x y)) ;16 (def map-in-vector ["<NAME>" {:birthday (java.util.Date. 73 1 6)}]) (let [[name {bd :birthday}] map-in-vector] (str name " was born on " bd)) ;"<NAME> was born on Tue Feb 06 00:00:00 CST 1973" ;保持被解构的集合 (let [{a :a :as original-map} m] (assoc original-map :name "<NAME>")) ;{"foo" 88, :name "<NAME>", :c [7 8 9], :b 6, :d {:e 10, :f 11}, 42 false, :a 5} ;默认值 ;可以使用:or来提供一个默认的map,如果要解构的key在集合中没有的话,那么默认map中的值会作为默认值绑定到我们的解构符号上去 (let [{k :unknown x :a :or {k 50}} m] (+ k x)) ;55 ;上述代码等同于 (let [{k :unknown x :a} m k (or k 50)] (+ k x)) ;:or能区分到底是美柚赋值,还是赋给的值就是逻辑false(nil或者false) (let [{opt1 :option} {:option false} opt1 (or opt1 true) {opt2 :option :or {:opt2 true}} {:option false}] {:opt1 opt1 :opt2 opt2}) ;绑定符号到map中同名关键字所对应的元素 (def chas {:name "<NAME>" :age 31 :location "Mass"}) (let [{name :name age :age location :location} chas] (format "%s is %s years old and lives in %s" name age location)) ;"Chas is 31 years old and lives in Mass" ;上述代码很冗长,这种情况下,Clojure提供了:keys、:strs和:syms来指定map中key的类型 ;:keys表示key的类型是关键字,:strs表示key的类型是字符串,:syms表示key的类型是符号 ;:keys (let [{:keys [name age location]} chas] (format "%s is %s years old and lives in %s" name age location)) ;:strs (def brian {"name" "Brain" "age" 31 "location" "British"}) (let [{:strs [name age location]} brian] (format "%s is %s years old and lives in %s" name age location)) ;"Brain is 31 years old and lives in British" ;:syms (def christophe {'name "<NAME>" 'age 33 'location "Rhone"}) (let [{:syms [name age location]} christophe] (format "%s is %s years old and lives in %s" name age location)) ;"<NAME> is 33 years old and lives in Rhone" ;对顺序集合的“剩余”部分使用map解构 (def user-info ["robert8990" 2011 :name "<NAME>" :city "Boston"]) (let [[username account-year & exra-info] user-info {:keys [name city]} (apply hash-map exra-info)] (format "%s is in %s" name city)) ;"<NAME> is in Boston" ;Clojure可以直接使用map解构来解构集合的剩余部分——如果沈阳部分的元素格式是偶数的话,顺序解构会把剩余的部分当做一个map来处理 (let [[username account-year & {:keys [name city]}] user-info] (format "%s is in %s" name city)) ;"<NAME> is in Boston" ;定义函数:fn (fn [x] (+ x 10)) ;函数定义时的参数与调用函数时实际传递的参数之间的对应是通过参数位置来完成的: ((fn [x] (+ x 10)) 8) ;18 ;也可以定义接受多个参数的函数 ((fn [x y z] (+ x y z)) 3 4 12) ;19 ;函数还可以又多个参数列表 (def strange-adder (fn adder-self-refrence ([x] (adder-self-refrence x 1)) ([x y] (+ x y)))) (strange-adder 10) ;11 (strange-adder 10 50) ;60 ;defn (defn strange-adder ([x] (strange-adder x 1)) ([x y] (+ x y))) (def redundant-adder (fn redundant-adder [x y z] (+ x y z))) ;等价于 (defn redundant-adder [x y z] (+ x y z)) ;解构函数参数 ;可变参函数 (defn concat-rest [x & rest] (apply str (butlast rest))) (concat-rest 0 1 2 3 4) ;123 ;“剩余参数”列表可以像其他序列一样进行解构 (defn make-user [& [user-id]] {:user-id (or user-id (str (java.util.UUID/randomUUID)))}) (make-user) ;{:user-id "b4ad6a0e-36e2-4e1b-91c4-b7a822964073"} (make-user "Ed<NAME>") ;{:user-id "Edgar"} ;关键字参数,关键字参数是构建在let对于剩余参数的map解构的基础上的。 ;定义一个接受很多参数的函数时通常又一些参数不是必选的,有一些参数可能又默认值,而且有时候魏蔓希望函数的使用者不必按照某个特定的顺序来传参 (defn make-user2 [username & {:keys [email join-date] :or {join-date (java.util.Date.)}}] {:username username :join-date join-date :email email}) (make-user2 "Bobby") ;{:username "Bobby", :join-date #inst "2015-03-26T13:52:50.037-00:00", :email nil} (make-user2 "Bobby" :join-date (java.util.Date.) :email "<EMAIL>") ;{:username "Bobby", :join-date #inst "2015-03-26T13:52:58.720-00:00", :email "<EMAIL>"} ;前置条件和后置条件 ;函数字面量,匿名函数 (fn [x y] (Math/pow x y)) #(Math/pow %1 %2) (read-string "#(Math/pow %1 %2)") ;(fn* [p1__828# p2__829#] (Math/pow p1__828# p2__829#)) ;函数字面量没有隐式地使用do ;普通的fn(以及由它引申出来的所有变种)把它的函数体放在一个隐式的do里面,因此我们可以定义下面的函数: (fn [x y] (println (str x \^ y)) (Math/pow x y)) ;如果使用函数字面量,需要显示地使用一个do形式 #(do (println (str %1 \^ %2)) (Math/pow %1 %2)) ;因为很多函数字面量都只接受一个参数,所以可以简单地使用%来引用它的第一个函数, #(Math/pow % %2) ;等价于 #(Math/pow %1 %2) ;可以定义不定参数的函数,并且通过%&来引用那些剩余函数 (fn [x & rest] (- x (apply + rest))) ;等价于 #(- % (apply + %&)) ;注意fn可以嵌套使用,但是函数字面量不能嵌套使用 ;defn的语法 ;(defn function-name doc-string? attr-map? [parameter-list] ; conditions-map? ; (expressions)) ;增加文档:doc-string? (defn total-cost "return line-item total of the item and quantity provided" [item-cost number-of-items] (* item-cost number-of-items)) (doc total-cost) ;conditions-map ;:pre 运行前检查 ;:post 运行后检查 (defn item-total [price quantity] {:pre [(> price 0) (> quantity 0)] :post [(> % 0)]} (* price quantity)) (item-total 20 1) ;;20 (item-total 20 0) ;;AssertionError Assert failed: (> quantity 0) (item-total 0 1) ;;AssertionError Assert failed: (> price 0) ;%用来表示函数的返回值 ;条件判断if ;如果if的第一个表达式的值是逻辑true的话,那么整个if的值就是第二个表达式的值 ;Clojure的条件判断把任何非nil或非false的值都判断为true (if "hi" \t) ;\t (if 42 \t) ;\t (if nil "unevaluated" \t) ;\t (if false "unevaluated" \t) ;\t (if (not true) \t) ;nil ;true?、false?检查所给的参数是不是布尔值true和false,而不是逻辑上的true和false ;循环:loop和recur ;Clojure提供了好几个有用的循环函数,包括doseq和dotimes,它们抖森构建在recur的基础之上 ;recur能够在不消耗堆栈空间的情况下把程序执行转到离本地上下文最近的loop头那里去,这个loop头可以是loop定义的,也可以是一个函数定义的。 (loop [x 5] (if (neg? x) x (recur (dec x)))) ;-1 ;函数也可以建立loop头,如果是函数建立loop头的话,那么recur所带的值则会绑定到函数的参数上面去 (defn countdown [x] (if (zero? x) :blastoff! (do (println x) (recur (dec x))))) (countdown 5) ;引用var:var ;命名一个var的符号求值成var所对应的值 (def x 5) x ;5 ;如果你想获得指向var本身的引用,而不是var的值,var这个特殊形式就是用来做这个的 (var x) ;#'user/x ;和java的互操作:.和new ;对象初始化 (java.util.ArrayList. 100) ;调用静态函数 (Math/pow 2 10) ;调用实例方法 (.substring "hello" 1 3) ;访问静态程爷变量 Integer/MAX_VALUE ;访问实例成员变量 ;(.someField someObject) ;异常处理:try、throw ;语法 (try expr* catch-clause* finally-clause?) ;状态修改:set! ;虽然Clojure强调使用不可变的数据结构和值,但是还是有一些场景中我们需要对一个状态进行改变 ;最常见的情况是调用一个java对象的set方法或者任意一个改变对象状态的方法,而对于剩下的那些场景,Clojure提供了函数:set!,它可以 ;1.设置那些没有根绑定的线程本地值 ;2.设置一个java的字段 ;3.设置由deftype定义的对象的可修改字段 ;锁的原语:monitor-enter和monitor-exit ;这两个是Clojure提供的锁原语,用来同步每个java对象上都有的monitor ;通常,不应该直接使用这两个原语,因为Clojure提供了一个宏:locking,它能够保证进行更合适的锁获取和锁释放
true
(ns clojure-tutorial.start.form) ;阻止求值:quote ;quote阻止Clojure表达式的求值 (quote x) (symbol? (quote x)) ;quote有对应的reader语法:单引号'。reader在求值到单引号的时候会把它解析成一个quote 'x ;任何Clojure形式都可以被quote,包括数据结构。如果使用数据结构,那么返回的是数据结构本身(数据结构内的表达式将不作求值操作) '(+ x x) ;(+ x x) (list? '(+ x x)) ;true (list '+ 'x 'x) ;(+ x x) ;quote的一个有趣应用就是探查reader对于任意一个形式的求值结果 ''x ;(quote x) '@x ;(clojure.core/deref x) '#(+ % %) ;(fn* [p1__786#] (+ p1__786# p1__786#)) '`(a b ~c) ;(clojure.core/seq (clojure.core/concat (clojure.core/list (quote user/a)) (clojure.core/list (quote user/b)) (clojure.core/list c))) ;代码块do ;do会依次求值你传进来的所有表达式,并且把最后一个表达式的结果作为返回值 (do (println "hi") (apply * [4 5 6])) ;hi ;120 ;这些表达式的值除了最后一个都被丢弃了,但是它们的副作用还是发生了。 ;很多其他形式,包括fn、let、loop、try、defn以及这些形式的变种都隐式地使用了do形式 (let [a (inc (rand-int 10)) b (inc (rand-int 10))] (println (format "You rooled a %s and a %s" a b))) ;定义Var:def ;def的作用是在当前命名空间里定义(或重定义)一个var(你可以同时给它赋一个值,也可以不赋值) (def p "foo") p ;本地绑定:let (defn hypot [x y] (let [x2 (* x x) y2 (* y y)] (Math/sqrt (+ x2 y2)))) ;在任何需要本地绑定的地方都间接地使用了let。比如fn使用let来绑定函数参数作为函数体内的本地绑定 ;我们会在let的绑定数组里面对一个表达式求值,但是我们对于表达式的值并不关系,也不会去使用这个值。 在这种情况下,通常使用_来指定这个绑定的名字 ;解构 ;定义一个vector (def v [42 "foo" 99.2 [5 12]]) (first v) ;42 (second v) ;"foo" (last v) ;[5 12] (nth v 2) ;99.2 (v 2) ;99.2 (.get v 2) ;99.2 ;顺序解构 ;顺序解构可以对任何顺序集合近线解构 ;Clojure原生的list、vector以及seq ;任何实现了java.util.List接口的集合(比如ArrayList和LinkedList) ;java数组 ;字符串,对它解构的结果是一个个字符 (def v [42 "foo" 99.2 [5 12]]) (let [[x y z] v] (+ x z)) ;141.2 (let [x (nth v 0) y (nth v 1) z (nth v 2)] (+ x z)) ;142.2 ;解构的形式还支持嵌套的解构形式 (let [[x _ _ [y z]] v] (+ x y z)) ;59 ;保持剩下的元素 ;可以使用&符号来保持解构剩下的那些元素 (let [[x & rest] v] rest) ;("foo" 99.2 [5 12]) ;rest是一个序列,而不是vector,虽然被解构的参数v是一个vector ;保持被解构的值 ;可以在解构形式中指定:as选项来把被解构的原始集合绑定到一个本地绑定 (let [[x _ z :as original-vector] v] (conj original-vector (+ x z))) ;[42 "foo" 99.2 [5 12] 141.2] ;这里的original-vector被绑定到未做修改的集合v ;map解构 ;map解构对于下面的几种数据结构有效 ;Clojure原生的hash-map、array-map,以及记录类型 ;任何实现了java.util.Map的对象 ;get方法所支持的任何对象,比如:Clojure原生vector,字符串、数组 ;map解构 (def m {:a 5 :b 6 :c [7 8 9] :d {:e 10 :f 11} "foo" 88 42 false}) (let [{a :a b :b} m] (+ a b)) ;11 ;可以在map解构中用做key的不止是关键字,可以是任何类型的值,比如字符串 (let [{f "foo"} m] (+ f 12)) ;100 (let [{v 42} m] (if v 1 0)) ;0 ;如果要进行map解构的是vector,字符串或者数组的话,那么解构的则是数字类型的数组下标。 (let [{x 3 y 8} [12 0 0 -18 44 6 0 0 1]] (+ x y)) ;-17 ;map解构也可以处理内嵌map (let [{{e :e} :d} m] (* 2 e)) ;20 ;可以把顺序解构和map解构结合起来 (let [{[x _ y] :c} m] (+ x y)) ;16 (def map-in-vector ["PI:NAME:<NAME>END_PI" {:birthday (java.util.Date. 73 1 6)}]) (let [[name {bd :birthday}] map-in-vector] (str name " was born on " bd)) ;"PI:NAME:<NAME>END_PI was born on Tue Feb 06 00:00:00 CST 1973" ;保持被解构的集合 (let [{a :a :as original-map} m] (assoc original-map :name "PI:NAME:<NAME>END_PI")) ;{"foo" 88, :name "PI:NAME:<NAME>END_PI", :c [7 8 9], :b 6, :d {:e 10, :f 11}, 42 false, :a 5} ;默认值 ;可以使用:or来提供一个默认的map,如果要解构的key在集合中没有的话,那么默认map中的值会作为默认值绑定到我们的解构符号上去 (let [{k :unknown x :a :or {k 50}} m] (+ k x)) ;55 ;上述代码等同于 (let [{k :unknown x :a} m k (or k 50)] (+ k x)) ;:or能区分到底是美柚赋值,还是赋给的值就是逻辑false(nil或者false) (let [{opt1 :option} {:option false} opt1 (or opt1 true) {opt2 :option :or {:opt2 true}} {:option false}] {:opt1 opt1 :opt2 opt2}) ;绑定符号到map中同名关键字所对应的元素 (def chas {:name "PI:NAME:<NAME>END_PI" :age 31 :location "Mass"}) (let [{name :name age :age location :location} chas] (format "%s is %s years old and lives in %s" name age location)) ;"Chas is 31 years old and lives in Mass" ;上述代码很冗长,这种情况下,Clojure提供了:keys、:strs和:syms来指定map中key的类型 ;:keys表示key的类型是关键字,:strs表示key的类型是字符串,:syms表示key的类型是符号 ;:keys (let [{:keys [name age location]} chas] (format "%s is %s years old and lives in %s" name age location)) ;:strs (def brian {"name" "Brain" "age" 31 "location" "British"}) (let [{:strs [name age location]} brian] (format "%s is %s years old and lives in %s" name age location)) ;"Brain is 31 years old and lives in British" ;:syms (def christophe {'name "PI:NAME:<NAME>END_PI" 'age 33 'location "Rhone"}) (let [{:syms [name age location]} christophe] (format "%s is %s years old and lives in %s" name age location)) ;"PI:NAME:<NAME>END_PI is 33 years old and lives in Rhone" ;对顺序集合的“剩余”部分使用map解构 (def user-info ["robert8990" 2011 :name "PI:NAME:<NAME>END_PI" :city "Boston"]) (let [[username account-year & exra-info] user-info {:keys [name city]} (apply hash-map exra-info)] (format "%s is in %s" name city)) ;"PI:NAME:<NAME>END_PI is in Boston" ;Clojure可以直接使用map解构来解构集合的剩余部分——如果沈阳部分的元素格式是偶数的话,顺序解构会把剩余的部分当做一个map来处理 (let [[username account-year & {:keys [name city]}] user-info] (format "%s is in %s" name city)) ;"PI:NAME:<NAME>END_PI is in Boston" ;定义函数:fn (fn [x] (+ x 10)) ;函数定义时的参数与调用函数时实际传递的参数之间的对应是通过参数位置来完成的: ((fn [x] (+ x 10)) 8) ;18 ;也可以定义接受多个参数的函数 ((fn [x y z] (+ x y z)) 3 4 12) ;19 ;函数还可以又多个参数列表 (def strange-adder (fn adder-self-refrence ([x] (adder-self-refrence x 1)) ([x y] (+ x y)))) (strange-adder 10) ;11 (strange-adder 10 50) ;60 ;defn (defn strange-adder ([x] (strange-adder x 1)) ([x y] (+ x y))) (def redundant-adder (fn redundant-adder [x y z] (+ x y z))) ;等价于 (defn redundant-adder [x y z] (+ x y z)) ;解构函数参数 ;可变参函数 (defn concat-rest [x & rest] (apply str (butlast rest))) (concat-rest 0 1 2 3 4) ;123 ;“剩余参数”列表可以像其他序列一样进行解构 (defn make-user [& [user-id]] {:user-id (or user-id (str (java.util.UUID/randomUUID)))}) (make-user) ;{:user-id "b4ad6a0e-36e2-4e1b-91c4-b7a822964073"} (make-user "EdPI:NAME:<NAME>END_PI") ;{:user-id "Edgar"} ;关键字参数,关键字参数是构建在let对于剩余参数的map解构的基础上的。 ;定义一个接受很多参数的函数时通常又一些参数不是必选的,有一些参数可能又默认值,而且有时候魏蔓希望函数的使用者不必按照某个特定的顺序来传参 (defn make-user2 [username & {:keys [email join-date] :or {join-date (java.util.Date.)}}] {:username username :join-date join-date :email email}) (make-user2 "Bobby") ;{:username "Bobby", :join-date #inst "2015-03-26T13:52:50.037-00:00", :email nil} (make-user2 "Bobby" :join-date (java.util.Date.) :email "PI:EMAIL:<EMAIL>END_PI") ;{:username "Bobby", :join-date #inst "2015-03-26T13:52:58.720-00:00", :email "PI:EMAIL:<EMAIL>END_PI"} ;前置条件和后置条件 ;函数字面量,匿名函数 (fn [x y] (Math/pow x y)) #(Math/pow %1 %2) (read-string "#(Math/pow %1 %2)") ;(fn* [p1__828# p2__829#] (Math/pow p1__828# p2__829#)) ;函数字面量没有隐式地使用do ;普通的fn(以及由它引申出来的所有变种)把它的函数体放在一个隐式的do里面,因此我们可以定义下面的函数: (fn [x y] (println (str x \^ y)) (Math/pow x y)) ;如果使用函数字面量,需要显示地使用一个do形式 #(do (println (str %1 \^ %2)) (Math/pow %1 %2)) ;因为很多函数字面量都只接受一个参数,所以可以简单地使用%来引用它的第一个函数, #(Math/pow % %2) ;等价于 #(Math/pow %1 %2) ;可以定义不定参数的函数,并且通过%&来引用那些剩余函数 (fn [x & rest] (- x (apply + rest))) ;等价于 #(- % (apply + %&)) ;注意fn可以嵌套使用,但是函数字面量不能嵌套使用 ;defn的语法 ;(defn function-name doc-string? attr-map? [parameter-list] ; conditions-map? ; (expressions)) ;增加文档:doc-string? (defn total-cost "return line-item total of the item and quantity provided" [item-cost number-of-items] (* item-cost number-of-items)) (doc total-cost) ;conditions-map ;:pre 运行前检查 ;:post 运行后检查 (defn item-total [price quantity] {:pre [(> price 0) (> quantity 0)] :post [(> % 0)]} (* price quantity)) (item-total 20 1) ;;20 (item-total 20 0) ;;AssertionError Assert failed: (> quantity 0) (item-total 0 1) ;;AssertionError Assert failed: (> price 0) ;%用来表示函数的返回值 ;条件判断if ;如果if的第一个表达式的值是逻辑true的话,那么整个if的值就是第二个表达式的值 ;Clojure的条件判断把任何非nil或非false的值都判断为true (if "hi" \t) ;\t (if 42 \t) ;\t (if nil "unevaluated" \t) ;\t (if false "unevaluated" \t) ;\t (if (not true) \t) ;nil ;true?、false?检查所给的参数是不是布尔值true和false,而不是逻辑上的true和false ;循环:loop和recur ;Clojure提供了好几个有用的循环函数,包括doseq和dotimes,它们抖森构建在recur的基础之上 ;recur能够在不消耗堆栈空间的情况下把程序执行转到离本地上下文最近的loop头那里去,这个loop头可以是loop定义的,也可以是一个函数定义的。 (loop [x 5] (if (neg? x) x (recur (dec x)))) ;-1 ;函数也可以建立loop头,如果是函数建立loop头的话,那么recur所带的值则会绑定到函数的参数上面去 (defn countdown [x] (if (zero? x) :blastoff! (do (println x) (recur (dec x))))) (countdown 5) ;引用var:var ;命名一个var的符号求值成var所对应的值 (def x 5) x ;5 ;如果你想获得指向var本身的引用,而不是var的值,var这个特殊形式就是用来做这个的 (var x) ;#'user/x ;和java的互操作:.和new ;对象初始化 (java.util.ArrayList. 100) ;调用静态函数 (Math/pow 2 10) ;调用实例方法 (.substring "hello" 1 3) ;访问静态程爷变量 Integer/MAX_VALUE ;访问实例成员变量 ;(.someField someObject) ;异常处理:try、throw ;语法 (try expr* catch-clause* finally-clause?) ;状态修改:set! ;虽然Clojure强调使用不可变的数据结构和值,但是还是有一些场景中我们需要对一个状态进行改变 ;最常见的情况是调用一个java对象的set方法或者任意一个改变对象状态的方法,而对于剩下的那些场景,Clojure提供了函数:set!,它可以 ;1.设置那些没有根绑定的线程本地值 ;2.设置一个java的字段 ;3.设置由deftype定义的对象的可修改字段 ;锁的原语:monitor-enter和monitor-exit ;这两个是Clojure提供的锁原语,用来同步每个java对象上都有的monitor ;通常,不应该直接使用这两个原语,因为Clojure提供了一个宏:locking,它能够保证进行更合适的锁获取和锁释放
[ { "context": "ntln \"Hello, \" fname))\n(greet-author {:last-name \"Vinge\" :first-name \"Vernor\"}) ;; ==> \"Hello, Vernor\"\n\n;", "end": 1584, "score": 0.9997360706329346, "start": 1579, "tag": "NAME", "value": "Vinge" }, { "context": "))\n(greet-author {:last-name \"Vinge\" :first-name \"Vernor\"}) ;; ==> \"Hello, Vernor\"\n\n;; Use vectors to de", "end": 1603, "score": 0.9995387196540833, "start": 1599, "tag": "NAME", "value": "Vern" }, { "context": "name \"Vinge\" :first-name \"Vernor\"}) ;; ==> \"Hello, Vernor\"\n\n;; Use vectors to destructure any sequential co", "end": 1630, "score": 0.9985203742980957, "start": 1624, "tag": "NAME", "value": "Vernor" } ]
clojure/programming-clojure/walkthrough/src/walkthrough/exploring.clj
waiyaki/learning-lisp
2
(require '[clojure.string :as str]) ;;;; Anonymous functions (defn indexable-word? "True if a word has more than 2 characters." [word] (> (count word) 2)) (filter indexable-word? (str/split "A fine day it is" #"\W+")) ;; with anonymous function (filter (fn [w] (> (count w) 2)) (str/split "A fine day it is" #"\W+")) ;; with macro syntax for anonymous functions using implicit parameter names (filter #(> (count %) 2) (str/split "A fine day it is" #"\W+")) (defn indexable-words "Return a list containing words with more than 2 characters from text" [text] (let [indexable-word? (fn [w] (> (count w) 2))] (filter indexable-word? (str/split text #"\W+")))) (indexable-words "A fine day it is.") (defn make-greeter [greeting-prefix] (fn [username] (str greeting-prefix ", " username))) (def hello-greeting (make-greeter "Hello")) (hello-greeting "world") (def aloha-greeting (make-greeter "Aloha")) (aloha-greeting "world") ((make-greeter "Howdy") "partner") ;;;; Vars, Bindings, Namespaces ;; namespace - a collection of names (symbols) that refer to vars ;; vars are bound to values ;; root-binding - initial value of a var ;; Objects defined with def or defn are stored in Clojure vars. ;; The special form `var` returns the var itself, not the value bound to the var (def foo 10) (var foo) ;; The `var` special form has the reader macro `#'` #'foo ;; => 'walkthrough.core/foo ;;; Destructuring ;; Use maps to destructure any associative collections (defn greet-author [{fname :first-name}] (println "Hello, " fname)) (greet-author {:last-name "Vinge" :first-name "Vernor"}) ;; ==> "Hello, Vernor" ;; Use vectors to destructure any sequential collection (let [[x y] [ 1 2 3]] [x y]) ;; => [1 2] ;; to skip over elements: (let [[_ _ z] [1 2 3]] z) ;; => 3 ;; You can bind elements within a collection and the entire collection ;; In a destructuring assignment, :as clause gives a binding for the entire coll (let [[x y :as coords] [1 2 3 4 5]] [x y coords]) ;; => [1 2 [1 2 3 4 5]] (defn ellipsize "Return the first 3 words followed by an ellipse (...)" [words] (let [[w1 w2 w3] (str/split words #"\s+")] (str/join " " [w1 w2 w3 "..."]))) (ellipsize "The quick brown fox jumped over the lazy dog.") ;; => "The quick brown ..." (defn indexed "Return a sequence of pairs of the form [idx elt] containing an element and it's index" [coll] (map-indexed vector coll)) (indexed "abcde") ;; => ([0 \a] [1 \b] [2 \c] [3 \d] [4 \e]) (defn index-filter "Like filter, but return the indices instead of the matches themselves" [pred coll] (when pred (for [[idx elt] (indexed coll) :when (pred elt)] idx))) ;; Clojure sets are functions that test membership... (index-filter #{\a \b} "abbcddb") ;; => (0 1 2 6) (defn index-of-any [pred coll] (first (index-filter pred coll))) (index-of-any #{\z \a} "zzabs") ;; => 0 (index-of-any #{\a \b} "xyz") ;; => nil
6300
(require '[clojure.string :as str]) ;;;; Anonymous functions (defn indexable-word? "True if a word has more than 2 characters." [word] (> (count word) 2)) (filter indexable-word? (str/split "A fine day it is" #"\W+")) ;; with anonymous function (filter (fn [w] (> (count w) 2)) (str/split "A fine day it is" #"\W+")) ;; with macro syntax for anonymous functions using implicit parameter names (filter #(> (count %) 2) (str/split "A fine day it is" #"\W+")) (defn indexable-words "Return a list containing words with more than 2 characters from text" [text] (let [indexable-word? (fn [w] (> (count w) 2))] (filter indexable-word? (str/split text #"\W+")))) (indexable-words "A fine day it is.") (defn make-greeter [greeting-prefix] (fn [username] (str greeting-prefix ", " username))) (def hello-greeting (make-greeter "Hello")) (hello-greeting "world") (def aloha-greeting (make-greeter "Aloha")) (aloha-greeting "world") ((make-greeter "Howdy") "partner") ;;;; Vars, Bindings, Namespaces ;; namespace - a collection of names (symbols) that refer to vars ;; vars are bound to values ;; root-binding - initial value of a var ;; Objects defined with def or defn are stored in Clojure vars. ;; The special form `var` returns the var itself, not the value bound to the var (def foo 10) (var foo) ;; The `var` special form has the reader macro `#'` #'foo ;; => 'walkthrough.core/foo ;;; Destructuring ;; Use maps to destructure any associative collections (defn greet-author [{fname :first-name}] (println "Hello, " fname)) (greet-author {:last-name "<NAME>" :first-name "<NAME>or"}) ;; ==> "Hello, <NAME>" ;; Use vectors to destructure any sequential collection (let [[x y] [ 1 2 3]] [x y]) ;; => [1 2] ;; to skip over elements: (let [[_ _ z] [1 2 3]] z) ;; => 3 ;; You can bind elements within a collection and the entire collection ;; In a destructuring assignment, :as clause gives a binding for the entire coll (let [[x y :as coords] [1 2 3 4 5]] [x y coords]) ;; => [1 2 [1 2 3 4 5]] (defn ellipsize "Return the first 3 words followed by an ellipse (...)" [words] (let [[w1 w2 w3] (str/split words #"\s+")] (str/join " " [w1 w2 w3 "..."]))) (ellipsize "The quick brown fox jumped over the lazy dog.") ;; => "The quick brown ..." (defn indexed "Return a sequence of pairs of the form [idx elt] containing an element and it's index" [coll] (map-indexed vector coll)) (indexed "abcde") ;; => ([0 \a] [1 \b] [2 \c] [3 \d] [4 \e]) (defn index-filter "Like filter, but return the indices instead of the matches themselves" [pred coll] (when pred (for [[idx elt] (indexed coll) :when (pred elt)] idx))) ;; Clojure sets are functions that test membership... (index-filter #{\a \b} "abbcddb") ;; => (0 1 2 6) (defn index-of-any [pred coll] (first (index-filter pred coll))) (index-of-any #{\z \a} "zzabs") ;; => 0 (index-of-any #{\a \b} "xyz") ;; => nil
true
(require '[clojure.string :as str]) ;;;; Anonymous functions (defn indexable-word? "True if a word has more than 2 characters." [word] (> (count word) 2)) (filter indexable-word? (str/split "A fine day it is" #"\W+")) ;; with anonymous function (filter (fn [w] (> (count w) 2)) (str/split "A fine day it is" #"\W+")) ;; with macro syntax for anonymous functions using implicit parameter names (filter #(> (count %) 2) (str/split "A fine day it is" #"\W+")) (defn indexable-words "Return a list containing words with more than 2 characters from text" [text] (let [indexable-word? (fn [w] (> (count w) 2))] (filter indexable-word? (str/split text #"\W+")))) (indexable-words "A fine day it is.") (defn make-greeter [greeting-prefix] (fn [username] (str greeting-prefix ", " username))) (def hello-greeting (make-greeter "Hello")) (hello-greeting "world") (def aloha-greeting (make-greeter "Aloha")) (aloha-greeting "world") ((make-greeter "Howdy") "partner") ;;;; Vars, Bindings, Namespaces ;; namespace - a collection of names (symbols) that refer to vars ;; vars are bound to values ;; root-binding - initial value of a var ;; Objects defined with def or defn are stored in Clojure vars. ;; The special form `var` returns the var itself, not the value bound to the var (def foo 10) (var foo) ;; The `var` special form has the reader macro `#'` #'foo ;; => 'walkthrough.core/foo ;;; Destructuring ;; Use maps to destructure any associative collections (defn greet-author [{fname :first-name}] (println "Hello, " fname)) (greet-author {:last-name "PI:NAME:<NAME>END_PI" :first-name "PI:NAME:<NAME>END_PIor"}) ;; ==> "Hello, PI:NAME:<NAME>END_PI" ;; Use vectors to destructure any sequential collection (let [[x y] [ 1 2 3]] [x y]) ;; => [1 2] ;; to skip over elements: (let [[_ _ z] [1 2 3]] z) ;; => 3 ;; You can bind elements within a collection and the entire collection ;; In a destructuring assignment, :as clause gives a binding for the entire coll (let [[x y :as coords] [1 2 3 4 5]] [x y coords]) ;; => [1 2 [1 2 3 4 5]] (defn ellipsize "Return the first 3 words followed by an ellipse (...)" [words] (let [[w1 w2 w3] (str/split words #"\s+")] (str/join " " [w1 w2 w3 "..."]))) (ellipsize "The quick brown fox jumped over the lazy dog.") ;; => "The quick brown ..." (defn indexed "Return a sequence of pairs of the form [idx elt] containing an element and it's index" [coll] (map-indexed vector coll)) (indexed "abcde") ;; => ([0 \a] [1 \b] [2 \c] [3 \d] [4 \e]) (defn index-filter "Like filter, but return the indices instead of the matches themselves" [pred coll] (when pred (for [[idx elt] (indexed coll) :when (pred elt)] idx))) ;; Clojure sets are functions that test membership... (index-filter #{\a \b} "abbcddb") ;; => (0 1 2 6) (defn index-of-any [pred coll] (first (index-filter pred coll))) (index-of-any #{\z \a} "zzabs") ;; => 0 (index-of-any #{\a \b} "xyz") ;; => nil
[ { "context": "(ns ^{:author \"Leeor Engel\"}\n chapter-3.chapter-3-q5-test\n (:require [cloj", "end": 26, "score": 0.9998882412910461, "start": 15, "tag": "NAME", "value": "Leeor Engel" } ]
Clojure/test/chapter_3/chapter_3_q5_test.clj
Kiandr/crackingcodinginterview
0
(ns ^{:author "Leeor Engel"} chapter-3.chapter-3-q5-test (:require [clojure.test :refer :all] [data-structures.stack :refer :all] [data-structures.persistent-stack :refer :all] [chapter-3.chapter-3-q5 :refer :all])) (deftest sort-stack-test (testing "Already sorted" (let [stack (create-stack '(1 2 3 4))] (let [sorted (sort-stack stack)] (is (= 1 (stack-peek sorted))) (is (= (create-stack (list 2 3 4)) (stack-pop sorted)))))) (testing "Basic sort" (let [stack (create-stack '(3 1 4 2))] (let [sorted (sort-stack stack)] (is (= 1 (stack-peek sorted))) (is (= (create-stack (list 2 3 4)) (stack-pop sorted)))))) (testing "Reverse order" (let [stack (create-stack '(8 7 6 5 4 3 2 1))] (let [sorted (sort-stack stack)] (is (= 1 (stack-peek sorted))) (is (= (create-stack (list 2 3 4 5 6 7 8)) (stack-pop sorted)))))) (testing "Basic sort" (let [stack (create-stack '(81 2 25 26 15 34 6))] (let [sorted (sort-stack stack)] (is (= 2 (stack-peek sorted))) (is (= (create-stack (list 6 15 25 26 34 81)) (stack-pop sorted)))))))
102522
(ns ^{:author "<NAME>"} chapter-3.chapter-3-q5-test (:require [clojure.test :refer :all] [data-structures.stack :refer :all] [data-structures.persistent-stack :refer :all] [chapter-3.chapter-3-q5 :refer :all])) (deftest sort-stack-test (testing "Already sorted" (let [stack (create-stack '(1 2 3 4))] (let [sorted (sort-stack stack)] (is (= 1 (stack-peek sorted))) (is (= (create-stack (list 2 3 4)) (stack-pop sorted)))))) (testing "Basic sort" (let [stack (create-stack '(3 1 4 2))] (let [sorted (sort-stack stack)] (is (= 1 (stack-peek sorted))) (is (= (create-stack (list 2 3 4)) (stack-pop sorted)))))) (testing "Reverse order" (let [stack (create-stack '(8 7 6 5 4 3 2 1))] (let [sorted (sort-stack stack)] (is (= 1 (stack-peek sorted))) (is (= (create-stack (list 2 3 4 5 6 7 8)) (stack-pop sorted)))))) (testing "Basic sort" (let [stack (create-stack '(81 2 25 26 15 34 6))] (let [sorted (sort-stack stack)] (is (= 2 (stack-peek sorted))) (is (= (create-stack (list 6 15 25 26 34 81)) (stack-pop sorted)))))))
true
(ns ^{:author "PI:NAME:<NAME>END_PI"} chapter-3.chapter-3-q5-test (:require [clojure.test :refer :all] [data-structures.stack :refer :all] [data-structures.persistent-stack :refer :all] [chapter-3.chapter-3-q5 :refer :all])) (deftest sort-stack-test (testing "Already sorted" (let [stack (create-stack '(1 2 3 4))] (let [sorted (sort-stack stack)] (is (= 1 (stack-peek sorted))) (is (= (create-stack (list 2 3 4)) (stack-pop sorted)))))) (testing "Basic sort" (let [stack (create-stack '(3 1 4 2))] (let [sorted (sort-stack stack)] (is (= 1 (stack-peek sorted))) (is (= (create-stack (list 2 3 4)) (stack-pop sorted)))))) (testing "Reverse order" (let [stack (create-stack '(8 7 6 5 4 3 2 1))] (let [sorted (sort-stack stack)] (is (= 1 (stack-peek sorted))) (is (= (create-stack (list 2 3 4 5 6 7 8)) (stack-pop sorted)))))) (testing "Basic sort" (let [stack (create-stack '(81 2 25 26 15 34 6))] (let [sorted (sort-stack stack)] (is (= 2 (stack-peek sorted))) (is (= (create-stack (list 6 15 25 26 34 81)) (stack-pop sorted)))))))
[ { "context": "((jsonpath [1 2 3] \"$.\") {} nil)))\n (is (= [\"Joe\" \"Bob\"] ((jsonpath [{:name \"Joe\"} {:name \"Bob\"}] ", "end": 5805, "score": 0.9994922876358032, "start": 5802, "tag": "NAME", "value": "Joe" }, { "context": "path [1 2 3] \"$.\") {} nil)))\n (is (= [\"Joe\" \"Bob\"] ((jsonpath [{:name \"Joe\"} {:name \"Bob\"}] \"$.nam", "end": 5811, "score": 0.999535083770752, "start": 5808, "tag": "NAME", "value": "Bob" }, { "context": "))\n (is (= [\"Joe\" \"Bob\"] ((jsonpath [{:name \"Joe\"} {:name \"Bob\"}] \"$.name\") {} nil))))\n (testin", "end": 5837, "score": 0.9995714426040649, "start": 5834, "tag": "NAME", "value": "Joe" }, { "context": "= [\"Joe\" \"Bob\"] ((jsonpath [{:name \"Joe\"} {:name \"Bob\"}] \"$.name\") {} nil))))\n (testing \"with map\"\n ", "end": 5851, "score": 0.9995916485786438, "start": 5848, "tag": "NAME", "value": "Bob" } ]
test/parsec/functions/parse_functions_test.clj
ExpediaGroup/parsec
1
(ns parsec.functions.parse-functions-test (:require [clojure.test :refer :all] [parsec.helpers :refer :all] [parsec.test-helpers :refer :all] [parsec.functions :refer :all] [parsec.functions.parsingfunctions :refer :all])) (deftest parsejson-test (let [parsejson (partial function-transform :parsejson)] (testing "with nil" (is (nil? ((parsejson nil) {} nil))) (is (nil? ((parsejson :col1) {:col1 nil} nil)))) (testing "with number" (is (= 0 ((parsejson "0") {} nil))) (is (= 1.0 ((parsejson "1.0") {} nil)))) (testing "with string" (is (= "hello world" ((parsejson "\"hello world\"") {} nil)))) (testing "with boolean" (is (false? ((parsejson "false") {} nil))) (is (true? ((parsejson "true") {} nil)))) (testing "with list" (is (= '() ((parsejson "[]") {} nil))) (is (= '(1 2) ((parsejson "[1, 2]") {} nil))) (is (sequential? ((parsejson "[1, 2]") {} nil)))) (testing "with map" (is (map? ((parsejson "{}") {} nil))) (is (= { :a 1 :b 2 } ((parsejson "{\"a\": 1, \"b\": 2}") {} nil))) (is (= { :a [1 2] :b { :c true } } ((parsejson "{\"a\": [1, 2], \"b\": { \"c\": true }}") {} nil)))))) (deftest parsecsv-test (let [parsecsv (partial function-transform :parsecsv)] (testing "with nil" (is (nil? ((parsecsv nil) {} nil))) (is (nil? ((parsecsv :col1) {:col1 nil} nil)))) (testing "with non-CSV data" (is (= [] ((parsecsv "0") {} nil))) (is (= [] ((parsecsv "\"hello world\"") {} nil))) (is (= [] ((parsecsv "false") {} nil))) (is (= [] ((parsecsv "true") {} nil))) (is (= [] ((parsecsv "[1, 2]") {} nil)))) (testing "with CSV string" (is (= [{:a "1" :b "2" :c "3"}] ((parsecsv "a,b,c\n1,2,3") {} nil))) (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "a,b,c\r\n1,2,3\r\n4,5,6") {} nil)))) (testing "with options" (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "a,b,c\t1,2,3\t4,5,6" { :eol "\t" }) {} nil))) (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "a\tb\tc\n1\t2\t3\n4\t5\t6" { :delimiter "\t" }) {} nil))) (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "`a`,`b`,`c`\n1,2,3\n4,5,6" { :quote "`" }) {} nil))) (is (= [{:a "hello world" :b "2" :c "3"} {:a "goodbye world" :b "5" :c "6"}] ((parsecsv "a-b-c\n`hello world`-2-3\n`goodbye world`-5-6" { :quote "`", :delimiter "-" }) {} nil)))) (testing "with headers" (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "a,b,c\n1,2,3\r\n4,5,6" { :headers true }) {} nil))) (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "1,2,3\r\n4,5,6" { :headers ["a","b","c"] }) {} nil))) (is (= [{:col0 "1" :col1 "2" :col2 "3"} {:col0 "4" :col1 "5" :col2 "6"}] ((parsecsv "1,2,3\r\n4,5,6" { :headers false }) {} nil))) ))) (deftest parsexml-test (let [parsexml (partial function-transform :parsexml)] (testing "with nil" (is (nil? ((parsexml nil) {} nil))) (is (nil? ((parsexml :col1) {:col1 nil} nil)))) (testing "with non-XML data" (is (thrown? Exception ((parsexml "0") {} nil))) (is (thrown? Exception ((parsexml "\"hello world\"") {} nil))) (is (thrown? Exception ((parsexml "false") {} nil))) (is (thrown? Exception ((parsexml "true") {} nil))) (is (thrown? Exception ((parsexml "[1, 2]") {} nil)))) (testing "with XML string" (is (= [{:root "one"}] ((parsexml "<root>one</root>") {} nil))) (is (= [{:root "one" :v "1"}] ((parsexml "<root v=\"1\">one</root>") {} nil))) (is (= [{:root "one" :v "1" :w "ok"}] ((parsexml "<root v=\"1\" w=\"ok\">one</root>") {} nil))) (is (= [{:a "one" :b "two"}] ((parsexml "<root><a>one</a><b>two</b></root>") {} nil))) (is (= [{:a "two"}] ((parsexml "<root><a>one</a><a>two</a></root>") {} nil)))) (testing "with raw mode" (is (= #clojure.data.xml.Element{ :tag :root :attrs {} :content ["one"] } ((parsexml "<root>one</root>" { :xpath "/root" :raw true }) {} nil)))) (testing "with xpath" (is (= [{:a "one"} {:a "two"}] ((parsexml "<root><a>one</a><a>two</a></root>" { :xpath "/root/a" }) {} nil))) (is (= [{:a "one"} {:a "two"}] ((parsexml "<root><subroot><a>one</a><a>two</a></subroot></root>" { :xpath "/root/subroot/a" }) {} nil))) (is (= [{:a "one"} {:a "two"}] ((parsexml "<root><subroot><a>one</a><a>two</a></subroot></root>" { :xpath "//a" }) {} nil))) (is (= [{:a "one"} {:b "two"}] ((parsexml "<root><subroot><a>one</a><b>two</b></subroot></root>" { :xpath "/root/subroot/a|/root/subroot/b" }) {} nil)))) (testing "with flatten" (is (= [{:a "one" :b "two"}] ((parsexml "<root><a>one</a><b>two</b></root>" { :xpath "/root" :flatten true}) {} nil))) (is (= [{ :children [{:a "one"}{:b "two"}] }] ((parsexml "<root><a>one</a><b>two</b></root>" { :xpath "/root" :flatten false}) {} nil))) (is (= [{ :root "root-text" :children [{:a "one"}{:b "two"}] }] ((parsexml "<root>root-text<a>one</a><b>two</b></root>" { :xpath "/root" :flatten false}) {} nil)))) )) (deftest jsonpath-test (let [jsonpath (partial function-transform :jsonpath)] (testing "with nil" (is (nil? ((jsonpath nil) {} nil))) (is (nil? ((jsonpath :col1) {:col1 nil} nil)))) (testing "with unexpected types" (is (nil? ((jsonpath "0") {} nil))) (is (nil? ((jsonpath "1.0") {} nil)))) (is (nil? ((jsonpath "\"hello world\"") {} nil))) (is (nil? ((jsonpath "false") {} nil))) (is (nil? ((jsonpath "true") {} nil))) (testing "with list" (is (= [1 2 3] ((jsonpath [1 2 3] "$") {} nil))) (is (= [1 2 3] ((jsonpath [1 2 3] "$.") {} nil))) (is (= ["Joe" "Bob"] ((jsonpath [{:name "Joe"} {:name "Bob"}] "$.name") {} nil)))) (testing "with map" (is (= {} ((jsonpath {} "$") {} nil))) (is (= {} ((jsonpath {} "$.") {} nil))) (is (= [1 2 3] ((jsonpath {:messages [1 2 3]} "$.messages") {} nil))) (is (= [1 2 3] ((jsonpath {:messages [1 2 3]} "$.messages[*]") {} nil))) (is (= [1 2 3] ((jsonpath {:response {:messages [1 2 3]}} "$.response.messages[*]") {} nil))) (is (= [1 2 3 4] ((jsonpath {:in {:messages [1 2 ]} :out {:messages [3 4]}} "$..messages[*]") {} nil))))))
41338
(ns parsec.functions.parse-functions-test (:require [clojure.test :refer :all] [parsec.helpers :refer :all] [parsec.test-helpers :refer :all] [parsec.functions :refer :all] [parsec.functions.parsingfunctions :refer :all])) (deftest parsejson-test (let [parsejson (partial function-transform :parsejson)] (testing "with nil" (is (nil? ((parsejson nil) {} nil))) (is (nil? ((parsejson :col1) {:col1 nil} nil)))) (testing "with number" (is (= 0 ((parsejson "0") {} nil))) (is (= 1.0 ((parsejson "1.0") {} nil)))) (testing "with string" (is (= "hello world" ((parsejson "\"hello world\"") {} nil)))) (testing "with boolean" (is (false? ((parsejson "false") {} nil))) (is (true? ((parsejson "true") {} nil)))) (testing "with list" (is (= '() ((parsejson "[]") {} nil))) (is (= '(1 2) ((parsejson "[1, 2]") {} nil))) (is (sequential? ((parsejson "[1, 2]") {} nil)))) (testing "with map" (is (map? ((parsejson "{}") {} nil))) (is (= { :a 1 :b 2 } ((parsejson "{\"a\": 1, \"b\": 2}") {} nil))) (is (= { :a [1 2] :b { :c true } } ((parsejson "{\"a\": [1, 2], \"b\": { \"c\": true }}") {} nil)))))) (deftest parsecsv-test (let [parsecsv (partial function-transform :parsecsv)] (testing "with nil" (is (nil? ((parsecsv nil) {} nil))) (is (nil? ((parsecsv :col1) {:col1 nil} nil)))) (testing "with non-CSV data" (is (= [] ((parsecsv "0") {} nil))) (is (= [] ((parsecsv "\"hello world\"") {} nil))) (is (= [] ((parsecsv "false") {} nil))) (is (= [] ((parsecsv "true") {} nil))) (is (= [] ((parsecsv "[1, 2]") {} nil)))) (testing "with CSV string" (is (= [{:a "1" :b "2" :c "3"}] ((parsecsv "a,b,c\n1,2,3") {} nil))) (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "a,b,c\r\n1,2,3\r\n4,5,6") {} nil)))) (testing "with options" (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "a,b,c\t1,2,3\t4,5,6" { :eol "\t" }) {} nil))) (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "a\tb\tc\n1\t2\t3\n4\t5\t6" { :delimiter "\t" }) {} nil))) (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "`a`,`b`,`c`\n1,2,3\n4,5,6" { :quote "`" }) {} nil))) (is (= [{:a "hello world" :b "2" :c "3"} {:a "goodbye world" :b "5" :c "6"}] ((parsecsv "a-b-c\n`hello world`-2-3\n`goodbye world`-5-6" { :quote "`", :delimiter "-" }) {} nil)))) (testing "with headers" (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "a,b,c\n1,2,3\r\n4,5,6" { :headers true }) {} nil))) (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "1,2,3\r\n4,5,6" { :headers ["a","b","c"] }) {} nil))) (is (= [{:col0 "1" :col1 "2" :col2 "3"} {:col0 "4" :col1 "5" :col2 "6"}] ((parsecsv "1,2,3\r\n4,5,6" { :headers false }) {} nil))) ))) (deftest parsexml-test (let [parsexml (partial function-transform :parsexml)] (testing "with nil" (is (nil? ((parsexml nil) {} nil))) (is (nil? ((parsexml :col1) {:col1 nil} nil)))) (testing "with non-XML data" (is (thrown? Exception ((parsexml "0") {} nil))) (is (thrown? Exception ((parsexml "\"hello world\"") {} nil))) (is (thrown? Exception ((parsexml "false") {} nil))) (is (thrown? Exception ((parsexml "true") {} nil))) (is (thrown? Exception ((parsexml "[1, 2]") {} nil)))) (testing "with XML string" (is (= [{:root "one"}] ((parsexml "<root>one</root>") {} nil))) (is (= [{:root "one" :v "1"}] ((parsexml "<root v=\"1\">one</root>") {} nil))) (is (= [{:root "one" :v "1" :w "ok"}] ((parsexml "<root v=\"1\" w=\"ok\">one</root>") {} nil))) (is (= [{:a "one" :b "two"}] ((parsexml "<root><a>one</a><b>two</b></root>") {} nil))) (is (= [{:a "two"}] ((parsexml "<root><a>one</a><a>two</a></root>") {} nil)))) (testing "with raw mode" (is (= #clojure.data.xml.Element{ :tag :root :attrs {} :content ["one"] } ((parsexml "<root>one</root>" { :xpath "/root" :raw true }) {} nil)))) (testing "with xpath" (is (= [{:a "one"} {:a "two"}] ((parsexml "<root><a>one</a><a>two</a></root>" { :xpath "/root/a" }) {} nil))) (is (= [{:a "one"} {:a "two"}] ((parsexml "<root><subroot><a>one</a><a>two</a></subroot></root>" { :xpath "/root/subroot/a" }) {} nil))) (is (= [{:a "one"} {:a "two"}] ((parsexml "<root><subroot><a>one</a><a>two</a></subroot></root>" { :xpath "//a" }) {} nil))) (is (= [{:a "one"} {:b "two"}] ((parsexml "<root><subroot><a>one</a><b>two</b></subroot></root>" { :xpath "/root/subroot/a|/root/subroot/b" }) {} nil)))) (testing "with flatten" (is (= [{:a "one" :b "two"}] ((parsexml "<root><a>one</a><b>two</b></root>" { :xpath "/root" :flatten true}) {} nil))) (is (= [{ :children [{:a "one"}{:b "two"}] }] ((parsexml "<root><a>one</a><b>two</b></root>" { :xpath "/root" :flatten false}) {} nil))) (is (= [{ :root "root-text" :children [{:a "one"}{:b "two"}] }] ((parsexml "<root>root-text<a>one</a><b>two</b></root>" { :xpath "/root" :flatten false}) {} nil)))) )) (deftest jsonpath-test (let [jsonpath (partial function-transform :jsonpath)] (testing "with nil" (is (nil? ((jsonpath nil) {} nil))) (is (nil? ((jsonpath :col1) {:col1 nil} nil)))) (testing "with unexpected types" (is (nil? ((jsonpath "0") {} nil))) (is (nil? ((jsonpath "1.0") {} nil)))) (is (nil? ((jsonpath "\"hello world\"") {} nil))) (is (nil? ((jsonpath "false") {} nil))) (is (nil? ((jsonpath "true") {} nil))) (testing "with list" (is (= [1 2 3] ((jsonpath [1 2 3] "$") {} nil))) (is (= [1 2 3] ((jsonpath [1 2 3] "$.") {} nil))) (is (= ["<NAME>" "<NAME>"] ((jsonpath [{:name "<NAME>"} {:name "<NAME>"}] "$.name") {} nil)))) (testing "with map" (is (= {} ((jsonpath {} "$") {} nil))) (is (= {} ((jsonpath {} "$.") {} nil))) (is (= [1 2 3] ((jsonpath {:messages [1 2 3]} "$.messages") {} nil))) (is (= [1 2 3] ((jsonpath {:messages [1 2 3]} "$.messages[*]") {} nil))) (is (= [1 2 3] ((jsonpath {:response {:messages [1 2 3]}} "$.response.messages[*]") {} nil))) (is (= [1 2 3 4] ((jsonpath {:in {:messages [1 2 ]} :out {:messages [3 4]}} "$..messages[*]") {} nil))))))
true
(ns parsec.functions.parse-functions-test (:require [clojure.test :refer :all] [parsec.helpers :refer :all] [parsec.test-helpers :refer :all] [parsec.functions :refer :all] [parsec.functions.parsingfunctions :refer :all])) (deftest parsejson-test (let [parsejson (partial function-transform :parsejson)] (testing "with nil" (is (nil? ((parsejson nil) {} nil))) (is (nil? ((parsejson :col1) {:col1 nil} nil)))) (testing "with number" (is (= 0 ((parsejson "0") {} nil))) (is (= 1.0 ((parsejson "1.0") {} nil)))) (testing "with string" (is (= "hello world" ((parsejson "\"hello world\"") {} nil)))) (testing "with boolean" (is (false? ((parsejson "false") {} nil))) (is (true? ((parsejson "true") {} nil)))) (testing "with list" (is (= '() ((parsejson "[]") {} nil))) (is (= '(1 2) ((parsejson "[1, 2]") {} nil))) (is (sequential? ((parsejson "[1, 2]") {} nil)))) (testing "with map" (is (map? ((parsejson "{}") {} nil))) (is (= { :a 1 :b 2 } ((parsejson "{\"a\": 1, \"b\": 2}") {} nil))) (is (= { :a [1 2] :b { :c true } } ((parsejson "{\"a\": [1, 2], \"b\": { \"c\": true }}") {} nil)))))) (deftest parsecsv-test (let [parsecsv (partial function-transform :parsecsv)] (testing "with nil" (is (nil? ((parsecsv nil) {} nil))) (is (nil? ((parsecsv :col1) {:col1 nil} nil)))) (testing "with non-CSV data" (is (= [] ((parsecsv "0") {} nil))) (is (= [] ((parsecsv "\"hello world\"") {} nil))) (is (= [] ((parsecsv "false") {} nil))) (is (= [] ((parsecsv "true") {} nil))) (is (= [] ((parsecsv "[1, 2]") {} nil)))) (testing "with CSV string" (is (= [{:a "1" :b "2" :c "3"}] ((parsecsv "a,b,c\n1,2,3") {} nil))) (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "a,b,c\r\n1,2,3\r\n4,5,6") {} nil)))) (testing "with options" (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "a,b,c\t1,2,3\t4,5,6" { :eol "\t" }) {} nil))) (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "a\tb\tc\n1\t2\t3\n4\t5\t6" { :delimiter "\t" }) {} nil))) (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "`a`,`b`,`c`\n1,2,3\n4,5,6" { :quote "`" }) {} nil))) (is (= [{:a "hello world" :b "2" :c "3"} {:a "goodbye world" :b "5" :c "6"}] ((parsecsv "a-b-c\n`hello world`-2-3\n`goodbye world`-5-6" { :quote "`", :delimiter "-" }) {} nil)))) (testing "with headers" (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "a,b,c\n1,2,3\r\n4,5,6" { :headers true }) {} nil))) (is (= [{:a "1" :b "2" :c "3"} {:a "4" :b "5" :c "6"}] ((parsecsv "1,2,3\r\n4,5,6" { :headers ["a","b","c"] }) {} nil))) (is (= [{:col0 "1" :col1 "2" :col2 "3"} {:col0 "4" :col1 "5" :col2 "6"}] ((parsecsv "1,2,3\r\n4,5,6" { :headers false }) {} nil))) ))) (deftest parsexml-test (let [parsexml (partial function-transform :parsexml)] (testing "with nil" (is (nil? ((parsexml nil) {} nil))) (is (nil? ((parsexml :col1) {:col1 nil} nil)))) (testing "with non-XML data" (is (thrown? Exception ((parsexml "0") {} nil))) (is (thrown? Exception ((parsexml "\"hello world\"") {} nil))) (is (thrown? Exception ((parsexml "false") {} nil))) (is (thrown? Exception ((parsexml "true") {} nil))) (is (thrown? Exception ((parsexml "[1, 2]") {} nil)))) (testing "with XML string" (is (= [{:root "one"}] ((parsexml "<root>one</root>") {} nil))) (is (= [{:root "one" :v "1"}] ((parsexml "<root v=\"1\">one</root>") {} nil))) (is (= [{:root "one" :v "1" :w "ok"}] ((parsexml "<root v=\"1\" w=\"ok\">one</root>") {} nil))) (is (= [{:a "one" :b "two"}] ((parsexml "<root><a>one</a><b>two</b></root>") {} nil))) (is (= [{:a "two"}] ((parsexml "<root><a>one</a><a>two</a></root>") {} nil)))) (testing "with raw mode" (is (= #clojure.data.xml.Element{ :tag :root :attrs {} :content ["one"] } ((parsexml "<root>one</root>" { :xpath "/root" :raw true }) {} nil)))) (testing "with xpath" (is (= [{:a "one"} {:a "two"}] ((parsexml "<root><a>one</a><a>two</a></root>" { :xpath "/root/a" }) {} nil))) (is (= [{:a "one"} {:a "two"}] ((parsexml "<root><subroot><a>one</a><a>two</a></subroot></root>" { :xpath "/root/subroot/a" }) {} nil))) (is (= [{:a "one"} {:a "two"}] ((parsexml "<root><subroot><a>one</a><a>two</a></subroot></root>" { :xpath "//a" }) {} nil))) (is (= [{:a "one"} {:b "two"}] ((parsexml "<root><subroot><a>one</a><b>two</b></subroot></root>" { :xpath "/root/subroot/a|/root/subroot/b" }) {} nil)))) (testing "with flatten" (is (= [{:a "one" :b "two"}] ((parsexml "<root><a>one</a><b>two</b></root>" { :xpath "/root" :flatten true}) {} nil))) (is (= [{ :children [{:a "one"}{:b "two"}] }] ((parsexml "<root><a>one</a><b>two</b></root>" { :xpath "/root" :flatten false}) {} nil))) (is (= [{ :root "root-text" :children [{:a "one"}{:b "two"}] }] ((parsexml "<root>root-text<a>one</a><b>two</b></root>" { :xpath "/root" :flatten false}) {} nil)))) )) (deftest jsonpath-test (let [jsonpath (partial function-transform :jsonpath)] (testing "with nil" (is (nil? ((jsonpath nil) {} nil))) (is (nil? ((jsonpath :col1) {:col1 nil} nil)))) (testing "with unexpected types" (is (nil? ((jsonpath "0") {} nil))) (is (nil? ((jsonpath "1.0") {} nil)))) (is (nil? ((jsonpath "\"hello world\"") {} nil))) (is (nil? ((jsonpath "false") {} nil))) (is (nil? ((jsonpath "true") {} nil))) (testing "with list" (is (= [1 2 3] ((jsonpath [1 2 3] "$") {} nil))) (is (= [1 2 3] ((jsonpath [1 2 3] "$.") {} nil))) (is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] ((jsonpath [{:name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"}] "$.name") {} nil)))) (testing "with map" (is (= {} ((jsonpath {} "$") {} nil))) (is (= {} ((jsonpath {} "$.") {} nil))) (is (= [1 2 3] ((jsonpath {:messages [1 2 3]} "$.messages") {} nil))) (is (= [1 2 3] ((jsonpath {:messages [1 2 3]} "$.messages[*]") {} nil))) (is (= [1 2 3] ((jsonpath {:response {:messages [1 2 3]}} "$.response.messages[*]") {} nil))) (is (= [1 2 3 4] ((jsonpath {:in {:messages [1 2 ]} :out {:messages [3 4]}} "$..messages[*]") {} nil))))))
[ { "context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brow", "end": 25, "score": 0.9998502135276794, "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.9999338984489441, "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.9997920393943787, "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.9999330639839172, "start": 79, "tag": "EMAIL", "value": "cb@opscode.com" } ]
config/software/couchdb.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. ;; (let [ env {"RPATH" "/opt/opscode/embedded/lib" "CURL_CONFIG" "/opt/opscode/embedded/bin/curl-config" "ICU_CONFIG" "/opt/opscode/embedded/bin/icu-config" "ERL" "/opt/opscode/embedded/bin/erl" "ERLC" "/opt/opscode/embedded/bin/erlc" "LD_RUN_PATH" "/opt/opscode/embedded/lib" "CFLAGS" "-L/opt/opscode/embedded/lib -I/opt/opscode/embedded/include" "PATH" (apply str (interpose ":" ["/opt/opscode/embedded/bin" (System/getenv "PATH")]))} ] (software "couchdb" :source "apache-couchdb-1.0.1" :steps [ {:env env :command "./bootstrap"} {:env env :command "./configure" :args ["--prefix=/opt/opscode/embedded" "--disable-init" "--disable-launchd" "--with-erlang=/opt/opscode/embedded/lib/erlang/usr/include" "--with-js-include=/opt/opscode/embedded/include" "--with-js-lib=/opt/opscode/embedded/lib" ]} {:env env :command "make"} {:env env :command "make" :args ["install"]} ]))
1361
;; ;; 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. ;; (let [ env {"RPATH" "/opt/opscode/embedded/lib" "CURL_CONFIG" "/opt/opscode/embedded/bin/curl-config" "ICU_CONFIG" "/opt/opscode/embedded/bin/icu-config" "ERL" "/opt/opscode/embedded/bin/erl" "ERLC" "/opt/opscode/embedded/bin/erlc" "LD_RUN_PATH" "/opt/opscode/embedded/lib" "CFLAGS" "-L/opt/opscode/embedded/lib -I/opt/opscode/embedded/include" "PATH" (apply str (interpose ":" ["/opt/opscode/embedded/bin" (System/getenv "PATH")]))} ] (software "couchdb" :source "apache-couchdb-1.0.1" :steps [ {:env env :command "./bootstrap"} {:env env :command "./configure" :args ["--prefix=/opt/opscode/embedded" "--disable-init" "--disable-launchd" "--with-erlang=/opt/opscode/embedded/lib/erlang/usr/include" "--with-js-include=/opt/opscode/embedded/include" "--with-js-lib=/opt/opscode/embedded/lib" ]} {:env env :command "make"} {:env env :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. ;; (let [ env {"RPATH" "/opt/opscode/embedded/lib" "CURL_CONFIG" "/opt/opscode/embedded/bin/curl-config" "ICU_CONFIG" "/opt/opscode/embedded/bin/icu-config" "ERL" "/opt/opscode/embedded/bin/erl" "ERLC" "/opt/opscode/embedded/bin/erlc" "LD_RUN_PATH" "/opt/opscode/embedded/lib" "CFLAGS" "-L/opt/opscode/embedded/lib -I/opt/opscode/embedded/include" "PATH" (apply str (interpose ":" ["/opt/opscode/embedded/bin" (System/getenv "PATH")]))} ] (software "couchdb" :source "apache-couchdb-1.0.1" :steps [ {:env env :command "./bootstrap"} {:env env :command "./configure" :args ["--prefix=/opt/opscode/embedded" "--disable-init" "--disable-launchd" "--with-erlang=/opt/opscode/embedded/lib/erlang/usr/include" "--with-js-include=/opt/opscode/embedded/include" "--with-js-lib=/opt/opscode/embedded/lib" ]} {:env env :command "make"} {:env env :command "make" :args ["install"]} ]))
[ { "context": " Lisp Problems\n; Based on a Prolog problem list by werner.hett@hti.bfh.ch\n; Working with lists\n\n; P01 (*) Find the last box", "end": 142, "score": 0.9999252557754517, "start": 120, "tag": "EMAIL", "value": "werner.hett@hti.bfh.ch" }, { "context": " list.\n\n; Example:\n; * (group3 '(aldo beat carla david evi flip gary hugo ida))\n; ( ( (ALDO BE", "end": 8190, "score": 0.9252439737319946, "start": 8185, "tag": "NAME", "value": "carla" }, { "context": "; Example:\n; * (group3 '(aldo beat carla david evi flip gary hugo ida))\n; ( ( (ALDO BEAT) (C", "end": 8196, "score": 0.7757138013839722, "start": 8192, "tag": "NAME", "value": "avid" }, { "context": "t carla david evi flip gary hugo ida))\n; ( ( (ALDO BEAT) (CARLA DAVID EVI) (FLIP GARY HUGO IDA) )\n; ", "end": 8237, "score": 0.5853555798530579, "start": 8233, "tag": "NAME", "value": "ALDO" }, { "context": "d evi flip gary hugo ida))\n; ( ( (ALDO BEAT) (CARLA DAVID EVI) (FLIP GARY HUGO IDA) )\n; ... )\n\n; b)", "end": 8256, "score": 0.9985215067863464, "start": 8245, "tag": "NAME", "value": "CARLA DAVID" }, { "context": "ry hugo ida))\n; ( ( (ALDO BEAT) (CARLA DAVID EVI) (FLIP GARY HUGO IDA) )\n; ... )\n\n; b) Gen", "end": 8260, "score": 0.5350772738456726, "start": 8258, "tag": "NAME", "value": "VI" }, { "context": "))\n; ( ( (ALDO BEAT) (CARLA DAVID EVI) (FLIP GARY HUGO IDA) )\n; ... )\n\n; b) Generalize the ", "end": 8272, "score": 0.871588408946991, "start": 8269, "tag": "NAME", "value": "ARY" }, { "context": " ( ( (ALDO BEAT) (CARLA DAVID EVI) (FLIP GARY HUGO IDA) )\n; ... )\n\n; b) Generalize the above", "end": 8277, "score": 0.8482741713523865, "start": 8274, "tag": "NAME", "value": "UGO" }, { "context": "groups.\n\n; Example:\n; * (group '(aldo beat carla david evi flip gary hugo ida) '(2 2 5))\n; ( (", "end": 8485, "score": 0.8124378323554993, "start": 8480, "tag": "NAME", "value": "carla" }, { "context": " Example:\n; * (group '(aldo beat carla david evi flip gary hugo ida) '(2 2 5))\n; ( ( (ALDO BEAT) (CARLA DAVID", "end": 8510, "score": 0.9431573152542114, "start": 8492, "tag": "NAME", "value": "evi flip gary hugo" }, { "context": "avid evi flip gary hugo ida) '(2 2 5))\n; ( ( (ALDO BEAT) (CARLA DAVID) (EVI FLIP GARY HUGO IDA) )\n; .", "end": 8546, "score": 0.968149721622467, "start": 8537, "tag": "NAME", "value": "ALDO BEAT" }, { "context": "p gary hugo ida) '(2 2 5))\n; ( ( (ALDO BEAT) (CARLA DAVID) (EVI FLIP GARY HUGO IDA) )\n; ... )\n\n; No", "end": 8560, "score": 0.9996258020401001, "start": 8549, "tag": "NAME", "value": "CARLA DAVID" }, { "context": "a) '(2 2 5))\n; ( ( (ALDO BEAT) (CARLA DAVID) (EVI FLIP GARY HUGO IDA) )\n; ... )\n\n; Note that we do not wan", "end": 8581, "score": 0.971261203289032, "start": 8563, "tag": "NAME", "value": "EVI FLIP GARY HUGO" }, { "context": "( (ALDO BEAT) (CARLA DAVID) (EVI FLIP GARY HUGO IDA) )\n; ... )\n\n; Note that we do not want pe", "end": 8585, "score": 0.6561874151229858, "start": 8584, "tag": "NAME", "value": "A" }, { "context": "wever, we make a difference between ((ALDO BEAT) (CARLA DAVID) ...) and ((CARLA DAVID) (ALDO BEAT) ...).\n", "end": 8791, "score": 0.9106100797653198, "start": 8786, "tag": "NAME", "value": "CARLA" }, { "context": " make a difference between ((ALDO BEAT) (CARLA DAVID) ...) and ((CARLA DAVID) (ALDO BEAT) ...).\n\n; ", "end": 8797, "score": 0.732607364654541, "start": 8795, "tag": "NAME", "value": "ID" }, { "context": "nce between ((ALDO BEAT) (CARLA DAVID) ...) and ((CARLA DAVID) (ALDO BEAT) ...).\n\n; You may find more about", "end": 8821, "score": 0.9280363321304321, "start": 8810, "tag": "NAME", "value": "CARLA DAVID" }, { "context": "knight positions (the knight's tour).\n\n; P92 (***) Von Koch's conjecture\n; Several years ago I met a", "end": 40789, "score": 0.7454948425292969, "start": 40786, "tag": "NAME", "value": "Von" }, { "context": " for which he didn't know a solution. His name was Von Koch, and I don't know whether the problem has been so", "end": 40943, "score": 0.9998124837875366, "start": 40935, "tag": "NAME", "value": "Von Koch" } ]
Clojure/99problems.clj
twolodzko/Learning
0
(ns ninety-nine-problems (:use clojure.test)) ; L-99: Ninety-Nine Lisp Problems ; Based on a Prolog problem list by werner.hett@hti.bfh.ch ; Working with lists ; P01 (*) Find the last box of a list. ; Example: ; * (my-last '(a b c d)) ; (D) (defn my-last [lst] (let [tail (next lst)] (if (nil? tail) lst (my-last tail)))) (deftest P01 (is (= (my-last '()) '())) (is (= (my-last '(1)) '(1))) (is (= (my-last '(1 2 3 4)) '(4)))) ; P02 (*) Find the last but one box of a list. ; Example: ; * (my-but-last '(a b c d)) ; (C D) (defn my-but-last [lst] (let [tail (next lst)] (if (nil? (next tail)) lst (my-but-last tail)))) (deftest P02 (is (= (my-but-last '()) '())) (is (= (my-but-last '(1)) '(1))) (is (= (my-but-last '(1 2)) '(1 2))) (is (= (my-but-last '(1 2 3)) '(2 3))) (is (= (my-but-last '(1 2 3 4)) '(3 4)))) ; P03 (*) Find the K'th element of a list. ; The first element in the list is number 1. ; Example: ; * (element-at '(a b c d e) 3) ; C (defn element-at [lst pos] (if (= pos 1) (first lst) (element-at (next lst) (- pos 1)))) (deftest P03 (is (= (element-at '() 1) nil)) (is (= (element-at '(1) 1) 1)) (is (= (element-at '(1 2) 1) 1)) (is (= (element-at '(1 2) 2) 2)) (is (= (element-at '(1 2) 3) nil)) (is (= (element-at '(1 2 3 4) 3) 3))) ; P04 (*) Find the number of elements of a list. (defn len [lst] ((fn [lst counter] (if (empty? lst) counter (recur (next lst) (+ counter 1)))) lst 0)) (deftest P04 (is (= (len '()) 0)) (is (= (len '(2)) 1)) (is (= (len '(1 2 3 4)) 4))) ; P05 (*) Reverse a list. (defn rev [lst] ((fn [inp out] (if (empty? inp) out (recur (next inp) (conj out (first inp))))) lst '())) (deftest P05 (is (= (rev '()) '())) (is (= (rev '(1)) '(1))) (is (= (rev '(1 2 3)) '(3 2 1)))) ; P06 (*) Find out whether a list is a palindrome. ; A palindrome can be read forward or backward; e.g. (x a m a x). (defn is-palindrome [lst] ((fn [fwd bwd] (if (empty? fwd) true (if (not= (first fwd) (first bwd)) false (recur (next fwd) (next bwd))))) lst (rev lst))) (deftest P06 (is (true? (is-palindrome '()))) (is (true? (is-palindrome '(1)))) (is (false? (is-palindrome '(1 2 3)))) (is (true? (is-palindrome '(2 3 1 3 2))))) ; P07 (**) Flatten a nested list structure. ; Transform a list, possibly holding lists as elements into a `flat' list by replacing each list with its elements (recursively). ; Example: ; * (my-flatten '(a (b (c d) e))) ; (A B C D E) ; Hint: Use the predefined functions list and append. (declare collect-flatten my-flatten) (defn collect-flatten [inp out] (if (empty? inp) (reverse out) (recur (next inp) (if (list? (first inp)) (concat (my-flatten (first inp)) out) (conj out (first inp)))))) (defn my-flatten [lst] (collect-flatten lst '())) (deftest P07 (is (= (my-flatten '()) '())) (is (= (my-flatten '(1)) '(1))) (is (= (my-flatten '(1 '(2 3))) '(1 2 3))) (is (= (my-flatten '(1 '(2 '(3 4) 5))) '(1 2 3 4 5)))) ; P08 (**) Eliminate consecutive duplicates of list elements. ; If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed. ; Example: ; * (compress '(a a a a b c c a a d e e e e)) ; (A B C A D E) ; P09 (**) Pack consecutive duplicates of list elements into sublists. ; If a list contains repeated elements they should be placed in separate sublists. ; Example: ; * (pack '(a a a a b c c a a d e e e e)) ; ((A A A A) (B) (C C) (A A) (D) (E E E E)) ; P10 (*) Run-length encoding of a list. ; Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as lists (N E) where N is the number of duplicates of the element E. ; Example: ; * (encode '(a a a a b c c a a d e e e e)) ; ((4 A) (1 B) (2 C) (2 A) (1 D)(4 E)) ; P11 (*) Modified run-length encoding. ; Modify the result of problem P10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as (N E) lists. ; Example: ; * (encode-modified '(a a a a b c c a a d e e e e)) ; ((4 A) B (2 C) (2 A) D (4 E)) ; P12 (**) Decode a run-length encoded list. ; Given a run-length code list generated as specified in problem P11. Construct its uncompressed version. ; P13 (**) Run-length encoding of a list (direct solution). ; Implement the so-called run-length encoding data compression method directly. I.e. don't explicitly create the sublists containing the duplicates, as in problem P09, but only count them. As in problem P11, simplify the result list by replacing the singleton lists (1 X) by X. ; Example: ; * (encode-direct '(a a a a b c c a a d e e e e)) ; ((4 A) B (2 C) (2 A) D (4 E)) ; P14 (*) Duplicate the elements of a list. ; Example: ; * (dupli '(a b c c d)) ; (A A B B C C C C D D) ; P15 (**) Replicate the elements of a list a given number of times. ; Example: ; * (repli '(a b c) 3) ; (A A A B B B C C C) ; P16 (**) Drop every N'th element from a list. ; Example: ; * (drop '(a b c d e f g h i k) 3) ; (A B D E G H K) ; P17 (*) Split a list into two parts; the length of the first part is given. ; Do not use any predefined predicates. ; Example: ; * (split '(a b c d e f g h i k) 3) ; ( (A B C) (D E F G H I K)) ; P18 (**) Extract a slice from a list. ; Given two indices, I and K, the slice is the list containing the elements between the I'th and K'th element of the original list (both limits included). Start counting the elements with 1. ; Example: ; * (slice '(a b c d e f g h i k) 3 7) ; (C D E F G) ; P19 (**) Rotate a list N places to the left. ; Examples: ; * (rotate '(a b c d e f g h) 3) ; (D E F G H A B C) ; * (rotate '(a b c d e f g h) -2) ; (G H A B C D E F) ; Hint: Use the predefined functions length and append, as well as the result of problem P17. ; P20 (*) Remove the K'th element from a list. ; Example: ; * (remove-at '(a b c d) 2) ; (A C D) ; P21 (*) Insert an element at a given position into a list. ; Example: ; * (insert-at 'alfa '(a b c d) 2) ; (A ALFA B C D) ; P22 (*) Create a list containing all integers within a given range. ; If first argument is smaller than second, produce a list in decreasing order. ; Example: ; * (range 4 9) ; (4 5 6 7 8 9) ; P23 (**) Extract a given number of randomly selected elements from a list. ; The selected items shall be returned in a list. ; Example: ; * (rnd-select '(a b c d e f g h) 3) ; (E D A) ; Hint: Use the built-in random number generator and the result of problem P20. ; P24 (*) Lotto: Draw N different random numbers from the set 1..M. ; The selected numbers shall be returned in a list. ; Example: ; * (lotto-select 6 49) ; (23 1 17 33 21 37) ; Hint: Combine the solutions of problems P22 and P23. ; P25 (*) Generate a random permutation of the elements of a list. ; Example: ; * (rnd-permu '(a b c d e f)) ; (B A D C E F) ; Hint: Use the solution of problem P23. ; P26 (**) Generate the combinations of K distinct objects chosen from the N elements of a list ; In how many ways can a committee of 3 be chosen from a group of 12 people? We all know that there are C(12,3) = 220 possibilities (C(N,K) denotes the well-known binomial coefficients). For pure mathematicians, this result may be great. But we want to really generate all the possibilities in a list. ; Example: ; * (combination 3 '(a b c d e f)) ; ((A B C) (A B D) (A B E) ... ) ; P27 (**) Group the elements of a set into disjoint subsets. ; a) In how many ways can a group of 9 people work in 3 disjoint subgroups of 2, 3 and 4 persons? Write a function that generates all the possibilities and returns them in a list. ; Example: ; * (group3 '(aldo beat carla david evi flip gary hugo ida)) ; ( ( (ALDO BEAT) (CARLA DAVID EVI) (FLIP GARY HUGO IDA) ) ; ... ) ; b) Generalize the above predicate in a way that we can specify a list of group sizes and the predicate will return a list of groups. ; Example: ; * (group '(aldo beat carla david evi flip gary hugo ida) '(2 2 5)) ; ( ( (ALDO BEAT) (CARLA DAVID) (EVI FLIP GARY HUGO IDA) ) ; ... ) ; Note that we do not want permutations of the group members; i.e. ((ALDO BEAT) ...) is the same solution as ((BEAT ALDO) ...). However, we make a difference between ((ALDO BEAT) (CARLA DAVID) ...) and ((CARLA DAVID) (ALDO BEAT) ...). ; You may find more about this combinatorial problem in a good book on discrete mathematics under the term "multinomial coefficients". ; P28 (**) Sorting a list of lists according to length of sublists ; a) We suppose that a list contains elements that are lists themselves. The objective is to sort the elements of this list according to their length. E.g. short lists first, longer lists later, or vice versa. ; Example: ; * (lsort '((a b c) (d e) (f g h) (d e) (i j k l) (m n) (o))) ; ((O) (D E) (D E) (M N) (A B C) (F G H) (I J K L)) ; b) Again, we suppose that a list contains elements that are lists themselves. But this time the objective is to sort the elements of this list according to their length frequency; i.e., in the default, where sorting is done ascendingly, lists with rare lengths are placed first, others with a more frequent length come later. ; Example: ; * (lfsort '((a b c) (d e) (f g h) (d e) (i j k l) (m n) (o))) ; ((i j k l) (o) (a b c) (f g h) (d e) (d e) (m n)) ; Note that in the above example, the first two lists in the result have length 4 and 1, both lengths appear just once. The third and forth list have length 3 which appears twice (there are two list of this length). And finally, the last three lists have length 2. This is the most frequent length. ; Arithmetic ; P31 (**) Determine whether a given integer number is prime. ; Example: ; * (is-prime 7) ; T ; P32 (**) Determine the greatest common divisor of two positive integer numbers. ; Use Euclid's algorithm. ; Example: ; * (gcd 36 63) ; 9 ; P33 (*) Determine whether two positive integer numbers are coprime. ; Two numbers are coprime if their greatest common divisor equals 1. ; Example: ; * (coprime 35 64) ; T ; P34 (**) Calculate Euler's totient function phi(m). ; Euler's so-called totient function phi(m) is defined as the number of positive integers r (1 <= r < m) that are coprime to m. ; Example: m = 10: r = 1,3,7,9; thus phi(m) = 4. Note the special case: phi(1) = 1. ; * (totient-phi 10) ; 4 ; Find out what the value of phi(m) is if m is a prime number. Euler's totient function plays an important role in one of the most widely used public key cryptography methods (RSA). In this exercise you should use the most primitive method to calculate this function (there are smarter ways that we shall discuss later). ; P35 (**) Determine the prime factors of a given positive integer. ; Construct a flat list containing the prime factors in ascending order. ; Example: ; * (prime-factors 315) ; (3 3 5 7) ; P36 (**) Determine the prime factors of a given positive integer (2). ; Construct a list containing the prime factors and their multiplicity. ; Example: ; * (prime-factors-mult 315) ; ((3 2) (5 1) (7 1)) ; Hint: The problem is similar to problem P13. ; P37 (**) Calculate Euler's totient function phi(m) (improved). ; See problem P34 for the definition of Euler's totient function. If the list of the prime factors of a number m is known in the form of problem P36 then the function phi(m) can be efficiently calculated as follows: Let ((p1 m1) (p2 m2) (p3 m3) ...) be the list of prime factors (and their multiplicities) of a given number m. Then phi(m) can be calculated with the following formula: ; phi(m) = (p1 - 1) * p1 ** (m1 - 1) + (p2 - 1) * p2 ** (m2 - 1) + (p3 - 1) * p3 ** (m3 - 1) + ... ; Note that a ** b stands for the b'th power of a. ; P38 (*) Compare the two methods of calculating Euler's totient function. ; Use the solutions of problems P34 and P37 to compare the algorithms. Take the number of logical inferences as a measure for efficiency. Try to calculate phi(10090) as an example. ; P39 (*) A list of prime numbers. ; Given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range. ; P40 (**) Goldbach's conjecture. ; Goldbach's conjecture says that every positive even number greater than 2 is the sum of two prime numbers. Example: 28 = 5 + 23. It is one of the most famous facts in number theory that has not been proved to be correct in the general case. It has been numerically confirmed up to very large numbers (much larger than we can go with our Prolog system). Write a predicate to find the two prime numbers that sum up to a given even integer. ; Example: ; * (goldbach 28) ; (5 23) ; P41 (**) A list of Goldbach compositions. ; Given a range of integers by its lower and upper limit, print a list of all even numbers and their Goldbach composition. ; Example: ; * (goldbach-list 9 20) ; 10 = 3 + 7 ; 12 = 5 + 7 ; 14 = 3 + 11 ; 16 = 3 + 13 ; 18 = 5 + 13 ; 20 = 3 + 17 ; In most cases, if an even number is written as the sum of two prime numbers, one of them is very small. Very rarely, the primes are both bigger than say 50. Try to find out how many such cases there are in the range 2..3000. ; Example (for a print limit of 50): ; * (goldbach-list 1 2000 50) ; 992 = 73 + 919 ; 1382 = 61 + 1321 ; 1856 = 67 + 1789 ; 1928 = 61 + 1867 ; Logic and Codes ; P46 (**) Truth tables for logical expressions. ; Define predicates and/2, or/2, nand/2, nor/2, xor/2, impl/2 and equ/2 (for logical equivalence) which succeed or fail according to the result of their respective operations; e.g. and(A,B) will succeed, if and only if both A and B succeed. Note that A and B can be Prolog goals (not only the constants true and fail). ; A logical expression in two variables can then be written in prefix notation, as in the following example: and(or(A,B),nand(A,B)). ; Now, write a predicate table/3 which prints the truth table of a given logical expression in two variables. ; Example: ; * table(A,B,and(A,or(A,B))). ; true true true ; true fail true ; fail true fail ; fail fail fail ; P47 (*) Truth tables for logical expressions (2). ; Continue problem P46 by defining and/2, or/2, etc as being operators. This allows to write the logical expression in the more natural way, as in the example: A and (A or not B). Define operator precedence as usual; i.e. as in Java. ; Example: ; * table(A,B, A and (A or not B)). ; true true true ; true fail true ; fail true fail ; fail fail fail ; P48 (**) Truth tables for logical expressions (3). ; Generalize problem P47 in such a way that the logical expression may contain any number of logical variables. Define table/2 in a way that table(List,Expr) prints the truth table for the expression Expr, which contains the logical variables enumerated in List. ; Example: ; * table([A,B,C], A and (B or C) equ A and B or A and C). ; true true true true ; true true fail true ; true fail true true ; true fail fail true ; fail true true true ; fail true fail true ; fail fail true true ; fail fail fail true ; P49 (**) Gray code. ; An n-bit Gray code is a sequence of n-bit strings constructed according to certain rules. For example, ; n = 1: C(1) = ['0','1']. ; n = 2: C(2) = ['00','01','11','10']. ; n = 3: C(3) = ['000','001','011','010',´110´,´111´,´101´,´100´]. ; Find out the construction rules and write a predicate with the following specification: ; % gray(N,C) :- C is the N-bit Gray code ; Can you apply the method of "result caching" in order to make the predicate more efficient, when it is to be used repeatedly? ; P50 (***) Huffman code. ; First of all, consult a good book on discrete mathematics or algorithms for a detailed description of Huffman codes! ; We suppose a set of symbols with their frequencies, given as a list of fr(S,F) terms. Example: [fr(a,45),fr(b,13),fr(c,12),fr(d,16),fr(e,9),fr(f,5)]. Our objective is to construct a list hc(S,C) terms, where C is the Huffman code word for the symbol S. In our example, the result could be Hs = [hc(a,'0'), hc(b,'101'), hc(c,'100'), hc(d,'111'), hc(e,'1101'), hc(f,'1100')] [hc(a,'01'),...etc.]. The task shall be performed by the predicate huffman/2 defined as follows: ; % huffman(Fs,Hs) :- Hs is the Huffman code table for the frequency table Fs ; Binary Trees ; A binary tree is either empty or it is composed of a root element and two successors, which are binary trees themselves. ; In Lisp we represent the empty tree by 'nil' and the non-empty tree by the list (X L R), where X denotes the root node and L and R denote the left and right subtree, respectively. The example tree depicted opposite is therefore represented by the following list: ; (a (b (d nil nil) (e nil nil)) (c nil (f (g nil nil) nil))) ; Other examples are a binary tree that consists of a root node only: ; (a nil nil) or an empty binary tree: nil. ; You can check your predicates using these example trees. They are given as test cases in p54.lisp. ; P54A (*) Check whether a given term represents a binary tree ; Write a predicate istree which returns true if and only if its argument is a list representing a binary tree. ; Example: ; * (istree (a (b nil nil) nil)) ; T ; * (istree (a (b nil nil))) ; NIL ; P55 (**) Construct completely balanced binary trees ; In a completely balanced binary tree, the following property holds for every node: The number of nodes in its left subtree and the number of nodes in its right subtree are almost equal, which means their difference is not greater than one. ; Write a function cbal-tree to construct completely balanced binary trees for a given number of nodes. The predicate should generate all solutions via backtracking. Put the letter 'x' as information into all nodes of the tree. ; Example: ; * cbal-tree(4,T). ; T = t(x, t(x, nil, nil), t(x, nil, t(x, nil, nil))) ; ; T = t(x, t(x, nil, nil), t(x, t(x, nil, nil), nil)) ; ; etc......No ; P56 (**) Symmetric binary trees ; Let us call a binary tree symmetric if you can draw a vertical line through the root node and then the right subtree is the mirror image of the left subtree. Write a predicate symmetric/1 to check whether a given binary tree is symmetric. Hint: Write a predicate mirror/2 first to check whether one tree is the mirror image of another. We are only interested in the structure, not in the contents of the nodes. ; P57 (**) Binary search trees (dictionaries) ; Use the predicate add/3, developed in chapter 4 of the course, to write a predicate to construct a binary search tree from a list of integer numbers. ; Example: ; * construct([3,2,5,7,1],T). ; T = t(3, t(2, t(1, nil, nil), nil), t(5, nil, t(7, nil, nil))) ; Then use this predicate to test the solution of the problem P56. ; Example: ; * test-symmetric([5,3,18,1,4,12,21]). ; Yes ; * test-symmetric([3,2,5,7,1]). ; No ; P58 (**) Generate-and-test paradigm ; Apply the generate-and-test paradigm to construct all symmetric, completely balanced binary trees with a given number of nodes. Example: ; * sym-cbal-trees(5,Ts). ; Ts = [t(x, t(x, nil, t(x, nil, nil)), t(x, t(x, nil, nil), nil)), t(x, t(x, t(x, nil, nil), nil), t(x, nil, t(x, nil, nil)))] ; How many such trees are there with 57 nodes? Investigate about how many solutions there are for a given number of nodes? What if the number is even? Write an appropriate predicate. ; P59 (**) Construct height-balanced binary trees ; In a height-balanced binary tree, the following property holds for every node: The height of its left subtree and the height of its right subtree are almost equal, which means their difference is not greater than one. ; Write a predicate hbal-tree/2 to construct height-balanced binary trees for a given height. The predicate should generate all solutions via backtracking. Put the letter 'x' as information into all nodes of the tree. ; Example: ; * hbal-tree(3,T). ; T = t(x, t(x, t(x, nil, nil), t(x, nil, nil)), t(x, t(x, nil, nil), t(x, nil, nil))) ; ; T = t(x, t(x, t(x, nil, nil), t(x, nil, nil)), t(x, t(x, nil, nil), nil)) ; ; etc......No ; P60 (**) Construct height-balanced binary trees with a given number of nodes ; Consider a height-balanced binary tree of height H. What is the maximum number of nodes it can contain? ; Clearly, MaxN = 2**H - 1. However, what is the minimum number MinN? This question is more difficult. Try to find a recursive statement and turn it into a predicate minNodes/2 defined as follwos: ; % minNodes(H,N) :- N is the minimum number of nodes in a height-balanced binary tree of height H. ; (integer,integer), (+,?) ; On the other hand, we might ask: what is the maximum height H a height-balanced binary tree with N nodes can have? ; % maxHeight(N,H) :- H is the maximum height of a height-balanced binary tree with N nodes ; (integer,integer), (+,?) ; Now, we can attack the main problem: construct all the height-balanced binary trees with a given nuber of nodes. ; % hbal-tree-nodes(N,T) :- T is a height-balanced binary tree with N nodes. ; Find out how many height-balanced trees exist for N = 15. ; P61 (*) Count the leaves of a binary tree ; A leaf is a node with no successors. Write a predicate count-leaves/2 to count them. ; % count-leaves(T,N) :- the binary tree T has N leaves ; P61A (*) Collect the leaves of a binary tree in a list ; A leaf is a node with no successors. Write a predicate leaves/2 to collect them in a list. ; % leaves(T,S) :- S is the list of all leaves of the binary tree T ; P62 (*) Collect the internal nodes of a binary tree in a list ; An internal node of a binary tree has either one or two non-empty successors. Write a predicate internals/2 to collect them in a list. ; % internals(T,S) :- S is the list of internal nodes of the binary tree T. ; P62B (*) Collect the nodes at a given level in a list ; A node of a binary tree is at level N if the path from the root to the node has length N-1. The root node is at level 1. Write a predicate atlevel/3 to collect all nodes at a given level in a list. ; % atlevel(T,L,S) :- S is the list of nodes of the binary tree T at level L ; Using atlevel/3 it is easy to construct a predicate levelorder/2 which creates the level-order sequence of the nodes. However, there are more efficient ways to do that. ; P63 (**) Construct a complete binary tree ; A complete binary tree with height H is defined as follows: The levels 1,2,3,...,H-1 contain the maximum number of nodes (i.e 2**(i-1) at the level i, note that we start counting the levels from 1 at the root). In level H, which may contain less than the maximum possible number of nodes, all the nodes are "left-adjusted". This means that in a levelorder tree traversal all internal nodes come first, the leaves come second, and empty successors (the nil's which are not really nodes!) come last. ; Particularly, complete binary trees are used as data structures (or addressing schemes) for heaps. ; We can assign an address number to each node in a complete binary tree by enumerating the nodes in levelorder, starting at the root with number 1. In doing so, we realize that for every node X with address A the following property holds: The address of X's left and right successors are 2*A and 2*A+1, respectively, supposed the successors do exist. This fact can be used to elegantly construct a complete binary tree structure. Write a predicate complete-binary-tree/2 with the following specification: ; % complete-binary-tree(N,T) :- T is a complete binary tree with N nodes. (+,?) ; Test your predicate in an appropriate way. ; P64 (**) Layout a binary tree (1) ; Given a binary tree as the usual Prolog term t(X,L,R) (or nil). As a preparation for drawing the tree, a layout algorithm is required to determine the position of each node in a rectangular grid. Several layout methods are conceivable, one of them is shown in the illustration below. ; In this layout strategy, the position of a node v is obtained by the following two rules: ; x(v) is equal to the position of the node v in the inorder sequence ; y(v) is equal to the depth of the node v in the tree ; In order to store the position of the nodes, we extend the Prolog term representing a node (and its successors) as follows: ; % nil represents the empty tree (as usual) ; % t(W,X,Y,L,R) represents a (non-empty) binary tree with root W "positioned" at (X,Y), and subtrees L and R ; Write a predicate layout-binary-tree/2 with the following specification: ; % layout-binary-tree(T,PT) :- PT is the "positioned" binary tree obtained from the binary tree T. (+,?) ; Test your predicate in an appropriate way. ; P65 (**) Layout a binary tree (2) ; An alternative layout method is depicted in the illustration opposite. Find out the rules and write the corresponding Prolog predicate. Hint: On a given level, the horizontal distance between neighboring nodes is constant. ; Use the same conventions as in problem P64 and test your predicate in an appropriate way. ; P66 (***) Layout a binary tree (3) ; Yet another layout strategy is shown in the illustration opposite. The method yields a very compact layout while maintaining a certain symmetry in every node. Find out the rules and write the corresponding Prolog predicate. Hint: Consider the horizontal distance between a node and its successor nodes. How tight can you pack together two subtrees to construct the combined binary tree? ; Use the same conventions as in problem P64 and P65 and test your predicate in an appropriate way. Note: This is a difficult problem. Don't give up too early! ; Which layout do you like most? ; P67 (**) A string representation of binary trees ; Somebody represents binary trees as strings of the following type (see example opposite): ; a(b(d,e),c(,f(g,))) ; a) Write a Prolog predicate which generates this string representation, if the tree is given as usual (as nil or t(X,L,R) term). Then write a predicate which does this inverse; i.e. given the string representation, construct the tree in the usual form. Finally, combine the two predicates in a single predicate tree-string/2 which can be used in both directions. ; b) Write the same predicate tree-string/2 using difference lists and a single predicate tree-dlist/2 which does the conversion between a tree and a difference list in both directions. ; For simplicity, suppose the information in the nodes is a single letter and there are no spaces in the string. ; P68 (**) Preorder and inorder sequences of binary trees ; We consider binary trees with nodes that are identified by single lower-case letters, as in the example of problem P67. ; a) Write predicates preorder/2 and inorder/2 that construct the preorder and inorder sequence of a given binary tree, respectively. The results should be atoms, e.g. 'abdecfg' for the preorder sequence of the example in problem P67. ; b) Can you use preorder/2 from problem part a) in the reverse direction; i.e. given a preorder sequence, construct a corresponding tree? If not, make the necessary arrangements. ; c) If both the preorder sequence and the inorder sequence of the nodes of a binary tree are given, then the tree is determined unambiguously. Write a predicate pre-in-tree/3 that does the job. ; d) Solve problems a) to c) using difference lists. Cool! Use the predefined predicate time/1 to compare the solutions. ; What happens if the same character appears in more than one node. Try for instance pre-in-tree(aba,baa,T). ; P69 (**) Dotstring representation of binary trees ; We consider again binary trees with nodes that are identified by single lower-case letters, as in the example of problem P67. Such a tree can be represented by the preorder sequence of its nodes in which dots (.) are inserted where an empty subtree (nil) is encountered during the tree traversal. For example, the tree shown in problem P67 is represented as 'abd..e..c.fg...'. First, try to establish a syntax (BNF or syntax diagrams) and then write a predicate tree-dotstring/2 which does the conversion in both directions. Use difference lists. ; Multiway Trees ; A multiway tree is composed of a root element and a (possibly empty) set of successors which are multiway trees themselves. A multiway tree is never empty. The set of successor trees is sometimes called a forest. ; In Prolog we represent a multiway tree by a term t(X,F), where X denotes the root node and F denotes the forest of successor trees (a Prolog list). The example tree depicted opposite is therefore represented by the following Prolog term: ; T = t(a,[t(f,[t(g,[])]),t(c,[]),t(b,[t(d,[]),t(e,[])])]) ; P70B (*) Check whether a given term represents a multiway tree ; Write a predicate istree/1 which succeeds if and only if its argument is a Prolog term representing a multiway tree. ; Example: ; * istree(t(a,[t(f,[t(g,[])]),t(c,[]),t(b,[t(d,[]),t(e,[])])])). ; Yes ; P70C (*) Count the nodes of a multiway tree ; Write a predicate nnodes/1 which counts the nodes of a given multiway tree. ; Example: ; * nnodes(t(a,[t(f,[])]),N). ; N = 2 ; Write another version of the predicate that allows for a flow pattern (o,i). ; P70 (**) Tree construction from a node string ; We suppose that the nodes of a multiway tree contain single characters. In the depth-first order sequence of its nodes, a special character ^ has been inserted whenever, during the tree traversal, the move is a backtrack to the previous level. ; By this rule, the tree in the figure opposite is represented as: afg^^c^bd^e^^^ ; Define the syntax of the string and write a predicate tree(String,Tree) to construct the Tree when the String is given. Work with atoms (instead of strings). Make your predicate work in both directions. ; P71 (*) Determine the internal path length of a tree ; We define the internal path length of a multiway tree as the total sum of the path lengths from the root to all nodes of the tree. By this definition, the tree in the figure of problem P70 has an internal path length of 9. Write a predicate ipl(Tree,IPL) for the flow pattern (+,-). ; P72 (*) Construct the bottom-up order sequence of the tree nodes ; Write a predicate bottom-up(Tree,Seq) which constructs the bottom-up sequence of the nodes of the multiway tree Tree. Seq should be a Prolog list. What happens if you run your predicate backwords? ; P73 (**) Lisp-like tree representation ; There is a particular notation for multiway trees in Lisp. Lisp is a prominent functional programming language, which is used primarily for artificial intelligence problems. As such it is one of the main competitors of Prolog. In Lisp almost everything is a list, just as in Prolog everything is a term. ; The following pictures show how multiway tree structures are represented in Lisp. ; Note that in the "lispy" notation a node with successors (children) in the tree is always the first element in a list, followed by its children. The "lispy" representation of a multiway tree is a sequence of atoms and parentheses '(' and ')', which we shall collectively call "tokens". We can represent this sequence of tokens as a Prolog list; e.g. the lispy expression (a (b c)) could be represented as the Prolog list ['(', a, '(', b, c, ')', ')']. Write a predicate tree-ltl(T,LTL) which constructs the "lispy token list" LTL if the tree is given as term T in the usual Prolog notation. ; Example: ; * tree-ltl(t(a,[t(b,[]),t(c,[])]),LTL). ; LTL = ['(', a, '(', b, c, ')', ')'] ; As a second, even more interesting exercise try to rewrite tree-ltl/2 in a way that the inverse conversion is also possible: Given the list LTL, construct the Prolog tree T. Use difference lists. ; Graphs ; A graph is defined as a set of nodes and a set of edges, where each edge is a pair of nodes. ; There are several ways to represent graphs in Prolog. One method is to represent each edge separately as one clause (fact). In this form, the graph depicted below is represented as the following predicate: ; edge(h,g). ; edge(k,f). ; edge(f,b). ; ... ; We call this edge-clause form. Obviously, isolated nodes cannot be represented. Another method is to represent the whole graph as one data object. According to the definition of the graph as a pair of two sets (nodes and edges), we may use the following Prolog term to represent the example graph: ; graph([b,c,d,f,g,h,k],[e(b,c),e(b,f),e(c,f),e(f,k),e(g,h)]) ; We call this graph-term form. Note, that the lists are kept sorted, they are really sets, without duplicated elements. Each edge appears only once in the edge list; i.e. an edge from a node x to another node y is represented as e(x,y), the term e(y,x) is not present. The graph-term form is our default representation. In SWI-Prolog there are predefined predicates to work with sets. ; A third representation method is to associate with each node the set of nodes that are adjacent to that node. We call this the adjacency-list form. In our example: ; [n(b,[c,f]), n(c,[b,f]), n(d,[]), n(f,[b,c,k]), ...] ; The representations we introduced so far are Prolog terms and therefore well suited for automated processing, but their syntax is not very user-friendly. Typing the terms by hand is cumbersome and error-prone. We can define a more compact and "human-friendly" notation as follows: A graph is represented by a list of atoms and terms of the type X-Y (i.e. functor '-' and arity 2). The atoms stand for isolated nodes, the X-Y terms describe edges. If an X appears as an endpoint of an edge, it is automatically defined as a node. Our example could be written as: ; [b-c, f-c, g-h, d, f-b, k-f, h-g] ; We call this the human-friendly form. As the example shows, the list does not have to be sorted and may even contain the same edge multiple times. Notice the isolated node d. (Actually, isolated nodes do not even have to be atoms in the Prolog sense, they can be compound terms, as in d(3.75,blue) instead of d in the example). ; When the edges are directed we call them arcs. These are represented by ordered pairs. Such a graph is called directed graph. To represent a directed graph, the forms discussed above are slightly modified. The example graph opposite is represented as follows: ; Arc-clause form ; arc(s,u). ; arc(u,r). ; ... ; Graph-term form ; digraph([r,s,t,u,v],[a(s,r),a(s,u),a(u,r),a(u,s),a(v,u)]) ; Adjacency-list form ; [n(r,[]),n(s,[r,u]),n(t,[]),n(u,[r]),n(v,[u])] ; Note that the adjacency-list does not have the information on whether it is a graph or a digraph. ; Human-friendly form ; [s > r, t, u > r, s > u, u > s, v > u] ; Finally, graphs and digraphs may have additional information attached to nodes and edges (arcs). For the nodes, this is no problem, as we can easily replace the single character identifiers with arbitrary compound terms, such as city('London',4711). On the other hand, for edges we have to extend our notation. Graphs with additional information attached to edges are called labelled graphs. ; Arc-clause form ; arc(m,q,7). ; arc(p,q,9). ; arc(p,m,5). ; Graph-term form ; digraph([k,m,p,q],[a(m,p,7),a(p,m,5),a(p,q,9)]) ; Adjacency-list form ; [n(k,[]),n(m,[q/7]),n(p,[m/5,q/9]),n(q,[])] ; Notice how the edge information has been packed into a term with functor '/' and arity 2, together with the corresponding node. ; Human-friendly form ; [p>q/9, m>q/7, k, p>m/5] ; The notation for labelled graphs can also be used for so-called multi-graphs, where more than one edge (or arc) are allowed between two given nodes. ; P80 (***) Conversions ; Write predicates to convert between the different graph representations. With these predicates, all representations are equivalent; i.e. for the following problems you can always pick freely the most convenient form. The reason this problem is rated (***) is not because it's particularly difficult, but because it's a lot of work to deal with all the special cases. ; P81 (**) Path from one node to another one ; Write a predicate path(G,A,B,P) to find an acyclic path P from node A to node b in the graph G. The predicate should return all paths via backtracking. ; P82 (*) Cycle from a given node ; Write a predicate cycle(G,A,P) to find a closed path (cycle) P starting at a given node A in the graph G. The predicate should return all cycles via backtracking. ; P83 (**) Construct all spanning trees ; Write a predicate s-tree(Graph,Tree) to construct (by backtracking) all spanning trees of a given graph. With this predicate, find out how many spanning trees there are for the graph depicted to the left. The data of this example graph can be found in the file p83.dat. When you have a correct solution for the s-tree/2 predicate, use it to define two other useful predicates: is-tree(Graph) and is-connected(Graph). Both are five-minutes tasks! ; P84 (**) Construct the minimal spanning tree ; Write a predicate ms-tree(Graph,Tree,Sum) to construct the minimal spanning tree of a given labelled graph. Hint: Use the algorithm of Prim. A small modification of the solution of P83 does the trick. The data of the example graph to the right can be found in the file p84.dat. ; P85 (**) Graph isomorphism ; Two graphs G1(N1,E1) and G2(N2,E2) are isomorphic if there is a bijection f: N1 -> N2 such that for any nodes X,Y of N1, X and Y are adjacent if and only if f(X) and f(Y) are adjacent. ; Write a predicate that determines whether two graphs are isomorphic. Hint: Use an open-ended list to represent the function f. ; P86 (**) Node degree and graph coloration ; a) Write a predicate degree(Graph,Node,Deg) that determines the degree of a given node. ; b) Write a predicate that generates a list of all nodes of a graph sorted according to decreasing degree. ; c) Use Welch-Powell's algorithm to paint the nodes of a graph in such a way that adjacent nodes have different colors. ; P87 (**) Depth-first order graph traversal (alternative solution) ; Write a predicate that generates a depth-first order graph traversal sequence. The starting point should be specified, and the output should be a list of nodes that are reachable from this starting point (in depth-first order). ; P88 (**) Connected components (alternative solution) ; Write a predicate that splits a graph into its connected components. ; P89 (**) Bipartite graphs ; Write a predicate that finds out whether a given graph is bipartite. ; Miscellaneous Problems ; P90 (**) Eight queens problem ; This is a classical problem in computer science. The objective is to place eight queens on a chessboard so that no two queens are attacking each other; i.e., no two queens are in the same row, the same column, or on the same diagonal. ; Hint: Represent the positions of the queens as a list of numbers 1..N. Example: [4,2,7,3,6,8,5,1] means that the queen in the first column is in row 4, the queen in the second column is in row 2, etc. Use the generate-and-test paradigm. ; P91 (**) Knight's tour ; Another famous problem is this one: How can a knight jump on an NxN chessboard in such a way that it visits every square exactly once? ; Hints: Represent the squares by pairs of their coordinates of the form X/Y, where both X and Y are integers between 1 and N. (Note that '/' is just a convenient functor, not division!) Define the relation jump(N,X/Y,U/V) to express the fact that a knight can jump from X/Y to U/V on a NxN chessboard. And finally, represent the solution of our problem as a list of N*N knight positions (the knight's tour). ; P92 (***) Von Koch's conjecture ; Several years ago I met a mathematician who was intrigued by a problem for which he didn't know a solution. His name was Von Koch, and I don't know whether the problem has been solved since. ; Anyway the puzzle goes like this: Given a tree with N nodes (and hence N-1 edges). Find a way to enumerate the nodes from 1 to N and, accordingly, the edges from 1 to N-1 in such a way, that for each edge K the difference of its node numbers equals to K. The conjecture is that this is always possible. ; For small trees the problem is easy to solve by hand. However, for larger trees, and 14 is already very large, it is extremely difficult to find a solution. And remember, we don't know for sure whether there is always a solution! ; Write a predicate that calculates a numbering scheme for a given tree. What is the solution for the larger tree pictured above? ; P93 (***) An arithmetic puzzle ; Given a list of integer numbers, find a correct way of inserting arithmetic signs (operators) such that the result is a correct equation. Example: With the list of numbers [2,3,5,7,11] we can form the equations 2-3+5+7 = 11 or 2 = (3*5+7)/11 (and ten others!). ; P94 (***) Generate K-regular simple graphs with N nodes ; In a K-regular graph all nodes have a degree of K; i.e. the number of edges incident in each node is K. How many (non-isomorphic!) 3-regular graphs with 6 nodes are there? See also a table of results and a Java applet that can represent graphs geometrically. ; P95 (**) English number words ; On financial documents, like cheques, numbers must sometimes be written in full words. Example: 175 must be written as one-seven-five. Write a predicate full-words/1 to print (non-negative) integer numbers in full words. ; P96 (**) Syntax checker (alternative solution with difference lists) ; In a certain programming language (Ada) identifiers are defined by the syntax diagram (railroad chart) opposite. Transform the syntax diagram into a system of syntax diagrams which do not contain loops; i.e. which are purely recursive. Using these modified diagrams, write a predicate identifier/1 that can check whether or not a given string is a legal identifier. ; % identifier(Str) :- Str is a legal identifier ; P97 (**) Sudoku ; Sudoku puzzles go like this: ; Problem statement Solution ; . . 4 | 8 . . | . 1 7 9 3 4 | 8 2 5 | 6 1 7 ; | | | | ; 6 7 . | 9 . . | . . . 6 7 2 | 9 1 4 | 8 5 3 ; | | | | ; 5 . 8 | . 3 . | . . 4 5 1 8 | 6 3 7 | 9 2 4 ; --------+---------+-------- --------+---------+-------- ; 3 . . | 7 4 . | 1 . . 3 2 5 | 7 4 8 | 1 6 9 ; | | | | ; . 6 9 | . . . | 7 8 . 4 6 9 | 1 5 3 | 7 8 2 ; | | | | ; . . 1 | . 6 9 | . . 5 7 8 1 | 2 6 9 | 4 3 5 ; --------+---------+-------- --------+---------+-------- ; 1 . . | . 8 . | 3 . 6 1 9 7 | 5 8 2 | 3 4 6 ; | | | | ; . . . | . . 6 | . 9 1 8 5 3 | 4 7 6 | 2 9 1 ; | | | | ; 2 4 . | . . 1 | 5 . . 2 4 6 | 3 9 1 | 5 7 8 ; Every spot in the puzzle belongs to a (horizontal) row and a (vertical) column, as well as to one single 3x3 square (which we call "square" for short). At the beginning, some of the spots carry a single-digit number between 1 and 9. The problem is to fill the missing spots with digits in such a way that every number between 1 and 9 appears exactly once in each row, in each column, and in each square. ; P98 (***) Nonograms ; Around 1994, a certain kind of puzzles was very popular in England. The "Sunday Telegraph" newspaper wrote: "Nonograms are puzzles from Japan and are currently published each week only in The Sunday Telegraph. Simply use your logic and skill to complete the grid and reveal a picture or diagram." As a Prolog programmer, you are in a better situation: you can have your computer do the work! Just write a little program ;-). ; The puzzle goes like this: Essentially, each row and column of a rectangular bitmap is annotated with the respective lengths of its distinct strings of occupied cells. The person who solves the puzzle must complete the bitmap given only these lengths. ; Problem statement: Solution: ; |_|_|_|_|_|_|_|_| 3 |_|X|X|X|_|_|_|_| 3 ; |_|_|_|_|_|_|_|_| 2 1 |X|X|_|X|_|_|_|_| 2 1 ; |_|_|_|_|_|_|_|_| 3 2 |_|X|X|X|_|_|X|X| 3 2 ; |_|_|_|_|_|_|_|_| 2 2 |_|_|X|X|_|_|X|X| 2 2 ; |_|_|_|_|_|_|_|_| 6 |_|_|X|X|X|X|X|X| 6 ; |_|_|_|_|_|_|_|_| 1 5 |X|_|X|X|X|X|X|_| 1 5 ; |_|_|_|_|_|_|_|_| 6 |X|X|X|X|X|X|_|_| 6 ; |_|_|_|_|_|_|_|_| 1 |_|_|_|_|X|_|_|_| 1 ; |_|_|_|_|_|_|_|_| 2 |_|_|_|X|X|_|_|_| 2 ; 1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3 ; 2 1 5 1 2 1 5 1 ; For the example above, the problem can be stated as the two lists [[3],[2,1],[3,2],[2,2],[6],[1,5],[6],[1],[2]] and [[1,2],[3,1],[1,5],[7,1],[5],[3],[4],[3]] which give the "solid" lengths of the rows and columns, top-to-bottom and left-to-right, respectively. Published puzzles are larger than this example, e.g. 25 x 20, and apparently always have unique solutions. ; P99 (***) Crossword puzzle ; Given an empty (or almost empty) framework of a crossword puzzle and a set of words. The problem is to place the words into the framework. ; The particular crossword puzzle is specified in a text file which first lists the words (one word per line) in an arbitrary order. Then, after an empty line, the crossword framework is defined. In this framework specification, an empty character location is represented by a dot (.). In order to make the solution easier, character locations can also contain predefined character values. The puzzle opposite is defined in the file p99a.dat, other examples are p99b.dat and p99d.dat. There is also an example of a puzzle (p99c.dat) which does not have a solution. ; Words are strings (character lists) of at least two characters. A horizontal or vertical sequence of character places in the crossword puzzle framework is called a site. Our problem is to find a compatible way of placing words onto sites. ; Hints: (1) The problem is not easy. You will need some time to thoroughly understand it. So, don't give up too early! And remember that the objective is a clean solution, not just a quick-and-dirty hack! ; (2) Reading the data file is a tricky problem for which a solution is provided in the file p99-readfile.lisp. Use the predicate read_lines/2. ; (3) For efficiency reasons it is important, at least for larger puzzles, to sort the words and the sites in a particular order. For this part of the problem, the solution of P28 may be very helpful. ; Last modified: Mon Oct 16 21:23:19 BRT 2006 (run-tests)
119413
(ns ninety-nine-problems (:use clojure.test)) ; L-99: Ninety-Nine Lisp Problems ; Based on a Prolog problem list by <EMAIL> ; Working with lists ; P01 (*) Find the last box of a list. ; Example: ; * (my-last '(a b c d)) ; (D) (defn my-last [lst] (let [tail (next lst)] (if (nil? tail) lst (my-last tail)))) (deftest P01 (is (= (my-last '()) '())) (is (= (my-last '(1)) '(1))) (is (= (my-last '(1 2 3 4)) '(4)))) ; P02 (*) Find the last but one box of a list. ; Example: ; * (my-but-last '(a b c d)) ; (C D) (defn my-but-last [lst] (let [tail (next lst)] (if (nil? (next tail)) lst (my-but-last tail)))) (deftest P02 (is (= (my-but-last '()) '())) (is (= (my-but-last '(1)) '(1))) (is (= (my-but-last '(1 2)) '(1 2))) (is (= (my-but-last '(1 2 3)) '(2 3))) (is (= (my-but-last '(1 2 3 4)) '(3 4)))) ; P03 (*) Find the K'th element of a list. ; The first element in the list is number 1. ; Example: ; * (element-at '(a b c d e) 3) ; C (defn element-at [lst pos] (if (= pos 1) (first lst) (element-at (next lst) (- pos 1)))) (deftest P03 (is (= (element-at '() 1) nil)) (is (= (element-at '(1) 1) 1)) (is (= (element-at '(1 2) 1) 1)) (is (= (element-at '(1 2) 2) 2)) (is (= (element-at '(1 2) 3) nil)) (is (= (element-at '(1 2 3 4) 3) 3))) ; P04 (*) Find the number of elements of a list. (defn len [lst] ((fn [lst counter] (if (empty? lst) counter (recur (next lst) (+ counter 1)))) lst 0)) (deftest P04 (is (= (len '()) 0)) (is (= (len '(2)) 1)) (is (= (len '(1 2 3 4)) 4))) ; P05 (*) Reverse a list. (defn rev [lst] ((fn [inp out] (if (empty? inp) out (recur (next inp) (conj out (first inp))))) lst '())) (deftest P05 (is (= (rev '()) '())) (is (= (rev '(1)) '(1))) (is (= (rev '(1 2 3)) '(3 2 1)))) ; P06 (*) Find out whether a list is a palindrome. ; A palindrome can be read forward or backward; e.g. (x a m a x). (defn is-palindrome [lst] ((fn [fwd bwd] (if (empty? fwd) true (if (not= (first fwd) (first bwd)) false (recur (next fwd) (next bwd))))) lst (rev lst))) (deftest P06 (is (true? (is-palindrome '()))) (is (true? (is-palindrome '(1)))) (is (false? (is-palindrome '(1 2 3)))) (is (true? (is-palindrome '(2 3 1 3 2))))) ; P07 (**) Flatten a nested list structure. ; Transform a list, possibly holding lists as elements into a `flat' list by replacing each list with its elements (recursively). ; Example: ; * (my-flatten '(a (b (c d) e))) ; (A B C D E) ; Hint: Use the predefined functions list and append. (declare collect-flatten my-flatten) (defn collect-flatten [inp out] (if (empty? inp) (reverse out) (recur (next inp) (if (list? (first inp)) (concat (my-flatten (first inp)) out) (conj out (first inp)))))) (defn my-flatten [lst] (collect-flatten lst '())) (deftest P07 (is (= (my-flatten '()) '())) (is (= (my-flatten '(1)) '(1))) (is (= (my-flatten '(1 '(2 3))) '(1 2 3))) (is (= (my-flatten '(1 '(2 '(3 4) 5))) '(1 2 3 4 5)))) ; P08 (**) Eliminate consecutive duplicates of list elements. ; If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed. ; Example: ; * (compress '(a a a a b c c a a d e e e e)) ; (A B C A D E) ; P09 (**) Pack consecutive duplicates of list elements into sublists. ; If a list contains repeated elements they should be placed in separate sublists. ; Example: ; * (pack '(a a a a b c c a a d e e e e)) ; ((A A A A) (B) (C C) (A A) (D) (E E E E)) ; P10 (*) Run-length encoding of a list. ; Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as lists (N E) where N is the number of duplicates of the element E. ; Example: ; * (encode '(a a a a b c c a a d e e e e)) ; ((4 A) (1 B) (2 C) (2 A) (1 D)(4 E)) ; P11 (*) Modified run-length encoding. ; Modify the result of problem P10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as (N E) lists. ; Example: ; * (encode-modified '(a a a a b c c a a d e e e e)) ; ((4 A) B (2 C) (2 A) D (4 E)) ; P12 (**) Decode a run-length encoded list. ; Given a run-length code list generated as specified in problem P11. Construct its uncompressed version. ; P13 (**) Run-length encoding of a list (direct solution). ; Implement the so-called run-length encoding data compression method directly. I.e. don't explicitly create the sublists containing the duplicates, as in problem P09, but only count them. As in problem P11, simplify the result list by replacing the singleton lists (1 X) by X. ; Example: ; * (encode-direct '(a a a a b c c a a d e e e e)) ; ((4 A) B (2 C) (2 A) D (4 E)) ; P14 (*) Duplicate the elements of a list. ; Example: ; * (dupli '(a b c c d)) ; (A A B B C C C C D D) ; P15 (**) Replicate the elements of a list a given number of times. ; Example: ; * (repli '(a b c) 3) ; (A A A B B B C C C) ; P16 (**) Drop every N'th element from a list. ; Example: ; * (drop '(a b c d e f g h i k) 3) ; (A B D E G H K) ; P17 (*) Split a list into two parts; the length of the first part is given. ; Do not use any predefined predicates. ; Example: ; * (split '(a b c d e f g h i k) 3) ; ( (A B C) (D E F G H I K)) ; P18 (**) Extract a slice from a list. ; Given two indices, I and K, the slice is the list containing the elements between the I'th and K'th element of the original list (both limits included). Start counting the elements with 1. ; Example: ; * (slice '(a b c d e f g h i k) 3 7) ; (C D E F G) ; P19 (**) Rotate a list N places to the left. ; Examples: ; * (rotate '(a b c d e f g h) 3) ; (D E F G H A B C) ; * (rotate '(a b c d e f g h) -2) ; (G H A B C D E F) ; Hint: Use the predefined functions length and append, as well as the result of problem P17. ; P20 (*) Remove the K'th element from a list. ; Example: ; * (remove-at '(a b c d) 2) ; (A C D) ; P21 (*) Insert an element at a given position into a list. ; Example: ; * (insert-at 'alfa '(a b c d) 2) ; (A ALFA B C D) ; P22 (*) Create a list containing all integers within a given range. ; If first argument is smaller than second, produce a list in decreasing order. ; Example: ; * (range 4 9) ; (4 5 6 7 8 9) ; P23 (**) Extract a given number of randomly selected elements from a list. ; The selected items shall be returned in a list. ; Example: ; * (rnd-select '(a b c d e f g h) 3) ; (E D A) ; Hint: Use the built-in random number generator and the result of problem P20. ; P24 (*) Lotto: Draw N different random numbers from the set 1..M. ; The selected numbers shall be returned in a list. ; Example: ; * (lotto-select 6 49) ; (23 1 17 33 21 37) ; Hint: Combine the solutions of problems P22 and P23. ; P25 (*) Generate a random permutation of the elements of a list. ; Example: ; * (rnd-permu '(a b c d e f)) ; (B A D C E F) ; Hint: Use the solution of problem P23. ; P26 (**) Generate the combinations of K distinct objects chosen from the N elements of a list ; In how many ways can a committee of 3 be chosen from a group of 12 people? We all know that there are C(12,3) = 220 possibilities (C(N,K) denotes the well-known binomial coefficients). For pure mathematicians, this result may be great. But we want to really generate all the possibilities in a list. ; Example: ; * (combination 3 '(a b c d e f)) ; ((A B C) (A B D) (A B E) ... ) ; P27 (**) Group the elements of a set into disjoint subsets. ; a) In how many ways can a group of 9 people work in 3 disjoint subgroups of 2, 3 and 4 persons? Write a function that generates all the possibilities and returns them in a list. ; Example: ; * (group3 '(aldo beat <NAME> d<NAME> evi flip gary hugo ida)) ; ( ( (<NAME> BEAT) (<NAME> E<NAME>) (FLIP G<NAME> H<NAME> IDA) ) ; ... ) ; b) Generalize the above predicate in a way that we can specify a list of group sizes and the predicate will return a list of groups. ; Example: ; * (group '(aldo beat <NAME> david <NAME> ida) '(2 2 5)) ; ( ( (<NAME>) (<NAME>) (<NAME> ID<NAME>) ) ; ... ) ; Note that we do not want permutations of the group members; i.e. ((ALDO BEAT) ...) is the same solution as ((BEAT ALDO) ...). However, we make a difference between ((ALDO BEAT) (<NAME> DAV<NAME>) ...) and ((<NAME>) (ALDO BEAT) ...). ; You may find more about this combinatorial problem in a good book on discrete mathematics under the term "multinomial coefficients". ; P28 (**) Sorting a list of lists according to length of sublists ; a) We suppose that a list contains elements that are lists themselves. The objective is to sort the elements of this list according to their length. E.g. short lists first, longer lists later, or vice versa. ; Example: ; * (lsort '((a b c) (d e) (f g h) (d e) (i j k l) (m n) (o))) ; ((O) (D E) (D E) (M N) (A B C) (F G H) (I J K L)) ; b) Again, we suppose that a list contains elements that are lists themselves. But this time the objective is to sort the elements of this list according to their length frequency; i.e., in the default, where sorting is done ascendingly, lists with rare lengths are placed first, others with a more frequent length come later. ; Example: ; * (lfsort '((a b c) (d e) (f g h) (d e) (i j k l) (m n) (o))) ; ((i j k l) (o) (a b c) (f g h) (d e) (d e) (m n)) ; Note that in the above example, the first two lists in the result have length 4 and 1, both lengths appear just once. The third and forth list have length 3 which appears twice (there are two list of this length). And finally, the last three lists have length 2. This is the most frequent length. ; Arithmetic ; P31 (**) Determine whether a given integer number is prime. ; Example: ; * (is-prime 7) ; T ; P32 (**) Determine the greatest common divisor of two positive integer numbers. ; Use Euclid's algorithm. ; Example: ; * (gcd 36 63) ; 9 ; P33 (*) Determine whether two positive integer numbers are coprime. ; Two numbers are coprime if their greatest common divisor equals 1. ; Example: ; * (coprime 35 64) ; T ; P34 (**) Calculate Euler's totient function phi(m). ; Euler's so-called totient function phi(m) is defined as the number of positive integers r (1 <= r < m) that are coprime to m. ; Example: m = 10: r = 1,3,7,9; thus phi(m) = 4. Note the special case: phi(1) = 1. ; * (totient-phi 10) ; 4 ; Find out what the value of phi(m) is if m is a prime number. Euler's totient function plays an important role in one of the most widely used public key cryptography methods (RSA). In this exercise you should use the most primitive method to calculate this function (there are smarter ways that we shall discuss later). ; P35 (**) Determine the prime factors of a given positive integer. ; Construct a flat list containing the prime factors in ascending order. ; Example: ; * (prime-factors 315) ; (3 3 5 7) ; P36 (**) Determine the prime factors of a given positive integer (2). ; Construct a list containing the prime factors and their multiplicity. ; Example: ; * (prime-factors-mult 315) ; ((3 2) (5 1) (7 1)) ; Hint: The problem is similar to problem P13. ; P37 (**) Calculate Euler's totient function phi(m) (improved). ; See problem P34 for the definition of Euler's totient function. If the list of the prime factors of a number m is known in the form of problem P36 then the function phi(m) can be efficiently calculated as follows: Let ((p1 m1) (p2 m2) (p3 m3) ...) be the list of prime factors (and their multiplicities) of a given number m. Then phi(m) can be calculated with the following formula: ; phi(m) = (p1 - 1) * p1 ** (m1 - 1) + (p2 - 1) * p2 ** (m2 - 1) + (p3 - 1) * p3 ** (m3 - 1) + ... ; Note that a ** b stands for the b'th power of a. ; P38 (*) Compare the two methods of calculating Euler's totient function. ; Use the solutions of problems P34 and P37 to compare the algorithms. Take the number of logical inferences as a measure for efficiency. Try to calculate phi(10090) as an example. ; P39 (*) A list of prime numbers. ; Given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range. ; P40 (**) Goldbach's conjecture. ; Goldbach's conjecture says that every positive even number greater than 2 is the sum of two prime numbers. Example: 28 = 5 + 23. It is one of the most famous facts in number theory that has not been proved to be correct in the general case. It has been numerically confirmed up to very large numbers (much larger than we can go with our Prolog system). Write a predicate to find the two prime numbers that sum up to a given even integer. ; Example: ; * (goldbach 28) ; (5 23) ; P41 (**) A list of Goldbach compositions. ; Given a range of integers by its lower and upper limit, print a list of all even numbers and their Goldbach composition. ; Example: ; * (goldbach-list 9 20) ; 10 = 3 + 7 ; 12 = 5 + 7 ; 14 = 3 + 11 ; 16 = 3 + 13 ; 18 = 5 + 13 ; 20 = 3 + 17 ; In most cases, if an even number is written as the sum of two prime numbers, one of them is very small. Very rarely, the primes are both bigger than say 50. Try to find out how many such cases there are in the range 2..3000. ; Example (for a print limit of 50): ; * (goldbach-list 1 2000 50) ; 992 = 73 + 919 ; 1382 = 61 + 1321 ; 1856 = 67 + 1789 ; 1928 = 61 + 1867 ; Logic and Codes ; P46 (**) Truth tables for logical expressions. ; Define predicates and/2, or/2, nand/2, nor/2, xor/2, impl/2 and equ/2 (for logical equivalence) which succeed or fail according to the result of their respective operations; e.g. and(A,B) will succeed, if and only if both A and B succeed. Note that A and B can be Prolog goals (not only the constants true and fail). ; A logical expression in two variables can then be written in prefix notation, as in the following example: and(or(A,B),nand(A,B)). ; Now, write a predicate table/3 which prints the truth table of a given logical expression in two variables. ; Example: ; * table(A,B,and(A,or(A,B))). ; true true true ; true fail true ; fail true fail ; fail fail fail ; P47 (*) Truth tables for logical expressions (2). ; Continue problem P46 by defining and/2, or/2, etc as being operators. This allows to write the logical expression in the more natural way, as in the example: A and (A or not B). Define operator precedence as usual; i.e. as in Java. ; Example: ; * table(A,B, A and (A or not B)). ; true true true ; true fail true ; fail true fail ; fail fail fail ; P48 (**) Truth tables for logical expressions (3). ; Generalize problem P47 in such a way that the logical expression may contain any number of logical variables. Define table/2 in a way that table(List,Expr) prints the truth table for the expression Expr, which contains the logical variables enumerated in List. ; Example: ; * table([A,B,C], A and (B or C) equ A and B or A and C). ; true true true true ; true true fail true ; true fail true true ; true fail fail true ; fail true true true ; fail true fail true ; fail fail true true ; fail fail fail true ; P49 (**) Gray code. ; An n-bit Gray code is a sequence of n-bit strings constructed according to certain rules. For example, ; n = 1: C(1) = ['0','1']. ; n = 2: C(2) = ['00','01','11','10']. ; n = 3: C(3) = ['000','001','011','010',´110´,´111´,´101´,´100´]. ; Find out the construction rules and write a predicate with the following specification: ; % gray(N,C) :- C is the N-bit Gray code ; Can you apply the method of "result caching" in order to make the predicate more efficient, when it is to be used repeatedly? ; P50 (***) Huffman code. ; First of all, consult a good book on discrete mathematics or algorithms for a detailed description of Huffman codes! ; We suppose a set of symbols with their frequencies, given as a list of fr(S,F) terms. Example: [fr(a,45),fr(b,13),fr(c,12),fr(d,16),fr(e,9),fr(f,5)]. Our objective is to construct a list hc(S,C) terms, where C is the Huffman code word for the symbol S. In our example, the result could be Hs = [hc(a,'0'), hc(b,'101'), hc(c,'100'), hc(d,'111'), hc(e,'1101'), hc(f,'1100')] [hc(a,'01'),...etc.]. The task shall be performed by the predicate huffman/2 defined as follows: ; % huffman(Fs,Hs) :- Hs is the Huffman code table for the frequency table Fs ; Binary Trees ; A binary tree is either empty or it is composed of a root element and two successors, which are binary trees themselves. ; In Lisp we represent the empty tree by 'nil' and the non-empty tree by the list (X L R), where X denotes the root node and L and R denote the left and right subtree, respectively. The example tree depicted opposite is therefore represented by the following list: ; (a (b (d nil nil) (e nil nil)) (c nil (f (g nil nil) nil))) ; Other examples are a binary tree that consists of a root node only: ; (a nil nil) or an empty binary tree: nil. ; You can check your predicates using these example trees. They are given as test cases in p54.lisp. ; P54A (*) Check whether a given term represents a binary tree ; Write a predicate istree which returns true if and only if its argument is a list representing a binary tree. ; Example: ; * (istree (a (b nil nil) nil)) ; T ; * (istree (a (b nil nil))) ; NIL ; P55 (**) Construct completely balanced binary trees ; In a completely balanced binary tree, the following property holds for every node: The number of nodes in its left subtree and the number of nodes in its right subtree are almost equal, which means their difference is not greater than one. ; Write a function cbal-tree to construct completely balanced binary trees for a given number of nodes. The predicate should generate all solutions via backtracking. Put the letter 'x' as information into all nodes of the tree. ; Example: ; * cbal-tree(4,T). ; T = t(x, t(x, nil, nil), t(x, nil, t(x, nil, nil))) ; ; T = t(x, t(x, nil, nil), t(x, t(x, nil, nil), nil)) ; ; etc......No ; P56 (**) Symmetric binary trees ; Let us call a binary tree symmetric if you can draw a vertical line through the root node and then the right subtree is the mirror image of the left subtree. Write a predicate symmetric/1 to check whether a given binary tree is symmetric. Hint: Write a predicate mirror/2 first to check whether one tree is the mirror image of another. We are only interested in the structure, not in the contents of the nodes. ; P57 (**) Binary search trees (dictionaries) ; Use the predicate add/3, developed in chapter 4 of the course, to write a predicate to construct a binary search tree from a list of integer numbers. ; Example: ; * construct([3,2,5,7,1],T). ; T = t(3, t(2, t(1, nil, nil), nil), t(5, nil, t(7, nil, nil))) ; Then use this predicate to test the solution of the problem P56. ; Example: ; * test-symmetric([5,3,18,1,4,12,21]). ; Yes ; * test-symmetric([3,2,5,7,1]). ; No ; P58 (**) Generate-and-test paradigm ; Apply the generate-and-test paradigm to construct all symmetric, completely balanced binary trees with a given number of nodes. Example: ; * sym-cbal-trees(5,Ts). ; Ts = [t(x, t(x, nil, t(x, nil, nil)), t(x, t(x, nil, nil), nil)), t(x, t(x, t(x, nil, nil), nil), t(x, nil, t(x, nil, nil)))] ; How many such trees are there with 57 nodes? Investigate about how many solutions there are for a given number of nodes? What if the number is even? Write an appropriate predicate. ; P59 (**) Construct height-balanced binary trees ; In a height-balanced binary tree, the following property holds for every node: The height of its left subtree and the height of its right subtree are almost equal, which means their difference is not greater than one. ; Write a predicate hbal-tree/2 to construct height-balanced binary trees for a given height. The predicate should generate all solutions via backtracking. Put the letter 'x' as information into all nodes of the tree. ; Example: ; * hbal-tree(3,T). ; T = t(x, t(x, t(x, nil, nil), t(x, nil, nil)), t(x, t(x, nil, nil), t(x, nil, nil))) ; ; T = t(x, t(x, t(x, nil, nil), t(x, nil, nil)), t(x, t(x, nil, nil), nil)) ; ; etc......No ; P60 (**) Construct height-balanced binary trees with a given number of nodes ; Consider a height-balanced binary tree of height H. What is the maximum number of nodes it can contain? ; Clearly, MaxN = 2**H - 1. However, what is the minimum number MinN? This question is more difficult. Try to find a recursive statement and turn it into a predicate minNodes/2 defined as follwos: ; % minNodes(H,N) :- N is the minimum number of nodes in a height-balanced binary tree of height H. ; (integer,integer), (+,?) ; On the other hand, we might ask: what is the maximum height H a height-balanced binary tree with N nodes can have? ; % maxHeight(N,H) :- H is the maximum height of a height-balanced binary tree with N nodes ; (integer,integer), (+,?) ; Now, we can attack the main problem: construct all the height-balanced binary trees with a given nuber of nodes. ; % hbal-tree-nodes(N,T) :- T is a height-balanced binary tree with N nodes. ; Find out how many height-balanced trees exist for N = 15. ; P61 (*) Count the leaves of a binary tree ; A leaf is a node with no successors. Write a predicate count-leaves/2 to count them. ; % count-leaves(T,N) :- the binary tree T has N leaves ; P61A (*) Collect the leaves of a binary tree in a list ; A leaf is a node with no successors. Write a predicate leaves/2 to collect them in a list. ; % leaves(T,S) :- S is the list of all leaves of the binary tree T ; P62 (*) Collect the internal nodes of a binary tree in a list ; An internal node of a binary tree has either one or two non-empty successors. Write a predicate internals/2 to collect them in a list. ; % internals(T,S) :- S is the list of internal nodes of the binary tree T. ; P62B (*) Collect the nodes at a given level in a list ; A node of a binary tree is at level N if the path from the root to the node has length N-1. The root node is at level 1. Write a predicate atlevel/3 to collect all nodes at a given level in a list. ; % atlevel(T,L,S) :- S is the list of nodes of the binary tree T at level L ; Using atlevel/3 it is easy to construct a predicate levelorder/2 which creates the level-order sequence of the nodes. However, there are more efficient ways to do that. ; P63 (**) Construct a complete binary tree ; A complete binary tree with height H is defined as follows: The levels 1,2,3,...,H-1 contain the maximum number of nodes (i.e 2**(i-1) at the level i, note that we start counting the levels from 1 at the root). In level H, which may contain less than the maximum possible number of nodes, all the nodes are "left-adjusted". This means that in a levelorder tree traversal all internal nodes come first, the leaves come second, and empty successors (the nil's which are not really nodes!) come last. ; Particularly, complete binary trees are used as data structures (or addressing schemes) for heaps. ; We can assign an address number to each node in a complete binary tree by enumerating the nodes in levelorder, starting at the root with number 1. In doing so, we realize that for every node X with address A the following property holds: The address of X's left and right successors are 2*A and 2*A+1, respectively, supposed the successors do exist. This fact can be used to elegantly construct a complete binary tree structure. Write a predicate complete-binary-tree/2 with the following specification: ; % complete-binary-tree(N,T) :- T is a complete binary tree with N nodes. (+,?) ; Test your predicate in an appropriate way. ; P64 (**) Layout a binary tree (1) ; Given a binary tree as the usual Prolog term t(X,L,R) (or nil). As a preparation for drawing the tree, a layout algorithm is required to determine the position of each node in a rectangular grid. Several layout methods are conceivable, one of them is shown in the illustration below. ; In this layout strategy, the position of a node v is obtained by the following two rules: ; x(v) is equal to the position of the node v in the inorder sequence ; y(v) is equal to the depth of the node v in the tree ; In order to store the position of the nodes, we extend the Prolog term representing a node (and its successors) as follows: ; % nil represents the empty tree (as usual) ; % t(W,X,Y,L,R) represents a (non-empty) binary tree with root W "positioned" at (X,Y), and subtrees L and R ; Write a predicate layout-binary-tree/2 with the following specification: ; % layout-binary-tree(T,PT) :- PT is the "positioned" binary tree obtained from the binary tree T. (+,?) ; Test your predicate in an appropriate way. ; P65 (**) Layout a binary tree (2) ; An alternative layout method is depicted in the illustration opposite. Find out the rules and write the corresponding Prolog predicate. Hint: On a given level, the horizontal distance between neighboring nodes is constant. ; Use the same conventions as in problem P64 and test your predicate in an appropriate way. ; P66 (***) Layout a binary tree (3) ; Yet another layout strategy is shown in the illustration opposite. The method yields a very compact layout while maintaining a certain symmetry in every node. Find out the rules and write the corresponding Prolog predicate. Hint: Consider the horizontal distance between a node and its successor nodes. How tight can you pack together two subtrees to construct the combined binary tree? ; Use the same conventions as in problem P64 and P65 and test your predicate in an appropriate way. Note: This is a difficult problem. Don't give up too early! ; Which layout do you like most? ; P67 (**) A string representation of binary trees ; Somebody represents binary trees as strings of the following type (see example opposite): ; a(b(d,e),c(,f(g,))) ; a) Write a Prolog predicate which generates this string representation, if the tree is given as usual (as nil or t(X,L,R) term). Then write a predicate which does this inverse; i.e. given the string representation, construct the tree in the usual form. Finally, combine the two predicates in a single predicate tree-string/2 which can be used in both directions. ; b) Write the same predicate tree-string/2 using difference lists and a single predicate tree-dlist/2 which does the conversion between a tree and a difference list in both directions. ; For simplicity, suppose the information in the nodes is a single letter and there are no spaces in the string. ; P68 (**) Preorder and inorder sequences of binary trees ; We consider binary trees with nodes that are identified by single lower-case letters, as in the example of problem P67. ; a) Write predicates preorder/2 and inorder/2 that construct the preorder and inorder sequence of a given binary tree, respectively. The results should be atoms, e.g. 'abdecfg' for the preorder sequence of the example in problem P67. ; b) Can you use preorder/2 from problem part a) in the reverse direction; i.e. given a preorder sequence, construct a corresponding tree? If not, make the necessary arrangements. ; c) If both the preorder sequence and the inorder sequence of the nodes of a binary tree are given, then the tree is determined unambiguously. Write a predicate pre-in-tree/3 that does the job. ; d) Solve problems a) to c) using difference lists. Cool! Use the predefined predicate time/1 to compare the solutions. ; What happens if the same character appears in more than one node. Try for instance pre-in-tree(aba,baa,T). ; P69 (**) Dotstring representation of binary trees ; We consider again binary trees with nodes that are identified by single lower-case letters, as in the example of problem P67. Such a tree can be represented by the preorder sequence of its nodes in which dots (.) are inserted where an empty subtree (nil) is encountered during the tree traversal. For example, the tree shown in problem P67 is represented as 'abd..e..c.fg...'. First, try to establish a syntax (BNF or syntax diagrams) and then write a predicate tree-dotstring/2 which does the conversion in both directions. Use difference lists. ; Multiway Trees ; A multiway tree is composed of a root element and a (possibly empty) set of successors which are multiway trees themselves. A multiway tree is never empty. The set of successor trees is sometimes called a forest. ; In Prolog we represent a multiway tree by a term t(X,F), where X denotes the root node and F denotes the forest of successor trees (a Prolog list). The example tree depicted opposite is therefore represented by the following Prolog term: ; T = t(a,[t(f,[t(g,[])]),t(c,[]),t(b,[t(d,[]),t(e,[])])]) ; P70B (*) Check whether a given term represents a multiway tree ; Write a predicate istree/1 which succeeds if and only if its argument is a Prolog term representing a multiway tree. ; Example: ; * istree(t(a,[t(f,[t(g,[])]),t(c,[]),t(b,[t(d,[]),t(e,[])])])). ; Yes ; P70C (*) Count the nodes of a multiway tree ; Write a predicate nnodes/1 which counts the nodes of a given multiway tree. ; Example: ; * nnodes(t(a,[t(f,[])]),N). ; N = 2 ; Write another version of the predicate that allows for a flow pattern (o,i). ; P70 (**) Tree construction from a node string ; We suppose that the nodes of a multiway tree contain single characters. In the depth-first order sequence of its nodes, a special character ^ has been inserted whenever, during the tree traversal, the move is a backtrack to the previous level. ; By this rule, the tree in the figure opposite is represented as: afg^^c^bd^e^^^ ; Define the syntax of the string and write a predicate tree(String,Tree) to construct the Tree when the String is given. Work with atoms (instead of strings). Make your predicate work in both directions. ; P71 (*) Determine the internal path length of a tree ; We define the internal path length of a multiway tree as the total sum of the path lengths from the root to all nodes of the tree. By this definition, the tree in the figure of problem P70 has an internal path length of 9. Write a predicate ipl(Tree,IPL) for the flow pattern (+,-). ; P72 (*) Construct the bottom-up order sequence of the tree nodes ; Write a predicate bottom-up(Tree,Seq) which constructs the bottom-up sequence of the nodes of the multiway tree Tree. Seq should be a Prolog list. What happens if you run your predicate backwords? ; P73 (**) Lisp-like tree representation ; There is a particular notation for multiway trees in Lisp. Lisp is a prominent functional programming language, which is used primarily for artificial intelligence problems. As such it is one of the main competitors of Prolog. In Lisp almost everything is a list, just as in Prolog everything is a term. ; The following pictures show how multiway tree structures are represented in Lisp. ; Note that in the "lispy" notation a node with successors (children) in the tree is always the first element in a list, followed by its children. The "lispy" representation of a multiway tree is a sequence of atoms and parentheses '(' and ')', which we shall collectively call "tokens". We can represent this sequence of tokens as a Prolog list; e.g. the lispy expression (a (b c)) could be represented as the Prolog list ['(', a, '(', b, c, ')', ')']. Write a predicate tree-ltl(T,LTL) which constructs the "lispy token list" LTL if the tree is given as term T in the usual Prolog notation. ; Example: ; * tree-ltl(t(a,[t(b,[]),t(c,[])]),LTL). ; LTL = ['(', a, '(', b, c, ')', ')'] ; As a second, even more interesting exercise try to rewrite tree-ltl/2 in a way that the inverse conversion is also possible: Given the list LTL, construct the Prolog tree T. Use difference lists. ; Graphs ; A graph is defined as a set of nodes and a set of edges, where each edge is a pair of nodes. ; There are several ways to represent graphs in Prolog. One method is to represent each edge separately as one clause (fact). In this form, the graph depicted below is represented as the following predicate: ; edge(h,g). ; edge(k,f). ; edge(f,b). ; ... ; We call this edge-clause form. Obviously, isolated nodes cannot be represented. Another method is to represent the whole graph as one data object. According to the definition of the graph as a pair of two sets (nodes and edges), we may use the following Prolog term to represent the example graph: ; graph([b,c,d,f,g,h,k],[e(b,c),e(b,f),e(c,f),e(f,k),e(g,h)]) ; We call this graph-term form. Note, that the lists are kept sorted, they are really sets, without duplicated elements. Each edge appears only once in the edge list; i.e. an edge from a node x to another node y is represented as e(x,y), the term e(y,x) is not present. The graph-term form is our default representation. In SWI-Prolog there are predefined predicates to work with sets. ; A third representation method is to associate with each node the set of nodes that are adjacent to that node. We call this the adjacency-list form. In our example: ; [n(b,[c,f]), n(c,[b,f]), n(d,[]), n(f,[b,c,k]), ...] ; The representations we introduced so far are Prolog terms and therefore well suited for automated processing, but their syntax is not very user-friendly. Typing the terms by hand is cumbersome and error-prone. We can define a more compact and "human-friendly" notation as follows: A graph is represented by a list of atoms and terms of the type X-Y (i.e. functor '-' and arity 2). The atoms stand for isolated nodes, the X-Y terms describe edges. If an X appears as an endpoint of an edge, it is automatically defined as a node. Our example could be written as: ; [b-c, f-c, g-h, d, f-b, k-f, h-g] ; We call this the human-friendly form. As the example shows, the list does not have to be sorted and may even contain the same edge multiple times. Notice the isolated node d. (Actually, isolated nodes do not even have to be atoms in the Prolog sense, they can be compound terms, as in d(3.75,blue) instead of d in the example). ; When the edges are directed we call them arcs. These are represented by ordered pairs. Such a graph is called directed graph. To represent a directed graph, the forms discussed above are slightly modified. The example graph opposite is represented as follows: ; Arc-clause form ; arc(s,u). ; arc(u,r). ; ... ; Graph-term form ; digraph([r,s,t,u,v],[a(s,r),a(s,u),a(u,r),a(u,s),a(v,u)]) ; Adjacency-list form ; [n(r,[]),n(s,[r,u]),n(t,[]),n(u,[r]),n(v,[u])] ; Note that the adjacency-list does not have the information on whether it is a graph or a digraph. ; Human-friendly form ; [s > r, t, u > r, s > u, u > s, v > u] ; Finally, graphs and digraphs may have additional information attached to nodes and edges (arcs). For the nodes, this is no problem, as we can easily replace the single character identifiers with arbitrary compound terms, such as city('London',4711). On the other hand, for edges we have to extend our notation. Graphs with additional information attached to edges are called labelled graphs. ; Arc-clause form ; arc(m,q,7). ; arc(p,q,9). ; arc(p,m,5). ; Graph-term form ; digraph([k,m,p,q],[a(m,p,7),a(p,m,5),a(p,q,9)]) ; Adjacency-list form ; [n(k,[]),n(m,[q/7]),n(p,[m/5,q/9]),n(q,[])] ; Notice how the edge information has been packed into a term with functor '/' and arity 2, together with the corresponding node. ; Human-friendly form ; [p>q/9, m>q/7, k, p>m/5] ; The notation for labelled graphs can also be used for so-called multi-graphs, where more than one edge (or arc) are allowed between two given nodes. ; P80 (***) Conversions ; Write predicates to convert between the different graph representations. With these predicates, all representations are equivalent; i.e. for the following problems you can always pick freely the most convenient form. The reason this problem is rated (***) is not because it's particularly difficult, but because it's a lot of work to deal with all the special cases. ; P81 (**) Path from one node to another one ; Write a predicate path(G,A,B,P) to find an acyclic path P from node A to node b in the graph G. The predicate should return all paths via backtracking. ; P82 (*) Cycle from a given node ; Write a predicate cycle(G,A,P) to find a closed path (cycle) P starting at a given node A in the graph G. The predicate should return all cycles via backtracking. ; P83 (**) Construct all spanning trees ; Write a predicate s-tree(Graph,Tree) to construct (by backtracking) all spanning trees of a given graph. With this predicate, find out how many spanning trees there are for the graph depicted to the left. The data of this example graph can be found in the file p83.dat. When you have a correct solution for the s-tree/2 predicate, use it to define two other useful predicates: is-tree(Graph) and is-connected(Graph). Both are five-minutes tasks! ; P84 (**) Construct the minimal spanning tree ; Write a predicate ms-tree(Graph,Tree,Sum) to construct the minimal spanning tree of a given labelled graph. Hint: Use the algorithm of Prim. A small modification of the solution of P83 does the trick. The data of the example graph to the right can be found in the file p84.dat. ; P85 (**) Graph isomorphism ; Two graphs G1(N1,E1) and G2(N2,E2) are isomorphic if there is a bijection f: N1 -> N2 such that for any nodes X,Y of N1, X and Y are adjacent if and only if f(X) and f(Y) are adjacent. ; Write a predicate that determines whether two graphs are isomorphic. Hint: Use an open-ended list to represent the function f. ; P86 (**) Node degree and graph coloration ; a) Write a predicate degree(Graph,Node,Deg) that determines the degree of a given node. ; b) Write a predicate that generates a list of all nodes of a graph sorted according to decreasing degree. ; c) Use Welch-Powell's algorithm to paint the nodes of a graph in such a way that adjacent nodes have different colors. ; P87 (**) Depth-first order graph traversal (alternative solution) ; Write a predicate that generates a depth-first order graph traversal sequence. The starting point should be specified, and the output should be a list of nodes that are reachable from this starting point (in depth-first order). ; P88 (**) Connected components (alternative solution) ; Write a predicate that splits a graph into its connected components. ; P89 (**) Bipartite graphs ; Write a predicate that finds out whether a given graph is bipartite. ; Miscellaneous Problems ; P90 (**) Eight queens problem ; This is a classical problem in computer science. The objective is to place eight queens on a chessboard so that no two queens are attacking each other; i.e., no two queens are in the same row, the same column, or on the same diagonal. ; Hint: Represent the positions of the queens as a list of numbers 1..N. Example: [4,2,7,3,6,8,5,1] means that the queen in the first column is in row 4, the queen in the second column is in row 2, etc. Use the generate-and-test paradigm. ; P91 (**) Knight's tour ; Another famous problem is this one: How can a knight jump on an NxN chessboard in such a way that it visits every square exactly once? ; Hints: Represent the squares by pairs of their coordinates of the form X/Y, where both X and Y are integers between 1 and N. (Note that '/' is just a convenient functor, not division!) Define the relation jump(N,X/Y,U/V) to express the fact that a knight can jump from X/Y to U/V on a NxN chessboard. And finally, represent the solution of our problem as a list of N*N knight positions (the knight's tour). ; P92 (***) <NAME> Koch's conjecture ; Several years ago I met a mathematician who was intrigued by a problem for which he didn't know a solution. His name was <NAME>, and I don't know whether the problem has been solved since. ; Anyway the puzzle goes like this: Given a tree with N nodes (and hence N-1 edges). Find a way to enumerate the nodes from 1 to N and, accordingly, the edges from 1 to N-1 in such a way, that for each edge K the difference of its node numbers equals to K. The conjecture is that this is always possible. ; For small trees the problem is easy to solve by hand. However, for larger trees, and 14 is already very large, it is extremely difficult to find a solution. And remember, we don't know for sure whether there is always a solution! ; Write a predicate that calculates a numbering scheme for a given tree. What is the solution for the larger tree pictured above? ; P93 (***) An arithmetic puzzle ; Given a list of integer numbers, find a correct way of inserting arithmetic signs (operators) such that the result is a correct equation. Example: With the list of numbers [2,3,5,7,11] we can form the equations 2-3+5+7 = 11 or 2 = (3*5+7)/11 (and ten others!). ; P94 (***) Generate K-regular simple graphs with N nodes ; In a K-regular graph all nodes have a degree of K; i.e. the number of edges incident in each node is K. How many (non-isomorphic!) 3-regular graphs with 6 nodes are there? See also a table of results and a Java applet that can represent graphs geometrically. ; P95 (**) English number words ; On financial documents, like cheques, numbers must sometimes be written in full words. Example: 175 must be written as one-seven-five. Write a predicate full-words/1 to print (non-negative) integer numbers in full words. ; P96 (**) Syntax checker (alternative solution with difference lists) ; In a certain programming language (Ada) identifiers are defined by the syntax diagram (railroad chart) opposite. Transform the syntax diagram into a system of syntax diagrams which do not contain loops; i.e. which are purely recursive. Using these modified diagrams, write a predicate identifier/1 that can check whether or not a given string is a legal identifier. ; % identifier(Str) :- Str is a legal identifier ; P97 (**) Sudoku ; Sudoku puzzles go like this: ; Problem statement Solution ; . . 4 | 8 . . | . 1 7 9 3 4 | 8 2 5 | 6 1 7 ; | | | | ; 6 7 . | 9 . . | . . . 6 7 2 | 9 1 4 | 8 5 3 ; | | | | ; 5 . 8 | . 3 . | . . 4 5 1 8 | 6 3 7 | 9 2 4 ; --------+---------+-------- --------+---------+-------- ; 3 . . | 7 4 . | 1 . . 3 2 5 | 7 4 8 | 1 6 9 ; | | | | ; . 6 9 | . . . | 7 8 . 4 6 9 | 1 5 3 | 7 8 2 ; | | | | ; . . 1 | . 6 9 | . . 5 7 8 1 | 2 6 9 | 4 3 5 ; --------+---------+-------- --------+---------+-------- ; 1 . . | . 8 . | 3 . 6 1 9 7 | 5 8 2 | 3 4 6 ; | | | | ; . . . | . . 6 | . 9 1 8 5 3 | 4 7 6 | 2 9 1 ; | | | | ; 2 4 . | . . 1 | 5 . . 2 4 6 | 3 9 1 | 5 7 8 ; Every spot in the puzzle belongs to a (horizontal) row and a (vertical) column, as well as to one single 3x3 square (which we call "square" for short). At the beginning, some of the spots carry a single-digit number between 1 and 9. The problem is to fill the missing spots with digits in such a way that every number between 1 and 9 appears exactly once in each row, in each column, and in each square. ; P98 (***) Nonograms ; Around 1994, a certain kind of puzzles was very popular in England. The "Sunday Telegraph" newspaper wrote: "Nonograms are puzzles from Japan and are currently published each week only in The Sunday Telegraph. Simply use your logic and skill to complete the grid and reveal a picture or diagram." As a Prolog programmer, you are in a better situation: you can have your computer do the work! Just write a little program ;-). ; The puzzle goes like this: Essentially, each row and column of a rectangular bitmap is annotated with the respective lengths of its distinct strings of occupied cells. The person who solves the puzzle must complete the bitmap given only these lengths. ; Problem statement: Solution: ; |_|_|_|_|_|_|_|_| 3 |_|X|X|X|_|_|_|_| 3 ; |_|_|_|_|_|_|_|_| 2 1 |X|X|_|X|_|_|_|_| 2 1 ; |_|_|_|_|_|_|_|_| 3 2 |_|X|X|X|_|_|X|X| 3 2 ; |_|_|_|_|_|_|_|_| 2 2 |_|_|X|X|_|_|X|X| 2 2 ; |_|_|_|_|_|_|_|_| 6 |_|_|X|X|X|X|X|X| 6 ; |_|_|_|_|_|_|_|_| 1 5 |X|_|X|X|X|X|X|_| 1 5 ; |_|_|_|_|_|_|_|_| 6 |X|X|X|X|X|X|_|_| 6 ; |_|_|_|_|_|_|_|_| 1 |_|_|_|_|X|_|_|_| 1 ; |_|_|_|_|_|_|_|_| 2 |_|_|_|X|X|_|_|_| 2 ; 1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3 ; 2 1 5 1 2 1 5 1 ; For the example above, the problem can be stated as the two lists [[3],[2,1],[3,2],[2,2],[6],[1,5],[6],[1],[2]] and [[1,2],[3,1],[1,5],[7,1],[5],[3],[4],[3]] which give the "solid" lengths of the rows and columns, top-to-bottom and left-to-right, respectively. Published puzzles are larger than this example, e.g. 25 x 20, and apparently always have unique solutions. ; P99 (***) Crossword puzzle ; Given an empty (or almost empty) framework of a crossword puzzle and a set of words. The problem is to place the words into the framework. ; The particular crossword puzzle is specified in a text file which first lists the words (one word per line) in an arbitrary order. Then, after an empty line, the crossword framework is defined. In this framework specification, an empty character location is represented by a dot (.). In order to make the solution easier, character locations can also contain predefined character values. The puzzle opposite is defined in the file p99a.dat, other examples are p99b.dat and p99d.dat. There is also an example of a puzzle (p99c.dat) which does not have a solution. ; Words are strings (character lists) of at least two characters. A horizontal or vertical sequence of character places in the crossword puzzle framework is called a site. Our problem is to find a compatible way of placing words onto sites. ; Hints: (1) The problem is not easy. You will need some time to thoroughly understand it. So, don't give up too early! And remember that the objective is a clean solution, not just a quick-and-dirty hack! ; (2) Reading the data file is a tricky problem for which a solution is provided in the file p99-readfile.lisp. Use the predicate read_lines/2. ; (3) For efficiency reasons it is important, at least for larger puzzles, to sort the words and the sites in a particular order. For this part of the problem, the solution of P28 may be very helpful. ; Last modified: Mon Oct 16 21:23:19 BRT 2006 (run-tests)
true
(ns ninety-nine-problems (:use clojure.test)) ; L-99: Ninety-Nine Lisp Problems ; Based on a Prolog problem list by PI:EMAIL:<EMAIL>END_PI ; Working with lists ; P01 (*) Find the last box of a list. ; Example: ; * (my-last '(a b c d)) ; (D) (defn my-last [lst] (let [tail (next lst)] (if (nil? tail) lst (my-last tail)))) (deftest P01 (is (= (my-last '()) '())) (is (= (my-last '(1)) '(1))) (is (= (my-last '(1 2 3 4)) '(4)))) ; P02 (*) Find the last but one box of a list. ; Example: ; * (my-but-last '(a b c d)) ; (C D) (defn my-but-last [lst] (let [tail (next lst)] (if (nil? (next tail)) lst (my-but-last tail)))) (deftest P02 (is (= (my-but-last '()) '())) (is (= (my-but-last '(1)) '(1))) (is (= (my-but-last '(1 2)) '(1 2))) (is (= (my-but-last '(1 2 3)) '(2 3))) (is (= (my-but-last '(1 2 3 4)) '(3 4)))) ; P03 (*) Find the K'th element of a list. ; The first element in the list is number 1. ; Example: ; * (element-at '(a b c d e) 3) ; C (defn element-at [lst pos] (if (= pos 1) (first lst) (element-at (next lst) (- pos 1)))) (deftest P03 (is (= (element-at '() 1) nil)) (is (= (element-at '(1) 1) 1)) (is (= (element-at '(1 2) 1) 1)) (is (= (element-at '(1 2) 2) 2)) (is (= (element-at '(1 2) 3) nil)) (is (= (element-at '(1 2 3 4) 3) 3))) ; P04 (*) Find the number of elements of a list. (defn len [lst] ((fn [lst counter] (if (empty? lst) counter (recur (next lst) (+ counter 1)))) lst 0)) (deftest P04 (is (= (len '()) 0)) (is (= (len '(2)) 1)) (is (= (len '(1 2 3 4)) 4))) ; P05 (*) Reverse a list. (defn rev [lst] ((fn [inp out] (if (empty? inp) out (recur (next inp) (conj out (first inp))))) lst '())) (deftest P05 (is (= (rev '()) '())) (is (= (rev '(1)) '(1))) (is (= (rev '(1 2 3)) '(3 2 1)))) ; P06 (*) Find out whether a list is a palindrome. ; A palindrome can be read forward or backward; e.g. (x a m a x). (defn is-palindrome [lst] ((fn [fwd bwd] (if (empty? fwd) true (if (not= (first fwd) (first bwd)) false (recur (next fwd) (next bwd))))) lst (rev lst))) (deftest P06 (is (true? (is-palindrome '()))) (is (true? (is-palindrome '(1)))) (is (false? (is-palindrome '(1 2 3)))) (is (true? (is-palindrome '(2 3 1 3 2))))) ; P07 (**) Flatten a nested list structure. ; Transform a list, possibly holding lists as elements into a `flat' list by replacing each list with its elements (recursively). ; Example: ; * (my-flatten '(a (b (c d) e))) ; (A B C D E) ; Hint: Use the predefined functions list and append. (declare collect-flatten my-flatten) (defn collect-flatten [inp out] (if (empty? inp) (reverse out) (recur (next inp) (if (list? (first inp)) (concat (my-flatten (first inp)) out) (conj out (first inp)))))) (defn my-flatten [lst] (collect-flatten lst '())) (deftest P07 (is (= (my-flatten '()) '())) (is (= (my-flatten '(1)) '(1))) (is (= (my-flatten '(1 '(2 3))) '(1 2 3))) (is (= (my-flatten '(1 '(2 '(3 4) 5))) '(1 2 3 4 5)))) ; P08 (**) Eliminate consecutive duplicates of list elements. ; If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed. ; Example: ; * (compress '(a a a a b c c a a d e e e e)) ; (A B C A D E) ; P09 (**) Pack consecutive duplicates of list elements into sublists. ; If a list contains repeated elements they should be placed in separate sublists. ; Example: ; * (pack '(a a a a b c c a a d e e e e)) ; ((A A A A) (B) (C C) (A A) (D) (E E E E)) ; P10 (*) Run-length encoding of a list. ; Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as lists (N E) where N is the number of duplicates of the element E. ; Example: ; * (encode '(a a a a b c c a a d e e e e)) ; ((4 A) (1 B) (2 C) (2 A) (1 D)(4 E)) ; P11 (*) Modified run-length encoding. ; Modify the result of problem P10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as (N E) lists. ; Example: ; * (encode-modified '(a a a a b c c a a d e e e e)) ; ((4 A) B (2 C) (2 A) D (4 E)) ; P12 (**) Decode a run-length encoded list. ; Given a run-length code list generated as specified in problem P11. Construct its uncompressed version. ; P13 (**) Run-length encoding of a list (direct solution). ; Implement the so-called run-length encoding data compression method directly. I.e. don't explicitly create the sublists containing the duplicates, as in problem P09, but only count them. As in problem P11, simplify the result list by replacing the singleton lists (1 X) by X. ; Example: ; * (encode-direct '(a a a a b c c a a d e e e e)) ; ((4 A) B (2 C) (2 A) D (4 E)) ; P14 (*) Duplicate the elements of a list. ; Example: ; * (dupli '(a b c c d)) ; (A A B B C C C C D D) ; P15 (**) Replicate the elements of a list a given number of times. ; Example: ; * (repli '(a b c) 3) ; (A A A B B B C C C) ; P16 (**) Drop every N'th element from a list. ; Example: ; * (drop '(a b c d e f g h i k) 3) ; (A B D E G H K) ; P17 (*) Split a list into two parts; the length of the first part is given. ; Do not use any predefined predicates. ; Example: ; * (split '(a b c d e f g h i k) 3) ; ( (A B C) (D E F G H I K)) ; P18 (**) Extract a slice from a list. ; Given two indices, I and K, the slice is the list containing the elements between the I'th and K'th element of the original list (both limits included). Start counting the elements with 1. ; Example: ; * (slice '(a b c d e f g h i k) 3 7) ; (C D E F G) ; P19 (**) Rotate a list N places to the left. ; Examples: ; * (rotate '(a b c d e f g h) 3) ; (D E F G H A B C) ; * (rotate '(a b c d e f g h) -2) ; (G H A B C D E F) ; Hint: Use the predefined functions length and append, as well as the result of problem P17. ; P20 (*) Remove the K'th element from a list. ; Example: ; * (remove-at '(a b c d) 2) ; (A C D) ; P21 (*) Insert an element at a given position into a list. ; Example: ; * (insert-at 'alfa '(a b c d) 2) ; (A ALFA B C D) ; P22 (*) Create a list containing all integers within a given range. ; If first argument is smaller than second, produce a list in decreasing order. ; Example: ; * (range 4 9) ; (4 5 6 7 8 9) ; P23 (**) Extract a given number of randomly selected elements from a list. ; The selected items shall be returned in a list. ; Example: ; * (rnd-select '(a b c d e f g h) 3) ; (E D A) ; Hint: Use the built-in random number generator and the result of problem P20. ; P24 (*) Lotto: Draw N different random numbers from the set 1..M. ; The selected numbers shall be returned in a list. ; Example: ; * (lotto-select 6 49) ; (23 1 17 33 21 37) ; Hint: Combine the solutions of problems P22 and P23. ; P25 (*) Generate a random permutation of the elements of a list. ; Example: ; * (rnd-permu '(a b c d e f)) ; (B A D C E F) ; Hint: Use the solution of problem P23. ; P26 (**) Generate the combinations of K distinct objects chosen from the N elements of a list ; In how many ways can a committee of 3 be chosen from a group of 12 people? We all know that there are C(12,3) = 220 possibilities (C(N,K) denotes the well-known binomial coefficients). For pure mathematicians, this result may be great. But we want to really generate all the possibilities in a list. ; Example: ; * (combination 3 '(a b c d e f)) ; ((A B C) (A B D) (A B E) ... ) ; P27 (**) Group the elements of a set into disjoint subsets. ; a) In how many ways can a group of 9 people work in 3 disjoint subgroups of 2, 3 and 4 persons? Write a function that generates all the possibilities and returns them in a list. ; Example: ; * (group3 '(aldo beat PI:NAME:<NAME>END_PI dPI:NAME:<NAME>END_PI evi flip gary hugo ida)) ; ( ( (PI:NAME:<NAME>END_PI BEAT) (PI:NAME:<NAME>END_PI EPI:NAME:<NAME>END_PI) (FLIP GPI:NAME:<NAME>END_PI HPI:NAME:<NAME>END_PI IDA) ) ; ... ) ; b) Generalize the above predicate in a way that we can specify a list of group sizes and the predicate will return a list of groups. ; Example: ; * (group '(aldo beat PI:NAME:<NAME>END_PI david PI:NAME:<NAME>END_PI ida) '(2 2 5)) ; ( ( (PI:NAME:<NAME>END_PI) (PI:NAME:<NAME>END_PI) (PI:NAME:<NAME>END_PI IDPI:NAME:<NAME>END_PI) ) ; ... ) ; Note that we do not want permutations of the group members; i.e. ((ALDO BEAT) ...) is the same solution as ((BEAT ALDO) ...). However, we make a difference between ((ALDO BEAT) (PI:NAME:<NAME>END_PI DAVPI:NAME:<NAME>END_PI) ...) and ((PI:NAME:<NAME>END_PI) (ALDO BEAT) ...). ; You may find more about this combinatorial problem in a good book on discrete mathematics under the term "multinomial coefficients". ; P28 (**) Sorting a list of lists according to length of sublists ; a) We suppose that a list contains elements that are lists themselves. The objective is to sort the elements of this list according to their length. E.g. short lists first, longer lists later, or vice versa. ; Example: ; * (lsort '((a b c) (d e) (f g h) (d e) (i j k l) (m n) (o))) ; ((O) (D E) (D E) (M N) (A B C) (F G H) (I J K L)) ; b) Again, we suppose that a list contains elements that are lists themselves. But this time the objective is to sort the elements of this list according to their length frequency; i.e., in the default, where sorting is done ascendingly, lists with rare lengths are placed first, others with a more frequent length come later. ; Example: ; * (lfsort '((a b c) (d e) (f g h) (d e) (i j k l) (m n) (o))) ; ((i j k l) (o) (a b c) (f g h) (d e) (d e) (m n)) ; Note that in the above example, the first two lists in the result have length 4 and 1, both lengths appear just once. The third and forth list have length 3 which appears twice (there are two list of this length). And finally, the last three lists have length 2. This is the most frequent length. ; Arithmetic ; P31 (**) Determine whether a given integer number is prime. ; Example: ; * (is-prime 7) ; T ; P32 (**) Determine the greatest common divisor of two positive integer numbers. ; Use Euclid's algorithm. ; Example: ; * (gcd 36 63) ; 9 ; P33 (*) Determine whether two positive integer numbers are coprime. ; Two numbers are coprime if their greatest common divisor equals 1. ; Example: ; * (coprime 35 64) ; T ; P34 (**) Calculate Euler's totient function phi(m). ; Euler's so-called totient function phi(m) is defined as the number of positive integers r (1 <= r < m) that are coprime to m. ; Example: m = 10: r = 1,3,7,9; thus phi(m) = 4. Note the special case: phi(1) = 1. ; * (totient-phi 10) ; 4 ; Find out what the value of phi(m) is if m is a prime number. Euler's totient function plays an important role in one of the most widely used public key cryptography methods (RSA). In this exercise you should use the most primitive method to calculate this function (there are smarter ways that we shall discuss later). ; P35 (**) Determine the prime factors of a given positive integer. ; Construct a flat list containing the prime factors in ascending order. ; Example: ; * (prime-factors 315) ; (3 3 5 7) ; P36 (**) Determine the prime factors of a given positive integer (2). ; Construct a list containing the prime factors and their multiplicity. ; Example: ; * (prime-factors-mult 315) ; ((3 2) (5 1) (7 1)) ; Hint: The problem is similar to problem P13. ; P37 (**) Calculate Euler's totient function phi(m) (improved). ; See problem P34 for the definition of Euler's totient function. If the list of the prime factors of a number m is known in the form of problem P36 then the function phi(m) can be efficiently calculated as follows: Let ((p1 m1) (p2 m2) (p3 m3) ...) be the list of prime factors (and their multiplicities) of a given number m. Then phi(m) can be calculated with the following formula: ; phi(m) = (p1 - 1) * p1 ** (m1 - 1) + (p2 - 1) * p2 ** (m2 - 1) + (p3 - 1) * p3 ** (m3 - 1) + ... ; Note that a ** b stands for the b'th power of a. ; P38 (*) Compare the two methods of calculating Euler's totient function. ; Use the solutions of problems P34 and P37 to compare the algorithms. Take the number of logical inferences as a measure for efficiency. Try to calculate phi(10090) as an example. ; P39 (*) A list of prime numbers. ; Given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range. ; P40 (**) Goldbach's conjecture. ; Goldbach's conjecture says that every positive even number greater than 2 is the sum of two prime numbers. Example: 28 = 5 + 23. It is one of the most famous facts in number theory that has not been proved to be correct in the general case. It has been numerically confirmed up to very large numbers (much larger than we can go with our Prolog system). Write a predicate to find the two prime numbers that sum up to a given even integer. ; Example: ; * (goldbach 28) ; (5 23) ; P41 (**) A list of Goldbach compositions. ; Given a range of integers by its lower and upper limit, print a list of all even numbers and their Goldbach composition. ; Example: ; * (goldbach-list 9 20) ; 10 = 3 + 7 ; 12 = 5 + 7 ; 14 = 3 + 11 ; 16 = 3 + 13 ; 18 = 5 + 13 ; 20 = 3 + 17 ; In most cases, if an even number is written as the sum of two prime numbers, one of them is very small. Very rarely, the primes are both bigger than say 50. Try to find out how many such cases there are in the range 2..3000. ; Example (for a print limit of 50): ; * (goldbach-list 1 2000 50) ; 992 = 73 + 919 ; 1382 = 61 + 1321 ; 1856 = 67 + 1789 ; 1928 = 61 + 1867 ; Logic and Codes ; P46 (**) Truth tables for logical expressions. ; Define predicates and/2, or/2, nand/2, nor/2, xor/2, impl/2 and equ/2 (for logical equivalence) which succeed or fail according to the result of their respective operations; e.g. and(A,B) will succeed, if and only if both A and B succeed. Note that A and B can be Prolog goals (not only the constants true and fail). ; A logical expression in two variables can then be written in prefix notation, as in the following example: and(or(A,B),nand(A,B)). ; Now, write a predicate table/3 which prints the truth table of a given logical expression in two variables. ; Example: ; * table(A,B,and(A,or(A,B))). ; true true true ; true fail true ; fail true fail ; fail fail fail ; P47 (*) Truth tables for logical expressions (2). ; Continue problem P46 by defining and/2, or/2, etc as being operators. This allows to write the logical expression in the more natural way, as in the example: A and (A or not B). Define operator precedence as usual; i.e. as in Java. ; Example: ; * table(A,B, A and (A or not B)). ; true true true ; true fail true ; fail true fail ; fail fail fail ; P48 (**) Truth tables for logical expressions (3). ; Generalize problem P47 in such a way that the logical expression may contain any number of logical variables. Define table/2 in a way that table(List,Expr) prints the truth table for the expression Expr, which contains the logical variables enumerated in List. ; Example: ; * table([A,B,C], A and (B or C) equ A and B or A and C). ; true true true true ; true true fail true ; true fail true true ; true fail fail true ; fail true true true ; fail true fail true ; fail fail true true ; fail fail fail true ; P49 (**) Gray code. ; An n-bit Gray code is a sequence of n-bit strings constructed according to certain rules. For example, ; n = 1: C(1) = ['0','1']. ; n = 2: C(2) = ['00','01','11','10']. ; n = 3: C(3) = ['000','001','011','010',´110´,´111´,´101´,´100´]. ; Find out the construction rules and write a predicate with the following specification: ; % gray(N,C) :- C is the N-bit Gray code ; Can you apply the method of "result caching" in order to make the predicate more efficient, when it is to be used repeatedly? ; P50 (***) Huffman code. ; First of all, consult a good book on discrete mathematics or algorithms for a detailed description of Huffman codes! ; We suppose a set of symbols with their frequencies, given as a list of fr(S,F) terms. Example: [fr(a,45),fr(b,13),fr(c,12),fr(d,16),fr(e,9),fr(f,5)]. Our objective is to construct a list hc(S,C) terms, where C is the Huffman code word for the symbol S. In our example, the result could be Hs = [hc(a,'0'), hc(b,'101'), hc(c,'100'), hc(d,'111'), hc(e,'1101'), hc(f,'1100')] [hc(a,'01'),...etc.]. The task shall be performed by the predicate huffman/2 defined as follows: ; % huffman(Fs,Hs) :- Hs is the Huffman code table for the frequency table Fs ; Binary Trees ; A binary tree is either empty or it is composed of a root element and two successors, which are binary trees themselves. ; In Lisp we represent the empty tree by 'nil' and the non-empty tree by the list (X L R), where X denotes the root node and L and R denote the left and right subtree, respectively. The example tree depicted opposite is therefore represented by the following list: ; (a (b (d nil nil) (e nil nil)) (c nil (f (g nil nil) nil))) ; Other examples are a binary tree that consists of a root node only: ; (a nil nil) or an empty binary tree: nil. ; You can check your predicates using these example trees. They are given as test cases in p54.lisp. ; P54A (*) Check whether a given term represents a binary tree ; Write a predicate istree which returns true if and only if its argument is a list representing a binary tree. ; Example: ; * (istree (a (b nil nil) nil)) ; T ; * (istree (a (b nil nil))) ; NIL ; P55 (**) Construct completely balanced binary trees ; In a completely balanced binary tree, the following property holds for every node: The number of nodes in its left subtree and the number of nodes in its right subtree are almost equal, which means their difference is not greater than one. ; Write a function cbal-tree to construct completely balanced binary trees for a given number of nodes. The predicate should generate all solutions via backtracking. Put the letter 'x' as information into all nodes of the tree. ; Example: ; * cbal-tree(4,T). ; T = t(x, t(x, nil, nil), t(x, nil, t(x, nil, nil))) ; ; T = t(x, t(x, nil, nil), t(x, t(x, nil, nil), nil)) ; ; etc......No ; P56 (**) Symmetric binary trees ; Let us call a binary tree symmetric if you can draw a vertical line through the root node and then the right subtree is the mirror image of the left subtree. Write a predicate symmetric/1 to check whether a given binary tree is symmetric. Hint: Write a predicate mirror/2 first to check whether one tree is the mirror image of another. We are only interested in the structure, not in the contents of the nodes. ; P57 (**) Binary search trees (dictionaries) ; Use the predicate add/3, developed in chapter 4 of the course, to write a predicate to construct a binary search tree from a list of integer numbers. ; Example: ; * construct([3,2,5,7,1],T). ; T = t(3, t(2, t(1, nil, nil), nil), t(5, nil, t(7, nil, nil))) ; Then use this predicate to test the solution of the problem P56. ; Example: ; * test-symmetric([5,3,18,1,4,12,21]). ; Yes ; * test-symmetric([3,2,5,7,1]). ; No ; P58 (**) Generate-and-test paradigm ; Apply the generate-and-test paradigm to construct all symmetric, completely balanced binary trees with a given number of nodes. Example: ; * sym-cbal-trees(5,Ts). ; Ts = [t(x, t(x, nil, t(x, nil, nil)), t(x, t(x, nil, nil), nil)), t(x, t(x, t(x, nil, nil), nil), t(x, nil, t(x, nil, nil)))] ; How many such trees are there with 57 nodes? Investigate about how many solutions there are for a given number of nodes? What if the number is even? Write an appropriate predicate. ; P59 (**) Construct height-balanced binary trees ; In a height-balanced binary tree, the following property holds for every node: The height of its left subtree and the height of its right subtree are almost equal, which means their difference is not greater than one. ; Write a predicate hbal-tree/2 to construct height-balanced binary trees for a given height. The predicate should generate all solutions via backtracking. Put the letter 'x' as information into all nodes of the tree. ; Example: ; * hbal-tree(3,T). ; T = t(x, t(x, t(x, nil, nil), t(x, nil, nil)), t(x, t(x, nil, nil), t(x, nil, nil))) ; ; T = t(x, t(x, t(x, nil, nil), t(x, nil, nil)), t(x, t(x, nil, nil), nil)) ; ; etc......No ; P60 (**) Construct height-balanced binary trees with a given number of nodes ; Consider a height-balanced binary tree of height H. What is the maximum number of nodes it can contain? ; Clearly, MaxN = 2**H - 1. However, what is the minimum number MinN? This question is more difficult. Try to find a recursive statement and turn it into a predicate minNodes/2 defined as follwos: ; % minNodes(H,N) :- N is the minimum number of nodes in a height-balanced binary tree of height H. ; (integer,integer), (+,?) ; On the other hand, we might ask: what is the maximum height H a height-balanced binary tree with N nodes can have? ; % maxHeight(N,H) :- H is the maximum height of a height-balanced binary tree with N nodes ; (integer,integer), (+,?) ; Now, we can attack the main problem: construct all the height-balanced binary trees with a given nuber of nodes. ; % hbal-tree-nodes(N,T) :- T is a height-balanced binary tree with N nodes. ; Find out how many height-balanced trees exist for N = 15. ; P61 (*) Count the leaves of a binary tree ; A leaf is a node with no successors. Write a predicate count-leaves/2 to count them. ; % count-leaves(T,N) :- the binary tree T has N leaves ; P61A (*) Collect the leaves of a binary tree in a list ; A leaf is a node with no successors. Write a predicate leaves/2 to collect them in a list. ; % leaves(T,S) :- S is the list of all leaves of the binary tree T ; P62 (*) Collect the internal nodes of a binary tree in a list ; An internal node of a binary tree has either one or two non-empty successors. Write a predicate internals/2 to collect them in a list. ; % internals(T,S) :- S is the list of internal nodes of the binary tree T. ; P62B (*) Collect the nodes at a given level in a list ; A node of a binary tree is at level N if the path from the root to the node has length N-1. The root node is at level 1. Write a predicate atlevel/3 to collect all nodes at a given level in a list. ; % atlevel(T,L,S) :- S is the list of nodes of the binary tree T at level L ; Using atlevel/3 it is easy to construct a predicate levelorder/2 which creates the level-order sequence of the nodes. However, there are more efficient ways to do that. ; P63 (**) Construct a complete binary tree ; A complete binary tree with height H is defined as follows: The levels 1,2,3,...,H-1 contain the maximum number of nodes (i.e 2**(i-1) at the level i, note that we start counting the levels from 1 at the root). In level H, which may contain less than the maximum possible number of nodes, all the nodes are "left-adjusted". This means that in a levelorder tree traversal all internal nodes come first, the leaves come second, and empty successors (the nil's which are not really nodes!) come last. ; Particularly, complete binary trees are used as data structures (or addressing schemes) for heaps. ; We can assign an address number to each node in a complete binary tree by enumerating the nodes in levelorder, starting at the root with number 1. In doing so, we realize that for every node X with address A the following property holds: The address of X's left and right successors are 2*A and 2*A+1, respectively, supposed the successors do exist. This fact can be used to elegantly construct a complete binary tree structure. Write a predicate complete-binary-tree/2 with the following specification: ; % complete-binary-tree(N,T) :- T is a complete binary tree with N nodes. (+,?) ; Test your predicate in an appropriate way. ; P64 (**) Layout a binary tree (1) ; Given a binary tree as the usual Prolog term t(X,L,R) (or nil). As a preparation for drawing the tree, a layout algorithm is required to determine the position of each node in a rectangular grid. Several layout methods are conceivable, one of them is shown in the illustration below. ; In this layout strategy, the position of a node v is obtained by the following two rules: ; x(v) is equal to the position of the node v in the inorder sequence ; y(v) is equal to the depth of the node v in the tree ; In order to store the position of the nodes, we extend the Prolog term representing a node (and its successors) as follows: ; % nil represents the empty tree (as usual) ; % t(W,X,Y,L,R) represents a (non-empty) binary tree with root W "positioned" at (X,Y), and subtrees L and R ; Write a predicate layout-binary-tree/2 with the following specification: ; % layout-binary-tree(T,PT) :- PT is the "positioned" binary tree obtained from the binary tree T. (+,?) ; Test your predicate in an appropriate way. ; P65 (**) Layout a binary tree (2) ; An alternative layout method is depicted in the illustration opposite. Find out the rules and write the corresponding Prolog predicate. Hint: On a given level, the horizontal distance between neighboring nodes is constant. ; Use the same conventions as in problem P64 and test your predicate in an appropriate way. ; P66 (***) Layout a binary tree (3) ; Yet another layout strategy is shown in the illustration opposite. The method yields a very compact layout while maintaining a certain symmetry in every node. Find out the rules and write the corresponding Prolog predicate. Hint: Consider the horizontal distance between a node and its successor nodes. How tight can you pack together two subtrees to construct the combined binary tree? ; Use the same conventions as in problem P64 and P65 and test your predicate in an appropriate way. Note: This is a difficult problem. Don't give up too early! ; Which layout do you like most? ; P67 (**) A string representation of binary trees ; Somebody represents binary trees as strings of the following type (see example opposite): ; a(b(d,e),c(,f(g,))) ; a) Write a Prolog predicate which generates this string representation, if the tree is given as usual (as nil or t(X,L,R) term). Then write a predicate which does this inverse; i.e. given the string representation, construct the tree in the usual form. Finally, combine the two predicates in a single predicate tree-string/2 which can be used in both directions. ; b) Write the same predicate tree-string/2 using difference lists and a single predicate tree-dlist/2 which does the conversion between a tree and a difference list in both directions. ; For simplicity, suppose the information in the nodes is a single letter and there are no spaces in the string. ; P68 (**) Preorder and inorder sequences of binary trees ; We consider binary trees with nodes that are identified by single lower-case letters, as in the example of problem P67. ; a) Write predicates preorder/2 and inorder/2 that construct the preorder and inorder sequence of a given binary tree, respectively. The results should be atoms, e.g. 'abdecfg' for the preorder sequence of the example in problem P67. ; b) Can you use preorder/2 from problem part a) in the reverse direction; i.e. given a preorder sequence, construct a corresponding tree? If not, make the necessary arrangements. ; c) If both the preorder sequence and the inorder sequence of the nodes of a binary tree are given, then the tree is determined unambiguously. Write a predicate pre-in-tree/3 that does the job. ; d) Solve problems a) to c) using difference lists. Cool! Use the predefined predicate time/1 to compare the solutions. ; What happens if the same character appears in more than one node. Try for instance pre-in-tree(aba,baa,T). ; P69 (**) Dotstring representation of binary trees ; We consider again binary trees with nodes that are identified by single lower-case letters, as in the example of problem P67. Such a tree can be represented by the preorder sequence of its nodes in which dots (.) are inserted where an empty subtree (nil) is encountered during the tree traversal. For example, the tree shown in problem P67 is represented as 'abd..e..c.fg...'. First, try to establish a syntax (BNF or syntax diagrams) and then write a predicate tree-dotstring/2 which does the conversion in both directions. Use difference lists. ; Multiway Trees ; A multiway tree is composed of a root element and a (possibly empty) set of successors which are multiway trees themselves. A multiway tree is never empty. The set of successor trees is sometimes called a forest. ; In Prolog we represent a multiway tree by a term t(X,F), where X denotes the root node and F denotes the forest of successor trees (a Prolog list). The example tree depicted opposite is therefore represented by the following Prolog term: ; T = t(a,[t(f,[t(g,[])]),t(c,[]),t(b,[t(d,[]),t(e,[])])]) ; P70B (*) Check whether a given term represents a multiway tree ; Write a predicate istree/1 which succeeds if and only if its argument is a Prolog term representing a multiway tree. ; Example: ; * istree(t(a,[t(f,[t(g,[])]),t(c,[]),t(b,[t(d,[]),t(e,[])])])). ; Yes ; P70C (*) Count the nodes of a multiway tree ; Write a predicate nnodes/1 which counts the nodes of a given multiway tree. ; Example: ; * nnodes(t(a,[t(f,[])]),N). ; N = 2 ; Write another version of the predicate that allows for a flow pattern (o,i). ; P70 (**) Tree construction from a node string ; We suppose that the nodes of a multiway tree contain single characters. In the depth-first order sequence of its nodes, a special character ^ has been inserted whenever, during the tree traversal, the move is a backtrack to the previous level. ; By this rule, the tree in the figure opposite is represented as: afg^^c^bd^e^^^ ; Define the syntax of the string and write a predicate tree(String,Tree) to construct the Tree when the String is given. Work with atoms (instead of strings). Make your predicate work in both directions. ; P71 (*) Determine the internal path length of a tree ; We define the internal path length of a multiway tree as the total sum of the path lengths from the root to all nodes of the tree. By this definition, the tree in the figure of problem P70 has an internal path length of 9. Write a predicate ipl(Tree,IPL) for the flow pattern (+,-). ; P72 (*) Construct the bottom-up order sequence of the tree nodes ; Write a predicate bottom-up(Tree,Seq) which constructs the bottom-up sequence of the nodes of the multiway tree Tree. Seq should be a Prolog list. What happens if you run your predicate backwords? ; P73 (**) Lisp-like tree representation ; There is a particular notation for multiway trees in Lisp. Lisp is a prominent functional programming language, which is used primarily for artificial intelligence problems. As such it is one of the main competitors of Prolog. In Lisp almost everything is a list, just as in Prolog everything is a term. ; The following pictures show how multiway tree structures are represented in Lisp. ; Note that in the "lispy" notation a node with successors (children) in the tree is always the first element in a list, followed by its children. The "lispy" representation of a multiway tree is a sequence of atoms and parentheses '(' and ')', which we shall collectively call "tokens". We can represent this sequence of tokens as a Prolog list; e.g. the lispy expression (a (b c)) could be represented as the Prolog list ['(', a, '(', b, c, ')', ')']. Write a predicate tree-ltl(T,LTL) which constructs the "lispy token list" LTL if the tree is given as term T in the usual Prolog notation. ; Example: ; * tree-ltl(t(a,[t(b,[]),t(c,[])]),LTL). ; LTL = ['(', a, '(', b, c, ')', ')'] ; As a second, even more interesting exercise try to rewrite tree-ltl/2 in a way that the inverse conversion is also possible: Given the list LTL, construct the Prolog tree T. Use difference lists. ; Graphs ; A graph is defined as a set of nodes and a set of edges, where each edge is a pair of nodes. ; There are several ways to represent graphs in Prolog. One method is to represent each edge separately as one clause (fact). In this form, the graph depicted below is represented as the following predicate: ; edge(h,g). ; edge(k,f). ; edge(f,b). ; ... ; We call this edge-clause form. Obviously, isolated nodes cannot be represented. Another method is to represent the whole graph as one data object. According to the definition of the graph as a pair of two sets (nodes and edges), we may use the following Prolog term to represent the example graph: ; graph([b,c,d,f,g,h,k],[e(b,c),e(b,f),e(c,f),e(f,k),e(g,h)]) ; We call this graph-term form. Note, that the lists are kept sorted, they are really sets, without duplicated elements. Each edge appears only once in the edge list; i.e. an edge from a node x to another node y is represented as e(x,y), the term e(y,x) is not present. The graph-term form is our default representation. In SWI-Prolog there are predefined predicates to work with sets. ; A third representation method is to associate with each node the set of nodes that are adjacent to that node. We call this the adjacency-list form. In our example: ; [n(b,[c,f]), n(c,[b,f]), n(d,[]), n(f,[b,c,k]), ...] ; The representations we introduced so far are Prolog terms and therefore well suited for automated processing, but their syntax is not very user-friendly. Typing the terms by hand is cumbersome and error-prone. We can define a more compact and "human-friendly" notation as follows: A graph is represented by a list of atoms and terms of the type X-Y (i.e. functor '-' and arity 2). The atoms stand for isolated nodes, the X-Y terms describe edges. If an X appears as an endpoint of an edge, it is automatically defined as a node. Our example could be written as: ; [b-c, f-c, g-h, d, f-b, k-f, h-g] ; We call this the human-friendly form. As the example shows, the list does not have to be sorted and may even contain the same edge multiple times. Notice the isolated node d. (Actually, isolated nodes do not even have to be atoms in the Prolog sense, they can be compound terms, as in d(3.75,blue) instead of d in the example). ; When the edges are directed we call them arcs. These are represented by ordered pairs. Such a graph is called directed graph. To represent a directed graph, the forms discussed above are slightly modified. The example graph opposite is represented as follows: ; Arc-clause form ; arc(s,u). ; arc(u,r). ; ... ; Graph-term form ; digraph([r,s,t,u,v],[a(s,r),a(s,u),a(u,r),a(u,s),a(v,u)]) ; Adjacency-list form ; [n(r,[]),n(s,[r,u]),n(t,[]),n(u,[r]),n(v,[u])] ; Note that the adjacency-list does not have the information on whether it is a graph or a digraph. ; Human-friendly form ; [s > r, t, u > r, s > u, u > s, v > u] ; Finally, graphs and digraphs may have additional information attached to nodes and edges (arcs). For the nodes, this is no problem, as we can easily replace the single character identifiers with arbitrary compound terms, such as city('London',4711). On the other hand, for edges we have to extend our notation. Graphs with additional information attached to edges are called labelled graphs. ; Arc-clause form ; arc(m,q,7). ; arc(p,q,9). ; arc(p,m,5). ; Graph-term form ; digraph([k,m,p,q],[a(m,p,7),a(p,m,5),a(p,q,9)]) ; Adjacency-list form ; [n(k,[]),n(m,[q/7]),n(p,[m/5,q/9]),n(q,[])] ; Notice how the edge information has been packed into a term with functor '/' and arity 2, together with the corresponding node. ; Human-friendly form ; [p>q/9, m>q/7, k, p>m/5] ; The notation for labelled graphs can also be used for so-called multi-graphs, where more than one edge (or arc) are allowed between two given nodes. ; P80 (***) Conversions ; Write predicates to convert between the different graph representations. With these predicates, all representations are equivalent; i.e. for the following problems you can always pick freely the most convenient form. The reason this problem is rated (***) is not because it's particularly difficult, but because it's a lot of work to deal with all the special cases. ; P81 (**) Path from one node to another one ; Write a predicate path(G,A,B,P) to find an acyclic path P from node A to node b in the graph G. The predicate should return all paths via backtracking. ; P82 (*) Cycle from a given node ; Write a predicate cycle(G,A,P) to find a closed path (cycle) P starting at a given node A in the graph G. The predicate should return all cycles via backtracking. ; P83 (**) Construct all spanning trees ; Write a predicate s-tree(Graph,Tree) to construct (by backtracking) all spanning trees of a given graph. With this predicate, find out how many spanning trees there are for the graph depicted to the left. The data of this example graph can be found in the file p83.dat. When you have a correct solution for the s-tree/2 predicate, use it to define two other useful predicates: is-tree(Graph) and is-connected(Graph). Both are five-minutes tasks! ; P84 (**) Construct the minimal spanning tree ; Write a predicate ms-tree(Graph,Tree,Sum) to construct the minimal spanning tree of a given labelled graph. Hint: Use the algorithm of Prim. A small modification of the solution of P83 does the trick. The data of the example graph to the right can be found in the file p84.dat. ; P85 (**) Graph isomorphism ; Two graphs G1(N1,E1) and G2(N2,E2) are isomorphic if there is a bijection f: N1 -> N2 such that for any nodes X,Y of N1, X and Y are adjacent if and only if f(X) and f(Y) are adjacent. ; Write a predicate that determines whether two graphs are isomorphic. Hint: Use an open-ended list to represent the function f. ; P86 (**) Node degree and graph coloration ; a) Write a predicate degree(Graph,Node,Deg) that determines the degree of a given node. ; b) Write a predicate that generates a list of all nodes of a graph sorted according to decreasing degree. ; c) Use Welch-Powell's algorithm to paint the nodes of a graph in such a way that adjacent nodes have different colors. ; P87 (**) Depth-first order graph traversal (alternative solution) ; Write a predicate that generates a depth-first order graph traversal sequence. The starting point should be specified, and the output should be a list of nodes that are reachable from this starting point (in depth-first order). ; P88 (**) Connected components (alternative solution) ; Write a predicate that splits a graph into its connected components. ; P89 (**) Bipartite graphs ; Write a predicate that finds out whether a given graph is bipartite. ; Miscellaneous Problems ; P90 (**) Eight queens problem ; This is a classical problem in computer science. The objective is to place eight queens on a chessboard so that no two queens are attacking each other; i.e., no two queens are in the same row, the same column, or on the same diagonal. ; Hint: Represent the positions of the queens as a list of numbers 1..N. Example: [4,2,7,3,6,8,5,1] means that the queen in the first column is in row 4, the queen in the second column is in row 2, etc. Use the generate-and-test paradigm. ; P91 (**) Knight's tour ; Another famous problem is this one: How can a knight jump on an NxN chessboard in such a way that it visits every square exactly once? ; Hints: Represent the squares by pairs of their coordinates of the form X/Y, where both X and Y are integers between 1 and N. (Note that '/' is just a convenient functor, not division!) Define the relation jump(N,X/Y,U/V) to express the fact that a knight can jump from X/Y to U/V on a NxN chessboard. And finally, represent the solution of our problem as a list of N*N knight positions (the knight's tour). ; P92 (***) PI:NAME:<NAME>END_PI Koch's conjecture ; Several years ago I met a mathematician who was intrigued by a problem for which he didn't know a solution. His name was PI:NAME:<NAME>END_PI, and I don't know whether the problem has been solved since. ; Anyway the puzzle goes like this: Given a tree with N nodes (and hence N-1 edges). Find a way to enumerate the nodes from 1 to N and, accordingly, the edges from 1 to N-1 in such a way, that for each edge K the difference of its node numbers equals to K. The conjecture is that this is always possible. ; For small trees the problem is easy to solve by hand. However, for larger trees, and 14 is already very large, it is extremely difficult to find a solution. And remember, we don't know for sure whether there is always a solution! ; Write a predicate that calculates a numbering scheme for a given tree. What is the solution for the larger tree pictured above? ; P93 (***) An arithmetic puzzle ; Given a list of integer numbers, find a correct way of inserting arithmetic signs (operators) such that the result is a correct equation. Example: With the list of numbers [2,3,5,7,11] we can form the equations 2-3+5+7 = 11 or 2 = (3*5+7)/11 (and ten others!). ; P94 (***) Generate K-regular simple graphs with N nodes ; In a K-regular graph all nodes have a degree of K; i.e. the number of edges incident in each node is K. How many (non-isomorphic!) 3-regular graphs with 6 nodes are there? See also a table of results and a Java applet that can represent graphs geometrically. ; P95 (**) English number words ; On financial documents, like cheques, numbers must sometimes be written in full words. Example: 175 must be written as one-seven-five. Write a predicate full-words/1 to print (non-negative) integer numbers in full words. ; P96 (**) Syntax checker (alternative solution with difference lists) ; In a certain programming language (Ada) identifiers are defined by the syntax diagram (railroad chart) opposite. Transform the syntax diagram into a system of syntax diagrams which do not contain loops; i.e. which are purely recursive. Using these modified diagrams, write a predicate identifier/1 that can check whether or not a given string is a legal identifier. ; % identifier(Str) :- Str is a legal identifier ; P97 (**) Sudoku ; Sudoku puzzles go like this: ; Problem statement Solution ; . . 4 | 8 . . | . 1 7 9 3 4 | 8 2 5 | 6 1 7 ; | | | | ; 6 7 . | 9 . . | . . . 6 7 2 | 9 1 4 | 8 5 3 ; | | | | ; 5 . 8 | . 3 . | . . 4 5 1 8 | 6 3 7 | 9 2 4 ; --------+---------+-------- --------+---------+-------- ; 3 . . | 7 4 . | 1 . . 3 2 5 | 7 4 8 | 1 6 9 ; | | | | ; . 6 9 | . . . | 7 8 . 4 6 9 | 1 5 3 | 7 8 2 ; | | | | ; . . 1 | . 6 9 | . . 5 7 8 1 | 2 6 9 | 4 3 5 ; --------+---------+-------- --------+---------+-------- ; 1 . . | . 8 . | 3 . 6 1 9 7 | 5 8 2 | 3 4 6 ; | | | | ; . . . | . . 6 | . 9 1 8 5 3 | 4 7 6 | 2 9 1 ; | | | | ; 2 4 . | . . 1 | 5 . . 2 4 6 | 3 9 1 | 5 7 8 ; Every spot in the puzzle belongs to a (horizontal) row and a (vertical) column, as well as to one single 3x3 square (which we call "square" for short). At the beginning, some of the spots carry a single-digit number between 1 and 9. The problem is to fill the missing spots with digits in such a way that every number between 1 and 9 appears exactly once in each row, in each column, and in each square. ; P98 (***) Nonograms ; Around 1994, a certain kind of puzzles was very popular in England. The "Sunday Telegraph" newspaper wrote: "Nonograms are puzzles from Japan and are currently published each week only in The Sunday Telegraph. Simply use your logic and skill to complete the grid and reveal a picture or diagram." As a Prolog programmer, you are in a better situation: you can have your computer do the work! Just write a little program ;-). ; The puzzle goes like this: Essentially, each row and column of a rectangular bitmap is annotated with the respective lengths of its distinct strings of occupied cells. The person who solves the puzzle must complete the bitmap given only these lengths. ; Problem statement: Solution: ; |_|_|_|_|_|_|_|_| 3 |_|X|X|X|_|_|_|_| 3 ; |_|_|_|_|_|_|_|_| 2 1 |X|X|_|X|_|_|_|_| 2 1 ; |_|_|_|_|_|_|_|_| 3 2 |_|X|X|X|_|_|X|X| 3 2 ; |_|_|_|_|_|_|_|_| 2 2 |_|_|X|X|_|_|X|X| 2 2 ; |_|_|_|_|_|_|_|_| 6 |_|_|X|X|X|X|X|X| 6 ; |_|_|_|_|_|_|_|_| 1 5 |X|_|X|X|X|X|X|_| 1 5 ; |_|_|_|_|_|_|_|_| 6 |X|X|X|X|X|X|_|_| 6 ; |_|_|_|_|_|_|_|_| 1 |_|_|_|_|X|_|_|_| 1 ; |_|_|_|_|_|_|_|_| 2 |_|_|_|X|X|_|_|_| 2 ; 1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3 ; 2 1 5 1 2 1 5 1 ; For the example above, the problem can be stated as the two lists [[3],[2,1],[3,2],[2,2],[6],[1,5],[6],[1],[2]] and [[1,2],[3,1],[1,5],[7,1],[5],[3],[4],[3]] which give the "solid" lengths of the rows and columns, top-to-bottom and left-to-right, respectively. Published puzzles are larger than this example, e.g. 25 x 20, and apparently always have unique solutions. ; P99 (***) Crossword puzzle ; Given an empty (or almost empty) framework of a crossword puzzle and a set of words. The problem is to place the words into the framework. ; The particular crossword puzzle is specified in a text file which first lists the words (one word per line) in an arbitrary order. Then, after an empty line, the crossword framework is defined. In this framework specification, an empty character location is represented by a dot (.). In order to make the solution easier, character locations can also contain predefined character values. The puzzle opposite is defined in the file p99a.dat, other examples are p99b.dat and p99d.dat. There is also an example of a puzzle (p99c.dat) which does not have a solution. ; Words are strings (character lists) of at least two characters. A horizontal or vertical sequence of character places in the crossword puzzle framework is called a site. Our problem is to find a compatible way of placing words onto sites. ; Hints: (1) The problem is not easy. You will need some time to thoroughly understand it. So, don't give up too early! And remember that the objective is a clean solution, not just a quick-and-dirty hack! ; (2) Reading the data file is a tricky problem for which a solution is provided in the file p99-readfile.lisp. Use the predicate read_lines/2. ; (3) For efficiency reasons it is important, at least for larger puzzles, to sort the words and the sites in a particular order. For this part of the problem, the solution of P28 may be very helpful. ; Last modified: Mon Oct 16 21:23:19 BRT 2006 (run-tests)
[ { "context": " job-handler (atom nil))\n\n(defn job-key\n [id]\n (qj/key (str id) \"jsk.job\"))\n\n;; this is a defrecord, qua", "end": 610, "score": 0.8748698234558105, "start": 604, "tag": "KEY", "value": "qj/key" }, { "context": "m nil))\n\n(defn job-key\n [id]\n (qj/key (str id) \"jsk.job\"))\n\n;; this is a defrecord, quartz needs a no arg", "end": 628, "score": 0.970810055732727, "start": 621, "tag": "KEY", "value": "jsk.job" } ]
src/jsk/director/quartz.clj
e85th/jsk
0
(ns jsk.director.quartz "Quartz Scheduler interface." (:require [clojurewerkz.quartzite.jobs :as qj :refer [defjob]] [clojurewerkz.quartzite.triggers :as qt] [clojurewerkz.quartzite.scheduler :as qs] [clojurewerkz.quartzite.conversion :as qc] [clojurewerkz.quartzite.schedule.cron :as cron] [schema.core :as s] [com.stuartsierra.component :as component] [taoensso.timbre :as log]) (:import [org.quartz Job JobDetail JobKey Trigger TriggerKey Scheduler])) (defonce job-handler (atom nil)) (defn job-key [id] (qj/key (str id) "jsk.job")) ;; this is a defrecord, quartz needs a no arg constructor for the class (defjob JskJob [ctx] (let [{:strs [node-id]} (qc/from-job-data ctx) handler @job-handler] (assert handler "quartz/init! must be called.") (handler node-id))) (defn job-detail "node-id must be unique across jobs and workflows" [node-id] (qj/build (qj/of-type JskJob) (qj/using-job-data {"node-id" node-id}) ; quartz requires string keys (qj/with-identity (job-key node-id)))) (s/defn cron-trigger [cron-expr] (qt/build (qt/start-now) (qt/with-schedule (cron/schedule (cron/cron-schedule cron-expr))))) (defn job-key-exists? [^Scheduler scheduler ^JobKey k] (.checkExists scheduler k)) (defn delete-job-triggers [scheduler node-id] (->> (qs/get-triggers-of-job scheduler (job-key node-id)) (qs/delete-triggers scheduler))) (defn- schedule-job* "Schedules a job with multiple triggers." [^Scheduler scheduler ^JobDetail job triggers] (.scheduleJob scheduler job (set triggers) true)) (s/defn schedule-cron-job "Schedules a job to be triggered based on the cron expressions. A job can have many triggers point to it. A trigger can only point to one job." [scheduler node-id :- s/Int cron-exprs :- #{s/Str}] (log/infof "Scheduling quartz job for node-id: %s" node-id) (delete-job-triggers scheduler node-id) (schedule-job* scheduler (job-detail node-id) (map cron-trigger cron-exprs))) (defn init! "Unfortunately have to be dirty and set state here to have director be fairly clean." [job-trigger-fn] (reset! job-handler job-trigger-fn))
58427
(ns jsk.director.quartz "Quartz Scheduler interface." (:require [clojurewerkz.quartzite.jobs :as qj :refer [defjob]] [clojurewerkz.quartzite.triggers :as qt] [clojurewerkz.quartzite.scheduler :as qs] [clojurewerkz.quartzite.conversion :as qc] [clojurewerkz.quartzite.schedule.cron :as cron] [schema.core :as s] [com.stuartsierra.component :as component] [taoensso.timbre :as log]) (:import [org.quartz Job JobDetail JobKey Trigger TriggerKey Scheduler])) (defonce job-handler (atom nil)) (defn job-key [id] (<KEY> (str id) "<KEY>")) ;; this is a defrecord, quartz needs a no arg constructor for the class (defjob JskJob [ctx] (let [{:strs [node-id]} (qc/from-job-data ctx) handler @job-handler] (assert handler "quartz/init! must be called.") (handler node-id))) (defn job-detail "node-id must be unique across jobs and workflows" [node-id] (qj/build (qj/of-type JskJob) (qj/using-job-data {"node-id" node-id}) ; quartz requires string keys (qj/with-identity (job-key node-id)))) (s/defn cron-trigger [cron-expr] (qt/build (qt/start-now) (qt/with-schedule (cron/schedule (cron/cron-schedule cron-expr))))) (defn job-key-exists? [^Scheduler scheduler ^JobKey k] (.checkExists scheduler k)) (defn delete-job-triggers [scheduler node-id] (->> (qs/get-triggers-of-job scheduler (job-key node-id)) (qs/delete-triggers scheduler))) (defn- schedule-job* "Schedules a job with multiple triggers." [^Scheduler scheduler ^JobDetail job triggers] (.scheduleJob scheduler job (set triggers) true)) (s/defn schedule-cron-job "Schedules a job to be triggered based on the cron expressions. A job can have many triggers point to it. A trigger can only point to one job." [scheduler node-id :- s/Int cron-exprs :- #{s/Str}] (log/infof "Scheduling quartz job for node-id: %s" node-id) (delete-job-triggers scheduler node-id) (schedule-job* scheduler (job-detail node-id) (map cron-trigger cron-exprs))) (defn init! "Unfortunately have to be dirty and set state here to have director be fairly clean." [job-trigger-fn] (reset! job-handler job-trigger-fn))
true
(ns jsk.director.quartz "Quartz Scheduler interface." (:require [clojurewerkz.quartzite.jobs :as qj :refer [defjob]] [clojurewerkz.quartzite.triggers :as qt] [clojurewerkz.quartzite.scheduler :as qs] [clojurewerkz.quartzite.conversion :as qc] [clojurewerkz.quartzite.schedule.cron :as cron] [schema.core :as s] [com.stuartsierra.component :as component] [taoensso.timbre :as log]) (:import [org.quartz Job JobDetail JobKey Trigger TriggerKey Scheduler])) (defonce job-handler (atom nil)) (defn job-key [id] (PI:KEY:<KEY>END_PI (str id) "PI:KEY:<KEY>END_PI")) ;; this is a defrecord, quartz needs a no arg constructor for the class (defjob JskJob [ctx] (let [{:strs [node-id]} (qc/from-job-data ctx) handler @job-handler] (assert handler "quartz/init! must be called.") (handler node-id))) (defn job-detail "node-id must be unique across jobs and workflows" [node-id] (qj/build (qj/of-type JskJob) (qj/using-job-data {"node-id" node-id}) ; quartz requires string keys (qj/with-identity (job-key node-id)))) (s/defn cron-trigger [cron-expr] (qt/build (qt/start-now) (qt/with-schedule (cron/schedule (cron/cron-schedule cron-expr))))) (defn job-key-exists? [^Scheduler scheduler ^JobKey k] (.checkExists scheduler k)) (defn delete-job-triggers [scheduler node-id] (->> (qs/get-triggers-of-job scheduler (job-key node-id)) (qs/delete-triggers scheduler))) (defn- schedule-job* "Schedules a job with multiple triggers." [^Scheduler scheduler ^JobDetail job triggers] (.scheduleJob scheduler job (set triggers) true)) (s/defn schedule-cron-job "Schedules a job to be triggered based on the cron expressions. A job can have many triggers point to it. A trigger can only point to one job." [scheduler node-id :- s/Int cron-exprs :- #{s/Str}] (log/infof "Scheduling quartz job for node-id: %s" node-id) (delete-job-triggers scheduler node-id) (schedule-job* scheduler (job-detail node-id) (map cron-trigger cron-exprs))) (defn init! "Unfortunately have to be dirty and set state here to have director be fairly clean." [job-trigger-fn] (reset! job-handler job-trigger-fn))
[ { "context": "(def matches \n [{:winner-name \"Kvitova P.\",\n :loser-name \"Ostapenko J.\",\n :tournament \"", "end": 42, "score": 0.9982589483261108, "start": 33, "tag": "NAME", "value": "Kvitova P" }, { "context": " \n [{:winner-name \"Kvitova P.\",\n :loser-name \"Ostapenko J.\",\n :tournament \"US Open\",\n :location \"New Yor", "end": 74, "score": 0.999453067779541, "start": 63, "tag": "NAME", "value": "Ostapenko J" }, { "context": " York\",\n :date \"2016-08-29\"}\n {:winner-name \"Kvitova P.\",\n :loser-name \"Buyukakcay C.\",\n :tournament ", "end": 182, "score": 0.9990582466125488, "start": 173, "tag": "NAME", "value": "Kvitova P" }, { "context": "}\n {:winner-name \"Kvitova P.\",\n :loser-name \"Buyukakcay C.\",\n :tournament \"US Open\",\n :location \"New Yor", "end": 215, "score": 0.9996029734611511, "start": 203, "tag": "NAME", "value": "Buyukakcay C" }, { "context": " York\",\n :date \"2016-08-31\"}\n {:winner-name \"Kvitova P.\",\n :loser-name \"Svitolina E.\",\n :tournament \"", "end": 323, "score": 0.9990048408508301, "start": 314, "tag": "NAME", "value": "Kvitova P" }, { "context": "}\n {:winner-name \"Kvitova P.\",\n :loser-name \"Svitolina E.\",\n :tournament \"US Open\",\n :location \"New Yor", "end": 355, "score": 0.9994855523109436, "start": 344, "tag": "NAME", "value": "Svitolina E" }, { "context": " York\",\n :date \"2016-09-02\"}\n {:winner-name \"Kerber A.\",\n :loser-name \"Kvitova P.\",\n :tournament \"US", "end": 462, "score": 0.9961154460906982, "start": 454, "tag": "NAME", "value": "Kerber A" }, { "context": "\"}\n {:winner-name \"Kerber A.\",\n :loser-name \"Kvitova P.\",\n :tournament \"US Open\",\n :location \"New Yor", "end": 492, "score": 0.9989398121833801, "start": 483, "tag": "NAME", "value": "Kvitova P" }, { "context": " York\",\n :date \"2016-09-05\"}\n {:winner-name \"Kvitova P.\",\n :loser-name \"Brengle M.\",\n :tournament \"To", "end": 600, "score": 0.999184787273407, "start": 591, "tag": "NAME", "value": "Kvitova P" }, { "context": "}\n {:winner-name \"Kvitova P.\",\n :loser-name \"Brengle M.\",\n :tournament \"Toray Pan Pacific Open\",\n :lo", "end": 630, "score": 0.9996227025985718, "start": 621, "tag": "NAME", "value": "Brengle M" }, { "context": "Tokyo\",\n :date \"2016-09-20\"}\n {:winner-name \"Puig M.\",\n :loser-name \"Kvitova P.\",\n :tournament \"To", "end": 747, "score": 0.9994292259216309, "start": 741, "tag": "NAME", "value": "Puig M" }, { "context": "20\"}\n {:winner-name \"Puig M.\",\n :loser-name \"Kvitova P.\",\n :tournament \"Toray Pan Pacific Open\",\n :lo", "end": 777, "score": 0.9994214177131653, "start": 768, "tag": "NAME", "value": "Kvitova P" } ]
chapter05/Exercise5.04/kvitova_matches.clj
TrainingByPackt/Clojure
0
(def matches [{:winner-name "Kvitova P.", :loser-name "Ostapenko J.", :tournament "US Open", :location "New York", :date "2016-08-29"} {:winner-name "Kvitova P.", :loser-name "Buyukakcay C.", :tournament "US Open", :location "New York", :date "2016-08-31"} {:winner-name "Kvitova P.", :loser-name "Svitolina E.", :tournament "US Open", :location "New York", :date "2016-09-02"} {:winner-name "Kerber A.", :loser-name "Kvitova P.", :tournament "US Open", :location "New York", :date "2016-09-05"} {:winner-name "Kvitova P.", :loser-name "Brengle M.", :tournament "Toray Pan Pacific Open", :location "Tokyo", :date "2016-09-20"} {:winner-name "Puig M.", :loser-name "Kvitova P.", :tournament "Toray Pan Pacific Open", :location "Tokyo", :date "2016-09-21"}])
30667
(def matches [{:winner-name "<NAME>.", :loser-name "<NAME>.", :tournament "US Open", :location "New York", :date "2016-08-29"} {:winner-name "<NAME>.", :loser-name "<NAME>.", :tournament "US Open", :location "New York", :date "2016-08-31"} {:winner-name "<NAME>.", :loser-name "<NAME>.", :tournament "US Open", :location "New York", :date "2016-09-02"} {:winner-name "<NAME>.", :loser-name "<NAME>.", :tournament "US Open", :location "New York", :date "2016-09-05"} {:winner-name "<NAME>.", :loser-name "<NAME>.", :tournament "Toray Pan Pacific Open", :location "Tokyo", :date "2016-09-20"} {:winner-name "<NAME>.", :loser-name "<NAME>.", :tournament "Toray Pan Pacific Open", :location "Tokyo", :date "2016-09-21"}])
true
(def matches [{:winner-name "PI:NAME:<NAME>END_PI.", :loser-name "PI:NAME:<NAME>END_PI.", :tournament "US Open", :location "New York", :date "2016-08-29"} {:winner-name "PI:NAME:<NAME>END_PI.", :loser-name "PI:NAME:<NAME>END_PI.", :tournament "US Open", :location "New York", :date "2016-08-31"} {:winner-name "PI:NAME:<NAME>END_PI.", :loser-name "PI:NAME:<NAME>END_PI.", :tournament "US Open", :location "New York", :date "2016-09-02"} {:winner-name "PI:NAME:<NAME>END_PI.", :loser-name "PI:NAME:<NAME>END_PI.", :tournament "US Open", :location "New York", :date "2016-09-05"} {:winner-name "PI:NAME:<NAME>END_PI.", :loser-name "PI:NAME:<NAME>END_PI.", :tournament "Toray Pan Pacific Open", :location "Tokyo", :date "2016-09-20"} {:winner-name "PI:NAME:<NAME>END_PI.", :loser-name "PI:NAME:<NAME>END_PI.", :tournament "Toray Pan Pacific Open", :location "Tokyo", :date "2016-09-21"}])
[ { "context": ": domains implementation\n;;;; Author: mikel evins\n;;;; Copyright: Copyright 2009 by mikel evins", "end": 244, "score": 0.9998771548271179, "start": 233, "tag": "NAME", "value": "mikel evins" }, { "context": " mikel evins\n;;;; Copyright: Copyright 2009 by mikel evins, all rights reserved\n;;;; License: Licensed", "end": 294, "score": 0.9998289346694946, "start": 283, "tag": "NAME", "value": "mikel evins" } ]
0.2.1/clj/build/classes/xg/categories/domains.clj
mikelevins/categories
5
;;;; *********************************************************************** ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: domains.clj ;;;; Project: Categories ;;;; Purpose: domains implementation ;;;; Author: mikel evins ;;;; Copyright: Copyright 2009 by mikel evins, all rights reserved ;;;; License: Licensed under the Apache License, version 2.0 ;;;; See the accompanying file "License" for more information ;;;; ;;;; *********************************************************************** (ns xg.categories.domains (:refer-clojure :exclude [type]) (:require xg.categories.utils xg.categories.structures xg.categories.types)) (refer 'xg.categories.utils) (refer 'xg.categories.structures) (refer 'xg.categories.types) ;;; ====================================================================== ;;; Domains ;;; ====================================================================== (defn default-method-adder [] (fn [fun meth] (let [mtable (:method-table fun)] (dosync (alter (:entries mtable) (fn [mt] (merge mt {(:signature meth) meth}))))))) (defn default-method-remover [] (fn [fun sig] (let [mtable (:method-table fun)] (dosync (alter (:entries mtable) (fn [mt] (dissoc mt sig))))))) (def <domain> (construct-structure-basis (into {} (map parse-keyspec `((:domain-data :default ~nil :setter ~true) (:method-adder :default ~(default-method-adder) :setter ~false) (:method-remover :default ~(default-method-remover) :setter ~false) (:method-selector :default ~false :setter ~false)))))) (defn get-domain-data [x] (deref (:domain-data (structure-map x)))) (defn set-domain-data! [x d] (update-structure-map! x d) x) (defn get-method-adder [x] (:method-adder (structure-map x))) (defn get-method-remover [x] (:method-remover (structure-map x))) (defn get-method-selector [x] (:method-selector (structure-map x)))
76257
;;;; *********************************************************************** ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: domains.clj ;;;; Project: Categories ;;;; Purpose: domains implementation ;;;; Author: <NAME> ;;;; Copyright: Copyright 2009 by <NAME>, all rights reserved ;;;; License: Licensed under the Apache License, version 2.0 ;;;; See the accompanying file "License" for more information ;;;; ;;;; *********************************************************************** (ns xg.categories.domains (:refer-clojure :exclude [type]) (:require xg.categories.utils xg.categories.structures xg.categories.types)) (refer 'xg.categories.utils) (refer 'xg.categories.structures) (refer 'xg.categories.types) ;;; ====================================================================== ;;; Domains ;;; ====================================================================== (defn default-method-adder [] (fn [fun meth] (let [mtable (:method-table fun)] (dosync (alter (:entries mtable) (fn [mt] (merge mt {(:signature meth) meth}))))))) (defn default-method-remover [] (fn [fun sig] (let [mtable (:method-table fun)] (dosync (alter (:entries mtable) (fn [mt] (dissoc mt sig))))))) (def <domain> (construct-structure-basis (into {} (map parse-keyspec `((:domain-data :default ~nil :setter ~true) (:method-adder :default ~(default-method-adder) :setter ~false) (:method-remover :default ~(default-method-remover) :setter ~false) (:method-selector :default ~false :setter ~false)))))) (defn get-domain-data [x] (deref (:domain-data (structure-map x)))) (defn set-domain-data! [x d] (update-structure-map! x d) x) (defn get-method-adder [x] (:method-adder (structure-map x))) (defn get-method-remover [x] (:method-remover (structure-map x))) (defn get-method-selector [x] (:method-selector (structure-map x)))
true
;;;; *********************************************************************** ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: domains.clj ;;;; Project: Categories ;;;; Purpose: domains implementation ;;;; Author: PI:NAME:<NAME>END_PI ;;;; Copyright: Copyright 2009 by PI:NAME:<NAME>END_PI, all rights reserved ;;;; License: Licensed under the Apache License, version 2.0 ;;;; See the accompanying file "License" for more information ;;;; ;;;; *********************************************************************** (ns xg.categories.domains (:refer-clojure :exclude [type]) (:require xg.categories.utils xg.categories.structures xg.categories.types)) (refer 'xg.categories.utils) (refer 'xg.categories.structures) (refer 'xg.categories.types) ;;; ====================================================================== ;;; Domains ;;; ====================================================================== (defn default-method-adder [] (fn [fun meth] (let [mtable (:method-table fun)] (dosync (alter (:entries mtable) (fn [mt] (merge mt {(:signature meth) meth}))))))) (defn default-method-remover [] (fn [fun sig] (let [mtable (:method-table fun)] (dosync (alter (:entries mtable) (fn [mt] (dissoc mt sig))))))) (def <domain> (construct-structure-basis (into {} (map parse-keyspec `((:domain-data :default ~nil :setter ~true) (:method-adder :default ~(default-method-adder) :setter ~false) (:method-remover :default ~(default-method-remover) :setter ~false) (:method-selector :default ~false :setter ~false)))))) (defn get-domain-data [x] (deref (:domain-data (structure-map x)))) (defn set-domain-data! [x d] (update-structure-map! x d) x) (defn get-method-adder [x] (:method-adder (structure-map x))) (defn get-method-remover [x] (:method-remover (structure-map x))) (defn get-method-selector [x] (:method-selector (structure-map x)))
[ { "context": "v.buttons\n [ui/raised-button {:label \"Tallenna\"\n :on-click save-tou", "end": 13909, "score": 0.5278527140617371, "start": 13904, "tag": "NAME", "value": "allen" }, { "context": "_token\")}]\n [text-field {:name :username\n :floating-label-text \"Käyttäjätu", "end": 16904, "score": 0.9943628311157227, "start": 16896, "tag": "USERNAME", "value": "username" }, { "context": " :username\n :floating-label-text \"Käyttäjätunnus\"\n :on-change no-op}]\n ", "end": 16958, "score": 0.9825474619865417, "start": 16944, "tag": "USERNAME", "value": "Käyttäjätunnus" }, { "context": " :password\n :floating-label-text \"Salasana\"\n :on-change no-op}]\n ", "end": 17149, "score": 0.8641297817230225, "start": 17141, "tag": "PASSWORD", "value": "Salasana" } ]
mtg-pairings-server/src/cljs/mtg_pairings_server/components/decklist/organizer.cljs
arttuka/mtg-pairings
2
(ns mtg-pairings-server.components.decklist.organizer (:require [reagent.core :as reagent :refer [atom]] [re-frame.core :refer [subscribe dispatch]] [cljsjs.material-ui] [cljs-react-material-ui.reagent :as ui] [cljs-react-material-ui.icons :as icons] [cljs-time.coerce :as coerce] [clojure.string :as str] [oops.core :refer [oget]] [mtg-pairings-server.components.decklist.print :refer [render-decklist]] [mtg-pairings-server.events.decklist :as events] [mtg-pairings-server.routes.decklist :as routes] [mtg-pairings-server.subscriptions.decklist :as subs] [mtg-pairings-server.styles.common :refer [palette]] [mtg-pairings-server.util :refer [format-date format-date-time to-local-date indexed get-host]] [mtg-pairings-server.util.decklist :refer [card-types type->header]] [mtg-pairings-server.util.material-ui :refer [text-field]])) (defn header [] (let [logged-in? (subscribe [::subs/user]) button-style {:margin-left "12px" :margin-right "12px"}] (fn header-render [] (let [disabled? (not @logged-in?)] [ui/toolbar {:class-name :decklist-organizer-header :style {:background-color (palette :primary1-color)}} [ui/toolbar-group {:first-child true} [ui/raised-button {:href (routes/organizer-path) :label "Kaikki turnaukset" :style button-style :disabled disabled?}] [ui/raised-button {:href (routes/organizer-new-tournament-path) :label "Uusi turnaus" :icon (reagent/as-element [icons/content-add {:style {:height "36px" :width "30px" :padding "6px 0 6px 6px" :vertical-align :top}}]) :style button-style :disabled disabled?}]] [ui/toolbar-group {:last-child true} [ui/raised-button {:href "/logout" :label "Kirjaudu ulos" :style button-style :disabled disabled?}]]])))) (def table-header-style {:color :black :font-weight :bold :font-size "16px" :height "36px"}) (defn list-submit-link [tournament-id] (let [submit-url (routes/new-decklist-path {:id tournament-id})] [:a {:href submit-url :target :_blank} (str (get-host) submit-url)])) (defn tournament-row [tournament] (let [column-style {:font-size "14px" :padding 0} link-props {:href (routes/organizer-tournament-path {:id (:id tournament)})}] [ui/table-row [ui/table-row-column {:class-name :date :style column-style} [:a.tournament-link link-props (format-date (:date tournament))]] [ui/table-row-column {:class-name :deadline :style column-style} [:a.tournament-link link-props (format-date-time (:deadline tournament))]] [ui/table-row-column {:class-name :name :style column-style} [:a.tournament-link link-props (:name tournament)]] [ui/table-row-column {:class-name :decklists :style column-style} [:a.tournament-link link-props (:decklist tournament)]] [ui/table-row-column {:class-name :submit-page :style {:font-size "14px"}} [list-submit-link (:id tournament)]]])) (defn all-tournaments [] (let [tournaments (subscribe [::subs/organizer-tournaments])] (fn all-tournaments-render [] [:div#decklist-organizer-tournaments [ui/table {:selectable false :class-name :tournaments} [ui/table-header {:display-select-all false :adjust-for-checkbox false} [ui/table-row {:style {:height "24px"}} [ui/table-header-column {:class-name :date :style table-header-style} "Päivä"] [ui/table-header-column {:class-name :deadline :style table-header-style} "Deadline"] [ui/table-header-column {:class-name :name :style table-header-style} "Turnaus"] [ui/table-header-column {:class-name :decklists :style table-header-style} "Dekkilistoja"] [ui/table-header-column {:class-name :submit-page :style table-header-style} "Listojen lähetyssivu"]]] [ui/table-body (for [tournament @tournaments] ^{:key (str (:id tournament) "--row")} [tournament-row tournament])]]]))) (defn sortable-header [{:keys [class-name column]} & children] (let [sort-data (subscribe [::subs/decklist-sort])] (fn sortable-header-render [{:keys [class-name column]} & children] (let [selected? (= column (:key @sort-data)) icon (if (and selected? (not (:ascending @sort-data))) icons/hardware-keyboard-arrow-up icons/hardware-keyboard-arrow-down) style (cond-> (assoc table-header-style :cursor :pointer) selected? (assoc :color (:accent1-color palette)))] [ui/table-header-column {:class-name class-name :style style :on-click #(dispatch [::events/sort-decklists column])} [icon {:style {:vertical-align :baseline :position :absolute :left 0 :color nil}}] children])))) (defn decklist-table [decklists selected-decklists on-select] [ui/table {:class-name :tournaments :multi-selectable true :on-row-selection on-select :all-rows-selected (= (count decklists) (count selected-decklists))} [ui/table-header [ui/table-row {:style {:height "24px"}} [ui/table-header-column {:class-name :dci :style table-header-style} "DCI"] [sortable-header {:class-name :name :column :name} "Nimi"] [sortable-header {:class-name :submitted :column :submitted} "Lähetetty"]]] [ui/table-body {:deselect-on-clickaway false} (for [decklist decklists :let [column-style {:font-size "14px" :padding 0} decklist-url (routes/organizer-view-path {:id (:id decklist)}) link-props {:href decklist-url :on-click #(dispatch [::events/load-decklist (:id decklist)])}]] ^{:key (str (:id decklist) "--row")} [ui/table-row {:selected (contains? selected-decklists (:id decklist))} [ui/table-row-column {:class-name :dci :style column-style} [:a.decklist-link link-props (:dci decklist)]] [ui/table-row-column {:class-name :name :style column-style} [:a.decklist-link link-props (str (:last-name decklist) ", " (:first-name decklist))]] [ui/table-row-column {:class-name :submitted :style column-style} [:a.decklist-link link-props (format-date-time (:submitted decklist))]]])]]) (defn notice [type text] (let [[color background] (case type :success [:black (:primary1-color palette)] :error [:white (:error-color palette)]) display? (atom true) on-delete #(reset! display? false)] (fn notice-render [type text] (when @display? [ui/chip {:background-color background :label-color color :on-request-delete on-delete} text])))) (defn notices [] (let [saved? (subscribe [::subs/saved?]) error? (subscribe [::subs/error :save-tournament])] (fn notices-render [] [:div.notices (when @saved? [notice :success "Tallennus onnistui"]) (when @error? [notice :error "Tallennus epäonnistui"])]))) (defn date-picker [opts] [ui/date-picker (merge {:container :inline :dialog-container-style {:left "-9999px"} :locale "fi-FI" :auto-ok true :DateTimeFormat (oget js/Intl "DateTimeFormat") :text-field-style {:width "128px"}} opts)]) (defn tournament [id] (let [saved-tournament (subscribe [::subs/organizer-tournament]) decklists (subscribe [::subs/organizer-decklists]) saving? (subscribe [::subs/saving?]) tournament (atom nil) set-name #(swap! tournament assoc :name %) set-date (fn [_ date] (swap! tournament assoc :date date)) set-deadline (fn [_ date] (swap! tournament assoc :deadline date)) set-format (fn [_ _ format] (swap! tournament assoc :format (keyword format))) save-tournament #(dispatch [::events/save-tournament (-> @tournament (select-keys [:id :name :format :date :deadline]) (update :date to-local-date) (update :deadline coerce/to-date-time))]) selected-decklists (atom #{}) on-select (fn [selection] (let [selection (js->clj selection)] (reset! selected-decklists (set (case selection "all" (map :id @decklists) "none" [] (map (comp :id @decklists) selection)))))) load-selected-decklists #(dispatch [::events/load-decklists @selected-decklists])] (fn tournament-render [id] (when (and (nil? @tournament) (some? @saved-tournament)) (reset! tournament (-> @saved-tournament (update :date coerce/to-date) (update :deadline coerce/to-date)))) [:div#decklist-organizer-tournament [:div.tournament-info [:div.fields [:div.field (let [value (:name @tournament "")] [text-field {:on-change set-name :floating-label-text "Turnauksen nimi" :value value :error-text (when (str/blank? value) "Nimi on pakollinen")}])] [:div.field (let [value (:format @tournament)] [ui/select-field {:on-change set-format :value value :floating-label-text "Formaatti" :error-text (when-not value "Formaatti on pakollinen") :style {:width "128px"}} [ui/menu-item {:value :standard :primary-text "Standard"}] [ui/menu-item {:value :modern :primary-text "Modern"}] [ui/menu-item {:value :legacy :primary-text "Legacy"}]])] [:div.field (let [value (:date @tournament)] [date-picker {:value value :error-text (when-not value "Päivämäärä on pakollinen") :on-change set-date :floating-label-text "Päivämäärä" :min-date (js/Date.)}])] [:div.field (let [value (:deadline @tournament)] [date-picker {:value value :error-text (when-not value "Listojen lähettämisen deadline on pakollinen") :on-change set-deadline :floating-label-text "Deadline" :min-date (js/Date.)}])] [:div.field (let [value (:deadline @tournament)] [ui/time-picker {:value value :floating-label-text "Deadline klo" :on-change set-deadline :format "24hr" :auto-ok true :minutes-step 10 :text-field-style {:width "128px"}}])]] [:div.link (when id [:p "Listojen lähetyssivu: " [list-submit-link id]])] [:div.buttons [ui/raised-button {:label "Tallenna" :on-click save-tournament :primary true :disabled (or @saving? (str/blank? (:name @tournament)) (nil? (:format @tournament)) (nil? (:date @tournament)) (nil? (:deadline @tournament))) :style {:width "200px"}}] (if @saving? [ui/circular-progress {:size 36 :style {:margin-left "24px" :margin-right "24px" :vertical-align :top}}] [:div.placeholder {:style {:display :inline-block :width "84px" :height "36px" :vertical-align :top}}]) [notices] [:br] [ui/raised-button {:label "Tulosta valitut listat" :href (routes/organizer-print-path) :on-click load-selected-decklists :primary true :disabled (empty? @selected-decklists) :style {:margin-top "12px" :width "200px"}}]]] [:div.decklists (if (seq @decklists) [decklist-table @decklists @selected-decklists on-select] [:p "Ei lähetettyjä listoja"])]]))) (defn view-decklist [] (let [decklist (subscribe [::subs/decklist-by-type]) tournament (subscribe [::subs/organizer-tournament])] (fn view-decklist-render [] [render-decklist @decklist @tournament]))) (defn view-decklists [] (let [decklists (subscribe [::subs/decklists-by-type]) tournament (subscribe [::subs/organizer-tournament]) printed? (clojure.core/atom false) print-page #(when (and (seq @decklists) @tournament (not @printed?)) (reset! printed? true) (.print js/window))] (reagent/create-class {:component-did-mount print-page :component-did-update print-page :reagent-render (fn view-decklists-render [] [:div (doall (for [decklist @decklists] ^{:key (:id decklist)} [render-decklist decklist @tournament]))])}))) (defn ^:private no-op []) (defn login [] [:div#decklist-organizer-login [:p "Kirjaudu sisään MtgSuomi-tunnuksillasi."] [:form {:action (str "/login?next=" (oget js/window "location" "pathname")) :method :post} [:input {:type :hidden :name :__anti-forgery-token :value (oget js/window "csrf_token")}] [text-field {:name :username :floating-label-text "Käyttäjätunnus" :on-change no-op}] [text-field {:name :password :type :password :floating-label-text "Salasana" :on-change no-op}] [ui/raised-button {:type :submit :label "Kirjaudu" :primary true}]]])
67591
(ns mtg-pairings-server.components.decklist.organizer (:require [reagent.core :as reagent :refer [atom]] [re-frame.core :refer [subscribe dispatch]] [cljsjs.material-ui] [cljs-react-material-ui.reagent :as ui] [cljs-react-material-ui.icons :as icons] [cljs-time.coerce :as coerce] [clojure.string :as str] [oops.core :refer [oget]] [mtg-pairings-server.components.decklist.print :refer [render-decklist]] [mtg-pairings-server.events.decklist :as events] [mtg-pairings-server.routes.decklist :as routes] [mtg-pairings-server.subscriptions.decklist :as subs] [mtg-pairings-server.styles.common :refer [palette]] [mtg-pairings-server.util :refer [format-date format-date-time to-local-date indexed get-host]] [mtg-pairings-server.util.decklist :refer [card-types type->header]] [mtg-pairings-server.util.material-ui :refer [text-field]])) (defn header [] (let [logged-in? (subscribe [::subs/user]) button-style {:margin-left "12px" :margin-right "12px"}] (fn header-render [] (let [disabled? (not @logged-in?)] [ui/toolbar {:class-name :decklist-organizer-header :style {:background-color (palette :primary1-color)}} [ui/toolbar-group {:first-child true} [ui/raised-button {:href (routes/organizer-path) :label "Kaikki turnaukset" :style button-style :disabled disabled?}] [ui/raised-button {:href (routes/organizer-new-tournament-path) :label "Uusi turnaus" :icon (reagent/as-element [icons/content-add {:style {:height "36px" :width "30px" :padding "6px 0 6px 6px" :vertical-align :top}}]) :style button-style :disabled disabled?}]] [ui/toolbar-group {:last-child true} [ui/raised-button {:href "/logout" :label "Kirjaudu ulos" :style button-style :disabled disabled?}]]])))) (def table-header-style {:color :black :font-weight :bold :font-size "16px" :height "36px"}) (defn list-submit-link [tournament-id] (let [submit-url (routes/new-decklist-path {:id tournament-id})] [:a {:href submit-url :target :_blank} (str (get-host) submit-url)])) (defn tournament-row [tournament] (let [column-style {:font-size "14px" :padding 0} link-props {:href (routes/organizer-tournament-path {:id (:id tournament)})}] [ui/table-row [ui/table-row-column {:class-name :date :style column-style} [:a.tournament-link link-props (format-date (:date tournament))]] [ui/table-row-column {:class-name :deadline :style column-style} [:a.tournament-link link-props (format-date-time (:deadline tournament))]] [ui/table-row-column {:class-name :name :style column-style} [:a.tournament-link link-props (:name tournament)]] [ui/table-row-column {:class-name :decklists :style column-style} [:a.tournament-link link-props (:decklist tournament)]] [ui/table-row-column {:class-name :submit-page :style {:font-size "14px"}} [list-submit-link (:id tournament)]]])) (defn all-tournaments [] (let [tournaments (subscribe [::subs/organizer-tournaments])] (fn all-tournaments-render [] [:div#decklist-organizer-tournaments [ui/table {:selectable false :class-name :tournaments} [ui/table-header {:display-select-all false :adjust-for-checkbox false} [ui/table-row {:style {:height "24px"}} [ui/table-header-column {:class-name :date :style table-header-style} "Päivä"] [ui/table-header-column {:class-name :deadline :style table-header-style} "Deadline"] [ui/table-header-column {:class-name :name :style table-header-style} "Turnaus"] [ui/table-header-column {:class-name :decklists :style table-header-style} "Dekkilistoja"] [ui/table-header-column {:class-name :submit-page :style table-header-style} "Listojen lähetyssivu"]]] [ui/table-body (for [tournament @tournaments] ^{:key (str (:id tournament) "--row")} [tournament-row tournament])]]]))) (defn sortable-header [{:keys [class-name column]} & children] (let [sort-data (subscribe [::subs/decklist-sort])] (fn sortable-header-render [{:keys [class-name column]} & children] (let [selected? (= column (:key @sort-data)) icon (if (and selected? (not (:ascending @sort-data))) icons/hardware-keyboard-arrow-up icons/hardware-keyboard-arrow-down) style (cond-> (assoc table-header-style :cursor :pointer) selected? (assoc :color (:accent1-color palette)))] [ui/table-header-column {:class-name class-name :style style :on-click #(dispatch [::events/sort-decklists column])} [icon {:style {:vertical-align :baseline :position :absolute :left 0 :color nil}}] children])))) (defn decklist-table [decklists selected-decklists on-select] [ui/table {:class-name :tournaments :multi-selectable true :on-row-selection on-select :all-rows-selected (= (count decklists) (count selected-decklists))} [ui/table-header [ui/table-row {:style {:height "24px"}} [ui/table-header-column {:class-name :dci :style table-header-style} "DCI"] [sortable-header {:class-name :name :column :name} "Nimi"] [sortable-header {:class-name :submitted :column :submitted} "Lähetetty"]]] [ui/table-body {:deselect-on-clickaway false} (for [decklist decklists :let [column-style {:font-size "14px" :padding 0} decklist-url (routes/organizer-view-path {:id (:id decklist)}) link-props {:href decklist-url :on-click #(dispatch [::events/load-decklist (:id decklist)])}]] ^{:key (str (:id decklist) "--row")} [ui/table-row {:selected (contains? selected-decklists (:id decklist))} [ui/table-row-column {:class-name :dci :style column-style} [:a.decklist-link link-props (:dci decklist)]] [ui/table-row-column {:class-name :name :style column-style} [:a.decklist-link link-props (str (:last-name decklist) ", " (:first-name decklist))]] [ui/table-row-column {:class-name :submitted :style column-style} [:a.decklist-link link-props (format-date-time (:submitted decklist))]]])]]) (defn notice [type text] (let [[color background] (case type :success [:black (:primary1-color palette)] :error [:white (:error-color palette)]) display? (atom true) on-delete #(reset! display? false)] (fn notice-render [type text] (when @display? [ui/chip {:background-color background :label-color color :on-request-delete on-delete} text])))) (defn notices [] (let [saved? (subscribe [::subs/saved?]) error? (subscribe [::subs/error :save-tournament])] (fn notices-render [] [:div.notices (when @saved? [notice :success "Tallennus onnistui"]) (when @error? [notice :error "Tallennus epäonnistui"])]))) (defn date-picker [opts] [ui/date-picker (merge {:container :inline :dialog-container-style {:left "-9999px"} :locale "fi-FI" :auto-ok true :DateTimeFormat (oget js/Intl "DateTimeFormat") :text-field-style {:width "128px"}} opts)]) (defn tournament [id] (let [saved-tournament (subscribe [::subs/organizer-tournament]) decklists (subscribe [::subs/organizer-decklists]) saving? (subscribe [::subs/saving?]) tournament (atom nil) set-name #(swap! tournament assoc :name %) set-date (fn [_ date] (swap! tournament assoc :date date)) set-deadline (fn [_ date] (swap! tournament assoc :deadline date)) set-format (fn [_ _ format] (swap! tournament assoc :format (keyword format))) save-tournament #(dispatch [::events/save-tournament (-> @tournament (select-keys [:id :name :format :date :deadline]) (update :date to-local-date) (update :deadline coerce/to-date-time))]) selected-decklists (atom #{}) on-select (fn [selection] (let [selection (js->clj selection)] (reset! selected-decklists (set (case selection "all" (map :id @decklists) "none" [] (map (comp :id @decklists) selection)))))) load-selected-decklists #(dispatch [::events/load-decklists @selected-decklists])] (fn tournament-render [id] (when (and (nil? @tournament) (some? @saved-tournament)) (reset! tournament (-> @saved-tournament (update :date coerce/to-date) (update :deadline coerce/to-date)))) [:div#decklist-organizer-tournament [:div.tournament-info [:div.fields [:div.field (let [value (:name @tournament "")] [text-field {:on-change set-name :floating-label-text "Turnauksen nimi" :value value :error-text (when (str/blank? value) "Nimi on pakollinen")}])] [:div.field (let [value (:format @tournament)] [ui/select-field {:on-change set-format :value value :floating-label-text "Formaatti" :error-text (when-not value "Formaatti on pakollinen") :style {:width "128px"}} [ui/menu-item {:value :standard :primary-text "Standard"}] [ui/menu-item {:value :modern :primary-text "Modern"}] [ui/menu-item {:value :legacy :primary-text "Legacy"}]])] [:div.field (let [value (:date @tournament)] [date-picker {:value value :error-text (when-not value "Päivämäärä on pakollinen") :on-change set-date :floating-label-text "Päivämäärä" :min-date (js/Date.)}])] [:div.field (let [value (:deadline @tournament)] [date-picker {:value value :error-text (when-not value "Listojen lähettämisen deadline on pakollinen") :on-change set-deadline :floating-label-text "Deadline" :min-date (js/Date.)}])] [:div.field (let [value (:deadline @tournament)] [ui/time-picker {:value value :floating-label-text "Deadline klo" :on-change set-deadline :format "24hr" :auto-ok true :minutes-step 10 :text-field-style {:width "128px"}}])]] [:div.link (when id [:p "Listojen lähetyssivu: " [list-submit-link id]])] [:div.buttons [ui/raised-button {:label "T<NAME>na" :on-click save-tournament :primary true :disabled (or @saving? (str/blank? (:name @tournament)) (nil? (:format @tournament)) (nil? (:date @tournament)) (nil? (:deadline @tournament))) :style {:width "200px"}}] (if @saving? [ui/circular-progress {:size 36 :style {:margin-left "24px" :margin-right "24px" :vertical-align :top}}] [:div.placeholder {:style {:display :inline-block :width "84px" :height "36px" :vertical-align :top}}]) [notices] [:br] [ui/raised-button {:label "Tulosta valitut listat" :href (routes/organizer-print-path) :on-click load-selected-decklists :primary true :disabled (empty? @selected-decklists) :style {:margin-top "12px" :width "200px"}}]]] [:div.decklists (if (seq @decklists) [decklist-table @decklists @selected-decklists on-select] [:p "Ei lähetettyjä listoja"])]]))) (defn view-decklist [] (let [decklist (subscribe [::subs/decklist-by-type]) tournament (subscribe [::subs/organizer-tournament])] (fn view-decklist-render [] [render-decklist @decklist @tournament]))) (defn view-decklists [] (let [decklists (subscribe [::subs/decklists-by-type]) tournament (subscribe [::subs/organizer-tournament]) printed? (clojure.core/atom false) print-page #(when (and (seq @decklists) @tournament (not @printed?)) (reset! printed? true) (.print js/window))] (reagent/create-class {:component-did-mount print-page :component-did-update print-page :reagent-render (fn view-decklists-render [] [:div (doall (for [decklist @decklists] ^{:key (:id decklist)} [render-decklist decklist @tournament]))])}))) (defn ^:private no-op []) (defn login [] [:div#decklist-organizer-login [:p "Kirjaudu sisään MtgSuomi-tunnuksillasi."] [:form {:action (str "/login?next=" (oget js/window "location" "pathname")) :method :post} [:input {:type :hidden :name :__anti-forgery-token :value (oget js/window "csrf_token")}] [text-field {:name :username :floating-label-text "Käyttäjätunnus" :on-change no-op}] [text-field {:name :password :type :password :floating-label-text "<PASSWORD>" :on-change no-op}] [ui/raised-button {:type :submit :label "Kirjaudu" :primary true}]]])
true
(ns mtg-pairings-server.components.decklist.organizer (:require [reagent.core :as reagent :refer [atom]] [re-frame.core :refer [subscribe dispatch]] [cljsjs.material-ui] [cljs-react-material-ui.reagent :as ui] [cljs-react-material-ui.icons :as icons] [cljs-time.coerce :as coerce] [clojure.string :as str] [oops.core :refer [oget]] [mtg-pairings-server.components.decklist.print :refer [render-decklist]] [mtg-pairings-server.events.decklist :as events] [mtg-pairings-server.routes.decklist :as routes] [mtg-pairings-server.subscriptions.decklist :as subs] [mtg-pairings-server.styles.common :refer [palette]] [mtg-pairings-server.util :refer [format-date format-date-time to-local-date indexed get-host]] [mtg-pairings-server.util.decklist :refer [card-types type->header]] [mtg-pairings-server.util.material-ui :refer [text-field]])) (defn header [] (let [logged-in? (subscribe [::subs/user]) button-style {:margin-left "12px" :margin-right "12px"}] (fn header-render [] (let [disabled? (not @logged-in?)] [ui/toolbar {:class-name :decklist-organizer-header :style {:background-color (palette :primary1-color)}} [ui/toolbar-group {:first-child true} [ui/raised-button {:href (routes/organizer-path) :label "Kaikki turnaukset" :style button-style :disabled disabled?}] [ui/raised-button {:href (routes/organizer-new-tournament-path) :label "Uusi turnaus" :icon (reagent/as-element [icons/content-add {:style {:height "36px" :width "30px" :padding "6px 0 6px 6px" :vertical-align :top}}]) :style button-style :disabled disabled?}]] [ui/toolbar-group {:last-child true} [ui/raised-button {:href "/logout" :label "Kirjaudu ulos" :style button-style :disabled disabled?}]]])))) (def table-header-style {:color :black :font-weight :bold :font-size "16px" :height "36px"}) (defn list-submit-link [tournament-id] (let [submit-url (routes/new-decklist-path {:id tournament-id})] [:a {:href submit-url :target :_blank} (str (get-host) submit-url)])) (defn tournament-row [tournament] (let [column-style {:font-size "14px" :padding 0} link-props {:href (routes/organizer-tournament-path {:id (:id tournament)})}] [ui/table-row [ui/table-row-column {:class-name :date :style column-style} [:a.tournament-link link-props (format-date (:date tournament))]] [ui/table-row-column {:class-name :deadline :style column-style} [:a.tournament-link link-props (format-date-time (:deadline tournament))]] [ui/table-row-column {:class-name :name :style column-style} [:a.tournament-link link-props (:name tournament)]] [ui/table-row-column {:class-name :decklists :style column-style} [:a.tournament-link link-props (:decklist tournament)]] [ui/table-row-column {:class-name :submit-page :style {:font-size "14px"}} [list-submit-link (:id tournament)]]])) (defn all-tournaments [] (let [tournaments (subscribe [::subs/organizer-tournaments])] (fn all-tournaments-render [] [:div#decklist-organizer-tournaments [ui/table {:selectable false :class-name :tournaments} [ui/table-header {:display-select-all false :adjust-for-checkbox false} [ui/table-row {:style {:height "24px"}} [ui/table-header-column {:class-name :date :style table-header-style} "Päivä"] [ui/table-header-column {:class-name :deadline :style table-header-style} "Deadline"] [ui/table-header-column {:class-name :name :style table-header-style} "Turnaus"] [ui/table-header-column {:class-name :decklists :style table-header-style} "Dekkilistoja"] [ui/table-header-column {:class-name :submit-page :style table-header-style} "Listojen lähetyssivu"]]] [ui/table-body (for [tournament @tournaments] ^{:key (str (:id tournament) "--row")} [tournament-row tournament])]]]))) (defn sortable-header [{:keys [class-name column]} & children] (let [sort-data (subscribe [::subs/decklist-sort])] (fn sortable-header-render [{:keys [class-name column]} & children] (let [selected? (= column (:key @sort-data)) icon (if (and selected? (not (:ascending @sort-data))) icons/hardware-keyboard-arrow-up icons/hardware-keyboard-arrow-down) style (cond-> (assoc table-header-style :cursor :pointer) selected? (assoc :color (:accent1-color palette)))] [ui/table-header-column {:class-name class-name :style style :on-click #(dispatch [::events/sort-decklists column])} [icon {:style {:vertical-align :baseline :position :absolute :left 0 :color nil}}] children])))) (defn decklist-table [decklists selected-decklists on-select] [ui/table {:class-name :tournaments :multi-selectable true :on-row-selection on-select :all-rows-selected (= (count decklists) (count selected-decklists))} [ui/table-header [ui/table-row {:style {:height "24px"}} [ui/table-header-column {:class-name :dci :style table-header-style} "DCI"] [sortable-header {:class-name :name :column :name} "Nimi"] [sortable-header {:class-name :submitted :column :submitted} "Lähetetty"]]] [ui/table-body {:deselect-on-clickaway false} (for [decklist decklists :let [column-style {:font-size "14px" :padding 0} decklist-url (routes/organizer-view-path {:id (:id decklist)}) link-props {:href decklist-url :on-click #(dispatch [::events/load-decklist (:id decklist)])}]] ^{:key (str (:id decklist) "--row")} [ui/table-row {:selected (contains? selected-decklists (:id decklist))} [ui/table-row-column {:class-name :dci :style column-style} [:a.decklist-link link-props (:dci decklist)]] [ui/table-row-column {:class-name :name :style column-style} [:a.decklist-link link-props (str (:last-name decklist) ", " (:first-name decklist))]] [ui/table-row-column {:class-name :submitted :style column-style} [:a.decklist-link link-props (format-date-time (:submitted decklist))]]])]]) (defn notice [type text] (let [[color background] (case type :success [:black (:primary1-color palette)] :error [:white (:error-color palette)]) display? (atom true) on-delete #(reset! display? false)] (fn notice-render [type text] (when @display? [ui/chip {:background-color background :label-color color :on-request-delete on-delete} text])))) (defn notices [] (let [saved? (subscribe [::subs/saved?]) error? (subscribe [::subs/error :save-tournament])] (fn notices-render [] [:div.notices (when @saved? [notice :success "Tallennus onnistui"]) (when @error? [notice :error "Tallennus epäonnistui"])]))) (defn date-picker [opts] [ui/date-picker (merge {:container :inline :dialog-container-style {:left "-9999px"} :locale "fi-FI" :auto-ok true :DateTimeFormat (oget js/Intl "DateTimeFormat") :text-field-style {:width "128px"}} opts)]) (defn tournament [id] (let [saved-tournament (subscribe [::subs/organizer-tournament]) decklists (subscribe [::subs/organizer-decklists]) saving? (subscribe [::subs/saving?]) tournament (atom nil) set-name #(swap! tournament assoc :name %) set-date (fn [_ date] (swap! tournament assoc :date date)) set-deadline (fn [_ date] (swap! tournament assoc :deadline date)) set-format (fn [_ _ format] (swap! tournament assoc :format (keyword format))) save-tournament #(dispatch [::events/save-tournament (-> @tournament (select-keys [:id :name :format :date :deadline]) (update :date to-local-date) (update :deadline coerce/to-date-time))]) selected-decklists (atom #{}) on-select (fn [selection] (let [selection (js->clj selection)] (reset! selected-decklists (set (case selection "all" (map :id @decklists) "none" [] (map (comp :id @decklists) selection)))))) load-selected-decklists #(dispatch [::events/load-decklists @selected-decklists])] (fn tournament-render [id] (when (and (nil? @tournament) (some? @saved-tournament)) (reset! tournament (-> @saved-tournament (update :date coerce/to-date) (update :deadline coerce/to-date)))) [:div#decklist-organizer-tournament [:div.tournament-info [:div.fields [:div.field (let [value (:name @tournament "")] [text-field {:on-change set-name :floating-label-text "Turnauksen nimi" :value value :error-text (when (str/blank? value) "Nimi on pakollinen")}])] [:div.field (let [value (:format @tournament)] [ui/select-field {:on-change set-format :value value :floating-label-text "Formaatti" :error-text (when-not value "Formaatti on pakollinen") :style {:width "128px"}} [ui/menu-item {:value :standard :primary-text "Standard"}] [ui/menu-item {:value :modern :primary-text "Modern"}] [ui/menu-item {:value :legacy :primary-text "Legacy"}]])] [:div.field (let [value (:date @tournament)] [date-picker {:value value :error-text (when-not value "Päivämäärä on pakollinen") :on-change set-date :floating-label-text "Päivämäärä" :min-date (js/Date.)}])] [:div.field (let [value (:deadline @tournament)] [date-picker {:value value :error-text (when-not value "Listojen lähettämisen deadline on pakollinen") :on-change set-deadline :floating-label-text "Deadline" :min-date (js/Date.)}])] [:div.field (let [value (:deadline @tournament)] [ui/time-picker {:value value :floating-label-text "Deadline klo" :on-change set-deadline :format "24hr" :auto-ok true :minutes-step 10 :text-field-style {:width "128px"}}])]] [:div.link (when id [:p "Listojen lähetyssivu: " [list-submit-link id]])] [:div.buttons [ui/raised-button {:label "TPI:NAME:<NAME>END_PIna" :on-click save-tournament :primary true :disabled (or @saving? (str/blank? (:name @tournament)) (nil? (:format @tournament)) (nil? (:date @tournament)) (nil? (:deadline @tournament))) :style {:width "200px"}}] (if @saving? [ui/circular-progress {:size 36 :style {:margin-left "24px" :margin-right "24px" :vertical-align :top}}] [:div.placeholder {:style {:display :inline-block :width "84px" :height "36px" :vertical-align :top}}]) [notices] [:br] [ui/raised-button {:label "Tulosta valitut listat" :href (routes/organizer-print-path) :on-click load-selected-decklists :primary true :disabled (empty? @selected-decklists) :style {:margin-top "12px" :width "200px"}}]]] [:div.decklists (if (seq @decklists) [decklist-table @decklists @selected-decklists on-select] [:p "Ei lähetettyjä listoja"])]]))) (defn view-decklist [] (let [decklist (subscribe [::subs/decklist-by-type]) tournament (subscribe [::subs/organizer-tournament])] (fn view-decklist-render [] [render-decklist @decklist @tournament]))) (defn view-decklists [] (let [decklists (subscribe [::subs/decklists-by-type]) tournament (subscribe [::subs/organizer-tournament]) printed? (clojure.core/atom false) print-page #(when (and (seq @decklists) @tournament (not @printed?)) (reset! printed? true) (.print js/window))] (reagent/create-class {:component-did-mount print-page :component-did-update print-page :reagent-render (fn view-decklists-render [] [:div (doall (for [decklist @decklists] ^{:key (:id decklist)} [render-decklist decklist @tournament]))])}))) (defn ^:private no-op []) (defn login [] [:div#decklist-organizer-login [:p "Kirjaudu sisään MtgSuomi-tunnuksillasi."] [:form {:action (str "/login?next=" (oget js/window "location" "pathname")) :method :post} [:input {:type :hidden :name :__anti-forgery-token :value (oget js/window "csrf_token")}] [text-field {:name :username :floating-label-text "Käyttäjätunnus" :on-change no-op}] [text-field {:name :password :type :password :floating-label-text "PI:PASSWORD:<PASSWORD>END_PI" :on-change no-op}] [ui/raised-button {:type :submit :label "Kirjaudu" :primary true}]]])
[ { "context": "\n\n {:question \"In the beginning of the 1st book, Arthur Dent's house was demolished to make way for w", "end": 705, "score": 0.773037314414978, "start": 703, "tag": "NAME", "value": "Ar" }, { "context": "{:question \"In the beginning of the 1st book, Arthur Dent's house was demolished to make way for what?\"\n ", "end": 714, "score": 0.9662746787071228, "start": 707, "tag": "NAME", "value": "ur Dent" }, { "context": " cover story - but really?\"\n :choices [\"To kill Arthur Dent, who was inexplicably woven into the fabric of ti", "end": 1298, "score": 0.9997221827507019, "start": 1287, "tag": "NAME", "value": "Arthur Dent" }, { "context": " fabric of time and space.\"\n \"To kill Zaphod Beeblebrox, who had a secret locked up inside of his brain.\"", "end": 1403, "score": 0.9998199343681335, "start": 1386, "tag": "NAME", "value": "Zaphod Beeblebrox" }, { "context": "ed up inside of his brain.\"\n \"To kill Fanchurch, who had a secret locked up inside of her brain.\"", "end": 1486, "score": 0.9987949728965759, "start": 1477, "tag": "NAME", "value": "Fanchurch" }, { "context": " :answer \"Mostly harmless\"\n }\n\n {:question \"Arthur Dent, when trying to get Heart of Gold's supercomputer", "end": 2440, "score": 0.9984602928161621, "start": 2429, "tag": "NAME", "value": "Arthur Dent" }, { "context": " apologize for the inconvenience\"}\n {:question \" Marvin, 'the paranoid android', especially loathed this ", "end": 4130, "score": 0.9993786811828613, "start": 4124, "tag": "NAME", "value": "Marvin" }, { "context": "andwich Maker of Lamuella, meat of what animal was Arthur Dent using for his sandwiches?\"\n :choices [\"Perfect", "end": 4481, "score": 0.9987209439277649, "start": 4470, "tag": "NAME", "value": "Arthur Dent" }, { "context": " {:question \"What was the name of the daughter of Arthur Dent and Trillian.\"\n :choices [\"Last Call Amanda\"\n ", "end": 5073, "score": 0.9641231894493103, "start": 5049, "tag": "NAME", "value": "Arthur Dent and Trillian" }, { "context": "rthur Dent and Trillian.\"\n :choices [\"Last Call Amanda\"\n \"Melody Pond\"\n \"Eccen", "end": 5107, "score": 0.8512142300605774, "start": 5101, "tag": "NAME", "value": "Amanda" }, { "context": "\"\n :choices [\"Last Call Amanda\"\n \"Melody Pond\"\n \"Eccentrica Gallumbits\"\n ", "end": 5135, "score": 0.9531400799751282, "start": 5124, "tag": "NAME", "value": "Melody Pond" }, { "context": "manda\"\n \"Melody Pond\"\n \"Eccentrica Gallumbits\"\n \"Random Frequent Flyer\"]\n :answ", "end": 5173, "score": 0.9977275133132935, "start": 5152, "tag": "NAME", "value": "Eccentrica Gallumbits" } ]
data/train/clojure/f2101272710ffda8edc9ca2d73efa86cea450f38questions.cljs
harshp8l/deep-learning-lang-detection
84
(ns cljs.quiz.questions) (def questions [{:question "What is the Answer to the Ultimate Question of Life, Universe, and Everything?" :answer "42" :choices ["0" "24" "42" "NaN" "\"\""]} {:question "What was eventually accepted for the Ultimate *Question* of Life, Universe, and Everything?" :choices ["What is yellow and dangerous?" "How many roads must a man walk down?" "How many Vogons does it take to change a lightbulb?" "What is six times seven?" "What is six times nine (in base 13)?" "None of the above."] :answer "How many roads must a man walk down?"} {:question "In the beginning of the 1st book, Arthur Dent's house was demolished to make way for what?" :choices ["a subway" "a corporate headquaters" "a pub" "a bypass"] :answer "a bypass"} {:question "In the beginning of the 1st book, planet Earth was demolished to make way for what?" :choices ["a sub-etha casino" "a Galgafrinchian golf course" "a Hyperspace byypass." "a space maze for white mice"] :answer "a Hyperspace byypass."} {:question "Yeah, that's *their* cover story - but really?" :choices ["To kill Arthur Dent, who was inexplicably woven into the fabric of time and space." "To kill Zaphod Beeblebrox, who had a secret locked up inside of his brain." "To kill Fanchurch, who had a secret locked up inside of her brain." "To stop the *real* question from being discovered on Earth." "3 and 4." "... demolishing planets is just what Vogons do."] :answer "3 and 4."} {:question "On planet Earth, in the ordering of the species by their intelligence level, what is the number assigned to Homo Sapiens?" :choices [ "1" "2" "3" "4" "5"] :answer "3"} {:question "What does Hitchhiker's Guide to the Galaxy has to say about planet Earth?" :choices ["Deadly" "Beautiful" "Boring" "Harmless"] :answer "Harmless"} {:question "... and after Ford Prefect spending 15 years stuck on the planet, what does it expand to?" :choices ["Deadly but boring" "Beautiful.. kind of" "Boring but deadly" "Mostly harmless"] :answer "Mostly harmless" } {:question "Arthur Dent, when trying to get Heart of Gold's supercomputer to brew him a drink, was invariably getting a cup of hot, brown liquied, which was almost, but not quite, entirely unlike... what?" :choices [ "tea" "coffee" "gin" "milk"] :answer "tea"} {:question "How do you spell \"Magrathea\"" :choices ["MA-grathea" "Magr-A-thea" "Magra-THEA"] :answer "Magra-THEA"} {:question "When orbiting the legendary planet of Magrathea, two incoming nuclear missiles were turned by the Improbability Drive of Heart Of Gold spaceship into... what, exactly?" :choices ["a little rubber mallet and a vinyl of Elvis" "a sperm whale and bowl of petunias." "a team of sales executives" "all of the above"] :answer "a sperm whale and bowl of petunias."} {:question " What's the trick to learning how to fly?" :choices ["really convince yourself you actually can do it" "procuring some antigrav gel" "start falling but manage to miss the ground" "spend an year on top of a pillar on a second planet of Stavromula Beta"] :answer "start falling but manage to miss the ground"} {:question " Written in thirty-foot high letters of fire on top of the Quentulus Quazgar Mountains in the land of Sevorbeupstry on planet Preliumtarn is God's Final Message to His Creation. What is it?" :choices ["Conditions may apply" "May cause depression and anxiety" "Don't panic" "We apologize for the inconvenience"] :answer "We apologize for the inconvenience"} {:question " Marvin, 'the paranoid android', especially loathed this creation of his native Cirius Cybernetics Corporation." :choices ["robotic tanks" "electronic salesmen" "sentient elevators" "talking doors"] :answer "talking doors"} {:question " As a Sandwich Maker of Lamuella, meat of what animal was Arthur Dent using for his sandwiches?" :choices ["Perfectly Normal Beast" "The Dish Of The Day" "scintillating jeweled scuttling crabs" "none of the above"] :answer "Perfectly Normal Beast"} {:question "What was the message dolphins left on Earth, before disappearing?" :choices ["so long, and thanks for all the fish" "it was nice, but now it's gone" "take care, and visit us on Santraginus V"] :answer "it was nice, but now it's gone"} {:question "What was the name of the daughter of Arthur Dent and Trillian." :choices ["Last Call Amanda" "Melody Pond" "Eccentrica Gallumbits" "Random Frequent Flyer"] :answer "Random Frequent Flyer"} {:question "Which of these books is NOT mentioned in Hitchhiker's Guide To The Galaxy" :choices ["Hitchhiker's Guide To The Galaxy" "What You Never Wanted to Know About Sex But Were Forced To Find Out" "Some More Of God's Greatest Mistakes" "Last Chance To See" "The Salmon Of Doubt" "Fifty-Three More Things To Do In Zero Gravity"] :answer "The Salmon Of Doubt"}])
14923
(ns cljs.quiz.questions) (def questions [{:question "What is the Answer to the Ultimate Question of Life, Universe, and Everything?" :answer "42" :choices ["0" "24" "42" "NaN" "\"\""]} {:question "What was eventually accepted for the Ultimate *Question* of Life, Universe, and Everything?" :choices ["What is yellow and dangerous?" "How many roads must a man walk down?" "How many Vogons does it take to change a lightbulb?" "What is six times seven?" "What is six times nine (in base 13)?" "None of the above."] :answer "How many roads must a man walk down?"} {:question "In the beginning of the 1st book, <NAME>th<NAME>'s house was demolished to make way for what?" :choices ["a subway" "a corporate headquaters" "a pub" "a bypass"] :answer "a bypass"} {:question "In the beginning of the 1st book, planet Earth was demolished to make way for what?" :choices ["a sub-etha casino" "a Galgafrinchian golf course" "a Hyperspace byypass." "a space maze for white mice"] :answer "a Hyperspace byypass."} {:question "Yeah, that's *their* cover story - but really?" :choices ["To kill <NAME>, who was inexplicably woven into the fabric of time and space." "To kill <NAME>, who had a secret locked up inside of his brain." "To kill <NAME>, who had a secret locked up inside of her brain." "To stop the *real* question from being discovered on Earth." "3 and 4." "... demolishing planets is just what Vogons do."] :answer "3 and 4."} {:question "On planet Earth, in the ordering of the species by their intelligence level, what is the number assigned to Homo Sapiens?" :choices [ "1" "2" "3" "4" "5"] :answer "3"} {:question "What does Hitchhiker's Guide to the Galaxy has to say about planet Earth?" :choices ["Deadly" "Beautiful" "Boring" "Harmless"] :answer "Harmless"} {:question "... and after Ford Prefect spending 15 years stuck on the planet, what does it expand to?" :choices ["Deadly but boring" "Beautiful.. kind of" "Boring but deadly" "Mostly harmless"] :answer "Mostly harmless" } {:question "<NAME>, when trying to get Heart of Gold's supercomputer to brew him a drink, was invariably getting a cup of hot, brown liquied, which was almost, but not quite, entirely unlike... what?" :choices [ "tea" "coffee" "gin" "milk"] :answer "tea"} {:question "How do you spell \"Magrathea\"" :choices ["MA-grathea" "Magr-A-thea" "Magra-THEA"] :answer "Magra-THEA"} {:question "When orbiting the legendary planet of Magrathea, two incoming nuclear missiles were turned by the Improbability Drive of Heart Of Gold spaceship into... what, exactly?" :choices ["a little rubber mallet and a vinyl of Elvis" "a sperm whale and bowl of petunias." "a team of sales executives" "all of the above"] :answer "a sperm whale and bowl of petunias."} {:question " What's the trick to learning how to fly?" :choices ["really convince yourself you actually can do it" "procuring some antigrav gel" "start falling but manage to miss the ground" "spend an year on top of a pillar on a second planet of Stavromula Beta"] :answer "start falling but manage to miss the ground"} {:question " Written in thirty-foot high letters of fire on top of the Quentulus Quazgar Mountains in the land of Sevorbeupstry on planet Preliumtarn is God's Final Message to His Creation. What is it?" :choices ["Conditions may apply" "May cause depression and anxiety" "Don't panic" "We apologize for the inconvenience"] :answer "We apologize for the inconvenience"} {:question " <NAME>, 'the paranoid android', especially loathed this creation of his native Cirius Cybernetics Corporation." :choices ["robotic tanks" "electronic salesmen" "sentient elevators" "talking doors"] :answer "talking doors"} {:question " As a Sandwich Maker of Lamuella, meat of what animal was <NAME> using for his sandwiches?" :choices ["Perfectly Normal Beast" "The Dish Of The Day" "scintillating jeweled scuttling crabs" "none of the above"] :answer "Perfectly Normal Beast"} {:question "What was the message dolphins left on Earth, before disappearing?" :choices ["so long, and thanks for all the fish" "it was nice, but now it's gone" "take care, and visit us on Santraginus V"] :answer "it was nice, but now it's gone"} {:question "What was the name of the daughter of <NAME>." :choices ["Last Call <NAME>" "<NAME>" "<NAME>" "Random Frequent Flyer"] :answer "Random Frequent Flyer"} {:question "Which of these books is NOT mentioned in Hitchhiker's Guide To The Galaxy" :choices ["Hitchhiker's Guide To The Galaxy" "What You Never Wanted to Know About Sex But Were Forced To Find Out" "Some More Of God's Greatest Mistakes" "Last Chance To See" "The Salmon Of Doubt" "Fifty-Three More Things To Do In Zero Gravity"] :answer "The Salmon Of Doubt"}])
true
(ns cljs.quiz.questions) (def questions [{:question "What is the Answer to the Ultimate Question of Life, Universe, and Everything?" :answer "42" :choices ["0" "24" "42" "NaN" "\"\""]} {:question "What was eventually accepted for the Ultimate *Question* of Life, Universe, and Everything?" :choices ["What is yellow and dangerous?" "How many roads must a man walk down?" "How many Vogons does it take to change a lightbulb?" "What is six times seven?" "What is six times nine (in base 13)?" "None of the above."] :answer "How many roads must a man walk down?"} {:question "In the beginning of the 1st book, PI:NAME:<NAME>END_PIthPI:NAME:<NAME>END_PI's house was demolished to make way for what?" :choices ["a subway" "a corporate headquaters" "a pub" "a bypass"] :answer "a bypass"} {:question "In the beginning of the 1st book, planet Earth was demolished to make way for what?" :choices ["a sub-etha casino" "a Galgafrinchian golf course" "a Hyperspace byypass." "a space maze for white mice"] :answer "a Hyperspace byypass."} {:question "Yeah, that's *their* cover story - but really?" :choices ["To kill PI:NAME:<NAME>END_PI, who was inexplicably woven into the fabric of time and space." "To kill PI:NAME:<NAME>END_PI, who had a secret locked up inside of his brain." "To kill PI:NAME:<NAME>END_PI, who had a secret locked up inside of her brain." "To stop the *real* question from being discovered on Earth." "3 and 4." "... demolishing planets is just what Vogons do."] :answer "3 and 4."} {:question "On planet Earth, in the ordering of the species by their intelligence level, what is the number assigned to Homo Sapiens?" :choices [ "1" "2" "3" "4" "5"] :answer "3"} {:question "What does Hitchhiker's Guide to the Galaxy has to say about planet Earth?" :choices ["Deadly" "Beautiful" "Boring" "Harmless"] :answer "Harmless"} {:question "... and after Ford Prefect spending 15 years stuck on the planet, what does it expand to?" :choices ["Deadly but boring" "Beautiful.. kind of" "Boring but deadly" "Mostly harmless"] :answer "Mostly harmless" } {:question "PI:NAME:<NAME>END_PI, when trying to get Heart of Gold's supercomputer to brew him a drink, was invariably getting a cup of hot, brown liquied, which was almost, but not quite, entirely unlike... what?" :choices [ "tea" "coffee" "gin" "milk"] :answer "tea"} {:question "How do you spell \"Magrathea\"" :choices ["MA-grathea" "Magr-A-thea" "Magra-THEA"] :answer "Magra-THEA"} {:question "When orbiting the legendary planet of Magrathea, two incoming nuclear missiles were turned by the Improbability Drive of Heart Of Gold spaceship into... what, exactly?" :choices ["a little rubber mallet and a vinyl of Elvis" "a sperm whale and bowl of petunias." "a team of sales executives" "all of the above"] :answer "a sperm whale and bowl of petunias."} {:question " What's the trick to learning how to fly?" :choices ["really convince yourself you actually can do it" "procuring some antigrav gel" "start falling but manage to miss the ground" "spend an year on top of a pillar on a second planet of Stavromula Beta"] :answer "start falling but manage to miss the ground"} {:question " Written in thirty-foot high letters of fire on top of the Quentulus Quazgar Mountains in the land of Sevorbeupstry on planet Preliumtarn is God's Final Message to His Creation. What is it?" :choices ["Conditions may apply" "May cause depression and anxiety" "Don't panic" "We apologize for the inconvenience"] :answer "We apologize for the inconvenience"} {:question " PI:NAME:<NAME>END_PI, 'the paranoid android', especially loathed this creation of his native Cirius Cybernetics Corporation." :choices ["robotic tanks" "electronic salesmen" "sentient elevators" "talking doors"] :answer "talking doors"} {:question " As a Sandwich Maker of Lamuella, meat of what animal was PI:NAME:<NAME>END_PI using for his sandwiches?" :choices ["Perfectly Normal Beast" "The Dish Of The Day" "scintillating jeweled scuttling crabs" "none of the above"] :answer "Perfectly Normal Beast"} {:question "What was the message dolphins left on Earth, before disappearing?" :choices ["so long, and thanks for all the fish" "it was nice, but now it's gone" "take care, and visit us on Santraginus V"] :answer "it was nice, but now it's gone"} {:question "What was the name of the daughter of PI:NAME:<NAME>END_PI." :choices ["Last Call PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "Random Frequent Flyer"] :answer "Random Frequent Flyer"} {:question "Which of these books is NOT mentioned in Hitchhiker's Guide To The Galaxy" :choices ["Hitchhiker's Guide To The Galaxy" "What You Never Wanted to Know About Sex But Were Forced To Find Out" "Some More Of God's Greatest Mistakes" "Last Chance To See" "The Salmon Of Doubt" "Fifty-Three More Things To Do In Zero Gravity"] :answer "The Salmon Of Doubt"}])
[ { "context": "; Copyright (c) 2011, Tom Van Cutsem, Vrije Universiteit Brussel\n; All rights reserved", "end": 36, "score": 0.9998112320899963, "start": 22, "tag": "NAME", "value": "Tom Van Cutsem" }, { "context": "M in Clojure\n;; Multicore Programming\n;; (c) 2011, Tom Van Cutsem\n\n;; alter vs. commute\n\n(ns test.commute\n (:impor", "end": 1670, "score": 0.9997832775115967, "start": 1656, "tag": "NAME", "value": "Tom Van Cutsem" }, { "context": "Adapted from clojure.org/concurrent_programming by Rich Hickey:\n; In this example a vector of Refs containing in", "end": 2016, "score": 0.9998576641082764, "start": 2005, "tag": "NAME", "value": "Rich Hickey" } ]
test/commute.clj
tvcutsem/stm-in-clojure
33
; Copyright (c) 2011, Tom Van Cutsem, Vrije Universiteit Brussel ; 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 Vrije Universiteit Brussel 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 VRIJE UNIVERSITEIT BRUSSEL 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. ;; MC-STM: meta-circular STM in Clojure ;; Multicore Programming ;; (c) 2011, Tom Van Cutsem ;; alter vs. commute (ns test.commute (:import (java.util.concurrent Executors))) ; (use 'stm.v0-native) ; (use 'stm.v1-simple) ; (use 'stm.v2-mvcc) ; (use 'stm.v3-mvcc-commute) ; (use 'stm.v4-mvcc-fine-grained) (use 'stm.v5-mvcc-fine-grained-barging) ;; === Contention === ; Adapted from clojure.org/concurrent_programming by Rich Hickey: ; In this example a vector of Refs containing integers is created (refs), ; then a set of threads are set up (pool) to run a number of iterations of ; incrementing every Ref (tasks). This creates extreme contention, ; but yields the correct result. No locks! ; update-fn is one of mc-alter or mc-commute (defn test-stm [nitems nthreads niters update-fn] (let [num-tries (atom 0) refs (map mc-ref (replicate nitems 0)) pool (Executors/newFixedThreadPool nthreads) tasks (map (fn [t] (fn [] (dotimes [n niters] (mc-dosync (swap! num-tries inc) (doseq [r refs] (update-fn r + 1 t)))))) (range nthreads))] (doseq [future (.invokeAll pool tasks)] (.get future)) (.shutdown pool) {:result (map mc-deref refs) :retries (- @num-tries (* nthreads niters)) })) ; 10 threads increment each of 10 refs 10000 times ; each ref should be incremented by 550000 in total = ; (* 10000 (+ 1 2 3 4 5 6 7 8 9 10)) ; -> (550000 550000 550000 550000 550000 550000 550000 550000 550000 550000) ; using mc-alter (let [res (time (test-stm 10 10 10000 mc-alter))] (assert (= (count (:result res)) 10)) (assert (every? (fn [r] (= r 550000)) (:result res))) (println "num retries using alter: " (:retries res))) ; using mc-commute (let [res (time (test-stm 10 10 10000 mc-commute))] (assert (= (count (:result res)) 10)) (assert (every? (fn [r] (= r 550000)) (:result res))) (println "num retries using commute: " (:retries res))) ; ----------------------------------------------------- ; observed behavior on: ; Clojure 1.2.0-RC2 ; JDK 1.6.0 ; Mac OS X 10.6.7 ; Macbook, 2.4 GHz Intel Core 2 Duo, 4 GB 1067 MHz DDR3 ; ----------------------------------------------------- ; for all timings below except v4, clearly the retries provoked by ; alter are not dominating the total running time, since ; the total execution time is virtually the same ; (even for v3 which implements commute properly) ; v0-native: ; alter: "Elapsed time: 2872.917 msecs" ; num retries using alter: 117439 ; commute: "Elapsed time: 2852.853 msecs" ; num retries using commute: 0 ; v1-simple: ; naive implementation of commute provides no benefit ; alter: "Elapsed time: 6514.418 msecs" ; num retries using alter: 84265 ; commute: "Elapsed time: 6325.194 msecs" ; num retries using commute: 93888 ; v2-mvcc: ; naive implementation of commute provides no benefit ; alter: "Elapsed time: 10744.366 msecs" ; num retries using alter: 107795 ; commute: "Elapsed time: 9478.161 msecs" ; num retries using commute: 97313 ; v3-mvcc-commute: ; proper implementation of commute: 0 retries ; alter: "Elapsed time: 11264.848 msecs" ; num retries using alter: 75726 ; commute: "Elapsed time: 10269.281 msecs" ; num retries using commute: 0 ; v4-mvcc-fine-grained: ; using commute halves the total running time ; unlike alter, commute does not acquire a lock on first read of an mc-ref ; alter: "Elapsed time: 16065.477 msecs" ; num retries using alter: 94028 ; commute: "Elapsed time: 8238.209 msecs" ; num retries using commute: 0
11306
; Copyright (c) 2011, <NAME>, Vrije Universiteit Brussel ; 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 Vrije Universiteit Brussel 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 VRIJE UNIVERSITEIT BRUSSEL 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. ;; MC-STM: meta-circular STM in Clojure ;; Multicore Programming ;; (c) 2011, <NAME> ;; alter vs. commute (ns test.commute (:import (java.util.concurrent Executors))) ; (use 'stm.v0-native) ; (use 'stm.v1-simple) ; (use 'stm.v2-mvcc) ; (use 'stm.v3-mvcc-commute) ; (use 'stm.v4-mvcc-fine-grained) (use 'stm.v5-mvcc-fine-grained-barging) ;; === Contention === ; Adapted from clojure.org/concurrent_programming by <NAME>: ; In this example a vector of Refs containing integers is created (refs), ; then a set of threads are set up (pool) to run a number of iterations of ; incrementing every Ref (tasks). This creates extreme contention, ; but yields the correct result. No locks! ; update-fn is one of mc-alter or mc-commute (defn test-stm [nitems nthreads niters update-fn] (let [num-tries (atom 0) refs (map mc-ref (replicate nitems 0)) pool (Executors/newFixedThreadPool nthreads) tasks (map (fn [t] (fn [] (dotimes [n niters] (mc-dosync (swap! num-tries inc) (doseq [r refs] (update-fn r + 1 t)))))) (range nthreads))] (doseq [future (.invokeAll pool tasks)] (.get future)) (.shutdown pool) {:result (map mc-deref refs) :retries (- @num-tries (* nthreads niters)) })) ; 10 threads increment each of 10 refs 10000 times ; each ref should be incremented by 550000 in total = ; (* 10000 (+ 1 2 3 4 5 6 7 8 9 10)) ; -> (550000 550000 550000 550000 550000 550000 550000 550000 550000 550000) ; using mc-alter (let [res (time (test-stm 10 10 10000 mc-alter))] (assert (= (count (:result res)) 10)) (assert (every? (fn [r] (= r 550000)) (:result res))) (println "num retries using alter: " (:retries res))) ; using mc-commute (let [res (time (test-stm 10 10 10000 mc-commute))] (assert (= (count (:result res)) 10)) (assert (every? (fn [r] (= r 550000)) (:result res))) (println "num retries using commute: " (:retries res))) ; ----------------------------------------------------- ; observed behavior on: ; Clojure 1.2.0-RC2 ; JDK 1.6.0 ; Mac OS X 10.6.7 ; Macbook, 2.4 GHz Intel Core 2 Duo, 4 GB 1067 MHz DDR3 ; ----------------------------------------------------- ; for all timings below except v4, clearly the retries provoked by ; alter are not dominating the total running time, since ; the total execution time is virtually the same ; (even for v3 which implements commute properly) ; v0-native: ; alter: "Elapsed time: 2872.917 msecs" ; num retries using alter: 117439 ; commute: "Elapsed time: 2852.853 msecs" ; num retries using commute: 0 ; v1-simple: ; naive implementation of commute provides no benefit ; alter: "Elapsed time: 6514.418 msecs" ; num retries using alter: 84265 ; commute: "Elapsed time: 6325.194 msecs" ; num retries using commute: 93888 ; v2-mvcc: ; naive implementation of commute provides no benefit ; alter: "Elapsed time: 10744.366 msecs" ; num retries using alter: 107795 ; commute: "Elapsed time: 9478.161 msecs" ; num retries using commute: 97313 ; v3-mvcc-commute: ; proper implementation of commute: 0 retries ; alter: "Elapsed time: 11264.848 msecs" ; num retries using alter: 75726 ; commute: "Elapsed time: 10269.281 msecs" ; num retries using commute: 0 ; v4-mvcc-fine-grained: ; using commute halves the total running time ; unlike alter, commute does not acquire a lock on first read of an mc-ref ; alter: "Elapsed time: 16065.477 msecs" ; num retries using alter: 94028 ; commute: "Elapsed time: 8238.209 msecs" ; num retries using commute: 0
true
; Copyright (c) 2011, PI:NAME:<NAME>END_PI, Vrije Universiteit Brussel ; 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 Vrije Universiteit Brussel 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 VRIJE UNIVERSITEIT BRUSSEL 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. ;; MC-STM: meta-circular STM in Clojure ;; Multicore Programming ;; (c) 2011, PI:NAME:<NAME>END_PI ;; alter vs. commute (ns test.commute (:import (java.util.concurrent Executors))) ; (use 'stm.v0-native) ; (use 'stm.v1-simple) ; (use 'stm.v2-mvcc) ; (use 'stm.v3-mvcc-commute) ; (use 'stm.v4-mvcc-fine-grained) (use 'stm.v5-mvcc-fine-grained-barging) ;; === Contention === ; Adapted from clojure.org/concurrent_programming by PI:NAME:<NAME>END_PI: ; In this example a vector of Refs containing integers is created (refs), ; then a set of threads are set up (pool) to run a number of iterations of ; incrementing every Ref (tasks). This creates extreme contention, ; but yields the correct result. No locks! ; update-fn is one of mc-alter or mc-commute (defn test-stm [nitems nthreads niters update-fn] (let [num-tries (atom 0) refs (map mc-ref (replicate nitems 0)) pool (Executors/newFixedThreadPool nthreads) tasks (map (fn [t] (fn [] (dotimes [n niters] (mc-dosync (swap! num-tries inc) (doseq [r refs] (update-fn r + 1 t)))))) (range nthreads))] (doseq [future (.invokeAll pool tasks)] (.get future)) (.shutdown pool) {:result (map mc-deref refs) :retries (- @num-tries (* nthreads niters)) })) ; 10 threads increment each of 10 refs 10000 times ; each ref should be incremented by 550000 in total = ; (* 10000 (+ 1 2 3 4 5 6 7 8 9 10)) ; -> (550000 550000 550000 550000 550000 550000 550000 550000 550000 550000) ; using mc-alter (let [res (time (test-stm 10 10 10000 mc-alter))] (assert (= (count (:result res)) 10)) (assert (every? (fn [r] (= r 550000)) (:result res))) (println "num retries using alter: " (:retries res))) ; using mc-commute (let [res (time (test-stm 10 10 10000 mc-commute))] (assert (= (count (:result res)) 10)) (assert (every? (fn [r] (= r 550000)) (:result res))) (println "num retries using commute: " (:retries res))) ; ----------------------------------------------------- ; observed behavior on: ; Clojure 1.2.0-RC2 ; JDK 1.6.0 ; Mac OS X 10.6.7 ; Macbook, 2.4 GHz Intel Core 2 Duo, 4 GB 1067 MHz DDR3 ; ----------------------------------------------------- ; for all timings below except v4, clearly the retries provoked by ; alter are not dominating the total running time, since ; the total execution time is virtually the same ; (even for v3 which implements commute properly) ; v0-native: ; alter: "Elapsed time: 2872.917 msecs" ; num retries using alter: 117439 ; commute: "Elapsed time: 2852.853 msecs" ; num retries using commute: 0 ; v1-simple: ; naive implementation of commute provides no benefit ; alter: "Elapsed time: 6514.418 msecs" ; num retries using alter: 84265 ; commute: "Elapsed time: 6325.194 msecs" ; num retries using commute: 93888 ; v2-mvcc: ; naive implementation of commute provides no benefit ; alter: "Elapsed time: 10744.366 msecs" ; num retries using alter: 107795 ; commute: "Elapsed time: 9478.161 msecs" ; num retries using commute: 97313 ; v3-mvcc-commute: ; proper implementation of commute: 0 retries ; alter: "Elapsed time: 11264.848 msecs" ; num retries using alter: 75726 ; commute: "Elapsed time: 10269.281 msecs" ; num retries using commute: 0 ; v4-mvcc-fine-grained: ; using commute halves the total running time ; unlike alter, commute does not acquire a lock on first read of an mc-ref ; alter: "Elapsed time: 16065.477 msecs" ; num retries using alter: 94028 ; commute: "Elapsed time: 8238.209 msecs" ; num retries using commute: 0
[ { "context": ":lastname \"bar\"}\n {:id \"2\" :firstname \"john\" :lastname \"doe\"}\n {:id \"3\" :firstname", "end": 1642, "score": 0.9980447888374329, "start": 1638, "tag": "NAME", "value": "john" }, { "context": " {:id \"2\" :firstname \"john\" :lastname \"doe\"}\n {:id \"3\" :firstname \"daniel\" :lastn", "end": 1658, "score": 0.8203845620155334, "start": 1655, "tag": "NAME", "value": "doe" }, { "context": ":lastname \"doe\"}\n {:id \"3\" :firstname \"daniel\" :lastname \"gerlach\"}])\n\n(defn health\n \"Returns ", "end": 1700, "score": 0.9987521171569824, "start": 1694, "tag": "NAME", "value": "daniel" }, { "context": " {:id \"3\" :firstname \"daniel\" :lastname \"gerlach\"}])\n\n(defn health\n \"Returns ring response health", "end": 1720, "score": 0.9919139742851257, "start": 1713, "tag": "NAME", "value": "gerlach" } ]
src/hello_world/handler.clj
gerlacdt/hello-world-compojure
0
(ns hello-world.handler (:require [compojure.core :refer :all] [compojure.route :as route] [ring.middleware.defaults :refer [wrap-defaults site-defaults]] [ring.middleware.json :refer [wrap-json-body wrap-json-response]] [ring.middleware.params :refer [wrap-params]] [ring.util.response :refer [response]] [cheshire.core :refer :all] [io.aviso.exception :as aviso-ex] [taoensso.timbre :as timbre :refer (log trace debug info warn error fatal report logf tracef debugf infof warnf errorf fatalf reportf spy get-env log-env)])) (defn json-output-fn [{:keys [?err_ vargs_ hostname_ timestamp_ level] :as args}] (let [messages (map (fn [msg] { :timestamp @timestamp_ :level level :hostname @hostname_ :message msg }) @vargs_) err (force ?err_) json-messages (map #(generate-string %) messages)] ;; (print "print default-fn-output" err) (if err (clojure.string/join "\n" (conj json-messages {:ex (aviso-ex/format-exception err)})) (clojure.string/join "\n" (conj json-messages))))) ;; (error (Exception. "my exception message") "text message") ;; (timbre/merge-config! ;; {:appenders {:println {:output-fn json-output-fn}}}) (timbre/merge-config! {:appenders {:println {:output-fn timbre/default-output-fn}}}) (def users [{:id "1" :firstname "foo" :lastname "bar"} {:id "2" :firstname "john" :lastname "doe"} {:id "3" :firstname "daniel" :lastname "gerlach"}]) (defn health "Returns ring response health check" [] (info "health check OK") (response {:status "OK"})) (defn get-users "Returns all users" [] (response users)) (defn get-user "Return user with given id" [id] (let [user (first (filter (fn [user] (when (= (:id user) id) user)) users))] (info user) (if user (response user) (route/not-found (response {:message "Not found"}))))) (defn duration "Returns duration in seconds. Input params should be System/nanoTime" [start] (float (/ (- (System/nanoTime) start) 1000000))) (defn wrap-response-time "Logs duration of response time" [handler] (fn [request] (let [start (System/nanoTime) response (handler request)] (info {:message "response time" :url (:uri request) :response-time-sec (duration start)}) response))) (defroutes handler (GET "/health" [] (health)) (GET "/users" {params :params} (get-users)) (GET "/users/:id" {{id :id} :params} (get-user id)) (route/not-found (response {:message "Not Found"}))) (def app (-> handler wrap-response-time wrap-params wrap-json-body wrap-json-response))
29184
(ns hello-world.handler (:require [compojure.core :refer :all] [compojure.route :as route] [ring.middleware.defaults :refer [wrap-defaults site-defaults]] [ring.middleware.json :refer [wrap-json-body wrap-json-response]] [ring.middleware.params :refer [wrap-params]] [ring.util.response :refer [response]] [cheshire.core :refer :all] [io.aviso.exception :as aviso-ex] [taoensso.timbre :as timbre :refer (log trace debug info warn error fatal report logf tracef debugf infof warnf errorf fatalf reportf spy get-env log-env)])) (defn json-output-fn [{:keys [?err_ vargs_ hostname_ timestamp_ level] :as args}] (let [messages (map (fn [msg] { :timestamp @timestamp_ :level level :hostname @hostname_ :message msg }) @vargs_) err (force ?err_) json-messages (map #(generate-string %) messages)] ;; (print "print default-fn-output" err) (if err (clojure.string/join "\n" (conj json-messages {:ex (aviso-ex/format-exception err)})) (clojure.string/join "\n" (conj json-messages))))) ;; (error (Exception. "my exception message") "text message") ;; (timbre/merge-config! ;; {:appenders {:println {:output-fn json-output-fn}}}) (timbre/merge-config! {:appenders {:println {:output-fn timbre/default-output-fn}}}) (def users [{:id "1" :firstname "foo" :lastname "bar"} {:id "2" :firstname "<NAME>" :lastname "<NAME>"} {:id "3" :firstname "<NAME>" :lastname "<NAME>"}]) (defn health "Returns ring response health check" [] (info "health check OK") (response {:status "OK"})) (defn get-users "Returns all users" [] (response users)) (defn get-user "Return user with given id" [id] (let [user (first (filter (fn [user] (when (= (:id user) id) user)) users))] (info user) (if user (response user) (route/not-found (response {:message "Not found"}))))) (defn duration "Returns duration in seconds. Input params should be System/nanoTime" [start] (float (/ (- (System/nanoTime) start) 1000000))) (defn wrap-response-time "Logs duration of response time" [handler] (fn [request] (let [start (System/nanoTime) response (handler request)] (info {:message "response time" :url (:uri request) :response-time-sec (duration start)}) response))) (defroutes handler (GET "/health" [] (health)) (GET "/users" {params :params} (get-users)) (GET "/users/:id" {{id :id} :params} (get-user id)) (route/not-found (response {:message "Not Found"}))) (def app (-> handler wrap-response-time wrap-params wrap-json-body wrap-json-response))
true
(ns hello-world.handler (:require [compojure.core :refer :all] [compojure.route :as route] [ring.middleware.defaults :refer [wrap-defaults site-defaults]] [ring.middleware.json :refer [wrap-json-body wrap-json-response]] [ring.middleware.params :refer [wrap-params]] [ring.util.response :refer [response]] [cheshire.core :refer :all] [io.aviso.exception :as aviso-ex] [taoensso.timbre :as timbre :refer (log trace debug info warn error fatal report logf tracef debugf infof warnf errorf fatalf reportf spy get-env log-env)])) (defn json-output-fn [{:keys [?err_ vargs_ hostname_ timestamp_ level] :as args}] (let [messages (map (fn [msg] { :timestamp @timestamp_ :level level :hostname @hostname_ :message msg }) @vargs_) err (force ?err_) json-messages (map #(generate-string %) messages)] ;; (print "print default-fn-output" err) (if err (clojure.string/join "\n" (conj json-messages {:ex (aviso-ex/format-exception err)})) (clojure.string/join "\n" (conj json-messages))))) ;; (error (Exception. "my exception message") "text message") ;; (timbre/merge-config! ;; {:appenders {:println {:output-fn json-output-fn}}}) (timbre/merge-config! {:appenders {:println {:output-fn timbre/default-output-fn}}}) (def users [{:id "1" :firstname "foo" :lastname "bar"} {:id "2" :firstname "PI:NAME:<NAME>END_PI" :lastname "PI:NAME:<NAME>END_PI"} {:id "3" :firstname "PI:NAME:<NAME>END_PI" :lastname "PI:NAME:<NAME>END_PI"}]) (defn health "Returns ring response health check" [] (info "health check OK") (response {:status "OK"})) (defn get-users "Returns all users" [] (response users)) (defn get-user "Return user with given id" [id] (let [user (first (filter (fn [user] (when (= (:id user) id) user)) users))] (info user) (if user (response user) (route/not-found (response {:message "Not found"}))))) (defn duration "Returns duration in seconds. Input params should be System/nanoTime" [start] (float (/ (- (System/nanoTime) start) 1000000))) (defn wrap-response-time "Logs duration of response time" [handler] (fn [request] (let [start (System/nanoTime) response (handler request)] (info {:message "response time" :url (:uri request) :response-time-sec (duration start)}) response))) (defroutes handler (GET "/health" [] (health)) (GET "/users" {params :params} (get-users)) (GET "/users/:id" {{id :id} :params} (get-user id)) (route/not-found (response {:message "Not Found"}))) (def app (-> handler wrap-response-time wrap-params wrap-json-body wrap-json-response))
[ { "context": "\"share\"}\n [:a {:class \"share-link\"\n :name name\n :href href}\n [:div {:class (str \"icon-", "end": 249, "score": 0.5534493923187256, "start": 245, "tag": "NAME", "value": "name" } ]
ui/src/cljs/photosure/bio/view.cljs
leblowl/photosure
2
(ns photosure.bio.view (:require [goog.string :as gstr] [photosure.nav.view :as nav])) (defn share-view [{:keys [name class href]}] ^{:key (str "share-" name)} [:li {:class "share"} [:a {:class "share-link" :name name :href href} [:div {:class (str "icon-share " class)}]]]) (defn shares-view [shares] [:ul {:class "shares"} (for [share shares] (share-view share))]) (defn -bio-view [{:keys [*bio]} emit] (let [{:keys [selfie-src about shares]} @*bio] [:div {:id "bio-container"} [:div {:id "bio"} [:div {:id "bio-liner"} [:img {:id "selfie" :src selfie-src}] [:div {:id "info-container"} [:div {:class "about-container"} [:p {:id "about" :dangerouslySetInnerHTML {:__html about}}]] [:div {:class "shares-container"} (shares-view shares)]]]] #_[:div.copyright "© 2020 cpleblow photography"]])) (defn bio-view [vm emit] (nav/nav-view -bio-view vm emit))
80506
(ns photosure.bio.view (:require [goog.string :as gstr] [photosure.nav.view :as nav])) (defn share-view [{:keys [name class href]}] ^{:key (str "share-" name)} [:li {:class "share"} [:a {:class "share-link" :name <NAME> :href href} [:div {:class (str "icon-share " class)}]]]) (defn shares-view [shares] [:ul {:class "shares"} (for [share shares] (share-view share))]) (defn -bio-view [{:keys [*bio]} emit] (let [{:keys [selfie-src about shares]} @*bio] [:div {:id "bio-container"} [:div {:id "bio"} [:div {:id "bio-liner"} [:img {:id "selfie" :src selfie-src}] [:div {:id "info-container"} [:div {:class "about-container"} [:p {:id "about" :dangerouslySetInnerHTML {:__html about}}]] [:div {:class "shares-container"} (shares-view shares)]]]] #_[:div.copyright "© 2020 cpleblow photography"]])) (defn bio-view [vm emit] (nav/nav-view -bio-view vm emit))
true
(ns photosure.bio.view (:require [goog.string :as gstr] [photosure.nav.view :as nav])) (defn share-view [{:keys [name class href]}] ^{:key (str "share-" name)} [:li {:class "share"} [:a {:class "share-link" :name PI:NAME:<NAME>END_PI :href href} [:div {:class (str "icon-share " class)}]]]) (defn shares-view [shares] [:ul {:class "shares"} (for [share shares] (share-view share))]) (defn -bio-view [{:keys [*bio]} emit] (let [{:keys [selfie-src about shares]} @*bio] [:div {:id "bio-container"} [:div {:id "bio"} [:div {:id "bio-liner"} [:img {:id "selfie" :src selfie-src}] [:div {:id "info-container"} [:div {:class "about-container"} [:p {:id "about" :dangerouslySetInnerHTML {:__html about}}]] [:div {:class "shares-container"} (shares-view shares)]]]] #_[:div.copyright "© 2020 cpleblow photography"]])) (defn bio-view [vm emit] (nav/nav-view -bio-view vm emit))
[ { "context": "ction [con db] (jdbc/insert! con :account {:name \"Tony\"}))\n row (first result)]\n (a", "end": 3277, "score": 0.9970312118530273, "start": 3273, "tag": "NAME", "value": "Tony" }, { "context": "t)]\n (assertions\n (:name row) => \"Tony\")))))\n\n(specification \"next-id (MySQL)\" :mysql\n ", "end": 3367, "score": 0.9888157248497009, "start": 3363, "tag": "NAME", "value": "Tony" }, { "context": " [(core/seed-row :account {:id :id/joe :name \"Joe\"})\n (core/seed-row :member {", "end": 4454, "score": 0.9996395111083984, "start": 4451, "tag": "NAME", "value": "Joe" }, { "context": "w :member {:id :id/sam :account_id :id/joe :name \"Sam\"})\n (core/seed-update :accou", "end": 4546, "score": 0.9995641112327576, "start": 4543, "tag": "NAME", "value": "Sam" }, { "context": "into the database\"\n (:name real-joe) => \"Joe\"\n (:last_edited_by real-joe) => sam)))))", "end": 5039, "score": 0.999350905418396, "start": 5036, "tag": "NAME", "value": "Joe" }, { "context": " (core/seed-row :account {:id :id/joe :name \"Joe\" :settings_id :id/joe-settings})\n ", "end": 18365, "score": 0.9991406202316284, "start": 18362, "tag": "NAME", "value": "Joe" }, { "context": " (core/seed-row :account {:id :id/mary :name \"Mary\" :settings_id :id/mary-settings})\n ", "end": 18464, "score": 0.9996706247329712, "start": 18460, "tag": "NAME", "value": "Mary" }, { "context": " (core/seed-row :member {:id :id/sam :name \"Sam\" :account_id :id/joe})\n (core/seed", "end": 18561, "score": 0.9996075630187988, "start": 18558, "tag": "NAME", "value": "Sam" }, { "context": ")\n (core/seed-row :member {:id :id/sally :name \"Sally\" :account_id :id/joe})\n ", "end": 18634, "score": 0.6522341370582581, "start": 18633, "tag": "USERNAME", "value": "s" }, { "context": " (core/seed-row :member {:id :id/sally :name \"Sally\" :account_id :id/joe})\n (core/seed", "end": 18651, "score": 0.9996862411499023, "start": 18646, "tag": "NAME", "value": "Sally" }, { "context": ")\n (core/seed-row :member {:id :id/judy :name \"Judy\" :account_id :id/mary})\n\n ", "end": 18727, "score": 0.8092873096466064, "start": 18723, "tag": "USERNAME", "value": "judy" }, { "context": " (core/seed-row :member {:id :id/judy :name \"Judy\" :account_id :id/mary})\n\n ; many-t", "end": 18739, "score": 0.999663233757019, "start": 18735, "tag": "NAME", "value": "Judy" }, { "context": " :account/name \"Joe\"\n :account/", "end": 21555, "score": 0.979719877243042, "start": 21552, "tag": "NAME", "value": "Joe" }, { "context": " :account/name \"Joe\"\n :account", "end": 22353, "score": 0.9998036623001099, "start": 22350, "tag": "NAME", "value": "Joe" }, { "context": " :account/members [{:db/id sam :person/name \"Sam\"}\n ", "end": 22443, "score": 0.9997725486755371, "start": 22440, "tag": "NAME", "value": "Sam" }, { "context": " {:db/id sally :person/name \"Sally\"}]\n ", "end": 22518, "score": 0.6314101219177246, "start": 22513, "tag": "NAME", "value": "sally" }, { "context": " {:db/id sally :person/name \"Sally\"}]\n :accou", "end": 22538, "score": 0.999752402305603, "start": 22533, "tag": "NAME", "value": "Sally" }, { "context": " :account/name \"Mary\"\n :account", "end": 22775, "score": 0.9998049736022949, "start": 22771, "tag": "NAME", "value": "Mary" }, { "context": " :account/members [{:db/id judy :person/name \"Judy\"}]}]\n query-3 [:db/i", "end": 22975, "score": 0.9997800588607788, "start": 22971, "tag": "NAME", "value": "Judy" }, { "context": "ice-1 :invoice/account {:db/id joe :account/name \"Joe\"}}\n ", "end": 23310, "score": 0.9997297525405884, "start": 23307, "tag": "NAME", "value": "Joe" }, { "context": "ice-2 :invoice/account {:db/id joe :account/name \"Joe\"}}]}]\n root-set #{joe", "end": 23435, "score": 0.9997557401657104, "start": 23432, "tag": "NAME", "value": "Joe" }, { "context": "tation-loop [{:db/id joe :account/name \"Joe\"\n :account", "end": 25330, "score": 0.9994370937347412, "start": 25327, "tag": "NAME", "value": "Joe" }, { "context": " :account/spouse {:db/id mary :account/name \"Mary\"\n ", "end": 25409, "score": 0.8439079523086548, "start": 25405, "tag": "NAME", "value": "mary" }, { "context": "count/spouse {:db/id mary :account/name \"Mary\"\n ", "end": 25429, "score": 0.9994645118713379, "start": 25425, "tag": "NAME", "value": "Mary" }, { "context": " :account/spouse {:db/id joe :account/name \"Joe\"}}}]\n source-table :accou", "end": 25534, "score": 0.9995884299278259, "start": 25531, "tag": "NAME", "value": "Joe" }, { "context": "e\n :account/name \"Joe\"\n :account/invoices [", "end": 27231, "score": 0.9997791647911072, "start": 27228, "tag": "NAME", "value": "Joe" }, { "context": "\n :account/name \"Joe\"\n :account/members ", "end": 27959, "score": 0.9997782111167908, "start": 27956, "tag": "NAME", "value": "Joe" }, { "context": " :account/members [{:db/id sam :person/name \"Sam\"}\n ", "end": 28039, "score": 0.9990566372871399, "start": 28036, "tag": "NAME", "value": "Sam" }, { "context": " {:db/id sally :person/name \"Sally\"}]\n :account/setting", "end": 28124, "score": 0.9993057250976562, "start": 28119, "tag": "NAME", "value": "Sally" }, { "context": "\n :account/name \"Mary\"\n :account/settings ", "end": 28331, "score": 0.9998003244400024, "start": 28327, "tag": "NAME", "value": "Mary" }, { "context": " :account/members [{:db/id judy :person/name \"Judy\"}]}]\n query-3 [:db/id :item/na", "end": 28511, "score": 0.9991559982299805, "start": 28507, "tag": "NAME", "value": "Judy" }, { "context": "ice-1 :invoice/account {:db/id joe :account/name \"Joe\"}}\n ", "end": 28816, "score": 0.9993563890457153, "start": 28813, "tag": "NAME", "value": "Joe" }, { "context": "ice-2 :invoice/account {:db/id joe :account/name \"Joe\"}}]}]\n root-set #{joe}\n ", "end": 28931, "score": 0.9994670152664185, "start": 28928, "tag": "NAME", "value": "Joe" }, { "context": " :account/name \"Joe\"\n :account/inv", "end": 30612, "score": 0.999174952507019, "start": 30609, "tag": "NAME", "value": "Joe" }, { "context": " :account/name \"Joe\"\n :account/me", "end": 31389, "score": 0.9996921420097351, "start": 31386, "tag": "NAME", "value": "Joe" }, { "context": " :account/members [{:db/id sam :person/name \"Sam\"}\n ", "end": 31476, "score": 0.9994726777076721, "start": 31473, "tag": "NAME", "value": "Sam" }, { "context": " {:db/id sally :person/name \"Sally\"}]\n ", "end": 31548, "score": 0.4661017656326294, "start": 31543, "tag": "USERNAME", "value": "sally" }, { "context": " {:db/id sally :person/name \"Sally\"}]\n :account/", "end": 31568, "score": 0.9997182488441467, "start": 31563, "tag": "NAME", "value": "Sally" }, { "context": " :account/name \"Mary\"\n :account/se", "end": 31796, "score": 0.9997543692588806, "start": 31792, "tag": "NAME", "value": "Mary" }, { "context": " :account/members [{:db/id judy :person/name \"Judy\"}]}]\n query-3 [:db/id :", "end": 31990, "score": 0.9997143745422363, "start": 31986, "tag": "NAME", "value": "Judy" }, { "context": "ice-1 :invoice/account {:db/id joe :account/name \"Joe\"}}\n ", "end": 32316, "score": 0.9993950724601746, "start": 32313, "tag": "NAME", "value": "Joe" }, { "context": "ice-2 :invoice/account {:db/id joe :account/name \"Joe\"}}]}]\n expected-filtered-result {:db/id ", "end": 32438, "score": 0.9996946454048157, "start": 32435, "tag": "NAME", "value": "Joe" }, { "context": " :account/name \"Joe\"\n :account/inv", "end": 32561, "score": 0.999623715877533, "start": 32558, "tag": "NAME", "value": "Joe" }, { "context": "y db h2-schema :account/id query-2 (sorted-set joe mary)) => expected-result-2\n \"many-to-many (rev", "end": 33506, "score": 0.955481767654419, "start": 33502, "tag": "NAME", "value": "mary" } ]
src/test/fulcro_sql/core_spec.clj
fulcrologic/fulcro-sql
20
(ns fulcro-sql.core-spec (:require [fulcro-spec.core :refer [assertions specification behavior when-mocking component]] [fulcro-sql.core :as core] [fulcro-sql.test-helpers :refer [with-database]] [clojure.spec.alpha :as s] [clj-time.core :as tm] [com.stuartsierra.component :as component] [clojure.java.jdbc :as jdbc] [clj-time.jdbc] [taoensso.timbre :as timbre]) (:import (com.cognitect.transit TaggedValue) (clojure.lang ExceptionInfo))) (def test-database {:hikaricp-config "test.properties" :migrations ["classpath:migrations/test"]}) (def mysql-database {:hikaricp-config "mysqltest.properties" :driver :mysql :database-name "test" :migrations ["classpath:migrations/mysqltest"]}) (def h2-database {:hikaricp-config "h2test.properties" :driver :h2 :database-name "test" :migrations ["classpath:migrations/h2test"]}) (def test-schema {::core/graph->sql {:person/name :member/name :person/account :member/account_id :settings/auto-open? :settings/auto_open :settings/keyboard-shortcuts? :settings/keyboard_shortcuts} ; NOTE: Om join prop, SQL column props ::core/joins {:account/members (core/to-many [:account/id :member/account_id]) :account/settings (core/to-one [:account/settings_id :settings/id]) :account/spouse (core/to-one [:account/spouse_id :account/id]) :member/account (core/to-one [:member/account_id :account/id]) :account/invoices (core/to-many [:account/id :invoice/account_id]) :invoice/account (core/to-one [:invoice/account_id :account/id]) :invoice/items (core/to-many [:invoice/id :invoice_items/invoice_id :invoice_items/item_id :item/id]) :item/invoices (core/to-many [:item/id :invoice_items/item_id :invoice_items/invoice_id :invoice/id]) :todo-list/items (core/to-many [:todo_list/id :todo_list_item/todo_list_id]) :todo-list-item/subitems (core/to-many [:todo_list_item/id :todo_list_item/parent_item_id])} ; sql table -> id col ::core/pks {}}) (def mysql-schema (assoc test-schema ::core/driver :mysql ::core/database-name "test")) ; needed for create/drop in mysql...there is no drop schema (def h2-schema (assoc test-schema ::core/driver :h2)) (specification "Database Component" :integration (behavior "Can create a functional database pool from HikariCP properties and Flyway migrations." (with-database [db test-database] (let [result (jdbc/with-db-connection [con db] (jdbc/insert! con :account {:name "Tony"})) row (first result)] (assertions (:name row) => "Tony"))))) (specification "next-id (MySQL)" :mysql (behavior "Pulls a monotonically increasing ID from the database (MySQL/MariaDB)" (with-database [db mysql-database] (let [a (core/next-id db mysql-schema :account) b (core/next-id db mysql-schema :account)] (assertions "IDs are numeric integers > 0" (> a 0) => true (> b 0) => true "IDs are increasing" (> b a) => true))))) (specification "next-id (PostgreSQL)" :integration (behavior "Pulls a monotonically increasing ID from the database (PostgreSQL)" (with-database [db test-database] (let [a (core/next-id db test-schema :account) b (core/next-id db test-schema :account)] (assertions "IDs are numeric integers > 0" (> a 0) => true (> b 0) => true "IDs are increasing" (> b a) => true))))) (specification "seed!" :integration (with-database [db test-database] (jdbc/with-db-connection [db db] (let [rows [(core/seed-row :account {:id :id/joe :name "Joe"}) (core/seed-row :member {:id :id/sam :account_id :id/joe :name "Sam"}) (core/seed-update :account :id/joe {:last_edited_by :id/sam})] {:keys [id/joe id/sam] :as tempids} (core/seed! db test-schema rows) real-joe (jdbc/get-by-id db :account joe) real-sam (jdbc/get-by-id db :member sam)] (assertions "Temporary IDs are returned for each row" (pos? joe) => true (pos? sam) => true "The data is inserted into the database" (:name real-joe) => "Joe" (:last_edited_by real-joe) => sam))))) (specification "Table Detection: `table-for`" (let [schema {::core/pks {} ::core/joins {} ::core/graph->sql {:thing/name :sql_table/name :boo/blah :sql_table/prop :the-thing/boo :the-table/bah}}] (assertions ":id and :db/id are ignored" (core/table-for schema [:account/name :db/id :id]) => :account "Detects the correct table name if all of the properties agree" (core/table-for schema [:account/name :account/status]) => :account "Detects the correct table name if all of the properties agree, and there is also a :db/id" (core/table-for schema [:db/id :account/name :account/status]) => :account "Remaps known graph->sql properties to ensure detection" (core/table-for schema [:thing/name :boo/blah]) => :sql_table "Throws an exception if a distinct table name cannot be resolved" (core/table-for schema [:db/id :account/name :user/status]) =throws=> (AssertionError #"Could not determine a single") "Ensures derived table names use underscores instead of hypens" (core/table-for schema [:a-thing/name]) => :a_thing (core/table-for schema [:the-thing/boo]) => :the_table (core/table-for schema [:the-crazy-woods/a]) => :the_crazy_woods "Column remaps are done before table detection" (core/table-for test-schema [:person/name]) => :member "Joins can determine table via the join name" (core/table-for test-schema [:db/id {:account/members [:db/id :member/name]}]) => :account (core/table-for schema [{:the-crazy-woods/a []}]) => :the_crazy_woods (core/table-for schema [{:user/name [:value]}]) => :user))) (def sample-schema {::core/graph->sql {:thing/name :sql_table/name :boo/blah :sql_table/prop :the-thing/boo :the-table/bah} ; FROM AN SQL PERSPECTIVE...Not Om ::core/pks {:account :id :member :id :invoice :id :item :id} ::core/joins { :account/address [:account/address_id :address/id] :account/members [:account/id :member/account_id] :member/account [:member/account_id :account/id] :invoice/items [:invoice/id :invoice_items/invoice_id :invoice_items/item_id :item/id] :item/invoice [:item/id :invoice_items/item_id :invoice_items/line_item_id :invoice/line_item_id]}}) (specification "columns-for" (assertions "Returns a set" (core/columns-for test-schema [:t/c]) =fn=> set? "Resolves the ID column via the derived table name" (core/columns-for test-schema [:db/id :person/name :person/account]) => #{:member/id :member/name :member/account_id}) (assert (s/valid? ::core/schema sample-schema) "Schema is valid") (behavior "id-columns from schema" (assertions "Gives back a set of :table/col keywords that represent the SQL database ID columns" (core/id-columns sample-schema) => #{:account/id :member/id :invoice/id :item/id})) (assertions "Converts an Om property to a proper column selector in SQL, with as AS clause of the Om property" (core/columns-for sample-schema [:thing/name]) => #{:sql_table/name :sql_table/id} (core/columns-for sample-schema [:the-thing/boo]) => #{:the_table/bah :the_table/id} "Joins contribute a column if the table has a join key." (core/columns-for sample-schema [:account/address]) => #{:account/address_id :account/id} (core/columns-for test-schema [:db/id {:account/members [:db/id :member/name]}]) => #{:account/id} "Joins without a local join column contribute their PK instead" (core/columns-for sample-schema [:account/members]) => #{:account/id} (core/columns-for sample-schema [:invoice/items]) => #{:invoice/id} (core/columns-for sample-schema [:item/invoice]) => #{:item/id})) (specification "Column Specification: `column-spec`" (assertions "Translates an sqlprop to an SQL selector" (core/column-spec sample-schema :account/name) => "account.name AS \"account/name\"")) (specification "sqlprop-for-join" (assertions "pulls the ID column if it is a FK back-reference join" (core/sqlprop-for-join test-schema {:account/members [:db/id :member/name]}) => :account/id (core/sqlprop-for-join test-schema {:account/invoices [:db/id :invoice/created_on]}) => :account/id "Pulls the correct FK column when edge goes from the given table" (core/sqlprop-for-join test-schema {:member/account [:db/id :account/name]}) => :member/account_id (core/sqlprop-for-join test-schema {:invoice/account [:db/id :account/name]}) => :invoice/account_id)) (specification "forward? and reverse?" (assertions "forward? is true when the join FK points from the source table to the PK of the target table" (core/forward? test-schema {:account/members [:db/id]}) => false (core/forward? test-schema {:account/settings [:db/id]}) => true (core/forward? test-schema {:invoice/items [:db/id]}) => false (core/forward? test-schema :account/members) => false (core/forward? test-schema :account/settings) => true (core/forward? test-schema :invoice/items) => false "reverse? is true when the join FK points from the source table to the PK of the target table" (core/reverse? test-schema {:account/members [:db/id]}) => true (core/reverse? test-schema {:account/settings [:db/id]}) => false (core/reverse? test-schema {:invoice/items [:db/id]}) => true)) (specification "filter-params->filters" (assertions "Converts a map of column filter parameters into filters for run-query" (core/filter-params->filters test-schema {:item/deleted {:eq 1 :max-depth 2}}) => {:item [(core/filter-where "item.deleted = ?" [1] 1 2)]} "Can specify min and max depth" (core/filter-params->filters test-schema {:item/deleted {:eq 1 :max-depth 2} :member/id {:gt 0 :min-depth 4}}) => {:item [(core/filter-where "item.deleted = ?" [1] 1 2)] :member [(core/filter-where "member.id > ?" [0] 4 1000)]} "Support null checks" (core/filter-params->filters test-schema {:item/other {:null true} :account/id {:null false}}) => {:item [(core/filter-where "item.other IS NULL" [])] :account [(core/filter-where "account.id IS NOT NULL" [])]} "Supports multiple filters on the same table" (core/filter-params->filters test-schema {:item/deleted {:eq 1 :max-depth 2} :item/quantity {:gt 0} }) => {:item [(core/filter-where "item.deleted = ?" [1] 1 2) (core/filter-where "item.quantity > ?" [0])]} "Throws a descriptive error when an unknown operation is used" (core/filter-params->filters test-schema {:item/deleted {:boo 1}}) =throws=> (ExceptionInfo #"Invalid operation in rule" (fn [e] (= (ex-data e) {:boo 1}))))) (specification "row-filter" (assertions "Returns [nil nil] if no filtering is needed" (#'core/row-filter test-schema {} #{:account}) => [nil nil] "The first element returned is an AND-joined clause of ONLY conditions that apply to the given table(s)" (first (#'core/row-filter test-schema {:account [(core/filter-where "account.deleted <> ?" [44])] :member [(core/filter-where "member.boo = ?" [2])]} #{:account})) => "(account.deleted <> ?)" (first (#'core/row-filter test-schema {:account [(core/filter-where "account.deleted <> ?" [44])] :item [(core/filter-where "item.id = ?" [44])] :member [(core/filter-where "member.deleted = ?" [44])]} #{:account :member})) => "(account.deleted <> ?) AND (member.deleted = ?)" "Honors the minimum depth" (first (#'core/row-filter test-schema {::core/depth 2 :account [(core/filter-where "account.deleted <> ?" [44] 3 1000)]} #{:account})) => nil (first (#'core/row-filter test-schema {::core/depth 3 :account [(core/filter-where "account.deleted <> ?" [44] 3 1000)]} #{:account})) =fn=> seq "Honors the maximum depth" (first (#'core/row-filter test-schema {::core/depth 2 :account [(core/filter-where "account.deleted <> ?" [44] 1 1)]} #{:account})) => nil (first (#'core/row-filter test-schema {::core/depth 1 :account [(core/filter-where "account.deleted <> ?" [44] 1 1)]} #{:account})) =fn=> seq "The second element returned is an in-order vector of parameters to use in the SQL clause" (second (#'core/row-filter test-schema {:account [(core/filter-where "account.deleted <> ?" [44])] :item [(core/filter-where "item.id = ?" [44])] :member [(core/filter-where "member.deleted = ?" [false])]} #{:account :member})) => [44 false] (second (#'core/row-filter test-schema {:account [(core/filter-where "account.deleted <> ?" [44])] :member [(core/filter-where "member.boo = ?" [2])]} #{:account})) => [44])) (specification "Single-level query-for query generation" (assertions "Generates a base non-recursive SQL query that includes necessary join resolution columns" (core/query-for test-schema nil [:db/id {:account/members [:db/id :member/name]}] (sorted-set 1 5 7 9)) => ["SELECT account.id AS \"account/id\" FROM account WHERE account.id IN (1,5,7,9)" nil] (core/query-for test-schema :account/members [:db/id :member/name] (sorted-set 1 5)) => ["SELECT member.account_id AS \"member/account_id\",member.id AS \"member/id\",member.name AS \"member/name\" FROM member WHERE member.account_id IN (1,5)" nil] (core/query-for test-schema :account/settings [:db/id :settings/auto-open?] (sorted-set 3)) => ["SELECT settings.auto_open AS \"settings/auto_open\",settings.id AS \"settings/id\" FROM settings WHERE settings.id IN (3)" nil] (core/query-for test-schema nil [:db/id :boo/name :boo/bah] #{3}) => ["SELECT boo.bah AS \"boo/bah\",boo.id AS \"boo/id\",boo.name AS \"boo/name\" FROM boo WHERE boo.id IN (3)" nil] "Derives correct SQL table name if possible" (core/query-for test-schema nil [:db/id {:account/members [:db/id :member/name]}] (sorted-set 1 5 7 9)) => ["SELECT account.id AS \"account/id\" FROM account WHERE account.id IN (1,5,7,9)" nil] (core/query-for test-schema nil [:db/id] (sorted-set 1 5 7 9)) =throws=> (AssertionError #"Could not determine") "Supports adding additional filter criteria" (core/query-for test-schema nil [:db/id {:account/members [:db/id :member/name]}] (sorted-set 1 5 7 9) {:account [(core/filter-where "account.deleted = ?" [false])]}) => ["SELECT account.id AS \"account/id\" FROM account WHERE (account.deleted = ?) AND account.id IN (1,5,7,9)" [false]] (core/query-for test-schema nil [:db/id {:account/members [:db/id :member/name]}] (sorted-set 1 5 7 9) {:account [(core/filter-where "account.deleted = ? AND account.age > ?" [false 22])]}) => ["SELECT account.id AS \"account/id\" FROM account WHERE (account.deleted = ? AND account.age > ?) AND account.id IN (1,5,7,9)" [false, 22]])) (specification "Run-query internals" (assertions "Returns nil if there are no IDs in the root set" (#'core/run-query* :db test-schema :prop [:a] {} {}) => nil) (behavior "Increments recursion depth tracking" (when-mocking (core/query-for s prop query ids filtering) =1x=> (do (assertions "Filtering is given the depth when generating the query" (get filtering ::core/depth) => 4) [nil nil]) (jdbc/query db params) =1x=> [] (core/compute-join-results db schema query rows filtering recursion-tracking) =1x=> (do (assertions "Passes the new depth to any recursive computation of join results" (::core/depth recursion-tracking) => 4) {}) (#'core/run-query* :db test-schema :prop [:a] {} #{1} {::core/depth 3})))) (def test-rows [; basic to-one and to-many (core/seed-row :settings {:id :id/joe-settings :auto_open true :keyboard_shortcuts false}) (core/seed-row :settings {:id :id/mary-settings :auto_open false :keyboard_shortcuts true}) (core/seed-row :account {:id :id/joe :name "Joe" :settings_id :id/joe-settings}) (core/seed-row :account {:id :id/mary :name "Mary" :settings_id :id/mary-settings}) (core/seed-row :member {:id :id/sam :name "Sam" :account_id :id/joe}) (core/seed-row :member {:id :id/sally :name "Sally" :account_id :id/joe}) (core/seed-row :member {:id :id/judy :name "Judy" :account_id :id/mary}) ; many-to-many (core/seed-row :invoice {:id :id/invoice-1 :account_id :id/joe :invoice_date (tm/date-time 2017 03 04)}) (core/seed-row :invoice {:id :id/invoice-2 :account_id :id/joe :invoice_date (tm/date-time 2016 01 02)}) (core/seed-row :item {:id :id/gadget :name "gadget"}) (core/seed-row :item {:id :id/widget :name "widget"}) (core/seed-row :item {:id :id/spanner :name "spanner"}) (core/seed-row :invoice_items {:id :join-row-1 :invoice_id :id/invoice-1 :item_id :id/gadget :invoice_items/quantity 2}) (core/seed-row :invoice_items {:id :join-row-2 :invoice_id :id/invoice-2 :item_id :id/widget :invoice_items/quantity 8}) (core/seed-row :invoice_items {:id :join-row-3 :invoice_id :id/invoice-2 :item_id :id/spanner :invoice_items/quantity 1}) (core/seed-row :invoice_items {:id :join-row-4 :invoice_id :id/invoice-2 :item_id :id/gadget :invoice_items/quantity 5}) ; graph loop (core/seed-update :account :id/joe {:spouse_id :id/mary}) (core/seed-update :account :id/mary {:spouse_id :id/joe}) ; non-looping recursion with some depth (core/seed-row :todo_list {:id :list-1 :name "Things to do"}) (core/seed-row :todo_list_item {:id :item-1 :label "A" :todo_list_id :list-1}) (core/seed-row :todo_list_item {:id :item-1-1 :label "A.1" :parent_item_id :item-1}) (core/seed-row :todo_list_item {:id :item-1-1-1 :label "A.1.1" :parent_item_id :item-1-1}) (core/seed-row :todo_list_item {:id :item-2 :label "B" :todo_list_id :list-1}) (core/seed-row :todo_list_item {:id :item-2-1 :label "B.1" :parent_item_id :item-2}) (core/seed-row :todo_list_item {:id :item-2-2 :label "B.2" :parent_item_id :item-2})]) (specification "Integration Tests for Graph Queries (PostgreSQL)" :integration (with-database [db test-database] (let [{:keys [id/joe id/mary id/invoice-1 id/invoice-2 id/gadget id/widget id/spanner id/sam id/sally id/judy id/joe-settings id/mary-settings list-1 item-1 item-1-1 item-1-1-1 item-2 item-2-1 item-2-2]} (core/seed! db test-schema test-rows) query [:db/id :account/name {:account/invoices [:db/id ;{:invoice/invoice_items [:invoice_items/quantity]} {:invoice/items [:db/id :item/name]}]}] expected-result {:db/id joe :account/name "Joe" :account/invoices [{:db/id invoice-1 :invoice/items [{:db/id gadget :item/name "gadget"}]} {:db/id invoice-2 :invoice/items [{:db/id gadget :item/name "gadget"} {:db/id widget :item/name "widget"} {:db/id spanner :item/name "spanner"}]}]} query-2 [:db/id :account/name {:account/members [:db/id :person/name]} {:account/settings [:db/id :settings/auto-open?]}] expected-result-2 [{:db/id joe :account/name "Joe" :account/members [{:db/id sam :person/name "Sam"} {:db/id sally :person/name "Sally"}] :account/settings {:db/id joe-settings :settings/auto-open? true}} {:db/id mary :account/name "Mary" :account/settings {:db/id mary-settings :settings/auto-open? false} :account/members [{:db/id judy :person/name "Judy"}]}] query-3 [:db/id :item/name {:item/invoices [:db/id {:invoice/account [:db/id :account/name]}]}] expected-result-3 [{:db/id gadget :item/name "gadget" :item/invoices [{:db/id invoice-1 :invoice/account {:db/id joe :account/name "Joe"}} {:db/id invoice-2 :invoice/account {:db/id joe :account/name "Joe"}}]}] root-set #{joe} recursive-query '[:db/id :todo-list/name {:todo-list/items [:db/id :todo-list-item/label {:todo-list-item/subitems ...}]}] recursive-query-depth '[:db/id :todo-list/name {:todo-list/items [:db/id :todo-list-item/label {:todo-list-item/subitems 1}]}] recursive-query-loop '[:db/id :account/name {:account/spouse ...}] recursive-expectation [{:db/id list-1 :todo-list/name "Things to do" :todo-list/items [{:db/id item-1 :todo-list-item/label "A" :todo-list-item/subitems [{:db/id item-1-1 :todo-list-item/label "A.1" :todo-list-item/subitems [{:db/id item-1-1-1 :todo-list-item/label "A.1.1"}]}]} {:db/id item-2 :todo-list-item/label "B" :todo-list-item/subitems [{:db/id item-2-1 :todo-list-item/label "B.1"} {:db/id item-2-2 :todo-list-item/label "B.2"}]}]}] recursive-expectation-depth [{:db/id list-1 :todo-list/name "Things to do" :todo-list/items [{:db/id item-1 :todo-list-item/label "A" :todo-list-item/subitems [{:db/id item-1-1 :todo-list-item/label "A.1"}]} {:db/id item-2 :todo-list-item/label "B" :todo-list-item/subitems [{:db/id item-2-1 :todo-list-item/label "B.1"} {:db/id item-2-2 :todo-list-item/label "B.2"}]}]}] recursive-expectation-loop [{:db/id joe :account/name "Joe" :account/spouse {:db/id mary :account/name "Mary" :account/spouse {:db/id joe :account/name "Joe"}}}] source-table :account] (assertions "to-many" (core/run-query db test-schema :account/id query #{joe}) => [expected-result] "parallel subjoins" (core/run-query db test-schema :account/id query-2 (sorted-set joe mary)) => expected-result-2 "recursion" (core/run-query db test-schema :todo-list/id recursive-query (sorted-set list-1)) => recursive-expectation "recursion with depth limit" (core/run-query db test-schema :todo-list/id recursive-query-depth (sorted-set list-1)) => recursive-expectation-depth "recursive loop detection" (core/run-query db test-schema :account/id recursive-query-loop (sorted-set joe)) => recursive-expectation-loop "reverse many-to-many" (core/run-query db test-schema :account/id query-3 (sorted-set gadget)) => expected-result-3)))) (specification "MySQL Integration Tests" :mysql (with-database [db mysql-database] (let [{:keys [id/joe id/mary id/invoice-1 id/invoice-2 id/gadget id/widget id/spanner id/sam id/sally id/judy id/joe-settings id/mary-settings]} (core/seed! db mysql-schema test-rows) query [:db/id :account/name {:account/invoices [:db/id ; TODO: data on join table ;{:invoice/invoice_items [:invoice_items/quantity]} {:invoice/items [:db/id :item/name]}]}] expected-result {:db/id joe :account/name "Joe" :account/invoices [{:db/id invoice-1 :invoice/items [{:db/id gadget :item/name "gadget"}]} {:db/id invoice-2 :invoice/items [{:db/id widget :item/name "widget"} {:db/id spanner :item/name "spanner"} {:db/id gadget :item/name "gadget"}]}]} query-2 [:db/id :account/name {:account/members [:db/id :person/name]} {:account/settings [:db/id :settings/auto-open?]}] expected-result-2 [{:db/id joe :account/name "Joe" :account/members [{:db/id sam :person/name "Sam"} {:db/id sally :person/name "Sally"}] :account/settings {:db/id joe-settings :settings/auto-open? true}} {:db/id mary :account/name "Mary" :account/settings {:db/id mary-settings :settings/auto-open? false} :account/members [{:db/id judy :person/name "Judy"}]}] query-3 [:db/id :item/name {:item/invoices [:db/id {:invoice/account [:db/id :account/name]}]}] expected-result-3 [{:db/id gadget :item/name "gadget" :item/invoices [{:db/id invoice-1 :invoice/account {:db/id joe :account/name "Joe"}} {:db/id invoice-2 :invoice/account {:db/id joe :account/name "Joe"}}]}] root-set #{joe} source-table :account fix-nums (fn [result] (clojure.walk/postwalk (fn [ele] (if (= java.math.BigInteger (type ele)) (long ele) ele)) result))] (assertions "many-to-many (forward)" (fix-nums (core/run-query db mysql-schema :account/id query #{joe})) => (fix-nums [expected-result]) "one-to-many query (forward)" (fix-nums (core/run-query db mysql-schema :account/id query-2 (sorted-set joe mary))) => (fix-nums expected-result-2) "many-to-many (reverse)" (core/run-query db mysql-schema :account/id query-3 (sorted-set gadget)) => expected-result-3)))) (specification "H2 Integration Tests" :h2 (with-database [db h2-database] (let [{:keys [id/joe id/mary id/invoice-1 id/invoice-2 id/gadget id/widget id/spanner id/sam id/sally id/judy id/joe-settings id/mary-settings]} (core/seed! db h2-schema test-rows) query [:db/id :account/name {:account/invoices [:db/id ; TODO: data on join table ;{:invoice/invoice_items [:invoice_items/quantity]} {:invoice/items [:db/id :item/name]}]}] expected-result {:db/id joe :account/name "Joe" :account/invoices [{:db/id invoice-1 :invoice/items [{:db/id gadget :item/name "gadget"}]} {:db/id invoice-2 :invoice/items [{:db/id widget :item/name "widget"} {:db/id spanner :item/name "spanner"} {:db/id gadget :item/name "gadget"}]}]} query-2 [:db/id :account/name {:account/members [:db/id :person/name]} {:account/settings [:db/id :settings/auto-open?]}] expected-result-2 [{:db/id joe :account/name "Joe" :account/members [{:db/id sam :person/name "Sam"} {:db/id sally :person/name "Sally"}] :account/settings {:db/id joe-settings :settings/auto-open? true}} {:db/id mary :account/name "Mary" :account/settings {:db/id mary-settings :settings/auto-open? false} :account/members [{:db/id judy :person/name "Judy"}]}] query-3 [:db/id :item/name {:item/invoices [:db/id {:invoice/account [:db/id :account/name]}]}] expected-result-3 [{:db/id gadget :item/name "gadget" :item/invoices [{:db/id invoice-1 :invoice/account {:db/id joe :account/name "Joe"}} {:db/id invoice-2 :invoice/account {:db/id joe :account/name "Joe"}}]}] expected-filtered-result {:db/id joe :account/name "Joe" :account/invoices [{:db/id invoice-1 :invoice/items [{:db/id gadget :item/name "gadget"}]} {:db/id invoice-2 :invoice/items [{:db/id gadget :item/name "gadget"}]}]} root-set #{joe} source-table :account fix-nums (fn [result] (clojure.walk/postwalk (fn [ele] (if (= java.math.BigInteger (type ele)) (long ele) ele)) result))] (assertions "many-to-many (forward)" (core/run-query db h2-schema :account/id query #{joe}) => [expected-result] "one-to-many query (forward)" (core/run-query db h2-schema :account/id query-2 (sorted-set joe mary)) => expected-result-2 "many-to-many (reverse)" (core/run-query db h2-schema :account/id query-3 (sorted-set gadget)) => expected-result-3 "filtered by explicit expression" (core/run-query db h2-schema :account/id query #{joe} {:item [(core/filter-where "item.name = ?" ["gadget"])]}) => [expected-filtered-result] "filtered by params" (core/run-query db h2-schema :account/id query #{joe} (core/filter-params->filters h2-schema {:item/name {:eq "gadget"}})) => [expected-filtered-result] "With min-depth limited filters" (core/run-query db h2-schema :account/id query #{joe} (core/filter-params->filters h2-schema {:item/name {:eq "gadget" :min-depth 3}})) => [expected-filtered-result] (core/run-query db h2-schema :account/id query #{joe} (core/filter-params->filters h2-schema {:item/name {:eq "gadget" :min-depth 4}})) => [expected-result] "With max-depth limited filters" (core/run-query db h2-schema :account/id query #{joe} (core/filter-params->filters h2-schema {:item/name {:eq "gadget" :max-depth 3}})) => [expected-filtered-result] (core/run-query db h2-schema :account/id query #{joe} (core/filter-params->filters h2-schema {:item/name {:eq "gadget" :max-depth 2}})) => [expected-result])))) (comment ;; useful to run in the REPL to eliminate info messages from tests: (do (require 'taoensso.timbre) (taoensso.timbre/set-level! :error)))
6748
(ns fulcro-sql.core-spec (:require [fulcro-spec.core :refer [assertions specification behavior when-mocking component]] [fulcro-sql.core :as core] [fulcro-sql.test-helpers :refer [with-database]] [clojure.spec.alpha :as s] [clj-time.core :as tm] [com.stuartsierra.component :as component] [clojure.java.jdbc :as jdbc] [clj-time.jdbc] [taoensso.timbre :as timbre]) (:import (com.cognitect.transit TaggedValue) (clojure.lang ExceptionInfo))) (def test-database {:hikaricp-config "test.properties" :migrations ["classpath:migrations/test"]}) (def mysql-database {:hikaricp-config "mysqltest.properties" :driver :mysql :database-name "test" :migrations ["classpath:migrations/mysqltest"]}) (def h2-database {:hikaricp-config "h2test.properties" :driver :h2 :database-name "test" :migrations ["classpath:migrations/h2test"]}) (def test-schema {::core/graph->sql {:person/name :member/name :person/account :member/account_id :settings/auto-open? :settings/auto_open :settings/keyboard-shortcuts? :settings/keyboard_shortcuts} ; NOTE: Om join prop, SQL column props ::core/joins {:account/members (core/to-many [:account/id :member/account_id]) :account/settings (core/to-one [:account/settings_id :settings/id]) :account/spouse (core/to-one [:account/spouse_id :account/id]) :member/account (core/to-one [:member/account_id :account/id]) :account/invoices (core/to-many [:account/id :invoice/account_id]) :invoice/account (core/to-one [:invoice/account_id :account/id]) :invoice/items (core/to-many [:invoice/id :invoice_items/invoice_id :invoice_items/item_id :item/id]) :item/invoices (core/to-many [:item/id :invoice_items/item_id :invoice_items/invoice_id :invoice/id]) :todo-list/items (core/to-many [:todo_list/id :todo_list_item/todo_list_id]) :todo-list-item/subitems (core/to-many [:todo_list_item/id :todo_list_item/parent_item_id])} ; sql table -> id col ::core/pks {}}) (def mysql-schema (assoc test-schema ::core/driver :mysql ::core/database-name "test")) ; needed for create/drop in mysql...there is no drop schema (def h2-schema (assoc test-schema ::core/driver :h2)) (specification "Database Component" :integration (behavior "Can create a functional database pool from HikariCP properties and Flyway migrations." (with-database [db test-database] (let [result (jdbc/with-db-connection [con db] (jdbc/insert! con :account {:name "<NAME>"})) row (first result)] (assertions (:name row) => "<NAME>"))))) (specification "next-id (MySQL)" :mysql (behavior "Pulls a monotonically increasing ID from the database (MySQL/MariaDB)" (with-database [db mysql-database] (let [a (core/next-id db mysql-schema :account) b (core/next-id db mysql-schema :account)] (assertions "IDs are numeric integers > 0" (> a 0) => true (> b 0) => true "IDs are increasing" (> b a) => true))))) (specification "next-id (PostgreSQL)" :integration (behavior "Pulls a monotonically increasing ID from the database (PostgreSQL)" (with-database [db test-database] (let [a (core/next-id db test-schema :account) b (core/next-id db test-schema :account)] (assertions "IDs are numeric integers > 0" (> a 0) => true (> b 0) => true "IDs are increasing" (> b a) => true))))) (specification "seed!" :integration (with-database [db test-database] (jdbc/with-db-connection [db db] (let [rows [(core/seed-row :account {:id :id/joe :name "<NAME>"}) (core/seed-row :member {:id :id/sam :account_id :id/joe :name "<NAME>"}) (core/seed-update :account :id/joe {:last_edited_by :id/sam})] {:keys [id/joe id/sam] :as tempids} (core/seed! db test-schema rows) real-joe (jdbc/get-by-id db :account joe) real-sam (jdbc/get-by-id db :member sam)] (assertions "Temporary IDs are returned for each row" (pos? joe) => true (pos? sam) => true "The data is inserted into the database" (:name real-joe) => "<NAME>" (:last_edited_by real-joe) => sam))))) (specification "Table Detection: `table-for`" (let [schema {::core/pks {} ::core/joins {} ::core/graph->sql {:thing/name :sql_table/name :boo/blah :sql_table/prop :the-thing/boo :the-table/bah}}] (assertions ":id and :db/id are ignored" (core/table-for schema [:account/name :db/id :id]) => :account "Detects the correct table name if all of the properties agree" (core/table-for schema [:account/name :account/status]) => :account "Detects the correct table name if all of the properties agree, and there is also a :db/id" (core/table-for schema [:db/id :account/name :account/status]) => :account "Remaps known graph->sql properties to ensure detection" (core/table-for schema [:thing/name :boo/blah]) => :sql_table "Throws an exception if a distinct table name cannot be resolved" (core/table-for schema [:db/id :account/name :user/status]) =throws=> (AssertionError #"Could not determine a single") "Ensures derived table names use underscores instead of hypens" (core/table-for schema [:a-thing/name]) => :a_thing (core/table-for schema [:the-thing/boo]) => :the_table (core/table-for schema [:the-crazy-woods/a]) => :the_crazy_woods "Column remaps are done before table detection" (core/table-for test-schema [:person/name]) => :member "Joins can determine table via the join name" (core/table-for test-schema [:db/id {:account/members [:db/id :member/name]}]) => :account (core/table-for schema [{:the-crazy-woods/a []}]) => :the_crazy_woods (core/table-for schema [{:user/name [:value]}]) => :user))) (def sample-schema {::core/graph->sql {:thing/name :sql_table/name :boo/blah :sql_table/prop :the-thing/boo :the-table/bah} ; FROM AN SQL PERSPECTIVE...Not Om ::core/pks {:account :id :member :id :invoice :id :item :id} ::core/joins { :account/address [:account/address_id :address/id] :account/members [:account/id :member/account_id] :member/account [:member/account_id :account/id] :invoice/items [:invoice/id :invoice_items/invoice_id :invoice_items/item_id :item/id] :item/invoice [:item/id :invoice_items/item_id :invoice_items/line_item_id :invoice/line_item_id]}}) (specification "columns-for" (assertions "Returns a set" (core/columns-for test-schema [:t/c]) =fn=> set? "Resolves the ID column via the derived table name" (core/columns-for test-schema [:db/id :person/name :person/account]) => #{:member/id :member/name :member/account_id}) (assert (s/valid? ::core/schema sample-schema) "Schema is valid") (behavior "id-columns from schema" (assertions "Gives back a set of :table/col keywords that represent the SQL database ID columns" (core/id-columns sample-schema) => #{:account/id :member/id :invoice/id :item/id})) (assertions "Converts an Om property to a proper column selector in SQL, with as AS clause of the Om property" (core/columns-for sample-schema [:thing/name]) => #{:sql_table/name :sql_table/id} (core/columns-for sample-schema [:the-thing/boo]) => #{:the_table/bah :the_table/id} "Joins contribute a column if the table has a join key." (core/columns-for sample-schema [:account/address]) => #{:account/address_id :account/id} (core/columns-for test-schema [:db/id {:account/members [:db/id :member/name]}]) => #{:account/id} "Joins without a local join column contribute their PK instead" (core/columns-for sample-schema [:account/members]) => #{:account/id} (core/columns-for sample-schema [:invoice/items]) => #{:invoice/id} (core/columns-for sample-schema [:item/invoice]) => #{:item/id})) (specification "Column Specification: `column-spec`" (assertions "Translates an sqlprop to an SQL selector" (core/column-spec sample-schema :account/name) => "account.name AS \"account/name\"")) (specification "sqlprop-for-join" (assertions "pulls the ID column if it is a FK back-reference join" (core/sqlprop-for-join test-schema {:account/members [:db/id :member/name]}) => :account/id (core/sqlprop-for-join test-schema {:account/invoices [:db/id :invoice/created_on]}) => :account/id "Pulls the correct FK column when edge goes from the given table" (core/sqlprop-for-join test-schema {:member/account [:db/id :account/name]}) => :member/account_id (core/sqlprop-for-join test-schema {:invoice/account [:db/id :account/name]}) => :invoice/account_id)) (specification "forward? and reverse?" (assertions "forward? is true when the join FK points from the source table to the PK of the target table" (core/forward? test-schema {:account/members [:db/id]}) => false (core/forward? test-schema {:account/settings [:db/id]}) => true (core/forward? test-schema {:invoice/items [:db/id]}) => false (core/forward? test-schema :account/members) => false (core/forward? test-schema :account/settings) => true (core/forward? test-schema :invoice/items) => false "reverse? is true when the join FK points from the source table to the PK of the target table" (core/reverse? test-schema {:account/members [:db/id]}) => true (core/reverse? test-schema {:account/settings [:db/id]}) => false (core/reverse? test-schema {:invoice/items [:db/id]}) => true)) (specification "filter-params->filters" (assertions "Converts a map of column filter parameters into filters for run-query" (core/filter-params->filters test-schema {:item/deleted {:eq 1 :max-depth 2}}) => {:item [(core/filter-where "item.deleted = ?" [1] 1 2)]} "Can specify min and max depth" (core/filter-params->filters test-schema {:item/deleted {:eq 1 :max-depth 2} :member/id {:gt 0 :min-depth 4}}) => {:item [(core/filter-where "item.deleted = ?" [1] 1 2)] :member [(core/filter-where "member.id > ?" [0] 4 1000)]} "Support null checks" (core/filter-params->filters test-schema {:item/other {:null true} :account/id {:null false}}) => {:item [(core/filter-where "item.other IS NULL" [])] :account [(core/filter-where "account.id IS NOT NULL" [])]} "Supports multiple filters on the same table" (core/filter-params->filters test-schema {:item/deleted {:eq 1 :max-depth 2} :item/quantity {:gt 0} }) => {:item [(core/filter-where "item.deleted = ?" [1] 1 2) (core/filter-where "item.quantity > ?" [0])]} "Throws a descriptive error when an unknown operation is used" (core/filter-params->filters test-schema {:item/deleted {:boo 1}}) =throws=> (ExceptionInfo #"Invalid operation in rule" (fn [e] (= (ex-data e) {:boo 1}))))) (specification "row-filter" (assertions "Returns [nil nil] if no filtering is needed" (#'core/row-filter test-schema {} #{:account}) => [nil nil] "The first element returned is an AND-joined clause of ONLY conditions that apply to the given table(s)" (first (#'core/row-filter test-schema {:account [(core/filter-where "account.deleted <> ?" [44])] :member [(core/filter-where "member.boo = ?" [2])]} #{:account})) => "(account.deleted <> ?)" (first (#'core/row-filter test-schema {:account [(core/filter-where "account.deleted <> ?" [44])] :item [(core/filter-where "item.id = ?" [44])] :member [(core/filter-where "member.deleted = ?" [44])]} #{:account :member})) => "(account.deleted <> ?) AND (member.deleted = ?)" "Honors the minimum depth" (first (#'core/row-filter test-schema {::core/depth 2 :account [(core/filter-where "account.deleted <> ?" [44] 3 1000)]} #{:account})) => nil (first (#'core/row-filter test-schema {::core/depth 3 :account [(core/filter-where "account.deleted <> ?" [44] 3 1000)]} #{:account})) =fn=> seq "Honors the maximum depth" (first (#'core/row-filter test-schema {::core/depth 2 :account [(core/filter-where "account.deleted <> ?" [44] 1 1)]} #{:account})) => nil (first (#'core/row-filter test-schema {::core/depth 1 :account [(core/filter-where "account.deleted <> ?" [44] 1 1)]} #{:account})) =fn=> seq "The second element returned is an in-order vector of parameters to use in the SQL clause" (second (#'core/row-filter test-schema {:account [(core/filter-where "account.deleted <> ?" [44])] :item [(core/filter-where "item.id = ?" [44])] :member [(core/filter-where "member.deleted = ?" [false])]} #{:account :member})) => [44 false] (second (#'core/row-filter test-schema {:account [(core/filter-where "account.deleted <> ?" [44])] :member [(core/filter-where "member.boo = ?" [2])]} #{:account})) => [44])) (specification "Single-level query-for query generation" (assertions "Generates a base non-recursive SQL query that includes necessary join resolution columns" (core/query-for test-schema nil [:db/id {:account/members [:db/id :member/name]}] (sorted-set 1 5 7 9)) => ["SELECT account.id AS \"account/id\" FROM account WHERE account.id IN (1,5,7,9)" nil] (core/query-for test-schema :account/members [:db/id :member/name] (sorted-set 1 5)) => ["SELECT member.account_id AS \"member/account_id\",member.id AS \"member/id\",member.name AS \"member/name\" FROM member WHERE member.account_id IN (1,5)" nil] (core/query-for test-schema :account/settings [:db/id :settings/auto-open?] (sorted-set 3)) => ["SELECT settings.auto_open AS \"settings/auto_open\",settings.id AS \"settings/id\" FROM settings WHERE settings.id IN (3)" nil] (core/query-for test-schema nil [:db/id :boo/name :boo/bah] #{3}) => ["SELECT boo.bah AS \"boo/bah\",boo.id AS \"boo/id\",boo.name AS \"boo/name\" FROM boo WHERE boo.id IN (3)" nil] "Derives correct SQL table name if possible" (core/query-for test-schema nil [:db/id {:account/members [:db/id :member/name]}] (sorted-set 1 5 7 9)) => ["SELECT account.id AS \"account/id\" FROM account WHERE account.id IN (1,5,7,9)" nil] (core/query-for test-schema nil [:db/id] (sorted-set 1 5 7 9)) =throws=> (AssertionError #"Could not determine") "Supports adding additional filter criteria" (core/query-for test-schema nil [:db/id {:account/members [:db/id :member/name]}] (sorted-set 1 5 7 9) {:account [(core/filter-where "account.deleted = ?" [false])]}) => ["SELECT account.id AS \"account/id\" FROM account WHERE (account.deleted = ?) AND account.id IN (1,5,7,9)" [false]] (core/query-for test-schema nil [:db/id {:account/members [:db/id :member/name]}] (sorted-set 1 5 7 9) {:account [(core/filter-where "account.deleted = ? AND account.age > ?" [false 22])]}) => ["SELECT account.id AS \"account/id\" FROM account WHERE (account.deleted = ? AND account.age > ?) AND account.id IN (1,5,7,9)" [false, 22]])) (specification "Run-query internals" (assertions "Returns nil if there are no IDs in the root set" (#'core/run-query* :db test-schema :prop [:a] {} {}) => nil) (behavior "Increments recursion depth tracking" (when-mocking (core/query-for s prop query ids filtering) =1x=> (do (assertions "Filtering is given the depth when generating the query" (get filtering ::core/depth) => 4) [nil nil]) (jdbc/query db params) =1x=> [] (core/compute-join-results db schema query rows filtering recursion-tracking) =1x=> (do (assertions "Passes the new depth to any recursive computation of join results" (::core/depth recursion-tracking) => 4) {}) (#'core/run-query* :db test-schema :prop [:a] {} #{1} {::core/depth 3})))) (def test-rows [; basic to-one and to-many (core/seed-row :settings {:id :id/joe-settings :auto_open true :keyboard_shortcuts false}) (core/seed-row :settings {:id :id/mary-settings :auto_open false :keyboard_shortcuts true}) (core/seed-row :account {:id :id/joe :name "<NAME>" :settings_id :id/joe-settings}) (core/seed-row :account {:id :id/mary :name "<NAME>" :settings_id :id/mary-settings}) (core/seed-row :member {:id :id/sam :name "<NAME>" :account_id :id/joe}) (core/seed-row :member {:id :id/sally :name "<NAME>" :account_id :id/joe}) (core/seed-row :member {:id :id/judy :name "<NAME>" :account_id :id/mary}) ; many-to-many (core/seed-row :invoice {:id :id/invoice-1 :account_id :id/joe :invoice_date (tm/date-time 2017 03 04)}) (core/seed-row :invoice {:id :id/invoice-2 :account_id :id/joe :invoice_date (tm/date-time 2016 01 02)}) (core/seed-row :item {:id :id/gadget :name "gadget"}) (core/seed-row :item {:id :id/widget :name "widget"}) (core/seed-row :item {:id :id/spanner :name "spanner"}) (core/seed-row :invoice_items {:id :join-row-1 :invoice_id :id/invoice-1 :item_id :id/gadget :invoice_items/quantity 2}) (core/seed-row :invoice_items {:id :join-row-2 :invoice_id :id/invoice-2 :item_id :id/widget :invoice_items/quantity 8}) (core/seed-row :invoice_items {:id :join-row-3 :invoice_id :id/invoice-2 :item_id :id/spanner :invoice_items/quantity 1}) (core/seed-row :invoice_items {:id :join-row-4 :invoice_id :id/invoice-2 :item_id :id/gadget :invoice_items/quantity 5}) ; graph loop (core/seed-update :account :id/joe {:spouse_id :id/mary}) (core/seed-update :account :id/mary {:spouse_id :id/joe}) ; non-looping recursion with some depth (core/seed-row :todo_list {:id :list-1 :name "Things to do"}) (core/seed-row :todo_list_item {:id :item-1 :label "A" :todo_list_id :list-1}) (core/seed-row :todo_list_item {:id :item-1-1 :label "A.1" :parent_item_id :item-1}) (core/seed-row :todo_list_item {:id :item-1-1-1 :label "A.1.1" :parent_item_id :item-1-1}) (core/seed-row :todo_list_item {:id :item-2 :label "B" :todo_list_id :list-1}) (core/seed-row :todo_list_item {:id :item-2-1 :label "B.1" :parent_item_id :item-2}) (core/seed-row :todo_list_item {:id :item-2-2 :label "B.2" :parent_item_id :item-2})]) (specification "Integration Tests for Graph Queries (PostgreSQL)" :integration (with-database [db test-database] (let [{:keys [id/joe id/mary id/invoice-1 id/invoice-2 id/gadget id/widget id/spanner id/sam id/sally id/judy id/joe-settings id/mary-settings list-1 item-1 item-1-1 item-1-1-1 item-2 item-2-1 item-2-2]} (core/seed! db test-schema test-rows) query [:db/id :account/name {:account/invoices [:db/id ;{:invoice/invoice_items [:invoice_items/quantity]} {:invoice/items [:db/id :item/name]}]}] expected-result {:db/id joe :account/name "<NAME>" :account/invoices [{:db/id invoice-1 :invoice/items [{:db/id gadget :item/name "gadget"}]} {:db/id invoice-2 :invoice/items [{:db/id gadget :item/name "gadget"} {:db/id widget :item/name "widget"} {:db/id spanner :item/name "spanner"}]}]} query-2 [:db/id :account/name {:account/members [:db/id :person/name]} {:account/settings [:db/id :settings/auto-open?]}] expected-result-2 [{:db/id joe :account/name "<NAME>" :account/members [{:db/id sam :person/name "<NAME>"} {:db/id <NAME> :person/name "<NAME>"}] :account/settings {:db/id joe-settings :settings/auto-open? true}} {:db/id mary :account/name "<NAME>" :account/settings {:db/id mary-settings :settings/auto-open? false} :account/members [{:db/id judy :person/name "<NAME>"}]}] query-3 [:db/id :item/name {:item/invoices [:db/id {:invoice/account [:db/id :account/name]}]}] expected-result-3 [{:db/id gadget :item/name "gadget" :item/invoices [{:db/id invoice-1 :invoice/account {:db/id joe :account/name "<NAME>"}} {:db/id invoice-2 :invoice/account {:db/id joe :account/name "<NAME>"}}]}] root-set #{joe} recursive-query '[:db/id :todo-list/name {:todo-list/items [:db/id :todo-list-item/label {:todo-list-item/subitems ...}]}] recursive-query-depth '[:db/id :todo-list/name {:todo-list/items [:db/id :todo-list-item/label {:todo-list-item/subitems 1}]}] recursive-query-loop '[:db/id :account/name {:account/spouse ...}] recursive-expectation [{:db/id list-1 :todo-list/name "Things to do" :todo-list/items [{:db/id item-1 :todo-list-item/label "A" :todo-list-item/subitems [{:db/id item-1-1 :todo-list-item/label "A.1" :todo-list-item/subitems [{:db/id item-1-1-1 :todo-list-item/label "A.1.1"}]}]} {:db/id item-2 :todo-list-item/label "B" :todo-list-item/subitems [{:db/id item-2-1 :todo-list-item/label "B.1"} {:db/id item-2-2 :todo-list-item/label "B.2"}]}]}] recursive-expectation-depth [{:db/id list-1 :todo-list/name "Things to do" :todo-list/items [{:db/id item-1 :todo-list-item/label "A" :todo-list-item/subitems [{:db/id item-1-1 :todo-list-item/label "A.1"}]} {:db/id item-2 :todo-list-item/label "B" :todo-list-item/subitems [{:db/id item-2-1 :todo-list-item/label "B.1"} {:db/id item-2-2 :todo-list-item/label "B.2"}]}]}] recursive-expectation-loop [{:db/id joe :account/name "<NAME>" :account/spouse {:db/id <NAME> :account/name "<NAME>" :account/spouse {:db/id joe :account/name "<NAME>"}}}] source-table :account] (assertions "to-many" (core/run-query db test-schema :account/id query #{joe}) => [expected-result] "parallel subjoins" (core/run-query db test-schema :account/id query-2 (sorted-set joe mary)) => expected-result-2 "recursion" (core/run-query db test-schema :todo-list/id recursive-query (sorted-set list-1)) => recursive-expectation "recursion with depth limit" (core/run-query db test-schema :todo-list/id recursive-query-depth (sorted-set list-1)) => recursive-expectation-depth "recursive loop detection" (core/run-query db test-schema :account/id recursive-query-loop (sorted-set joe)) => recursive-expectation-loop "reverse many-to-many" (core/run-query db test-schema :account/id query-3 (sorted-set gadget)) => expected-result-3)))) (specification "MySQL Integration Tests" :mysql (with-database [db mysql-database] (let [{:keys [id/joe id/mary id/invoice-1 id/invoice-2 id/gadget id/widget id/spanner id/sam id/sally id/judy id/joe-settings id/mary-settings]} (core/seed! db mysql-schema test-rows) query [:db/id :account/name {:account/invoices [:db/id ; TODO: data on join table ;{:invoice/invoice_items [:invoice_items/quantity]} {:invoice/items [:db/id :item/name]}]}] expected-result {:db/id joe :account/name "<NAME>" :account/invoices [{:db/id invoice-1 :invoice/items [{:db/id gadget :item/name "gadget"}]} {:db/id invoice-2 :invoice/items [{:db/id widget :item/name "widget"} {:db/id spanner :item/name "spanner"} {:db/id gadget :item/name "gadget"}]}]} query-2 [:db/id :account/name {:account/members [:db/id :person/name]} {:account/settings [:db/id :settings/auto-open?]}] expected-result-2 [{:db/id joe :account/name "<NAME>" :account/members [{:db/id sam :person/name "<NAME>"} {:db/id sally :person/name "<NAME>"}] :account/settings {:db/id joe-settings :settings/auto-open? true}} {:db/id mary :account/name "<NAME>" :account/settings {:db/id mary-settings :settings/auto-open? false} :account/members [{:db/id judy :person/name "<NAME>"}]}] query-3 [:db/id :item/name {:item/invoices [:db/id {:invoice/account [:db/id :account/name]}]}] expected-result-3 [{:db/id gadget :item/name "gadget" :item/invoices [{:db/id invoice-1 :invoice/account {:db/id joe :account/name "<NAME>"}} {:db/id invoice-2 :invoice/account {:db/id joe :account/name "<NAME>"}}]}] root-set #{joe} source-table :account fix-nums (fn [result] (clojure.walk/postwalk (fn [ele] (if (= java.math.BigInteger (type ele)) (long ele) ele)) result))] (assertions "many-to-many (forward)" (fix-nums (core/run-query db mysql-schema :account/id query #{joe})) => (fix-nums [expected-result]) "one-to-many query (forward)" (fix-nums (core/run-query db mysql-schema :account/id query-2 (sorted-set joe mary))) => (fix-nums expected-result-2) "many-to-many (reverse)" (core/run-query db mysql-schema :account/id query-3 (sorted-set gadget)) => expected-result-3)))) (specification "H2 Integration Tests" :h2 (with-database [db h2-database] (let [{:keys [id/joe id/mary id/invoice-1 id/invoice-2 id/gadget id/widget id/spanner id/sam id/sally id/judy id/joe-settings id/mary-settings]} (core/seed! db h2-schema test-rows) query [:db/id :account/name {:account/invoices [:db/id ; TODO: data on join table ;{:invoice/invoice_items [:invoice_items/quantity]} {:invoice/items [:db/id :item/name]}]}] expected-result {:db/id joe :account/name "<NAME>" :account/invoices [{:db/id invoice-1 :invoice/items [{:db/id gadget :item/name "gadget"}]} {:db/id invoice-2 :invoice/items [{:db/id widget :item/name "widget"} {:db/id spanner :item/name "spanner"} {:db/id gadget :item/name "gadget"}]}]} query-2 [:db/id :account/name {:account/members [:db/id :person/name]} {:account/settings [:db/id :settings/auto-open?]}] expected-result-2 [{:db/id joe :account/name "<NAME>" :account/members [{:db/id sam :person/name "<NAME>"} {:db/id sally :person/name "<NAME>"}] :account/settings {:db/id joe-settings :settings/auto-open? true}} {:db/id mary :account/name "<NAME>" :account/settings {:db/id mary-settings :settings/auto-open? false} :account/members [{:db/id judy :person/name "<NAME>"}]}] query-3 [:db/id :item/name {:item/invoices [:db/id {:invoice/account [:db/id :account/name]}]}] expected-result-3 [{:db/id gadget :item/name "gadget" :item/invoices [{:db/id invoice-1 :invoice/account {:db/id joe :account/name "<NAME>"}} {:db/id invoice-2 :invoice/account {:db/id joe :account/name "<NAME>"}}]}] expected-filtered-result {:db/id joe :account/name "<NAME>" :account/invoices [{:db/id invoice-1 :invoice/items [{:db/id gadget :item/name "gadget"}]} {:db/id invoice-2 :invoice/items [{:db/id gadget :item/name "gadget"}]}]} root-set #{joe} source-table :account fix-nums (fn [result] (clojure.walk/postwalk (fn [ele] (if (= java.math.BigInteger (type ele)) (long ele) ele)) result))] (assertions "many-to-many (forward)" (core/run-query db h2-schema :account/id query #{joe}) => [expected-result] "one-to-many query (forward)" (core/run-query db h2-schema :account/id query-2 (sorted-set joe <NAME>)) => expected-result-2 "many-to-many (reverse)" (core/run-query db h2-schema :account/id query-3 (sorted-set gadget)) => expected-result-3 "filtered by explicit expression" (core/run-query db h2-schema :account/id query #{joe} {:item [(core/filter-where "item.name = ?" ["gadget"])]}) => [expected-filtered-result] "filtered by params" (core/run-query db h2-schema :account/id query #{joe} (core/filter-params->filters h2-schema {:item/name {:eq "gadget"}})) => [expected-filtered-result] "With min-depth limited filters" (core/run-query db h2-schema :account/id query #{joe} (core/filter-params->filters h2-schema {:item/name {:eq "gadget" :min-depth 3}})) => [expected-filtered-result] (core/run-query db h2-schema :account/id query #{joe} (core/filter-params->filters h2-schema {:item/name {:eq "gadget" :min-depth 4}})) => [expected-result] "With max-depth limited filters" (core/run-query db h2-schema :account/id query #{joe} (core/filter-params->filters h2-schema {:item/name {:eq "gadget" :max-depth 3}})) => [expected-filtered-result] (core/run-query db h2-schema :account/id query #{joe} (core/filter-params->filters h2-schema {:item/name {:eq "gadget" :max-depth 2}})) => [expected-result])))) (comment ;; useful to run in the REPL to eliminate info messages from tests: (do (require 'taoensso.timbre) (taoensso.timbre/set-level! :error)))
true
(ns fulcro-sql.core-spec (:require [fulcro-spec.core :refer [assertions specification behavior when-mocking component]] [fulcro-sql.core :as core] [fulcro-sql.test-helpers :refer [with-database]] [clojure.spec.alpha :as s] [clj-time.core :as tm] [com.stuartsierra.component :as component] [clojure.java.jdbc :as jdbc] [clj-time.jdbc] [taoensso.timbre :as timbre]) (:import (com.cognitect.transit TaggedValue) (clojure.lang ExceptionInfo))) (def test-database {:hikaricp-config "test.properties" :migrations ["classpath:migrations/test"]}) (def mysql-database {:hikaricp-config "mysqltest.properties" :driver :mysql :database-name "test" :migrations ["classpath:migrations/mysqltest"]}) (def h2-database {:hikaricp-config "h2test.properties" :driver :h2 :database-name "test" :migrations ["classpath:migrations/h2test"]}) (def test-schema {::core/graph->sql {:person/name :member/name :person/account :member/account_id :settings/auto-open? :settings/auto_open :settings/keyboard-shortcuts? :settings/keyboard_shortcuts} ; NOTE: Om join prop, SQL column props ::core/joins {:account/members (core/to-many [:account/id :member/account_id]) :account/settings (core/to-one [:account/settings_id :settings/id]) :account/spouse (core/to-one [:account/spouse_id :account/id]) :member/account (core/to-one [:member/account_id :account/id]) :account/invoices (core/to-many [:account/id :invoice/account_id]) :invoice/account (core/to-one [:invoice/account_id :account/id]) :invoice/items (core/to-many [:invoice/id :invoice_items/invoice_id :invoice_items/item_id :item/id]) :item/invoices (core/to-many [:item/id :invoice_items/item_id :invoice_items/invoice_id :invoice/id]) :todo-list/items (core/to-many [:todo_list/id :todo_list_item/todo_list_id]) :todo-list-item/subitems (core/to-many [:todo_list_item/id :todo_list_item/parent_item_id])} ; sql table -> id col ::core/pks {}}) (def mysql-schema (assoc test-schema ::core/driver :mysql ::core/database-name "test")) ; needed for create/drop in mysql...there is no drop schema (def h2-schema (assoc test-schema ::core/driver :h2)) (specification "Database Component" :integration (behavior "Can create a functional database pool from HikariCP properties and Flyway migrations." (with-database [db test-database] (let [result (jdbc/with-db-connection [con db] (jdbc/insert! con :account {:name "PI:NAME:<NAME>END_PI"})) row (first result)] (assertions (:name row) => "PI:NAME:<NAME>END_PI"))))) (specification "next-id (MySQL)" :mysql (behavior "Pulls a monotonically increasing ID from the database (MySQL/MariaDB)" (with-database [db mysql-database] (let [a (core/next-id db mysql-schema :account) b (core/next-id db mysql-schema :account)] (assertions "IDs are numeric integers > 0" (> a 0) => true (> b 0) => true "IDs are increasing" (> b a) => true))))) (specification "next-id (PostgreSQL)" :integration (behavior "Pulls a monotonically increasing ID from the database (PostgreSQL)" (with-database [db test-database] (let [a (core/next-id db test-schema :account) b (core/next-id db test-schema :account)] (assertions "IDs are numeric integers > 0" (> a 0) => true (> b 0) => true "IDs are increasing" (> b a) => true))))) (specification "seed!" :integration (with-database [db test-database] (jdbc/with-db-connection [db db] (let [rows [(core/seed-row :account {:id :id/joe :name "PI:NAME:<NAME>END_PI"}) (core/seed-row :member {:id :id/sam :account_id :id/joe :name "PI:NAME:<NAME>END_PI"}) (core/seed-update :account :id/joe {:last_edited_by :id/sam})] {:keys [id/joe id/sam] :as tempids} (core/seed! db test-schema rows) real-joe (jdbc/get-by-id db :account joe) real-sam (jdbc/get-by-id db :member sam)] (assertions "Temporary IDs are returned for each row" (pos? joe) => true (pos? sam) => true "The data is inserted into the database" (:name real-joe) => "PI:NAME:<NAME>END_PI" (:last_edited_by real-joe) => sam))))) (specification "Table Detection: `table-for`" (let [schema {::core/pks {} ::core/joins {} ::core/graph->sql {:thing/name :sql_table/name :boo/blah :sql_table/prop :the-thing/boo :the-table/bah}}] (assertions ":id and :db/id are ignored" (core/table-for schema [:account/name :db/id :id]) => :account "Detects the correct table name if all of the properties agree" (core/table-for schema [:account/name :account/status]) => :account "Detects the correct table name if all of the properties agree, and there is also a :db/id" (core/table-for schema [:db/id :account/name :account/status]) => :account "Remaps known graph->sql properties to ensure detection" (core/table-for schema [:thing/name :boo/blah]) => :sql_table "Throws an exception if a distinct table name cannot be resolved" (core/table-for schema [:db/id :account/name :user/status]) =throws=> (AssertionError #"Could not determine a single") "Ensures derived table names use underscores instead of hypens" (core/table-for schema [:a-thing/name]) => :a_thing (core/table-for schema [:the-thing/boo]) => :the_table (core/table-for schema [:the-crazy-woods/a]) => :the_crazy_woods "Column remaps are done before table detection" (core/table-for test-schema [:person/name]) => :member "Joins can determine table via the join name" (core/table-for test-schema [:db/id {:account/members [:db/id :member/name]}]) => :account (core/table-for schema [{:the-crazy-woods/a []}]) => :the_crazy_woods (core/table-for schema [{:user/name [:value]}]) => :user))) (def sample-schema {::core/graph->sql {:thing/name :sql_table/name :boo/blah :sql_table/prop :the-thing/boo :the-table/bah} ; FROM AN SQL PERSPECTIVE...Not Om ::core/pks {:account :id :member :id :invoice :id :item :id} ::core/joins { :account/address [:account/address_id :address/id] :account/members [:account/id :member/account_id] :member/account [:member/account_id :account/id] :invoice/items [:invoice/id :invoice_items/invoice_id :invoice_items/item_id :item/id] :item/invoice [:item/id :invoice_items/item_id :invoice_items/line_item_id :invoice/line_item_id]}}) (specification "columns-for" (assertions "Returns a set" (core/columns-for test-schema [:t/c]) =fn=> set? "Resolves the ID column via the derived table name" (core/columns-for test-schema [:db/id :person/name :person/account]) => #{:member/id :member/name :member/account_id}) (assert (s/valid? ::core/schema sample-schema) "Schema is valid") (behavior "id-columns from schema" (assertions "Gives back a set of :table/col keywords that represent the SQL database ID columns" (core/id-columns sample-schema) => #{:account/id :member/id :invoice/id :item/id})) (assertions "Converts an Om property to a proper column selector in SQL, with as AS clause of the Om property" (core/columns-for sample-schema [:thing/name]) => #{:sql_table/name :sql_table/id} (core/columns-for sample-schema [:the-thing/boo]) => #{:the_table/bah :the_table/id} "Joins contribute a column if the table has a join key." (core/columns-for sample-schema [:account/address]) => #{:account/address_id :account/id} (core/columns-for test-schema [:db/id {:account/members [:db/id :member/name]}]) => #{:account/id} "Joins without a local join column contribute their PK instead" (core/columns-for sample-schema [:account/members]) => #{:account/id} (core/columns-for sample-schema [:invoice/items]) => #{:invoice/id} (core/columns-for sample-schema [:item/invoice]) => #{:item/id})) (specification "Column Specification: `column-spec`" (assertions "Translates an sqlprop to an SQL selector" (core/column-spec sample-schema :account/name) => "account.name AS \"account/name\"")) (specification "sqlprop-for-join" (assertions "pulls the ID column if it is a FK back-reference join" (core/sqlprop-for-join test-schema {:account/members [:db/id :member/name]}) => :account/id (core/sqlprop-for-join test-schema {:account/invoices [:db/id :invoice/created_on]}) => :account/id "Pulls the correct FK column when edge goes from the given table" (core/sqlprop-for-join test-schema {:member/account [:db/id :account/name]}) => :member/account_id (core/sqlprop-for-join test-schema {:invoice/account [:db/id :account/name]}) => :invoice/account_id)) (specification "forward? and reverse?" (assertions "forward? is true when the join FK points from the source table to the PK of the target table" (core/forward? test-schema {:account/members [:db/id]}) => false (core/forward? test-schema {:account/settings [:db/id]}) => true (core/forward? test-schema {:invoice/items [:db/id]}) => false (core/forward? test-schema :account/members) => false (core/forward? test-schema :account/settings) => true (core/forward? test-schema :invoice/items) => false "reverse? is true when the join FK points from the source table to the PK of the target table" (core/reverse? test-schema {:account/members [:db/id]}) => true (core/reverse? test-schema {:account/settings [:db/id]}) => false (core/reverse? test-schema {:invoice/items [:db/id]}) => true)) (specification "filter-params->filters" (assertions "Converts a map of column filter parameters into filters for run-query" (core/filter-params->filters test-schema {:item/deleted {:eq 1 :max-depth 2}}) => {:item [(core/filter-where "item.deleted = ?" [1] 1 2)]} "Can specify min and max depth" (core/filter-params->filters test-schema {:item/deleted {:eq 1 :max-depth 2} :member/id {:gt 0 :min-depth 4}}) => {:item [(core/filter-where "item.deleted = ?" [1] 1 2)] :member [(core/filter-where "member.id > ?" [0] 4 1000)]} "Support null checks" (core/filter-params->filters test-schema {:item/other {:null true} :account/id {:null false}}) => {:item [(core/filter-where "item.other IS NULL" [])] :account [(core/filter-where "account.id IS NOT NULL" [])]} "Supports multiple filters on the same table" (core/filter-params->filters test-schema {:item/deleted {:eq 1 :max-depth 2} :item/quantity {:gt 0} }) => {:item [(core/filter-where "item.deleted = ?" [1] 1 2) (core/filter-where "item.quantity > ?" [0])]} "Throws a descriptive error when an unknown operation is used" (core/filter-params->filters test-schema {:item/deleted {:boo 1}}) =throws=> (ExceptionInfo #"Invalid operation in rule" (fn [e] (= (ex-data e) {:boo 1}))))) (specification "row-filter" (assertions "Returns [nil nil] if no filtering is needed" (#'core/row-filter test-schema {} #{:account}) => [nil nil] "The first element returned is an AND-joined clause of ONLY conditions that apply to the given table(s)" (first (#'core/row-filter test-schema {:account [(core/filter-where "account.deleted <> ?" [44])] :member [(core/filter-where "member.boo = ?" [2])]} #{:account})) => "(account.deleted <> ?)" (first (#'core/row-filter test-schema {:account [(core/filter-where "account.deleted <> ?" [44])] :item [(core/filter-where "item.id = ?" [44])] :member [(core/filter-where "member.deleted = ?" [44])]} #{:account :member})) => "(account.deleted <> ?) AND (member.deleted = ?)" "Honors the minimum depth" (first (#'core/row-filter test-schema {::core/depth 2 :account [(core/filter-where "account.deleted <> ?" [44] 3 1000)]} #{:account})) => nil (first (#'core/row-filter test-schema {::core/depth 3 :account [(core/filter-where "account.deleted <> ?" [44] 3 1000)]} #{:account})) =fn=> seq "Honors the maximum depth" (first (#'core/row-filter test-schema {::core/depth 2 :account [(core/filter-where "account.deleted <> ?" [44] 1 1)]} #{:account})) => nil (first (#'core/row-filter test-schema {::core/depth 1 :account [(core/filter-where "account.deleted <> ?" [44] 1 1)]} #{:account})) =fn=> seq "The second element returned is an in-order vector of parameters to use in the SQL clause" (second (#'core/row-filter test-schema {:account [(core/filter-where "account.deleted <> ?" [44])] :item [(core/filter-where "item.id = ?" [44])] :member [(core/filter-where "member.deleted = ?" [false])]} #{:account :member})) => [44 false] (second (#'core/row-filter test-schema {:account [(core/filter-where "account.deleted <> ?" [44])] :member [(core/filter-where "member.boo = ?" [2])]} #{:account})) => [44])) (specification "Single-level query-for query generation" (assertions "Generates a base non-recursive SQL query that includes necessary join resolution columns" (core/query-for test-schema nil [:db/id {:account/members [:db/id :member/name]}] (sorted-set 1 5 7 9)) => ["SELECT account.id AS \"account/id\" FROM account WHERE account.id IN (1,5,7,9)" nil] (core/query-for test-schema :account/members [:db/id :member/name] (sorted-set 1 5)) => ["SELECT member.account_id AS \"member/account_id\",member.id AS \"member/id\",member.name AS \"member/name\" FROM member WHERE member.account_id IN (1,5)" nil] (core/query-for test-schema :account/settings [:db/id :settings/auto-open?] (sorted-set 3)) => ["SELECT settings.auto_open AS \"settings/auto_open\",settings.id AS \"settings/id\" FROM settings WHERE settings.id IN (3)" nil] (core/query-for test-schema nil [:db/id :boo/name :boo/bah] #{3}) => ["SELECT boo.bah AS \"boo/bah\",boo.id AS \"boo/id\",boo.name AS \"boo/name\" FROM boo WHERE boo.id IN (3)" nil] "Derives correct SQL table name if possible" (core/query-for test-schema nil [:db/id {:account/members [:db/id :member/name]}] (sorted-set 1 5 7 9)) => ["SELECT account.id AS \"account/id\" FROM account WHERE account.id IN (1,5,7,9)" nil] (core/query-for test-schema nil [:db/id] (sorted-set 1 5 7 9)) =throws=> (AssertionError #"Could not determine") "Supports adding additional filter criteria" (core/query-for test-schema nil [:db/id {:account/members [:db/id :member/name]}] (sorted-set 1 5 7 9) {:account [(core/filter-where "account.deleted = ?" [false])]}) => ["SELECT account.id AS \"account/id\" FROM account WHERE (account.deleted = ?) AND account.id IN (1,5,7,9)" [false]] (core/query-for test-schema nil [:db/id {:account/members [:db/id :member/name]}] (sorted-set 1 5 7 9) {:account [(core/filter-where "account.deleted = ? AND account.age > ?" [false 22])]}) => ["SELECT account.id AS \"account/id\" FROM account WHERE (account.deleted = ? AND account.age > ?) AND account.id IN (1,5,7,9)" [false, 22]])) (specification "Run-query internals" (assertions "Returns nil if there are no IDs in the root set" (#'core/run-query* :db test-schema :prop [:a] {} {}) => nil) (behavior "Increments recursion depth tracking" (when-mocking (core/query-for s prop query ids filtering) =1x=> (do (assertions "Filtering is given the depth when generating the query" (get filtering ::core/depth) => 4) [nil nil]) (jdbc/query db params) =1x=> [] (core/compute-join-results db schema query rows filtering recursion-tracking) =1x=> (do (assertions "Passes the new depth to any recursive computation of join results" (::core/depth recursion-tracking) => 4) {}) (#'core/run-query* :db test-schema :prop [:a] {} #{1} {::core/depth 3})))) (def test-rows [; basic to-one and to-many (core/seed-row :settings {:id :id/joe-settings :auto_open true :keyboard_shortcuts false}) (core/seed-row :settings {:id :id/mary-settings :auto_open false :keyboard_shortcuts true}) (core/seed-row :account {:id :id/joe :name "PI:NAME:<NAME>END_PI" :settings_id :id/joe-settings}) (core/seed-row :account {:id :id/mary :name "PI:NAME:<NAME>END_PI" :settings_id :id/mary-settings}) (core/seed-row :member {:id :id/sam :name "PI:NAME:<NAME>END_PI" :account_id :id/joe}) (core/seed-row :member {:id :id/sally :name "PI:NAME:<NAME>END_PI" :account_id :id/joe}) (core/seed-row :member {:id :id/judy :name "PI:NAME:<NAME>END_PI" :account_id :id/mary}) ; many-to-many (core/seed-row :invoice {:id :id/invoice-1 :account_id :id/joe :invoice_date (tm/date-time 2017 03 04)}) (core/seed-row :invoice {:id :id/invoice-2 :account_id :id/joe :invoice_date (tm/date-time 2016 01 02)}) (core/seed-row :item {:id :id/gadget :name "gadget"}) (core/seed-row :item {:id :id/widget :name "widget"}) (core/seed-row :item {:id :id/spanner :name "spanner"}) (core/seed-row :invoice_items {:id :join-row-1 :invoice_id :id/invoice-1 :item_id :id/gadget :invoice_items/quantity 2}) (core/seed-row :invoice_items {:id :join-row-2 :invoice_id :id/invoice-2 :item_id :id/widget :invoice_items/quantity 8}) (core/seed-row :invoice_items {:id :join-row-3 :invoice_id :id/invoice-2 :item_id :id/spanner :invoice_items/quantity 1}) (core/seed-row :invoice_items {:id :join-row-4 :invoice_id :id/invoice-2 :item_id :id/gadget :invoice_items/quantity 5}) ; graph loop (core/seed-update :account :id/joe {:spouse_id :id/mary}) (core/seed-update :account :id/mary {:spouse_id :id/joe}) ; non-looping recursion with some depth (core/seed-row :todo_list {:id :list-1 :name "Things to do"}) (core/seed-row :todo_list_item {:id :item-1 :label "A" :todo_list_id :list-1}) (core/seed-row :todo_list_item {:id :item-1-1 :label "A.1" :parent_item_id :item-1}) (core/seed-row :todo_list_item {:id :item-1-1-1 :label "A.1.1" :parent_item_id :item-1-1}) (core/seed-row :todo_list_item {:id :item-2 :label "B" :todo_list_id :list-1}) (core/seed-row :todo_list_item {:id :item-2-1 :label "B.1" :parent_item_id :item-2}) (core/seed-row :todo_list_item {:id :item-2-2 :label "B.2" :parent_item_id :item-2})]) (specification "Integration Tests for Graph Queries (PostgreSQL)" :integration (with-database [db test-database] (let [{:keys [id/joe id/mary id/invoice-1 id/invoice-2 id/gadget id/widget id/spanner id/sam id/sally id/judy id/joe-settings id/mary-settings list-1 item-1 item-1-1 item-1-1-1 item-2 item-2-1 item-2-2]} (core/seed! db test-schema test-rows) query [:db/id :account/name {:account/invoices [:db/id ;{:invoice/invoice_items [:invoice_items/quantity]} {:invoice/items [:db/id :item/name]}]}] expected-result {:db/id joe :account/name "PI:NAME:<NAME>END_PI" :account/invoices [{:db/id invoice-1 :invoice/items [{:db/id gadget :item/name "gadget"}]} {:db/id invoice-2 :invoice/items [{:db/id gadget :item/name "gadget"} {:db/id widget :item/name "widget"} {:db/id spanner :item/name "spanner"}]}]} query-2 [:db/id :account/name {:account/members [:db/id :person/name]} {:account/settings [:db/id :settings/auto-open?]}] expected-result-2 [{:db/id joe :account/name "PI:NAME:<NAME>END_PI" :account/members [{:db/id sam :person/name "PI:NAME:<NAME>END_PI"} {:db/id PI:NAME:<NAME>END_PI :person/name "PI:NAME:<NAME>END_PI"}] :account/settings {:db/id joe-settings :settings/auto-open? true}} {:db/id mary :account/name "PI:NAME:<NAME>END_PI" :account/settings {:db/id mary-settings :settings/auto-open? false} :account/members [{:db/id judy :person/name "PI:NAME:<NAME>END_PI"}]}] query-3 [:db/id :item/name {:item/invoices [:db/id {:invoice/account [:db/id :account/name]}]}] expected-result-3 [{:db/id gadget :item/name "gadget" :item/invoices [{:db/id invoice-1 :invoice/account {:db/id joe :account/name "PI:NAME:<NAME>END_PI"}} {:db/id invoice-2 :invoice/account {:db/id joe :account/name "PI:NAME:<NAME>END_PI"}}]}] root-set #{joe} recursive-query '[:db/id :todo-list/name {:todo-list/items [:db/id :todo-list-item/label {:todo-list-item/subitems ...}]}] recursive-query-depth '[:db/id :todo-list/name {:todo-list/items [:db/id :todo-list-item/label {:todo-list-item/subitems 1}]}] recursive-query-loop '[:db/id :account/name {:account/spouse ...}] recursive-expectation [{:db/id list-1 :todo-list/name "Things to do" :todo-list/items [{:db/id item-1 :todo-list-item/label "A" :todo-list-item/subitems [{:db/id item-1-1 :todo-list-item/label "A.1" :todo-list-item/subitems [{:db/id item-1-1-1 :todo-list-item/label "A.1.1"}]}]} {:db/id item-2 :todo-list-item/label "B" :todo-list-item/subitems [{:db/id item-2-1 :todo-list-item/label "B.1"} {:db/id item-2-2 :todo-list-item/label "B.2"}]}]}] recursive-expectation-depth [{:db/id list-1 :todo-list/name "Things to do" :todo-list/items [{:db/id item-1 :todo-list-item/label "A" :todo-list-item/subitems [{:db/id item-1-1 :todo-list-item/label "A.1"}]} {:db/id item-2 :todo-list-item/label "B" :todo-list-item/subitems [{:db/id item-2-1 :todo-list-item/label "B.1"} {:db/id item-2-2 :todo-list-item/label "B.2"}]}]}] recursive-expectation-loop [{:db/id joe :account/name "PI:NAME:<NAME>END_PI" :account/spouse {:db/id PI:NAME:<NAME>END_PI :account/name "PI:NAME:<NAME>END_PI" :account/spouse {:db/id joe :account/name "PI:NAME:<NAME>END_PI"}}}] source-table :account] (assertions "to-many" (core/run-query db test-schema :account/id query #{joe}) => [expected-result] "parallel subjoins" (core/run-query db test-schema :account/id query-2 (sorted-set joe mary)) => expected-result-2 "recursion" (core/run-query db test-schema :todo-list/id recursive-query (sorted-set list-1)) => recursive-expectation "recursion with depth limit" (core/run-query db test-schema :todo-list/id recursive-query-depth (sorted-set list-1)) => recursive-expectation-depth "recursive loop detection" (core/run-query db test-schema :account/id recursive-query-loop (sorted-set joe)) => recursive-expectation-loop "reverse many-to-many" (core/run-query db test-schema :account/id query-3 (sorted-set gadget)) => expected-result-3)))) (specification "MySQL Integration Tests" :mysql (with-database [db mysql-database] (let [{:keys [id/joe id/mary id/invoice-1 id/invoice-2 id/gadget id/widget id/spanner id/sam id/sally id/judy id/joe-settings id/mary-settings]} (core/seed! db mysql-schema test-rows) query [:db/id :account/name {:account/invoices [:db/id ; TODO: data on join table ;{:invoice/invoice_items [:invoice_items/quantity]} {:invoice/items [:db/id :item/name]}]}] expected-result {:db/id joe :account/name "PI:NAME:<NAME>END_PI" :account/invoices [{:db/id invoice-1 :invoice/items [{:db/id gadget :item/name "gadget"}]} {:db/id invoice-2 :invoice/items [{:db/id widget :item/name "widget"} {:db/id spanner :item/name "spanner"} {:db/id gadget :item/name "gadget"}]}]} query-2 [:db/id :account/name {:account/members [:db/id :person/name]} {:account/settings [:db/id :settings/auto-open?]}] expected-result-2 [{:db/id joe :account/name "PI:NAME:<NAME>END_PI" :account/members [{:db/id sam :person/name "PI:NAME:<NAME>END_PI"} {:db/id sally :person/name "PI:NAME:<NAME>END_PI"}] :account/settings {:db/id joe-settings :settings/auto-open? true}} {:db/id mary :account/name "PI:NAME:<NAME>END_PI" :account/settings {:db/id mary-settings :settings/auto-open? false} :account/members [{:db/id judy :person/name "PI:NAME:<NAME>END_PI"}]}] query-3 [:db/id :item/name {:item/invoices [:db/id {:invoice/account [:db/id :account/name]}]}] expected-result-3 [{:db/id gadget :item/name "gadget" :item/invoices [{:db/id invoice-1 :invoice/account {:db/id joe :account/name "PI:NAME:<NAME>END_PI"}} {:db/id invoice-2 :invoice/account {:db/id joe :account/name "PI:NAME:<NAME>END_PI"}}]}] root-set #{joe} source-table :account fix-nums (fn [result] (clojure.walk/postwalk (fn [ele] (if (= java.math.BigInteger (type ele)) (long ele) ele)) result))] (assertions "many-to-many (forward)" (fix-nums (core/run-query db mysql-schema :account/id query #{joe})) => (fix-nums [expected-result]) "one-to-many query (forward)" (fix-nums (core/run-query db mysql-schema :account/id query-2 (sorted-set joe mary))) => (fix-nums expected-result-2) "many-to-many (reverse)" (core/run-query db mysql-schema :account/id query-3 (sorted-set gadget)) => expected-result-3)))) (specification "H2 Integration Tests" :h2 (with-database [db h2-database] (let [{:keys [id/joe id/mary id/invoice-1 id/invoice-2 id/gadget id/widget id/spanner id/sam id/sally id/judy id/joe-settings id/mary-settings]} (core/seed! db h2-schema test-rows) query [:db/id :account/name {:account/invoices [:db/id ; TODO: data on join table ;{:invoice/invoice_items [:invoice_items/quantity]} {:invoice/items [:db/id :item/name]}]}] expected-result {:db/id joe :account/name "PI:NAME:<NAME>END_PI" :account/invoices [{:db/id invoice-1 :invoice/items [{:db/id gadget :item/name "gadget"}]} {:db/id invoice-2 :invoice/items [{:db/id widget :item/name "widget"} {:db/id spanner :item/name "spanner"} {:db/id gadget :item/name "gadget"}]}]} query-2 [:db/id :account/name {:account/members [:db/id :person/name]} {:account/settings [:db/id :settings/auto-open?]}] expected-result-2 [{:db/id joe :account/name "PI:NAME:<NAME>END_PI" :account/members [{:db/id sam :person/name "PI:NAME:<NAME>END_PI"} {:db/id sally :person/name "PI:NAME:<NAME>END_PI"}] :account/settings {:db/id joe-settings :settings/auto-open? true}} {:db/id mary :account/name "PI:NAME:<NAME>END_PI" :account/settings {:db/id mary-settings :settings/auto-open? false} :account/members [{:db/id judy :person/name "PI:NAME:<NAME>END_PI"}]}] query-3 [:db/id :item/name {:item/invoices [:db/id {:invoice/account [:db/id :account/name]}]}] expected-result-3 [{:db/id gadget :item/name "gadget" :item/invoices [{:db/id invoice-1 :invoice/account {:db/id joe :account/name "PI:NAME:<NAME>END_PI"}} {:db/id invoice-2 :invoice/account {:db/id joe :account/name "PI:NAME:<NAME>END_PI"}}]}] expected-filtered-result {:db/id joe :account/name "PI:NAME:<NAME>END_PI" :account/invoices [{:db/id invoice-1 :invoice/items [{:db/id gadget :item/name "gadget"}]} {:db/id invoice-2 :invoice/items [{:db/id gadget :item/name "gadget"}]}]} root-set #{joe} source-table :account fix-nums (fn [result] (clojure.walk/postwalk (fn [ele] (if (= java.math.BigInteger (type ele)) (long ele) ele)) result))] (assertions "many-to-many (forward)" (core/run-query db h2-schema :account/id query #{joe}) => [expected-result] "one-to-many query (forward)" (core/run-query db h2-schema :account/id query-2 (sorted-set joe PI:NAME:<NAME>END_PI)) => expected-result-2 "many-to-many (reverse)" (core/run-query db h2-schema :account/id query-3 (sorted-set gadget)) => expected-result-3 "filtered by explicit expression" (core/run-query db h2-schema :account/id query #{joe} {:item [(core/filter-where "item.name = ?" ["gadget"])]}) => [expected-filtered-result] "filtered by params" (core/run-query db h2-schema :account/id query #{joe} (core/filter-params->filters h2-schema {:item/name {:eq "gadget"}})) => [expected-filtered-result] "With min-depth limited filters" (core/run-query db h2-schema :account/id query #{joe} (core/filter-params->filters h2-schema {:item/name {:eq "gadget" :min-depth 3}})) => [expected-filtered-result] (core/run-query db h2-schema :account/id query #{joe} (core/filter-params->filters h2-schema {:item/name {:eq "gadget" :min-depth 4}})) => [expected-result] "With max-depth limited filters" (core/run-query db h2-schema :account/id query #{joe} (core/filter-params->filters h2-schema {:item/name {:eq "gadget" :max-depth 3}})) => [expected-filtered-result] (core/run-query db h2-schema :account/id query #{joe} (core/filter-params->filters h2-schema {:item/name {:eq "gadget" :max-depth 2}})) => [expected-result])))) (comment ;; useful to run in the REPL to eliminate info messages from tests: (do (require 'taoensso.timbre) (taoensso.timbre/set-level! :error)))
[ { "context": ";-\n; Copyright 2015 © Meikel Brandmeyer.\n; All rights reserved.\n;\n; Licensed under the EU", "end": 39, "score": 0.9998742341995239, "start": 22, "tag": "NAME", "value": "Meikel Brandmeyer" } ]
src/main/clojure/hay/engine.clj
pinky-editor/hay
2
;- ; Copyright 2015 © Meikel Brandmeyer. ; All rights reserved. ; ; Licensed under the EUPL V.1.1 (cf. file EUPL-1.1 distributed with the ; source code.) Translations in other european languages available at ; https://joinup.ec.europa.eu/software/page/eupl. ; ; Alternatively, you may choose to use the software under the MIT license ; (cf. file MIT distributed with the source code). (ns hay.engine (:require hay.compiler hay.grammar) (:import clojure.lang.AFunction hay.compiler.Compilate hay.grammar.Block)) (def runtime (atom {:namespaces {}})) (defrecord HayThread [stack value word state instructions locals]) (defn >hay-thread [compilate] (->HayThread [] nil nil :running (:instructions compilate) {"*ns*" "hay.stack"})) (defmulti evaluate (fn [_thread instruction] (nth instruction 0)) :default :NO-OP) (defn step [thread] (if-let [[op & more-instructions] (seq (:instructions thread))] (-> thread (assoc :instructions more-instructions) (evaluate op)) (assoc thread :state :done))) (defn run [thread] (if (= (:state thread) :running) (recur (step thread)) thread)) (defn freeze [thread] (assoc thread :state :frozen)) (defn thaw [thread] (assoc thread :state :running)) (defmethod evaluate :NO-OP [thread _] thread) (defmethod evaluate :FREEZE [thread _] (freeze thread)) (defn pop-n [stack n] (case n 0 [stack []] 1 [(pop stack) [(peek stack)]] (reduce (fn [[stack values] _] [(pop stack) (conj values (peek stack))]) [stack []] (range n)))) (defmethod evaluate :POP [thread [_ n]] (let [n (or n 1) [nstack values] (pop-n (:stack thread) n)] (-> thread (assoc :stack nstack) (assoc :value values)))) (defmethod evaluate :PUSH [thread _] (-> thread (update-in [:stack] conj (:value thread)) (assoc :value nil))) (defmethod evaluate :PUSH-ALL [thread _] (-> thread (update-in [:stack] into (:value thread)) (assoc :value nil))) (defmethod evaluate :VALUE [thread [_ v]] (assoc thread :value v)) (defmethod evaluate :WORD [thread [_ f]] (assoc thread :word f)) (defprotocol ICall (call [this thread])) (extend-protocol ICall AFunction (call [this thread] (letfn [(do-call [v] (case (count v) 0 (this) 1 (this (nth v 0)) 2 (this (nth v 0) (nth v 1)) 3 (this (nth v 0) (nth v 1) (nth v 2)) 4 (this (nth v 0) (nth v 1) (nth v 2) (nth v 3)) 5 (this (nth v 0) (nth v 1) (nth v 2) (nth v 3) (nth v 4)) (apply this v)))] (update-in thread [:value] do-call))) Compilate (call [this thread] (-> this :instructions (concat (:instructions thread)) (->> (assoc thread :instructions))))) (defmethod evaluate :CALL [thread _] (call (:word thread) thread)) (defmethod evaluate :THREAD-CALL [thread [_ f]] (f thread)) (defn ^:private >word [x] {:post [(instance? Compilate %)]} (cond (vector? x) (nth x 1) (instance? Compilate x) x :else (or (:hay/compilate (meta x)) (deref x)))) (defmethod evaluate :LOOKUP [thread [_ sym]] (let [nspace (namespace sym) sspace (or nspace (get (:locals thread) "*ns*")) name (name sym)] (if-let [w (or (when-not nspace (find (:locals thread) name)) (get-in @runtime [:namespaces sspace :words name]) (get (ns-publics (symbol sspace)) (symbol name)) (get-in @runtime [:namespaces "hay.stack" :words name]) (get (ns-publics 'clojure.core) (symbol name)))] (assoc thread :instructions (concat [[:WORD (>word w)] hay.compiler/CALL] (:instructions thread))) (throw (ex-info (str "unknown word: " name) {:sym sym}))))) (defn hay-call [block] (fn [& args] (let [t (>hay-thread block) t (assoc t :stack (into [] (reverse args))) t (run t)] (peek (:stack t)))))
70066
;- ; Copyright 2015 © <NAME>. ; All rights reserved. ; ; Licensed under the EUPL V.1.1 (cf. file EUPL-1.1 distributed with the ; source code.) Translations in other european languages available at ; https://joinup.ec.europa.eu/software/page/eupl. ; ; Alternatively, you may choose to use the software under the MIT license ; (cf. file MIT distributed with the source code). (ns hay.engine (:require hay.compiler hay.grammar) (:import clojure.lang.AFunction hay.compiler.Compilate hay.grammar.Block)) (def runtime (atom {:namespaces {}})) (defrecord HayThread [stack value word state instructions locals]) (defn >hay-thread [compilate] (->HayThread [] nil nil :running (:instructions compilate) {"*ns*" "hay.stack"})) (defmulti evaluate (fn [_thread instruction] (nth instruction 0)) :default :NO-OP) (defn step [thread] (if-let [[op & more-instructions] (seq (:instructions thread))] (-> thread (assoc :instructions more-instructions) (evaluate op)) (assoc thread :state :done))) (defn run [thread] (if (= (:state thread) :running) (recur (step thread)) thread)) (defn freeze [thread] (assoc thread :state :frozen)) (defn thaw [thread] (assoc thread :state :running)) (defmethod evaluate :NO-OP [thread _] thread) (defmethod evaluate :FREEZE [thread _] (freeze thread)) (defn pop-n [stack n] (case n 0 [stack []] 1 [(pop stack) [(peek stack)]] (reduce (fn [[stack values] _] [(pop stack) (conj values (peek stack))]) [stack []] (range n)))) (defmethod evaluate :POP [thread [_ n]] (let [n (or n 1) [nstack values] (pop-n (:stack thread) n)] (-> thread (assoc :stack nstack) (assoc :value values)))) (defmethod evaluate :PUSH [thread _] (-> thread (update-in [:stack] conj (:value thread)) (assoc :value nil))) (defmethod evaluate :PUSH-ALL [thread _] (-> thread (update-in [:stack] into (:value thread)) (assoc :value nil))) (defmethod evaluate :VALUE [thread [_ v]] (assoc thread :value v)) (defmethod evaluate :WORD [thread [_ f]] (assoc thread :word f)) (defprotocol ICall (call [this thread])) (extend-protocol ICall AFunction (call [this thread] (letfn [(do-call [v] (case (count v) 0 (this) 1 (this (nth v 0)) 2 (this (nth v 0) (nth v 1)) 3 (this (nth v 0) (nth v 1) (nth v 2)) 4 (this (nth v 0) (nth v 1) (nth v 2) (nth v 3)) 5 (this (nth v 0) (nth v 1) (nth v 2) (nth v 3) (nth v 4)) (apply this v)))] (update-in thread [:value] do-call))) Compilate (call [this thread] (-> this :instructions (concat (:instructions thread)) (->> (assoc thread :instructions))))) (defmethod evaluate :CALL [thread _] (call (:word thread) thread)) (defmethod evaluate :THREAD-CALL [thread [_ f]] (f thread)) (defn ^:private >word [x] {:post [(instance? Compilate %)]} (cond (vector? x) (nth x 1) (instance? Compilate x) x :else (or (:hay/compilate (meta x)) (deref x)))) (defmethod evaluate :LOOKUP [thread [_ sym]] (let [nspace (namespace sym) sspace (or nspace (get (:locals thread) "*ns*")) name (name sym)] (if-let [w (or (when-not nspace (find (:locals thread) name)) (get-in @runtime [:namespaces sspace :words name]) (get (ns-publics (symbol sspace)) (symbol name)) (get-in @runtime [:namespaces "hay.stack" :words name]) (get (ns-publics 'clojure.core) (symbol name)))] (assoc thread :instructions (concat [[:WORD (>word w)] hay.compiler/CALL] (:instructions thread))) (throw (ex-info (str "unknown word: " name) {:sym sym}))))) (defn hay-call [block] (fn [& args] (let [t (>hay-thread block) t (assoc t :stack (into [] (reverse args))) t (run t)] (peek (:stack t)))))
true
;- ; Copyright 2015 © PI:NAME:<NAME>END_PI. ; All rights reserved. ; ; Licensed under the EUPL V.1.1 (cf. file EUPL-1.1 distributed with the ; source code.) Translations in other european languages available at ; https://joinup.ec.europa.eu/software/page/eupl. ; ; Alternatively, you may choose to use the software under the MIT license ; (cf. file MIT distributed with the source code). (ns hay.engine (:require hay.compiler hay.grammar) (:import clojure.lang.AFunction hay.compiler.Compilate hay.grammar.Block)) (def runtime (atom {:namespaces {}})) (defrecord HayThread [stack value word state instructions locals]) (defn >hay-thread [compilate] (->HayThread [] nil nil :running (:instructions compilate) {"*ns*" "hay.stack"})) (defmulti evaluate (fn [_thread instruction] (nth instruction 0)) :default :NO-OP) (defn step [thread] (if-let [[op & more-instructions] (seq (:instructions thread))] (-> thread (assoc :instructions more-instructions) (evaluate op)) (assoc thread :state :done))) (defn run [thread] (if (= (:state thread) :running) (recur (step thread)) thread)) (defn freeze [thread] (assoc thread :state :frozen)) (defn thaw [thread] (assoc thread :state :running)) (defmethod evaluate :NO-OP [thread _] thread) (defmethod evaluate :FREEZE [thread _] (freeze thread)) (defn pop-n [stack n] (case n 0 [stack []] 1 [(pop stack) [(peek stack)]] (reduce (fn [[stack values] _] [(pop stack) (conj values (peek stack))]) [stack []] (range n)))) (defmethod evaluate :POP [thread [_ n]] (let [n (or n 1) [nstack values] (pop-n (:stack thread) n)] (-> thread (assoc :stack nstack) (assoc :value values)))) (defmethod evaluate :PUSH [thread _] (-> thread (update-in [:stack] conj (:value thread)) (assoc :value nil))) (defmethod evaluate :PUSH-ALL [thread _] (-> thread (update-in [:stack] into (:value thread)) (assoc :value nil))) (defmethod evaluate :VALUE [thread [_ v]] (assoc thread :value v)) (defmethod evaluate :WORD [thread [_ f]] (assoc thread :word f)) (defprotocol ICall (call [this thread])) (extend-protocol ICall AFunction (call [this thread] (letfn [(do-call [v] (case (count v) 0 (this) 1 (this (nth v 0)) 2 (this (nth v 0) (nth v 1)) 3 (this (nth v 0) (nth v 1) (nth v 2)) 4 (this (nth v 0) (nth v 1) (nth v 2) (nth v 3)) 5 (this (nth v 0) (nth v 1) (nth v 2) (nth v 3) (nth v 4)) (apply this v)))] (update-in thread [:value] do-call))) Compilate (call [this thread] (-> this :instructions (concat (:instructions thread)) (->> (assoc thread :instructions))))) (defmethod evaluate :CALL [thread _] (call (:word thread) thread)) (defmethod evaluate :THREAD-CALL [thread [_ f]] (f thread)) (defn ^:private >word [x] {:post [(instance? Compilate %)]} (cond (vector? x) (nth x 1) (instance? Compilate x) x :else (or (:hay/compilate (meta x)) (deref x)))) (defmethod evaluate :LOOKUP [thread [_ sym]] (let [nspace (namespace sym) sspace (or nspace (get (:locals thread) "*ns*")) name (name sym)] (if-let [w (or (when-not nspace (find (:locals thread) name)) (get-in @runtime [:namespaces sspace :words name]) (get (ns-publics (symbol sspace)) (symbol name)) (get-in @runtime [:namespaces "hay.stack" :words name]) (get (ns-publics 'clojure.core) (symbol name)))] (assoc thread :instructions (concat [[:WORD (>word w)] hay.compiler/CALL] (:instructions thread))) (throw (ex-info (str "unknown word: " name) {:sym sym}))))) (defn hay-call [block] (fn [& args] (let [t (>hay-thread block) t (assoc t :stack (into [] (reverse args))) t (run t)] (peek (:stack t)))))
[ { "context": "ns declarations in dirs, JARs, or CLASSPATH\n\n;; by Stuart Sierra, http://stuartsierra.com/\n;; April 19, 2009\n\n;; C", "end": 100, "score": 0.9998885989189148, "start": 87, "tag": "NAME", "value": "Stuart Sierra" }, { "context": "artsierra.com/\n;; April 19, 2009\n\n;; Copyright (c) Stuart Sierra, 2009. All rights reserved. The use\n;; and distr", "end": 176, "score": 0.9998883008956909, "start": 163, "tag": "NAME", "value": "Stuart Sierra" }, { "context": "y other, from this software.\n\n\n(ns \n #^{:author \"Stuart Sierra\",\n :doc \"Search for ns declarations in dirs, ", "end": 647, "score": 0.9998888969421387, "start": 634, "tag": "NAME", "value": "Stuart Sierra" } ]
ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/find_namespaces.clj
allertonm/Couverjure
3
;;; find_namespaces.clj: search for ns declarations in dirs, JARs, or CLASSPATH ;; by Stuart Sierra, http://stuartsierra.com/ ;; April 19, 2009 ;; Copyright (c) Stuart Sierra, 2009. 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 #^{:author "Stuart Sierra", :doc "Search for ns declarations in dirs, JARs, or CLASSPATH"} clojure.contrib.find-namespaces (:require [clojure.contrib.classpath :as cp] [clojure.contrib.jar :as jar]) (import (java.io File FileReader BufferedReader PushbackReader InputStreamReader) (java.util.jar JarFile))) ;;; Finding namespaces in a directory tree (defn clojure-source-file? "Returns true if file is a normal file with a .clj extension." [#^File file] (and (.isFile file) (.endsWith (.getName file) ".clj"))) (defn find-clojure-sources-in-dir "Searches recursively under dir for Clojure source files (.clj). Returns a sequence of File objects, in breadth-first sort order." [#^File dir] ;; Use sort by absolute path to get breadth-first search. (sort-by #(.getAbsolutePath %) (filter clojure-source-file? (file-seq dir)))) (defn comment? "Returns true if form is a (comment ...)" [form] (and (list? form) (= 'comment (first form)))) (defn ns-decl? "Returns true if form is a (ns ...) declaration." [form] (and (list? form) (= 'ns (first form)))) (defn read-ns-decl "Attempts to read a (ns ...) declaration from rdr, and returns the unevaluated form. Returns nil if read fails or if a ns declaration cannot be found. The ns declaration must be the first Clojure form in the file, except for (comment ...) forms." [#^PushbackReader rdr] (try (let [form (read rdr)] (cond (ns-decl? form) form (comment? form) (recur rdr) :else nil)) (catch Exception e nil))) (defn read-file-ns-decl "Attempts to read a (ns ...) declaration from file, and returns the unevaluated form. Returns nil if read fails, or if the first form is not a ns declaration." [#^File file] (with-open [rdr (PushbackReader. (BufferedReader. (FileReader. file)))] (read-ns-decl rdr))) (defn find-ns-decls-in-dir "Searches dir recursively for (ns ...) declarations in Clojure source files; returns the unevaluated ns declarations." [#^File dir] (filter identity (map read-file-ns-decl (find-clojure-sources-in-dir dir)))) (defn find-namespaces-in-dir "Searches dir recursively for (ns ...) declarations in Clojure source files; returns the symbol names of the declared namespaces." [#^File dir] (map second (find-ns-decls-in-dir dir))) ;;; Finding namespaces in JAR files (defn clojure-sources-in-jar "Returns a sequence of filenames ending in .clj found in the JAR file." [#^JarFile jar-file] (filter #(.endsWith % ".clj") (jar/filenames-in-jar jar-file))) (defn read-ns-decl-from-jarfile-entry "Attempts to read a (ns ...) declaration from the named entry in the JAR file, and returns the unevaluated form. Returns nil if the read fails, or if the first form is not a ns declaration." [#^JarFile jarfile #^String entry-name] (with-open [rdr (PushbackReader. (BufferedReader. (InputStreamReader. (.getInputStream jarfile (.getEntry jarfile entry-name)))))] (read-ns-decl rdr))) (defn find-ns-decls-in-jarfile "Searches the JAR file for Clojure source files containing (ns ...) declarations; returns the unevaluated ns declarations." [#^JarFile jarfile] (filter identity (map #(read-ns-decl-from-jarfile-entry jarfile %) (clojure-sources-in-jar jarfile)))) (defn find-namespaces-in-jarfile "Searches the JAR file for Clojure source files containing (ns ...) declarations. Returns a sequence of the symbol names of the declared namespaces." [#^JarFile jarfile] (map second (find-ns-decls-in-jarfile jarfile))) ;;; Finding namespaces anywhere on CLASSPATH (defn find-ns-decls-on-classpath "Searches CLASSPATH (both directories and JAR files) for Clojure source files containing (ns ...) declarations. Returns a sequence of the unevaluated ns declaration forms." [] (concat (mapcat find-ns-decls-in-dir (cp/classpath-directories)) (mapcat find-ns-decls-in-jarfile (cp/classpath-jarfiles)))) (defn find-namespaces-on-classpath "Searches CLASSPATH (both directories and JAR files) for Clojure source files containing (ns ...) declarations. Returns a sequence of the symbol names of the declared namespaces." [] (map second (find-ns-decls-on-classpath)))
97824
;;; find_namespaces.clj: search for ns declarations in dirs, JARs, or CLASSPATH ;; by <NAME>, http://stuartsierra.com/ ;; April 19, 2009 ;; Copyright (c) <NAME>, 2009. 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 #^{:author "<NAME>", :doc "Search for ns declarations in dirs, JARs, or CLASSPATH"} clojure.contrib.find-namespaces (:require [clojure.contrib.classpath :as cp] [clojure.contrib.jar :as jar]) (import (java.io File FileReader BufferedReader PushbackReader InputStreamReader) (java.util.jar JarFile))) ;;; Finding namespaces in a directory tree (defn clojure-source-file? "Returns true if file is a normal file with a .clj extension." [#^File file] (and (.isFile file) (.endsWith (.getName file) ".clj"))) (defn find-clojure-sources-in-dir "Searches recursively under dir for Clojure source files (.clj). Returns a sequence of File objects, in breadth-first sort order." [#^File dir] ;; Use sort by absolute path to get breadth-first search. (sort-by #(.getAbsolutePath %) (filter clojure-source-file? (file-seq dir)))) (defn comment? "Returns true if form is a (comment ...)" [form] (and (list? form) (= 'comment (first form)))) (defn ns-decl? "Returns true if form is a (ns ...) declaration." [form] (and (list? form) (= 'ns (first form)))) (defn read-ns-decl "Attempts to read a (ns ...) declaration from rdr, and returns the unevaluated form. Returns nil if read fails or if a ns declaration cannot be found. The ns declaration must be the first Clojure form in the file, except for (comment ...) forms." [#^PushbackReader rdr] (try (let [form (read rdr)] (cond (ns-decl? form) form (comment? form) (recur rdr) :else nil)) (catch Exception e nil))) (defn read-file-ns-decl "Attempts to read a (ns ...) declaration from file, and returns the unevaluated form. Returns nil if read fails, or if the first form is not a ns declaration." [#^File file] (with-open [rdr (PushbackReader. (BufferedReader. (FileReader. file)))] (read-ns-decl rdr))) (defn find-ns-decls-in-dir "Searches dir recursively for (ns ...) declarations in Clojure source files; returns the unevaluated ns declarations." [#^File dir] (filter identity (map read-file-ns-decl (find-clojure-sources-in-dir dir)))) (defn find-namespaces-in-dir "Searches dir recursively for (ns ...) declarations in Clojure source files; returns the symbol names of the declared namespaces." [#^File dir] (map second (find-ns-decls-in-dir dir))) ;;; Finding namespaces in JAR files (defn clojure-sources-in-jar "Returns a sequence of filenames ending in .clj found in the JAR file." [#^JarFile jar-file] (filter #(.endsWith % ".clj") (jar/filenames-in-jar jar-file))) (defn read-ns-decl-from-jarfile-entry "Attempts to read a (ns ...) declaration from the named entry in the JAR file, and returns the unevaluated form. Returns nil if the read fails, or if the first form is not a ns declaration." [#^JarFile jarfile #^String entry-name] (with-open [rdr (PushbackReader. (BufferedReader. (InputStreamReader. (.getInputStream jarfile (.getEntry jarfile entry-name)))))] (read-ns-decl rdr))) (defn find-ns-decls-in-jarfile "Searches the JAR file for Clojure source files containing (ns ...) declarations; returns the unevaluated ns declarations." [#^JarFile jarfile] (filter identity (map #(read-ns-decl-from-jarfile-entry jarfile %) (clojure-sources-in-jar jarfile)))) (defn find-namespaces-in-jarfile "Searches the JAR file for Clojure source files containing (ns ...) declarations. Returns a sequence of the symbol names of the declared namespaces." [#^JarFile jarfile] (map second (find-ns-decls-in-jarfile jarfile))) ;;; Finding namespaces anywhere on CLASSPATH (defn find-ns-decls-on-classpath "Searches CLASSPATH (both directories and JAR files) for Clojure source files containing (ns ...) declarations. Returns a sequence of the unevaluated ns declaration forms." [] (concat (mapcat find-ns-decls-in-dir (cp/classpath-directories)) (mapcat find-ns-decls-in-jarfile (cp/classpath-jarfiles)))) (defn find-namespaces-on-classpath "Searches CLASSPATH (both directories and JAR files) for Clojure source files containing (ns ...) declarations. Returns a sequence of the symbol names of the declared namespaces." [] (map second (find-ns-decls-on-classpath)))
true
;;; find_namespaces.clj: search for ns declarations in dirs, JARs, or CLASSPATH ;; by PI:NAME:<NAME>END_PI, http://stuartsierra.com/ ;; April 19, 2009 ;; Copyright (c) PI:NAME:<NAME>END_PI, 2009. 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 #^{:author "PI:NAME:<NAME>END_PI", :doc "Search for ns declarations in dirs, JARs, or CLASSPATH"} clojure.contrib.find-namespaces (:require [clojure.contrib.classpath :as cp] [clojure.contrib.jar :as jar]) (import (java.io File FileReader BufferedReader PushbackReader InputStreamReader) (java.util.jar JarFile))) ;;; Finding namespaces in a directory tree (defn clojure-source-file? "Returns true if file is a normal file with a .clj extension." [#^File file] (and (.isFile file) (.endsWith (.getName file) ".clj"))) (defn find-clojure-sources-in-dir "Searches recursively under dir for Clojure source files (.clj). Returns a sequence of File objects, in breadth-first sort order." [#^File dir] ;; Use sort by absolute path to get breadth-first search. (sort-by #(.getAbsolutePath %) (filter clojure-source-file? (file-seq dir)))) (defn comment? "Returns true if form is a (comment ...)" [form] (and (list? form) (= 'comment (first form)))) (defn ns-decl? "Returns true if form is a (ns ...) declaration." [form] (and (list? form) (= 'ns (first form)))) (defn read-ns-decl "Attempts to read a (ns ...) declaration from rdr, and returns the unevaluated form. Returns nil if read fails or if a ns declaration cannot be found. The ns declaration must be the first Clojure form in the file, except for (comment ...) forms." [#^PushbackReader rdr] (try (let [form (read rdr)] (cond (ns-decl? form) form (comment? form) (recur rdr) :else nil)) (catch Exception e nil))) (defn read-file-ns-decl "Attempts to read a (ns ...) declaration from file, and returns the unevaluated form. Returns nil if read fails, or if the first form is not a ns declaration." [#^File file] (with-open [rdr (PushbackReader. (BufferedReader. (FileReader. file)))] (read-ns-decl rdr))) (defn find-ns-decls-in-dir "Searches dir recursively for (ns ...) declarations in Clojure source files; returns the unevaluated ns declarations." [#^File dir] (filter identity (map read-file-ns-decl (find-clojure-sources-in-dir dir)))) (defn find-namespaces-in-dir "Searches dir recursively for (ns ...) declarations in Clojure source files; returns the symbol names of the declared namespaces." [#^File dir] (map second (find-ns-decls-in-dir dir))) ;;; Finding namespaces in JAR files (defn clojure-sources-in-jar "Returns a sequence of filenames ending in .clj found in the JAR file." [#^JarFile jar-file] (filter #(.endsWith % ".clj") (jar/filenames-in-jar jar-file))) (defn read-ns-decl-from-jarfile-entry "Attempts to read a (ns ...) declaration from the named entry in the JAR file, and returns the unevaluated form. Returns nil if the read fails, or if the first form is not a ns declaration." [#^JarFile jarfile #^String entry-name] (with-open [rdr (PushbackReader. (BufferedReader. (InputStreamReader. (.getInputStream jarfile (.getEntry jarfile entry-name)))))] (read-ns-decl rdr))) (defn find-ns-decls-in-jarfile "Searches the JAR file for Clojure source files containing (ns ...) declarations; returns the unevaluated ns declarations." [#^JarFile jarfile] (filter identity (map #(read-ns-decl-from-jarfile-entry jarfile %) (clojure-sources-in-jar jarfile)))) (defn find-namespaces-in-jarfile "Searches the JAR file for Clojure source files containing (ns ...) declarations. Returns a sequence of the symbol names of the declared namespaces." [#^JarFile jarfile] (map second (find-ns-decls-in-jarfile jarfile))) ;;; Finding namespaces anywhere on CLASSPATH (defn find-ns-decls-on-classpath "Searches CLASSPATH (both directories and JAR files) for Clojure source files containing (ns ...) declarations. Returns a sequence of the unevaluated ns declaration forms." [] (concat (mapcat find-ns-decls-in-dir (cp/classpath-directories)) (mapcat find-ns-decls-in-jarfile (cp/classpath-jarfiles)))) (defn find-namespaces-on-classpath "Searches CLASSPATH (both directories and JAR files) for Clojure source files containing (ns ...) declarations. Returns a sequence of the symbol names of the declared namespaces." [] (map second (find-ns-decls-on-classpath)))
[ { "context": ";; Copyright (c) 2011,2012,2013 Walter Tetzner\n\n;; Permission is hereby granted, free of charge,", "end": 46, "score": 0.9998157024383545, "start": 32, "tag": "NAME", "value": "Walter Tetzner" } ]
src/org/bovinegenius/exploding_fish/path.clj
wtetzner/exploding-fish
93
;; Copyright (c) 2011,2012,2013 Walter Tetzner ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, copy, ;; modify, merge, publish, distribute, sublicense, and/or sell copies ;; of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;; DEALINGS IN THE SOFTWARE. (ns org.bovinegenius.exploding-fish.path (:require (clojure [string :as str]))) (defn split-path "Split a path into its parts." [path] (->> (range (count path)) (map (fn [index] (String. ^ints (into-array Integer/TYPE [(.codePointAt ^String path index)]) 0 1))) (reduce (fn [parts char] (if (= "/" char) (conj parts "") (assoc parts (-> parts count dec) (str (last parts) char)))) [""]))) (defn ^String normalize "Normalize the given path." [path] (if (nil? path) path (->> (str/replace path #"/+" "/") split-path (remove (partial = ".")) (reduce (fn [pieces element] (cond (and (= element "..") (or (empty? pieces) (= (last pieces) ".."))) (conj pieces element) (= element "..") (pop pieces) :else (conj pieces element))) []) (str/join "/")))) (defn absolute? "Returns true if the given path is absolute, false otherwise." [path] (.startsWith ^String path "/")) (defn ^String resolve-path "Resolve one path against a base path." [base path] (if (absolute? path) (normalize path) (let [base-parts (split-path base) path-parts (split-path path)] (->> (concat (butlast base-parts) path-parts) (str/join "/") normalize))))
41459
;; Copyright (c) 2011,2012,2013 <NAME> ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, copy, ;; modify, merge, publish, distribute, sublicense, and/or sell copies ;; of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;; DEALINGS IN THE SOFTWARE. (ns org.bovinegenius.exploding-fish.path (:require (clojure [string :as str]))) (defn split-path "Split a path into its parts." [path] (->> (range (count path)) (map (fn [index] (String. ^ints (into-array Integer/TYPE [(.codePointAt ^String path index)]) 0 1))) (reduce (fn [parts char] (if (= "/" char) (conj parts "") (assoc parts (-> parts count dec) (str (last parts) char)))) [""]))) (defn ^String normalize "Normalize the given path." [path] (if (nil? path) path (->> (str/replace path #"/+" "/") split-path (remove (partial = ".")) (reduce (fn [pieces element] (cond (and (= element "..") (or (empty? pieces) (= (last pieces) ".."))) (conj pieces element) (= element "..") (pop pieces) :else (conj pieces element))) []) (str/join "/")))) (defn absolute? "Returns true if the given path is absolute, false otherwise." [path] (.startsWith ^String path "/")) (defn ^String resolve-path "Resolve one path against a base path." [base path] (if (absolute? path) (normalize path) (let [base-parts (split-path base) path-parts (split-path path)] (->> (concat (butlast base-parts) path-parts) (str/join "/") normalize))))
true
;; Copyright (c) 2011,2012,2013 PI:NAME:<NAME>END_PI ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, copy, ;; modify, merge, publish, distribute, sublicense, and/or sell copies ;; of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;; DEALINGS IN THE SOFTWARE. (ns org.bovinegenius.exploding-fish.path (:require (clojure [string :as str]))) (defn split-path "Split a path into its parts." [path] (->> (range (count path)) (map (fn [index] (String. ^ints (into-array Integer/TYPE [(.codePointAt ^String path index)]) 0 1))) (reduce (fn [parts char] (if (= "/" char) (conj parts "") (assoc parts (-> parts count dec) (str (last parts) char)))) [""]))) (defn ^String normalize "Normalize the given path." [path] (if (nil? path) path (->> (str/replace path #"/+" "/") split-path (remove (partial = ".")) (reduce (fn [pieces element] (cond (and (= element "..") (or (empty? pieces) (= (last pieces) ".."))) (conj pieces element) (= element "..") (pop pieces) :else (conj pieces element))) []) (str/join "/")))) (defn absolute? "Returns true if the given path is absolute, false otherwise." [path] (.startsWith ^String path "/")) (defn ^String resolve-path "Resolve one path against a base path." [base path] (if (absolute? path) (normalize path) (let [base-parts (split-path base) path-parts (split-path path)] (->> (concat (butlast base-parts) path-parts) (str/join "/") normalize))))
[ { "context": "ast-update-time\" 1000, \"owner\" \"test-1\", \"token\" \"token-1\"}\n {\"last-update-time\"", "end": 5218, "score": 0.7095683217048645, "start": 5211, "tag": "KEY", "value": "token-1" }, { "context": "ast-update-time\" 2000, \"owner\" \"test-2\", \"token\" \"token-2\"}\n {\"last-update-time\"", "end": 5309, "score": 0.6050283312797546, "start": 5302, "tag": "KEY", "value": "token-2" }, { "context": "ast-update-time\" 3000, \"owner\" \"test-3\", \"token\" \"token-3\"}]]\n (with-redefs [make-http-request (fn", "end": 5398, "score": 0.7762542963027954, "start": 5393, "tag": "KEY", "value": "token" }, { "context": "pdate-time\" 3000, \"owner\" \"test-3\", \"token\" \"token-3\"}]]\n (with-redefs [make-http-request (fn [", "end": 5400, "score": 0.548646092414856, "start": 5399, "tag": "PASSWORD", "value": "3" }, { "context": "rl \"http://www.test.com:1234\"\n test-token \"lorem-ipsum\"\n expected-options {:headers {\"accept\" \"ap", "end": 6281, "score": 0.9967330694198608, "start": 6270, "tag": "PASSWORD", "value": "lorem-ipsum" }, { "context": "rl \"http://www.test.com:1234\"\n test-token \"lorem-ipsum\"\n test-token-etag (System/currentTimeMilli", "end": 8519, "score": 0.9980422854423523, "start": 8508, "tag": "PASSWORD", "value": "lorem-ipsum" }, { "context": "rl \"http://www.test.com:1234\"\n test-token \"lorem-ipsum\"\n test-token-etag (System/currentTimeMilli", "end": 11494, "score": 0.9979894757270813, "start": 11483, "tag": "PASSWORD", "value": "lorem-ipsum" }, { "context": "rl \"http://www.test.com:1234\"\n test-token \"lorem-ipsum\"\n queue-timeout-ms 120000\n expected", "end": 14317, "score": 0.99626225233078, "start": 14306, "tag": "PASSWORD", "value": "lorem-ipsum" } ]
token-syncer/test/token_syncer/waiter_test.clj
twosigmajab/waiter
1
;; ;; 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 token-syncer.waiter-test (:require [clojure.core.async :as async] [clojure.data.json :as json] [clojure.test :refer :all] [qbits.jet.client.http :as http] [token-syncer.waiter :refer :all])) (defn- send-json-response [body-data & {:keys [headers status]}] (let [body-chan (async/promise-chan)] (->> body-data json/write-str (async/put! body-chan)) (cond-> {:body body-chan :headers (or headers {})} status (assoc :status status)))) (deftest test-make-http-request (let [http-client-wrapper (Object.) test-endpoint "/foo/bar" test-body "test-body-data" test-headers {"header" "value", "source" "test"} test-query-params {"foo" "bar", "lorem" "ipsum"}] (testing "simple request" (with-redefs [http/get (fn get-wrapper [in-http-client in-endopint-url in-options] (is (= http-client-wrapper in-http-client)) (is (= test-endpoint in-endopint-url)) (is (not (contains? in-options :auth))) (is (= {:body test-body :headers test-headers :fold-chunked-response? true :query-string test-query-params} (update in-options :headers dissoc "x-cid"))) (let [response-chan (async/promise-chan)] (async/put! response-chan {}) response-chan))] (make-http-request http-client-wrapper test-endpoint :body test-body :headers test-headers :query-params test-query-params))) (testing "spengo auth" (let [call-counter (atom 0)] (with-redefs [http/get (fn get-wrapper [in-http-client in-endopint-url in-options] (swap! call-counter inc) (is (= http-client-wrapper in-http-client)) (is (= test-endpoint in-endopint-url)) (when (= @call-counter 2) (is (contains? in-options :auth))) (is (= {:body test-body :headers test-headers :fold-chunked-response? true :query-string test-query-params} (-> in-options (dissoc :auth) (update :headers dissoc "x-cid")))) (let [response-chan (async/promise-chan) response (cond-> {} (not (:auth in-options)) (assoc :status 401 :headers {"www-authenticate" "Negotiate"}))] (async/put! response-chan response) response-chan))] (make-http-request http-client-wrapper test-endpoint :body test-body :headers test-headers :query-params test-query-params) (is (= 2 @call-counter))))))) (deftest test-load-token-list (let [http-client-wrapper (Object.) test-cluster-url "http://www.test.com:1234"] (testing "error in response" (let [error (Exception. "exception from test")] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/tokens") in-endopint-url)) (is (= [:headers {"accept" "application/json"} :query-params {"include" ["deleted" "metadata"]}] in-options)) (throw error))] (is (thrown-with-msg? Exception #"exception from test" (load-token-list http-client-wrapper test-cluster-url)))))) (testing "successful response" (let [token-response [{"last-update-time" 1000, "owner" "test-1", "token" "token-1"} {"last-update-time" 2000, "owner" "test-2", "token" "token-2"} {"last-update-time" 3000, "owner" "test-3", "token" "token-3"}]] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/tokens") in-endopint-url)) (is (= [:headers {"accept" "application/json"} :query-params {"include" ["deleted" "metadata"]}] in-options)) (send-json-response token-response :status 200))] (is (= token-response (load-token-list http-client-wrapper test-cluster-url)))))))) (deftest test-load-token (let [http-client-wrapper (Object.) test-cluster-url "http://www.test.com:1234" test-token "lorem-ipsum" expected-options {:headers {"accept" "application/json" "x-waiter-token" test-token} :query-params {"include" ["deleted" "metadata"]}}] (testing "error in response" (let [error (Exception. "exception from test")] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (throw error))] (is (= {:error error} (load-token http-client-wrapper test-cluster-url test-token)))))) (testing "successful response" (let [token-response {"foo" "bar", "lorem" "ipsum"} current-time-ms (-> (System/currentTimeMillis) (mod 1000) (* 1000)) last-modified-str current-time-ms] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response token-response :headers {"etag" last-modified-str} :status 200))] (is (= {:description {"foo" "bar", "lorem" "ipsum"} :headers {"etag" last-modified-str} :status 200 :token-etag current-time-ms} (load-token http-client-wrapper test-cluster-url test-token)))))))) (deftest test-store-token (let [http-client-wrapper (Object.) test-cluster-url "http://www.test.com:1234" test-token "lorem-ipsum" test-token-etag (System/currentTimeMillis) test-description {"foo" "bar" "lorem" "ipsum"} expected-options {:body (json/write-str (assoc test-description :token test-token)) :headers {"accept" "application/json" "if-match" test-token-etag} :method :post :query-params {"update-mode" "admin"}}] (testing "error in response" (let [error (Exception. "exception from test")] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (throw error))] (is (thrown-with-msg? Exception #"exception from test" (store-token http-client-wrapper test-cluster-url test-token test-token-etag test-description)))))) (testing "error in status code" (let [token-response {"message" "failed"}] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response token-response :status 300))] (is (thrown-with-msg? Exception #"Token store failed" (store-token http-client-wrapper test-cluster-url test-token test-token-etag test-description)))))) (testing "successful response" (let [token-response {"message" "success"}] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response token-response :status 200))] (is (= {:body token-response, :headers {}, :status 200} (store-token http-client-wrapper test-cluster-url test-token test-token-etag test-description)))))))) (deftest test-hard-delete-token (let [http-client-wrapper (Object.) test-cluster-url "http://www.test.com:1234" test-token "lorem-ipsum" test-token-etag (System/currentTimeMillis) expected-options {:headers {"accept" "application/json" "if-match" test-token-etag "x-waiter-token" test-token} :method :delete :query-params {"hard-delete" "true"}}] (testing "error in response" (let [error (Exception. "exception from test")] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (throw error))] (is (thrown-with-msg? Exception #"exception from test" (hard-delete-token http-client-wrapper test-cluster-url test-token test-token-etag)))))) (testing "error in status code" (let [token-response {"message" "failed"}] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response token-response :status 300))] (is (thrown-with-msg? Exception #"Token hard-delete failed" (hard-delete-token http-client-wrapper test-cluster-url test-token test-token-etag)))))) (testing "successful response" (let [token-response {"message" "success"}] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response token-response :status 200))] (is (= {:body token-response, :headers {}, :status 200} (hard-delete-token http-client-wrapper test-cluster-url test-token test-token-etag)))))))) (deftest test-health-check-token (let [http-client-wrapper (Object.) test-cluster-url "http://www.test.com:1234" test-token "lorem-ipsum" queue-timeout-ms 120000 expected-options {:headers {"x-waiter-queue-timeout" queue-timeout-ms "x-waiter-token" test-token} :method :get :query-params {}}] (testing "error in loading token" (let [error (Exception. "exception from test")] (with-redefs [load-token (fn [in-http-client-wrapper in-cluster-url in-token] (is (= http-client-wrapper in-http-client-wrapper)) (is (= test-cluster-url in-cluster-url)) (is (= test-token in-token)) (throw error)) make-http-request (fn [& _] (throw (Exception. "unexpected call")))] (is (thrown-with-msg? Exception #"exception from test" (health-check-token http-client-wrapper test-cluster-url test-token queue-timeout-ms)))))) (testing "deleted token" (let [error (Exception. "exception from test")] (with-redefs [load-token (fn [in-http-client-wrapper in-cluster-url in-token] (is (= http-client-wrapper in-http-client-wrapper)) (is (= test-cluster-url in-cluster-url)) (is (= test-token in-token)) {"deleted" true "health-check-url" "/health-check"}) make-http-request (fn [& _] (throw (Exception. "unexpected call")))] (is (nil? (health-check-token http-client-wrapper test-cluster-url test-token queue-timeout-ms)))))) (testing "error in health check" (let [error (Exception. "exception from test")] (with-redefs [load-token (fn [in-http-client-wrapper in-cluster-url in-token] (is (= http-client-wrapper in-http-client-wrapper)) (is (= test-cluster-url in-cluster-url)) (is (= test-token in-token)) {:description {"health-check-url" "/health-check"}}) make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/health-check") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (throw error))] (is (thrown-with-msg? Exception #"exception from test" (health-check-token http-client-wrapper test-cluster-url test-token queue-timeout-ms)))))) (testing "error in status code" (with-redefs [load-token (fn [in-http-client-wrapper in-cluster-url in-token] (is (= http-client-wrapper in-http-client-wrapper)) (is (= test-cluster-url in-cluster-url)) (is (= test-token in-token)) {:description {"health-check-url" "/health-check"}}) make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/health-check") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response {"message" "failed"} :status 400))] (is (= {:body "{\"message\":\"failed\"}" :headers {} :status 400} (health-check-token http-client-wrapper test-cluster-url test-token queue-timeout-ms))))) (testing "successful response" (with-redefs [load-token (fn [in-http-client-wrapper in-cluster-url in-token] (is (= http-client-wrapper in-http-client-wrapper)) (is (= test-cluster-url in-cluster-url)) (is (= test-token in-token)) {:description {"health-check-url" "/health-check"}}) make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/health-check") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response {"message" "success"} :status 200))] (is (= {:body "{\"message\":\"success\"}" :headers {} :status 200} (health-check-token http-client-wrapper test-cluster-url test-token queue-timeout-ms)))))))
26402
;; ;; 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 token-syncer.waiter-test (:require [clojure.core.async :as async] [clojure.data.json :as json] [clojure.test :refer :all] [qbits.jet.client.http :as http] [token-syncer.waiter :refer :all])) (defn- send-json-response [body-data & {:keys [headers status]}] (let [body-chan (async/promise-chan)] (->> body-data json/write-str (async/put! body-chan)) (cond-> {:body body-chan :headers (or headers {})} status (assoc :status status)))) (deftest test-make-http-request (let [http-client-wrapper (Object.) test-endpoint "/foo/bar" test-body "test-body-data" test-headers {"header" "value", "source" "test"} test-query-params {"foo" "bar", "lorem" "ipsum"}] (testing "simple request" (with-redefs [http/get (fn get-wrapper [in-http-client in-endopint-url in-options] (is (= http-client-wrapper in-http-client)) (is (= test-endpoint in-endopint-url)) (is (not (contains? in-options :auth))) (is (= {:body test-body :headers test-headers :fold-chunked-response? true :query-string test-query-params} (update in-options :headers dissoc "x-cid"))) (let [response-chan (async/promise-chan)] (async/put! response-chan {}) response-chan))] (make-http-request http-client-wrapper test-endpoint :body test-body :headers test-headers :query-params test-query-params))) (testing "spengo auth" (let [call-counter (atom 0)] (with-redefs [http/get (fn get-wrapper [in-http-client in-endopint-url in-options] (swap! call-counter inc) (is (= http-client-wrapper in-http-client)) (is (= test-endpoint in-endopint-url)) (when (= @call-counter 2) (is (contains? in-options :auth))) (is (= {:body test-body :headers test-headers :fold-chunked-response? true :query-string test-query-params} (-> in-options (dissoc :auth) (update :headers dissoc "x-cid")))) (let [response-chan (async/promise-chan) response (cond-> {} (not (:auth in-options)) (assoc :status 401 :headers {"www-authenticate" "Negotiate"}))] (async/put! response-chan response) response-chan))] (make-http-request http-client-wrapper test-endpoint :body test-body :headers test-headers :query-params test-query-params) (is (= 2 @call-counter))))))) (deftest test-load-token-list (let [http-client-wrapper (Object.) test-cluster-url "http://www.test.com:1234"] (testing "error in response" (let [error (Exception. "exception from test")] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/tokens") in-endopint-url)) (is (= [:headers {"accept" "application/json"} :query-params {"include" ["deleted" "metadata"]}] in-options)) (throw error))] (is (thrown-with-msg? Exception #"exception from test" (load-token-list http-client-wrapper test-cluster-url)))))) (testing "successful response" (let [token-response [{"last-update-time" 1000, "owner" "test-1", "token" "<KEY>"} {"last-update-time" 2000, "owner" "test-2", "token" "<KEY>"} {"last-update-time" 3000, "owner" "test-3", "token" "<KEY>-<PASSWORD>"}]] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/tokens") in-endopint-url)) (is (= [:headers {"accept" "application/json"} :query-params {"include" ["deleted" "metadata"]}] in-options)) (send-json-response token-response :status 200))] (is (= token-response (load-token-list http-client-wrapper test-cluster-url)))))))) (deftest test-load-token (let [http-client-wrapper (Object.) test-cluster-url "http://www.test.com:1234" test-token "<PASSWORD>" expected-options {:headers {"accept" "application/json" "x-waiter-token" test-token} :query-params {"include" ["deleted" "metadata"]}}] (testing "error in response" (let [error (Exception. "exception from test")] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (throw error))] (is (= {:error error} (load-token http-client-wrapper test-cluster-url test-token)))))) (testing "successful response" (let [token-response {"foo" "bar", "lorem" "ipsum"} current-time-ms (-> (System/currentTimeMillis) (mod 1000) (* 1000)) last-modified-str current-time-ms] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response token-response :headers {"etag" last-modified-str} :status 200))] (is (= {:description {"foo" "bar", "lorem" "ipsum"} :headers {"etag" last-modified-str} :status 200 :token-etag current-time-ms} (load-token http-client-wrapper test-cluster-url test-token)))))))) (deftest test-store-token (let [http-client-wrapper (Object.) test-cluster-url "http://www.test.com:1234" test-token "<PASSWORD>" test-token-etag (System/currentTimeMillis) test-description {"foo" "bar" "lorem" "ipsum"} expected-options {:body (json/write-str (assoc test-description :token test-token)) :headers {"accept" "application/json" "if-match" test-token-etag} :method :post :query-params {"update-mode" "admin"}}] (testing "error in response" (let [error (Exception. "exception from test")] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (throw error))] (is (thrown-with-msg? Exception #"exception from test" (store-token http-client-wrapper test-cluster-url test-token test-token-etag test-description)))))) (testing "error in status code" (let [token-response {"message" "failed"}] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response token-response :status 300))] (is (thrown-with-msg? Exception #"Token store failed" (store-token http-client-wrapper test-cluster-url test-token test-token-etag test-description)))))) (testing "successful response" (let [token-response {"message" "success"}] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response token-response :status 200))] (is (= {:body token-response, :headers {}, :status 200} (store-token http-client-wrapper test-cluster-url test-token test-token-etag test-description)))))))) (deftest test-hard-delete-token (let [http-client-wrapper (Object.) test-cluster-url "http://www.test.com:1234" test-token "<PASSWORD>" test-token-etag (System/currentTimeMillis) expected-options {:headers {"accept" "application/json" "if-match" test-token-etag "x-waiter-token" test-token} :method :delete :query-params {"hard-delete" "true"}}] (testing "error in response" (let [error (Exception. "exception from test")] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (throw error))] (is (thrown-with-msg? Exception #"exception from test" (hard-delete-token http-client-wrapper test-cluster-url test-token test-token-etag)))))) (testing "error in status code" (let [token-response {"message" "failed"}] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response token-response :status 300))] (is (thrown-with-msg? Exception #"Token hard-delete failed" (hard-delete-token http-client-wrapper test-cluster-url test-token test-token-etag)))))) (testing "successful response" (let [token-response {"message" "success"}] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response token-response :status 200))] (is (= {:body token-response, :headers {}, :status 200} (hard-delete-token http-client-wrapper test-cluster-url test-token test-token-etag)))))))) (deftest test-health-check-token (let [http-client-wrapper (Object.) test-cluster-url "http://www.test.com:1234" test-token "<PASSWORD>" queue-timeout-ms 120000 expected-options {:headers {"x-waiter-queue-timeout" queue-timeout-ms "x-waiter-token" test-token} :method :get :query-params {}}] (testing "error in loading token" (let [error (Exception. "exception from test")] (with-redefs [load-token (fn [in-http-client-wrapper in-cluster-url in-token] (is (= http-client-wrapper in-http-client-wrapper)) (is (= test-cluster-url in-cluster-url)) (is (= test-token in-token)) (throw error)) make-http-request (fn [& _] (throw (Exception. "unexpected call")))] (is (thrown-with-msg? Exception #"exception from test" (health-check-token http-client-wrapper test-cluster-url test-token queue-timeout-ms)))))) (testing "deleted token" (let [error (Exception. "exception from test")] (with-redefs [load-token (fn [in-http-client-wrapper in-cluster-url in-token] (is (= http-client-wrapper in-http-client-wrapper)) (is (= test-cluster-url in-cluster-url)) (is (= test-token in-token)) {"deleted" true "health-check-url" "/health-check"}) make-http-request (fn [& _] (throw (Exception. "unexpected call")))] (is (nil? (health-check-token http-client-wrapper test-cluster-url test-token queue-timeout-ms)))))) (testing "error in health check" (let [error (Exception. "exception from test")] (with-redefs [load-token (fn [in-http-client-wrapper in-cluster-url in-token] (is (= http-client-wrapper in-http-client-wrapper)) (is (= test-cluster-url in-cluster-url)) (is (= test-token in-token)) {:description {"health-check-url" "/health-check"}}) make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/health-check") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (throw error))] (is (thrown-with-msg? Exception #"exception from test" (health-check-token http-client-wrapper test-cluster-url test-token queue-timeout-ms)))))) (testing "error in status code" (with-redefs [load-token (fn [in-http-client-wrapper in-cluster-url in-token] (is (= http-client-wrapper in-http-client-wrapper)) (is (= test-cluster-url in-cluster-url)) (is (= test-token in-token)) {:description {"health-check-url" "/health-check"}}) make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/health-check") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response {"message" "failed"} :status 400))] (is (= {:body "{\"message\":\"failed\"}" :headers {} :status 400} (health-check-token http-client-wrapper test-cluster-url test-token queue-timeout-ms))))) (testing "successful response" (with-redefs [load-token (fn [in-http-client-wrapper in-cluster-url in-token] (is (= http-client-wrapper in-http-client-wrapper)) (is (= test-cluster-url in-cluster-url)) (is (= test-token in-token)) {:description {"health-check-url" "/health-check"}}) make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/health-check") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response {"message" "success"} :status 200))] (is (= {:body "{\"message\":\"success\"}" :headers {} :status 200} (health-check-token http-client-wrapper test-cluster-url test-token queue-timeout-ms)))))))
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 token-syncer.waiter-test (:require [clojure.core.async :as async] [clojure.data.json :as json] [clojure.test :refer :all] [qbits.jet.client.http :as http] [token-syncer.waiter :refer :all])) (defn- send-json-response [body-data & {:keys [headers status]}] (let [body-chan (async/promise-chan)] (->> body-data json/write-str (async/put! body-chan)) (cond-> {:body body-chan :headers (or headers {})} status (assoc :status status)))) (deftest test-make-http-request (let [http-client-wrapper (Object.) test-endpoint "/foo/bar" test-body "test-body-data" test-headers {"header" "value", "source" "test"} test-query-params {"foo" "bar", "lorem" "ipsum"}] (testing "simple request" (with-redefs [http/get (fn get-wrapper [in-http-client in-endopint-url in-options] (is (= http-client-wrapper in-http-client)) (is (= test-endpoint in-endopint-url)) (is (not (contains? in-options :auth))) (is (= {:body test-body :headers test-headers :fold-chunked-response? true :query-string test-query-params} (update in-options :headers dissoc "x-cid"))) (let [response-chan (async/promise-chan)] (async/put! response-chan {}) response-chan))] (make-http-request http-client-wrapper test-endpoint :body test-body :headers test-headers :query-params test-query-params))) (testing "spengo auth" (let [call-counter (atom 0)] (with-redefs [http/get (fn get-wrapper [in-http-client in-endopint-url in-options] (swap! call-counter inc) (is (= http-client-wrapper in-http-client)) (is (= test-endpoint in-endopint-url)) (when (= @call-counter 2) (is (contains? in-options :auth))) (is (= {:body test-body :headers test-headers :fold-chunked-response? true :query-string test-query-params} (-> in-options (dissoc :auth) (update :headers dissoc "x-cid")))) (let [response-chan (async/promise-chan) response (cond-> {} (not (:auth in-options)) (assoc :status 401 :headers {"www-authenticate" "Negotiate"}))] (async/put! response-chan response) response-chan))] (make-http-request http-client-wrapper test-endpoint :body test-body :headers test-headers :query-params test-query-params) (is (= 2 @call-counter))))))) (deftest test-load-token-list (let [http-client-wrapper (Object.) test-cluster-url "http://www.test.com:1234"] (testing "error in response" (let [error (Exception. "exception from test")] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/tokens") in-endopint-url)) (is (= [:headers {"accept" "application/json"} :query-params {"include" ["deleted" "metadata"]}] in-options)) (throw error))] (is (thrown-with-msg? Exception #"exception from test" (load-token-list http-client-wrapper test-cluster-url)))))) (testing "successful response" (let [token-response [{"last-update-time" 1000, "owner" "test-1", "token" "PI:KEY:<KEY>END_PI"} {"last-update-time" 2000, "owner" "test-2", "token" "PI:KEY:<KEY>END_PI"} {"last-update-time" 3000, "owner" "test-3", "token" "PI:KEY:<KEY>END_PI-PI:PASSWORD:<PASSWORD>END_PI"}]] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/tokens") in-endopint-url)) (is (= [:headers {"accept" "application/json"} :query-params {"include" ["deleted" "metadata"]}] in-options)) (send-json-response token-response :status 200))] (is (= token-response (load-token-list http-client-wrapper test-cluster-url)))))))) (deftest test-load-token (let [http-client-wrapper (Object.) test-cluster-url "http://www.test.com:1234" test-token "PI:PASSWORD:<PASSWORD>END_PI" expected-options {:headers {"accept" "application/json" "x-waiter-token" test-token} :query-params {"include" ["deleted" "metadata"]}}] (testing "error in response" (let [error (Exception. "exception from test")] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (throw error))] (is (= {:error error} (load-token http-client-wrapper test-cluster-url test-token)))))) (testing "successful response" (let [token-response {"foo" "bar", "lorem" "ipsum"} current-time-ms (-> (System/currentTimeMillis) (mod 1000) (* 1000)) last-modified-str current-time-ms] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response token-response :headers {"etag" last-modified-str} :status 200))] (is (= {:description {"foo" "bar", "lorem" "ipsum"} :headers {"etag" last-modified-str} :status 200 :token-etag current-time-ms} (load-token http-client-wrapper test-cluster-url test-token)))))))) (deftest test-store-token (let [http-client-wrapper (Object.) test-cluster-url "http://www.test.com:1234" test-token "PI:PASSWORD:<PASSWORD>END_PI" test-token-etag (System/currentTimeMillis) test-description {"foo" "bar" "lorem" "ipsum"} expected-options {:body (json/write-str (assoc test-description :token test-token)) :headers {"accept" "application/json" "if-match" test-token-etag} :method :post :query-params {"update-mode" "admin"}}] (testing "error in response" (let [error (Exception. "exception from test")] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (throw error))] (is (thrown-with-msg? Exception #"exception from test" (store-token http-client-wrapper test-cluster-url test-token test-token-etag test-description)))))) (testing "error in status code" (let [token-response {"message" "failed"}] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response token-response :status 300))] (is (thrown-with-msg? Exception #"Token store failed" (store-token http-client-wrapper test-cluster-url test-token test-token-etag test-description)))))) (testing "successful response" (let [token-response {"message" "success"}] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response token-response :status 200))] (is (= {:body token-response, :headers {}, :status 200} (store-token http-client-wrapper test-cluster-url test-token test-token-etag test-description)))))))) (deftest test-hard-delete-token (let [http-client-wrapper (Object.) test-cluster-url "http://www.test.com:1234" test-token "PI:PASSWORD:<PASSWORD>END_PI" test-token-etag (System/currentTimeMillis) expected-options {:headers {"accept" "application/json" "if-match" test-token-etag "x-waiter-token" test-token} :method :delete :query-params {"hard-delete" "true"}}] (testing "error in response" (let [error (Exception. "exception from test")] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (throw error))] (is (thrown-with-msg? Exception #"exception from test" (hard-delete-token http-client-wrapper test-cluster-url test-token test-token-etag)))))) (testing "error in status code" (let [token-response {"message" "failed"}] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response token-response :status 300))] (is (thrown-with-msg? Exception #"Token hard-delete failed" (hard-delete-token http-client-wrapper test-cluster-url test-token test-token-etag)))))) (testing "successful response" (let [token-response {"message" "success"}] (with-redefs [make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/token") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response token-response :status 200))] (is (= {:body token-response, :headers {}, :status 200} (hard-delete-token http-client-wrapper test-cluster-url test-token test-token-etag)))))))) (deftest test-health-check-token (let [http-client-wrapper (Object.) test-cluster-url "http://www.test.com:1234" test-token "PI:PASSWORD:<PASSWORD>END_PI" queue-timeout-ms 120000 expected-options {:headers {"x-waiter-queue-timeout" queue-timeout-ms "x-waiter-token" test-token} :method :get :query-params {}}] (testing "error in loading token" (let [error (Exception. "exception from test")] (with-redefs [load-token (fn [in-http-client-wrapper in-cluster-url in-token] (is (= http-client-wrapper in-http-client-wrapper)) (is (= test-cluster-url in-cluster-url)) (is (= test-token in-token)) (throw error)) make-http-request (fn [& _] (throw (Exception. "unexpected call")))] (is (thrown-with-msg? Exception #"exception from test" (health-check-token http-client-wrapper test-cluster-url test-token queue-timeout-ms)))))) (testing "deleted token" (let [error (Exception. "exception from test")] (with-redefs [load-token (fn [in-http-client-wrapper in-cluster-url in-token] (is (= http-client-wrapper in-http-client-wrapper)) (is (= test-cluster-url in-cluster-url)) (is (= test-token in-token)) {"deleted" true "health-check-url" "/health-check"}) make-http-request (fn [& _] (throw (Exception. "unexpected call")))] (is (nil? (health-check-token http-client-wrapper test-cluster-url test-token queue-timeout-ms)))))) (testing "error in health check" (let [error (Exception. "exception from test")] (with-redefs [load-token (fn [in-http-client-wrapper in-cluster-url in-token] (is (= http-client-wrapper in-http-client-wrapper)) (is (= test-cluster-url in-cluster-url)) (is (= test-token in-token)) {:description {"health-check-url" "/health-check"}}) make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/health-check") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (throw error))] (is (thrown-with-msg? Exception #"exception from test" (health-check-token http-client-wrapper test-cluster-url test-token queue-timeout-ms)))))) (testing "error in status code" (with-redefs [load-token (fn [in-http-client-wrapper in-cluster-url in-token] (is (= http-client-wrapper in-http-client-wrapper)) (is (= test-cluster-url in-cluster-url)) (is (= test-token in-token)) {:description {"health-check-url" "/health-check"}}) make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/health-check") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response {"message" "failed"} :status 400))] (is (= {:body "{\"message\":\"failed\"}" :headers {} :status 400} (health-check-token http-client-wrapper test-cluster-url test-token queue-timeout-ms))))) (testing "successful response" (with-redefs [load-token (fn [in-http-client-wrapper in-cluster-url in-token] (is (= http-client-wrapper in-http-client-wrapper)) (is (= test-cluster-url in-cluster-url)) (is (= test-token in-token)) {:description {"health-check-url" "/health-check"}}) make-http-request (fn [in-http-client-wrapper in-endopint-url & in-options] (is (= http-client-wrapper in-http-client-wrapper)) (is (= (str test-cluster-url "/health-check") in-endopint-url)) (is (= expected-options (apply hash-map in-options))) (send-json-response {"message" "success"} :status 200))] (is (= {:body "{\"message\":\"success\"}" :headers {} :status 200} (health-check-token http-client-wrapper test-cluster-url test-token queue-timeout-ms)))))))
[ { "context": ";; The MIT License (MIT)\n;;\n;; Copyright (c) 2016 Richard Hull\n;;\n;; Permission is hereby granted, free of charg", "end": 62, "score": 0.9997742176055908, "start": 50, "tag": "NAME", "value": "Richard Hull" } ]
src/clustering/core/qt.cljc
CharlesHD/clustering
17
;; The MIT License (MIT) ;; ;; Copyright (c) 2016 Richard Hull ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in all ;; copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns clustering.core.qt "Quality Threshold (QT) clustering algorithm From: https://sites.google.com/site/dataclusteringalgorithms/quality-threshold-clustering-algorithm-1 1) Initialize the threshold distance allowed for clusters and the minimum cluster size. 2) Build a candidate cluster for each data point by including the closest point, the next closest, and so on, until the distance of the cluster surpasses the threshold. 3) Save the candidate cluster with the most points as the first true cluster, and remove all points in the cluster from further consideration. 4) Repeat with the reduced set of points until no more cluster can be formed having the minimum cluster size." (:require [clojure.set :refer [difference]])) (defn candidate-cluster "Determine which members of the dataset are closed to the candidate point within the given threshold" [distance-fn point dataset threshold] (let [too-big? #(> (distance-fn point %) threshold)] (set (remove too-big? dataset)))) (defn most-candidates [distance-fn dataset threshold] "Finds the largest cluster with the most members" (->> dataset (map #(candidate-cluster distance-fn % dataset threshold)) (sort-by count >) first)) (defn cluster "Groups members of supplied dataset into specific clusters according to the provided distance function (this should take 2 collection members and return a scalar difference between them). Candidate clusters are assembled such that the distance of the cluster surpasses the threshold. Further clusters are formed from the remaining points until no more clusters can be formed having the minimum cluster size." [distance-fn dataset threshold min-size] (loop [clusters [] uniq (set dataset)] (let [best (most-candidates distance-fn uniq threshold)] (if (< (count best) min-size) clusters (recur (conj clusters best) (difference uniq best))))))
83099
;; The MIT License (MIT) ;; ;; Copyright (c) 2016 <NAME> ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in all ;; copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns clustering.core.qt "Quality Threshold (QT) clustering algorithm From: https://sites.google.com/site/dataclusteringalgorithms/quality-threshold-clustering-algorithm-1 1) Initialize the threshold distance allowed for clusters and the minimum cluster size. 2) Build a candidate cluster for each data point by including the closest point, the next closest, and so on, until the distance of the cluster surpasses the threshold. 3) Save the candidate cluster with the most points as the first true cluster, and remove all points in the cluster from further consideration. 4) Repeat with the reduced set of points until no more cluster can be formed having the minimum cluster size." (:require [clojure.set :refer [difference]])) (defn candidate-cluster "Determine which members of the dataset are closed to the candidate point within the given threshold" [distance-fn point dataset threshold] (let [too-big? #(> (distance-fn point %) threshold)] (set (remove too-big? dataset)))) (defn most-candidates [distance-fn dataset threshold] "Finds the largest cluster with the most members" (->> dataset (map #(candidate-cluster distance-fn % dataset threshold)) (sort-by count >) first)) (defn cluster "Groups members of supplied dataset into specific clusters according to the provided distance function (this should take 2 collection members and return a scalar difference between them). Candidate clusters are assembled such that the distance of the cluster surpasses the threshold. Further clusters are formed from the remaining points until no more clusters can be formed having the minimum cluster size." [distance-fn dataset threshold min-size] (loop [clusters [] uniq (set dataset)] (let [best (most-candidates distance-fn uniq threshold)] (if (< (count best) min-size) clusters (recur (conj clusters best) (difference uniq best))))))
true
;; The MIT License (MIT) ;; ;; Copyright (c) 2016 PI:NAME:<NAME>END_PI ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in all ;; copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns clustering.core.qt "Quality Threshold (QT) clustering algorithm From: https://sites.google.com/site/dataclusteringalgorithms/quality-threshold-clustering-algorithm-1 1) Initialize the threshold distance allowed for clusters and the minimum cluster size. 2) Build a candidate cluster for each data point by including the closest point, the next closest, and so on, until the distance of the cluster surpasses the threshold. 3) Save the candidate cluster with the most points as the first true cluster, and remove all points in the cluster from further consideration. 4) Repeat with the reduced set of points until no more cluster can be formed having the minimum cluster size." (:require [clojure.set :refer [difference]])) (defn candidate-cluster "Determine which members of the dataset are closed to the candidate point within the given threshold" [distance-fn point dataset threshold] (let [too-big? #(> (distance-fn point %) threshold)] (set (remove too-big? dataset)))) (defn most-candidates [distance-fn dataset threshold] "Finds the largest cluster with the most members" (->> dataset (map #(candidate-cluster distance-fn % dataset threshold)) (sort-by count >) first)) (defn cluster "Groups members of supplied dataset into specific clusters according to the provided distance function (this should take 2 collection members and return a scalar difference between them). Candidate clusters are assembled such that the distance of the cluster surpasses the threshold. Further clusters are formed from the remaining points until no more clusters can be formed having the minimum cluster size." [distance-fn dataset threshold min-size] (loop [clusters [] uniq (set dataset)] (let [best (most-candidates distance-fn uniq threshold)] (if (< (count best) min-size) clusters (recur (conj clusters best) (difference uniq best))))))
[ { "context": " :color \"red\"}]\n; :cursor-colors {\"coby\" \"red\"\n; \"chuck\" \"blue\"\n; ", "end": 172, "score": 0.7892501354217529, "start": 168, "tag": "NAME", "value": "coby" }, { "context": "cursor-colors {\"coby\" \"red\"\n; \"chuck\" \"blue\"\n; \"alex\" \"green\"}\n; ", "end": 207, "score": 0.9195553660392761, "start": 202, "tag": "NAME", "value": "chuck" }, { "context": " \"chuck\" \"blue\"\n; \"alex\" \"green\"}\n; :editables [{:h [:h2 \"Live editing", "end": 242, "score": 0.934039294719696, "start": 238, "tag": "NAME", "value": "alex" } ]
src/thingy/helpers.cljs
acobster/live-proto
0
(ns thingy.helpers) ;(defonce appstate ; (r/atom ; {:selection {} ; :remote-cursors [{:pos [3 1 25] ; :color "red"}] ; :cursor-colors {"coby" "red" ; "chuck" "blue" ; "alex" "green"} ; :editables [{:h [:h2 "Live editing demo"]} ; {:h [:p "Officia corrupti quis consectetur dolore nihil reprehenderit consectetur odio voluptatum."]} ; {:h [:p "Nihil veniam labore animi magna occaecat. Cillum quos et mollit consequat. Assumenda duis est fuga consectetur nostrud lorem ad."]} ; {:h [:h3 "H3 Heading"]} ; {:h [:p "Ad proident distinctio eos quo minim et. Repellendus irure eiusmod eligendi tempor enim nobis fuga."]}]})) ;; ------------------------- ;; Views (defn cursor [c] [:span.cursor {:data-color "green" :style {:color (:color c) :border-color (:color c)}}]) (defn- inject-at [n coll x] (let [[left right] (split-at n coll)] (concat left [x] right))) (defn- element? [x] (and (vector? x) (keyword? (first x)))) (defn- has-attrs-map? [elem] (and (element? elem) (map? (second elem)))) (defn- normalize-attrs [elem] (if (has-attrs-map? elem) elem (vec (inject-at 1 elem {})))) (defn with-cursors [html cursors] (reduce place-cursor html cursors)) (defn make-editable? "Determine whether to make the given element contenteditable or not" [elem] (and (element? elem) (contains? #{:h2 :h3 :p} (first elem)))) (defn make-editable [elem] (vec (assoc-in (normalize-attrs elem) [1 :content-editable] true))) (defn contenteditable [x] (if (make-editable? x) (make-editable x) x)) ;(defn editable [html] ; (with-cursors html (:remote-cursors @appstate))) ; ;(defn home-page [] ; [editable ; (vec (concat [:div.app-containter] (map :h (:editables @appstate))))])
38803
(ns thingy.helpers) ;(defonce appstate ; (r/atom ; {:selection {} ; :remote-cursors [{:pos [3 1 25] ; :color "red"}] ; :cursor-colors {"<NAME>" "red" ; "<NAME>" "blue" ; "<NAME>" "green"} ; :editables [{:h [:h2 "Live editing demo"]} ; {:h [:p "Officia corrupti quis consectetur dolore nihil reprehenderit consectetur odio voluptatum."]} ; {:h [:p "Nihil veniam labore animi magna occaecat. Cillum quos et mollit consequat. Assumenda duis est fuga consectetur nostrud lorem ad."]} ; {:h [:h3 "H3 Heading"]} ; {:h [:p "Ad proident distinctio eos quo minim et. Repellendus irure eiusmod eligendi tempor enim nobis fuga."]}]})) ;; ------------------------- ;; Views (defn cursor [c] [:span.cursor {:data-color "green" :style {:color (:color c) :border-color (:color c)}}]) (defn- inject-at [n coll x] (let [[left right] (split-at n coll)] (concat left [x] right))) (defn- element? [x] (and (vector? x) (keyword? (first x)))) (defn- has-attrs-map? [elem] (and (element? elem) (map? (second elem)))) (defn- normalize-attrs [elem] (if (has-attrs-map? elem) elem (vec (inject-at 1 elem {})))) (defn with-cursors [html cursors] (reduce place-cursor html cursors)) (defn make-editable? "Determine whether to make the given element contenteditable or not" [elem] (and (element? elem) (contains? #{:h2 :h3 :p} (first elem)))) (defn make-editable [elem] (vec (assoc-in (normalize-attrs elem) [1 :content-editable] true))) (defn contenteditable [x] (if (make-editable? x) (make-editable x) x)) ;(defn editable [html] ; (with-cursors html (:remote-cursors @appstate))) ; ;(defn home-page [] ; [editable ; (vec (concat [:div.app-containter] (map :h (:editables @appstate))))])
true
(ns thingy.helpers) ;(defonce appstate ; (r/atom ; {:selection {} ; :remote-cursors [{:pos [3 1 25] ; :color "red"}] ; :cursor-colors {"PI:NAME:<NAME>END_PI" "red" ; "PI:NAME:<NAME>END_PI" "blue" ; "PI:NAME:<NAME>END_PI" "green"} ; :editables [{:h [:h2 "Live editing demo"]} ; {:h [:p "Officia corrupti quis consectetur dolore nihil reprehenderit consectetur odio voluptatum."]} ; {:h [:p "Nihil veniam labore animi magna occaecat. Cillum quos et mollit consequat. Assumenda duis est fuga consectetur nostrud lorem ad."]} ; {:h [:h3 "H3 Heading"]} ; {:h [:p "Ad proident distinctio eos quo minim et. Repellendus irure eiusmod eligendi tempor enim nobis fuga."]}]})) ;; ------------------------- ;; Views (defn cursor [c] [:span.cursor {:data-color "green" :style {:color (:color c) :border-color (:color c)}}]) (defn- inject-at [n coll x] (let [[left right] (split-at n coll)] (concat left [x] right))) (defn- element? [x] (and (vector? x) (keyword? (first x)))) (defn- has-attrs-map? [elem] (and (element? elem) (map? (second elem)))) (defn- normalize-attrs [elem] (if (has-attrs-map? elem) elem (vec (inject-at 1 elem {})))) (defn with-cursors [html cursors] (reduce place-cursor html cursors)) (defn make-editable? "Determine whether to make the given element contenteditable or not" [elem] (and (element? elem) (contains? #{:h2 :h3 :p} (first elem)))) (defn make-editable [elem] (vec (assoc-in (normalize-attrs elem) [1 :content-editable] true))) (defn contenteditable [x] (if (make-editable? x) (make-editable x) x)) ;(defn editable [html] ; (with-cursors html (:remote-cursors @appstate))) ; ;(defn home-page [] ; [editable ; (vec (concat [:div.app-containter] (map :h (:editables @appstate))))])
[ { "context": " ;(eacl/grant! *conn #:eacl{:who [:eacl/ident :jan-hendrik]\n ; :what :invoic", "end": 2355, "score": 0.7232847213745117, "start": 2354, "tag": "USERNAME", "value": "h" }, { "context": "1 :eacl/parent ?p) (child-of ?c ?c1)]]\n; false :jan-hendrik\n; :product/name\n; #{}\n; nil\n; :test-store", "end": 4441, "score": 0.9751977920532227, "start": 4430, "tag": "USERNAME", "value": "jan-hendrik" }, { "context": "le :eacl/what :product/name]\n; [?rule :eacl/who :jan-hendrik]]\n\n(comment\n\n (eacl-fixtures\n (fn []\n ;(", "end": 4666, "score": 0.6731143593788147, "start": 4655, "tag": "USERNAME", "value": "jan-hendrik" }, { "context": " (fn []\n ;(d/transact *conn [{:db/ident :jan-hendrik\n ; :eacl/ident :j", "end": 4751, "score": 0.47290369868278503, "start": 4748, "tag": "NAME", "value": "jan" }, { "context": "(fn []\n ;(d/transact *conn [{:db/ident :jan-hendrik\n ; :eacl/ident :jan", "end": 4753, "score": 0.4024117588996887, "start": 4752, "tag": "USERNAME", "value": "h" }, { "context": "n []\n ;(d/transact *conn [{:db/ident :jan-hendrik\n ; :eacl/ident :jan-he", "end": 4756, "score": 0.4145144820213318, "start": 4753, "tag": "NAME", "value": "end" }, { "context": " \"contact\"\n :contact/full-name \"Jan-Hendrik\"}\n\n {:db/id \"invoices\"\n :e", "end": 9809, "score": 0.9998771548271179, "start": 9798, "tag": "NAME", "value": "Jan-Hendrik" }, { "context": " {:db/id \"user\"\n :eacl/ident :jan-hendrik\n :eacl/parent \"user\" ", "end": 10035, "score": 0.9686700701713562, "start": 10024, "tag": "USERNAME", "value": "jan-hendrik" }, { "context": "eacl/assign-role-at! *conn\n ; [:eacl/ident :jan-hendrik]\n ; [:eacl/ident :role/store-manager] ;; ne", "end": 10872, "score": 0.9893706440925598, "start": 10861, "tag": "USERNAME", "value": "jan-hendrik" }, { "context": "se? (eacl/can? @*conn #:eacl {:who [:eacl/ident :jan-hendrik]\n :what [:", "end": 11295, "score": 0.9899042844772339, "start": 11284, "tag": "USERNAME", "value": "jan-hendrik" }, { "context": "e? (eacl/can? @*conn #:eacl {:who [:eacl/ident :jan-hendrik]\n :what [", "end": 11680, "score": 0.9905261993408203, "start": 11669, "tag": "USERNAME", "value": "jan-hendrik" }, { "context": "s (eacl/grant! *conn #:eacl {:who [:eacl/ident :jan-hendrik]\n ; :what :invoic", "end": 11929, "score": 0.991246223449707, "start": 11918, "tag": "USERNAME", "value": "jan-hendrik" }, { "context": "e? (eacl/can? @*conn #:eacl {:who [:eacl/ident :jan-hendrik]\n :what", "end": 12687, "score": 0.6827311515808105, "start": 12679, "tag": "USERNAME", "value": "jan-hend" }, { "context": "/can? @*conn #:eacl {:who [:eacl/ident :jan-hendrik]\n :what [", "end": 12690, "score": 0.495124489068985, "start": 12687, "tag": "NAME", "value": "rik" }, { "context": "s (eacl/grant! *conn #:eacl {:who [:eacl/ident :jan-hendrik]\n :what", "end": 13247, "score": 0.5455406904220581, "start": 13244, "tag": "NAME", "value": "jan" }, { "context": "eacl/grant! *conn #:eacl {:who [:eacl/ident :jan-hendrik]\n :what ", "end": 13249, "score": 0.7367417812347412, "start": 13248, "tag": "USERNAME", "value": "h" }, { "context": "cl/grant! *conn #:eacl {:who [:eacl/ident :jan-hendrik]\n :what [:invo", "end": 13255, "score": 0.5748015642166138, "start": 13249, "tag": "NAME", "value": "endrik" }, { "context": " ;(eacl/grant! *conn #:eacl {:who [:eacl/ident :jan-hendrik]\n ; :where [:eacl/iden", "end": 17007, "score": 0.5510643124580383, "start": 16996, "tag": "NAME", "value": "jan-hendrik" }, { "context": "*conn\n #:eacl {:who [:eacl/ident :jan-hendrik]\n :what :invoice/n", "end": 17324, "score": 0.4343162775039673, "start": 17321, "tag": "NAME", "value": "jan" }, { "context": " #:eacl {:who [:eacl/ident :jan-hendrik]\n :what :invoice/number ", "end": 17332, "score": 0.46690747141838074, "start": 17329, "tag": "NAME", "value": "rik" }, { "context": "\n; (let [notify-rule #:eacl{:who [:db/ident :jan-hendrik]\n; :where [:db/ident ", "end": 21421, "score": 0.9972071647644043, "start": 21410, "tag": "USERNAME", "value": "jan-hendrik" }, { "context": " admin (eacl/create-user! conn {:user/name \"Test User\"})\n; invoices (eacl/create-entity! conn {:ea", "end": 27421, "score": 0.9994707107543945, "start": 27412, "tag": "USERNAME", "value": "Test User" }, { "context": " user (eacl/create-user! conn {:user/name \"Petrus Theron\"})]\n; (eacl/grant-access! conn {:eacl/user use", "end": 29005, "score": 0.9998140335083008, "start": 28992, "tag": "NAME", "value": "Petrus Theron" } ]
test/eacl/core_test.clj
theronic/clj-eacl
36
(ns eacl.core-test (:require ;[bridge.utils :refer [spy profile]] [clojure.test :as t :refer (deftest is testing)] [taoensso.timbre :as log] [eacl.core :as eacl] [eacl.data.schema :as schema] [datahike.api :as d] [datahike.core :as dc] [clojure.spec.test.alpha :as st])) ;[bridge.fixtures.common-fixtures :as f :refer (*conn *db)] ;[bridge.fixtures.catalog-fixtures :as cf] ;[bridge.fixtures.auth-fixtures :as af] ;[bridge.fixtures.auth-fixtures :as fa])) (def n-iterations 150) ;; was 100000. belongs under perf/benchmark tests. (def ^:dynamic *conn nil) (defn create-mem-conn [& [tx-initial]] (let [cfg-mem {:store {:backend :mem :id (str 123)}}] ;(str (rand-int 1000))}}] ;(nano/nano-id)}}] (d/create-database cfg-mem :tx-initial tx-initial) (let [conn (d/connect cfg-mem)] (when tx-initial (d/transact conn tx-initial)) conn))) (defn conn-fixture [test-fn] (st/instrument) (let [conn (create-mem-conn schema/v1-eacl-schema)] ;(mount/start-with {#'bridge.data.datahike/conn conn}) (with-bindings {#'*conn conn} (test-fn)) ;; should we call destroy here? (d/release conn) ;(mount/stop) ;; hmm (st/unstrument) true)) (defn eacl-fixtures [test-fn] (assert *conn) (d/transact *conn schema/v1-eacl-schema) (d/transact *conn [{:db/ident :contact/full-name :db/valueType :db.type/string :db/cardinality :db.cardinality/one} {:db/ident :user/contact :db/valueType :db.type/ref :db/cardinality :db.cardinality/one} {:db/ident :invoice/number :db/valueType :db.type/string :db/unique :db.unique/identity :db/cardinality :db.cardinality/one}]) ;(let [conn (->> {:db/ident :invoice/number ; :db/valueType :db.type/string ; :db/unique :db.unique/identity ; :db/cardinality :db.cardinality/one} ; (conj schema/v1-eacl-schema) ; (d/create-mem-conn))]) (d/transact *conn [{:db/ident :invoices :eacl/ident :invoices}]) ;(eacl/grant! *conn #:eacl{:who [:eacl/ident :jan-hendrik] ; :what :invoice/number}) (time (d/transact *conn (vec (for [inv-num (range 1 (inc n-iterations))] {:db/id (- inv-num) :invoice/number (str "INV" inv-num) :eacl/parent [:eacl/ident :invoices]})))) (d/transact *conn [{:db/id [:eacl/ident :invoices] :eacl/path "invoices" :eacl/ident :invoices} {:db/id -2 :db/ident :petrus}]) ;(with-bindings {#'*conn conn}) (test-fn)) ;(d/release *conn)) ;(deftest fixture-sanity ; (testing "can transact fixtures against empty-db" ; (eacl-fixtures (fn [])))) ;(d/transact (d/empty-db) eacl-fixtures))) (comment (mount.core/start)) ;; hmm yeah it would be good to not rely on any bridge schema. (t/use-fixtures :each conn-fixture eacl-fixtures) ;fa/auth-fixtures) ; eacl-fixtures) ;(t/use-fixtures :each f/conn-fixture af/auth-fixtures cf/catalog-fixtures eacl-fixtures) ;(clojure.test/use-fixtures my-fixtures) ;(doseq [inv-num (range n-iterations)] ; (d/transact conn {:invoice/number inv-num ; :eacl/parent [:eacl/ident :invoices]})) ;(deftest grant-deny) ;(let [conn (d/create-mem-conn (conj schema/v1-eacl-schema {:db/ident :invoice/number ; :db/valueType :db.type/string ; :db/unique :db.unique/identity ; :db/cardinality :db.cardinality/one}))])) ;(eacl/grant! conn #:eacl{:who :petrus ; :what :invoices ; :how :read}))) (def crud #{:create :read :update :delete}) ;'{:find [(pull ?rule [*])], ; :in [$ % ?allow ?who ?what ?why ?when ?where ?how], ; :where [[?rule :eacl/allowed? ?allow] [?rule :eacl/who ?who] [?rule :eacl/what ?what] [?rule :eacl/where ?where] [?rule :eacl/how ?how]] ; ([[(child-of ?c ?p) (?c :eacl/parent ?p)] [(child-of ?c ?p) (?c1 :eacl/parent ?p) (child-of ?c ?c1)]] ; false :jan-hendrik ; :product/name ; #{} ; nil ; :test-store ; :create)} ;'[:find ?rule ; :where ; [?rule :eacl/allowed? true] ; [?rule :eacl/where :test-store] ; [?rule :eacl/what :product/name] ; [?rule :eacl/who :jan-hendrik]] (comment (eacl-fixtures (fn [] ;(d/transact *conn [{:db/ident :jan-hendrik ; :eacl/ident :jan-hendrik} ; {:eacl/ident :test-store} ; {:db/ident :product/name}]) (let [rule {:eacl/who [:eacl/ident :jan-hendrik] :eacl/what [:db/ident :product/name] :eacl/where [:eacl/ident :test-store] :eacl/how :create}] (eacl/grant! *conn rule) (let [db (d/db *conn)] (log/warn "TEST" (d/q '[:find ?rule :in $ ?who :where [?rule :eacl/allowed? true] [?rule :eacl/where :test-store] [?rule :eacl/what :product/name] [?rule :eacl/who ?who]] (d/db *conn) [:db/ident :jan-hendrik])) ;(let [{:eacl/keys [who what why when where how]} demand] ; (log/warn "CUSTOM" (into [] (d/q ; (eacl/build-rule-query demand) ; (d/db *conn) eacl/child-rules ; true [:db/ident :jan-hendrik])))) ;(or who #{}))))) ;(or what #{}) ;(or why #{}) ;(or when #{}) ;(or where #{}) ;(or how #{}))))) (log/warn (eacl/can? db rule))))))) (deftest sanity-tests (testing "can? doesn't blow up" (let [db (d/db-with (dc/empty-db) schema/v1-eacl-schema)] (is (false? (eacl/can? db #:eacl{:who [:eacl/ident :me] :what [:eacl/ident :thing] :where [:eacl/ident :anywhere] :how :read})))))) ;[:eacl/ident :read]}))))) (comment (eacl/can? @*conn {:eacl/who [:eacl/ident :alex] :eacl/how :read :eacl/read [:docket/number 567] :eacl/where #inst "2000-05-05"})) ;(defn create-order! [db order-number lines] ; (eacl/can! db {:eacl/who :alex ; :eacl/what :order/number ; :eacl/how :create ; :eacl/when (t/now) ; :eacl/why ""})) (deftest recursion-tests (testing "that child inherits parent's rules" (is (d/transact *conn [{:db/id -1 :eacl/ident :alice} {:db/id -2 :eacl/ident :bob}])) (d/transact *conn [[:db/add [:db/ident :invoice/number] :eacl/parent [:db/ident :invoice/number]]]) ;; required for most queries to work. Big todo. (is (eacl/create-role! *conn {:db/ident :manager})) (is (false? (eacl/can? @*conn #:eacl {:who [:db/ident :manager] :what [:db/ident :invoice/number] :how :read}))) (is (eacl/grant! *conn #:eacl {:who [:db/ident :manager] :what [:db/ident :invoice/number] :how :read})) (is (true? (eacl/can? @*conn #:eacl {:who [:db/ident :manager] :what [:db/ident :invoice/number] :how :read}))))) ;(is (true? (eacl/can? @*conn #:eacl {:who [:db/ident :manager] ; :what [:db/ident :invoice/number] ; :how :read}))) ;(d/transact *conn [[:db/ident :alice] :eacl/parent [:db/ident :manager]]) ;(eacl/can? @*conn #:eacl {:who [:db/ident :alice]}))) ;(eacl/assign-role-at!) ;(eacl/grant! *conn #:eacl {:who [:db/ident]}))) (deftest store-rules (is (d/transact *conn [{:db/ident :product/name :db/valueType :db.type/string :db/cardinality :db.cardinality/one} {:db/ident :store/name :db/valueType :db.type/string :db/cardinality :db.cardinality/one} {:db/ident :invoice/number :db/valueType :db.type/string :db/unique :db.unique/identity} {:db/ident :invoice/total :db/valueType :db.type/bigdec :db/cardinality :db.cardinality/one :db/index true} {:db/ident :contact/name :db/valueType :db.type/string :db/cardinality :db.cardinality/one}])) ;(d/transact *conn [{:db/id "role" ; :eacl/ident :role/store-manager ; :eacl/role "role"}]) (is (d/transact *conn [{:db/id "store" :eacl/ident :test-store :eacl/parent "store" ;; required :eacl/role "store" ;; required :store/name "Ancestral Nourishment Store"} {:db/id "contact" :contact/full-name "Jan-Hendrik"} {:db/id "invoices" :eacl/parent "invoices" ;; NB MUST BE OWN PARENT. :eacl/ident :invoices} {:db/id "user" :eacl/ident :jan-hendrik :eacl/parent "user" ;; hack :eacl/role "user" ;; hack :user/contact "contact"}])) (prn "write invoices:") (time (d/transact *conn (vec (for [inv-num (range 1 (inc n-iterations))] {:db/id (- inv-num) :invoice/number (str "INV" inv-num) :eacl/parent [:eacl/ident :invoices]})))) (prn "invoices:" (d/q '[:find ?num :where [?inv :invoice/number ?num]] @*conn)) ;(is (d/transact *conn [{:invoice/number "INV123" ; :eacl/parent [:db/ident :invoice/number] ; :invoice/total 123.45M}])) (is (eacl/create-role! *conn {:eacl/ident :role/store-manager})) ;(is (eacl/assign-role-at! *conn ; [:eacl/ident :jan-hendrik] ; [:eacl/ident :role/store-manager] ;; need some sugar here. ; [:eacl/ident :test-store])) (is (d/transact *conn [{:invoice/number "INV123" ;; will complain :invoice/total 123.45M :eacl/parent [:eacl/ident :invoices]}])) ;:eacl/parent [:eacl/ident :test-store]}])) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :jan-hendrik] :what [:invoice/number "INV123"]}))) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :jan-hendrik] :what [:db/ident :invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) ;(is (eacl/grant! *conn #:eacl {:who [:eacl/ident :jan-hendrik] ; :what :invoice/number ;[:invoice/number "INV123"] ; :where [:eacl/ident :test-store]})) (is (eacl/grant! *conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:eacl/ident :invoices] ;:invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]})) (is (true? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:eacl/ident :invoices] ;:invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :jan-hendrik] :what [:eacl/ident :invoices] ;:invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) ;(is (eacl/grant! *conn #:eacl {:who [:eacl/ident :role/store-manager] ; :what :invoices ;[:invoice/number "INV123"] ; :where [:eacl/ident :test-store]})) (testing "give test user fine-grained access to a particular invoice" (is (eacl/grant! *conn #:eacl {:who [:eacl/ident :jan-hendrik] :what [:invoice/number "INV123"] ;[:eacl/ident :invoices] ;/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (testing "we can retrieve the grant just issued" (let [[allowed? rule] (first (d/q '[:find ?allowed (pull ?rule [* {:eacl/who [:eacl/ident] :eacl/what [:eacl/ident :invoice/number] :eacl/where [:eacl/ident]}]) :in $ ?who :where [?rule :eacl/who ?who] [?rule :eacl/allowed? ?allowed]] @*conn [:eacl/ident :jan-hendrik]))] (is (= true allowed?)))) ;(is (d/transact *conn [[:db/add [:invoice/number "INV123"] :eacl/parent :invoice/number]])) (prn "xxx HERE") ;(d/q '[:find ?rule ; :where ; [?rule :eacl/who [:eacl/ident :jan-hendrik]]]) (testing "previous grant! has taken effect" ;; why is this not working? (is (true? (eacl/can? @*conn #:eacl{:who [:eacl/ident :jan-hendrik] :what [:invoice/number "INV123"] ;; todo inherit place. :where [:eacl/ident :test-store]})))) (is (eacl/deny! *conn #:eacl {:who [:eacl/ident :jan-hendrik] :what [:invoice/number "INV123"] ;; todo inherit place. :where [:eacl/ident :test-store]})) ;; why isn't deny working? (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :jan-hendrik] :what [:invoice/number "INV123"] ;; todo inherit place. :where [:eacl/ident :test-store]}))) (prn "Manager: " (d/pull @*conn '[*] [:eacl/ident :role/store-manager])) (prn (d/pull @*conn '[*] [:eacl/ident :jan-hendrik])) (d/transact *conn [[:db/add [:db/ident :invoice/number] :eacl/parent [:eacl/ident :invoices]]]) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:db/ident :eacl/who] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (is (true? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:db/ident :invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (is (eacl/grant! *conn #:eacl {:who [:eacl/ident :role/store-manager] :what :invoice/number ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]})) (is (true? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:db/ident :invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (is (eacl/deny! *conn #:eacl {:who [:eacl/ident :role/store-manager] :what :invoice/number ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]})) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:db/ident :invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) ;(eacl/grant! *conn #:eacl {:who [:eacl/ident :jan-hendrik] ; :where [:eacl/ident :test-store] ; :what [:invoice/number "INV123"]}) (d/transact *conn [[:db/add [:eacl/ident :jan-hendrik] :eacl/parent [:eacl/ident :role/store-manager]]]) (is (true? (eacl/can? @*conn #:eacl {:who [:eacl/ident :jan-hendrik] :what :invoice/number ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) ;(eacl) (is (d/transact *conn [{:db/ident :event/key :db/doc "Event keyword to trigger subscription notifications." :db/valueType :db.type/keyword :db/unique :db.unique/identity :db/cardinality :db.cardinality/one}])) ;; subscribe vs grant? ;; Todo: use EACL to validate itself for e.g. granting new rules. (is (eacl/grant! *conn #:eacl{;:when {:event/key :event/new-order} ;; inheritance :who [:eacl/ident :role/store-manager] ;; vs. view vs. see? ;; todo: support '1 year' from now for times. :how :read ;; :notify? all aspects? what about children of the store? ;; Todo: think about how to support arbitrary queries in :what. Maybe call it query for subs. ;:what '[*] ;; hmm not valid. how to implement this? :where [:eacl/ident :test-store] ;; better name :why :email/notification})) ;; how to mix (is (eacl/enum-event-triggers @*conn :event/new-order)) ;; is EACL the right place for this kind of topic subscription? (let [test-rule #:eacl{:who [:eacl/ident :jan-hendrik] ;[:db/ident :jan-hendrik] :what [:db/ident :product/name] :where [:eacl/ident :test-store] ;[:db/ident :test-store] :how :create}] (eacl/grant! *conn test-rule) ;; how can we enum all the rules for this user? (let [db @*conn user-rules (eacl/enum-user-rules db [:eacl/ident :jan-hendrik]) jan (d/entity db [:eacl/ident :jan-hendrik])] (log/debug "User rules:" user-rules) ;; need some jigs to test entity equality. ;; do pulls return entities? (let [rule1 (ffirst user-rules)] (is (= (:db/id (first (:eacl/who rule1)) (:db/id jan)))))) ; (is (= (:eacl/who rule1) {:eacl/who [:eacl/ident :jan-hendrik]})))) (is (true? (eacl/can? (d/db *conn) test-rule))))) (deftest notify-tests (testing "who can?" (let [db @*conn] (log/debug "Who:" (eacl/who-can? db #:eacl{:who '?who :what [:db/ident :product/name] :where [:eacl/ident :test-store] :how :create}))))) ;(deftest can?-multi-arity ;; how should this work? ; (is (true? (eacl/can? (d/db *conn) ; #:eacl{:who #{[:db/ident :jan-hendrik]} ;[:db/ident :jan-hendrik] ; :what [:db/ident :product/name] ; :where [:db/ident :test-store] ;[:db/ident :test-store] ; :how :create})))) ;; what's the simplest thing that can work for notifications? ;; assign store roles. Well basically that's what a rule is. ;; We just need to match the what and the where. ;(deftest notify-tests ; (testing "who can?" ; (let [db @*conn] ; (is (eacl/who-can? db {})))) ; ; (testing "can we use EACL roles for notifications?" ; ;; generalised subscriptions? coz well, if someone edits something, we know right. ; ;; Need differential dataflow here. ; ; ;; what should notification API look like? Basically we are subscribing to entities with an :sales-order/number + user has a certain right at :sales-order/store. ; ;; could we design rule queries that they are unified? ; ;; in this case it's basically `?order :sales-order/store ?store` for any ?order but limited ?store. ; ;; Can we use Datomic listeners for this + filter? ; ; ;; why vs how for order notifications? ; ; (let [notify-rule #:eacl{:who [:db/ident :jan-hendrik] ; :where [:db/ident :test-store] ; :why :notify/new-order ; :how '[*] ;; hmm any attribute. Would be cool if this qorks as expected. ; ;; can what be new incoming orders? ; ;; can :what be a recursive pull for the order we care about? ; :what :sales-order/number}] ; (eacl/grant! *conn notify-rule) ; (let [db @*conn] ; (is (not (eacl/can? db (dissoc notify-rule :eacl/who)))) ; (is (not (eacl/can? db (assoc notify-rule :eacl/who [:db/ident :petrus])))) ; (is (eacl/can? db notify-rule)))) ; ; ;'[:find (pull ?order [*]) ; ; :where ; ; [?order :sales-order/number ?number ; ; ?order :sales-order/store ?store ; ; ;; we have to name these order notification. ; ; ?rule :eacl/what ?order ;; :sales-order/number ;; hmm. ; ; ?rule :eacl/where ?store ; ; ?rule :eacl/allowed? true ; ; ?rule :eacl/who ?who]] ; (let [group (eacl/create-group! *conn {:group/name "Test"}) ; db @*conn ; rule #:eacl{:how :notify/order-placed ;[:db/ident :test-store] ; ;; note the absence of ?who. ; ;; hmm, can we use datomic listener + filter here? No, has to be indexed queryable. ; :what [:db/ident :test-store]}]) ; ;(eacl/enum-who-can db rule)) ; ;(eacl/who-can? db)) ; ;(eacl/can? @*conn #:eacl{:who ?who ; ; :what [:db/ident :test-store] ; ; :where [] ; ; ;; hmm, could :why be the answer here? ; ; :how :notify/order-placed})) ; ())) ;(deftest enum-tests ; (d/transact *conn ; [{:db/id -1 ; :eacl/path "invoices" ; :eacl/ident :invoices} ; {:db/id -2 ; :db/ident :petrus}]) ; ; (time ; (d/transact *conn ; (vec (for [inv-num (range 1 (inc n-iterations))] ; {:db/id (- inv-num) ; :invoice/number (str "INV" inv-num) ; :eacl/parent [:eacl/ident :invoices]})))) ; ; (is (empty? (log/debug "Enum 1:" (eacl/enum-user-rules (d/db *conn) [:db/ident :petrus])))) ; ; ;(comment ; ; (let [conn (d/create-mem-conn (conj schema/v1-eacl-schema {:db/ident :invoice/number ; ; :db/valueType :db.type/string ; ; :db/unique :db.unique/identity ; ; :db/cardinality :db.cardinality/one})) ; ; rule {:eacl/who [:db/ident :petrus] ; ; :eacl/what [:eacl/ident :invoices] ; ; ;:eacl/where [:eacl/ident :invoices] ;;temp ; ; :eacl/how :read}] ; ; (d/transact conn (eacl/tx-rule true rule)))) ; ; (let [rule {:eacl/who [:db/ident :petrus] ; :eacl/what [:eacl/ident :invoices] ; :eacl/how :read}] ; (d/transact *conn [{:db/id -1 ; :eacl/parent -1 ;; own parent ; :db/ident :petrus} ; {:db/id -2 ; :eacl/ident :invoices ; :eacl/parent -2}]) ; ; ;(eacl/tx-rule true rule) ; ; (is (false? (eacl/can? (d/db *conn) rule))) ; (eacl/grant! *conn rule) ; (log/debug "Enum 2:" (eacl/enum-user-rules (d/db *conn) [:db/ident :petrus])) ; (is (= 1 (count (eacl/enum-user-rules (d/db *conn) [:db/ident :petrus])))) ; ;;(log/debug "Enum 2:" (eacl/enum-user-permissions @conn (:db/id who))) ; (log/debug "qry:" (eacl/build-rule-query rule)) ; (is (true? (eacl/can? (d/db *conn) rule))) ; ; (eacl/deny! *conn rule) ; (is (false? (time (eacl/can? (d/db *conn) rule)))) ; ; ;; Thinking about rule inheritance: ; ;; 1. Specific overrides general rules. ; ;; 2. Given a tie, deny overrules allow. ; ;; 3. How can we use rules prospectively to see if a transaction will trigger any rules? ; ; (eacl/grant! *conn rule) ;; should this complain about a conflicting rule, or should it override the deny-rule? ; (is (true? (eacl/can? (d/db *conn) rule))))) ;(is (false? (eacl/can? (d/db conn) {:db/})))))) ;(is (false? (eacl/can? (d/db conn))))))) ; (:db/id invoices)})))) ;; ; ; (let [db @conn] ; (is (false? (eacl/can? db {:eacl/who who ;(:db/id user) ; :eacl/what what ; :eacl/how :read}))) ; (:db/id invoices)})))) ; (eacl/grant! conn {:eacl/who who ; :eacl/what what ; :eacl/how :read}) ; ; (log/debug "Enum 2:" (eacl/enum-user-permissions @conn (:db/id who))) ; (is (true? (eacl/can? @conn {:eacl/user who ; (:db/id user) ; :eacl/action :read ; :eacl/resource what}))) ; (:db/id invoices)})))))) ; (eacl/deny! conn {:eacl/who who ; :eacl/what what ; :eacl/how :read}) ; (eacl/grant! conn {:eacl/who who ; :eacl/what what ; :eacl/how :write}) ; (log/debug "Enum 3:" (eacl/enum-user-permissions @conn (:db/id who))) ; (let [db1 @conn] ; (is (false? (eacl/can? db1 {:eacl/who who ; :eacl/what what ; :eacl/how :read}))) ; (is (true? (eacl/can? db1 {:eacl/who who ; :eacl/what what ; :eacl/how :write}))))))) (comment) ;(clojure.test/run-tests (enum-tests)) ;(let [conn (d/create-mem-conn schema/latest-schema) ; admin (eacl/create-user! conn {:user/name "Test User"}) ; invoices (eacl/create-entity! conn {:eacl/path "invoices"})] ; ; (eacl/grant! conn ; {:eacl/who admin ; :eacl/how :read ; :eacl/what invoices}) ; ; (eacl/deny! conn ; {:eacl/who admin ; :eacl/action :write ; :eacl/what invoices}) ; ; (d/q '[:find ?perm ; (pull ?user [*]) ; ?action ; (pull ?resource [*]) ; (pull ?group [*]) ; (pull ?perm [*]) ; :in ; $ % ; ?user ?action ?resource ;; how to handle group? ; :where ; [?perm :eacl/group ?group] ;; not sure ; [?perm :eacl/resource ?resource] ; [?perm :eacl/how :read] ; :read] ; [?perm :eacl/allowed? true] ; true] ; (not [?perm :eacl/allowed? false]) ;; /blocked? ; (child-of ?user ?group)] ; @conn ; eacl/child-rules ; (:db/id admin) :read (:db/id invoices)))) ;(d/q '[:find ; (pull ?user [*]) ; ?allowed ; ?action ; (pull ?resource [*]) ; (pull ?group [*]) ; (pull ?perm [*]) ; :in $ % ; :where ; ;[?perm :eacl/user ?user] ; [?perm :eacl/resource ?resource] ; [?perm :eacl/allowed? ?allowed] ; [?perm :eacl/action ?action] ; (child-of ?user ?group)] ; @conn ; eacl/child-rules))) ;(deftest eacl-tests ; (let [conn eacl/conn ;; eww ; invoices (eacl/create-entity! conn {:eacl/ident "invoices"}) ; user (eacl/create-user! conn {:user/name "Petrus Theron"})] ; (eacl/grant-access! conn {:eacl/user user ; :eacl/resource (:db/id invoices) ; ;:eacl/path "invoices/*" ; :eacl/action :read}) ; (log/debug "enum:" (eacl/enum-user-permissions @conn user)) ; (is (true? (eacl/can-user? @conn {:eacl/user user ; :eacl/resource (:db/id invoices) ; ;:eacl/path "invoices/*" ;; hmm ; ;:eacl/location "Cape Town" ; :eacl/action :read}))))) (comment (clojure.test/run-tests)) ;(enum-tests) ;(enum) ;(clojure.test/) ;(clojure.test/run-tests)
70337
(ns eacl.core-test (:require ;[bridge.utils :refer [spy profile]] [clojure.test :as t :refer (deftest is testing)] [taoensso.timbre :as log] [eacl.core :as eacl] [eacl.data.schema :as schema] [datahike.api :as d] [datahike.core :as dc] [clojure.spec.test.alpha :as st])) ;[bridge.fixtures.common-fixtures :as f :refer (*conn *db)] ;[bridge.fixtures.catalog-fixtures :as cf] ;[bridge.fixtures.auth-fixtures :as af] ;[bridge.fixtures.auth-fixtures :as fa])) (def n-iterations 150) ;; was 100000. belongs under perf/benchmark tests. (def ^:dynamic *conn nil) (defn create-mem-conn [& [tx-initial]] (let [cfg-mem {:store {:backend :mem :id (str 123)}}] ;(str (rand-int 1000))}}] ;(nano/nano-id)}}] (d/create-database cfg-mem :tx-initial tx-initial) (let [conn (d/connect cfg-mem)] (when tx-initial (d/transact conn tx-initial)) conn))) (defn conn-fixture [test-fn] (st/instrument) (let [conn (create-mem-conn schema/v1-eacl-schema)] ;(mount/start-with {#'bridge.data.datahike/conn conn}) (with-bindings {#'*conn conn} (test-fn)) ;; should we call destroy here? (d/release conn) ;(mount/stop) ;; hmm (st/unstrument) true)) (defn eacl-fixtures [test-fn] (assert *conn) (d/transact *conn schema/v1-eacl-schema) (d/transact *conn [{:db/ident :contact/full-name :db/valueType :db.type/string :db/cardinality :db.cardinality/one} {:db/ident :user/contact :db/valueType :db.type/ref :db/cardinality :db.cardinality/one} {:db/ident :invoice/number :db/valueType :db.type/string :db/unique :db.unique/identity :db/cardinality :db.cardinality/one}]) ;(let [conn (->> {:db/ident :invoice/number ; :db/valueType :db.type/string ; :db/unique :db.unique/identity ; :db/cardinality :db.cardinality/one} ; (conj schema/v1-eacl-schema) ; (d/create-mem-conn))]) (d/transact *conn [{:db/ident :invoices :eacl/ident :invoices}]) ;(eacl/grant! *conn #:eacl{:who [:eacl/ident :jan-hendrik] ; :what :invoice/number}) (time (d/transact *conn (vec (for [inv-num (range 1 (inc n-iterations))] {:db/id (- inv-num) :invoice/number (str "INV" inv-num) :eacl/parent [:eacl/ident :invoices]})))) (d/transact *conn [{:db/id [:eacl/ident :invoices] :eacl/path "invoices" :eacl/ident :invoices} {:db/id -2 :db/ident :petrus}]) ;(with-bindings {#'*conn conn}) (test-fn)) ;(d/release *conn)) ;(deftest fixture-sanity ; (testing "can transact fixtures against empty-db" ; (eacl-fixtures (fn [])))) ;(d/transact (d/empty-db) eacl-fixtures))) (comment (mount.core/start)) ;; hmm yeah it would be good to not rely on any bridge schema. (t/use-fixtures :each conn-fixture eacl-fixtures) ;fa/auth-fixtures) ; eacl-fixtures) ;(t/use-fixtures :each f/conn-fixture af/auth-fixtures cf/catalog-fixtures eacl-fixtures) ;(clojure.test/use-fixtures my-fixtures) ;(doseq [inv-num (range n-iterations)] ; (d/transact conn {:invoice/number inv-num ; :eacl/parent [:eacl/ident :invoices]})) ;(deftest grant-deny) ;(let [conn (d/create-mem-conn (conj schema/v1-eacl-schema {:db/ident :invoice/number ; :db/valueType :db.type/string ; :db/unique :db.unique/identity ; :db/cardinality :db.cardinality/one}))])) ;(eacl/grant! conn #:eacl{:who :petrus ; :what :invoices ; :how :read}))) (def crud #{:create :read :update :delete}) ;'{:find [(pull ?rule [*])], ; :in [$ % ?allow ?who ?what ?why ?when ?where ?how], ; :where [[?rule :eacl/allowed? ?allow] [?rule :eacl/who ?who] [?rule :eacl/what ?what] [?rule :eacl/where ?where] [?rule :eacl/how ?how]] ; ([[(child-of ?c ?p) (?c :eacl/parent ?p)] [(child-of ?c ?p) (?c1 :eacl/parent ?p) (child-of ?c ?c1)]] ; false :jan-hendrik ; :product/name ; #{} ; nil ; :test-store ; :create)} ;'[:find ?rule ; :where ; [?rule :eacl/allowed? true] ; [?rule :eacl/where :test-store] ; [?rule :eacl/what :product/name] ; [?rule :eacl/who :jan-hendrik]] (comment (eacl-fixtures (fn [] ;(d/transact *conn [{:db/ident :<NAME>-h<NAME>rik ; :eacl/ident :jan-hendrik} ; {:eacl/ident :test-store} ; {:db/ident :product/name}]) (let [rule {:eacl/who [:eacl/ident :jan-hendrik] :eacl/what [:db/ident :product/name] :eacl/where [:eacl/ident :test-store] :eacl/how :create}] (eacl/grant! *conn rule) (let [db (d/db *conn)] (log/warn "TEST" (d/q '[:find ?rule :in $ ?who :where [?rule :eacl/allowed? true] [?rule :eacl/where :test-store] [?rule :eacl/what :product/name] [?rule :eacl/who ?who]] (d/db *conn) [:db/ident :jan-hendrik])) ;(let [{:eacl/keys [who what why when where how]} demand] ; (log/warn "CUSTOM" (into [] (d/q ; (eacl/build-rule-query demand) ; (d/db *conn) eacl/child-rules ; true [:db/ident :jan-hendrik])))) ;(or who #{}))))) ;(or what #{}) ;(or why #{}) ;(or when #{}) ;(or where #{}) ;(or how #{}))))) (log/warn (eacl/can? db rule))))))) (deftest sanity-tests (testing "can? doesn't blow up" (let [db (d/db-with (dc/empty-db) schema/v1-eacl-schema)] (is (false? (eacl/can? db #:eacl{:who [:eacl/ident :me] :what [:eacl/ident :thing] :where [:eacl/ident :anywhere] :how :read})))))) ;[:eacl/ident :read]}))))) (comment (eacl/can? @*conn {:eacl/who [:eacl/ident :alex] :eacl/how :read :eacl/read [:docket/number 567] :eacl/where #inst "2000-05-05"})) ;(defn create-order! [db order-number lines] ; (eacl/can! db {:eacl/who :alex ; :eacl/what :order/number ; :eacl/how :create ; :eacl/when (t/now) ; :eacl/why ""})) (deftest recursion-tests (testing "that child inherits parent's rules" (is (d/transact *conn [{:db/id -1 :eacl/ident :alice} {:db/id -2 :eacl/ident :bob}])) (d/transact *conn [[:db/add [:db/ident :invoice/number] :eacl/parent [:db/ident :invoice/number]]]) ;; required for most queries to work. Big todo. (is (eacl/create-role! *conn {:db/ident :manager})) (is (false? (eacl/can? @*conn #:eacl {:who [:db/ident :manager] :what [:db/ident :invoice/number] :how :read}))) (is (eacl/grant! *conn #:eacl {:who [:db/ident :manager] :what [:db/ident :invoice/number] :how :read})) (is (true? (eacl/can? @*conn #:eacl {:who [:db/ident :manager] :what [:db/ident :invoice/number] :how :read}))))) ;(is (true? (eacl/can? @*conn #:eacl {:who [:db/ident :manager] ; :what [:db/ident :invoice/number] ; :how :read}))) ;(d/transact *conn [[:db/ident :alice] :eacl/parent [:db/ident :manager]]) ;(eacl/can? @*conn #:eacl {:who [:db/ident :alice]}))) ;(eacl/assign-role-at!) ;(eacl/grant! *conn #:eacl {:who [:db/ident]}))) (deftest store-rules (is (d/transact *conn [{:db/ident :product/name :db/valueType :db.type/string :db/cardinality :db.cardinality/one} {:db/ident :store/name :db/valueType :db.type/string :db/cardinality :db.cardinality/one} {:db/ident :invoice/number :db/valueType :db.type/string :db/unique :db.unique/identity} {:db/ident :invoice/total :db/valueType :db.type/bigdec :db/cardinality :db.cardinality/one :db/index true} {:db/ident :contact/name :db/valueType :db.type/string :db/cardinality :db.cardinality/one}])) ;(d/transact *conn [{:db/id "role" ; :eacl/ident :role/store-manager ; :eacl/role "role"}]) (is (d/transact *conn [{:db/id "store" :eacl/ident :test-store :eacl/parent "store" ;; required :eacl/role "store" ;; required :store/name "Ancestral Nourishment Store"} {:db/id "contact" :contact/full-name "<NAME>"} {:db/id "invoices" :eacl/parent "invoices" ;; NB MUST BE OWN PARENT. :eacl/ident :invoices} {:db/id "user" :eacl/ident :jan-hendrik :eacl/parent "user" ;; hack :eacl/role "user" ;; hack :user/contact "contact"}])) (prn "write invoices:") (time (d/transact *conn (vec (for [inv-num (range 1 (inc n-iterations))] {:db/id (- inv-num) :invoice/number (str "INV" inv-num) :eacl/parent [:eacl/ident :invoices]})))) (prn "invoices:" (d/q '[:find ?num :where [?inv :invoice/number ?num]] @*conn)) ;(is (d/transact *conn [{:invoice/number "INV123" ; :eacl/parent [:db/ident :invoice/number] ; :invoice/total 123.45M}])) (is (eacl/create-role! *conn {:eacl/ident :role/store-manager})) ;(is (eacl/assign-role-at! *conn ; [:eacl/ident :jan-hendrik] ; [:eacl/ident :role/store-manager] ;; need some sugar here. ; [:eacl/ident :test-store])) (is (d/transact *conn [{:invoice/number "INV123" ;; will complain :invoice/total 123.45M :eacl/parent [:eacl/ident :invoices]}])) ;:eacl/parent [:eacl/ident :test-store]}])) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :jan-hendrik] :what [:invoice/number "INV123"]}))) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :jan-hendrik] :what [:db/ident :invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) ;(is (eacl/grant! *conn #:eacl {:who [:eacl/ident :jan-hendrik] ; :what :invoice/number ;[:invoice/number "INV123"] ; :where [:eacl/ident :test-store]})) (is (eacl/grant! *conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:eacl/ident :invoices] ;:invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]})) (is (true? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:eacl/ident :invoices] ;:invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :jan-hend<NAME>] :what [:eacl/ident :invoices] ;:invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) ;(is (eacl/grant! *conn #:eacl {:who [:eacl/ident :role/store-manager] ; :what :invoices ;[:invoice/number "INV123"] ; :where [:eacl/ident :test-store]})) (testing "give test user fine-grained access to a particular invoice" (is (eacl/grant! *conn #:eacl {:who [:eacl/ident :<NAME>-h<NAME>] :what [:invoice/number "INV123"] ;[:eacl/ident :invoices] ;/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (testing "we can retrieve the grant just issued" (let [[allowed? rule] (first (d/q '[:find ?allowed (pull ?rule [* {:eacl/who [:eacl/ident] :eacl/what [:eacl/ident :invoice/number] :eacl/where [:eacl/ident]}]) :in $ ?who :where [?rule :eacl/who ?who] [?rule :eacl/allowed? ?allowed]] @*conn [:eacl/ident :jan-hendrik]))] (is (= true allowed?)))) ;(is (d/transact *conn [[:db/add [:invoice/number "INV123"] :eacl/parent :invoice/number]])) (prn "xxx HERE") ;(d/q '[:find ?rule ; :where ; [?rule :eacl/who [:eacl/ident :jan-hendrik]]]) (testing "previous grant! has taken effect" ;; why is this not working? (is (true? (eacl/can? @*conn #:eacl{:who [:eacl/ident :jan-hendrik] :what [:invoice/number "INV123"] ;; todo inherit place. :where [:eacl/ident :test-store]})))) (is (eacl/deny! *conn #:eacl {:who [:eacl/ident :jan-hendrik] :what [:invoice/number "INV123"] ;; todo inherit place. :where [:eacl/ident :test-store]})) ;; why isn't deny working? (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :jan-hendrik] :what [:invoice/number "INV123"] ;; todo inherit place. :where [:eacl/ident :test-store]}))) (prn "Manager: " (d/pull @*conn '[*] [:eacl/ident :role/store-manager])) (prn (d/pull @*conn '[*] [:eacl/ident :jan-hendrik])) (d/transact *conn [[:db/add [:db/ident :invoice/number] :eacl/parent [:eacl/ident :invoices]]]) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:db/ident :eacl/who] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (is (true? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:db/ident :invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (is (eacl/grant! *conn #:eacl {:who [:eacl/ident :role/store-manager] :what :invoice/number ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]})) (is (true? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:db/ident :invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (is (eacl/deny! *conn #:eacl {:who [:eacl/ident :role/store-manager] :what :invoice/number ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]})) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:db/ident :invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) ;(eacl/grant! *conn #:eacl {:who [:eacl/ident :<NAME>] ; :where [:eacl/ident :test-store] ; :what [:invoice/number "INV123"]}) (d/transact *conn [[:db/add [:eacl/ident :jan-hendrik] :eacl/parent [:eacl/ident :role/store-manager]]]) (is (true? (eacl/can? @*conn #:eacl {:who [:eacl/ident :<NAME>-hend<NAME>] :what :invoice/number ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) ;(eacl) (is (d/transact *conn [{:db/ident :event/key :db/doc "Event keyword to trigger subscription notifications." :db/valueType :db.type/keyword :db/unique :db.unique/identity :db/cardinality :db.cardinality/one}])) ;; subscribe vs grant? ;; Todo: use EACL to validate itself for e.g. granting new rules. (is (eacl/grant! *conn #:eacl{;:when {:event/key :event/new-order} ;; inheritance :who [:eacl/ident :role/store-manager] ;; vs. view vs. see? ;; todo: support '1 year' from now for times. :how :read ;; :notify? all aspects? what about children of the store? ;; Todo: think about how to support arbitrary queries in :what. Maybe call it query for subs. ;:what '[*] ;; hmm not valid. how to implement this? :where [:eacl/ident :test-store] ;; better name :why :email/notification})) ;; how to mix (is (eacl/enum-event-triggers @*conn :event/new-order)) ;; is EACL the right place for this kind of topic subscription? (let [test-rule #:eacl{:who [:eacl/ident :jan-hendrik] ;[:db/ident :jan-hendrik] :what [:db/ident :product/name] :where [:eacl/ident :test-store] ;[:db/ident :test-store] :how :create}] (eacl/grant! *conn test-rule) ;; how can we enum all the rules for this user? (let [db @*conn user-rules (eacl/enum-user-rules db [:eacl/ident :jan-hendrik]) jan (d/entity db [:eacl/ident :jan-hendrik])] (log/debug "User rules:" user-rules) ;; need some jigs to test entity equality. ;; do pulls return entities? (let [rule1 (ffirst user-rules)] (is (= (:db/id (first (:eacl/who rule1)) (:db/id jan)))))) ; (is (= (:eacl/who rule1) {:eacl/who [:eacl/ident :jan-hendrik]})))) (is (true? (eacl/can? (d/db *conn) test-rule))))) (deftest notify-tests (testing "who can?" (let [db @*conn] (log/debug "Who:" (eacl/who-can? db #:eacl{:who '?who :what [:db/ident :product/name] :where [:eacl/ident :test-store] :how :create}))))) ;(deftest can?-multi-arity ;; how should this work? ; (is (true? (eacl/can? (d/db *conn) ; #:eacl{:who #{[:db/ident :jan-hendrik]} ;[:db/ident :jan-hendrik] ; :what [:db/ident :product/name] ; :where [:db/ident :test-store] ;[:db/ident :test-store] ; :how :create})))) ;; what's the simplest thing that can work for notifications? ;; assign store roles. Well basically that's what a rule is. ;; We just need to match the what and the where. ;(deftest notify-tests ; (testing "who can?" ; (let [db @*conn] ; (is (eacl/who-can? db {})))) ; ; (testing "can we use EACL roles for notifications?" ; ;; generalised subscriptions? coz well, if someone edits something, we know right. ; ;; Need differential dataflow here. ; ; ;; what should notification API look like? Basically we are subscribing to entities with an :sales-order/number + user has a certain right at :sales-order/store. ; ;; could we design rule queries that they are unified? ; ;; in this case it's basically `?order :sales-order/store ?store` for any ?order but limited ?store. ; ;; Can we use Datomic listeners for this + filter? ; ; ;; why vs how for order notifications? ; ; (let [notify-rule #:eacl{:who [:db/ident :jan-hendrik] ; :where [:db/ident :test-store] ; :why :notify/new-order ; :how '[*] ;; hmm any attribute. Would be cool if this qorks as expected. ; ;; can what be new incoming orders? ; ;; can :what be a recursive pull for the order we care about? ; :what :sales-order/number}] ; (eacl/grant! *conn notify-rule) ; (let [db @*conn] ; (is (not (eacl/can? db (dissoc notify-rule :eacl/who)))) ; (is (not (eacl/can? db (assoc notify-rule :eacl/who [:db/ident :petrus])))) ; (is (eacl/can? db notify-rule)))) ; ; ;'[:find (pull ?order [*]) ; ; :where ; ; [?order :sales-order/number ?number ; ; ?order :sales-order/store ?store ; ; ;; we have to name these order notification. ; ; ?rule :eacl/what ?order ;; :sales-order/number ;; hmm. ; ; ?rule :eacl/where ?store ; ; ?rule :eacl/allowed? true ; ; ?rule :eacl/who ?who]] ; (let [group (eacl/create-group! *conn {:group/name "Test"}) ; db @*conn ; rule #:eacl{:how :notify/order-placed ;[:db/ident :test-store] ; ;; note the absence of ?who. ; ;; hmm, can we use datomic listener + filter here? No, has to be indexed queryable. ; :what [:db/ident :test-store]}]) ; ;(eacl/enum-who-can db rule)) ; ;(eacl/who-can? db)) ; ;(eacl/can? @*conn #:eacl{:who ?who ; ; :what [:db/ident :test-store] ; ; :where [] ; ; ;; hmm, could :why be the answer here? ; ; :how :notify/order-placed})) ; ())) ;(deftest enum-tests ; (d/transact *conn ; [{:db/id -1 ; :eacl/path "invoices" ; :eacl/ident :invoices} ; {:db/id -2 ; :db/ident :petrus}]) ; ; (time ; (d/transact *conn ; (vec (for [inv-num (range 1 (inc n-iterations))] ; {:db/id (- inv-num) ; :invoice/number (str "INV" inv-num) ; :eacl/parent [:eacl/ident :invoices]})))) ; ; (is (empty? (log/debug "Enum 1:" (eacl/enum-user-rules (d/db *conn) [:db/ident :petrus])))) ; ; ;(comment ; ; (let [conn (d/create-mem-conn (conj schema/v1-eacl-schema {:db/ident :invoice/number ; ; :db/valueType :db.type/string ; ; :db/unique :db.unique/identity ; ; :db/cardinality :db.cardinality/one})) ; ; rule {:eacl/who [:db/ident :petrus] ; ; :eacl/what [:eacl/ident :invoices] ; ; ;:eacl/where [:eacl/ident :invoices] ;;temp ; ; :eacl/how :read}] ; ; (d/transact conn (eacl/tx-rule true rule)))) ; ; (let [rule {:eacl/who [:db/ident :petrus] ; :eacl/what [:eacl/ident :invoices] ; :eacl/how :read}] ; (d/transact *conn [{:db/id -1 ; :eacl/parent -1 ;; own parent ; :db/ident :petrus} ; {:db/id -2 ; :eacl/ident :invoices ; :eacl/parent -2}]) ; ; ;(eacl/tx-rule true rule) ; ; (is (false? (eacl/can? (d/db *conn) rule))) ; (eacl/grant! *conn rule) ; (log/debug "Enum 2:" (eacl/enum-user-rules (d/db *conn) [:db/ident :petrus])) ; (is (= 1 (count (eacl/enum-user-rules (d/db *conn) [:db/ident :petrus])))) ; ;;(log/debug "Enum 2:" (eacl/enum-user-permissions @conn (:db/id who))) ; (log/debug "qry:" (eacl/build-rule-query rule)) ; (is (true? (eacl/can? (d/db *conn) rule))) ; ; (eacl/deny! *conn rule) ; (is (false? (time (eacl/can? (d/db *conn) rule)))) ; ; ;; Thinking about rule inheritance: ; ;; 1. Specific overrides general rules. ; ;; 2. Given a tie, deny overrules allow. ; ;; 3. How can we use rules prospectively to see if a transaction will trigger any rules? ; ; (eacl/grant! *conn rule) ;; should this complain about a conflicting rule, or should it override the deny-rule? ; (is (true? (eacl/can? (d/db *conn) rule))))) ;(is (false? (eacl/can? (d/db conn) {:db/})))))) ;(is (false? (eacl/can? (d/db conn))))))) ; (:db/id invoices)})))) ;; ; ; (let [db @conn] ; (is (false? (eacl/can? db {:eacl/who who ;(:db/id user) ; :eacl/what what ; :eacl/how :read}))) ; (:db/id invoices)})))) ; (eacl/grant! conn {:eacl/who who ; :eacl/what what ; :eacl/how :read}) ; ; (log/debug "Enum 2:" (eacl/enum-user-permissions @conn (:db/id who))) ; (is (true? (eacl/can? @conn {:eacl/user who ; (:db/id user) ; :eacl/action :read ; :eacl/resource what}))) ; (:db/id invoices)})))))) ; (eacl/deny! conn {:eacl/who who ; :eacl/what what ; :eacl/how :read}) ; (eacl/grant! conn {:eacl/who who ; :eacl/what what ; :eacl/how :write}) ; (log/debug "Enum 3:" (eacl/enum-user-permissions @conn (:db/id who))) ; (let [db1 @conn] ; (is (false? (eacl/can? db1 {:eacl/who who ; :eacl/what what ; :eacl/how :read}))) ; (is (true? (eacl/can? db1 {:eacl/who who ; :eacl/what what ; :eacl/how :write}))))))) (comment) ;(clojure.test/run-tests (enum-tests)) ;(let [conn (d/create-mem-conn schema/latest-schema) ; admin (eacl/create-user! conn {:user/name "Test User"}) ; invoices (eacl/create-entity! conn {:eacl/path "invoices"})] ; ; (eacl/grant! conn ; {:eacl/who admin ; :eacl/how :read ; :eacl/what invoices}) ; ; (eacl/deny! conn ; {:eacl/who admin ; :eacl/action :write ; :eacl/what invoices}) ; ; (d/q '[:find ?perm ; (pull ?user [*]) ; ?action ; (pull ?resource [*]) ; (pull ?group [*]) ; (pull ?perm [*]) ; :in ; $ % ; ?user ?action ?resource ;; how to handle group? ; :where ; [?perm :eacl/group ?group] ;; not sure ; [?perm :eacl/resource ?resource] ; [?perm :eacl/how :read] ; :read] ; [?perm :eacl/allowed? true] ; true] ; (not [?perm :eacl/allowed? false]) ;; /blocked? ; (child-of ?user ?group)] ; @conn ; eacl/child-rules ; (:db/id admin) :read (:db/id invoices)))) ;(d/q '[:find ; (pull ?user [*]) ; ?allowed ; ?action ; (pull ?resource [*]) ; (pull ?group [*]) ; (pull ?perm [*]) ; :in $ % ; :where ; ;[?perm :eacl/user ?user] ; [?perm :eacl/resource ?resource] ; [?perm :eacl/allowed? ?allowed] ; [?perm :eacl/action ?action] ; (child-of ?user ?group)] ; @conn ; eacl/child-rules))) ;(deftest eacl-tests ; (let [conn eacl/conn ;; eww ; invoices (eacl/create-entity! conn {:eacl/ident "invoices"}) ; user (eacl/create-user! conn {:user/name "<NAME>"})] ; (eacl/grant-access! conn {:eacl/user user ; :eacl/resource (:db/id invoices) ; ;:eacl/path "invoices/*" ; :eacl/action :read}) ; (log/debug "enum:" (eacl/enum-user-permissions @conn user)) ; (is (true? (eacl/can-user? @conn {:eacl/user user ; :eacl/resource (:db/id invoices) ; ;:eacl/path "invoices/*" ;; hmm ; ;:eacl/location "Cape Town" ; :eacl/action :read}))))) (comment (clojure.test/run-tests)) ;(enum-tests) ;(enum) ;(clojure.test/) ;(clojure.test/run-tests)
true
(ns eacl.core-test (:require ;[bridge.utils :refer [spy profile]] [clojure.test :as t :refer (deftest is testing)] [taoensso.timbre :as log] [eacl.core :as eacl] [eacl.data.schema :as schema] [datahike.api :as d] [datahike.core :as dc] [clojure.spec.test.alpha :as st])) ;[bridge.fixtures.common-fixtures :as f :refer (*conn *db)] ;[bridge.fixtures.catalog-fixtures :as cf] ;[bridge.fixtures.auth-fixtures :as af] ;[bridge.fixtures.auth-fixtures :as fa])) (def n-iterations 150) ;; was 100000. belongs under perf/benchmark tests. (def ^:dynamic *conn nil) (defn create-mem-conn [& [tx-initial]] (let [cfg-mem {:store {:backend :mem :id (str 123)}}] ;(str (rand-int 1000))}}] ;(nano/nano-id)}}] (d/create-database cfg-mem :tx-initial tx-initial) (let [conn (d/connect cfg-mem)] (when tx-initial (d/transact conn tx-initial)) conn))) (defn conn-fixture [test-fn] (st/instrument) (let [conn (create-mem-conn schema/v1-eacl-schema)] ;(mount/start-with {#'bridge.data.datahike/conn conn}) (with-bindings {#'*conn conn} (test-fn)) ;; should we call destroy here? (d/release conn) ;(mount/stop) ;; hmm (st/unstrument) true)) (defn eacl-fixtures [test-fn] (assert *conn) (d/transact *conn schema/v1-eacl-schema) (d/transact *conn [{:db/ident :contact/full-name :db/valueType :db.type/string :db/cardinality :db.cardinality/one} {:db/ident :user/contact :db/valueType :db.type/ref :db/cardinality :db.cardinality/one} {:db/ident :invoice/number :db/valueType :db.type/string :db/unique :db.unique/identity :db/cardinality :db.cardinality/one}]) ;(let [conn (->> {:db/ident :invoice/number ; :db/valueType :db.type/string ; :db/unique :db.unique/identity ; :db/cardinality :db.cardinality/one} ; (conj schema/v1-eacl-schema) ; (d/create-mem-conn))]) (d/transact *conn [{:db/ident :invoices :eacl/ident :invoices}]) ;(eacl/grant! *conn #:eacl{:who [:eacl/ident :jan-hendrik] ; :what :invoice/number}) (time (d/transact *conn (vec (for [inv-num (range 1 (inc n-iterations))] {:db/id (- inv-num) :invoice/number (str "INV" inv-num) :eacl/parent [:eacl/ident :invoices]})))) (d/transact *conn [{:db/id [:eacl/ident :invoices] :eacl/path "invoices" :eacl/ident :invoices} {:db/id -2 :db/ident :petrus}]) ;(with-bindings {#'*conn conn}) (test-fn)) ;(d/release *conn)) ;(deftest fixture-sanity ; (testing "can transact fixtures against empty-db" ; (eacl-fixtures (fn [])))) ;(d/transact (d/empty-db) eacl-fixtures))) (comment (mount.core/start)) ;; hmm yeah it would be good to not rely on any bridge schema. (t/use-fixtures :each conn-fixture eacl-fixtures) ;fa/auth-fixtures) ; eacl-fixtures) ;(t/use-fixtures :each f/conn-fixture af/auth-fixtures cf/catalog-fixtures eacl-fixtures) ;(clojure.test/use-fixtures my-fixtures) ;(doseq [inv-num (range n-iterations)] ; (d/transact conn {:invoice/number inv-num ; :eacl/parent [:eacl/ident :invoices]})) ;(deftest grant-deny) ;(let [conn (d/create-mem-conn (conj schema/v1-eacl-schema {:db/ident :invoice/number ; :db/valueType :db.type/string ; :db/unique :db.unique/identity ; :db/cardinality :db.cardinality/one}))])) ;(eacl/grant! conn #:eacl{:who :petrus ; :what :invoices ; :how :read}))) (def crud #{:create :read :update :delete}) ;'{:find [(pull ?rule [*])], ; :in [$ % ?allow ?who ?what ?why ?when ?where ?how], ; :where [[?rule :eacl/allowed? ?allow] [?rule :eacl/who ?who] [?rule :eacl/what ?what] [?rule :eacl/where ?where] [?rule :eacl/how ?how]] ; ([[(child-of ?c ?p) (?c :eacl/parent ?p)] [(child-of ?c ?p) (?c1 :eacl/parent ?p) (child-of ?c ?c1)]] ; false :jan-hendrik ; :product/name ; #{} ; nil ; :test-store ; :create)} ;'[:find ?rule ; :where ; [?rule :eacl/allowed? true] ; [?rule :eacl/where :test-store] ; [?rule :eacl/what :product/name] ; [?rule :eacl/who :jan-hendrik]] (comment (eacl-fixtures (fn [] ;(d/transact *conn [{:db/ident :PI:NAME:<NAME>END_PI-hPI:NAME:<NAME>END_PIrik ; :eacl/ident :jan-hendrik} ; {:eacl/ident :test-store} ; {:db/ident :product/name}]) (let [rule {:eacl/who [:eacl/ident :jan-hendrik] :eacl/what [:db/ident :product/name] :eacl/where [:eacl/ident :test-store] :eacl/how :create}] (eacl/grant! *conn rule) (let [db (d/db *conn)] (log/warn "TEST" (d/q '[:find ?rule :in $ ?who :where [?rule :eacl/allowed? true] [?rule :eacl/where :test-store] [?rule :eacl/what :product/name] [?rule :eacl/who ?who]] (d/db *conn) [:db/ident :jan-hendrik])) ;(let [{:eacl/keys [who what why when where how]} demand] ; (log/warn "CUSTOM" (into [] (d/q ; (eacl/build-rule-query demand) ; (d/db *conn) eacl/child-rules ; true [:db/ident :jan-hendrik])))) ;(or who #{}))))) ;(or what #{}) ;(or why #{}) ;(or when #{}) ;(or where #{}) ;(or how #{}))))) (log/warn (eacl/can? db rule))))))) (deftest sanity-tests (testing "can? doesn't blow up" (let [db (d/db-with (dc/empty-db) schema/v1-eacl-schema)] (is (false? (eacl/can? db #:eacl{:who [:eacl/ident :me] :what [:eacl/ident :thing] :where [:eacl/ident :anywhere] :how :read})))))) ;[:eacl/ident :read]}))))) (comment (eacl/can? @*conn {:eacl/who [:eacl/ident :alex] :eacl/how :read :eacl/read [:docket/number 567] :eacl/where #inst "2000-05-05"})) ;(defn create-order! [db order-number lines] ; (eacl/can! db {:eacl/who :alex ; :eacl/what :order/number ; :eacl/how :create ; :eacl/when (t/now) ; :eacl/why ""})) (deftest recursion-tests (testing "that child inherits parent's rules" (is (d/transact *conn [{:db/id -1 :eacl/ident :alice} {:db/id -2 :eacl/ident :bob}])) (d/transact *conn [[:db/add [:db/ident :invoice/number] :eacl/parent [:db/ident :invoice/number]]]) ;; required for most queries to work. Big todo. (is (eacl/create-role! *conn {:db/ident :manager})) (is (false? (eacl/can? @*conn #:eacl {:who [:db/ident :manager] :what [:db/ident :invoice/number] :how :read}))) (is (eacl/grant! *conn #:eacl {:who [:db/ident :manager] :what [:db/ident :invoice/number] :how :read})) (is (true? (eacl/can? @*conn #:eacl {:who [:db/ident :manager] :what [:db/ident :invoice/number] :how :read}))))) ;(is (true? (eacl/can? @*conn #:eacl {:who [:db/ident :manager] ; :what [:db/ident :invoice/number] ; :how :read}))) ;(d/transact *conn [[:db/ident :alice] :eacl/parent [:db/ident :manager]]) ;(eacl/can? @*conn #:eacl {:who [:db/ident :alice]}))) ;(eacl/assign-role-at!) ;(eacl/grant! *conn #:eacl {:who [:db/ident]}))) (deftest store-rules (is (d/transact *conn [{:db/ident :product/name :db/valueType :db.type/string :db/cardinality :db.cardinality/one} {:db/ident :store/name :db/valueType :db.type/string :db/cardinality :db.cardinality/one} {:db/ident :invoice/number :db/valueType :db.type/string :db/unique :db.unique/identity} {:db/ident :invoice/total :db/valueType :db.type/bigdec :db/cardinality :db.cardinality/one :db/index true} {:db/ident :contact/name :db/valueType :db.type/string :db/cardinality :db.cardinality/one}])) ;(d/transact *conn [{:db/id "role" ; :eacl/ident :role/store-manager ; :eacl/role "role"}]) (is (d/transact *conn [{:db/id "store" :eacl/ident :test-store :eacl/parent "store" ;; required :eacl/role "store" ;; required :store/name "Ancestral Nourishment Store"} {:db/id "contact" :contact/full-name "PI:NAME:<NAME>END_PI"} {:db/id "invoices" :eacl/parent "invoices" ;; NB MUST BE OWN PARENT. :eacl/ident :invoices} {:db/id "user" :eacl/ident :jan-hendrik :eacl/parent "user" ;; hack :eacl/role "user" ;; hack :user/contact "contact"}])) (prn "write invoices:") (time (d/transact *conn (vec (for [inv-num (range 1 (inc n-iterations))] {:db/id (- inv-num) :invoice/number (str "INV" inv-num) :eacl/parent [:eacl/ident :invoices]})))) (prn "invoices:" (d/q '[:find ?num :where [?inv :invoice/number ?num]] @*conn)) ;(is (d/transact *conn [{:invoice/number "INV123" ; :eacl/parent [:db/ident :invoice/number] ; :invoice/total 123.45M}])) (is (eacl/create-role! *conn {:eacl/ident :role/store-manager})) ;(is (eacl/assign-role-at! *conn ; [:eacl/ident :jan-hendrik] ; [:eacl/ident :role/store-manager] ;; need some sugar here. ; [:eacl/ident :test-store])) (is (d/transact *conn [{:invoice/number "INV123" ;; will complain :invoice/total 123.45M :eacl/parent [:eacl/ident :invoices]}])) ;:eacl/parent [:eacl/ident :test-store]}])) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :jan-hendrik] :what [:invoice/number "INV123"]}))) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :jan-hendrik] :what [:db/ident :invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) ;(is (eacl/grant! *conn #:eacl {:who [:eacl/ident :jan-hendrik] ; :what :invoice/number ;[:invoice/number "INV123"] ; :where [:eacl/ident :test-store]})) (is (eacl/grant! *conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:eacl/ident :invoices] ;:invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]})) (is (true? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:eacl/ident :invoices] ;:invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :jan-hendPI:NAME:<NAME>END_PI] :what [:eacl/ident :invoices] ;:invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) ;(is (eacl/grant! *conn #:eacl {:who [:eacl/ident :role/store-manager] ; :what :invoices ;[:invoice/number "INV123"] ; :where [:eacl/ident :test-store]})) (testing "give test user fine-grained access to a particular invoice" (is (eacl/grant! *conn #:eacl {:who [:eacl/ident :PI:NAME:<NAME>END_PI-hPI:NAME:<NAME>END_PI] :what [:invoice/number "INV123"] ;[:eacl/ident :invoices] ;/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (testing "we can retrieve the grant just issued" (let [[allowed? rule] (first (d/q '[:find ?allowed (pull ?rule [* {:eacl/who [:eacl/ident] :eacl/what [:eacl/ident :invoice/number] :eacl/where [:eacl/ident]}]) :in $ ?who :where [?rule :eacl/who ?who] [?rule :eacl/allowed? ?allowed]] @*conn [:eacl/ident :jan-hendrik]))] (is (= true allowed?)))) ;(is (d/transact *conn [[:db/add [:invoice/number "INV123"] :eacl/parent :invoice/number]])) (prn "xxx HERE") ;(d/q '[:find ?rule ; :where ; [?rule :eacl/who [:eacl/ident :jan-hendrik]]]) (testing "previous grant! has taken effect" ;; why is this not working? (is (true? (eacl/can? @*conn #:eacl{:who [:eacl/ident :jan-hendrik] :what [:invoice/number "INV123"] ;; todo inherit place. :where [:eacl/ident :test-store]})))) (is (eacl/deny! *conn #:eacl {:who [:eacl/ident :jan-hendrik] :what [:invoice/number "INV123"] ;; todo inherit place. :where [:eacl/ident :test-store]})) ;; why isn't deny working? (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :jan-hendrik] :what [:invoice/number "INV123"] ;; todo inherit place. :where [:eacl/ident :test-store]}))) (prn "Manager: " (d/pull @*conn '[*] [:eacl/ident :role/store-manager])) (prn (d/pull @*conn '[*] [:eacl/ident :jan-hendrik])) (d/transact *conn [[:db/add [:db/ident :invoice/number] :eacl/parent [:eacl/ident :invoices]]]) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:db/ident :eacl/who] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (is (true? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:db/ident :invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (is (eacl/grant! *conn #:eacl {:who [:eacl/ident :role/store-manager] :what :invoice/number ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]})) (is (true? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:db/ident :invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) (is (eacl/deny! *conn #:eacl {:who [:eacl/ident :role/store-manager] :what :invoice/number ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]})) (is (false? (eacl/can? @*conn #:eacl {:who [:eacl/ident :role/store-manager] :what [:db/ident :invoice/number] ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) ;(eacl/grant! *conn #:eacl {:who [:eacl/ident :PI:NAME:<NAME>END_PI] ; :where [:eacl/ident :test-store] ; :what [:invoice/number "INV123"]}) (d/transact *conn [[:db/add [:eacl/ident :jan-hendrik] :eacl/parent [:eacl/ident :role/store-manager]]]) (is (true? (eacl/can? @*conn #:eacl {:who [:eacl/ident :PI:NAME:<NAME>END_PI-hendPI:NAME:<NAME>END_PI] :what :invoice/number ;[:invoice/number "INV123"] :where [:eacl/ident :test-store]}))) ;(eacl) (is (d/transact *conn [{:db/ident :event/key :db/doc "Event keyword to trigger subscription notifications." :db/valueType :db.type/keyword :db/unique :db.unique/identity :db/cardinality :db.cardinality/one}])) ;; subscribe vs grant? ;; Todo: use EACL to validate itself for e.g. granting new rules. (is (eacl/grant! *conn #:eacl{;:when {:event/key :event/new-order} ;; inheritance :who [:eacl/ident :role/store-manager] ;; vs. view vs. see? ;; todo: support '1 year' from now for times. :how :read ;; :notify? all aspects? what about children of the store? ;; Todo: think about how to support arbitrary queries in :what. Maybe call it query for subs. ;:what '[*] ;; hmm not valid. how to implement this? :where [:eacl/ident :test-store] ;; better name :why :email/notification})) ;; how to mix (is (eacl/enum-event-triggers @*conn :event/new-order)) ;; is EACL the right place for this kind of topic subscription? (let [test-rule #:eacl{:who [:eacl/ident :jan-hendrik] ;[:db/ident :jan-hendrik] :what [:db/ident :product/name] :where [:eacl/ident :test-store] ;[:db/ident :test-store] :how :create}] (eacl/grant! *conn test-rule) ;; how can we enum all the rules for this user? (let [db @*conn user-rules (eacl/enum-user-rules db [:eacl/ident :jan-hendrik]) jan (d/entity db [:eacl/ident :jan-hendrik])] (log/debug "User rules:" user-rules) ;; need some jigs to test entity equality. ;; do pulls return entities? (let [rule1 (ffirst user-rules)] (is (= (:db/id (first (:eacl/who rule1)) (:db/id jan)))))) ; (is (= (:eacl/who rule1) {:eacl/who [:eacl/ident :jan-hendrik]})))) (is (true? (eacl/can? (d/db *conn) test-rule))))) (deftest notify-tests (testing "who can?" (let [db @*conn] (log/debug "Who:" (eacl/who-can? db #:eacl{:who '?who :what [:db/ident :product/name] :where [:eacl/ident :test-store] :how :create}))))) ;(deftest can?-multi-arity ;; how should this work? ; (is (true? (eacl/can? (d/db *conn) ; #:eacl{:who #{[:db/ident :jan-hendrik]} ;[:db/ident :jan-hendrik] ; :what [:db/ident :product/name] ; :where [:db/ident :test-store] ;[:db/ident :test-store] ; :how :create})))) ;; what's the simplest thing that can work for notifications? ;; assign store roles. Well basically that's what a rule is. ;; We just need to match the what and the where. ;(deftest notify-tests ; (testing "who can?" ; (let [db @*conn] ; (is (eacl/who-can? db {})))) ; ; (testing "can we use EACL roles for notifications?" ; ;; generalised subscriptions? coz well, if someone edits something, we know right. ; ;; Need differential dataflow here. ; ; ;; what should notification API look like? Basically we are subscribing to entities with an :sales-order/number + user has a certain right at :sales-order/store. ; ;; could we design rule queries that they are unified? ; ;; in this case it's basically `?order :sales-order/store ?store` for any ?order but limited ?store. ; ;; Can we use Datomic listeners for this + filter? ; ; ;; why vs how for order notifications? ; ; (let [notify-rule #:eacl{:who [:db/ident :jan-hendrik] ; :where [:db/ident :test-store] ; :why :notify/new-order ; :how '[*] ;; hmm any attribute. Would be cool if this qorks as expected. ; ;; can what be new incoming orders? ; ;; can :what be a recursive pull for the order we care about? ; :what :sales-order/number}] ; (eacl/grant! *conn notify-rule) ; (let [db @*conn] ; (is (not (eacl/can? db (dissoc notify-rule :eacl/who)))) ; (is (not (eacl/can? db (assoc notify-rule :eacl/who [:db/ident :petrus])))) ; (is (eacl/can? db notify-rule)))) ; ; ;'[:find (pull ?order [*]) ; ; :where ; ; [?order :sales-order/number ?number ; ; ?order :sales-order/store ?store ; ; ;; we have to name these order notification. ; ; ?rule :eacl/what ?order ;; :sales-order/number ;; hmm. ; ; ?rule :eacl/where ?store ; ; ?rule :eacl/allowed? true ; ; ?rule :eacl/who ?who]] ; (let [group (eacl/create-group! *conn {:group/name "Test"}) ; db @*conn ; rule #:eacl{:how :notify/order-placed ;[:db/ident :test-store] ; ;; note the absence of ?who. ; ;; hmm, can we use datomic listener + filter here? No, has to be indexed queryable. ; :what [:db/ident :test-store]}]) ; ;(eacl/enum-who-can db rule)) ; ;(eacl/who-can? db)) ; ;(eacl/can? @*conn #:eacl{:who ?who ; ; :what [:db/ident :test-store] ; ; :where [] ; ; ;; hmm, could :why be the answer here? ; ; :how :notify/order-placed})) ; ())) ;(deftest enum-tests ; (d/transact *conn ; [{:db/id -1 ; :eacl/path "invoices" ; :eacl/ident :invoices} ; {:db/id -2 ; :db/ident :petrus}]) ; ; (time ; (d/transact *conn ; (vec (for [inv-num (range 1 (inc n-iterations))] ; {:db/id (- inv-num) ; :invoice/number (str "INV" inv-num) ; :eacl/parent [:eacl/ident :invoices]})))) ; ; (is (empty? (log/debug "Enum 1:" (eacl/enum-user-rules (d/db *conn) [:db/ident :petrus])))) ; ; ;(comment ; ; (let [conn (d/create-mem-conn (conj schema/v1-eacl-schema {:db/ident :invoice/number ; ; :db/valueType :db.type/string ; ; :db/unique :db.unique/identity ; ; :db/cardinality :db.cardinality/one})) ; ; rule {:eacl/who [:db/ident :petrus] ; ; :eacl/what [:eacl/ident :invoices] ; ; ;:eacl/where [:eacl/ident :invoices] ;;temp ; ; :eacl/how :read}] ; ; (d/transact conn (eacl/tx-rule true rule)))) ; ; (let [rule {:eacl/who [:db/ident :petrus] ; :eacl/what [:eacl/ident :invoices] ; :eacl/how :read}] ; (d/transact *conn [{:db/id -1 ; :eacl/parent -1 ;; own parent ; :db/ident :petrus} ; {:db/id -2 ; :eacl/ident :invoices ; :eacl/parent -2}]) ; ; ;(eacl/tx-rule true rule) ; ; (is (false? (eacl/can? (d/db *conn) rule))) ; (eacl/grant! *conn rule) ; (log/debug "Enum 2:" (eacl/enum-user-rules (d/db *conn) [:db/ident :petrus])) ; (is (= 1 (count (eacl/enum-user-rules (d/db *conn) [:db/ident :petrus])))) ; ;;(log/debug "Enum 2:" (eacl/enum-user-permissions @conn (:db/id who))) ; (log/debug "qry:" (eacl/build-rule-query rule)) ; (is (true? (eacl/can? (d/db *conn) rule))) ; ; (eacl/deny! *conn rule) ; (is (false? (time (eacl/can? (d/db *conn) rule)))) ; ; ;; Thinking about rule inheritance: ; ;; 1. Specific overrides general rules. ; ;; 2. Given a tie, deny overrules allow. ; ;; 3. How can we use rules prospectively to see if a transaction will trigger any rules? ; ; (eacl/grant! *conn rule) ;; should this complain about a conflicting rule, or should it override the deny-rule? ; (is (true? (eacl/can? (d/db *conn) rule))))) ;(is (false? (eacl/can? (d/db conn) {:db/})))))) ;(is (false? (eacl/can? (d/db conn))))))) ; (:db/id invoices)})))) ;; ; ; (let [db @conn] ; (is (false? (eacl/can? db {:eacl/who who ;(:db/id user) ; :eacl/what what ; :eacl/how :read}))) ; (:db/id invoices)})))) ; (eacl/grant! conn {:eacl/who who ; :eacl/what what ; :eacl/how :read}) ; ; (log/debug "Enum 2:" (eacl/enum-user-permissions @conn (:db/id who))) ; (is (true? (eacl/can? @conn {:eacl/user who ; (:db/id user) ; :eacl/action :read ; :eacl/resource what}))) ; (:db/id invoices)})))))) ; (eacl/deny! conn {:eacl/who who ; :eacl/what what ; :eacl/how :read}) ; (eacl/grant! conn {:eacl/who who ; :eacl/what what ; :eacl/how :write}) ; (log/debug "Enum 3:" (eacl/enum-user-permissions @conn (:db/id who))) ; (let [db1 @conn] ; (is (false? (eacl/can? db1 {:eacl/who who ; :eacl/what what ; :eacl/how :read}))) ; (is (true? (eacl/can? db1 {:eacl/who who ; :eacl/what what ; :eacl/how :write}))))))) (comment) ;(clojure.test/run-tests (enum-tests)) ;(let [conn (d/create-mem-conn schema/latest-schema) ; admin (eacl/create-user! conn {:user/name "Test User"}) ; invoices (eacl/create-entity! conn {:eacl/path "invoices"})] ; ; (eacl/grant! conn ; {:eacl/who admin ; :eacl/how :read ; :eacl/what invoices}) ; ; (eacl/deny! conn ; {:eacl/who admin ; :eacl/action :write ; :eacl/what invoices}) ; ; (d/q '[:find ?perm ; (pull ?user [*]) ; ?action ; (pull ?resource [*]) ; (pull ?group [*]) ; (pull ?perm [*]) ; :in ; $ % ; ?user ?action ?resource ;; how to handle group? ; :where ; [?perm :eacl/group ?group] ;; not sure ; [?perm :eacl/resource ?resource] ; [?perm :eacl/how :read] ; :read] ; [?perm :eacl/allowed? true] ; true] ; (not [?perm :eacl/allowed? false]) ;; /blocked? ; (child-of ?user ?group)] ; @conn ; eacl/child-rules ; (:db/id admin) :read (:db/id invoices)))) ;(d/q '[:find ; (pull ?user [*]) ; ?allowed ; ?action ; (pull ?resource [*]) ; (pull ?group [*]) ; (pull ?perm [*]) ; :in $ % ; :where ; ;[?perm :eacl/user ?user] ; [?perm :eacl/resource ?resource] ; [?perm :eacl/allowed? ?allowed] ; [?perm :eacl/action ?action] ; (child-of ?user ?group)] ; @conn ; eacl/child-rules))) ;(deftest eacl-tests ; (let [conn eacl/conn ;; eww ; invoices (eacl/create-entity! conn {:eacl/ident "invoices"}) ; user (eacl/create-user! conn {:user/name "PI:NAME:<NAME>END_PI"})] ; (eacl/grant-access! conn {:eacl/user user ; :eacl/resource (:db/id invoices) ; ;:eacl/path "invoices/*" ; :eacl/action :read}) ; (log/debug "enum:" (eacl/enum-user-permissions @conn user)) ; (is (true? (eacl/can-user? @conn {:eacl/user user ; :eacl/resource (:db/id invoices) ; ;:eacl/path "invoices/*" ;; hmm ; ;:eacl/location "Cape Town" ; :eacl/action :read}))))) (comment (clojure.test/run-tests)) ;(enum-tests) ;(enum) ;(clojure.test/) ;(clojure.test/run-tests)
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.999812126159668, "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.9998209476470947, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/src/clj/editor/view.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.view (:require [dynamo.graph :as g])) (g/defnode WorkbenchView (input resource-node g/NodeID) (input node-id+resource g/Any :substitute nil) (input dirty? g/Bool :substitute false) (output view-data g/Any (g/fnk [_node-id node-id+resource] [_node-id (when-let [[node-id resource] node-id+resource] {:resource-node node-id :resource resource})])) ;; we cache view-dirty? to avoid recomputing dirty? on the resource ;; node for every open tab whenever one resource changes (output view-dirty? g/Any :cached (g/fnk [_node-id dirty?] [_node-id dirty?]))) (defn connect-resource-node [view resource-node] (concat (g/connect resource-node :_node-id view :resource-node) (g/connect resource-node :valid-node-id+resource view :node-id+resource) (g/connect resource-node :dirty? view :dirty?)))
72320
;; 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.view (:require [dynamo.graph :as g])) (g/defnode WorkbenchView (input resource-node g/NodeID) (input node-id+resource g/Any :substitute nil) (input dirty? g/Bool :substitute false) (output view-data g/Any (g/fnk [_node-id node-id+resource] [_node-id (when-let [[node-id resource] node-id+resource] {:resource-node node-id :resource resource})])) ;; we cache view-dirty? to avoid recomputing dirty? on the resource ;; node for every open tab whenever one resource changes (output view-dirty? g/Any :cached (g/fnk [_node-id dirty?] [_node-id dirty?]))) (defn connect-resource-node [view resource-node] (concat (g/connect resource-node :_node-id view :resource-node) (g/connect resource-node :valid-node-id+resource view :node-id+resource) (g/connect resource-node :dirty? view :dirty?)))
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.view (:require [dynamo.graph :as g])) (g/defnode WorkbenchView (input resource-node g/NodeID) (input node-id+resource g/Any :substitute nil) (input dirty? g/Bool :substitute false) (output view-data g/Any (g/fnk [_node-id node-id+resource] [_node-id (when-let [[node-id resource] node-id+resource] {:resource-node node-id :resource resource})])) ;; we cache view-dirty? to avoid recomputing dirty? on the resource ;; node for every open tab whenever one resource changes (output view-dirty? g/Any :cached (g/fnk [_node-id dirty?] [_node-id dirty?]))) (defn connect-resource-node [view resource-node] (concat (g/connect resource-node :_node-id view :resource-node) (g/connect resource-node :valid-node-id+resource view :node-id+resource) (g/connect resource-node :dirty? view :dirty?)))
[ { "context": "3 4]))\n\n (def ov (ova [{:id :a1 :score 10 :name \"Bill\" :gender :m :nationality :aus}\n ", "end": 417, "score": 0.9998656511306763, "start": 413, "tag": "NAME", "value": "Bill" }, { "context": " :aus}\n {:id :a2 :score 15 :name \"John\" :gender :m :nationality :aus}]))\n\n (def ov (ov", "end": 497, "score": 0.9998568296432495, "start": 493, "tag": "NAME", "value": "John" }, { "context": " players\n (ova [{:id :a1 :score 10 :info {:name \"Bill\" :gender :m :nationality :aus}}\n {:id :a2", "end": 1927, "score": 0.9996918439865112, "start": 1923, "tag": "NAME", "value": "Bill" }, { "context": "y :aus}}\n {:id :a2 :score 15 :info {:name \"John\" :gender :m :nationality :aus}}\n {:id :a3", "end": 2006, "score": 0.9997511506080627, "start": 2002, "tag": "NAME", "value": "John" }, { "context": "y :aus}}\n {:id :a3 :score 15 :info {:name \"Dave\" :gender :m :nationality :aus}}\n {:id :a4", "end": 2085, "score": 0.9994746446609497, "start": 2081, "tag": "NAME", "value": "Dave" }, { "context": "y :aus}}\n {:id :a4 :score 11 :info {:name \"Henry\" :gender :m :nationality :usa}}\n {:id :a5 ", "end": 2165, "score": 0.9994215965270996, "start": 2160, "tag": "NAME", "value": "Henry" }, { "context": "y :usa}}\n {:id :a5 :score 20 :info {:name \"Scott\" :gender :m :nationality :usa}}\n {:id :a6 ", "end": 2244, "score": 0.9995771646499634, "start": 2239, "tag": "NAME", "value": "Scott" }, { "context": "y :usa}}\n {:id :a6 :score 13 :info {:name \"Tom\" :gender :m :nationality :usa}}\n {:id :a", "end": 2321, "score": 0.9998058676719666, "start": 2318, "tag": "NAME", "value": "Tom" }, { "context": "y :usa}}\n {:id :a7 :score 15 :info {:name \"Jill\" :gender :f :nationality :aus}}\n {:id :a8", "end": 2401, "score": 0.9994800090789795, "start": 2397, "tag": "NAME", "value": "Jill" }, { "context": "y :aus}}\n {:id :a8 :score 19 :info {:name \"Sally\" :gender :f :nationality :usa}}\n {:id :a9 ", "end": 2481, "score": 0.9996806383132935, "start": 2476, "tag": "NAME", "value": "Sally" }, { "context": "y :usa}}\n {:id :a9 :score 13 :info {:name \"Rose\" :gender :f :nationality :aus}}]))\n\n[[:subsectio", "end": 2559, "score": 0.9996707439422607, "start": 2555, "tag": "NAME", "value": "Rose" }, { "context": "layers 0)\n => #{{:id :a1 :score 10 :info {:name \"Bill\" :gender :m :nationality :aus}}})\n\n\"##### Predic", "end": 2720, "score": 0.9998262524604797, "start": 2716, "tag": "NAME", "value": "Bill" }, { "context": " %) :a1))\n => #{{:id :a1 :score 10 :info {:name \"Bill\" :gender :m :nationality :aus}}})\n\n\"##### List P", "end": 2864, "score": 0.9998450875282288, "start": 2860, "tag": "NAME", "value": "Bill" }, { "context": "(= :a1)))\n => #{{:id :a1 :score 10 :info {:name \"Bill\" :gender :m :nationality :aus}}})\n\n\"##### Vector", "end": 3011, "score": 0.9997804760932922, "start": 3007, "tag": "NAME", "value": "Bill" }, { "context": ":id :a1])\n => #{{:id :a1 :score 10 :info {:name \"Bill\" :gender :m :nationality :aus}}}\n\n (select play", "end": 3155, "score": 0.9997779726982117, "start": 3151, "tag": "NAME", "value": "Bill" }, { "context": "e even?])\n => #{{:id :a1 :score 10 :info {:name \"Bill\" :gender :m :nationality :aus}}\n {:id :a5 ", "end": 3269, "score": 0.9997335076332092, "start": 3265, "tag": "NAME", "value": "Bill" }, { "context": "ty :aus}}\n {:id :a5 :score 20 :info {:name \"Scott\" :gender :m :nationality :usa}}}\n\n (select playe", "end": 3348, "score": 0.9988563060760498, "start": 3343, "tag": "NAME", "value": "Scott" }, { "context": "'(< 13)])\n => #{{:id :a1 :score 10 :info {:name \"Bill\" :gender :m :nationality :aus}}\n {:id :a4 ", "end": 3463, "score": 0.9997106790542603, "start": 3459, "tag": "NAME", "value": "Bill" }, { "context": "ty :aus}}\n {:id :a4 :score 11 :info {:name \"Henry\" :gender :m :nationality :usa}}}\n\n (select playe", "end": 3542, "score": 0.9988536834716797, "start": 3537, "tag": "NAME", "value": "Henry" }, { "context": "der] :f])\n => #{{:id :a9 :score 13 :info {:name \"Rose\" :gender :f :nationality :aus}}})\n\n\"##### Sets:\"", "end": 3671, "score": 0.9990997910499573, "start": 3667, "tag": "NAME", "value": "Rose" }, { "context": "s #{1 2})\n => #{{:id :a2 :score 15 :info {:name \"John\" :gender :m :nationality :aus}}\n {:id :a3 ", "end": 3799, "score": 0.9998235106468201, "start": 3795, "tag": "NAME", "value": "John" }, { "context": "ty :aus}}\n {:id :a3 :score 15 :info {:name \"Dave\" :gender :m :nationality :aus}}}\n\n (select play", "end": 3877, "score": 0.9990415573120117, "start": 3873, "tag": "NAME", "value": "Dave" }, { "context": "er] :f]})\n => #{{:id :a1 :score 10 :info {:name \"Bill\" :gender :m :nationality :aus}}\n {:id :a5 ", "end": 4025, "score": 0.9997873902320862, "start": 4021, "tag": "NAME", "value": "Bill" }, { "context": "ty :aus}}\n {:id :a5 :score 20 :info {:name \"Scott\" :gender :m :nationality :usa}}\n {:id :a9 :", "end": 4104, "score": 0.9977256059646606, "start": 4099, "tag": "NAME", "value": "Scott" }, { "context": "ty :usa}}\n {:id :a9 :score 13 :info {:name \"Rose\" :gender :f :nationality :aus}}})\n\n[[:subsection", "end": 4181, "score": 0.9987822771072388, "start": 4177, "tag": "NAME", "value": "Rose" }, { "context": "f]})\n => (just [{:id :a1 :score 10 :info {:name \"Bill\" :gender :m :nationality :aus}}\n {:id", "end": 4460, "score": 0.9996318817138672, "start": 4456, "tag": "NAME", "value": "Bill" }, { "context": "us}}\n {:id :a5 :score 20 :info {:name \"Scott\" :gender :m :nationality :usa}}\n {:id ", "end": 4544, "score": 0.9993768930435181, "start": 4539, "tag": "NAME", "value": "Scott" }, { "context": "sa}}\n {:id :a9 :score 13 :info {:name \"Rose\" :gender :f :nationality :aus}}]\n :in-", "end": 4626, "score": 0.9995783567428589, "start": 4622, "tag": "NAME", "value": "Rose" }, { "context": "(players 0)\n => {:id :a1 :score 10 :info {:name \"Bill\" :gender :m :nationality :aus}}\n\n (players 1)\n ", "end": 5014, "score": 0.9994347095489502, "start": 5010, "tag": "NAME", "value": "Bill" }, { "context": "(players 1)\n => {:id :a2 :score 15 :info {:name \"John\" :gender :m :nationality :aus}}\n\n (players :a3)", "end": 5105, "score": 0.999778687953949, "start": 5101, "tag": "NAME", "value": "John" }, { "context": "layers :a3)\n => {:id :a3 :score 15 :info {:name \"Dave\" :gender :m :nationality :aus}}\n\n (:a3 players)", "end": 5198, "score": 0.9990928173065186, "start": 5194, "tag": "NAME", "value": "Dave" }, { "context": "a3 players)\n => {:id :a3 :score 15 :info {:name \"Dave\" :gender :m :nationality :aus}}\n\n (ov :a10)\n =", "end": 5291, "score": 0.9993166923522949, "start": 5287, "tag": "NAME", "value": "Dave" } ]
test/documentation/hara_concurrent_ova/api.clj
ikitommi/hara
0
(ns documentation.hara-concurrent-ova.api (:use midje.sweet) (:require [hara.concurrent.ova :refer :all] [hara.common.watch :as watch])) [[:section {:title "Basics"}]] [[:subsection {:title "ova"}]] "An `ova` deals with data in a vector. The data can be anything but it is recommended that the data are clojure maps." (fact (def ov (ova [1 2 3 4])) (def ov (ova [{:id :a1 :score 10 :name "Bill" :gender :m :nationality :aus} {:id :a2 :score 15 :name "John" :gender :m :nationality :aus}])) (def ov (ova [{:type "form" :data {:sex :m :age 23}} {:type "form" :data {:sex :f :age 24}}]))) [[:subsection {:title "persistent!"}]] "Since `ova.core.Ova` implements the `clojure.lang.ITransientCollection` interface, it can be made persistent with `persistent!`." (fact (persistent! (ova [1 2 3 4])) => [1 2 3 4]) [[:subsection {:title "init!"}]] "`init!` resets the data elements in an ova to another set of values. Any change in the ova requires it to be wrapped in a `dosync` macro." (fact (def ov (ova [1 2 3 4])) (dosync (init! ov [5 6 7 8 9])) (persistent! ov) => [5 6 7 8 9]) [[:subsection {:title "<<"}]] "The output macro is a shorthand for outputting the value of `ova` after a series of transformations. There is an implicit `dosync` block within the macro." (fact (<< (def ov (ova [1 2 3 4])) (init! ov [5 6 7 8 9])) => [5 6 7 8 9]) [[:section {:title "Clojure"}]] "Built-in operations supported including (but not limited to): - `map`, `reduce`, `first`, `next`, `nth` and many more `seq` operations - `get`, `contains?` - `deref` - `add-watch`, `remove-watch` - `pop!`, `push!`, `conj!` " [[:section {:title "Query"}]] "Where ova shines is in the various ways that elements can be selected. It is best to define some data that can be queried:" (def players (ova [{:id :a1 :score 10 :info {:name "Bill" :gender :m :nationality :aus}} {:id :a2 :score 15 :info {:name "John" :gender :m :nationality :aus}} {:id :a3 :score 15 :info {:name "Dave" :gender :m :nationality :aus}} {:id :a4 :score 11 :info {:name "Henry" :gender :m :nationality :usa}} {:id :a5 :score 20 :info {:name "Scott" :gender :m :nationality :usa}} {:id :a6 :score 13 :info {:name "Tom" :gender :m :nationality :usa}} {:id :a7 :score 15 :info {:name "Jill" :gender :f :nationality :aus}} {:id :a8 :score 19 :info {:name "Sally" :gender :f :nationality :usa}} {:id :a9 :score 13 :info {:name "Rose" :gender :f :nationality :aus}}])) [[:subsection {:title "select"}]] "##### Index:" (fact (select players 0) => #{{:id :a1 :score 10 :info {:name "Bill" :gender :m :nationality :aus}}}) "##### Predicates:" (fact (select players #(= (:id %) :a1)) => #{{:id :a1 :score 10 :info {:name "Bill" :gender :m :nationality :aus}}}) "##### List Predicates:" (fact (select players '(:id (= :a1))) => #{{:id :a1 :score 10 :info {:name "Bill" :gender :m :nationality :aus}}}) "##### Vector Predicates:" (fact (select players [:id :a1]) => #{{:id :a1 :score 10 :info {:name "Bill" :gender :m :nationality :aus}}} (select players [:score even?]) => #{{:id :a1 :score 10 :info {:name "Bill" :gender :m :nationality :aus}} {:id :a5 :score 20 :info {:name "Scott" :gender :m :nationality :usa}}} (select players [:score '(< 13)]) => #{{:id :a1 :score 10 :info {:name "Bill" :gender :m :nationality :aus}} {:id :a4 :score 11 :info {:name "Henry" :gender :m :nationality :usa}}} (select players [:score 13 [:info :gender] :f]) => #{{:id :a9 :score 13 :info {:name "Rose" :gender :f :nationality :aus}}}) "##### Sets:" (fact (select players #{1 2}) => #{{:id :a2 :score 15 :info {:name "John" :gender :m :nationality :aus}} {:id :a3 :score 15 :info {:name "Dave" :gender :m :nationality :aus}}} (select players #{[:score even?] [:score 13 [:info :gender] :f]}) => #{{:id :a1 :score 10 :info {:name "Bill" :gender :m :nationality :aus}} {:id :a5 :score 20 :info {:name "Scott" :gender :m :nationality :usa}} {:id :a9 :score 13 :info {:name "Rose" :gender :f :nationality :aus}}}) [[:subsection {:title "selectv"}]] "`selectv` is the same as `select` except it returns a vector instead of a set." (fact (selectv players #{[:score even?] [:score 13 [:info :gender] :f]}) => (just [{:id :a1 :score 10 :info {:name "Bill" :gender :m :nationality :aus}} {:id :a5 :score 20 :info {:name "Scott" :gender :m :nationality :usa}} {:id :a9 :score 13 :info {:name "Rose" :gender :f :nationality :aus}}] :in-any-order)) [[:subsection {:title "fn"}]] "`ova` implements the `clojure.lang.IFn` interface and so can be called with select parameters. It can be used to return elements within an array. Additionally, if an element has an :id tag, it will search based on the :id tag." (fact (players 0) => {:id :a1 :score 10 :info {:name "Bill" :gender :m :nationality :aus}} (players 1) => {:id :a2 :score 15 :info {:name "John" :gender :m :nationality :aus}} (players :a3) => {:id :a3 :score 15 :info {:name "Dave" :gender :m :nationality :aus}} (:a3 players) => {:id :a3 :score 15 :info {:name "Dave" :gender :m :nationality :aus}} (ov :a10) => nil) [[:section {:title "Array Operations"}]] [[:subsection {:title "append!"}]] "`append!` adds additional elements to the end:" (fact (<< (append! (ova [1 2 3 4]) 5 6 7 8)) => [1 2 3 4 5 6 7 8]) [[:subsection {:title "concat!"}]] "`concat!` joins an array at the end:" (fact (<< (concat! (ova [1 2 3 4]) [5 6 7 8])) => [1 2 3 4 5 6 7 8]) [[:subsection {:title "insert!"}]] "`insert!` allows elements to be inserted." (fact (<< (insert! (ova [:a :b :c :e :f]) :d 3)) => [:a :b :c :d :e :f]) [[:subsection {:title "empty!"}]] "`empty!` clears all elements" (fact (<< (empty! (ova [:a :b :c :d]))) => []) [[:subsection {:title "remove!"}]] "`remove!` will selectively remove elements from the `ova`. The query syntax can be used" (fact (<< (remove! (ova [:a :b :c :d]) '(= :a))) => [:b :c :d] (<< (remove! (ova [1 2 3 4 5 6 7 8 9]) #{'(< 3) '(> 6)})) => [3 4 5 6]) [[:subsection {:title "filter!"}]] "`filter!` performs the opposite of `remove!`. It will keep all elements in the array that matches the query." (fact (<< (filter! (ova [:a :b :c :d]) '(= :a))) => [:a] (<< (filter! (ova [1 2 3 4 5 6 7 8 9]) #{'(< 3) '(> 6)})) => [1 2 7 8 9]) [[:subsection {:title "sort!"}]] "`sort!` arranges the array in order of the comparator. It can take only a comparator, or a selector/comparator combination." (fact (<< (sort! (ova [9 8 7 6 5 4 3 2 1]) <)) => [1 2 3 4 5 6 7 8 9] (<< (sort! (ova [1 2 3 4 5 6 7 8 9]) identity >)) => [9 8 7 6 5 4 3 2 1]) [[:subsection {:title "reverse!"}]] "`reverse!` arranges array elements in reverse" (fact (<< (reverse! (ova [1 2 3 4 5 6 7 8 9]))) => [9 8 7 6 5 4 3 2 1]) [[:section {:title "Element Operations"}]] "Element operations are specific to manipulating the elements within the array." [[:subsection {:title "!!"}]] "`!!` sets the value of all selected indices to a specified value." (fact (<< (!! (ova [1 2 3 4 5 6 7 8 9]) 0 0)) => [0 2 3 4 5 6 7 8 9] (<< (!! (ova [1 2 3 4 5 6 7 8 9]) odd? 0)) => [0 2 0 4 0 6 0 8 0] (<< (!! (ova [1 2 3 4 5 6 7 8 9]) '(> 4) 0)) => [1 2 3 4 0 0 0 0 0]) [[:subsection {:title "map!"}]] "`map!` performs an operation on every element." (fact (<< (map! (ova [1 2 3 4 5 6 7 8 9]) inc)) => [2 3 4 5 6 7 8 9 10]) [[:subsection {:title "smap!"}]] "`smap!` performs an operation only on selected elements" (fact (<< (smap! (ova [1 2 3 4 5 6 7 8 9]) odd? inc)) => [2 2 4 4 6 6 8 8 10]) [[:subsection {:title "map-indexed!"}]] "`map-indexed!` performs an operation with the element index as the second parameter on every element" (fact (<< (map-indexed! (ova [1 2 3 4 5 6 7 8 9]) +)) => [1 3 5 7 9 11 13 15 17]) [[:subsection {:title "smap-indexed!"}]] "`smap-indexed!` performs an operation with the element index as the second parameter on selected elements" (fact (<< (smap-indexed! (ova [1 2 3 4 5 6 7 8 9]) odd? +)) => [1 2 5 4 9 6 13 8 17]) [[:subsection {:title "!>"}]] "The threading array performs a series of operations on selected elements." (fact (<< (!> (ova [1 2 3 4 5 6 7 8 9]) odd? (* 10) (+ 5))) => [15 2 35 4 55 6 75 8 95]) [[:section {:title "Element Watch" :tag "element-watch-2"}]] "Watches can be set up so that. Instead of a normal ref/atom watch where there are four inputs to the watch function, the Element watch requires an additional input to distinguish which array a change has occured. The function signature looks like:" (comment (fn [k o r p v] ;; key, ova, ref, prev, current (... do something ...))) [[:subsection {:title "get-elem-watch"}]] "`get-elem-watches` takes as input an `ova` and returns a map of element watches and their keys." [[:subsection {:title "add-elem-watch"}]] "`add-elem-watch` adds a watch function on all elements of an `ova`." (fact (def ov (ova [1 2 3 4])) (def watch (atom [])) (def cj-fn (fn [k o r p v] ;; key, ova, ref, prev, current (swap! watch conj [p v]))) (watch/add ov :conj cj-fn) ;; add watch (keys (watch/list ov)) ;; get watches => [:conj] (<< (map! ov + 10)) ;; elements in ov are manipulated => [11 12 13 14] (sort @watch) => [[1 11] [2 12] [3 13] [4 14]]) ;; watch is also changed [[:subsection {:title "remove-elem-watch"}]] "`remove-elem-watch` cleares the element watch function to a `ova`." (fact (watch/clear ov :conj) (keys (watch/list ov)) => nil) [[:subsection {:title "add-elem-change-watch"}]] "`add-elem-change-watch` only updates when part of the array changes. This is a really useful abstraction when the element is a big nested map. This is the same as `add-elem-watch` though an additional selector is needed to determine if the expected part of the element has change. Its usage can be seen in the [example](#scoreboard-example)"
18241
(ns documentation.hara-concurrent-ova.api (:use midje.sweet) (:require [hara.concurrent.ova :refer :all] [hara.common.watch :as watch])) [[:section {:title "Basics"}]] [[:subsection {:title "ova"}]] "An `ova` deals with data in a vector. The data can be anything but it is recommended that the data are clojure maps." (fact (def ov (ova [1 2 3 4])) (def ov (ova [{:id :a1 :score 10 :name "<NAME>" :gender :m :nationality :aus} {:id :a2 :score 15 :name "<NAME>" :gender :m :nationality :aus}])) (def ov (ova [{:type "form" :data {:sex :m :age 23}} {:type "form" :data {:sex :f :age 24}}]))) [[:subsection {:title "persistent!"}]] "Since `ova.core.Ova` implements the `clojure.lang.ITransientCollection` interface, it can be made persistent with `persistent!`." (fact (persistent! (ova [1 2 3 4])) => [1 2 3 4]) [[:subsection {:title "init!"}]] "`init!` resets the data elements in an ova to another set of values. Any change in the ova requires it to be wrapped in a `dosync` macro." (fact (def ov (ova [1 2 3 4])) (dosync (init! ov [5 6 7 8 9])) (persistent! ov) => [5 6 7 8 9]) [[:subsection {:title "<<"}]] "The output macro is a shorthand for outputting the value of `ova` after a series of transformations. There is an implicit `dosync` block within the macro." (fact (<< (def ov (ova [1 2 3 4])) (init! ov [5 6 7 8 9])) => [5 6 7 8 9]) [[:section {:title "Clojure"}]] "Built-in operations supported including (but not limited to): - `map`, `reduce`, `first`, `next`, `nth` and many more `seq` operations - `get`, `contains?` - `deref` - `add-watch`, `remove-watch` - `pop!`, `push!`, `conj!` " [[:section {:title "Query"}]] "Where ova shines is in the various ways that elements can be selected. It is best to define some data that can be queried:" (def players (ova [{:id :a1 :score 10 :info {:name "<NAME>" :gender :m :nationality :aus}} {:id :a2 :score 15 :info {:name "<NAME>" :gender :m :nationality :aus}} {:id :a3 :score 15 :info {:name "<NAME>" :gender :m :nationality :aus}} {:id :a4 :score 11 :info {:name "<NAME>" :gender :m :nationality :usa}} {:id :a5 :score 20 :info {:name "<NAME>" :gender :m :nationality :usa}} {:id :a6 :score 13 :info {:name "<NAME>" :gender :m :nationality :usa}} {:id :a7 :score 15 :info {:name "<NAME>" :gender :f :nationality :aus}} {:id :a8 :score 19 :info {:name "<NAME>" :gender :f :nationality :usa}} {:id :a9 :score 13 :info {:name "<NAME>" :gender :f :nationality :aus}}])) [[:subsection {:title "select"}]] "##### Index:" (fact (select players 0) => #{{:id :a1 :score 10 :info {:name "<NAME>" :gender :m :nationality :aus}}}) "##### Predicates:" (fact (select players #(= (:id %) :a1)) => #{{:id :a1 :score 10 :info {:name "<NAME>" :gender :m :nationality :aus}}}) "##### List Predicates:" (fact (select players '(:id (= :a1))) => #{{:id :a1 :score 10 :info {:name "<NAME>" :gender :m :nationality :aus}}}) "##### Vector Predicates:" (fact (select players [:id :a1]) => #{{:id :a1 :score 10 :info {:name "<NAME>" :gender :m :nationality :aus}}} (select players [:score even?]) => #{{:id :a1 :score 10 :info {:name "<NAME>" :gender :m :nationality :aus}} {:id :a5 :score 20 :info {:name "<NAME>" :gender :m :nationality :usa}}} (select players [:score '(< 13)]) => #{{:id :a1 :score 10 :info {:name "<NAME>" :gender :m :nationality :aus}} {:id :a4 :score 11 :info {:name "<NAME>" :gender :m :nationality :usa}}} (select players [:score 13 [:info :gender] :f]) => #{{:id :a9 :score 13 :info {:name "<NAME>" :gender :f :nationality :aus}}}) "##### Sets:" (fact (select players #{1 2}) => #{{:id :a2 :score 15 :info {:name "<NAME>" :gender :m :nationality :aus}} {:id :a3 :score 15 :info {:name "<NAME>" :gender :m :nationality :aus}}} (select players #{[:score even?] [:score 13 [:info :gender] :f]}) => #{{:id :a1 :score 10 :info {:name "<NAME>" :gender :m :nationality :aus}} {:id :a5 :score 20 :info {:name "<NAME>" :gender :m :nationality :usa}} {:id :a9 :score 13 :info {:name "<NAME>" :gender :f :nationality :aus}}}) [[:subsection {:title "selectv"}]] "`selectv` is the same as `select` except it returns a vector instead of a set." (fact (selectv players #{[:score even?] [:score 13 [:info :gender] :f]}) => (just [{:id :a1 :score 10 :info {:name "<NAME>" :gender :m :nationality :aus}} {:id :a5 :score 20 :info {:name "<NAME>" :gender :m :nationality :usa}} {:id :a9 :score 13 :info {:name "<NAME>" :gender :f :nationality :aus}}] :in-any-order)) [[:subsection {:title "fn"}]] "`ova` implements the `clojure.lang.IFn` interface and so can be called with select parameters. It can be used to return elements within an array. Additionally, if an element has an :id tag, it will search based on the :id tag." (fact (players 0) => {:id :a1 :score 10 :info {:name "<NAME>" :gender :m :nationality :aus}} (players 1) => {:id :a2 :score 15 :info {:name "<NAME>" :gender :m :nationality :aus}} (players :a3) => {:id :a3 :score 15 :info {:name "<NAME>" :gender :m :nationality :aus}} (:a3 players) => {:id :a3 :score 15 :info {:name "<NAME>" :gender :m :nationality :aus}} (ov :a10) => nil) [[:section {:title "Array Operations"}]] [[:subsection {:title "append!"}]] "`append!` adds additional elements to the end:" (fact (<< (append! (ova [1 2 3 4]) 5 6 7 8)) => [1 2 3 4 5 6 7 8]) [[:subsection {:title "concat!"}]] "`concat!` joins an array at the end:" (fact (<< (concat! (ova [1 2 3 4]) [5 6 7 8])) => [1 2 3 4 5 6 7 8]) [[:subsection {:title "insert!"}]] "`insert!` allows elements to be inserted." (fact (<< (insert! (ova [:a :b :c :e :f]) :d 3)) => [:a :b :c :d :e :f]) [[:subsection {:title "empty!"}]] "`empty!` clears all elements" (fact (<< (empty! (ova [:a :b :c :d]))) => []) [[:subsection {:title "remove!"}]] "`remove!` will selectively remove elements from the `ova`. The query syntax can be used" (fact (<< (remove! (ova [:a :b :c :d]) '(= :a))) => [:b :c :d] (<< (remove! (ova [1 2 3 4 5 6 7 8 9]) #{'(< 3) '(> 6)})) => [3 4 5 6]) [[:subsection {:title "filter!"}]] "`filter!` performs the opposite of `remove!`. It will keep all elements in the array that matches the query." (fact (<< (filter! (ova [:a :b :c :d]) '(= :a))) => [:a] (<< (filter! (ova [1 2 3 4 5 6 7 8 9]) #{'(< 3) '(> 6)})) => [1 2 7 8 9]) [[:subsection {:title "sort!"}]] "`sort!` arranges the array in order of the comparator. It can take only a comparator, or a selector/comparator combination." (fact (<< (sort! (ova [9 8 7 6 5 4 3 2 1]) <)) => [1 2 3 4 5 6 7 8 9] (<< (sort! (ova [1 2 3 4 5 6 7 8 9]) identity >)) => [9 8 7 6 5 4 3 2 1]) [[:subsection {:title "reverse!"}]] "`reverse!` arranges array elements in reverse" (fact (<< (reverse! (ova [1 2 3 4 5 6 7 8 9]))) => [9 8 7 6 5 4 3 2 1]) [[:section {:title "Element Operations"}]] "Element operations are specific to manipulating the elements within the array." [[:subsection {:title "!!"}]] "`!!` sets the value of all selected indices to a specified value." (fact (<< (!! (ova [1 2 3 4 5 6 7 8 9]) 0 0)) => [0 2 3 4 5 6 7 8 9] (<< (!! (ova [1 2 3 4 5 6 7 8 9]) odd? 0)) => [0 2 0 4 0 6 0 8 0] (<< (!! (ova [1 2 3 4 5 6 7 8 9]) '(> 4) 0)) => [1 2 3 4 0 0 0 0 0]) [[:subsection {:title "map!"}]] "`map!` performs an operation on every element." (fact (<< (map! (ova [1 2 3 4 5 6 7 8 9]) inc)) => [2 3 4 5 6 7 8 9 10]) [[:subsection {:title "smap!"}]] "`smap!` performs an operation only on selected elements" (fact (<< (smap! (ova [1 2 3 4 5 6 7 8 9]) odd? inc)) => [2 2 4 4 6 6 8 8 10]) [[:subsection {:title "map-indexed!"}]] "`map-indexed!` performs an operation with the element index as the second parameter on every element" (fact (<< (map-indexed! (ova [1 2 3 4 5 6 7 8 9]) +)) => [1 3 5 7 9 11 13 15 17]) [[:subsection {:title "smap-indexed!"}]] "`smap-indexed!` performs an operation with the element index as the second parameter on selected elements" (fact (<< (smap-indexed! (ova [1 2 3 4 5 6 7 8 9]) odd? +)) => [1 2 5 4 9 6 13 8 17]) [[:subsection {:title "!>"}]] "The threading array performs a series of operations on selected elements." (fact (<< (!> (ova [1 2 3 4 5 6 7 8 9]) odd? (* 10) (+ 5))) => [15 2 35 4 55 6 75 8 95]) [[:section {:title "Element Watch" :tag "element-watch-2"}]] "Watches can be set up so that. Instead of a normal ref/atom watch where there are four inputs to the watch function, the Element watch requires an additional input to distinguish which array a change has occured. The function signature looks like:" (comment (fn [k o r p v] ;; key, ova, ref, prev, current (... do something ...))) [[:subsection {:title "get-elem-watch"}]] "`get-elem-watches` takes as input an `ova` and returns a map of element watches and their keys." [[:subsection {:title "add-elem-watch"}]] "`add-elem-watch` adds a watch function on all elements of an `ova`." (fact (def ov (ova [1 2 3 4])) (def watch (atom [])) (def cj-fn (fn [k o r p v] ;; key, ova, ref, prev, current (swap! watch conj [p v]))) (watch/add ov :conj cj-fn) ;; add watch (keys (watch/list ov)) ;; get watches => [:conj] (<< (map! ov + 10)) ;; elements in ov are manipulated => [11 12 13 14] (sort @watch) => [[1 11] [2 12] [3 13] [4 14]]) ;; watch is also changed [[:subsection {:title "remove-elem-watch"}]] "`remove-elem-watch` cleares the element watch function to a `ova`." (fact (watch/clear ov :conj) (keys (watch/list ov)) => nil) [[:subsection {:title "add-elem-change-watch"}]] "`add-elem-change-watch` only updates when part of the array changes. This is a really useful abstraction when the element is a big nested map. This is the same as `add-elem-watch` though an additional selector is needed to determine if the expected part of the element has change. Its usage can be seen in the [example](#scoreboard-example)"
true
(ns documentation.hara-concurrent-ova.api (:use midje.sweet) (:require [hara.concurrent.ova :refer :all] [hara.common.watch :as watch])) [[:section {:title "Basics"}]] [[:subsection {:title "ova"}]] "An `ova` deals with data in a vector. The data can be anything but it is recommended that the data are clojure maps." (fact (def ov (ova [1 2 3 4])) (def ov (ova [{:id :a1 :score 10 :name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus} {:id :a2 :score 15 :name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}])) (def ov (ova [{:type "form" :data {:sex :m :age 23}} {:type "form" :data {:sex :f :age 24}}]))) [[:subsection {:title "persistent!"}]] "Since `ova.core.Ova` implements the `clojure.lang.ITransientCollection` interface, it can be made persistent with `persistent!`." (fact (persistent! (ova [1 2 3 4])) => [1 2 3 4]) [[:subsection {:title "init!"}]] "`init!` resets the data elements in an ova to another set of values. Any change in the ova requires it to be wrapped in a `dosync` macro." (fact (def ov (ova [1 2 3 4])) (dosync (init! ov [5 6 7 8 9])) (persistent! ov) => [5 6 7 8 9]) [[:subsection {:title "<<"}]] "The output macro is a shorthand for outputting the value of `ova` after a series of transformations. There is an implicit `dosync` block within the macro." (fact (<< (def ov (ova [1 2 3 4])) (init! ov [5 6 7 8 9])) => [5 6 7 8 9]) [[:section {:title "Clojure"}]] "Built-in operations supported including (but not limited to): - `map`, `reduce`, `first`, `next`, `nth` and many more `seq` operations - `get`, `contains?` - `deref` - `add-watch`, `remove-watch` - `pop!`, `push!`, `conj!` " [[:section {:title "Query"}]] "Where ova shines is in the various ways that elements can be selected. It is best to define some data that can be queried:" (def players (ova [{:id :a1 :score 10 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}} {:id :a2 :score 15 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}} {:id :a3 :score 15 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}} {:id :a4 :score 11 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :usa}} {:id :a5 :score 20 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :usa}} {:id :a6 :score 13 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :usa}} {:id :a7 :score 15 :info {:name "PI:NAME:<NAME>END_PI" :gender :f :nationality :aus}} {:id :a8 :score 19 :info {:name "PI:NAME:<NAME>END_PI" :gender :f :nationality :usa}} {:id :a9 :score 13 :info {:name "PI:NAME:<NAME>END_PI" :gender :f :nationality :aus}}])) [[:subsection {:title "select"}]] "##### Index:" (fact (select players 0) => #{{:id :a1 :score 10 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}}}) "##### Predicates:" (fact (select players #(= (:id %) :a1)) => #{{:id :a1 :score 10 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}}}) "##### List Predicates:" (fact (select players '(:id (= :a1))) => #{{:id :a1 :score 10 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}}}) "##### Vector Predicates:" (fact (select players [:id :a1]) => #{{:id :a1 :score 10 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}}} (select players [:score even?]) => #{{:id :a1 :score 10 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}} {:id :a5 :score 20 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :usa}}} (select players [:score '(< 13)]) => #{{:id :a1 :score 10 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}} {:id :a4 :score 11 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :usa}}} (select players [:score 13 [:info :gender] :f]) => #{{:id :a9 :score 13 :info {:name "PI:NAME:<NAME>END_PI" :gender :f :nationality :aus}}}) "##### Sets:" (fact (select players #{1 2}) => #{{:id :a2 :score 15 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}} {:id :a3 :score 15 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}}} (select players #{[:score even?] [:score 13 [:info :gender] :f]}) => #{{:id :a1 :score 10 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}} {:id :a5 :score 20 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :usa}} {:id :a9 :score 13 :info {:name "PI:NAME:<NAME>END_PI" :gender :f :nationality :aus}}}) [[:subsection {:title "selectv"}]] "`selectv` is the same as `select` except it returns a vector instead of a set." (fact (selectv players #{[:score even?] [:score 13 [:info :gender] :f]}) => (just [{:id :a1 :score 10 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}} {:id :a5 :score 20 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :usa}} {:id :a9 :score 13 :info {:name "PI:NAME:<NAME>END_PI" :gender :f :nationality :aus}}] :in-any-order)) [[:subsection {:title "fn"}]] "`ova` implements the `clojure.lang.IFn` interface and so can be called with select parameters. It can be used to return elements within an array. Additionally, if an element has an :id tag, it will search based on the :id tag." (fact (players 0) => {:id :a1 :score 10 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}} (players 1) => {:id :a2 :score 15 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}} (players :a3) => {:id :a3 :score 15 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}} (:a3 players) => {:id :a3 :score 15 :info {:name "PI:NAME:<NAME>END_PI" :gender :m :nationality :aus}} (ov :a10) => nil) [[:section {:title "Array Operations"}]] [[:subsection {:title "append!"}]] "`append!` adds additional elements to the end:" (fact (<< (append! (ova [1 2 3 4]) 5 6 7 8)) => [1 2 3 4 5 6 7 8]) [[:subsection {:title "concat!"}]] "`concat!` joins an array at the end:" (fact (<< (concat! (ova [1 2 3 4]) [5 6 7 8])) => [1 2 3 4 5 6 7 8]) [[:subsection {:title "insert!"}]] "`insert!` allows elements to be inserted." (fact (<< (insert! (ova [:a :b :c :e :f]) :d 3)) => [:a :b :c :d :e :f]) [[:subsection {:title "empty!"}]] "`empty!` clears all elements" (fact (<< (empty! (ova [:a :b :c :d]))) => []) [[:subsection {:title "remove!"}]] "`remove!` will selectively remove elements from the `ova`. The query syntax can be used" (fact (<< (remove! (ova [:a :b :c :d]) '(= :a))) => [:b :c :d] (<< (remove! (ova [1 2 3 4 5 6 7 8 9]) #{'(< 3) '(> 6)})) => [3 4 5 6]) [[:subsection {:title "filter!"}]] "`filter!` performs the opposite of `remove!`. It will keep all elements in the array that matches the query." (fact (<< (filter! (ova [:a :b :c :d]) '(= :a))) => [:a] (<< (filter! (ova [1 2 3 4 5 6 7 8 9]) #{'(< 3) '(> 6)})) => [1 2 7 8 9]) [[:subsection {:title "sort!"}]] "`sort!` arranges the array in order of the comparator. It can take only a comparator, or a selector/comparator combination." (fact (<< (sort! (ova [9 8 7 6 5 4 3 2 1]) <)) => [1 2 3 4 5 6 7 8 9] (<< (sort! (ova [1 2 3 4 5 6 7 8 9]) identity >)) => [9 8 7 6 5 4 3 2 1]) [[:subsection {:title "reverse!"}]] "`reverse!` arranges array elements in reverse" (fact (<< (reverse! (ova [1 2 3 4 5 6 7 8 9]))) => [9 8 7 6 5 4 3 2 1]) [[:section {:title "Element Operations"}]] "Element operations are specific to manipulating the elements within the array." [[:subsection {:title "!!"}]] "`!!` sets the value of all selected indices to a specified value." (fact (<< (!! (ova [1 2 3 4 5 6 7 8 9]) 0 0)) => [0 2 3 4 5 6 7 8 9] (<< (!! (ova [1 2 3 4 5 6 7 8 9]) odd? 0)) => [0 2 0 4 0 6 0 8 0] (<< (!! (ova [1 2 3 4 5 6 7 8 9]) '(> 4) 0)) => [1 2 3 4 0 0 0 0 0]) [[:subsection {:title "map!"}]] "`map!` performs an operation on every element." (fact (<< (map! (ova [1 2 3 4 5 6 7 8 9]) inc)) => [2 3 4 5 6 7 8 9 10]) [[:subsection {:title "smap!"}]] "`smap!` performs an operation only on selected elements" (fact (<< (smap! (ova [1 2 3 4 5 6 7 8 9]) odd? inc)) => [2 2 4 4 6 6 8 8 10]) [[:subsection {:title "map-indexed!"}]] "`map-indexed!` performs an operation with the element index as the second parameter on every element" (fact (<< (map-indexed! (ova [1 2 3 4 5 6 7 8 9]) +)) => [1 3 5 7 9 11 13 15 17]) [[:subsection {:title "smap-indexed!"}]] "`smap-indexed!` performs an operation with the element index as the second parameter on selected elements" (fact (<< (smap-indexed! (ova [1 2 3 4 5 6 7 8 9]) odd? +)) => [1 2 5 4 9 6 13 8 17]) [[:subsection {:title "!>"}]] "The threading array performs a series of operations on selected elements." (fact (<< (!> (ova [1 2 3 4 5 6 7 8 9]) odd? (* 10) (+ 5))) => [15 2 35 4 55 6 75 8 95]) [[:section {:title "Element Watch" :tag "element-watch-2"}]] "Watches can be set up so that. Instead of a normal ref/atom watch where there are four inputs to the watch function, the Element watch requires an additional input to distinguish which array a change has occured. The function signature looks like:" (comment (fn [k o r p v] ;; key, ova, ref, prev, current (... do something ...))) [[:subsection {:title "get-elem-watch"}]] "`get-elem-watches` takes as input an `ova` and returns a map of element watches and their keys." [[:subsection {:title "add-elem-watch"}]] "`add-elem-watch` adds a watch function on all elements of an `ova`." (fact (def ov (ova [1 2 3 4])) (def watch (atom [])) (def cj-fn (fn [k o r p v] ;; key, ova, ref, prev, current (swap! watch conj [p v]))) (watch/add ov :conj cj-fn) ;; add watch (keys (watch/list ov)) ;; get watches => [:conj] (<< (map! ov + 10)) ;; elements in ov are manipulated => [11 12 13 14] (sort @watch) => [[1 11] [2 12] [3 13] [4 14]]) ;; watch is also changed [[:subsection {:title "remove-elem-watch"}]] "`remove-elem-watch` cleares the element watch function to a `ova`." (fact (watch/clear ov :conj) (keys (watch/list ov)) => nil) [[:subsection {:title "add-elem-change-watch"}]] "`add-elem-change-watch` only updates when part of the array changes. This is a really useful abstraction when the element is a big nested map. This is the same as `add-elem-watch` though an additional selector is needed to determine if the expected part of the element has change. Its usage can be seen in the [example](#scoreboard-example)"
[ { "context": "otal\n; count is meaningful.\n;\n; # References\n;\n; - Mehta, Cyrus R., and Pralay Senchaudhuri. \"Conditional ", "end": 538, "score": 0.9998681545257568, "start": 533, "tag": "NAME", "value": "Mehta" }, { "context": "count is meaningful.\n;\n; # References\n;\n; - Mehta, Cyrus R., and Pralay Senchaudhuri. \"Conditional versus un", "end": 547, "score": 0.999865710735321, "start": 540, "tag": "NAME", "value": "Cyrus R" }, { "context": "ngful.\n;\n; # References\n;\n; - Mehta, Cyrus R., and Pralay Senchaudhuri. \"Conditional versus unconditional exact tests fo", "end": 573, "score": 0.9998722076416016, "start": 554, "tag": "NAME", "value": "Pralay Senchaudhuri" } ]
FisherExactTest/fisher_exact_test.clj
gyk/TrivialSolutions
2
; Fisher's Exact Test ; =================== ; ; The left-upper cell follows Fisher's noncentral hypergeometric distribution, and when conditioned ; on the total, under the null hypothesis it degenerates to a hypergeometric distribution which no ; longer depends on the nuisance parameter $\pi$. ; ; Note that odds ratio = 1 is (roughly speaking) equivalent to conditioning on the total ; "responders", as under the null hypothesis the two types are all the same therefore only the total ; count is meaningful. ; ; # References ; ; - Mehta, Cyrus R., and Pralay Senchaudhuri. "Conditional versus unconditional exact tests for ; comparing two binomials." Cytel Software Corporation 675 (2003): 1-5. (WARNING: some mistakes in ; the paper.) ; - Does Fisher's Exact test for a 2×2 table use the Non-central Hypergeometric or the ; Hypergeometric distribution? (<https://stats.stackexchange.com/q/259494>) ; - <https://en.wikipedia.org/wiki/Fisher%27s_exact_test#Controversies> (defn binomial-coeff "Computes the value of `choose(n, k)`." [n k] (let [k (min k (- n k)) num (apply *' (range (inc (- n k)) (inc n))) denum (apply *' (range 1 (inc k)))] (/ num denum))) (defn hypergeometric-distribution "Returns a high-order function that transforms `x` to `choose(r, x) * choose(N - r, n - x) / choose(N, n)`" [r n N] (fn [x] (/ (* (binomial-coeff r x) (binomial-coeff (- N r) (- n x))) (binomial-coeff N n)))) (defn hypergeometric-distribution' "Similar to `hypergeometric-distribution` but tries to avoid arithmetic overflow at the expense of precision." [r n N] (fn [x] (Math/exp (+ (Math/log (binomial-coeff r x)) (Math/log (binomial-coeff (- N r) (- n x))) (- (Math/log (binomial-coeff N n))))))) ; The table is arranged like this: ; ; | - | X1 | X2 | ; |:--:|:--:|:--:| ; |*Y1*| a | b | ; |*Y2*| c | d | ; ; ; The probability is `(a + b)! (c + d)! (a + c)! (b + d)! / (a! b! c! d! (a + b + c + d)!)`. Due to ; the symmetry of the problem, rotating/swapping rows/swapping columns of the table does not change ; the probability. (defn rearrange "Rearranges the table for easier computation." [tbl] (letfn [(swap-rows [[a b c d :as t]] (if (> (+ a c) (+ b d)) [b a d c] t)) (swap-cols [[a b c d :as t]] (if (> (/ (float a) c) (/ (float b) d)) [c d a b] t))] (-> tbl swap-rows swap-cols))) ; NOTE: Only two-tailed minimum likelihood interval is supported. (defn fisher-exact-test "Returns the p-value of the test." [a b c d] (let [[a b c d] (rearrange [a b c d]) distr (hypergeometric-distribution (+ a b) (+ a c) (+ a b c d)) p (distr a) p-left (reduce + (map distr (range 0 a))) p-right (reduce + (for [x (range (+ a c) a -1) :let [p' (distr x)] :while (<= p' p)] p'))] ; For debugging, comment it out later. (do (prn "p = " (float p)) (prn "p-left = " (float p-left)) (prn "p-right = " (float p-right))) (float (+ p-left p p-right)))) ; ================================ (defn- approx= [lhs rhs] (< (Math/abs (- lhs rhs)) 1e-4)) (assert (approx= (fisher-exact-test 1 9 11 3) 0.002759)) (assert (approx= (fisher-exact-test 7 12 0 5) 0.272069)) (assert (approx= (fisher-exact-test 2 31 136 15532) 0.033903)) (assert (approx= (fisher-exact-test 4 1 20 1) 0.353846))
109930
; Fisher's Exact Test ; =================== ; ; The left-upper cell follows Fisher's noncentral hypergeometric distribution, and when conditioned ; on the total, under the null hypothesis it degenerates to a hypergeometric distribution which no ; longer depends on the nuisance parameter $\pi$. ; ; Note that odds ratio = 1 is (roughly speaking) equivalent to conditioning on the total ; "responders", as under the null hypothesis the two types are all the same therefore only the total ; count is meaningful. ; ; # References ; ; - <NAME>, <NAME>., and <NAME>. "Conditional versus unconditional exact tests for ; comparing two binomials." Cytel Software Corporation 675 (2003): 1-5. (WARNING: some mistakes in ; the paper.) ; - Does Fisher's Exact test for a 2×2 table use the Non-central Hypergeometric or the ; Hypergeometric distribution? (<https://stats.stackexchange.com/q/259494>) ; - <https://en.wikipedia.org/wiki/Fisher%27s_exact_test#Controversies> (defn binomial-coeff "Computes the value of `choose(n, k)`." [n k] (let [k (min k (- n k)) num (apply *' (range (inc (- n k)) (inc n))) denum (apply *' (range 1 (inc k)))] (/ num denum))) (defn hypergeometric-distribution "Returns a high-order function that transforms `x` to `choose(r, x) * choose(N - r, n - x) / choose(N, n)`" [r n N] (fn [x] (/ (* (binomial-coeff r x) (binomial-coeff (- N r) (- n x))) (binomial-coeff N n)))) (defn hypergeometric-distribution' "Similar to `hypergeometric-distribution` but tries to avoid arithmetic overflow at the expense of precision." [r n N] (fn [x] (Math/exp (+ (Math/log (binomial-coeff r x)) (Math/log (binomial-coeff (- N r) (- n x))) (- (Math/log (binomial-coeff N n))))))) ; The table is arranged like this: ; ; | - | X1 | X2 | ; |:--:|:--:|:--:| ; |*Y1*| a | b | ; |*Y2*| c | d | ; ; ; The probability is `(a + b)! (c + d)! (a + c)! (b + d)! / (a! b! c! d! (a + b + c + d)!)`. Due to ; the symmetry of the problem, rotating/swapping rows/swapping columns of the table does not change ; the probability. (defn rearrange "Rearranges the table for easier computation." [tbl] (letfn [(swap-rows [[a b c d :as t]] (if (> (+ a c) (+ b d)) [b a d c] t)) (swap-cols [[a b c d :as t]] (if (> (/ (float a) c) (/ (float b) d)) [c d a b] t))] (-> tbl swap-rows swap-cols))) ; NOTE: Only two-tailed minimum likelihood interval is supported. (defn fisher-exact-test "Returns the p-value of the test." [a b c d] (let [[a b c d] (rearrange [a b c d]) distr (hypergeometric-distribution (+ a b) (+ a c) (+ a b c d)) p (distr a) p-left (reduce + (map distr (range 0 a))) p-right (reduce + (for [x (range (+ a c) a -1) :let [p' (distr x)] :while (<= p' p)] p'))] ; For debugging, comment it out later. (do (prn "p = " (float p)) (prn "p-left = " (float p-left)) (prn "p-right = " (float p-right))) (float (+ p-left p p-right)))) ; ================================ (defn- approx= [lhs rhs] (< (Math/abs (- lhs rhs)) 1e-4)) (assert (approx= (fisher-exact-test 1 9 11 3) 0.002759)) (assert (approx= (fisher-exact-test 7 12 0 5) 0.272069)) (assert (approx= (fisher-exact-test 2 31 136 15532) 0.033903)) (assert (approx= (fisher-exact-test 4 1 20 1) 0.353846))
true
; Fisher's Exact Test ; =================== ; ; The left-upper cell follows Fisher's noncentral hypergeometric distribution, and when conditioned ; on the total, under the null hypothesis it degenerates to a hypergeometric distribution which no ; longer depends on the nuisance parameter $\pi$. ; ; Note that odds ratio = 1 is (roughly speaking) equivalent to conditioning on the total ; "responders", as under the null hypothesis the two types are all the same therefore only the total ; count is meaningful. ; ; # References ; ; - PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI., and PI:NAME:<NAME>END_PI. "Conditional versus unconditional exact tests for ; comparing two binomials." Cytel Software Corporation 675 (2003): 1-5. (WARNING: some mistakes in ; the paper.) ; - Does Fisher's Exact test for a 2×2 table use the Non-central Hypergeometric or the ; Hypergeometric distribution? (<https://stats.stackexchange.com/q/259494>) ; - <https://en.wikipedia.org/wiki/Fisher%27s_exact_test#Controversies> (defn binomial-coeff "Computes the value of `choose(n, k)`." [n k] (let [k (min k (- n k)) num (apply *' (range (inc (- n k)) (inc n))) denum (apply *' (range 1 (inc k)))] (/ num denum))) (defn hypergeometric-distribution "Returns a high-order function that transforms `x` to `choose(r, x) * choose(N - r, n - x) / choose(N, n)`" [r n N] (fn [x] (/ (* (binomial-coeff r x) (binomial-coeff (- N r) (- n x))) (binomial-coeff N n)))) (defn hypergeometric-distribution' "Similar to `hypergeometric-distribution` but tries to avoid arithmetic overflow at the expense of precision." [r n N] (fn [x] (Math/exp (+ (Math/log (binomial-coeff r x)) (Math/log (binomial-coeff (- N r) (- n x))) (- (Math/log (binomial-coeff N n))))))) ; The table is arranged like this: ; ; | - | X1 | X2 | ; |:--:|:--:|:--:| ; |*Y1*| a | b | ; |*Y2*| c | d | ; ; ; The probability is `(a + b)! (c + d)! (a + c)! (b + d)! / (a! b! c! d! (a + b + c + d)!)`. Due to ; the symmetry of the problem, rotating/swapping rows/swapping columns of the table does not change ; the probability. (defn rearrange "Rearranges the table for easier computation." [tbl] (letfn [(swap-rows [[a b c d :as t]] (if (> (+ a c) (+ b d)) [b a d c] t)) (swap-cols [[a b c d :as t]] (if (> (/ (float a) c) (/ (float b) d)) [c d a b] t))] (-> tbl swap-rows swap-cols))) ; NOTE: Only two-tailed minimum likelihood interval is supported. (defn fisher-exact-test "Returns the p-value of the test." [a b c d] (let [[a b c d] (rearrange [a b c d]) distr (hypergeometric-distribution (+ a b) (+ a c) (+ a b c d)) p (distr a) p-left (reduce + (map distr (range 0 a))) p-right (reduce + (for [x (range (+ a c) a -1) :let [p' (distr x)] :while (<= p' p)] p'))] ; For debugging, comment it out later. (do (prn "p = " (float p)) (prn "p-left = " (float p-left)) (prn "p-right = " (float p-right))) (float (+ p-left p p-right)))) ; ================================ (defn- approx= [lhs rhs] (< (Math/abs (- lhs rhs)) 1e-4)) (assert (approx= (fisher-exact-test 1 9 11 3) 0.002759)) (assert (approx= (fisher-exact-test 7 12 0 5) 0.272069)) (assert (approx= (fisher-exact-test 2 31 136 15532) 0.033903)) (assert (approx= (fisher-exact-test 4 1 20 1) 0.353846))
[ { "context": "ties\n {:hiding #{}\n :auth\n {:KEY (.getBytes \"s49628MbrU8VoG8Q\")\n :MACKEY (.getBytes \"R4A6bX69a4NU68xK\")}})\n\n", "end": 167, "score": 0.994594395160675, "start": 151, "tag": "KEY", "value": "s49628MbrU8VoG8Q" }, { "context": "Bytes \"s49628MbrU8VoG8Q\")\n :MACKEY (.getBytes \"R4A6bX69a4NU68xK\")}})\n\n(def properties\n (if (file-exists? propert", "end": 210, "score": 0.9955219030380249, "start": 194, "tag": "KEY", "value": "R4A6bX69a4NU68xK" } ]
src/ontrail/conf.clj
jrosti/ontrail
1
(ns ontrail.conf (:use ontrail.utils)) (def properties-file "properties.clj") (def default-properties {:hiding #{} :auth {:KEY (.getBytes "s49628MbrU8VoG8Q") :MACKEY (.getBytes "R4A6bX69a4NU68xK")}}) (def properties (if (file-exists? properties-file) (eval (read-string (slurp properties-file))) default-properties))
48854
(ns ontrail.conf (:use ontrail.utils)) (def properties-file "properties.clj") (def default-properties {:hiding #{} :auth {:KEY (.getBytes "<KEY>") :MACKEY (.getBytes "<KEY>")}}) (def properties (if (file-exists? properties-file) (eval (read-string (slurp properties-file))) default-properties))
true
(ns ontrail.conf (:use ontrail.utils)) (def properties-file "properties.clj") (def default-properties {:hiding #{} :auth {:KEY (.getBytes "PI:KEY:<KEY>END_PI") :MACKEY (.getBytes "PI:KEY:<KEY>END_PI")}}) (def properties (if (file-exists? properties-file) (eval (read-string (slurp properties-file))) default-properties))
[ { "context": ";;; Copyright 2011 Howard M. Lewis Ship\n;;;\n;;; Licensed under the Apache License, Versio", "end": 39, "score": 0.9998646974563599, "start": 19, "tag": "NAME", "value": "Howard M. Lewis Ship" } ]
src/cascade/request.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.request "Functions used to initialize a Cascade application and process requests." (:import [java.util Calendar Date] [java.text Format]) (:require [ring.util [response :as ring] [mime-type :as mime-type]] [ring.middleware.file-info :as file-info]) (:use [compojure core] [cascade dom asset import exception])) (defn asset-handler "Internal handler for asset requests. Returns the response from the handler, or nil if no handler matches the name. asset-factories Maps keywords for the asset domain (eg., :file or :classpath) to the factory function (which takes a path) domain Keyword used to locate factory function path String path passed to the handler." [asset-factories domain path] (let [factory (domain asset-factories) asset (and factory (factory path)) stream (and asset (content-stream asset))] (if stream (-> (ring/response stream) (ring/header "Expires" (@asset-configuration :expiration)) (ring/content-type (get-content-type asset)))))) (defn- now-plus-ten-years "Returns a string representation of the current Date plus ten years, used for setting expiration date of assets." [] (let [^Format format (file-info/make-http-format)] (->> (doto (Calendar/getInstance) (.add Calendar/YEAR 10)) .getTime (.format format)))) (def placeholder-routes "Returns a placeholder request handling function that always returns nil." (routes)) (defn wrap-serialize-html "Wraps a handler that produces a seq of DOM nodes (e.g., one created via defview or template) so that the returned dom-nodes are converted into a seq of strings (the markup to be streamed to the client)." [handler] (fn [req] (let [response (handler req)] (and response (update-in response [:body] serialize-html))))) (defn wrap-html-markup "Wraps the handler (which renders a request to DOM nodes) with full rendering support, including imports." [handler] (-> handler wrap-imports wrap-serialize-html)) (defn render-report-exception [req exception] ((-> (fn [req] (exception-report req exception)) wrap-imports wrap-serialize-html) req)) (defn wrap-exception-reporting "Middleware for standard Cascade exception reporting; exceptions are caught and reported using the Cascade exception report view." [handler] (fn [req] (try (handler req) (catch Exception e (render-report-exception req e))))) (defn initialize "Initializes asset handling for Cascade. This sets an application version (a value incorporated into URLs, which should change with each new deployment. Named arguments: :html-routes Routes that produce full-page rendered HTML markup. The provided handlers should render the request to a seq of DOM nodes. :virtual-folder (default \"assets\") The root folder under which assets will be exposed to the client. :public-folder (default \"public\") The file system folder under which file assets are stored. May be an absolute path, should not end with a slash. :file-extensions Additional file-extension to MIME type mappings, beyond the default set (defined by ring.util.mime-type/default-mime-types). :asset-factories Additional asset dispatcher mappings. Keys are domain keywords, values are functions that accept a path within that domain. The functions should construct and return a cascade.asset/Asset. Default support for the :file and :classpath domains." [application-version & {:keys [virtual-folder public-folder file-extensions asset-factories html-routes] :or {virtual-folder "assets" public-folder "public"}}] (let [root (str "/" virtual-folder "/" application-version) asset-factories (merge {:file file-asset :classpath classpath-asset} asset-factories)] (reset! asset-configuration {:application-version application-version :expiration (now-plus-ten-years) :public-folder public-folder :assets-folder root :file-extensions (merge mime-type/default-mime-types file-extensions)}) (printf "Initialized asset access at virtual folder %s\n" root) (-> (routes (GET [(str root "/:domain/:path") :path #".*"] [domain path] (asset-handler asset-factories (keyword domain) path)) (wrap-html-markup (or html-routes placeholder-routes))) wrap-exception-reporting)))
106588
;;; 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.request "Functions used to initialize a Cascade application and process requests." (:import [java.util Calendar Date] [java.text Format]) (:require [ring.util [response :as ring] [mime-type :as mime-type]] [ring.middleware.file-info :as file-info]) (:use [compojure core] [cascade dom asset import exception])) (defn asset-handler "Internal handler for asset requests. Returns the response from the handler, or nil if no handler matches the name. asset-factories Maps keywords for the asset domain (eg., :file or :classpath) to the factory function (which takes a path) domain Keyword used to locate factory function path String path passed to the handler." [asset-factories domain path] (let [factory (domain asset-factories) asset (and factory (factory path)) stream (and asset (content-stream asset))] (if stream (-> (ring/response stream) (ring/header "Expires" (@asset-configuration :expiration)) (ring/content-type (get-content-type asset)))))) (defn- now-plus-ten-years "Returns a string representation of the current Date plus ten years, used for setting expiration date of assets." [] (let [^Format format (file-info/make-http-format)] (->> (doto (Calendar/getInstance) (.add Calendar/YEAR 10)) .getTime (.format format)))) (def placeholder-routes "Returns a placeholder request handling function that always returns nil." (routes)) (defn wrap-serialize-html "Wraps a handler that produces a seq of DOM nodes (e.g., one created via defview or template) so that the returned dom-nodes are converted into a seq of strings (the markup to be streamed to the client)." [handler] (fn [req] (let [response (handler req)] (and response (update-in response [:body] serialize-html))))) (defn wrap-html-markup "Wraps the handler (which renders a request to DOM nodes) with full rendering support, including imports." [handler] (-> handler wrap-imports wrap-serialize-html)) (defn render-report-exception [req exception] ((-> (fn [req] (exception-report req exception)) wrap-imports wrap-serialize-html) req)) (defn wrap-exception-reporting "Middleware for standard Cascade exception reporting; exceptions are caught and reported using the Cascade exception report view." [handler] (fn [req] (try (handler req) (catch Exception e (render-report-exception req e))))) (defn initialize "Initializes asset handling for Cascade. This sets an application version (a value incorporated into URLs, which should change with each new deployment. Named arguments: :html-routes Routes that produce full-page rendered HTML markup. The provided handlers should render the request to a seq of DOM nodes. :virtual-folder (default \"assets\") The root folder under which assets will be exposed to the client. :public-folder (default \"public\") The file system folder under which file assets are stored. May be an absolute path, should not end with a slash. :file-extensions Additional file-extension to MIME type mappings, beyond the default set (defined by ring.util.mime-type/default-mime-types). :asset-factories Additional asset dispatcher mappings. Keys are domain keywords, values are functions that accept a path within that domain. The functions should construct and return a cascade.asset/Asset. Default support for the :file and :classpath domains." [application-version & {:keys [virtual-folder public-folder file-extensions asset-factories html-routes] :or {virtual-folder "assets" public-folder "public"}}] (let [root (str "/" virtual-folder "/" application-version) asset-factories (merge {:file file-asset :classpath classpath-asset} asset-factories)] (reset! asset-configuration {:application-version application-version :expiration (now-plus-ten-years) :public-folder public-folder :assets-folder root :file-extensions (merge mime-type/default-mime-types file-extensions)}) (printf "Initialized asset access at virtual folder %s\n" root) (-> (routes (GET [(str root "/:domain/:path") :path #".*"] [domain path] (asset-handler asset-factories (keyword domain) path)) (wrap-html-markup (or html-routes placeholder-routes))) wrap-exception-reporting)))
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.request "Functions used to initialize a Cascade application and process requests." (:import [java.util Calendar Date] [java.text Format]) (:require [ring.util [response :as ring] [mime-type :as mime-type]] [ring.middleware.file-info :as file-info]) (:use [compojure core] [cascade dom asset import exception])) (defn asset-handler "Internal handler for asset requests. Returns the response from the handler, or nil if no handler matches the name. asset-factories Maps keywords for the asset domain (eg., :file or :classpath) to the factory function (which takes a path) domain Keyword used to locate factory function path String path passed to the handler." [asset-factories domain path] (let [factory (domain asset-factories) asset (and factory (factory path)) stream (and asset (content-stream asset))] (if stream (-> (ring/response stream) (ring/header "Expires" (@asset-configuration :expiration)) (ring/content-type (get-content-type asset)))))) (defn- now-plus-ten-years "Returns a string representation of the current Date plus ten years, used for setting expiration date of assets." [] (let [^Format format (file-info/make-http-format)] (->> (doto (Calendar/getInstance) (.add Calendar/YEAR 10)) .getTime (.format format)))) (def placeholder-routes "Returns a placeholder request handling function that always returns nil." (routes)) (defn wrap-serialize-html "Wraps a handler that produces a seq of DOM nodes (e.g., one created via defview or template) so that the returned dom-nodes are converted into a seq of strings (the markup to be streamed to the client)." [handler] (fn [req] (let [response (handler req)] (and response (update-in response [:body] serialize-html))))) (defn wrap-html-markup "Wraps the handler (which renders a request to DOM nodes) with full rendering support, including imports." [handler] (-> handler wrap-imports wrap-serialize-html)) (defn render-report-exception [req exception] ((-> (fn [req] (exception-report req exception)) wrap-imports wrap-serialize-html) req)) (defn wrap-exception-reporting "Middleware for standard Cascade exception reporting; exceptions are caught and reported using the Cascade exception report view." [handler] (fn [req] (try (handler req) (catch Exception e (render-report-exception req e))))) (defn initialize "Initializes asset handling for Cascade. This sets an application version (a value incorporated into URLs, which should change with each new deployment. Named arguments: :html-routes Routes that produce full-page rendered HTML markup. The provided handlers should render the request to a seq of DOM nodes. :virtual-folder (default \"assets\") The root folder under which assets will be exposed to the client. :public-folder (default \"public\") The file system folder under which file assets are stored. May be an absolute path, should not end with a slash. :file-extensions Additional file-extension to MIME type mappings, beyond the default set (defined by ring.util.mime-type/default-mime-types). :asset-factories Additional asset dispatcher mappings. Keys are domain keywords, values are functions that accept a path within that domain. The functions should construct and return a cascade.asset/Asset. Default support for the :file and :classpath domains." [application-version & {:keys [virtual-folder public-folder file-extensions asset-factories html-routes] :or {virtual-folder "assets" public-folder "public"}}] (let [root (str "/" virtual-folder "/" application-version) asset-factories (merge {:file file-asset :classpath classpath-asset} asset-factories)] (reset! asset-configuration {:application-version application-version :expiration (now-plus-ten-years) :public-folder public-folder :assets-folder root :file-extensions (merge mime-type/default-mime-types file-extensions)}) (printf "Initialized asset access at virtual folder %s\n" root) (-> (routes (GET [(str root "/:domain/:path") :path #".*"] [domain path] (asset-handler asset-factories (keyword domain) path)) (wrap-html-markup (or html-routes placeholder-routes))) wrap-exception-reporting)))
[ { "context": "er the MIT license\n\n; Copyright (c) 2014 - 2018 by Burkhardt Renz THM. All rights reserved.\n; The use and distribut", "end": 181, "score": 0.9998886585235596, "start": 167, "tag": "NAME", "value": "Burkhardt Renz" }, { "context": " to the Kodkod constraint solver.\"\n :author \"Burkhardt Renz, THM\"}\nlwb.pred.kic\n (:refer-clojure :exclude [a", "end": 708, "score": 0.999885618686676, "start": 694, "tag": "NAME", "value": "Burkhardt Renz" } ]
src/lwb/pred/kic.clj
esb-lwb/lwb
22
; kic - Kodkod in Clojure ; based on the Kodkod Constraint Solver, see http://emina.github.io/kodkod/ ; licensed under the MIT license ; Copyright (c) 2014 - 2018 by 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) ; 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 "An ultra-thin wrapper to the Kodkod constraint solver." :author "Burkhardt Renz, THM"} lwb.pred.kic (:refer-clojure :exclude [and or not some]) (:require [clojure.set :as set]) (:import (kodkod.ast Formula Expression Decls Variable Relation) (kodkod.instance Universe Bounds Tuple TupleSet TupleFactory) (kodkod.engine Solver Solution) (java.util Collection))) ;; ##Universe (defn universe "A Kodkod Universe from the given vector of items." [set] (Universe. ^Collection set)) ;; ##Instances (defn factory "A Kodkod TupleFactory for the given universe." [universe] (.factory universe)) (defn bounds "A Kodkod bounds object for the given universe." [universe] (Bounds. universe)) ;; ##Relations (defn relation "A Kodkod relation with the given `name` and `arity'." [name arity] (Relation/nary name arity)) (defn make-const "A Kodkod relation for a const or nullary function with corresponding bounds." [key factory bounds] (let [r (Relation/unary (name key)) ts (.setOf factory (to-array [key])) _ (.boundExactly bounds r ts)] [(symbol (name key)) r])) (defn make-pred "A Kodkod relation for a predicate with corresponding bounds." [key arity factory bounds] (let [r (Relation/nary (name key) arity) ts (.allOf ^TupleFactory factory arity) _ (.bound bounds r ts)] [(symbol (name key)) r])) (defn make-func "A Kodkod relation for a function with corresponding bounds. A function is represented as a relation where the last component is the result of the function applied to the elements of the other components." [key arity factory bounds] (let [ar (inc arity) r (Relation/nary (name key) ar) ts (.allOf factory ar) _ (.bound bounds r ts)] [(symbol (name key)) r])) (defn make-prop "A Kodkod relation for a proposition with corresponding bounds. A proposition is represented in Kodkod as unary relation with atmost 1 element. If the relation is empty, the value of the proposition is false, true if there is an element in the relation." [key factory bounds] (let [r (Relation/unary (name key)) lower (.noneOf factory 1) upper (.setOf factory (to-array [(first (.universe bounds))])) _ (.bound bounds r lower upper)] [(symbol (name key)) r])) ;; ##Operators in kic (defn not "(not fml), the negation of fml." [^Formula fml] (.not fml)) (defn and "(and & fmls), the conjunction of the given fmls " [& fmls] (Formula/and ^"[Lkodkod.ast.Formula;" (into-array Formula fmls))) (defn or "(or & fmls), the disjunction of the given fmls" [& fmls] (Formula/or ^"[Lkodkod.ast.Formula;" (into-array Formula fmls))) (defn impl "(impl fml1 fml2), the implication fml1 -> fml2." [^Formula fml1 ^Formula fml2] (.implies fml1 fml2)) (defn equiv "(equiv fml1 fml2), the equivalence of the given fmls" [^Formula fml1 ^Formula fml2] (.iff fml1 fml2)) (defn xor "(xor fml1 fml2), exclusive or of the given fmls" [^Formula fml1 ^Formula fml2] (.not (.iff fml1 fml2))) (defn ite "(ite fml fml1 fml2), if then else" [^Formula fml ^Formula fml1 ^Formula fml2] (.and (.implies fml fml1) (.implies (.not fml) fml2))) (def TRUE "TRUE, truth, i.e. the constant fml TRUE." Formula/TRUE) (def FALSE "FALSE, contradiction, i.e. the constant fml FALSE." Formula/FALSE) ;; ##Predicates for expressions (defn eq "(eq expr1 expr2), expressing whether expr1 equals expr2." [^Expression expr1 ^Expression expr2] (.eq expr1 expr2)) (defn in "(in expr1 expr2), expressing whether expr1 is a subset of expr2." [^Expression expr1 ^Expression expr2] (.in expr1 expr2)) (defn one "(one expr), expressing whether expr has exactly one tuple." [^Expression expr] (.one expr)) ;; ##Operators for expressions (defn join "(join expr1 expr2), the dotjoin of the arguments." [^Expression expr1 ^Expression expr2] (.join expr1 expr2)) (defn product "(product expr1 ...), the product of the arguments." [& exprs] (Expression/product ^"[Lkodkod.ast.Expression;" (into-array Expression exprs))) ;; ##Declarations (defn variable "(variable var-name), constructs a variable of arity 1." [var-name] (Variable/unary (name var-name))) (defn decls "(decls decl & more-decls), the combined decls from the arguments." [decl & more-decls] (reduce #(.and ^Decls %1 ^Decls %2) decl more-decls)) (defn decl "(decl variable) -> (decl variable UNIV :one)." [^Variable variable] (.oneOf variable Expression/UNIV)) ;; ##Quantors (defn forall "`fml` holds for all variables in `var-vec` with values from the universe, e.g. `(forall [x y] (pred x y))`." [var-vec fml] (let [d (apply decls (map decl var-vec))] (.forAll fml d))) (defn exists "There exists elements in the universe such that `fml` holds for them, e.g. `(exists [x y] (pred x y))`." [var-vec fml] (let [d (apply decls (map decl var-vec))] (.forSome fml d))) ;; ##Running Kodkod (defn solve "(solve formula bounds) -> a kodkod.engine.Solution" [formula bounds] (let [solver (Solver.)] (.solve solver formula bounds))) (defn solve-all [formula bounds] (let [solver (Solver.)] (doto (.options solver) (.setSymmetryBreaking 0)) (iterator-seq (.solveAll solver formula bounds)))) ; Translating a Kodkod solution into Clojure data structures (defn vector-from-tpl "vector <- kodkod.instance.Tuple" [^Tuple tpl] (vec (for [i (range 0 (.arity tpl))] (let [atom (.atom tpl i)] (if (symbol? atom) (keyword atom) atom))))) ; kodkod.instance.TupleSet -> set of vectors (defn vecset-from-ts "set of vectors <- kodkod.instance.TupleSet" [^TupleSet ts] (set (map vector-from-tpl ts))) ; kodkod's Map<Relation, TupleSet> -> map of (relation name, set of vectors) (defn relmap-from-instmap "map of (relation symbol, set of tuples) from kodkod's instance" [instmap] (let [keys (for [^Relation r (keys instmap)] (symbol (.name r))), vals (for [^TupleSet t (vals instmap)] (vecset-from-ts t))] ; a witness for a variable in an existential quantified formula is marked with a beginning $ in Kodkod, ; it's not really a part of the result. (into {} (filter #(not= \$ (first (name (key %)))) (zipmap keys vals))))) ; Universe from the tuples of the solution (defn univ "Set of items from a Kodkod Universe" [^Universe universe] (->> universe (map #(if (symbol? %) (identity %) (keyword %))) (set) (hash-map :univ) )) ; kodkod.engine.Solution -> map of universe and relations (defn model "Model satisfying the kic spec" [^Universe universe ^Solution solution] (if (.sat solution) (let [relmap (relmap-from-instmap (.relationTuples (.instance solution)))] (into relmap (univ universe)))))
2032
; kic - Kodkod in Clojure ; based on the Kodkod Constraint Solver, see http://emina.github.io/kodkod/ ; licensed under the MIT license ; Copyright (c) 2014 - 2018 by <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) ; 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 "An ultra-thin wrapper to the Kodkod constraint solver." :author "<NAME>, THM"} lwb.pred.kic (:refer-clojure :exclude [and or not some]) (:require [clojure.set :as set]) (:import (kodkod.ast Formula Expression Decls Variable Relation) (kodkod.instance Universe Bounds Tuple TupleSet TupleFactory) (kodkod.engine Solver Solution) (java.util Collection))) ;; ##Universe (defn universe "A Kodkod Universe from the given vector of items." [set] (Universe. ^Collection set)) ;; ##Instances (defn factory "A Kodkod TupleFactory for the given universe." [universe] (.factory universe)) (defn bounds "A Kodkod bounds object for the given universe." [universe] (Bounds. universe)) ;; ##Relations (defn relation "A Kodkod relation with the given `name` and `arity'." [name arity] (Relation/nary name arity)) (defn make-const "A Kodkod relation for a const or nullary function with corresponding bounds." [key factory bounds] (let [r (Relation/unary (name key)) ts (.setOf factory (to-array [key])) _ (.boundExactly bounds r ts)] [(symbol (name key)) r])) (defn make-pred "A Kodkod relation for a predicate with corresponding bounds." [key arity factory bounds] (let [r (Relation/nary (name key) arity) ts (.allOf ^TupleFactory factory arity) _ (.bound bounds r ts)] [(symbol (name key)) r])) (defn make-func "A Kodkod relation for a function with corresponding bounds. A function is represented as a relation where the last component is the result of the function applied to the elements of the other components." [key arity factory bounds] (let [ar (inc arity) r (Relation/nary (name key) ar) ts (.allOf factory ar) _ (.bound bounds r ts)] [(symbol (name key)) r])) (defn make-prop "A Kodkod relation for a proposition with corresponding bounds. A proposition is represented in Kodkod as unary relation with atmost 1 element. If the relation is empty, the value of the proposition is false, true if there is an element in the relation." [key factory bounds] (let [r (Relation/unary (name key)) lower (.noneOf factory 1) upper (.setOf factory (to-array [(first (.universe bounds))])) _ (.bound bounds r lower upper)] [(symbol (name key)) r])) ;; ##Operators in kic (defn not "(not fml), the negation of fml." [^Formula fml] (.not fml)) (defn and "(and & fmls), the conjunction of the given fmls " [& fmls] (Formula/and ^"[Lkodkod.ast.Formula;" (into-array Formula fmls))) (defn or "(or & fmls), the disjunction of the given fmls" [& fmls] (Formula/or ^"[Lkodkod.ast.Formula;" (into-array Formula fmls))) (defn impl "(impl fml1 fml2), the implication fml1 -> fml2." [^Formula fml1 ^Formula fml2] (.implies fml1 fml2)) (defn equiv "(equiv fml1 fml2), the equivalence of the given fmls" [^Formula fml1 ^Formula fml2] (.iff fml1 fml2)) (defn xor "(xor fml1 fml2), exclusive or of the given fmls" [^Formula fml1 ^Formula fml2] (.not (.iff fml1 fml2))) (defn ite "(ite fml fml1 fml2), if then else" [^Formula fml ^Formula fml1 ^Formula fml2] (.and (.implies fml fml1) (.implies (.not fml) fml2))) (def TRUE "TRUE, truth, i.e. the constant fml TRUE." Formula/TRUE) (def FALSE "FALSE, contradiction, i.e. the constant fml FALSE." Formula/FALSE) ;; ##Predicates for expressions (defn eq "(eq expr1 expr2), expressing whether expr1 equals expr2." [^Expression expr1 ^Expression expr2] (.eq expr1 expr2)) (defn in "(in expr1 expr2), expressing whether expr1 is a subset of expr2." [^Expression expr1 ^Expression expr2] (.in expr1 expr2)) (defn one "(one expr), expressing whether expr has exactly one tuple." [^Expression expr] (.one expr)) ;; ##Operators for expressions (defn join "(join expr1 expr2), the dotjoin of the arguments." [^Expression expr1 ^Expression expr2] (.join expr1 expr2)) (defn product "(product expr1 ...), the product of the arguments." [& exprs] (Expression/product ^"[Lkodkod.ast.Expression;" (into-array Expression exprs))) ;; ##Declarations (defn variable "(variable var-name), constructs a variable of arity 1." [var-name] (Variable/unary (name var-name))) (defn decls "(decls decl & more-decls), the combined decls from the arguments." [decl & more-decls] (reduce #(.and ^Decls %1 ^Decls %2) decl more-decls)) (defn decl "(decl variable) -> (decl variable UNIV :one)." [^Variable variable] (.oneOf variable Expression/UNIV)) ;; ##Quantors (defn forall "`fml` holds for all variables in `var-vec` with values from the universe, e.g. `(forall [x y] (pred x y))`." [var-vec fml] (let [d (apply decls (map decl var-vec))] (.forAll fml d))) (defn exists "There exists elements in the universe such that `fml` holds for them, e.g. `(exists [x y] (pred x y))`." [var-vec fml] (let [d (apply decls (map decl var-vec))] (.forSome fml d))) ;; ##Running Kodkod (defn solve "(solve formula bounds) -> a kodkod.engine.Solution" [formula bounds] (let [solver (Solver.)] (.solve solver formula bounds))) (defn solve-all [formula bounds] (let [solver (Solver.)] (doto (.options solver) (.setSymmetryBreaking 0)) (iterator-seq (.solveAll solver formula bounds)))) ; Translating a Kodkod solution into Clojure data structures (defn vector-from-tpl "vector <- kodkod.instance.Tuple" [^Tuple tpl] (vec (for [i (range 0 (.arity tpl))] (let [atom (.atom tpl i)] (if (symbol? atom) (keyword atom) atom))))) ; kodkod.instance.TupleSet -> set of vectors (defn vecset-from-ts "set of vectors <- kodkod.instance.TupleSet" [^TupleSet ts] (set (map vector-from-tpl ts))) ; kodkod's Map<Relation, TupleSet> -> map of (relation name, set of vectors) (defn relmap-from-instmap "map of (relation symbol, set of tuples) from kodkod's instance" [instmap] (let [keys (for [^Relation r (keys instmap)] (symbol (.name r))), vals (for [^TupleSet t (vals instmap)] (vecset-from-ts t))] ; a witness for a variable in an existential quantified formula is marked with a beginning $ in Kodkod, ; it's not really a part of the result. (into {} (filter #(not= \$ (first (name (key %)))) (zipmap keys vals))))) ; Universe from the tuples of the solution (defn univ "Set of items from a Kodkod Universe" [^Universe universe] (->> universe (map #(if (symbol? %) (identity %) (keyword %))) (set) (hash-map :univ) )) ; kodkod.engine.Solution -> map of universe and relations (defn model "Model satisfying the kic spec" [^Universe universe ^Solution solution] (if (.sat solution) (let [relmap (relmap-from-instmap (.relationTuples (.instance solution)))] (into relmap (univ universe)))))
true
; kic - Kodkod in Clojure ; based on the Kodkod Constraint Solver, see http://emina.github.io/kodkod/ ; licensed under the MIT license ; Copyright (c) 2014 - 2018 by 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) ; 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 "An ultra-thin wrapper to the Kodkod constraint solver." :author "PI:NAME:<NAME>END_PI, THM"} lwb.pred.kic (:refer-clojure :exclude [and or not some]) (:require [clojure.set :as set]) (:import (kodkod.ast Formula Expression Decls Variable Relation) (kodkod.instance Universe Bounds Tuple TupleSet TupleFactory) (kodkod.engine Solver Solution) (java.util Collection))) ;; ##Universe (defn universe "A Kodkod Universe from the given vector of items." [set] (Universe. ^Collection set)) ;; ##Instances (defn factory "A Kodkod TupleFactory for the given universe." [universe] (.factory universe)) (defn bounds "A Kodkod bounds object for the given universe." [universe] (Bounds. universe)) ;; ##Relations (defn relation "A Kodkod relation with the given `name` and `arity'." [name arity] (Relation/nary name arity)) (defn make-const "A Kodkod relation for a const or nullary function with corresponding bounds." [key factory bounds] (let [r (Relation/unary (name key)) ts (.setOf factory (to-array [key])) _ (.boundExactly bounds r ts)] [(symbol (name key)) r])) (defn make-pred "A Kodkod relation for a predicate with corresponding bounds." [key arity factory bounds] (let [r (Relation/nary (name key) arity) ts (.allOf ^TupleFactory factory arity) _ (.bound bounds r ts)] [(symbol (name key)) r])) (defn make-func "A Kodkod relation for a function with corresponding bounds. A function is represented as a relation where the last component is the result of the function applied to the elements of the other components." [key arity factory bounds] (let [ar (inc arity) r (Relation/nary (name key) ar) ts (.allOf factory ar) _ (.bound bounds r ts)] [(symbol (name key)) r])) (defn make-prop "A Kodkod relation for a proposition with corresponding bounds. A proposition is represented in Kodkod as unary relation with atmost 1 element. If the relation is empty, the value of the proposition is false, true if there is an element in the relation." [key factory bounds] (let [r (Relation/unary (name key)) lower (.noneOf factory 1) upper (.setOf factory (to-array [(first (.universe bounds))])) _ (.bound bounds r lower upper)] [(symbol (name key)) r])) ;; ##Operators in kic (defn not "(not fml), the negation of fml." [^Formula fml] (.not fml)) (defn and "(and & fmls), the conjunction of the given fmls " [& fmls] (Formula/and ^"[Lkodkod.ast.Formula;" (into-array Formula fmls))) (defn or "(or & fmls), the disjunction of the given fmls" [& fmls] (Formula/or ^"[Lkodkod.ast.Formula;" (into-array Formula fmls))) (defn impl "(impl fml1 fml2), the implication fml1 -> fml2." [^Formula fml1 ^Formula fml2] (.implies fml1 fml2)) (defn equiv "(equiv fml1 fml2), the equivalence of the given fmls" [^Formula fml1 ^Formula fml2] (.iff fml1 fml2)) (defn xor "(xor fml1 fml2), exclusive or of the given fmls" [^Formula fml1 ^Formula fml2] (.not (.iff fml1 fml2))) (defn ite "(ite fml fml1 fml2), if then else" [^Formula fml ^Formula fml1 ^Formula fml2] (.and (.implies fml fml1) (.implies (.not fml) fml2))) (def TRUE "TRUE, truth, i.e. the constant fml TRUE." Formula/TRUE) (def FALSE "FALSE, contradiction, i.e. the constant fml FALSE." Formula/FALSE) ;; ##Predicates for expressions (defn eq "(eq expr1 expr2), expressing whether expr1 equals expr2." [^Expression expr1 ^Expression expr2] (.eq expr1 expr2)) (defn in "(in expr1 expr2), expressing whether expr1 is a subset of expr2." [^Expression expr1 ^Expression expr2] (.in expr1 expr2)) (defn one "(one expr), expressing whether expr has exactly one tuple." [^Expression expr] (.one expr)) ;; ##Operators for expressions (defn join "(join expr1 expr2), the dotjoin of the arguments." [^Expression expr1 ^Expression expr2] (.join expr1 expr2)) (defn product "(product expr1 ...), the product of the arguments." [& exprs] (Expression/product ^"[Lkodkod.ast.Expression;" (into-array Expression exprs))) ;; ##Declarations (defn variable "(variable var-name), constructs a variable of arity 1." [var-name] (Variable/unary (name var-name))) (defn decls "(decls decl & more-decls), the combined decls from the arguments." [decl & more-decls] (reduce #(.and ^Decls %1 ^Decls %2) decl more-decls)) (defn decl "(decl variable) -> (decl variable UNIV :one)." [^Variable variable] (.oneOf variable Expression/UNIV)) ;; ##Quantors (defn forall "`fml` holds for all variables in `var-vec` with values from the universe, e.g. `(forall [x y] (pred x y))`." [var-vec fml] (let [d (apply decls (map decl var-vec))] (.forAll fml d))) (defn exists "There exists elements in the universe such that `fml` holds for them, e.g. `(exists [x y] (pred x y))`." [var-vec fml] (let [d (apply decls (map decl var-vec))] (.forSome fml d))) ;; ##Running Kodkod (defn solve "(solve formula bounds) -> a kodkod.engine.Solution" [formula bounds] (let [solver (Solver.)] (.solve solver formula bounds))) (defn solve-all [formula bounds] (let [solver (Solver.)] (doto (.options solver) (.setSymmetryBreaking 0)) (iterator-seq (.solveAll solver formula bounds)))) ; Translating a Kodkod solution into Clojure data structures (defn vector-from-tpl "vector <- kodkod.instance.Tuple" [^Tuple tpl] (vec (for [i (range 0 (.arity tpl))] (let [atom (.atom tpl i)] (if (symbol? atom) (keyword atom) atom))))) ; kodkod.instance.TupleSet -> set of vectors (defn vecset-from-ts "set of vectors <- kodkod.instance.TupleSet" [^TupleSet ts] (set (map vector-from-tpl ts))) ; kodkod's Map<Relation, TupleSet> -> map of (relation name, set of vectors) (defn relmap-from-instmap "map of (relation symbol, set of tuples) from kodkod's instance" [instmap] (let [keys (for [^Relation r (keys instmap)] (symbol (.name r))), vals (for [^TupleSet t (vals instmap)] (vecset-from-ts t))] ; a witness for a variable in an existential quantified formula is marked with a beginning $ in Kodkod, ; it's not really a part of the result. (into {} (filter #(not= \$ (first (name (key %)))) (zipmap keys vals))))) ; Universe from the tuples of the solution (defn univ "Set of items from a Kodkod Universe" [^Universe universe] (->> universe (map #(if (symbol? %) (identity %) (keyword %))) (set) (hash-map :univ) )) ; kodkod.engine.Solution -> map of universe and relations (defn model "Model satisfying the kic spec" [^Universe universe ^Solution solution] (if (.sat solution) (let [relmap (relmap-from-instmap (.relationTuples (.instance solution)))] (into relmap (univ universe)))))
[ { "context": ";; Copyright (c) Rich Hickey and contributors. All rights reserved.\n;; The u", "end": 30, "score": 0.9998530745506287, "start": 19, "tag": "NAME", "value": "Rich Hickey" } ]
server/target/clojure/core/async/impl/timers.clj
OctavioBR/healthcheck
0
;; Copyright (c) Rich Hickey and contributors. 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 ^{:skip-wiki true} clojure.core.async.impl.timers (:require [clojure.core.async.impl.protocols :as impl] [clojure.core.async.impl.channels :as channels]) (:import [java.util.concurrent DelayQueue Delayed TimeUnit ConcurrentSkipListMap])) (set! *warn-on-reflection* true) (defonce ^:private ^DelayQueue timeouts-queue (DelayQueue.)) (defonce ^:private ^ConcurrentSkipListMap timeouts-map (ConcurrentSkipListMap.)) (def ^:const TIMEOUT_RESOLUTION_MS 10) (deftype TimeoutQueueEntry [channel ^long timestamp] Delayed (getDelay [this time-unit] (.convert time-unit (- timestamp (System/currentTimeMillis)) TimeUnit/MILLISECONDS)) (compareTo [this other] (let [ostamp (.timestamp ^TimeoutQueueEntry other)] (if (< timestamp ostamp) -1 (if (= timestamp ostamp) 0 1)))) impl/Channel (close! [this] (impl/close! channel))) (defn timeout "returns a channel that will close after msecs" [^long msecs] (let [timeout (+ (System/currentTimeMillis) msecs) me (.ceilingEntry timeouts-map timeout)] (or (when (and me (< (.getKey me) (+ timeout TIMEOUT_RESOLUTION_MS))) (.channel ^TimeoutQueueEntry (.getValue me))) (let [timeout-channel (channels/chan nil) timeout-entry (TimeoutQueueEntry. timeout-channel timeout)] (.put timeouts-map timeout timeout-entry) (.put timeouts-queue timeout-entry) timeout-channel)))) (defn- timeout-worker [] (let [q timeouts-queue] (loop [] (let [^TimeoutQueueEntry tqe (.take q)] (.remove timeouts-map (.timestamp tqe) tqe) (impl/close! tqe)) (recur)))) (defonce timeout-daemon (doto (Thread. ^Runnable timeout-worker "clojure.core.async.timers/timeout-daemon") (.setDaemon true) (.start)))
52471
;; Copyright (c) <NAME> and contributors. 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 ^{:skip-wiki true} clojure.core.async.impl.timers (:require [clojure.core.async.impl.protocols :as impl] [clojure.core.async.impl.channels :as channels]) (:import [java.util.concurrent DelayQueue Delayed TimeUnit ConcurrentSkipListMap])) (set! *warn-on-reflection* true) (defonce ^:private ^DelayQueue timeouts-queue (DelayQueue.)) (defonce ^:private ^ConcurrentSkipListMap timeouts-map (ConcurrentSkipListMap.)) (def ^:const TIMEOUT_RESOLUTION_MS 10) (deftype TimeoutQueueEntry [channel ^long timestamp] Delayed (getDelay [this time-unit] (.convert time-unit (- timestamp (System/currentTimeMillis)) TimeUnit/MILLISECONDS)) (compareTo [this other] (let [ostamp (.timestamp ^TimeoutQueueEntry other)] (if (< timestamp ostamp) -1 (if (= timestamp ostamp) 0 1)))) impl/Channel (close! [this] (impl/close! channel))) (defn timeout "returns a channel that will close after msecs" [^long msecs] (let [timeout (+ (System/currentTimeMillis) msecs) me (.ceilingEntry timeouts-map timeout)] (or (when (and me (< (.getKey me) (+ timeout TIMEOUT_RESOLUTION_MS))) (.channel ^TimeoutQueueEntry (.getValue me))) (let [timeout-channel (channels/chan nil) timeout-entry (TimeoutQueueEntry. timeout-channel timeout)] (.put timeouts-map timeout timeout-entry) (.put timeouts-queue timeout-entry) timeout-channel)))) (defn- timeout-worker [] (let [q timeouts-queue] (loop [] (let [^TimeoutQueueEntry tqe (.take q)] (.remove timeouts-map (.timestamp tqe) tqe) (impl/close! tqe)) (recur)))) (defonce timeout-daemon (doto (Thread. ^Runnable timeout-worker "clojure.core.async.timers/timeout-daemon") (.setDaemon true) (.start)))
true
;; Copyright (c) PI:NAME:<NAME>END_PI and contributors. 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 ^{:skip-wiki true} clojure.core.async.impl.timers (:require [clojure.core.async.impl.protocols :as impl] [clojure.core.async.impl.channels :as channels]) (:import [java.util.concurrent DelayQueue Delayed TimeUnit ConcurrentSkipListMap])) (set! *warn-on-reflection* true) (defonce ^:private ^DelayQueue timeouts-queue (DelayQueue.)) (defonce ^:private ^ConcurrentSkipListMap timeouts-map (ConcurrentSkipListMap.)) (def ^:const TIMEOUT_RESOLUTION_MS 10) (deftype TimeoutQueueEntry [channel ^long timestamp] Delayed (getDelay [this time-unit] (.convert time-unit (- timestamp (System/currentTimeMillis)) TimeUnit/MILLISECONDS)) (compareTo [this other] (let [ostamp (.timestamp ^TimeoutQueueEntry other)] (if (< timestamp ostamp) -1 (if (= timestamp ostamp) 0 1)))) impl/Channel (close! [this] (impl/close! channel))) (defn timeout "returns a channel that will close after msecs" [^long msecs] (let [timeout (+ (System/currentTimeMillis) msecs) me (.ceilingEntry timeouts-map timeout)] (or (when (and me (< (.getKey me) (+ timeout TIMEOUT_RESOLUTION_MS))) (.channel ^TimeoutQueueEntry (.getValue me))) (let [timeout-channel (channels/chan nil) timeout-entry (TimeoutQueueEntry. timeout-channel timeout)] (.put timeouts-map timeout timeout-entry) (.put timeouts-queue timeout-entry) timeout-channel)))) (defn- timeout-worker [] (let [q timeouts-queue] (loop [] (let [^TimeoutQueueEntry tqe (.take q)] (.remove timeouts-map (.timestamp tqe) tqe) (impl/close! tqe)) (recur)))) (defonce timeout-daemon (doto (Thread. ^Runnable timeout-worker "clojure.core.async.timers/timeout-daemon") (.setDaemon true) (.start)))
[ { "context": "other deva in hand\"\n (doseq [deva [\"Aghora\" \"Sadyojata\" \"Vamadeva\"]]\n (do-game\n (new-gam", "end": 4417, "score": 0.6666630506515503, "start": 4408, "tag": "NAME", "value": "Sadyojata" }, { "context": "n hand\"\n (doseq [deva [\"Aghora\" \"Sadyojata\" \"Vamadeva\"]]\n (do-game\n (new-game {:runner ", "end": 4428, "score": 0.653896689414978, "start": 4420, "tag": "NAME", "value": "Vamadeva" }, { "context": "state :corp)\n (play-from-hand state :runner \"Aghora\")\n (run-on state \"HQ\")\n (rez state :cor", "end": 5509, "score": 0.7020031809806824, "start": 5503, "tag": "NAME", "value": "Aghora" }, { "context": " break ability worked\"))))\n\n(deftest algernon\n ;; Algernon - pay 2 credits to gain a click, trash if no s", "end": 6240, "score": 0.8194321393966675, "start": 6235, "tag": "NAME", "value": "Alger" }, { "context": "n\"\n (do-game\n (new-game {:runner {:deck [\"Algernon\"]}})\n (take-credits state :corp)\n (play", "end": 6392, "score": 0.7982708811759949, "start": 6384, "tag": "NAME", "value": "Algernon" }, { "context": "state :corp)\n (play-from-hand state :runner \"Algernon\")\n (take-credits state :runner)\n (take-", "end": 6476, "score": 0.9480640888214111, "start": 6468, "tag": "NAME", "value": "Algernon" }, { "context": " (get-runner))) \"No cards trashed\")\n (is (= \"Algernon\" (:title (get-program state 0))) \"Algernon ", "end": 7010, "score": 0.5368631482124329, "start": 7008, "tag": "NAME", "value": "Al" }, { "context": "n\"\n (do-game\n (new-game {:runner {:deck [\"Algernon\"]}})\n (take-credits state :corp)\n (play", "end": 7171, "score": 0.9970995783805847, "start": 7163, "tag": "NAME", "value": "Algernon" }, { "context": "state :corp)\n (play-from-hand state :runner \"Algernon\")\n (take-credits state :runner)\n (take-", "end": 7255, "score": 0.9980066418647766, "start": 7247, "tag": "NAME", "value": "Algernon" }, { "context": "n\"\n (do-game\n (new-game {:runner {:deck [\"Algernon\"]}})\n (take-credits state :corp)\n (play", "end": 7957, "score": 0.9968035817146301, "start": 7949, "tag": "NAME", "value": "Algernon" }, { "context": "state :corp)\n (play-from-hand state :runner \"Algernon\")\n (take-credits state :runner)\n (take-", "end": 8041, "score": 0.997523307800293, "start": 8033, "tag": "NAME", "value": "Algernon" }, { "context": " should be back in hand\")))))\n\n(deftest atman\n ;; Atman\n (testing \"Installing with 0 power counters\"\n", "end": 16727, "score": 0.9315089583396912, "start": 16725, "tag": "NAME", "value": "At" }, { "context": "s\"\n (do-game\n (new-game {:runner {:deck [\"Atman\"]}})\n (take-credits state :corp)\n (play", "end": 16829, "score": 0.9762557744979858, "start": 16824, "tag": "NAME", "value": "Atman" }, { "context": "state :corp)\n (play-from-hand state :runner \"Atman\")\n (click-prompt state :runner \"0\")\n (i", "end": 16910, "score": 0.9668565988540649, "start": 16905, "tag": "NAME", "value": "Atman" }, { "context": "s\"\n (do-game\n (new-game {:runner {:deck [\"Atman\"]}})\n (take-credits state :corp)\n (play", "end": 17268, "score": 0.9326395988464355, "start": 17263, "tag": "NAME", "value": "Atman" }, { "context": "o-game\n (new-game {:runner {:deck [\"Bankroll\" \"Jak Sinclair\"]}})\n (take-credits state :corp)\n (core/gai", "end": 21472, "score": 0.9986237287521362, "start": 21460, "tag": "NAME", "value": "Jak Sinclair" }, { "context": "er \"Bankroll\")\n (play-from-hand state :runner \"Jak Sinclair\")\n (is (= 3 (core/available-mu state)) \"Bankro", "end": 21642, "score": 0.9946855306625366, "start": 21630, "tag": "NAME", "value": "Jak Sinclair" }, { "context": "Bankroll was trashed\"))))\n\n(deftest berserker\n ;; Berserker\n (do-game\n (new-game {:corp {:deck [(qty \"", "end": 22987, "score": 0.811126708984375, "start": 22981, "tag": "NAME", "value": "Berser" }, { "context": " :credits 100}\n :runner {:hand [\"Berserker\"]}})\n (play-from-hand state :corp \"Ice Wall\" \"", "end": 23187, "score": 0.9953354001045227, "start": 23178, "tag": "NAME", "value": "Berserker" }, { "context": "s state :corp)\n (play-from-hand state :runner \"Berserker\")\n (let [berserker (get-program state 0)]\n ", "end": 23554, "score": 0.9883133172988892, "start": 23545, "tag": "NAME", "value": "Berserker" }, { "context": "r \"Brahman\")\n (play-from-hand state :runner \"Paricia\")\n (play-from-hand state :runner \"Cache\")\n ", "end": 31105, "score": 0.9997622966766357, "start": 31098, "tag": "NAME", "value": "Paricia" }, { "context": "r \"Paricia\")\n (play-from-hand state :runner \"Cache\")\n (core/gain state :runner :credit 1)\n ", "end": 31150, "score": 0.9365400671958923, "start": 31145, "tag": "NAME", "value": "Cache" }, { "context": "R\"\n (do-game\n (new-game {:runner {:deck [\"Brahman\" \"Paricia\"]}\n :corp {:deck [\"Spid", "end": 31955, "score": 0.9997707009315491, "start": 31948, "tag": "NAME", "value": "Brahman" }, { "context": "-game\n (new-game {:runner {:deck [\"Brahman\" \"Paricia\"]}\n :corp {:deck [\"Spiderweb\"]}})", "end": 31965, "score": 0.9996993541717529, "start": 31958, "tag": "NAME", "value": "Paricia" }, { "context": "state :corp)\n (play-from-hand state :runner \"Brahman\")\n (play-from-hand state :runner \"Paricia\")\n", "end": 32145, "score": 0.99973464012146, "start": 32138, "tag": "NAME", "value": "Brahman" }, { "context": "r \"Brahman\")\n (play-from-hand state :runner \"Paricia\")\n (let [brah (get-program state 0)\n ", "end": 32192, "score": 0.9995703101158142, "start": 32185, "tag": "NAME", "value": "Paricia" }, { "context": "\"Nisei MK II\"]}\n :runner {:deck [\"Brahman\"]}})\n (play-from-hand state :corp \"Ice Wall\"", "end": 32947, "score": 0.998981237411499, "start": 32940, "tag": "NAME", "value": "Brahman" }, { "context": "state :corp)\n (play-from-hand state :runner \"Brahman\")\n (let [brah (get-program state 0)\n ", "end": 33124, "score": 0.9987514615058899, "start": 33117, "tag": "NAME", "value": "Brahman" }, { "context": "y\"\n (do-game\n (new-game {:runner {:deck [\"Brahman\" \"Paricia\"]}\n :corp {:deck [\"Spid", "end": 33790, "score": 0.999670147895813, "start": 33783, "tag": "NAME", "value": "Brahman" }, { "context": "-game\n (new-game {:runner {:deck [\"Brahman\" \"Paricia\"]}\n :corp {:deck [\"Spiderweb\"]}})", "end": 33800, "score": 0.9996298551559448, "start": 33793, "tag": "NAME", "value": "Paricia" }, { "context": "state :corp)\n (play-from-hand state :runner \"Brahman\")\n (play-from-hand state :runner \"Paricia\")\n", "end": 33980, "score": 0.9991786479949951, "start": 33973, "tag": "NAME", "value": "Brahman" }, { "context": "r \"Brahman\")\n (play-from-hand state :runner \"Paricia\")\n (core/gain state :runner :credit 1)\n ", "end": 34027, "score": 0.999260425567627, "start": 34020, "tag": "NAME", "value": "Paricia" }, { "context": "\n (do-game\n (new-game {:runner {:deck [\"Bukhgalter\" \"Mimic\"]}\n :corp {:deck [\"Pup", "end": 34760, "score": 0.613004207611084, "start": 34755, "tag": "NAME", "value": "khgal" }, { "context": "20 :click 1)\n (play-from-hand state :runner \"Bukhgalter\")\n (play-from-hand state :runner \"Mimic\")\n ", "end": 34994, "score": 0.6751208305358887, "start": 34984, "tag": "NAME", "value": "Bukhgalter" }, { "context": "-game state\n (play-from-hand state :runner \"Carmen\")\n (let [carmen (get-program state 0)]\n ", "end": 41890, "score": 0.7282840609550476, "start": 41885, "tag": "NAME", "value": "armen" }, { "context": "-game state\n (play-from-hand state :runner \"Carmen\")\n (let [carmen (get-program state 0)]\n ", "end": 42422, "score": 0.6498623490333557, "start": 42417, "tag": "NAME", "value": "armen" }, { "context": "Barrier\"\n (play-from-hand state :runner \"Chameleon\")\n (click-prompt state :runner \"Barrie", "end": 49026, "score": 0.4896259903907776, "start": 49023, "tag": "NAME", "value": "ame" }, { "context": "de Gate\"\n (play-from-hand state :runner \"Chameleon\")\n (click-prompt state :runner \"Code G", "end": 49963, "score": 0.4952375292778015, "start": 49960, "tag": "NAME", "value": "ame" }, { "context": "er \"Cloak\")\n (play-from-hand state :runner \"Dai V\")\n (run-on state :hq)\n (let [enig (get-", "end": 76583, "score": 0.8800746202468872, "start": 76579, "tag": "NAME", "value": "ai V" }, { "context": "er :click 3)\n (play-from-hand state :runner \"Datasucker\")\n (let [ds (get-program state 0)\n ", "end": 78520, "score": 0.7319004535675049, "start": 78515, "tag": "USERNAME", "value": "Datas" }, { "context": "state :corp)\n (play-from-hand state :runner \"DaVinci\")\n (run-on state \"HQ\")\n (changes-val-ma", "end": 80700, "score": 0.6898766756057739, "start": 80693, "tag": "NAME", "value": "DaVinci" }, { "context": "state :corp)\n (play-from-hand state :runner \"DaVinci\")\n (run-on state \"HQ\")\n (run-continue s", "end": 81079, "score": 0.6660710573196411, "start": 81072, "tag": "NAME", "value": "DaVinci" }, { "context": "\n (do-game\n (new-game {:runner {:hand [\"DaVinci\" \"The Turning Wheel\"]}})\n (take-credits ", "end": 81432, "score": 0.4909842908382416, "start": 81431, "tag": "NAME", "value": "V" }, { "context": "state :corp)\n (play-from-hand state :runner \"DaVinci\")\n (let [davinci (get-program state 0)]\n ", "end": 81539, "score": 0.6762253046035767, "start": 81532, "tag": "NAME", "value": "DaVinci" }, { "context": "4987\"\n (do-game\n (new-game {:runner {:id \"Armand \\\"Geist\\\" Walker: Tech Lord\"\n ", "end": 82155, "score": 0.9965800046920776, "start": 82149, "tag": "NAME", "value": "Armand" }, { "context": "do-game\n (new-game {:runner {:id \"Armand \\\"Geist\\\" Walker: Tech Lord\"\n :d", "end": 82163, "score": 0.6120376586914062, "start": 82160, "tag": "NAME", "value": "ist" }, { "context": ")) \"Fetal AI stolen\")))))\n\n(deftest dhegdheer\n ;; Dheghdheer - hosting a breaker with strength based on unused", "end": 85370, "score": 0.967179000377655, "start": 85360, "tag": "NAME", "value": "Dheghdheer" }, { "context": "s\"\n (do-game\n (new-game {:runner {:deck [\"Adept\" \"Dhegdheer\"]}})\n (take-credits state :c", "end": 85532, "score": 0.7174274921417236, "start": 85531, "tag": "NAME", "value": "A" }, { "context": "do-game\n (new-game {:runner {:deck [\"Adept\" \"Dhegdheer\"]}})\n (take-credits state :corp)\n (core", "end": 85548, "score": 0.9566752314567566, "start": 85539, "tag": "NAME", "value": "Dhegdheer" }, { "context": "r :credit 5)\n (play-from-hand state :runner \"Dhegdheer\")\n (play-from-hand state :runner \"Adept\")\n ", "end": 85675, "score": 0.9625347256660461, "start": 85666, "tag": "NAME", "value": "Dhegdheer" }, { "context": "\"Dhegdheer\")\n (play-from-hand state :runner \"Adept\")\n (is (= 3 (:credit (get-runner))) \"3 c", "end": 85716, "score": 0.6430023908615112, "start": 85715, "tag": "NAME", "value": "A" }, { "context": "s\"\n (do-game\n (new-game {:runner {:deck [\"Adept\" \"Dhegdheer\"]}})\n (take-credits state :c", "end": 86487, "score": 0.6982039213180542, "start": 86486, "tag": "NAME", "value": "A" }, { "context": "do-game\n (new-game {:runner {:deck [\"Adept\" \"Dhegdheer\"]}})\n (take-credits state :corp)\n (core", "end": 86503, "score": 0.9386870265007019, "start": 86494, "tag": "NAME", "value": "Dhegdheer" }, { "context": "r :credit 5)\n (play-from-hand state :runner \"Dhegdheer\")\n (play-from-hand state :runner \"Adept\")\n ", "end": 86630, "score": 0.984596848487854, "start": 86621, "tag": "NAME", "value": "Dhegdheer" }, { "context": "m\"\n (do-game\n (new-game {:runner {:deck [\"Djinn\" \"Chakana\"]}})\n (take-credits state :corp)\n ", "end": 90743, "score": 0.7483482360839844, "start": 90738, "tag": "NAME", "value": "Djinn" }, { "context": "state :corp)\n (play-from-hand state :runner \"Djinn\")\n (is (= 3 (core/available-mu state)))\n ", "end": 90834, "score": 0.9993287324905396, "start": 90829, "tag": "NAME", "value": "Djinn" }, { "context": "m\"\n (do-game\n (new-game {:runner {:deck [\"Djinn\" \"Parasite\"]}})\n (take-credits state :corp)\n", "end": 91383, "score": 0.939443826675415, "start": 91378, "tag": "NAME", "value": "Djinn" }, { "context": "state :corp)\n (play-from-hand state :runner \"Djinn\")\n (core/move state :runner (find-card \"Para", "end": 91475, "score": 0.999282717704773, "start": 91470, "tag": "NAME", "value": "Djinn" }, { "context": "game state\n (play-from-hand state :runner \"Echelon\")\n (let [echelon (get-program state 0)]\n ", "end": 94487, "score": 0.9954037070274353, "start": 94480, "tag": "NAME", "value": "Echelon" }, { "context": "game state\n (play-from-hand state :runner \"Echelon\")\n (let [echelon (get-program state 0)]\n ", "end": 95049, "score": 0.9965448975563049, "start": 95042, "tag": "NAME", "value": "Echelon" }, { "context": "ore\"\n (do-game\n (new-game {:corp {:deck [\"Caduceus\"]}\n :runner {:deck [\"Faerie\"]}})\n", "end": 103163, "score": 0.9887495040893555, "start": 103155, "tag": "NAME", "value": "Caduceus" }, { "context": "k [\"Caduceus\"]}\n :runner {:deck [\"Faerie\"]}})\n (play-from-hand state :corp \"Caduceus\"", "end": 103207, "score": 0.9950534701347351, "start": 103201, "tag": "NAME", "value": "Faerie" }, { "context": " [\"Faerie\"]}})\n (play-from-hand state :corp \"Caduceus\" \"Archives\")\n (take-credits state :corp)\n ", "end": 103256, "score": 0.9735243916511536, "start": 103248, "tag": "NAME", "value": "Caduceus" }, { "context": "state :corp)\n (play-from-hand state :runner \"Faerie\")\n (let [fae (get-program state 0)]\n ", "end": 103346, "score": 0.971132218837738, "start": 103340, "tag": "NAME", "value": "Faerie" }, { "context": " (run-continue state)\n (is (find-card \"Faerie\" (:discard (get-runner))) \"Faerie trashed\"))))\n ", "end": 103845, "score": 0.6917831301689148, "start": 103839, "tag": "NAME", "value": "Faerie" }, { "context": "eak\"\n (do-game\n (new-game {:corp {:deck [\"Caduceus\"]}\n :runner {:deck [\"Faerie\"]}})\n", "end": 103990, "score": 0.9766144156455994, "start": 103982, "tag": "NAME", "value": "Caduceus" }, { "context": "k [\"Caduceus\"]}\n :runner {:deck [\"Faerie\"]}})\n (play-from-hand state :corp \"Caduceus\"", "end": 104034, "score": 0.9687855243682861, "start": 104028, "tag": "NAME", "value": "Faerie" }, { "context": " [\"Faerie\"]}})\n (play-from-hand state :corp \"Caduceus\" \"Archives\")\n (take-credits state :corp)\n ", "end": 104083, "score": 0.9570340514183044, "start": 104075, "tag": "NAME", "value": "Caduceus" }, { "context": "unner faust 1)\n (click-card state :runner \"Gordian Blade\")\n (is (empty? (:prompt (get-runner))) \"No", "end": 107968, "score": 0.9100167155265808, "start": 107955, "tag": "NAME", "value": "Gordian Blade" }, { "context": "d [\"Ice Wall\"]}\n :runner {:hand [\"Femme Fatale\"]\n :credits 20}", "end": 109959, "score": 0.5070289969444275, "start": 109956, "tag": "NAME", "value": "Fem" }, { "context": "state :corp)\n (play-from-hand state :runner \"Fermenter\")\n (let [fermenter (get-program state 0)]\n ", "end": 110812, "score": 0.9638941884040833, "start": 110803, "tag": "NAME", "value": "Fermenter" }, { "context": "ion\"\n (do-game\n (new-game {:corp {:deck [\"Adonis Campaign\"]}\n :runner {:deck [\"Fermenter\" \"", "end": 111455, "score": 0.9836869835853577, "start": 111440, "tag": "NAME", "value": "Adonis Campaign" }, { "context": "nis Campaign\"]}\n :runner {:deck [\"Fermenter\" \"Hivemind\"]}})\n (take-credits state :corp)\n", "end": 111502, "score": 0.9952405691146851, "start": 111493, "tag": "NAME", "value": "Fermenter" }, { "context": "\"]}\n :runner {:deck [\"Fermenter\" \"Hivemind\"]}})\n (take-credits state :corp)\n (play", "end": 111513, "score": 0.9958593845367432, "start": 111505, "tag": "NAME", "value": "Hivemind" }, { "context": "state :corp)\n (play-from-hand state :runner \"Fermenter\")\n (play-from-hand state :runner \"Hivemind\")", "end": 111598, "score": 0.991415798664093, "start": 111589, "tag": "NAME", "value": "Fermenter" }, { "context": "\"Fermenter\")\n (play-from-hand state :runner \"Hivemind\")\n (take-credits state :runner)\n (take-", "end": 111646, "score": 0.9933460354804993, "start": 111638, "tag": "NAME", "value": "Hivemind" }, { "context": "n\"\n (do-game\n (new-game {:runner {:deck [\"Gauss\"]}\n :options {:start-as :runner}}", "end": 112442, "score": 0.9375709295272827, "start": 112437, "tag": "NAME", "value": "Gauss" }, { "context": "s :runner}})\n (play-from-hand state :runner \"Gauss\")\n (let [gauss (get-program state 0)]\n ", "end": 112536, "score": 0.9591799974441528, "start": 112531, "tag": "NAME", "value": "Gauss" }, { "context": "s state :corp)\n (play-from-hand state :runner \"Gravedigger\")\n (let [gd (get-program state 0)]\n (tras", "end": 120016, "score": 0.9931927919387817, "start": 120005, "tag": "USERNAME", "value": "Gravedigger" }, { "context": "state :corp)\n (play-from-hand state :runner \"Harbinger\")\n (trash state :runner (-> (get-runner) :ri", "end": 121223, "score": 0.8516569137573242, "start": 121214, "tag": "NAME", "value": "Harbinger" }, { "context": "state :corp)\n (play-from-hand state :runner \"Hyperdriver\")\n (is (= 1 (core/available-mu state))", "end": 121699, "score": 0.7146041989326477, "start": 121694, "tag": "NAME", "value": "Hyper" }, { "context": "state :corp)\n (play-from-hand state :runner \"Dhegdheer\")\n (let [dheg (get-program state 0)]\n ", "end": 122370, "score": 0.5566078424453735, "start": 122367, "tag": "NAME", "value": "Dhe" }, { "context": "te :corp)\n (play-from-hand state :runner \"Dhegdheer\")\n (let [dheg (get-program state 0)]\n ", "end": 122376, "score": 0.6116736531257629, "start": 122370, "tag": "USERNAME", "value": "gdheer" }, { "context": " :credits 100}\n :runner {:id \"Rielle \\\"Kit\\\" Peddler: Transhuman\"\n ", "end": 139817, "score": 0.9354744553565979, "start": 139811, "tag": "NAME", "value": "Rielle" }, { "context": " :runner {:id \"Rielle \\\"Kit\\\" Peddler: Transhuman\"\n :hand [\"Inversific", "end": 139841, "score": 0.7237668037414551, "start": 139835, "tag": "NAME", "value": "Transh" }, { "context": " purge\n (do-game\n (new-game {:runner {:deck [\"Lamprey\"]}})\n (take-credits state :corp)\n (play-fro", "end": 149130, "score": 0.9913163185119629, "start": 149123, "tag": "NAME", "value": "Lamprey" }, { "context": "s state :corp)\n (play-from-hand state :runner \"Lamprey\")\n (let [lamp (get-program state 0)]\n (ru", "end": 149209, "score": 0.9880097508430481, "start": 149202, "tag": "NAME", "value": "Lamprey" }, { "context": "r :click 3)\n (play-from-hand state :runner \"Leech\")\n (let [le (get-program state 0)\n ", "end": 150174, "score": 0.5582247972488403, "start": 150172, "tag": "NAME", "value": "ee" }, { "context": "r :credit 5)\n (play-from-hand state :runner \"Leprechaun\")\n (play-from-hand state :runner \"Adept\")\n ", "end": 152442, "score": 0.995974063873291, "start": 152432, "tag": "NAME", "value": "Leprechaun" }, { "context": "s\"\n (do-game\n (new-game {:runner {:deck [\"Leprechaun\" \"Hyperdriver\" \"Imp\"]}})\n (take-credits stat", "end": 153137, "score": 0.8611204028129578, "start": 153127, "tag": "NAME", "value": "Leprechaun" }, { "context": "state :corp)\n (play-from-hand state :runner \"Leprechaun\")\n (let [lep (get-program state 0)]\n ", "end": 153243, "score": 0.9634665250778198, "start": 153233, "tag": "NAME", "value": "Leprechaun" }, { "context": "s state :corp)\n (play-from-hand state :runner \"Mammon\")\n (take-credits state :runner)\n (take", "end": 158001, "score": 0.6397318840026855, "start": 158000, "tag": "NAME", "value": "M" }, { "context": "s\"\n (do-game\n (new-game {:runner {:deck [\"Sure Gamble\"]\n :hand [\"Mantle\" \"Prog", "end": 159357, "score": 0.8886416554450989, "start": 159346, "tag": "NAME", "value": "Sure Gamble" }, { "context": "e-credits state :corp)))))\n\n(deftest marjanah\n ;; Marjanah\n (before-each [state (new-game {:runner {:hand [", "end": 160047, "score": 0.8805673718452454, "start": 160039, "tag": "NAME", "value": "Marjanah" }, { "context": "fore-each [state (new-game {:runner {:hand [(qty \"Marjanah\" 2)]\n :c", "end": 160111, "score": 0.736042320728302, "start": 160103, "tag": "NAME", "value": "Marjanah" }, { "context": " (play-from-hand state :runner \"Marjanah\")\n (run-on state :hq)\n ", "end": 160532, "score": 0.9671030640602112, "start": 160524, "tag": "NAME", "value": "Marjanah" }, { "context": "elf\")\n (play-from-hand state :runner \"Datasucker\")\n (is (= 2 (get-strength (refresh maven))", "end": 165095, "score": 0.6050798296928406, "start": 165090, "tag": "NAME", "value": "ucker" }, { "context": "est\"\n (do-game\n (new-game {:corp {:deck [\"Anansi\"]\n :credits 20}\n ", "end": 165967, "score": 0.9562526941299438, "start": 165961, "tag": "NAME", "value": "Anansi" }, { "context": ":credits 20}})\n (play-from-hand state :corp \"Anansi\" \"HQ\")\n (rez state :corp (get-ice state :hq ", "end": 166132, "score": 0.9708939790725708, "start": 166126, "tag": "NAME", "value": "Anansi" }, { "context": "s state :corp)\n (play-from-hand state :runner \"Origami\")\n (is (= 6 (hand-size :runner)))\n (play-fr", "end": 182255, "score": 0.8580955266952515, "start": 182248, "tag": "NAME", "value": "Origami" }, { "context": "ize :runner)))\n (play-from-hand state :runner \"Origami\")\n (is (= 9 (hand-size :runner)) \"Max hand siz", "end": 182335, "score": 0.7706528902053833, "start": 182328, "tag": "NAME", "value": "Origami" }, { "context": "s state :corp)\n (play-from-hand state :runner \"Paricia\")\n (let [pad (get-content state :remote1 0)\n ", "end": 204668, "score": 0.9991859197616577, "start": 204661, "tag": "NAME", "value": "Paricia" }, { "context": "(dotimes [_ 2]\n (click-card state :runner \"Paricia\"))\n (is (nil? (refresh pad)) \"PAD Campaign s", "end": 205315, "score": 0.9989751577377319, "start": 205308, "tag": "NAME", "value": "Paricia" }, { "context": "state :corp)\n (play-from-hand state :runner \"Persephone\")\n (run-on state \"Archives\")\n (run-cont", "end": 212137, "score": 0.94756680727005, "start": 212127, "tag": "USERNAME", "value": "Persephone" }, { "context": "state :corp)\n (play-from-hand state :runner \"Pheromones\")\n (let [ph (get-program state 0)]\n (", "end": 213345, "score": 0.6038340926170349, "start": 213335, "tag": "USERNAME", "value": "Pheromones" }, { "context": "; Plague\n (do-game\n (new-game {:corp {:deck [\"Mark Yale\"]}\n :runner {:deck [\"Plague\"]}})\n ", "end": 214689, "score": 0.9997410774230957, "start": 214680, "tag": "NAME", "value": "Mark Yale" }, { "context": "ck [\"Plague\"]}})\n (play-from-hand state :corp \"Mark Yale\" \"New remote\")\n (take-credits state :corp)\n ", "end": 214779, "score": 0.9997398853302002, "start": 214770, "tag": "NAME", "value": "Mark Yale" }, { "context": "begins\n (do-game\n (new-game {:runner {:deck [\"Rezeki\"]}})\n (take-credits state :corp)\n (play-fro", "end": 219847, "score": 0.6480802893638611, "start": 219841, "tag": "NAME", "value": "Rezeki" }, { "context": "s state :corp)\n (play-from-hand state :runner \"Rezeki\")\n (take-credits state :runner)\n (let [cred", "end": 219925, "score": 0.6565399169921875, "start": 219919, "tag": "NAME", "value": "Rezeki" }, { "context": "s with another deva in hand\"\n (doseq [deva [\"Aghora\" \"Sadyojata\" \"Vamadeva\"]]\n (do-game\n ", "end": 225329, "score": 0.5689615607261658, "start": 225328, "tag": "NAME", "value": "A" }, { "context": "other deva in hand\"\n (doseq [deva [\"Aghora\" \"Sadyojata\" \"Vamadeva\"]]\n (do-game\n ", "end": 225338, "score": 0.7234331369400024, "start": 225337, "tag": "NAME", "value": "S" }, { "context": "n hand\"\n (doseq [deva [\"Aghora\" \"Sadyojata\" \"Vamadeva\"]]\n (do-game\n (new-game {:", "end": 225350, "score": 0.6063871383666992, "start": 225349, "tag": "NAME", "value": "V" }, { "context": " :credits 10}\n :runner {:deck [\"Savant\" \"Box-E\"]\n :credits 20}", "end": 229340, "score": 0.5796762704849243, "start": 229338, "tag": "NAME", "value": "av" }, { "context": "n 2+ link\n (do-game\n (new-game {:runner {:id \"Nasir Meidan: Cyber Explorer\"\n :deck [\"", "end": 234041, "score": 0.9920406937599182, "start": 234029, "tag": "NAME", "value": "Nasir Meidan" }, { "context": "2+ link\"))))\n\n(deftest sneakdoor-beta\n (testing \"Gabriel Santiago, Ash on HQ should prevent Sneakdoor HQ access but", "end": 234949, "score": 0.9998471140861511, "start": 234933, "tag": "NAME", "value": "Gabriel Santiago" }, { "context": " [\"Ash 2X3ZB9CY\"]}\n :runner {:id \"Gabriel Santiago: Consummate Professional\"\n ", "end": 235147, "score": 0.9998483061790466, "start": 235131, "tag": "NAME", "value": "Gabriel Santiago" }, { "context": " \"Corroder\")\n (play-from-hand state :runner \"Gordian Blade\")\n (let [tako (get-program state 0)\n ", "end": 254646, "score": 0.9795742034912109, "start": 254633, "tag": "NAME", "value": "Gordian Blade" }, { "context": "ate :corp)\n (play-from-hand state :runner \"Trypano\")\n (click-card state :runner (get-card sta", "end": 262174, "score": 0.8211773037910461, "start": 262167, "tag": "NAME", "value": "Trypano" }, { "context": "t-rezzed))\n (play-from-hand state :runner \"Trypano\")\n (click-card state :runner architect-unr", "end": 262292, "score": 0.7674386501312256, "start": 262285, "tag": "NAME", "value": "Trypano" }, { "context": "\"Architect\"]}\n :runner {:deck [\"Trypano\" \"Hivemind\" (qty \"Surge\" 2)]}})\n (play-from-", "end": 263477, "score": 0.746344804763794, "start": 263472, "tag": "NAME", "value": "ypano" }, { "context": "ate :corp)\n (play-from-hand state :runner \"Tycoon\")\n (let [tycoon (get-program state 0)\n ", "end": 265033, "score": 0.6099339127540588, "start": 265029, "tag": "NAME", "value": "coon" }, { "context": "ate :corp)\n (play-from-hand state :runner \"Tycoon\")\n (let [tycoon (get-program state 0)\n ", "end": 266178, "score": 0.609911322593689, "start": 266174, "tag": "NAME", "value": "coon" }, { "context": "eak\"\n (do-game\n (new-game {:corp {:deck [\"Markus 1.0\"]}\n :runner {:deck [\"Tycoon\"]", "end": 267112, "score": 0.7584645748138428, "start": 267106, "tag": "NAME", "value": "Markus" }, { "context": " [\"Tycoon\"]}})\n (play-from-hand state :corp \"Markus 1.0\" \"HQ\")\n (rez state :corp (get-ice state ", "end": 267207, "score": 0.6484587788581848, "start": 267201, "tag": "NAME", "value": "Markus" }, { "context": ":credits 20}})\n (play-from-hand state :corp \"Afshar\" \"R&D\")\n (rez state :corp (get-ice state :rd", "end": 268149, "score": 0.7134336233139038, "start": 268143, "tag": "NAME", "value": "Afshar" }, { "context": "te :corp)\n (play-from-hand state :runner \"Vamadeva\")\n (card-ability state :runner (get-progra", "end": 273605, "score": 0.5599703192710876, "start": 273598, "tag": "NAME", "value": "amadeva" }, { "context": "s with another deva in hand\"\n (doseq [deva [\"Aghora\" \"Sadyojata\" \"Vamadeva\"]]\n (do-game\n ", "end": 273836, "score": 0.7375528216362, "start": 273830, "tag": "NAME", "value": "Aghora" }, { "context": "other deva in hand\"\n (doseq [deva [\"Aghora\" \"Sadyojata\" \"Vamadeva\"]]\n (do-game\n (new-gam", "end": 273848, "score": 0.876512885093689, "start": 273839, "tag": "NAME", "value": "Sadyojata" }, { "context": "n hand\"\n (doseq [deva [\"Aghora\" \"Sadyojata\" \"Vamadeva\"]]\n (do-game\n (new-game {:runner ", "end": 273859, "score": 0.7668587565422058, "start": 273851, "tag": "NAME", "value": "Vamadeva" }, { "context": "eck [\"Ice Wall\"]}\n :runner {:deck [\"Wari\"]}})\n (play-from-hand state :corp \"Ice Wall", "end": 275654, "score": 0.691504180431366, "start": 275653, "tag": "NAME", "value": "W" }, { "context": "s state :corp)\n (play-from-hand state :runner \"Wari\")\n (run-empty-server state \"HQ\")\n (click", "end": 275780, "score": 0.621508002281189, "start": 275779, "tag": "NAME", "value": "W" } ]
test/clj/game/cards/programs_test.clj
jove-m/netrunner
0
(ns game.cards.programs-test (:require [game.core :as core] [game.core.card :refer :all] [game.macros :refer [req]] [game.utils :as utils] [game.core-test :refer :all] [game.utils-test :refer :all] [game.macros-test :refer :all] [clojure.test :refer :all])) (deftest abagnale ;; Abagnale (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Abagnale"] :credits 10}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Abagnale") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 2) (is (= :approach-server (:phase (get-run))) "Run has bypassed Enigma") (is (find-card "Abagnale" (:discard (get-runner))) "Abagnale is trashed"))) (deftest adept ;; Adept (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Cobra"] :credits 10} :runner {:deck ["Adept" "Box-E"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Cobra" "R&D") (take-credits state :corp) (play-from-hand state :runner "Adept") (let [adept (get-program state 0) iw (get-ice state :hq 0) cobra (get-ice state :rd 0)] (is (= 2 (core/available-mu state))) (is (= 4 (get-strength (refresh adept))) "+2 strength for 2 unused MU") (play-from-hand state :runner "Box-E") (is (= 4 (core/available-mu state))) (is (= 6 (get-strength (refresh adept))) "+4 strength for 4 unused MU") (run-on state :hq) (rez state :corp iw) (run-continue state) (card-ability state :runner (refresh adept) 0) (click-prompt state :runner "End the run") (is (:broken (first (:subroutines (refresh iw)))) "Broke a barrier subroutine") (run-jack-out state) (run-on state :rd) (rez state :corp cobra) (run-continue state) (card-ability state :runner (refresh adept) 0) (click-prompt state :runner "Trash a program") (click-prompt state :runner "Done") (is (:broken (first (:subroutines (refresh cobra)))) "Broke a sentry subroutine")))) (deftest afterimage ;; Afterimage (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"] :credits 10} :runner {:hand ["Afterimage"] :credits 10}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (play-from-hand state :runner "Afterimage") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "Yes") (is (= :approach-server (:phase (get-run))) "Run has bypassed Rototurret"))) (testing "Can only be used once per turn. #5032" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"] :credits 10} :runner {:hand ["Afterimage"] :credits 10}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (play-from-hand state :runner "Afterimage") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "Yes") (is (= :approach-server (:phase (get-run))) "Run has bypassed Rototurret") (run-jack-out state) (run-on state "HQ") (run-continue state) (is (empty? (:prompt (get-runner))) "No bypass prompt")))) (deftest aghora ;; Aghora (testing "Swap ability" (testing "Doesnt work if no Deva in hand" (do-game (new-game {:runner {:hand ["Aghora" "Corroder"] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Aghora") (card-ability state :runner (get-program state 0) 2) (is (empty? (:prompt (get-runner))) "No select prompt as there's no Deva in hand"))) (testing "Works with another deva in hand" (doseq [deva ["Aghora" "Sadyojata" "Vamadeva"]] (do-game (new-game {:runner {:hand ["Aghora" deva] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Aghora") (let [installed-deva (get-program state 0)] (card-ability state :runner installed-deva 2) (click-card state :runner (first (:hand (get-runner)))) (is (not (utils/same-card? installed-deva (get-program state 0))) "Installed deva is not same as previous deva") (is (= deva (:title (get-program state 0))))))))) (testing "Break ability targets ice with rez cost 5 or higher" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Endless EULA"] :credits 10} :runner {:hand ["Aghora"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Endless EULA" "R&D") (take-credits state :corp) (play-from-hand state :runner "Aghora") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "No break prompt") (run-jack-out state) (run-on state "R&D") (rez state :corp (get-ice state :rd 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (seq (:prompt (get-runner))) "Have a break prompt") (click-prompt state :runner "End the run unless the Runner pays 1 [Credits]") (click-prompt state :runner "Done") (is (:broken (first (:subroutines (get-ice state :rd 0)))) "The break ability worked")))) (deftest algernon ;; Algernon - pay 2 credits to gain a click, trash if no successful run (testing "Use, successful run" (do-game (new-game {:runner {:deck ["Algernon"]}}) (take-credits state :corp) (play-from-hand state :runner "Algernon") (take-credits state :runner) (take-credits state :corp) (is (= 8 (:credit (get-runner))) "Runner starts with 8 credits") (is (= 4 (:click (get-runner))) "Runner starts with 4 clicks") (click-prompt state :runner "Yes") (is (= 6 (:credit (get-runner))) "Runner pays 2 credits") (is (= 5 (:click (get-runner))) "Runner gains 1 click") (run-empty-server state "Archives") (take-credits state :runner) (is (empty? (:discard (get-runner))) "No cards trashed") (is (= "Algernon" (:title (get-program state 0))) "Algernon still installed"))) (testing "Use, no successful run" (do-game (new-game {:runner {:deck ["Algernon"]}}) (take-credits state :corp) (play-from-hand state :runner "Algernon") (take-credits state :runner) (take-credits state :corp) (is (= 8 (:credit (get-runner))) "Runner starts with 8 credits") (is (= 4 (:click (get-runner))) "Runner starts with 4 clicks") (click-prompt state :runner "Yes") (is (= 6 (:credit (get-runner))) "Runner pays 2 credits") (is (= 5 (:click (get-runner))) "Runner gains 1 click") (run-on state "Archives") (run-jack-out state) (take-credits state :runner) (is (= 1 (count (:discard (get-runner)))) "Algernon trashed") (is (empty? (get-program state)) "No programs installed"))) (testing "Not used, no successful run" (do-game (new-game {:runner {:deck ["Algernon"]}}) (take-credits state :corp) (play-from-hand state :runner "Algernon") (take-credits state :runner) (take-credits state :corp) (is (= 8 (:credit (get-runner))) "Runner starts with 8 credits") (is (= 4 (:click (get-runner))) "Runner starts with 4 clicks") (click-prompt state :runner "No") (is (= 8 (:credit (get-runner))) "No credits spent") (is (= 4 (:click (get-runner))) "No clicks gained") (run-on state "Archives") (run-jack-out state) (take-credits state :runner) (is (empty? (:discard (get-runner))) "No cards trashed") (is (= "Algernon" (:title (get-program state 0))) "Algernon still installed")))) (deftest ^{:card-title "alias"} alias-breaker ;; Alias (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand [(qty "Zed 1.0" 2)]} :runner {:hand ["Alias"] :credits 10}}) (play-from-hand state :corp "Zed 1.0" "HQ") (play-from-hand state :corp "Zed 1.0" "New remote") (take-credits state :corp) (play-from-hand state :runner "Alias") (let [alias (get-program state 0) zed1 (get-ice state :hq 0) zed2 (get-ice state :remote1 0)] (is (= 1 (get-strength (refresh alias))) "Starts with 2 strength") (card-ability state :runner (refresh alias) 1) (is (= 4 (get-strength (refresh alias))) "Can gain strength outside of a run") (run-on state :hq) (rez state :corp (refresh zed1)) (run-continue state) (card-ability state :runner (refresh alias) 0) (click-prompt state :runner "Do 1 brain damage") (click-prompt state :runner "Done") (is (= 1 (count (filter :broken (:subroutines (refresh zed1))))) "The subroutine is broken") (run-jack-out state) (is (= 1 (get-strength (refresh alias))) "Drops back down to base strength on run end") (run-on state :remote1) (rez state :corp (refresh zed2)) (run-continue state) (card-ability state :runner (refresh alias) 0) (is (empty? (:prompt (get-runner))) "No break prompt because we're running a remote")))) (deftest amina ;; Amina ability (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Amina"] :credits 15}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Amina") (let [amina (get-program state 0) enigma (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh enigma)) (is (= 4 (:credit (get-corp)))) (run-continue state) (card-ability state :runner (refresh amina) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "Done") (run-continue state) (is (= 4 (:credit (get-corp))) "Corp did not lose 1c because not all subs were broken") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh amina) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (run-continue state) (is (= 3 (:credit (get-corp))) "Corp lost 1 credit") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh amina) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (run-continue state) (is (= 3 (:credit (get-corp))) "Ability only once per turn"))) (testing "Amina only triggers on itself. Issue #4716" (do-game (new-game {:runner {:deck ["Amina" "Yog.0"]} :corp {:deck ["Enigma"]}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (core/gain state :runner :credit 20 :click 1) (play-from-hand state :runner "Amina") (play-from-hand state :runner "Yog.0") (let [amina (get-program state 0) yog (get-program state 1) enima (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh enima)) (run-continue state) (card-ability state :runner (refresh amina) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh yog) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (changes-val-macro 0 (:credit (get-corp)) "No credit gain from Amina" (click-prompt state :runner "End the run") (run-continue state)) (run-jack-out state))))) (deftest analog-dreamers ;; Analog Dreamers (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Hostile Takeover" "PAD Campaign"]} :runner {:hand ["Analog Dreamers"]}}) (play-from-hand state :corp "Hostile Takeover" "New remote") (play-from-hand state :corp "PAD Campaign" "New remote") (advance state (get-content state :remote1 0) 1) (take-credits state :corp) (play-from-hand state :runner "Analog Dreamers") (card-ability state :runner (get-program state 0) 0) (run-continue state) (click-prompt state :runner "Analog Dreamers") (click-card state :runner "Hostile Takeover") (is (= "Choose a card to shuffle into R&D" (:msg (prompt-map :runner))) "Can't click on Hostile Takeover") (let [number-of-shuffles (count (core/turn-events state :corp :corp-shuffle-deck)) pad (get-content state :remote2 0)] (click-card state :runner "PAD Campaign") (is (< number-of-shuffles (count (core/turn-events state :corp :corp-shuffle-deck))) "Should be shuffled") (is (find-card "PAD Campaign" (:deck (get-corp))) "PAD Campaign is shuffled into R&D") (is (nil? (refresh pad)) "PAD Campaign is shuffled into R&D")))) (deftest ankusa ;; Ankusa (testing "Boost 1 strength for 1 credit" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Battlement"]} :runner {:hand ["Ankusa"] :credits 15}}) (play-from-hand state :corp "Battlement" "HQ") (take-credits state :corp) (play-from-hand state :runner "Ankusa") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (let [ankusa (get-program state 0) credits (:credit (get-runner))] "Boost ability costs 1 credit each" (card-ability state :runner ankusa 1) (is (= (dec credits) (:credit (get-runner))) "Boost 1 for 1 credit") (is (= (inc (get-strength ankusa)) (get-strength (refresh ankusa))) "Ankusa gains 1 strength")))) (testing "Break 1 for 2 credits" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Battlement"]} :runner {:hand ["Ankusa"] :credits 15}}) (play-from-hand state :corp "Battlement" "HQ") (take-credits state :corp) (play-from-hand state :runner "Ankusa") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (let [ankusa (get-program state 0)] (card-ability state :runner ankusa 1) (card-ability state :runner ankusa 1) (changes-val-macro -2 (:credit (get-runner)) "Break ability costs 2 credits" (card-ability state :runner ankusa 0) (click-prompt state :runner "End the run") (click-prompt state :runner "Done"))))) (testing "Breaking an ice fully returns it to hand. Issue #4711" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Battlement"]} :runner {:hand ["Ankusa"] :credits 15}}) (play-from-hand state :corp "Battlement" "HQ") (take-credits state :corp) (play-from-hand state :runner "Ankusa") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (let [ankusa (get-program state 0)] (card-ability state :runner ankusa 1) (card-ability state :runner ankusa 1) (card-ability state :runner ankusa 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (is (find-card "Battlement" (:hand (get-corp))) "Battlement should be back in hand"))))) (deftest atman ;; Atman (testing "Installing with 0 power counters" (do-game (new-game {:runner {:deck ["Atman"]}}) (take-credits state :corp) (play-from-hand state :runner "Atman") (click-prompt state :runner "0") (is (= 3 (core/available-mu state))) (let [atman (get-program state 0)] (is (zero? (get-counters atman :power)) "0 power counters") (is (zero? (get-strength atman)) "0 current strength")))) (testing "Installing with 2 power counters" (do-game (new-game {:runner {:deck ["Atman"]}}) (take-credits state :corp) (play-from-hand state :runner "Atman") (click-prompt state :runner "2") (is (= 3 (core/available-mu state))) (let [atman (get-program state 0)] (is (= 2 (get-counters atman :power)) "2 power counters") (is (= 2 (get-strength atman)) "2 current strength"))))) (deftest au-revoir ;; Au Revoir - Gain 1 credit every time you jack out (do-game (new-game {:runner {:deck [(qty "Au Revoir" 2)]}}) (take-credits state :corp) (play-from-hand state :runner "Au Revoir") (run-on state "Archives") (run-jack-out state) (is (= 5 (:credit (get-runner))) "Gained 1 credit from jacking out") (play-from-hand state :runner "Au Revoir") (run-on state "Archives") (run-jack-out state) (is (= 6 (:credit (get-runner))) "Gained 1 credit from each copy of Au Revoir"))) (deftest aumakua ;; Aumakua - Gain credit on no-trash (testing "Gain counter on no trash" (do-game (new-game {:corp {:deck [(qty "PAD Campaign" 3)]} :runner {:deck ["Aumakua"]}}) (play-from-hand state :corp "PAD Campaign" "New remote") (take-credits state :corp) (play-from-hand state :runner "Aumakua") (run-empty-server state "Server 1") (click-prompt state :runner "No action") (is (= 1 (get-counters (get-program state 0) :virus)) "Aumakua gains virus counter from no-trash") (core/gain state :runner :credit 5) (run-empty-server state "Server 1") (click-prompt state :runner "Pay 4 [Credits] to trash") (is (= 1 (get-counters (get-program state 0) :virus)) "Aumakua does not gain virus counter from trash"))) (testing "Gain counters on empty archives" (do-game (new-game {:runner {:deck ["Aumakua"]} :options {:start-as :runner}}) (play-from-hand state :runner "Aumakua") (run-empty-server state :archives) (is (= 1 (get-counters (get-program state 0) :virus)) "Aumakua gains virus counter from accessing empty Archives"))) (testing "Neutralize All Threats interaction" (do-game (new-game {:corp {:deck [(qty "PAD Campaign" 3)]} :runner {:deck ["Aumakua" "Neutralize All Threats"]}}) (play-from-hand state :corp "PAD Campaign" "New remote") (take-credits state :corp) (play-from-hand state :runner "Aumakua") (play-from-hand state :runner "Neutralize All Threats") (core/gain state :runner :credit 5) (run-empty-server state "Server 1") (is (zero? (get-counters (get-program state 0) :virus)) "Aumakua does not gain virus counter from ABT-forced trash")))) (deftest baba-yaga ;; Baba Yaga (do-game (new-game {:runner {:deck ["Baba Yaga" "Faerie" "Yog.0" "Sharpshooter"]}}) (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Baba Yaga") (play-from-hand state :runner "Sharpshooter") (let [baba (get-program state 0) base-abicount (count (:abilities baba))] (card-ability state :runner baba 0) (click-card state :runner "Faerie") (is (= (+ 2 base-abicount) (count (:abilities (refresh baba)))) "Baba Yaga gained 2 subroutines from Faerie") (card-ability state :runner (refresh baba) 0) (click-card state :runner (find-card "Yog.0" (:hand (get-runner)))) (is (= (+ 3 base-abicount) (count (:abilities (refresh baba)))) "Baba Yaga gained 1 subroutine from Yog.0") (trash state :runner (first (:hosted (refresh baba)))) (is (= (inc base-abicount) (count (:abilities (refresh baba)))) "Baba Yaga lost 2 subroutines from trashed Faerie") (card-ability state :runner baba 1) (click-card state :runner (find-card "Sharpshooter" (:program (:rig (get-runner))))) (is (= 2 (count (:hosted (refresh baba)))) "Faerie and Sharpshooter hosted on Baba Yaga") (is (= 1 (core/available-mu state)) "1 MU left with 2 breakers on Baba Yaga") (is (= 4 (:credit (get-runner))) "-5 from Baba, -1 from Sharpshooter played into Rig, -5 from Yog")))) (deftest bankroll ;; Bankroll - Includes check for Issue #4334 (do-game (new-game {:runner {:deck ["Bankroll" "Jak Sinclair"]}}) (take-credits state :corp) (core/gain state :runner :click 10) (play-from-hand state :runner "Bankroll") (play-from-hand state :runner "Jak Sinclair") (is (= 3 (core/available-mu state)) "Bankroll uses up 1 MU") (is (= 1 (:credit (get-runner))) "Bankroll cost 1 to install") (let [bankroll (get-program state 0) hosted-credits #(get-counters (refresh bankroll) :credit)] (is (zero? (hosted-credits)) "No counters on Bankroll on install") (run-empty-server state "Archives") (is (= 1 (hosted-credits)) "One credit counter on Bankroll after one successful run") (run-empty-server state "R&D") (is (= 2 (hosted-credits)) "Two credit counter on Bankroll after two successful runs") (run-empty-server state "HQ") (click-prompt state :runner "No action") (is (= 3 (hosted-credits)) "Three credit counter on Bankroll after three successful runs") (take-credits state :runner) (take-credits state :corp) (end-phase-12 state :runner) (click-prompt state :runner "Yes") (click-prompt state :runner "R&D") (run-continue state) (let [credits (:credit (get-runner))] (is (= 3 (hosted-credits)) "Jak Sinclair didn't trigger Bankroll") (card-ability state :runner bankroll 0) (is (= (+ 3 credits) (:credit (get-runner))) "Gained 3 credits when trashing Bankroll")) (is (= 1 (-> (get-runner) :discard count)) "Bankroll was trashed")))) (deftest berserker ;; Berserker (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Hive" "Enigma"] :credits 100} :runner {:hand ["Berserker"]}}) (play-from-hand state :corp "Ice Wall" "Archives") (play-from-hand state :corp "Hive" "R&D") (play-from-hand state :corp "Enigma" "HQ") (rez state :corp (get-ice state :archives 0)) (rez state :corp (get-ice state :rd 0)) (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Berserker") (let [berserker (get-program state 0)] (is (= 2 (get-strength (refresh berserker))) "Berserker strength starts at 2") (run-on state :archives) (run-continue state) (is (= 3 (get-strength (refresh berserker))) "Berserker gains 1 strength from Ice Wall") (run-jack-out state) (is (= 2 (get-strength (refresh berserker))) "Berserker strength resets at end of run") (run-on state :rd) (run-continue state) (is (= 7 (get-strength (refresh berserker))) "Berserker gains 5 strength from Hive") (run-jack-out state) (is (= 2 (get-strength (refresh berserker))) "Berserker strength resets at end of run") (run-on state :hq) (run-continue state) (is (= 2 (get-strength (refresh berserker))) "Berserker gains 0 strength from Enigma (non-barrier)")))) (deftest black-orchestra (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Macrophage"] :credits 10} :runner {:hand ["Black Orchestra"] :credits 100}}) (play-from-hand state :corp "Macrophage" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Black Orchestra") (let [bo (get-program state 0)] (run-on state :hq) (run-continue state) (card-ability state :runner bo 0) (card-ability state :runner bo 0) (is (empty? (:prompt (get-runner))) "Has no break prompt as strength isn't high enough") (card-ability state :runner bo 0) (is (= 8 (get-strength (refresh bo))) "Pumped Black Orchestra up to str 8") (click-prompt state :runner "Trace 4 - Purge virus counters") (click-prompt state :runner "Trace 3 - Trash a virus") (is (= 2 (count (filter :broken (:subroutines (get-ice state :hq 0))))))))) (testing "auto-pump" (testing "Pumping more than once, breaking more than once" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Macrophage"] :credits 10} :runner {:hand ["Black Orchestra"] :credits 100}}) (play-from-hand state :corp "Macrophage" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Black Orchestra") (let [bo (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -12 (:credit (get-runner)) "Paid 12 to fully break Macrophage with Black Orchestra" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh bo)})) (is (= 10 (get-strength (refresh bo))) "Pumped Black Orchestra up to str 10") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "No pumping, breaking more than once" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Aiki"] :credits 10} :runner {:hand ["Black Orchestra"] :credits 100}}) (play-from-hand state :corp "Aiki" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Black Orchestra") (let [bo (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -6 (:credit (get-runner)) "Paid 6 to fully break Aiki with Black Orchestra" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh bo)})) (is (= 6 (get-strength (refresh bo))) "Pumped Black Orchestra up to str 6") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "Pumping and breaking once" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"] :credits 10} :runner {:hand ["Black Orchestra"] :credits 100}}) (play-from-hand state :corp "Enigma" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Black Orchestra") (let [bo (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -3 (:credit (get-runner)) "Paid 3 to fully break Enigma with Black Orchestra" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh bo)})) (is (= 4 (get-strength (refresh bo))) "Pumped Black Orchestra up to str 6") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "No auto-break on unbreakable subs" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Afshar"] :credits 10} :runner {:hand ["Black Orchestra"] :credits 100}}) (play-from-hand state :corp "Afshar" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Black Orchestra") (let [bo (get-program state 0)] (run-on state :hq) (run-continue state) (is (empty? (filter #(:dynamic %) (:abilities (refresh bo)))) "No auto-pumping option for Afshar"))))) (testing "Heap Locked" (do-game (new-game {:corp {:deck ["Enigma" "Blacklist"]} :runner {:deck [(qty "Black Orchestra" 1)]}}) (play-from-hand state :corp "Enigma" "Archives") (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (refresh (get-content state :remote1 0))) (take-credits state :corp) (trash-from-hand state :runner "Black Orchestra") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (is (empty? (:prompt (get-runner))) "Black Orchestra prompt did not come up")))) (deftest botulus ;; Botulus (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:credits 15 :hand ["Botulus"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Botulus") (click-card state :runner (get-ice state :hq 0)) (let [iw (get-ice state :hq 0) bot (first (:hosted (refresh iw)))] (run-on state :hq) (rez state :corp iw) (run-continue state) (card-ability state :runner (refresh bot) 0) (click-prompt state :runner "End the run") (is (zero? (count (remove :broken (:subroutines (refresh iw))))) "All subroutines have been broken")))) (deftest brahman ;; Brahman (testing "Basic test" (do-game (new-game {:runner {:deck ["Brahman" "Paricia" "Cache"]} :corp {:deck ["Ice Wall"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Brahman") (play-from-hand state :runner "Paricia") (play-from-hand state :runner "Cache") (core/gain state :runner :credit 1) (let [brah (get-program state 0) par (get-program state 1) cache (get-program state 2) iw (get-ice state :hq 0)] (run-on state :hq) (rez state :corp iw) (run-continue state) (card-ability state :runner brah 0) ;break sub (click-prompt state :runner "End the run") (run-continue state) (is (= 0 (count (:deck (get-runner)))) "Stack is empty.") (click-card state :runner cache) (is (= 0 (count (:deck (get-runner)))) "Did not put Cache on top.") (click-card state :runner par) (is (= 1 (count (:deck (get-runner)))) "Paricia on top of Stack now.")))) (testing "Prompt on ETR" (do-game (new-game {:runner {:deck ["Brahman" "Paricia"]} :corp {:deck ["Spiderweb"]}}) (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (play-from-hand state :runner "Brahman") (play-from-hand state :runner "Paricia") (let [brah (get-program state 0) par (get-program state 1) spi (get-ice state :hq 0)] (run-on state :hq) (rez state :corp spi) (run-continue state) (card-ability state :runner brah 0) ;break sub (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (card-subroutine state :corp spi 0) ;ETR (is (= 0 (count (:deck (get-runner)))) "Stack is empty.") (click-card state :runner par) (is (= 1 (count (:deck (get-runner)))) "Paricia on top of Stack now.")))) (testing "Brahman works with Nisei tokens" (do-game (new-game {:corp {:deck ["Ice Wall" "Nisei MK II"]} :runner {:deck ["Brahman"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-and-score state "Nisei MK II") (take-credits state :corp) (play-from-hand state :runner "Brahman") (let [brah (get-program state 0) iw (get-ice state :hq 0) nisei (get-scored state :corp 0)] (run-on state "HQ") (rez state :corp iw) (run-continue state) (card-ability state :runner brah 0) ;break sub (click-prompt state :runner "End the run") (card-ability state :corp (refresh nisei) 0) ; Nisei Token (is (= 0 (count (:deck (get-runner)))) "Stack is empty.") (click-card state :runner brah) (is (= 1 (count (:deck (get-runner)))) "Brahman on top of Stack now.")))) (testing "Works with dynamic ability" (do-game (new-game {:runner {:deck ["Brahman" "Paricia"]} :corp {:deck ["Spiderweb"]}}) (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (play-from-hand state :runner "Brahman") (play-from-hand state :runner "Paricia") (core/gain state :runner :credit 1) (let [brah (get-program state 0) par (get-program state 1) spi (get-ice state :hq 0)] (run-on state :hq) (rez state :corp spi) (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh brah)}) (core/continue state :corp nil) (is (= 0 (count (:deck (get-runner)))) "Stack is empty.") (click-card state :runner par) (is (= 1 (count (:deck (get-runner)))) "Paricia on top of Stack now."))))) (deftest bukhgalter ;; Bukhgalter ability (testing "2c for breaking subs only with Bukhgalter" (do-game (new-game {:runner {:deck ["Bukhgalter" "Mimic"]} :corp {:deck ["Pup"]}}) (play-from-hand state :corp "Pup" "HQ") (take-credits state :corp) (core/gain state :runner :credit 20 :click 1) (play-from-hand state :runner "Bukhgalter") (play-from-hand state :runner "Mimic") (let [bukhgalter (get-program state 0) mimic (get-program state 1) pup (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh pup)) (run-continue state) (card-ability state :runner (refresh mimic) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (changes-val-macro -1 (:credit (get-runner)) "No credit gain from Bukhgalter for breaking with only Mimic" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]")) (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh bukhgalter) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (click-prompt state :runner "Done") (card-ability state :runner (refresh mimic) 0) (changes-val-macro -1 (:credit (get-runner)) "No credit gain from Bukhgalter" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]")) (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh bukhgalter) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (changes-val-macro (+ 2 -1) (:credit (get-runner)) "2 credits gained from Bukhgalter" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]"))))) (testing "gaining 2c only once per turn" (do-game (new-game {:runner {:deck ["Bukhgalter" "Mimic"]} :corp {:deck ["Pup"]}}) (play-from-hand state :corp "Pup" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Bukhgalter") (let [bukhgalter (get-program state 0) pup (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh pup)) (run-continue state) (card-ability state :runner (refresh bukhgalter) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (changes-val-macro (+ 2 -1) (:credit (get-runner)) "2 credits gained from Bukhgalter" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]")) (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh bukhgalter) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (changes-val-macro -1 (:credit (get-runner)) "No credits gained from Bukhgalter" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]"))))) (testing "Bukhgalter only triggers on itself. Issue #4716" (do-game (new-game {:runner {:deck ["Bukhgalter" "Mimic"]} :corp {:deck ["Pup"]}}) (play-from-hand state :corp "Pup" "HQ") (take-credits state :corp) (core/gain state :runner :credit 20 :click 1) (play-from-hand state :runner "Bukhgalter") (play-from-hand state :runner "Mimic") (let [bukhgalter (get-program state 0) mimic (get-program state 1) pup (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh pup)) (run-continue state) (card-ability state :runner (refresh bukhgalter) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh mimic) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (changes-val-macro -1 (:credit (get-runner)) "No credit gain from Bukhgalter" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]")) (run-jack-out state))))) (deftest buzzsaw ;; Buzzsaw (before-each [state (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"] :credits 20} :runner {:deck ["Buzzsaw"] :credits 20}}) _ (do (play-from-hand state :corp "Enigma" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Buzzsaw") (run-on state :hq) (run-continue state)) enigma (get-ice state :hq 0) buzzsaw (get-program state 0)] (testing "pump ability" (do-game state (changes-val-macro -3 (:credit (get-runner)) "Runner spends 3 credits to pump Buzzsaw" (card-ability state :runner buzzsaw 1)) (changes-val-macro 1 (get-strength (refresh buzzsaw)) "Buzzsaw gains 1 strength per pump" (card-ability state :runner buzzsaw 1)))) (testing "break ability" (do-game state (changes-val-macro -1 (:credit (get-runner)) "Runner spends 1 credits to break with Buzzsaw" (card-ability state :runner buzzsaw 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run")) (is (every? :broken (:subroutines (refresh enigma))) "Buzzsaw breaks 2 subs at once"))))) (deftest carmen ;; Carmen (before-each [state (new-game {:runner {:hand [(qty "Carmen" 2)] :credits 20} :corp {:deck [(qty "Hedge Fund" 5)] :hand ["Swordsman"] :credits 20}}) _ (do (play-from-hand state :corp "Swordsman" "HQ") (take-credits state :corp)) swordsman (get-ice state :hq 0)] (testing "install cost discount" (do-game state (take-credits state :corp) (changes-val-macro -5 (:credit (get-runner)) "Without discount" (play-from-hand state :runner "Carmen")) (take-credits state :runner) (take-credits state :corp) (run-empty-server state :archives) (changes-val-macro -3 (:credit (get-runner)) "With discount" (play-from-hand state :runner "Carmen")))) (testing "pump ability" (do-game state (play-from-hand state :runner "Carmen") (let [carmen (get-program state 0)] (run-on state :hq) (rez state :corp swordsman) (run-continue state :encounter-ice) (changes-val-macro -2 (:credit (get-runner)) "Pump costs 2" (card-ability state :runner carmen 1)) (changes-val-macro 3 (get-strength (refresh carmen)) "Carmen gains 3 str" (card-ability state :runner carmen 1))))) (testing "break ability" (do-game state (play-from-hand state :runner "Carmen") (let [carmen (get-program state 0)] (run-on state :hq) (rez state :corp swordsman) (run-continue state :encounter-ice) (changes-val-macro -1 (:credit (get-runner)) "Break costs 1" (card-ability state :runner carmen 0) (click-prompt state :runner "Trash an AI program")) (click-prompt state :runner "Do 1 net damage") (is (empty? (:prompt (get-runner))) "Only breaks 1 sub at a time")))))) (deftest cerberus-rex-h2 ;; Cerberus "Rex" H2 - boost 1 for 1 cred, break for 1 counter (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:deck ["Cerberus \"Rex\" H2"]}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cerberus \"Rex\" H2") (is (= 2 (:credit (get-runner))) "2 credits left after install") (let [enigma (get-ice state :hq 0) rex (get-program state 0)] (run-on state "HQ") (rez state :corp enigma) (run-continue state) (is (= 4 (get-counters rex :power)) "Start with 4 counters") ;; boost strength (card-ability state :runner rex 1) (is (= 1 (:credit (get-runner))) "Spend 1 credit to boost") (is (= 2 (get-strength (refresh rex))) "At strength 2 after boost") ;; break (card-ability state :runner rex 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (is (= 1 (:credit (get-runner))) "No credits spent to break") (is (= 3 (get-counters (refresh rex) :power)) "One counter used to break")))) (deftest chakana ;; Chakana (testing "gain counters on r&d runs" (do-game (new-game {:runner {:hand ["Chakana"]}}) (take-credits state :corp) (play-from-hand state :runner "Chakana") (let [chakana (get-program state 0)] (is (zero? (get-counters (refresh chakana) :virus)) "Chakana starts with 0 counters") (run-empty-server state "R&D") (is (= 1 (get-counters (refresh chakana) :virus)) "Chakana starts with 0 counters") (run-empty-server state "R&D") (is (= 2 (get-counters (refresh chakana) :virus)) "Chakana starts with 0 counters") (run-empty-server state "HQ") (is (= 2 (get-counters (refresh chakana) :virus)) "Chakana starts with 0 counters")))) (testing "3 counters increases advancement requirements by 1" (do-game (new-game {:corp {:hand ["Hostile Takeover"]} :runner {:hand ["Chakana"]}}) (play-from-hand state :corp "Hostile Takeover" "New remote") (take-credits state :corp) (play-from-hand state :runner "Chakana") (is (= 2 (core/get-advancement-requirement (get-content state :remote1 0))) "Hostile Takeover is a 2/1 by default") (let [chakana (get-program state 0)] (core/gain state :runner :click 10) (run-empty-server state "R&D") (run-empty-server state "R&D") (run-empty-server state "R&D") (is (= 3 (get-counters (refresh chakana) :virus))) (is (= 3 (core/get-advancement-requirement (get-content state :remote1 0))) "Hostile Takeover is affected by Chakana"))))) (deftest chameleon ;; Chameleon - Install on corp turn, only returns to hand at end of runner's turn (testing "with Clone Chip" (do-game (new-game {:runner {:deck ["Chameleon" "Clone Chip"]}}) (take-credits state :corp) (play-from-hand state :runner "Clone Chip") (core/move state :runner (find-card "Chameleon" (:hand (get-runner))) :discard) (take-credits state :runner) (is (zero? (count (:hand (get-runner))))) ;; Install Chameleon on corp turn (take-credits state :corp 1) (let [chip (get-hardware state 0)] (card-ability state :runner chip 0) (click-card state :runner (find-card "Chameleon" (:discard (get-runner)))) (click-prompt state :runner "Sentry")) (take-credits state :corp) (is (zero? (count (:hand (get-runner)))) "Chameleon not returned to hand at end of corp turn") (take-credits state :runner) (is (= 1 (count (:hand (get-runner)))) "Chameleon returned to hand at end of runner's turn"))) (testing "Returns to hand after hosting. #977" (do-game (new-game {:runner {:deck [(qty "Chameleon" 2) "Scheherazade"]}}) (take-credits state :corp) (play-from-hand state :runner "Chameleon") (click-prompt state :runner "Barrier") (is (= 3 (:credit (get-runner))) "-2 from playing Chameleon") ;; Host the Chameleon on Scheherazade that was just played (as in Personal Workshop/Hayley ability scenarios) (play-from-hand state :runner "Scheherazade") (let [scheherazade (get-program state 1)] (card-ability state :runner scheherazade 1) ; Host an installed program (click-card state :runner (find-card "Chameleon" (:program (:rig (get-runner))))) (is (= 4 (:credit (get-runner))) "+1 from hosting onto Scheherazade") ;; Install another Chameleon directly onto Scheherazade (card-ability state :runner scheherazade 0) ; Install and host a program from Grip (click-card state :runner (find-card "Chameleon" (:hand (get-runner)))) (click-prompt state :runner "Code Gate") (is (= 2 (count (:hosted (refresh scheherazade)))) "2 Chameleons hosted on Scheherazade") (is (= 3 (:credit (get-runner))) "-2 from playing Chameleon, +1 from installing onto Scheherazade")) (is (zero? (count (:hand (get-runner)))) "Both Chameleons in play - hand size 0") (take-credits state :runner) (click-prompt state :runner "Chameleon") (is (= 2 (count (:hand (get-runner)))) "Both Chameleons returned to hand - hand size 2"))) (testing "Can break subroutines only on chosen subtype" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma" "Rototurret"] :credits 10} :runner {:hand ["Chameleon"] :credits 100}}) (play-from-hand state :corp "Ice Wall" "Archives") (play-from-hand state :corp "Enigma" "HQ") (play-from-hand state :corp "Rototurret" "R&D") (rez state :corp (get-ice state :archives 0)) (rez state :corp (get-ice state :hq 0)) (rez state :corp (get-ice state :rd 0)) (take-credits state :corp) (testing "Choosing Barrier" (play-from-hand state :runner "Chameleon") (click-prompt state :runner "Barrier") (run-on state :archives) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "End the run") (is (empty? (:prompt (get-runner))) "Broke all subroutines on Ice Wall") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Enigma") (run-jack-out state) (run-on state :rd) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Rototurret") (run-jack-out state)) (take-credits state :runner) (take-credits state :corp) (testing "Choosing Code Gate" (play-from-hand state :runner "Chameleon") (click-prompt state :runner "Code Gate") (run-on state :archives) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Ice Wall") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (is (empty? (:prompt (get-runner))) "Broke all subroutines on Engima") (run-jack-out state) (run-on state :rd) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Rototurret") (run-jack-out state)) (take-credits state :runner) (take-credits state :corp) (testing "Choosing Sentry" (play-from-hand state :runner "Chameleon") (click-prompt state :runner "Sentry") (run-on state :archives) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Ice Wall") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Enigma") (run-jack-out state) (run-on state :rd) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "Trash a program") (click-prompt state :runner "End the run") (is (empty? (:prompt (get-runner))) "Broke all subroutines on Rototurret"))))) (deftest chisel ;; Chisel (testing "Basic test" (do-game (new-game {:corp {:hand ["Ice Wall"]} :runner {:hand ["Chisel"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Chisel") (click-card state :runner "Ice Wall") (let [iw (get-ice state :hq 0) chisel (first (:hosted (refresh iw)))] (run-on state "HQ") (rez state :corp iw) (is (zero? (get-counters (refresh chisel) :virus))) (run-continue state) (is (= 1 (get-counters (refresh chisel) :virus))) (is (refresh iw) "Ice Wall still around, just at 0 strength") (run-jack-out state) (run-on state "HQ") (run-continue state) (is (nil? (refresh iw)) "Ice Wall should be trashed") (is (nil? (refresh chisel)) "Chisel should likewise be trashed")))) (testing "Doesn't work if the ice is unrezzed" (do-game (new-game {:corp {:hand ["Ice Wall"]} :runner {:hand ["Chisel"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (core/gain state :runner :click 10) (play-from-hand state :runner "Chisel") (click-card state :runner "Ice Wall") (let [iw (get-ice state :hq 0) chisel (first (:hosted (refresh iw)))] (run-on state "HQ") (is (zero? (get-counters (refresh chisel) :virus))) (is (zero? (get-counters (refresh chisel) :virus)) "Chisel gains no counters as Ice Wall is unrezzed") (is (refresh iw) "Ice Wall still around, still at 1 strength") (core/jack-out state :runner nil) (run-on state "HQ") (rez state :corp iw) (run-continue state) (is (= 1 (get-counters (refresh chisel) :virus)) "Chisel now has 1 counter") (core/jack-out state :runner nil) (derez state :corp iw) (run-on state "HQ") (run-continue state) (is (refresh iw) "Ice Wall should still be around as it's unrezzed")))) (testing "Chisel does not account for other sources of strength modification on hosted ICE #5391" (do-game (new-game {:corp {:hand ["Ice Wall"]} :runner {:hand ["Chisel" "Devil Charm"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Chisel") (play-from-hand state :runner "Devil Charm") (click-card state :runner "Ice Wall") (let [iw (get-ice state :hq 0) chisel (first (:hosted (refresh iw)))] (run-on state "HQ") (rez state :corp iw) (run-continue state) (click-prompt state :runner "Devil Charm") (click-prompt state :runner "Yes") (is (nil? (refresh iw)) "Ice Wall should be trashed") (is (nil? (refresh chisel)) "Chisel should likewise be trashed"))))) (deftest cleaver ;; Cleaver (before-each [state (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Battlement"]} :runner {:hand ["Cleaver"] :credits 15}}) _ (do (play-from-hand state :corp "Battlement" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cleaver") (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state :encounter-ice)) battlement (get-ice state :hq 0) cleaver (get-program state 0)] (testing "pump ability" (do-game state (changes-val-macro -2 (:credit (get-runner)) "costs 2" (card-ability state :runner cleaver 1)) (changes-val-macro 1 (get-strength (refresh cleaver)) "Gains 1 strength" (card-ability state :runner cleaver 1)))) (testing "pump ability" (do-game state (changes-val-macro -1 (:credit (get-runner)) "costs 1" (card-ability state :runner cleaver 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run")) (is (every? :broken (:subroutines (refresh battlement)))))))) (deftest cloak ;; Cloak (testing "Pay-credits prompt" (do-game (new-game {:runner {:deck ["Cloak" "Refractor"]}}) (take-credits state :corp) (play-from-hand state :runner "Cloak") (play-from-hand state :runner "Refractor") (let [cl (get-program state 0) refr (get-program state 1)] (changes-val-macro 0 (:credit (get-runner)) "Used 1 credit from Cloak" (card-ability state :runner refr 1) (click-card state :runner cl)))))) (deftest conduit ;; Conduit (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 8)] :hand ["Hedge Fund"]} :runner {:deck ["Conduit"]}}) (take-credits state :corp) (play-from-hand state :runner "Conduit") (let [conduit (get-program state 0)] (card-ability state :runner conduit 0) (is (:run @state) "Run initiated") (run-continue state) (click-prompt state :runner "No action") (click-prompt state :runner "Yes") (is (empty? (:prompt (get-runner))) "Prompt closed") (is (= 1 (get-counters (refresh conduit) :virus))) (is (not (:run @state)) "Run ended") (card-ability state :runner conduit 0) (run-continue state) (is (= 1 (core/access-bonus-count state :runner :rd)) "Runner should access 1 additional card") (click-prompt state :runner "No action") (click-prompt state :runner "No action") (click-prompt state :runner "Yes") (is (= 2 (get-counters (refresh conduit) :virus))) (run-empty-server state :rd) (is (= 0 (core/access-bonus-count state :runner :rd)) "Runner should access 0 additional card on normal run")))) (testing "Knobkierie interaction (Issue #5748) - Knobkierie before Conduit" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 8)] :hand ["Hedge Fund"]} :runner {:deck ["Conduit" "Knobkierie"] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Conduit") (play-from-hand state :runner "Knobkierie") (let [conduit (get-program state 0) knobkierie (get-hardware state 0)] (card-ability state :runner conduit 0) (is (:run @state) "Run initiated") (run-continue state :access-server) (click-prompt state :runner "Knobkierie") (click-prompt state :runner "Yes") (click-card state :runner (refresh conduit)) (is (= 1 (core/access-bonus-count state :runner :rd)) "Runner should access 1 additional card")))) (testing "Knobkierie interaction (Issue #5748) - Conduit before Knobkierie" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 8)] :hand ["Hedge Fund"]} :runner {:deck ["Conduit" "Knobkierie"] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Conduit") (play-from-hand state :runner "Knobkierie") (let [conduit (get-program state 0) knobkierie (get-hardware state 0)] (card-ability state :runner conduit 0) (is (:run @state) "Run initiated") (run-continue state :access-server) (click-prompt state :runner "Conduit") (click-prompt state :runner "Yes") (click-card state :runner (refresh conduit)) (is (= 0 (core/access-bonus-count state :runner :rd)) "Runner should not access additional cards"))))) (deftest consume ;; Consume - gain virus counter for trashing corp card. click to get 2c per counter. (testing "Trash and cash out" (do-game (new-game {:corp {:deck ["Adonis Campaign"]} :runner {:deck ["Consume"]}}) (play-from-hand state :corp "Adonis Campaign" "New remote") (take-credits state :corp) (play-from-hand state :runner "Consume") (let [c (get-program state 0)] (is (zero? (get-counters (refresh c) :virus)) "Consume starts with no counters") (run-empty-server state "Server 1") (click-prompt state :runner "Pay 3 [Credits] to trash") (click-prompt state :runner "Yes") (is (= 1 (count (:discard (get-corp)))) "Adonis Campaign trashed") (is (= 1 (get-counters (refresh c) :virus)) "Consume gains a counter") (is (zero? (:credit (get-runner))) "Runner starts with no credits") (card-ability state :runner c 0) (is (= 2 (:credit (get-runner))) "Runner gains 2 credits") (is (zero? (get-counters (refresh c) :virus)) "Consume loses counters")))) (testing "Hivemind interaction" (do-game (new-game {:corp {:deck ["Adonis Campaign"]} :runner {:deck ["Consume" "Hivemind"]}}) (play-from-hand state :corp "Adonis Campaign" "New remote") (take-credits state :corp) (core/gain state :runner :credit 3) (play-from-hand state :runner "Consume") (play-from-hand state :runner "Hivemind") (let [c (get-program state 0) h (get-program state 1)] (is (zero? (get-counters (refresh c) :virus)) "Consume starts with no counters") (is (= 1 (get-counters (refresh h) :virus)) "Hivemind starts with a counter") (run-empty-server state "Server 1") (click-prompt state :runner "Pay 3 [Credits] to trash") (click-prompt state :runner "Yes") (is (= 1 (count (:discard (get-corp)))) "Adonis Campaign trashed") (is (= 1 (get-counters (refresh c) :virus)) "Consume gains a counter") (is (= 1 (get-counters (refresh h) :virus)) "Hivemind retains counter") (is (zero? (:credit (get-runner))) "Runner starts with no credits") (card-ability state :runner c 0) (is (= 4 (:credit (get-runner))) "Runner gains 4 credits") (is (zero? (get-counters (refresh c) :virus)) "Consume loses counters") (is (zero? (get-counters (refresh h) :virus)) "Hivemind loses counters")))) (testing "Hivemind counters only" (do-game (new-game {:runner {:deck ["Consume" "Hivemind"]}}) (take-credits state :corp) (play-from-hand state :runner "Consume") (play-from-hand state :runner "Hivemind") (let [c (get-program state 0) h (get-program state 1)] (is (zero? (get-counters (refresh c) :virus)) "Consume starts with no counters") (is (= 1 (get-counters (refresh h) :virus)) "Hivemind starts with a counter") (is (zero? (:credit (get-runner))) "Runner starts with no credits") (card-ability state :runner c 0) (is (= 2 (:credit (get-runner))) "Runner gains 2 credits") (is (zero? (get-counters (refresh c) :virus)) "Consume loses counters") (is (zero? (get-counters (refresh h) :virus)) "Hivemind loses counters"))))) (deftest cordyceps ;; Cordyceps (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma" "Hedge Fund"]} :runner {:hand ["Cordyceps"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cordyceps") (run-on state "HQ") (let [iw (get-ice state :hq 0) enig (get-ice state :hq 1) cor (get-program state 0)] (is (= 2 (get-counters (refresh cor) :virus)) "Cordyceps was installed with 2 virus tokens") (run-continue state) (run-continue state) (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner (refresh enig)) (click-card state :runner (refresh iw)) (click-prompt state :runner "No action")) (let [iw (get-ice state :hq 1) enig (get-ice state :hq 0) cor (get-program state 0)] (is (= "Ice Wall" (:title iw)) "Ice Wall now outermost ice") (is (= "Enigma" (:title enig)) "Enigma now outermost ice") (is (= 1 (get-counters (refresh cor) :virus)) "Used 1 virus token")) (take-credits state :runner) (take-credits state :corp) (run-on state "R&D") (run-continue state) (click-prompt state :runner "No action") (is (empty? (:prompt (get-runner))) "No prompt on uniced server"))) (testing "No prompt with less than 2 ice installed" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Hedge Fund"]} :runner {:hand ["Cordyceps"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cordyceps") (run-on state "HQ") (run-continue state) (run-continue state) (click-prompt state :runner "No action") (is (empty? (:prompt (get-runner))) "No prompt with only 1 installed ice"))) (testing "No prompt when empty" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma" "Hedge Fund"]} :runner {:hand ["Cordyceps"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cordyceps") (core/add-counter state :runner (get-program state 0) :virus -2) (is (= 0 (get-counters (get-program state 0) :virus)) "Has no virus tokens") (run-on state "HQ") (run-continue state) (run-continue state) (run-continue state) (is (= "You accessed Hedge Fund." (:msg (prompt-map :runner)))) (click-prompt state :runner "No action") (is (empty? (:prompt (get-runner))) "No prompt with no virus counters"))) (testing "Works with Hivemind installed" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma" "Hedge Fund"]} :runner {:hand ["Cordyceps" "Hivemind"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cordyceps") (core/add-counter state :runner (get-program state 0) :virus -2) (play-from-hand state :runner "Hivemind") (run-on state "HQ") (run-continue state) (run-continue state) (run-continue state) (is (= "Use Cordyceps to swap ice?" (:msg (prompt-map :runner)))) (click-prompt state :runner "Yes") (is (= "Select ice protecting this server" (:msg (prompt-map :runner)))) (is (= :select (prompt-type :runner))) (click-card state :runner "Ice Wall") (click-card state :runner "Enigma") (is (= "Select a card with virus counters (0 of 1 virus counters)" (:msg (prompt-map :runner)))) (click-card state :runner "Hivemind") (is (= "Enigma" (:title (get-ice state :hq 0)))) (is (= "Ice Wall" (:title (get-ice state :hq 1)))) (click-prompt state :runner "No action") (is (empty? (:prompt (get-runner))) "No prompt with only 1 installed ice")))) (deftest corroder ;; Corroder (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:credits 15 :hand ["Corroder"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Corroder") (run-on state "HQ") (let [iw (get-ice state :hq 0) cor (get-program state 0)] (rez state :corp iw) (run-continue state) (card-ability state :runner cor 1) (card-ability state :runner cor 0) (click-prompt state :runner "End the run") (is (zero? (count (remove :broken (:subroutines (refresh iw))))) "All subroutines have been broken")))) (deftest cradle ;; Cradle (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["Cradle" (qty "Cache" 100)]}}) (starting-hand state :runner ["Cradle"]) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (core/gain state :runner :credit 100 :click 100) (play-from-hand state :runner "Cradle") (let [cradle (get-program state 0) strength (get-strength (refresh cradle))] (dotimes [n 5] (when (pos? n) (core/draw state :runner n)) (core/fake-checkpoint state) (is (= (- strength n) (get-strength (refresh cradle))) (str "Cradle should lose " n " strength")) (starting-hand state :runner []) (core/fake-checkpoint state) (is (= strength (get-strength (refresh cradle))) (str "Cradle should be back to original strength"))) (click-draw state :runner) (is (= (dec strength) (get-strength (refresh cradle))) "Cradle should lose 1 strength") (play-from-hand state :runner "Cache") (is (= strength (get-strength (refresh cradle))) (str "Cradle should be back to original strength"))))) (deftest crescentus ;; Crescentus should only work on rezzed ice (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["Crescentus" "Corroder"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Corroder") (play-from-hand state :runner "Crescentus") (run-on state "HQ") (let [cor (get-program state 0) cres (get-program state 1) iw (get-ice state :hq 0)] (rez state :corp iw) (run-continue state) (is (rezzed? (refresh iw)) "Ice Wall is now rezzed") (card-ability state :runner cor 0) (click-prompt state :runner "End the run") (card-ability state :runner cres 0) (is (nil? (get-program state 1)) "Crescentus could be used because the ICE is rezzed") (is (not (rezzed? (refresh iw))) "Ice Wall is no longer rezzed")))) (deftest crypsis ;; Crypsis - Loses a virus counter after encountering ice it broke (testing "Breaking a sub spends a virus counter" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Crypsis"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "Archives") (take-credits state :corp) (play-from-hand state :runner "Crypsis") (let [crypsis (get-program state 0)] (card-ability state :runner crypsis 2) (is (= 1 (get-counters (refresh crypsis) :virus)) "Crypsis has 1 virus counter") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (card-ability state :runner (refresh crypsis) 1) ; Match strength (card-ability state :runner (refresh crypsis) 0) ; Break (click-prompt state :runner "End the run") (is (= 1 (get-counters (refresh crypsis) :virus)) "Crypsis has 1 virus counter") (run-continue state) (is (zero? (get-counters (refresh crypsis) :virus)) "Crypsis has 0 virus counters")))) (testing "Inability to remove a virus counter trashes Crypsis" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Crypsis"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "Archives") (take-credits state :corp) (play-from-hand state :runner "Crypsis") (let [crypsis (get-program state 0)] (is (zero? (get-counters (refresh crypsis) :virus)) "Crypsis has 0 virus counters") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (card-ability state :runner (refresh crypsis) 1) ; Match strength (card-ability state :runner (refresh crypsis) 0) ; Break (click-prompt state :runner "End the run") (run-continue state) (is (find-card "Crypsis" (:discard (get-runner))) "Crypsis was trashed")))) (testing "Working with auto-pump-and-break" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Crypsis"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Crypsis") (let [crypsis (get-program state 0) iw (get-ice state :hq 0)] (card-ability state :runner crypsis 2) (is (= 1 (get-counters (refresh crypsis) :virus)) "Crypsis has 1 virus counter") (run-on state "HQ") (rez state :corp (refresh iw)) (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh crypsis)}) (core/continue state :corp nil) (is (= 0 (get-counters (refresh crypsis) :virus)) "Used up virus token on Crypsis"))))) (deftest cyber-cypher (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Macrophage" "Macrophage"] :credits 100} :runner {:hand ["Cyber-Cypher"] :credits 100}}) (play-from-hand state :corp "Macrophage" "R&D") (play-from-hand state :corp "Macrophage" "HQ") (rez state :corp (get-ice state :rd 0)) (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Cyber-Cypher") (click-prompt state :runner "HQ") (let [cc (get-program state 0)] (run-on state :hq) (run-continue state) (card-ability state :runner cc 1) (card-ability state :runner cc 1) (card-ability state :runner cc 1) (is (= 7 (get-strength (refresh cc))) "Can pump Cyber-Cypher on the right server") (card-ability state :runner cc 0) (click-prompt state :runner "Trace 4 - Purge virus counters") (click-prompt state :runner "Trace 3 - Trash a virus") (click-prompt state :runner "Done") (is (= 2 (count (filter :broken (:subroutines (get-ice state :hq 0))))) "Can break subs on the right server") (run-jack-out state)) (let [cc (get-program state 0)] (run-on state :rd) (run-continue state) (card-ability state :runner cc 1) (is (= 4 (get-strength (refresh cc))) "Can't pump Cyber-Cyper on a different server") (core/update! state :runner (assoc (refresh cc) :current-strength 7)) (is (= 7 (get-strength (refresh cc))) "Manually set equal strength") (card-ability state :runner cc 0) (is (empty? (:prompt (get-runner))) "Can't break subs on a different server") (is (zero? (count (filter :broken (:subroutines (get-ice state :rd 0))))) "No subs are broken")))) (deftest d4v1d ;; D4v1d (testing "Can break 5+ strength ice" (do-game (new-game {:corp {:deck ["Ice Wall" "Hadrian's Wall"]} :runner {:deck ["D4v1d"]}}) (core/gain state :corp :credit 10) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Hadrian's Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "D4v1d") (let [had (get-ice state :hq 1) iw (get-ice state :hq 0) d4 (get-program state 0)] (is (= 3 (get-counters d4 :power)) "D4v1d installed with 3 power tokens") (run-on state :hq) (rez state :corp had) (run-continue state) (card-ability state :runner d4 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (is (= 1 (get-counters (refresh d4) :power)) "Used 2 power tokens from D4v1d to break") (run-continue state) (rez state :corp iw) (run-continue state) (card-ability state :runner d4 0) (is (empty? (:prompt (get-runner))) "No prompt for breaking 1 strength Ice Wall"))))) (deftest dai-v ;; Dai V (testing "Basic test" (do-game (new-game {:corp {:deck ["Enigma"]} :runner {:deck [(qty "Cloak" 2) "Dai V"]}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Cloak") (play-from-hand state :runner "Cloak") (play-from-hand state :runner "Dai V") (run-on state :hq) (let [enig (get-ice state :hq 0) cl1 (get-program state 0) cl2 (get-program state 1) daiv (get-program state 2)] (rez state :corp enig) (run-continue state) (changes-val-macro -1 (:credit (get-runner)) "Used 1 credit to pump and 2 credits from Cloaks to break" (card-ability state :runner daiv 1) (click-prompt state :runner "Done") (card-ability state :runner daiv 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (click-card state :runner cl1) (click-card state :runner cl2)))))) (deftest darwin ;; Darwin - starts at 0 strength (do-game (new-game {:runner {:deck ["Darwin"]}}) (take-credits state :corp) (play-from-hand state :runner "Darwin") (let [darwin (get-program state 0)] (is (zero? (get-counters (refresh darwin) :virus)) "Darwin starts with 0 virus counters") (is (zero? (get-strength (refresh darwin))) "Darwin starts at 0 strength") (take-credits state :runner) (take-credits state :corp) (card-ability state :runner (refresh darwin) 1) ; add counter (is (= 1 (get-counters (refresh darwin) :virus)) "Darwin gains 1 virus counter") (is (= 1 (get-strength (refresh darwin))) "Darwin is at 1 strength")))) (deftest datasucker ;; Datasucker - Reduce strength of encountered ICE (testing "Basic test" (do-game (new-game {:corp {:deck ["Fire Wall"]} :runner {:deck ["Datasucker"]}}) (play-from-hand state :corp "Fire Wall" "New remote") (take-credits state :corp) (core/gain state :runner :click 3) (play-from-hand state :runner "Datasucker") (let [ds (get-program state 0) fw (get-ice state :remote1 0)] (run-empty-server state "Archives") (is (= 1 (get-counters (refresh ds) :virus))) (run-empty-server state "Archives") (is (= 2 (get-counters (refresh ds) :virus))) (run-on state "Server 1") (run-continue state) (run-continue state) (is (= 2 (get-counters (refresh ds) :virus)) "No counter gained, not a central server") (run-on state "Server 1") (rez state :corp fw) (run-continue state) (is (= 5 (get-strength (refresh fw)))) (card-ability state :runner ds 0) (is (= 1 (get-counters (refresh ds) :virus)) "1 counter spent from Datasucker") (is (= 4 (get-strength (refresh fw))) "Fire Wall strength lowered by 1")))) (testing "does not affect next ice when current is trashed. Issue #1788" (do-game (new-game {:corp {:deck ["Wraparound" "Spiderweb"]} :runner {:deck ["Datasucker" "Parasite"]}}) (play-from-hand state :corp "Wraparound" "HQ") (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (core/gain state :corp :credit 10) (play-from-hand state :runner "Datasucker") (let [sucker (get-program state 0) wrap (get-ice state :hq 0) spider (get-ice state :hq 1)] (core/add-counter state :runner sucker :virus 2) (rez state :corp spider) (rez state :corp wrap) (play-from-hand state :runner "Parasite") (click-card state :runner "Spiderweb") (run-on state "HQ") (run-continue state) (card-ability state :runner (refresh sucker) 0) (card-ability state :runner (refresh sucker) 0) (is (find-card "Spiderweb" (:discard (get-corp))) "Spiderweb trashed by Parasite + Datasucker") (is (= 7 (get-strength (refresh wrap))) "Wraparound not reduced by Datasucker"))))) (deftest davinci ;; DaVinci (testing "Gain 1 counter on successful run" (do-game (new-game {:runner {:hand ["DaVinci"]}}) (take-credits state :corp) (play-from-hand state :runner "DaVinci") (run-on state "HQ") (changes-val-macro 1 (get-counters (get-program state 0) :power) "DaVinci gains 1 counter on successful run" (run-continue state)))) (testing "Gain no counters on unsuccessful run" (do-game (new-game {:runner {:hand ["DaVinci"]}}) (take-credits state :corp) (play-from-hand state :runner "DaVinci") (run-on state "HQ") (run-continue state) (changes-val-macro 0 (get-counters (get-program state 0) :power) "DaVinci does not gain counter on unsuccessful run" (run-jack-out state)))) (testing "Install a card with install cost lower than number of counters" (do-game (new-game {:runner {:hand ["DaVinci" "The Turning Wheel"]}}) (take-credits state :corp) (play-from-hand state :runner "DaVinci") (let [davinci (get-program state 0)] (core/add-counter state :runner davinci :power 2) (changes-val-macro 0 (:credit (get-runner)) "DaVinci installs The Turning Wheel for free" (card-ability state :runner (refresh davinci) 0) (click-card state :runner "The Turning Wheel")) (is (get-resource state 0) "The Turning Wheel is installed") (is (find-card "DaVinci" (:discard (get-runner))) "DaVinci is trashed")))) (testing "Using ability should trigger trash effects first. Issue #4987" (do-game (new-game {:runner {:id "Armand \"Geist\" Walker: Tech Lord" :deck ["Simulchip"] :hand ["DaVinci" "The Turning Wheel"]}}) (take-credits state :corp) (play-from-hand state :runner "DaVinci") (let [davinci (get-program state 0)] (core/add-counter state :runner davinci :power 2) (changes-val-macro 0 (:credit (get-runner)) "DaVinci installs Simulchip for free" (card-ability state :runner (refresh davinci) 0) (click-card state :runner "Simulchip")) (is (get-hardware state 0) "Simulchip is installed") (is (find-card "DaVinci" (:discard (get-runner))) "DaVinci is trashed"))))) (deftest demara ;; Demara (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Demara"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Demara") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 2) (is (= :approach-server (:phase (get-run))) "Run has bypassed Ice Wall") (is (find-card "Demara" (:discard (get-runner))) "Demara is trashed"))) (deftest deus-x (testing "vs Multiple Hostile Infrastructure" (do-game (new-game {:corp {:deck [(qty "Hostile Infrastructure" 3)]} :runner {:deck [(qty "Deus X" 3) (qty "Sure Gamble" 2)]}}) (play-from-hand state :corp "Hostile Infrastructure" "New remote") (play-from-hand state :corp "Hostile Infrastructure" "New remote") (play-from-hand state :corp "Hostile Infrastructure" "New remote") (core/gain state :corp :credit 10) (rez state :corp (get-content state :remote1 0)) (rez state :corp (get-content state :remote2 0)) (rez state :corp (get-content state :remote3 0)) (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Deus X") (run-empty-server state "Server 1") (click-prompt state :runner "Pay 5 [Credits] to trash") (let [dx (get-program state 0)] (card-ability state :runner dx 1) (is (= 2 (count (:hand (get-runner)))) "Deus X prevented one Hostile net damage")))) (testing "vs Multiple sources of net damage" (do-game (new-game {:corp {:id "Jinteki: Personal Evolution" :deck [(qty "Fetal AI" 6)]} :runner {:deck [(qty "Deus X" 3) (qty "Sure Gamble" 2)]}}) (play-from-hand state :corp "Fetal AI" "New remote") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Deus X") (run-empty-server state "Server 1") (let [dx (get-program state 0)] (card-ability state :runner dx 1) (click-prompt state :runner "Pay to steal") (is (= 3 (count (:hand (get-runner)))) "Deus X prevented net damage from accessing Fetal AI, but not from Personal Evolution") (is (= 1 (count (:scored (get-runner)))) "Fetal AI stolen"))))) (deftest dhegdheer ;; Dheghdheer - hosting a breaker with strength based on unused MU should calculate correctly (testing "with credit savings" (do-game (new-game {:runner {:deck ["Adept" "Dhegdheer"]}}) (take-credits state :corp) (core/gain state :runner :credit 5) (play-from-hand state :runner "Dhegdheer") (play-from-hand state :runner "Adept") (is (= 3 (:credit (get-runner))) "3 credits left after individual installs") (is (= 2 (core/available-mu state)) "2 MU used") (let [dheg (get-program state 0) adpt (get-program state 1)] (is (= 4 (get-strength (refresh adpt))) "Adept at 4 strength individually") (card-ability state :runner dheg 1) (click-card state :runner (refresh adpt)) (let [hosted-adpt (first (:hosted (refresh dheg)))] (is (= 4 (:credit (get-runner))) "4 credits left after hosting") (is (= 4 (core/available-mu state)) "0 MU used") (is (= 6 (get-strength (refresh hosted-adpt))) "Adept at 6 strength hosted"))))) (testing "without credit savings" (do-game (new-game {:runner {:deck ["Adept" "Dhegdheer"]}}) (take-credits state :corp) (core/gain state :runner :credit 5) (play-from-hand state :runner "Dhegdheer") (play-from-hand state :runner "Adept") (is (= 3 (:credit (get-runner))) "3 credits left after individual installs") (is (= 2 (core/available-mu state)) "2 MU used") (let [dheg (get-program state 0) adpt (get-program state 1)] (is (= 4 (get-strength (refresh adpt))) "Adept at 4 strength individually") (card-ability state :runner dheg 2) (click-card state :runner (refresh adpt)) (let [hosted-adpt (first (:hosted (refresh dheg)))] (is (= 3 (:credit (get-runner))) "4 credits left after hosting") (is (= 4 (core/available-mu state)) "0 MU used") (is (= 6 (get-strength (refresh hosted-adpt))) "Adept at 6 strength hosted")))))) (deftest disrupter ;; Disrupter (do-game (new-game {:corp {:deck [(qty "SEA Source" 2)]} :runner {:deck ["Disrupter"]}}) (take-credits state :corp) (run-empty-server state "Archives") (play-from-hand state :runner "Disrupter") (take-credits state :runner) (play-from-hand state :corp "SEA Source") (click-prompt state :runner "Yes") (is (zero? (:base (prompt-map :corp))) "Base trace should now be 0") (is (= 1 (-> (get-runner) :discard count)) "Disrupter should be in Heap") (click-prompt state :corp "0") (click-prompt state :runner "0") (is (zero? (count-tags state)) "Runner should gain no tag from beating trace") (play-from-hand state :corp "SEA Source") (is (= 3 (:base (prompt-map :corp))) "Base trace should be reset to 3"))) (deftest diwan ;; Diwan - Full test (do-game (new-game {:corp {:deck [(qty "Ice Wall" 3) (qty "Fire Wall" 3) (qty "Crisium Grid" 2)]} :runner {:deck ["Diwan"]}}) (take-credits state :corp) (play-from-hand state :runner "Diwan") (click-prompt state :runner "HQ") (take-credits state :runner) (is (= 8 (:credit (get-corp))) "8 credits for corp at start of second turn") (play-from-hand state :corp "Ice Wall" "R&D") (is (= 8 (:credit (get-corp))) "Diwan did not charge extra for install on another server") (play-from-hand state :corp "Ice Wall" "HQ") (is (= 7 (:credit (get-corp))) "Diwan charged 1cr to install ice protecting the named server") (play-from-hand state :corp "Crisium Grid" "HQ") (is (= 7 (:credit (get-corp))) "Diwan didn't charge to install another upgrade in root of HQ") (take-credits state :corp) (take-credits state :runner) (play-from-hand state :corp "Ice Wall" "HQ") (is (= 5 (:credit (get-corp))) "Diwan charged 1cr + 1cr to install a second ice protecting the named server") (core/gain state :corp :click 1) (core/purge state :corp) (play-from-hand state :corp "Fire Wall" "HQ") ; 2cr cost from normal install cost (is (= "Diwan" (-> (get-runner) :discard first :title)) "Diwan was trashed from purge") (is (= 3 (:credit (get-corp))) "No charge for installs after Diwan purged"))) (deftest djinn ;; Djinn (testing "Hosted Chakana does not disable advancing agendas. Issue #750" (do-game (new-game {:corp {:deck ["Priority Requisition"]} :runner {:deck ["Djinn" "Chakana"]}}) (play-from-hand state :corp "Priority Requisition" "New remote") (take-credits state :corp 2) (play-from-hand state :runner "Djinn") (let [djinn (get-program state 0) agenda (get-content state :remote1 0)] (is agenda "Agenda was installed") (card-ability state :runner djinn 1) (click-card state :runner (find-card "Chakana" (:hand (get-runner)))) (let [chak (first (:hosted (refresh djinn)))] (is (= "Chakana" (:title chak)) "Djinn has a hosted Chakana") ;; manually add 3 counters (core/add-counter state :runner (first (:hosted (refresh djinn))) :virus 3) (take-credits state :runner 2) (core/advance state :corp {:card agenda}) (is (= 1 (get-counters (refresh agenda) :advancement)) "Agenda was advanced"))))) (testing "Host a non-icebreaker program" (do-game (new-game {:runner {:deck ["Djinn" "Chakana"]}}) (take-credits state :corp) (play-from-hand state :runner "Djinn") (is (= 3 (core/available-mu state))) (let [djinn (get-program state 0)] (card-ability state :runner djinn 1) (click-card state :runner (find-card "Chakana" (:hand (get-runner)))) (is (= 3 (core/available-mu state)) "No memory used to host on Djinn") (is (= "Chakana" (:title (first (:hosted (refresh djinn))))) "Djinn has a hosted Chakana") (is (= 1 (:credit (get-runner))) "Full cost to host on Djinn")))) (testing "Tutor a virus program" (do-game (new-game {:runner {:deck ["Djinn" "Parasite"]}}) (take-credits state :corp) (play-from-hand state :runner "Djinn") (core/move state :runner (find-card "Parasite" (:hand (get-runner))) :deck) (is (zero? (count (:hand (get-runner)))) "No cards in hand after moving Parasite to deck") (let [djinn (get-program state 0)] (card-ability state :runner djinn 0) (click-prompt state :runner (find-card "Parasite" (:deck (get-runner)))) (is (= "Parasite" (:title (first (:hand (get-runner))))) "Djinn moved Parasite to hand") (is (= 2 (:credit (get-runner))) "1cr to use Djinn ability") (is (= 2 (:click (get-runner))) "1click to use Djinn ability"))))) (deftest eater (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 2)]} :runner {:deck [(qty "Eater" 2)]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (core/gain state :runner :credit 100) (play-from-hand state :runner "Eater") (let [eater (get-program state 0) iw (get-ice state :hq 0)] (run-on state "HQ") (rez state :corp (refresh iw)) (run-continue state) (card-ability state :runner eater 0) (click-prompt state :runner "End the run") (run-continue state) (run-continue state) (is (empty? (:prompt (get-runner))) "No prompt for accessing cards")))) (testing "Eater interaction with remote server. Issue #4536" (do-game (new-game {:corp {:deck [(qty "Rototurret" 2) "NGO Front"]} :runner {:deck [(qty "Eater" 2)]}}) (play-from-hand state :corp "NGO Front" "New remote") (play-from-hand state :corp "Rototurret" "Server 1") (take-credits state :corp) (core/gain state :runner :credit 100) (play-from-hand state :runner "Eater") (let [eater (get-program state 0) ngo (get-content state :remote1 0) rt (get-ice state :remote1 0)] (run-on state "Server 1") (rez state :corp (refresh rt)) (run-continue state) (card-ability state :runner eater 0) (click-prompt state :runner "End the run") (click-prompt state :runner "Done") (fire-subs state (refresh rt)) (click-card state :corp eater) (run-continue state) (run-continue state) (is (find-card "Eater" (:discard (get-runner))) "Eater is trashed") (is (empty? (:prompt (get-runner))) "No prompt for accessing cards"))))) (deftest echelon ;; Echelon (before-each [state (new-game {:runner {:hand [(qty "Echelon" 5)] :credits 20} :corp {:deck [(qty "Hedge Fund" 5)] :hand ["Owl"] :credits 20}}) _ (do (play-from-hand state :corp "Owl" "HQ") (take-credits state :corp)) owl (get-ice state :hq 0)] (testing "pump ability" (do-game state (play-from-hand state :runner "Echelon") (let [echelon (get-program state 0)] (run-on state :hq) (rez state :corp owl) (run-continue state :encounter-ice) (changes-val-macro -3 (:credit (get-runner)) "Pump costs 3" (card-ability state :runner echelon 1)) (changes-val-macro 2 (get-strength (refresh echelon)) "Echelon gains 2 str" (card-ability state :runner echelon 1))))) (testing "break ability" (do-game state (play-from-hand state :runner "Echelon") (let [echelon (get-program state 0)] (run-on state :hq) (rez state :corp owl) (run-continue state :encounter-ice) (changes-val-macro -1 (:credit (get-runner)) "Break costs 1" (card-ability state :runner echelon 0) (click-prompt state :runner "Add installed program to the top of the Runner's Stack")) (is (empty? (:prompt (get-runner))) "Only breaks 1 sub at a time")))) (testing "Gains str per icebreaker" (do-game state (take-credits state :corp) (play-from-hand state :runner "Echelon") (let [echelon (get-program state 0)] (is (= 1 (get-strength (refresh echelon))) "0 + 1 icebreaker installed") (play-from-hand state :runner "Echelon") (is (= 2 (get-strength (refresh echelon))) "0 + 2 icebreaker installed") (play-from-hand state :runner "Echelon") (is (= 3 (get-strength (refresh echelon))) "0 + 3 icebreaker installed")))))) (deftest egret ;; Egret (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Mother Goddess"]} :runner {:hand [(qty "Egret" 2)]}}) (play-from-hand state :corp "Mother Goddess" "HQ") (rez state :corp (get-ice state :hq 0)) (let [mg (get-ice state :hq 0)] (take-credits state :corp) (play-from-hand state :runner "Egret") (click-card state :runner mg) (is (has-subtype? (refresh mg) "Barrier")) (is (has-subtype? (refresh mg) "Code Gate")) (is (has-subtype? (refresh mg) "Sentry")) (trash state :runner (first (:hosted (refresh mg)))) (is (not (has-subtype? (refresh mg) "Barrier"))) (is (not (has-subtype? (refresh mg) "Code Gate"))) (is (not (has-subtype? (refresh mg) "Sentry")))))) (deftest engolo ;; Engolo (testing "Subtype is removed when Engolo is trashed mid-encounter. Issue #4039" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"]} :runner {:hand ["Engolo"] :credits 10}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (play-from-hand state :runner "Engolo") (let [roto (get-ice state :hq 0) engolo (get-program state 0)] (run-on state :hq) (rez state :corp roto) (run-continue state) (click-prompt state :runner "Yes") (is (has-subtype? (refresh roto) "Code Gate")) (card-subroutine state :corp roto 0) (click-card state :corp engolo) (run-continue state) (is (nil? (refresh engolo)) "Engolo is trashed") (is (not (has-subtype? (refresh roto) "Code Gate")) "Rototurret loses subtype even when Engolo is trashed")))) (testing "Marks eid as :ability #4962" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"]} :runner {:hand ["Engolo" "Trickster Taka"] :credits 20}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (play-from-hand state :runner "Trickster Taka") (core/add-counter state :runner (get-resource state 0) :credit 2) (play-from-hand state :runner "Engolo") (let [roto (get-ice state :hq 0) engolo (get-program state 0)] (run-on state :hq) (rez state :corp roto) (run-continue state) (changes-val-macro 0 (:credit (get-runner)) "Runner spends credits on Taka" (click-prompt state :runner "Yes") (click-card state :runner "Trickster Taka") (click-card state :runner "Trickster Taka")) (is (zero? (get-counters (get-resource state 0) :credit)) "Taka has been used") (run-jack-out state) (is (nil? (get-run))) (is (empty? (:prompt (get-corp)))) (is (empty? (:prompt (get-runner)))))))) (deftest equivocation ;; Equivocation - interactions with other successful-run events. (do-game (new-game {:corp {:deck [(qty "Restructure" 3) (qty "Hedge Fund" 3)]} :runner {:id "Laramy Fisk: Savvy Investor" :deck ["Equivocation" "Desperado"]}}) (starting-hand state :corp ["Hedge Fund"]) (take-credits state :corp) (play-from-hand state :runner "Equivocation") (play-from-hand state :runner "Desperado") (run-empty-server state :rd) (click-prompt state :runner "Laramy Fisk: Savvy Investor") (click-prompt state :runner "Yes") (is (= 2 (count (:hand (get-corp)))) "Corp forced to draw by Fisk") (click-prompt state :runner "Yes") ; Equivocation prompt (click-prompt state :runner "Yes") ; force the draw (is (= 1 (:credit (get-runner))) "Runner gained 1cr from Desperado") (is (= 3 (count (:hand (get-corp)))) "Corp forced to draw by Equivocation") (click-prompt state :runner "No action") (is (not (:run @state)) "Run ended"))) (deftest euler ;; Euler (testing "Basic test" (do-game (new-game {:runner {:hand ["Euler"] :credits 20} :corp {:hand ["Enigma"]}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Euler") (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state) (changes-val-macro 0 (:credit (get-runner)) "Broke Enigma for 0c" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (get-program state 0)}) (core/continue state :corp nil)) (run-jack-out state) (take-credits state :runner) (take-credits state :corp) (run-on state :hq) (run-continue state) (changes-val-macro -2 (:credit (get-runner)) "Broke Enigma for 2c" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (get-program state 0)}) (core/continue state :corp nil)))) (testing "Correct log test" (do-game (new-game {:runner {:hand ["Euler"] :credits 20} :corp {:hand ["Enigma"]}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Euler") (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (get-program state 0)}) (is (second-last-log-contains? state "Runner pays 0 \\[Credits\\] to use Euler to break all 2 subroutines on Enigma.") "Correct log with correct cost") (core/continue state :corp nil) (run-jack-out state) (take-credits state :runner) (take-credits state :corp) (run-on state :hq) (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (get-program state 0)}) (is (second-last-log-contains? state "Runner pays 2 \\[Credits\\] to use Euler to break all 2 subroutines on Enigma.") "Correct second log with correct cost") (core/continue state :corp nil)))) (deftest expert-schedule-analyzer ;; Expert Schedule Analyzer (do-game (new-game {:runner {:deck ["Expert Schedule Analyzer"]}}) (take-credits state :corp) (play-from-hand state :runner "Expert Schedule Analyzer") (card-ability state :runner (get-program state 0) 0) (run-continue state) (is (= "Choose an access replacement ability" (:msg (prompt-map :runner))) "Replacement effect is optional") (click-prompt state :runner "Expert Schedule Analyzer") (is (last-log-contains? state "Runner uses Expert Schedule Analyzer to reveal all of the cards cards in HQ:") "All of HQ is revealed correctly"))) (deftest faerie (testing "Trash after encounter is over, not before" (do-game (new-game {:corp {:deck ["Caduceus"]} :runner {:deck ["Faerie"]}}) (play-from-hand state :corp "Caduceus" "Archives") (take-credits state :corp) (play-from-hand state :runner "Faerie") (let [fae (get-program state 0)] (run-on state :archives) (rez state :corp (get-ice state :archives 0)) (run-continue state) (card-ability state :runner fae 1) (card-ability state :runner fae 0) (click-prompt state :runner "Trace 3 - Gain 3 [Credits]") (click-prompt state :runner "Trace 2 - End the run") (is (refresh fae) "Faerie not trashed until encounter over") (run-continue state) (is (find-card "Faerie" (:discard (get-runner))) "Faerie trashed")))) (testing "Works with auto-pump-and-break" (do-game (new-game {:corp {:deck ["Caduceus"]} :runner {:deck ["Faerie"]}}) (play-from-hand state :corp "Caduceus" "Archives") (take-credits state :corp) (play-from-hand state :runner "Faerie") (let [fae (get-program state 0)] (run-on state :archives) (rez state :corp (get-ice state :archives 0)) (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh fae)}) (core/continue state :corp nil) (is (find-card "Faerie" (:discard (get-runner))) "Faerie trashed"))))) (deftest false-echo ;; False Echo - choice for Corp (testing "Add to HQ" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["False Echo"]}}) (play-from-hand state :corp "Ice Wall" "Archives") (take-credits state :corp) (play-from-hand state :runner "False Echo") (run-on state "Archives") (run-continue state) (click-prompt state :runner "Yes") (click-prompt state :corp "Add to HQ") (is (find-card "Ice Wall" (:hand (get-corp))) "Ice Wall added to HQ") (is (find-card "False Echo" (:discard (get-runner))) "False Echo trashed"))) (testing "Rez" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["False Echo"]}}) (play-from-hand state :corp "Ice Wall" "Archives") (take-credits state :corp) (play-from-hand state :runner "False Echo") (run-on state "Archives") (run-continue state) (click-prompt state :runner "Yes") (click-prompt state :corp "Rez") (is (rezzed? (get-ice state :archives 0)) "Ice Wall rezzed") (is (find-card "False Echo" (:discard (get-runner))) "False Echo trashed")))) (deftest faust (testing "Basic test: Break by discarding" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:deck ["Faust" "Sure Gamble"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Faust") (let [faust (get-program state 0)] (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner faust 0) (click-prompt state :runner "End the run") (click-card state :runner "Sure Gamble") (is (= 1 (count (:discard (get-runner)))) "1 card trashed")))) (testing "Basic test: Pump by discarding" (do-game (new-game {:runner {:deck ["Faust" "Sure Gamble"]}}) (take-credits state :corp) (play-from-hand state :runner "Faust") (let [faust (get-program state 0)] (card-ability state :runner faust 1) (click-card state :runner "Sure Gamble") (is (= 4 (get-strength (refresh faust))) "4 current strength") (is (= 1 (count (:discard (get-runner)))) "1 card trashed")))) (testing "Pump does not trigger trash prevention. #760" (do-game (new-game {:runner {:hand ["Faust" "Sacrificial Construct" "Fall Guy" "Astrolabe" "Gordian Blade" "Armitage Codebusting"]}}) (take-credits state :corp) (play-from-hand state :runner "Faust") (play-from-hand state :runner "Fall Guy") (play-from-hand state :runner "Sacrificial Construct") (is (= 2 (count (get-resource state))) "Resources installed") (let [faust (get-program state 0)] (card-ability state :runner faust 1) (click-card state :runner "Astrolabe") (is (empty? (:prompt (get-runner))) "No trash-prevention prompt for hardware") (card-ability state :runner faust 1) (click-card state :runner "Gordian Blade") (is (empty? (:prompt (get-runner))) "No trash-prevention prompt for program") (card-ability state :runner faust 1) (click-card state :runner "Armitage Codebusting") (is (empty? (:prompt (get-runner))) "No trash-prevention prompt for resource"))))) (deftest femme-fatale ;; Femme Fatale (testing "Bypass functionality" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Femme Fatale"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (let [iw (get-ice state :hq 0)] (play-from-hand state :runner "Femme Fatale") (click-card state :runner iw) (run-on state "HQ") (rez state :corp iw) (run-continue state) (is (= "Pay 1 [Credits] to bypass Ice Wall?" (:msg (prompt-map :runner)))) (click-prompt state :runner "Yes") (is (= :approach-server (:phase (get-run))) "Femme Fatale has bypassed Ice Wall")))) (testing "Bypass leaves if uninstalled" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Femme Fatale"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (let [iw (get-ice state :hq 0)] (play-from-hand state :runner "Femme Fatale") (click-card state :runner iw) (core/move state :runner (get-program state 0) :deck) (run-on state "HQ") (rez state :corp iw) (run-continue state) (is (nil? (prompt-map :runner)) "Femme ability doesn't fire after uninstall")))) (testing "Bypass doesn't persist if ice is uninstalled and reinstalled" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Femme Fatale"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Femme Fatale") (click-card state :runner (get-ice state :hq 0)) (core/move state :corp (get-ice state :hq 0) :hand) (take-credits state :runner) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (is (nil? (prompt-map :runner)) "Femme ability doesn't fire after uninstall")))) (deftest fermenter ;; Fermenter - click, trash to get 2c per counter. (testing "Trash and cash out" (do-game (new-game {:runner {:deck ["Fermenter"]}}) (take-credits state :corp) (play-from-hand state :runner "Fermenter") (let [fermenter (get-program state 0)] (is (= 1 (get-counters (refresh fermenter) :virus)) "Fermenter has 1 counter from install") (take-credits state :runner) (take-credits state :corp) (is (= 2 (get-counters (refresh fermenter) :virus)) "Fermenter has 2 counters") (changes-val-macro 4 (:credit (get-runner)) "Gain 4 credits from Fermenter ability" (card-ability state :runner fermenter 0)) (is (= 1 (count (:discard (get-runner)))) "Fermenter is trashed")))) (testing "Hivemind interaction" (do-game (new-game {:corp {:deck ["Adonis Campaign"]} :runner {:deck ["Fermenter" "Hivemind"]}}) (take-credits state :corp) (play-from-hand state :runner "Fermenter") (play-from-hand state :runner "Hivemind") (take-credits state :runner) (take-credits state :corp) (let [fermenter (get-program state 0) hivemind (get-program state 1)] (is (= 2 (get-counters (refresh fermenter) :virus)) "Fermenter has 2 counters") (is (= 1 (get-counters (refresh hivemind) :virus)) "Hivemind has 1 counter") (changes-val-macro 6 (:credit (get-runner)) "Gain 6 credits from Fermenter ability" (card-ability state :runner fermenter 0)) (is (= 1 (count (:discard (get-runner)))) "Fermenter is trashed") (is (= 1 (get-counters (refresh hivemind) :virus)) "Hivemind has still 1 counter"))))) (deftest gauss ;; Gauss (testing "Loses strength at end of Runner's turn" (do-game (new-game {:runner {:deck ["Gauss"]} :options {:start-as :runner}}) (play-from-hand state :runner "Gauss") (let [gauss (get-program state 0)] (is (= 4 (get-strength (refresh gauss))) "+3 base strength") (run-on state :hq) (card-ability state :runner (refresh gauss) 1) ;; boost (is (= 6 (get-strength (refresh gauss))) "+3 base and boosted strength") (run-jack-out state) (is (= 4 (get-strength (refresh gauss))) "Boost lost after run") (take-credits state :runner) (is (= 1 (get-strength (refresh gauss))) "Back to normal strength")))) (testing "Loses strength at end of Corp's turn" (do-game (new-game {:runner {:deck ["Gauss"]}}) (core/gain state :runner :click 1) (play-from-hand state :runner "Gauss") (let [gauss (get-program state 0)] (is (= 4 (get-strength (refresh gauss))) "+3 base strength") (take-credits state :corp) (is (= 1 (get-strength (refresh gauss))) "Back to normal strength"))))) (deftest god-of-war ;; God of War - Take 1 tag to place 2 virus counters (do-game (new-game {:runner {:deck ["God of War"]}}) (take-credits state :corp) (play-from-hand state :runner "God of War") (take-credits state :runner) (take-credits state :corp) (let [gow (get-program state 0)] (card-ability state :runner gow 2) (is (= 1 (count-tags state))) (is (= 2 (get-counters (refresh gow) :virus)) "God of War has 2 virus counters")))) (deftest grappling-hook ;; Grappling Hook (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Little Engine"] :credits 10} :runner {:hand [(qty "Grappling Hook" 2) "Corroder" "Torch"] :credits 100}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Little Engine" "New remote") (take-credits state :corp) (core/gain state :runner :click 10) (play-from-hand state :runner "Grappling Hook") (play-from-hand state :runner "Grappling Hook") (play-from-hand state :runner "Corroder") (play-from-hand state :runner "Torch") (let [iw (get-ice state :hq 0) le (get-ice state :remote1 0) gh1 (get-program state 0) gh2 (get-program state 1) cor (get-program state 2) torch (get-program state 3)] (run-on state :hq) (rez state :corp iw) (run-continue state) (card-ability state :runner gh1 0) (is (empty? (:prompt (get-runner))) "No break prompt as Ice Wall only has 1 subroutine") (is (refresh gh1) "Grappling Hook isn't trashed") (card-ability state :runner cor 0) (click-prompt state :runner "End the run") (card-ability state :runner gh1 0) (is (empty? (:prompt (get-runner))) "No break prompt as Ice Wall has no unbroken subroutines") (is (refresh gh1) "Grappling Hook isn't trashed") (run-jack-out state) (run-on state :remote1) (rez state :corp le) (run-continue state) (card-ability state :runner gh1 0) (is (seq (:prompt (get-runner))) "Grappling Hook creates break prompt") (click-prompt state :runner "End the run") (is (= 2 (count (filter :broken (:subroutines (refresh le))))) "Little Engine has 2 of 3 subroutines broken") (is (nil? (refresh gh1)) "Grappling Hook is now trashed") (run-jack-out state) (run-on state :remote1) (run-continue state) (core/update! state :runner (assoc (refresh torch) :current-strength 7)) (card-ability state :runner torch 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (click-prompt state :runner "Done") (card-ability state :runner gh2 0) (is (empty? (:prompt (get-runner))) "No break prompt as Little Engine has more than 1 broken sub") (is (refresh gh2) "Grappling Hook isn't trashed")))) (testing "Interaction with Fairchild 3.0" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Fairchild 3.0"] :credits 6} :runner {:hand ["Grappling Hook"] }}) (play-from-hand state :corp "Fairchild 3.0" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Grappling Hook") (run-on state "HQ") (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "Do 1 brain damage or end the run") (is (= 1 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broke all but one subroutine") (is (= "Do 1 brain damage or end the run" (:label (first (remove :broken (:subroutines (get-ice state :hq 0)))))) "Broke all but selected sub") (is (nil? (refresh (get-program state 0))) "Grappling Hook is now trashed"))) (testing "interaction with News Hound #4988" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["News Hound" "Surveillance Sweep"] :credits 10} :runner {:hand ["Grappling Hook"] :credits 100}}) (play-from-hand state :corp "News Hound" "HQ") (play-from-hand state :corp "Surveillance Sweep") (take-credits state :corp) (play-from-hand state :runner "Grappling Hook") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "Trace 3 - Give the Runner 1 tag") (fire-subs state (get-ice state :hq 0)) (click-prompt state :runner "10") (click-prompt state :corp "1") (is (zero? (count-tags state)) "Runner gained no tags") (is (get-run) "Run hasn't ended") (is (empty? (:prompt (get-corp))) "Corp shouldn't have a prompt") (is (empty? (:prompt (get-runner))) "Runner shouldn't have a prompt"))) (testing "Selecting a sub when multiple of the same title exist #5291" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Hive"] :credits 10} :runner {:hand ["Grappling Hook" "Gbahali"] :credits 10}}) (play-from-hand state :corp "Hive" "HQ") (take-credits state :corp) (play-from-hand state :runner "Grappling Hook") (play-from-hand state :runner "Gbahali") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) "Break all but 1 subroutine") (click-prompt state :runner "End the run" {:idx 4}) (card-ability state :runner (get-resource state 0) "Break the last subroutine") (is (core/all-subs-broken? (get-ice state :hq 0)) "Grappling Hook and Gbahali worked together")))) (deftest gravedigger ;; Gravedigger - Gain counters when Corp cards are trashed, spend click-counter to mill Corp (do-game (new-game {:corp {:deck [(qty "Launch Campaign" 2) (qty "Enigma" 2)]} :runner {:deck ["Gravedigger"]}}) (play-from-hand state :corp "Launch Campaign" "New remote") (play-from-hand state :corp "Launch Campaign" "New remote") (take-credits state :corp) (play-from-hand state :runner "Gravedigger") (let [gd (get-program state 0)] (trash state :corp (get-content state :remote1 0)) (is (= 1 (get-counters (refresh gd) :virus)) "Gravedigger gained 1 counter") (trash state :corp (get-content state :remote2 0)) (is (= 2 (get-counters (refresh gd) :virus)) "Gravedigger gained 1 counter") (core/move state :corp (find-card "Enigma" (:hand (get-corp))) :deck) (core/move state :corp (find-card "Enigma" (:hand (get-corp))) :deck) (is (= 2 (count (:deck (get-corp))))) (card-ability state :runner gd 0) (is (= 1 (get-counters (refresh gd) :virus)) "Spent 1 counter from Gravedigger") (is (= 2 (:click (get-runner))) "Spent 1 click") (is (= 1 (count (:deck (get-corp))))) (is (= 3 (count (:discard (get-corp)))) "Milled 1 card from R&D")))) (deftest harbinger ;; Harbinger (testing "install facedown when Blacklist installed" (do-game (new-game {:corp {:deck ["Blacklist"]} :runner {:deck ["Harbinger"]}}) (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (get-content state :remote1 0)) (take-credits state :corp) (play-from-hand state :runner "Harbinger") (trash state :runner (-> (get-runner) :rig :program first)) (is (zero? (count (:discard (get-runner)))) "Harbinger not in heap") (is (-> (get-runner) :rig :facedown first :facedown) "Harbinger installed facedown")))) (deftest hyperdriver ;; Hyperdriver - Remove from game to gain 3 clicks (testing "Basic test" (do-game (new-game {:runner {:deck ["Hyperdriver"]}}) (take-credits state :corp) (play-from-hand state :runner "Hyperdriver") (is (= 1 (core/available-mu state)) "3 MU used") (take-credits state :runner) (take-credits state :corp) (is (:runner-phase-12 @state) "Runner in Step 1.2") (let [hyp (get-program state 0)] (card-ability state :runner hyp 0) (end-phase-12 state :runner) (is (= 7 (:click (get-runner))) "Gained 3 clicks") (is (= 1 (count (:rfg (get-runner)))) "Hyperdriver removed from game")))) (testing "triggering a Dhegdeered Hyperdriver should not grant +3 MU" (do-game (new-game {:runner {:deck ["Hyperdriver" "Dhegdheer"]}}) (take-credits state :corp) (play-from-hand state :runner "Dhegdheer") (let [dheg (get-program state 0)] (card-ability state :runner dheg 0) (click-card state :runner (find-card "Hyperdriver" (:hand (get-runner)))) (is (= 4 (core/available-mu state)) "0 MU used by Hyperdriver hosted on Dhegdheer") (is (= 2 (:click (get-runner))) "2 clicks used") (is (= 3 (:credit (get-runner))) "2 credits used") (take-credits state :runner) (take-credits state :corp) (is (:runner-phase-12 @state) "Runner in Step 1.2") (let [hyp (first (:hosted (refresh dheg)))] (card-ability state :runner hyp 0) (end-phase-12 state :runner) (is (= 7 (:click (get-runner))) "Used Hyperdriver") (is (= 4 (core/available-mu state)) "Still 0 MU used after Hyperdriver removed from game")))))) (deftest ika ;; Ika (testing "Can be hosted on both rezzed/unrezzed ice, respects no-host, is blanked by Magnet" (do-game (new-game {:corp {:deck ["Tithonium" "Enigma" "Magnet"]} :runner {:deck ["Ika"]}}) (play-from-hand state :corp "Enigma" "HQ") (play-from-hand state :corp "Tithonium" "Archives") (play-from-hand state :corp "Magnet" "R&D") (take-credits state :corp) (play-from-hand state :runner "Ika") (core/gain state :runner :credit 100) (core/gain state :corp :credit 100) (let [ika (get-program state 0) enigma (get-ice state :hq 0) tithonium (get-ice state :archives 0) magnet (get-ice state :rd 0)] (let [creds (:credit (get-runner))] (card-ability state :runner ika 0) ; host on a piece of ice (click-card state :runner tithonium) (is (utils/same-card? ika (first (:hosted (refresh tithonium)))) "Ika was rehosted") (is (= (- creds 2) (:credit (get-runner))) "Rehosting from rig cost 2 creds")) (run-on state :archives) (run-continue state) (let [creds (:credit (get-runner)) ika (first (:hosted (refresh tithonium)))] (card-ability state :runner ika 0) (click-card state :runner enigma) (is (utils/same-card? ika (first (:hosted (refresh enigma)))) "Ika was rehosted") (is (= (- creds 2) (:credit (get-runner))) "Rehosting from ice during run cost 2 creds")) (rez state :corp tithonium) (let [creds (:credit (get-runner)) ika (first (:hosted (refresh enigma)))] (card-ability state :runner ika 0) (click-card state :runner tithonium) (is (zero?(count (:hosted (refresh tithonium)))) "Ika was not hosted on Tithonium") (is (= creds (:credit (get-runner))) "Clicking invalid targets is free") (click-prompt state :runner "Done") (rez state :corp magnet) (click-card state :corp ika) (is (zero?(count (:hosted (refresh enigma)))) "Ika was removed from Enigma") (is (= 1 (count (:hosted (refresh magnet)))) "Ika was hosted onto Magnet") (let [ika (first (:hosted (refresh magnet)))] (is (zero?(count (:abilities ika))) "Ika was blanked"))))))) (deftest imp ;; Imp (testing "Full test" (letfn [(imp-test [card] (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand [card]} :runner {:deck ["Imp"]}}) (take-credits state :corp) (play-from-hand state :runner "Imp") (run-empty-server state "HQ") (click-prompt state :runner "[Imp] Hosted virus counter: Trash card") (is (= 1 (count (:discard (get-corp)))))))] (doall (map imp-test ["Hostile Takeover" "Dedicated Response Team" "Beanstalk Royalties" "Ice Wall" "Oberth Protocol"])))) (testing "vs an ambush" (do-game (new-game {:corp {:deck ["Prisec"]} :runner {:deck ["Imp" (qty "Sure Gamble" 3)]}}) (play-from-hand state :corp "Prisec" "New remote") (take-credits state :corp) (let [credits (:credit (get-corp)) tags (count-tags state) grip (count (:hand (get-runner))) archives (count (:discard (get-corp)))] (play-from-hand state :runner "Imp") (run-empty-server state :remote1) (click-prompt state :corp "Yes") (click-prompt state :runner "[Imp] Hosted virus counter: Trash card") (is (= 2 (- credits (:credit (get-corp)))) "Corp paid 2 for Prisec") (is (= 1 (- (count-tags state) tags)) "Runner has 1 tag") (is (= 2 (- grip (count (:hand (get-runner))))) "Runner took 1 meat damage") (is (= 1 (- (count (:discard (get-corp))) archives)) "Used Imp to trash Prisec")))) (testing "vs The Future Perfect" ;; Psi-game happens on access [5.5.1], Imp is a trash ability [5.5.2] (do-game (new-game {:corp {:deck ["The Future Perfect"]} :runner {:deck ["Imp"]}}) (take-credits state :corp) (play-from-hand state :runner "Imp") (testing "Access, corp wins psi-game" (run-empty-server state "HQ") ;; Should access TFP at this point (click-prompt state :corp "1 [Credits]") (click-prompt state :runner "0 [Credits]") (click-prompt state :runner "[Imp] Hosted virus counter: Trash card") (take-credits state :runner) (is (= "The Future Perfect" (get-in @state [:corp :discard 0 :title])) "TFP trashed") (is (zero? (:agenda-point (get-runner))) "Runner did not steal TFP") (core/move state :corp (find-card "The Future Perfect" (:discard (get-corp))) :hand)) (take-credits state :runner) (take-credits state :corp) (testing "Access, runner wins psi-game" (run-empty-server state "HQ") ;; Access prompt for TFP (click-prompt state :corp "0 [Credits]") (click-prompt state :runner "0 [Credits]") ;; Fail psi game (click-prompt state :runner "[Imp] Hosted virus counter: Trash card") (is (= "The Future Perfect" (get-in @state [:corp :discard 0 :title])) "TFP trashed") (is (zero? (:agenda-point (get-runner))) "Runner did not steal TFP")))) (testing "vs cards in Archives" (do-game (new-game {:corp {:deck ["Hostile Takeover"]} :runner {:deck ["Imp"]}}) (core/move state :corp (find-card "Hostile Takeover" (:hand (get-corp))) :discard) (take-credits state :corp) (play-from-hand state :runner "Imp") (run-empty-server state "Archives") (is (= ["Steal"] (prompt-buttons :runner)) "Should only get the option to steal Hostile on access in Archives"))) (testing "Hivemind installed #5000" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:deck ["Imp" "Hivemind"]}}) (take-credits state :corp) (play-from-hand state :runner "Hivemind") (is (= 1 (get-counters (get-program state 0) :virus))) (play-from-hand state :runner "Imp") (core/add-counter state :runner (get-program state 1) :virus -2) (is (= 0 (get-counters (get-program state 1) :virus))) (run-empty-server state "HQ") (click-prompt state :runner "[Imp] Hosted virus counter: Trash card") (click-card state :runner "Hivemind") (is (= 1 (count (:discard (get-corp))))) (is (= 0 (get-counters (get-program state 0) :virus))))) (testing "can't be used when empty #5190" (do-game (new-game {:corp {:hand ["Hostile Takeover"]} :runner {:hand ["Imp" "Cache"]}}) (take-credits state :corp) (play-from-hand state :runner "Cache") (play-from-hand state :runner "Imp") (core/update! state :runner (assoc-in (get-program state 1) [:counter :virus] 0)) (run-empty-server state "HQ") (is (= ["Steal"] (prompt-buttons :runner)) "Should only get the option to steal Hostile on access in Archives")))) (deftest incubator ;; Incubator - Gain 1 virus counter per turn; trash to move them to an installed virus program (do-game (new-game {:runner {:deck ["Incubator" "Datasucker"]}}) (take-credits state :corp) (play-from-hand state :runner "Datasucker") (play-from-hand state :runner "Incubator") (take-credits state :runner) (take-credits state :corp) (let [ds (get-program state 0) incub (get-program state 1)] (is (= 1 (get-counters (refresh incub) :virus)) "Incubator gained 1 virus counter") (take-credits state :runner) (take-credits state :corp) (is (= 2 (get-counters (refresh incub) :virus)) "Incubator has 2 virus counters") (card-ability state :runner incub 0) (click-card state :runner ds) (is (= 2 (get-counters (refresh ds) :virus)) "Datasucker has 2 virus counters moved from Incubator") (is (= 1 (count (get-program state)))) (is (= 1 (count (:discard (get-runner)))) "Incubator trashed") (is (= 3 (:click (get-runner))))))) (deftest inversificator ;; Inversificator (testing "Shouldn't hook up events for unrezzed ice" (do-game (new-game {:corp {:deck ["Turing" "Kakugo"]} :runner {:deck ["Inversificator" "Sure Gamble"]}}) (play-from-hand state :corp "Kakugo" "HQ") (play-from-hand state :corp "Turing" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Inversificator") (let [inv (get-program state 0) tur (get-ice state :hq 1)] (is (= 1 (count (:hand (get-runner)))) "Runner starts with 1 card in hand") (run-on state "HQ") (rez state :corp (refresh tur)) (run-continue state) (card-ability state :runner (refresh inv) 0) (click-prompt state :runner "End the run unless the Runner spends [Click][Click][Click]") (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner (get-ice state :hq 1)) (click-card state :runner (get-ice state :hq 0)) (run-jack-out state) (is (= 1 (count (:hand (get-runner)))) "Runner still has 1 card in hand") (run-on state :hq) (run-continue state) (is (= 1 (count (:hand (get-runner)))) "Kakugo doesn't fire when unrezzed")))) (testing "Switched ice resets broken subs. Issue #4857" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand [(qty "Viktor 1.0" 2)] :credits 20} :runner {:hand ["Inversificator"] :credits 20}}) (play-from-hand state :corp "Viktor 1.0" "HQ") (rez state :corp (get-ice state :hq 0)) (play-from-hand state :corp "Viktor 1.0" "New remote") (rez state :corp (get-ice state :remote1 0)) (take-credits state :corp) (play-from-hand state :runner "Inversificator") (run-on state "HQ") (run-continue state) (let [inv (get-program state 0)] (card-ability state :runner (refresh inv) 1) (card-ability state :runner (refresh inv) 0) (click-prompt state :runner "Do 1 brain damage") (click-prompt state :runner "End the run") (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner (get-ice state :hq 0)) (click-card state :runner (get-ice state :remote1 0)) (run-continue state) (is (not-any? :broken (:subroutines (get-ice state :remote1 0))) "None of the subs are marked as broken anymore")))) (testing "Doesn't fire when other programs break an ice. Issue #4858" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand [(qty "Viktor 1.0" 2)] :credits 20} :runner {:hand ["Inversificator" "Maven" "Cache"] :credits 20}}) (play-from-hand state :corp "Viktor 1.0" "HQ") (rez state :corp (get-ice state :hq 0)) (play-from-hand state :corp "Viktor 1.0" "New remote") (rez state :corp (get-ice state :remote1 0)) (take-credits state :corp) (core/gain state :runner :click 10) (play-from-hand state :runner "Cache") (play-from-hand state :runner "Maven") (play-from-hand state :runner "Inversificator") ;; Use Inversificator in another run first (run-on state "Server 1") (run-continue state) (let [maven (get-program state 1) inv (get-program state 2)] (card-ability state :runner (refresh inv) 1) (card-ability state :runner (refresh inv) 0) (click-prompt state :runner "Do 1 brain damage") (click-prompt state :runner "End the run") (run-continue state) (click-prompt state :runner "No") (run-continue state) ;; Use non-Inversificator breaker (run-on state "HQ") (run-continue state) (card-ability state :runner (refresh maven) 0) (click-prompt state :runner "Do 1 brain damage") (click-prompt state :runner "End the run") (run-continue state) (is (not (prompt-is-card? state :runner inv)) "Prompt shouldn't be Inversificator") (is (empty? (:prompt (get-corp))) "Corp shouldn't have a prompt") (is (empty? (:prompt (get-runner))) "Runner shouldn't have a prompt")))) (testing "Inversificator shouldn't fire when ice is unrezzed. Issue #4859" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Viktor 1.0" "Quandary"] :credits 20} :runner {:hand ["Inversificator"] :credits 20}}) (play-from-hand state :corp "Quandary" "HQ") (play-from-hand state :corp "Viktor 1.0" "HQ") (take-credits state :corp) (play-from-hand state :runner "Inversificator") (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (run-continue state) (let [inv (get-program state 0)] (card-ability state :runner (refresh inv) 1) (card-ability state :runner (refresh inv) 0) (click-prompt state :runner "Do 1 brain damage") (click-prompt state :runner "End the run") (run-continue state) (click-prompt state :runner "No") (run-continue state) (run-continue state) (is (not (prompt-is-card? state :runner inv)) "Prompt shouldn't be Inversificator") (is (empty? (:prompt (get-corp))) "Corp shouldn't have a prompt") (is (empty? (:prompt (get-runner))) "Runner shouldn't have a prompt")))) (testing "shouldn't fire ice's on-pass ability #5143" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Kakugo" "Quandary"] :credits 20} :runner {:hand ["Sure Gamble" "Inversificator"] :credits 20}}) (play-from-hand state :corp "Quandary" "HQ") (play-from-hand state :corp "Kakugo" "HQ") (take-credits state :corp) (play-from-hand state :runner "Inversificator") (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (core/register-floating-effect state :corp nil (let [ice (get-ice state :hq 1)] {:type :gain-subtype :req (req (utils/same-card? ice target)) :value "Code Gate"})) (run-continue state) (let [inv (get-program state 0)] (card-ability state :runner (refresh inv) 1) (card-ability state :runner (refresh inv) 0) (click-prompt state :runner "End the run") (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner (get-ice state :hq 1)) (click-card state :runner (get-ice state :hq 0)) (is (= 1 (count (:hand (get-runner)))))))) (testing "Async issue with Thimblerig #5042" (do-game (new-game {:corp {:hand ["Drafter" "Border Control" "Vanilla" "Thimblerig"] :credits 100} :runner {:hand ["Inversificator"] :credits 100}}) (core/gain state :corp :click 1) (play-from-hand state :corp "Border Control" "R&D") (play-from-hand state :corp "Drafter" "R&D") (play-from-hand state :corp "Vanilla" "HQ") (play-from-hand state :corp "Thimblerig" "HQ") (take-credits state :corp) (play-from-hand state :runner "Inversificator") (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "End the run") (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner "Drafter") (is (= ["Border Control" "Thimblerig"] (map :title (get-ice state :rd)))) (is (= ["Vanilla" "Drafter"] (map :title (get-ice state :hq)))) (is (empty? (:prompt (get-corp))) "Corp gets no Thimblerig prompt") (is (empty? (:prompt (get-runner))) "No more prompts open"))) (testing "Swap vs subtype issues #5170" (do-game (new-game {:corp {:hand ["Drafter" "Data Raven" "Vanilla"] :credits 100} :runner {:id "Rielle \"Kit\" Peddler: Transhuman" :hand ["Inversificator" "Hunting Grounds" "Stargate"] :credits 100}}) (play-from-hand state :corp "Data Raven" "R&D") (play-from-hand state :corp "Drafter" "R&D") (play-from-hand state :corp "Vanilla" "Archives") (take-credits state :corp) (play-from-hand state :runner "Inversificator") (play-from-hand state :runner "Hunting Grounds") (play-from-hand state :runner "Stargate") (core/gain state :runner :click 10) (let [inv (get-program state 0) hg (get-resource state 0) sg (get-program state 1)] (card-ability state :runner sg 0) (run-continue state) (rez state :corp (get-ice state :rd 0)) (card-ability state :runner hg 0) (run-continue state) (card-ability state :runner inv 1) (card-ability state :runner inv 1) (card-ability state :runner inv 0) (click-prompt state :runner "Trace 3 - Add 1 power counter") (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner "Vanilla") (is (= ["Vanilla" "Drafter"] (map :title (get-ice state :rd)))) (is (= ["Data Raven"] (map :title (get-ice state :archives)))))))) (deftest ixodidae ;; Ixodidae should not trigger on psi-games (do-game (new-game {:corp {:deck ["Snowflake"]} :runner {:deck ["Ixodidae" "Lamprey"]}}) (play-from-hand state :corp "Snowflake" "HQ") (take-credits state :corp) (is (= 7 (:credit (get-corp))) "Corp at 7 credits") (play-from-hand state :runner "Ixodidae") (play-from-hand state :runner "Lamprey") (is (= 3 (:credit (get-runner))) "Runner paid 3 credits to install Ixodidae and Lamprey") (run-on state :hq) (let [s (get-ice state :hq 0)] (rez state :corp s) (run-continue state) (card-subroutine state :corp s 0) (is (prompt-is-card? state :corp s) "Corp prompt is on Snowflake") (is (prompt-is-card? state :runner s) "Runner prompt is on Snowflake") (is (= 6 (:credit (get-corp))) "Corp paid 1 credit to rezz Snowflake") (click-prompt state :corp "1 [Credits]") (click-prompt state :runner "1 [Credits]") (is (= 5 (:credit (get-corp))) "Corp paid 1 credit to psi game") (is (= 2 (:credit (get-runner))) "Runner did not gain 1 credit from Ixodidae when corp spent on psi game") (run-continue state) (run-continue state) (is (= 4 (:credit (get-corp))) "Corp lost 1 credit to Lamprey") (is (= 3 (:credit (get-runner))) "Runner gains 1 credit from Ixodidae due to Lamprey")))) (deftest keyhole ;; Keyhole (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 10)] :hand ["Herald" "Troll"]} :runner {:hand ["Keyhole"]}}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (is (= "Troll" (-> (get-corp) :deck first :title)) "Troll on top of deck") (is (= "Herald" (-> (get-corp) :deck second :title)) "Herald 2nd") (take-credits state :corp) (play-from-hand state :runner "Keyhole") (card-ability state :runner (get-program state 0) 0) (is (:run @state) "Run initiated") (run-continue state) (let [number-of-shuffles (count (core/turn-events state :corp :corp-shuffle-deck))] (click-prompt state :runner "Troll") (is (empty? (:prompt (get-runner))) "Prompt closed") (is (not (:run @state)) "Run ended") (is (-> (get-corp) :discard first :seen) "Troll is faceup") (is (= "Troll" (-> (get-corp) :discard first :title)) "Troll was trashed") (is (find-card "Herald" (:deck (get-corp))) "Herald now in R&D") (is (< number-of-shuffles (count (core/turn-events state :corp :corp-shuffle-deck))) "Corp has shuffled R&D")) (card-ability state :runner (get-program state 0) 0) (is (:run @state) "Keyhole can be used multiple times per turn")))) (deftest kyuban ;; Kyuban (testing "Gain creds when passing a piece of ice, both when rezzed and when unrezzed." (do-game (new-game {:corp {:deck [(qty "Lockdown" 3)]} :runner {:deck [(qty "Kyuban" 1)]}}) (play-from-hand state :corp "Lockdown" "HQ") (play-from-hand state :corp "Lockdown" "Archives") (let [ld1 (get-ice state :archives 0) ld2 (get-ice state :hq 0)] (take-credits state :corp) (play-from-hand state :runner "Kyuban") (click-card state :runner ld1) (let [starting-creds (:credit (get-runner))] (run-on state "HQ") (run-continue state) (is (= starting-creds (:credit (get-runner))) "Gained no money for passing other ice") (run-jack-out state) (run-on state "Archives") (run-continue state) (is (= (+ starting-creds 2) (:credit (get-runner))) "Gained 2 creds for passing unrezzed host ice")) (let [starting-creds-2 (:credit (get-runner))] (core/jack-out state :runner nil) (run-on state "Archives") (rez state :corp ld1) (run-continue state) (run-continue state) (run-continue state) (is (= (+ starting-creds-2 2) (:credit (get-runner))) "Gained 2 creds for passing rezzed host ice"))))) (testing "HB: Architects of Tomorrow interaction" (do-game (new-game {:corp {:id "Haas-Bioroid: Architects of Tomorrow" :deck ["Eli 1.0"]} :runner {:deck ["Kyuban"]}}) (play-from-hand state :corp "Eli 1.0" "HQ") (let [eli (get-ice state :hq 0)] (rez state :corp eli) (take-credits state :corp) (play-from-hand state :runner "Kyuban") (click-card state :runner eli)) (let [starting-creds (:credit (get-runner))] (run-on state "HQ") (run-continue state) (run-continue state) (click-prompt state :corp "Done") (run-continue state) (is (= (+ starting-creds 2) (:credit (get-runner))) "Only gained 2 credits for passing Eli"))))) (deftest laamb ;; Laamb (testing "Ability gives an card Barrier subtype" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Laamb"] :credits 30}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Laamb") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "Yes") (is (has-subtype? (get-ice state :hq 0) "Barrier") "Enigma has been given Barrier"))) (testing "Ability only lasts until end of encounter" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Laamb"] :credits 30}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Laamb") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "Yes") (run-continue state) (is (not (has-subtype? (get-ice state :hq 0) "Barrier")) "Enigma no longer has Barrier subtype"))) (testing "Returning the ice to hand after using ability resets subtype. Issue #3193" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Laamb" "Ankusa"] :credits 30}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Laamb") (play-from-hand state :runner "Ankusa") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "Yes") (let [laamb (get-program state 0) ankusa (get-program state 1)] (card-ability state :runner ankusa 1) (card-ability state :runner ankusa 1) (card-ability state :runner ankusa 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (is (nil? (get-ice state :hq 0)) "Enigma has been returned to HQ") (is (find-card "Enigma" (:hand (get-corp))) "Enigma has been returned to HQ") (run-jack-out state) (take-credits state :runner) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (is (not (has-subtype? (get-ice state :hq 0) "Barrier")) "Enigma doesn't has Barrier subtype") (is (prompt-is-card? state :runner laamb) "Laamb opens the prompt a second time"))))) (deftest lamprey ;; Lamprey - Corp loses 1 credit for each successful HQ run; trashed on purge (do-game (new-game {:runner {:deck ["Lamprey"]}}) (take-credits state :corp) (play-from-hand state :runner "Lamprey") (let [lamp (get-program state 0)] (run-empty-server state :hq) (is (= 7 (:credit (get-corp))) "Corp lost 1 credit") (click-prompt state :runner "No action") (run-empty-server state :hq) (is (= 6 (:credit (get-corp))) "Corp lost 1 credit") (click-prompt state :runner "No action") (run-empty-server state :hq) (is (= 5 (:credit (get-corp))) "Corp lost 1 credit") (click-prompt state :runner "No action") (take-credits state :runner) (core/purge state :corp) (is (empty? (get-program state)) "Lamprey trashed by purge")))) (deftest leech ;; Leech - Reduce strength of encountered ICE (testing "Basic test" (do-game (new-game {:corp {:deck ["Fire Wall"]} :runner {:deck ["Leech"]}}) (play-from-hand state :corp "Fire Wall" "New remote") (take-credits state :corp) (core/gain state :runner :click 3) (play-from-hand state :runner "Leech") (let [le (get-program state 0) fw (get-ice state :remote1 0)] (run-empty-server state "Archives") (is (= 1 (get-counters (refresh le) :virus))) (run-empty-server state "Archives") (is (= 2 (get-counters (refresh le) :virus))) (run-on state "Server 1") (run-continue state) (run-continue state) (is (= 2 (get-counters (refresh le) :virus)) "No counter gained, not a central server") (run-on state "Server 1") (rez state :corp fw) (run-continue state) (is (= 5 (get-strength (refresh fw)))) (card-ability state :runner le 0) (is (= 1 (get-counters (refresh le) :virus)) "1 counter spent from Leech") (is (= 4 (get-strength (refresh fw))) "Fire Wall strength lowered by 1")))) (testing "does not affect next ice when current is trashed. Issue #1788" (do-game (new-game {:corp {:deck ["Wraparound" "Spiderweb"]} :runner {:deck ["Leech" "Parasite"]}}) (play-from-hand state :corp "Wraparound" "HQ") (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (core/gain state :corp :credit 10) (play-from-hand state :runner "Leech") (let [leech (get-program state 0) wrap (get-ice state :hq 0) spider (get-ice state :hq 1)] (core/add-counter state :runner leech :virus 2) (rez state :corp spider) (rez state :corp wrap) (play-from-hand state :runner "Parasite") (click-card state :runner "Spiderweb") (run-on state "HQ") (run-continue state) (card-ability state :runner (refresh leech) 0) (card-ability state :runner (refresh leech) 0) (is (find-card "Spiderweb" (:discard (get-corp))) "Spiderweb trashed by Parasite + Leech") (is (= 7 (get-strength (refresh wrap))) "Wraparound not reduced by Leech"))))) (deftest leprechaun ;; Leprechaun - hosting a breaker with strength based on unused MU should calculate correctly (testing "Basic test" (do-game (new-game {:runner {:deck ["Adept" "Leprechaun"]}}) (take-credits state :corp) (core/gain state :runner :credit 5) (play-from-hand state :runner "Leprechaun") (play-from-hand state :runner "Adept") (is (= 1 (core/available-mu state)) "3 MU used") (let [lep (get-program state 0) adpt (get-program state 1)] (is (= 3 (get-strength (refresh adpt))) "Adept at 3 strength individually") (card-ability state :runner lep 1) (click-card state :runner (refresh adpt)) (let [hosted-adpt (first (:hosted (refresh lep)))] (is (= 3 (core/available-mu state)) "1 MU used") (is (= 5 (get-strength (refresh hosted-adpt))) "Adept at 5 strength hosted"))))) (testing "Keep MU the same when hosting or trashing hosted programs" (do-game (new-game {:runner {:deck ["Leprechaun" "Hyperdriver" "Imp"]}}) (take-credits state :corp) (play-from-hand state :runner "Leprechaun") (let [lep (get-program state 0)] (card-ability state :runner lep 0) (click-card state :runner (find-card "Hyperdriver" (:hand (get-runner)))) (is (= 2 (:click (get-runner)))) (is (= 2 (:credit (get-runner)))) (is (= 3 (core/available-mu state)) "Hyperdriver 3 MU not deducted from available MU") (card-ability state :runner lep 0) (click-card state :runner (find-card "Imp" (:hand (get-runner)))) (is (= 1 (:click (get-runner)))) (is (zero? (:credit (get-runner)))) (is (= 3 (core/available-mu state)) "Imp 1 MU not deducted from available MU") ;; Trash Hyperdriver (core/move state :runner (find-card "Hyperdriver" (:hosted (refresh lep))) :discard) (is (= 3 (core/available-mu state)) "Hyperdriver 3 MU not added to available MU") (core/move state :runner (find-card "Imp" (:hosted (refresh lep))) :discard) ; trash Imp (is (= 3 (core/available-mu state)) "Imp 1 MU not added to available MU"))))) (deftest lustig ;; Lustig (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"]} :runner {:hand ["Lustig"] :credits 10}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (play-from-hand state :runner "Lustig") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 2) (is (= :approach-server (:phase (get-run))) "Run has bypassed Rototurret") (is (find-card "Lustig" (:discard (get-runner))) "Lustig is trashed"))) (deftest magnum-opus ;; Magnum Opus - Gain 2 cr (do-game (new-game {:runner {:deck ["Magnum Opus"]}}) (take-credits state :corp) (play-from-hand state :runner "Magnum Opus") (is (= 2 (core/available-mu state))) (is (zero? (:credit (get-runner)))) (let [mopus (get-program state 0)] (card-ability state :runner mopus 0) (is (= 2 (:credit (get-runner))) "Gain 2cr")))) (deftest makler ;; Makler (testing "Break ability costs 2 for 2 subroutines" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Battlement"]} :runner {:hand ["Makler"] :credits 20}}) (play-from-hand state :corp "Battlement" "HQ") (take-credits state :corp) (play-from-hand state :runner "Makler") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (changes-val-macro -2 (:credit (get-runner)) "Break ability costs 2 credits" (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run")))) (testing "Boost ability costs 2 credits, increases strength by 2" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Bastion"]} :runner {:hand ["Makler"] :credits 20}}) (play-from-hand state :corp "Bastion" "HQ") (take-credits state :corp) (play-from-hand state :runner "Makler") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (changes-val-macro -2 (:credit (get-runner)) "Boost ability costs 2 credits" (card-ability state :runner (get-program state 0) 1)) (changes-val-macro 2 (get-strength (get-program state 0)) "Boost ability increases strength by 2" (card-ability state :runner (get-program state 0) 1)))) (testing "Break all subs ability gives 1 credit" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand [(qty "Battlement" 2)]} :runner {:hand ["Makler"] :credits 20}}) (play-from-hand state :corp "Battlement" "HQ") (play-from-hand state :corp "Battlement" "Archives") (take-credits state :corp) (play-from-hand state :runner "Makler") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (changes-val-macro 1 (:credit (get-runner)) "Break all subs ability gives 1 credit" (run-continue state))))) (deftest mammon ;; Mammon - Pay to add X power counters at start of turn, all removed at end of turn (do-game (new-game {:runner {:deck ["Mammon"]}}) (take-credits state :corp) (play-from-hand state :runner "Mammon") (take-credits state :runner) (take-credits state :corp) (let [mam (get-program state 0)] (is (= 5 (:credit (get-runner))) "Starts with 5 credits") (card-ability state :runner mam 0) (click-prompt state :runner "3") (is (= 2 (:credit (get-runner))) "Spent 3 credits") (is (= 3 (get-counters (refresh mam) :power)) "Mammon has 3 power counters") (take-credits state :runner) (is (zero? (get-counters (refresh mam) :power)) "All power counters removed")))) (deftest mantle ;; Mantle (testing "Works with programs" (do-game ;; Using Tracker to demonstrate that it's not just icebreakers (new-game {:runner {:hand ["Mantle" "Tracker"]}}) (take-credits state :corp) (play-from-hand state :runner "Mantle") (play-from-hand state :runner "Tracker") (take-credits state :runner) (take-credits state :corp) (click-prompt state :runner "HQ") (let [mantle (get-program state 0) tracker (get-program state 1)] (card-ability state :runner tracker 0) (changes-val-macro -1 (get-counters (refresh mantle) :recurring) "Can spend credits on Mantle for programs" (click-card state :runner mantle))))) (testing "Works with programs" (do-game (new-game {:runner {:deck ["Sure Gamble"] :hand ["Mantle" "Prognostic Q-Loop"]}}) (take-credits state :corp) (play-from-hand state :runner "Mantle") (play-from-hand state :runner "Prognostic Q-Loop") (take-credits state :runner) (take-credits state :corp) (let [mantle (get-program state 0) qloop (get-hardware state 0)] (card-ability state :runner qloop 1) (changes-val-macro -1 (get-counters (refresh mantle) :recurring) "Can spend credits on Mantle for programs" (click-card state :runner mantle)) (take-credits state :runner) (take-credits state :corp))))) (deftest marjanah ;; Marjanah (before-each [state (new-game {:runner {:hand [(qty "Marjanah" 2)] :credits 20} :corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"] :credits 20}}) _ (do (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Marjanah") (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state :encounter-ice)) ice-wall (get-ice state :hq 0) marjanah (get-program state 0)] (testing "pump ability" (do-game state (changes-val-macro -1 (:credit (get-runner)) "Pump costs 1" (card-ability state :runner marjanah 1)) (changes-val-macro 1 (get-strength (refresh marjanah)) "Marjanah gains 1 str" (card-ability state :runner marjanah 1)))) (testing "break ability" (do-game state (changes-val-macro -2 (:credit (get-runner)) "Break costs 2" (card-ability state :runner marjanah 0) (click-prompt state :runner "End the run")))) (testing "discount after successful run" (do-game state (run-continue state :approach-server) (run-continue state nil) (run-on state :hq) (run-continue state :encounter-ice) (changes-val-macro -1 (:credit (get-runner)) "Break costs 1 after run" (card-ability state :runner marjanah 0) (click-prompt state :runner "End the run")))))) (deftest mass-driver ;; Mass-Driver (testing "Basic test" (do-game (new-game {:corp {:deck ["Enigma" "Endless EULA"] :credits 20} :runner {:deck ["Mass-Driver"] :credits 20}}) (play-from-hand state :corp "Endless EULA" "HQ") (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Mass-Driver") (let [eula (get-ice state :hq 0) enigma (get-ice state :hq 1) mass-driver (get-program state 0)] (run-on state :hq) (rez state :corp enigma) (run-continue state) (card-ability state :runner mass-driver 1) (card-ability state :runner mass-driver 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (run-continue state) (rez state :corp eula) (run-continue state) (fire-subs state (refresh eula)) ; only resolve 3 subs (click-prompt state :runner "Pay 1 [Credits]") (click-prompt state :runner "Pay 1 [Credits]") (click-prompt state :runner "Pay 1 [Credits]") (is (empty? (:prompt (get-runner))) "No more prompts open")))) (testing "Interaction with Spooned" (do-game (new-game {:corp {:deck ["Enigma" "Endless EULA"]} :runner {:deck ["Mass-Driver" "Spooned"]}}) (play-from-hand state :corp "Endless EULA" "HQ") (play-from-hand state :corp "Enigma" "HQ") (core/gain state :corp :credit 20) (take-credits state :corp) (core/gain state :runner :credit 20) (play-from-hand state :runner "Mass-Driver") (let [eula (get-ice state :hq 0) enigma (get-ice state :hq 1) mass-driver (get-program state 0)] (play-from-hand state :runner "Spooned") (click-prompt state :runner "HQ") (rez state :corp enigma) (run-continue state) (card-ability state :runner mass-driver 1) (card-ability state :runner mass-driver 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (run-continue state) (is (= 1 (count (:discard (get-corp)))) "Enigma is trashed") (rez state :corp eula) (run-continue state) (fire-subs state (refresh eula)) ; only resolve 3 subs (click-prompt state :runner "Pay 1 [Credits]") (click-prompt state :runner "Pay 1 [Credits]") (click-prompt state :runner "Pay 1 [Credits]") (is (empty? (:prompt (get-runner))) "No more prompts open"))))) (deftest maven ;; Maven (testing "Basic test" (do-game (new-game {:corp {:deck ["Border Control"] :credits 20} :runner {:hand ["Maven" "Datasucker"] :credits 20}}) (play-from-hand state :corp "Border Control" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Maven") (let [maven (get-program state 0)] (is (= 1 (get-strength (refresh maven))) "Maven boosts itself") (play-from-hand state :runner "Datasucker") (is (= 2 (get-strength (refresh maven))) "+1 str from Datasucker") (run-on state "HQ") (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh maven)}) (is (second-last-log-contains? state "Runner pays 4 \\[Credits\\] to use Maven to break all 2 subroutines on Border Control.") "Correct log with autopump ability") (run-jack-out state) (run-on state "HQ") (run-continue state) (card-ability state :runner (refresh maven) 0) (click-prompt state :runner "End the run") (is (last-log-contains? state "Runner pays 2 \\[Credits\\] to use Maven to break 1 subroutine on Border Control.") "Correct log with single sub break"))))) (deftest mayfly ;; Mayfly (testing "Basic test" (do-game (new-game {:corp {:deck ["Anansi"] :credits 20} :runner {:hand ["Mayfly"] :credits 20}}) (play-from-hand state :corp "Anansi" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Mayfly") (let [mayfly (get-program state 0)] (run-on state "HQ") (run-continue state) (changes-val-macro -7 (:credit (get-runner)) "Paid 7 to fully break Anansi with Mayfly" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh mayfly)})) (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines") (run-jack-out state) (is (= 1 (count (:discard (get-runner)))) "Mayfly trashed when run ends"))))) (deftest mimic ;; Mimic (testing "Basic auto-break test" (do-game (new-game {:corp {:hand ["Pup"]} :runner {:hand [(qty "Mimic" 5)]}}) (play-from-hand state :corp "Pup" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Mimic") (let [mimic (get-program state 0)] (is (= 2 (:credit (get-runner))) "Runner starts with 2 credits") (is (= 4 (count (:hand (get-runner)))) "Runner has 4 cards in hand") (run-on state "HQ") (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh mimic)}) (is (second-last-log-contains? state "Runner pays 2 \\[Credits\\] to use Mimic to break all 2 subroutines on Pup") "Correct log with autopump ability") (run-jack-out state) (is (zero? (:credit (get-runner))) "Runner spent 2 credits to break Pup") (is (= 4 (count (:hand (get-runner)))) "Runner still has 4 cards in hand")))) (testing "No dynamic options if below strength" (do-game (new-game {:corp {:hand ["Anansi"] :credits 10} :runner {:hand [(qty "Mimic" 5)] :credits 10}}) (play-from-hand state :corp "Anansi" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Mimic") (let [mimic (get-program state 0)] (is (= 7 (:credit (get-runner))) "Runner starts with 7 credits") (is (= 4 (count (:hand (get-runner)))) "Runner has 4 cards in hand") (run-on state "HQ") (run-continue state) (is (= 1 (count (:abilities (refresh mimic)))) "Auto pump and break ability on Mimic is not available")))) (testing "Dynamic options when ice weakened" (do-game (new-game {:corp {:hand ["Zed 2.0"] :credits 10} :runner {:hand ["Mimic" "Ice Carver" ] :credits 10}}) (play-from-hand state :corp "Zed 2.0" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Ice Carver") (play-from-hand state :runner "Mimic") (let [mimic (get-program state 0)] (is (= 4 (:credit (get-runner))) "Runner starts with 4 credits") (run-on state "HQ") (run-continue state) (is (= 2 (count (:abilities (refresh mimic)))) "Auto pump and break ability on Mimic is available") (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh mimic)}) (is (second-last-log-contains? state "Runner pays 3 \\[Credits\\] to use Mimic to break all 3 subroutines on Zed 2.0") "Correct log with autopump ability") (run-jack-out state) (is (= 1 (:credit (get-runner))) "Runner spent 3 credits to break Zed 2.0"))))) (deftest misdirection ;; Misdirection (testing "Recurring credits interaction. Issue #4868" (do-game (new-game {:runner {:hand ["Misdirection" "Multithreader"] :credits 10 :tags 2}}) (take-credits state :corp) (core/gain state :runner :click 2) (play-from-hand state :runner "Misdirection") (play-from-hand state :runner "Multithreader") (let [mis (get-program state 0) multi (get-program state 1)] (changes-val-macro 0 (:credit (get-runner)) "Using recurring credits" (card-ability state :runner mis 0) (click-prompt state :runner "2") (is (= "Select a credit providing card (0 of 2 credits)" (:msg (prompt-map :runner))) "Runner has pay-credit prompt") (click-card state :runner multi) (click-card state :runner multi)) (is (zero? (count-tags state)) "Runner has lost both tags")))) (testing "Using credits from Mantle and credit pool" (do-game (new-game {:runner {:hand ["Misdirection" "Mantle"] :credits 10 :tags 4}}) (take-credits state :corp) (core/gain state :runner :click 2) (play-from-hand state :runner "Misdirection") (play-from-hand state :runner "Mantle") (let [mis (get-program state 0) mantle (get-program state 1)] (changes-val-macro -3 (:credit (get-runner)) "Using recurring credits and credits from credit pool" (card-ability state :runner mis 0) (click-prompt state :runner "4") (is (= "Select a credit providing card (0 of 4 credits)" (:msg (prompt-map :runner))) "Runner has pay-credit prompt") (click-card state :runner mantle)) (is (zero? (count-tags state)) "Runner has lost all 4 tags")))) (testing "Basic behavior" (do-game (new-game {:runner {:hand ["Misdirection"] :credits 5 :tags 2}}) (take-credits state :corp) (play-from-hand state :runner "Misdirection") (let [mis (get-program state 0)] (is (= 5 (:credit (get-runner))) "Runner starts with 5 credits") (is (= 3 (:click (get-runner))) "Runner starts with 3 clicks") (card-ability state :runner mis 0) (click-prompt state :runner "2") (is (zero? (count-tags state)) "Runner has lost both tags") (is (= 1 (:click (get-runner))) "Runner spent 2 clicks (1 remaining)") (is (= 3 (:credit (get-runner))) "Runner spent 2 credits (3 remaining)"))))) (deftest mkultra ;; MKUltra (testing "auto-pump" (testing "Pumping and breaking for 1" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"] :credits 10} :runner {:hand ["MKUltra"] :credits 100}}) (play-from-hand state :corp "Rototurret" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "MKUltra") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -3 (:credit (get-runner)) "Paid 3 to fully break Rototurret with MKUltra" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh pc)})) (is (= 3 (get-strength (refresh pc))) "Pumped MKUltra up to str 3") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines"))))) (testing "Heap Locked" (do-game (new-game {:corp {:deck ["Rototurret" "Blacklist"]} :runner {:deck [(qty "MKUltra" 1)]}}) (play-from-hand state :corp "Rototurret" "Archives") (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (refresh (get-content state :remote1 0))) (take-credits state :corp) (trash-from-hand state :runner "MKUltra") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (is (empty? (:prompt (get-runner))) "MKUltra prompt did not come up")))) (deftest multithreader ;; Multithreader (testing "Pay-credits prompt" (do-game (new-game {:runner {:deck ["Multithreader" "Abagnale"]}}) (take-credits state :corp) (core/gain state :runner :credit 20) (play-from-hand state :runner "Multithreader") (play-from-hand state :runner "Abagnale") (let [mt (get-program state 0) ab (get-program state 1)] (changes-val-macro 0 (:credit (get-runner)) "Used 2 credits from Multithreader" (card-ability state :runner ab 1) (is (= "Select a credit providing card (0 of 2 credits)" (:msg (prompt-map :runner))) "Runner has pay-credit prompt") (click-card state :runner mt) (click-card state :runner mt)))))) (deftest musaazi ;; Musaazi gains virus counters on successful runs and can spend virus counters from any installed card (do-game (new-game {:corp {:deck ["Lancelot"]} :runner {:deck ["Musaazi" "Imp"]}}) (play-from-hand state :corp "Lancelot" "HQ") (take-credits state :corp) (play-from-hand state :runner "Musaazi") (play-from-hand state :runner "Imp") (let [lancelot (get-ice state :hq 0) musaazi (get-program state 0) imp (get-program state 1)] (run-empty-server state "Archives") (is (= 1 (get-counters (refresh musaazi) :virus)) "Musaazi has 1 virus counter") (is (= 1 (get-strength (refresh musaazi))) "Initial Musaazi strength") (is (= 2 (get-counters (refresh imp) :virus)) "Initial Imp virus counters") (run-on state "HQ") (rez state :corp lancelot) (run-continue state) (card-ability state :runner musaazi 1) ; match strength (click-card state :runner imp) (is (= 1 (get-counters (refresh imp) :virus)) "Imp lost 1 virus counter to pump") (is (= 2 (get-strength (refresh musaazi))) "Musaazi strength 2") (is (empty? (:prompt (get-runner))) "No prompt open") (card-ability state :runner musaazi 0) (click-prompt state :runner "Trash a program") (click-card state :runner musaazi) (click-prompt state :runner "Resolve a Grail ICE subroutine from HQ") (click-card state :runner imp) (is (zero? (get-counters (refresh imp) :virus)) "Imp lost its final virus counter") (is (zero? (get-counters (refresh imp) :virus)) "Musaazi lost its virus counter")))) (deftest na-not-k ;; Na'Not'K - Strength adjusts accordingly when ice installed during run (testing "Basic test" (do-game (new-game {:corp {:deck ["Architect" "Eli 1.0"]} :runner {:deck ["Na'Not'K"]}}) (play-from-hand state :corp "Architect" "HQ") (take-credits state :corp) (play-from-hand state :runner "Na'Not'K") (let [nanotk (get-program state 0) architect (get-ice state :hq 0)] (is (= 1 (get-strength (refresh nanotk))) "Default strength") (run-on state "HQ") (rez state :corp architect) (run-continue state) (is (= 2 (get-strength (refresh nanotk))) "1 ice on HQ") (card-subroutine state :corp (refresh architect) 1) (click-card state :corp (find-card "Eli 1.0" (:hand (get-corp)))) (click-prompt state :corp "HQ") (is (= 3 (get-strength (refresh nanotk))) "2 ice on HQ") (run-jack-out state) (is (= 1 (get-strength (refresh nanotk))) "Back to default strength")))) (testing "Strength adjusts accordingly when run redirected to another server" (do-game (new-game {:corp {:deck ["Susanoo-no-Mikoto" "Crick" "Cortex Lock"] :credits 20} :runner {:deck ["Na'Not'K"]}}) (play-from-hand state :corp "Cortex Lock" "HQ") (play-from-hand state :corp "Susanoo-no-Mikoto" "HQ") (play-from-hand state :corp "Crick" "Archives") (take-credits state :corp) (play-from-hand state :runner "Na'Not'K") (let [nanotk (get-program state 0) susanoo (get-ice state :hq 1)] (is (= 1 (get-strength (refresh nanotk))) "Default strength") (run-on state "HQ") (rez state :corp susanoo) (run-continue state) (is (= 3 (get-strength (refresh nanotk))) "2 ice on HQ") (card-subroutine state :corp (refresh susanoo) 0) (is (= 2 (get-strength (refresh nanotk))) "1 ice on Archives") (run-jack-out state) (is (= 1 (get-strength (refresh nanotk))) "Back to default strength"))))) (deftest nfr ;; Nfr (testing "Basic test" (do-game (new-game {:runner {:deck ["Nfr"]} :corp {:deck ["Ice Wall"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Nfr") (let [nfr (get-program state 0) icew (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh icew)) (run-continue state) (card-ability state :runner (refresh nfr) 0) (click-prompt state :runner "End the run") (changes-val-macro 1 (get-counters (refresh nfr) :power) "Got 1 token" (run-continue state)))))) (deftest nyashia ;; Nyashia (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 10)] :hand ["Hedge Fund"]} :runner {:deck ["Nyashia"]}}) (take-credits state :corp) (play-from-hand state :runner "Nyashia") (run-on state "R&D") (run-continue state) (click-prompt state :runner "Yes") (is (= 2 (:total (core/num-cards-to-access state :runner :rd nil)))))) (deftest odore (testing "Basic test" (do-game (new-game {:corp {:deck ["Cobra"]} :runner {:deck ["Odore" (qty "Logic Bomb" 3)]}}) (play-from-hand state :corp "Cobra" "HQ") (take-credits state :corp) (play-from-hand state :runner "Odore") (let [odore (get-program state 0) cobra (get-ice state :hq 0)] (core/gain state :runner :click 2 :credit 20) (run-on state "HQ") (rez state :corp cobra) (run-continue state) (changes-val-macro -5 (:credit (get-runner)) "Paid 3 to pump and 2 to break" (card-ability state :runner odore 2) (card-ability state :runner odore 0) (click-prompt state :runner "Trash a program") (click-prompt state :runner "Do 2 net damage"))))) (testing "auto-pump-and-break with and without 3 virtual resources" (do-game (new-game {:corp {:deck ["Cobra"]} :runner {:deck ["Odore" (qty "Logic Bomb" 3)]}}) (play-from-hand state :corp "Cobra" "HQ") (take-credits state :corp) (play-from-hand state :runner "Odore") (let [odore (get-program state 0) cobra (get-ice state :hq 0)] (core/gain state :runner :click 2 :credit 20) (run-on state "HQ") (rez state :corp cobra) (run-continue state) (changes-val-macro -5 (:credit (get-runner)) "Paid 3 to pump and 2 to break" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh odore)})) (core/continue state :corp nil) (run-jack-out state) (dotimes [_ 3] (play-from-hand state :runner "Logic Bomb")) (run-on state "HQ") (run-continue state) (changes-val-macro -3 (:credit (get-runner)) "Paid 3 to pump and 0 to break" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh odore)})))))) (deftest origami ;; Origami - Increases Runner max hand size (do-game (new-game {:runner {:deck [(qty "Origami" 2)]}}) (take-credits state :corp) (play-from-hand state :runner "Origami") (is (= 6 (hand-size :runner))) (play-from-hand state :runner "Origami") (is (= 9 (hand-size :runner)) "Max hand size increased by 2 for each copy installed"))) (deftest overmind ;; Overmind - Start with counters equal to unused MU (do-game (new-game {:runner {:deck ["Overmind" "Deep Red" "Sure Gamble" "Akamatsu Mem Chip" ]}}) (take-credits state :corp) (play-from-hand state :runner "Sure Gamble") (play-from-hand state :runner "Akamatsu Mem Chip") (is (= 5 (core/available-mu state))) (play-from-hand state :runner "Deep Red") (is (= 8 (core/available-mu state))) (play-from-hand state :runner "Overmind") (is (= 7 (core/available-mu state))) (let [ov (get-program state 0)] (is (= 7 (get-counters (refresh ov) :power)) "Overmind has 5 counters")))) (deftest paintbrush ;; Paintbrush - Give rezzed ICE a chosen subtype until the end of the next run (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["Paintbrush"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Paintbrush") (is (= 2 (core/available-mu state))) (let [iwall (get-ice state :hq 0) pb (get-program state 0)] (card-ability state :runner pb 0) (click-card state :runner iwall) (is (= 3 (:click (get-runner))) "Ice Wall not rezzed, so no click charged") (click-prompt state :runner "Done") ; cancel out (rez state :corp iwall) (card-ability state :runner pb 0) (click-card state :runner iwall) (click-prompt state :runner "Code Gate") (is (= 2 (:click (get-runner))) "Click charged") (is (has-subtype? (refresh iwall) "Code Gate") "Ice Wall gained Code Gate") (run-empty-server state "Archives") (is (not (has-subtype? (refresh iwall) "Code Gate")) "Ice Wall lost Code Gate at the end of the run")))) (deftest panchatantra ;; Panchatantra (before-each [state (new-game {:corp {:hand ["Ice Wall"]} :runner {:hand ["Panchatantra"]}}) _ (do (play-from-hand state :corp "Ice Wall" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Panchatantra") (run-on state :hq) (run-continue state)) iw (get-ice state :hq 0)] (testing "Choices do not include Barrier, Code Gate, or Sentry" (do-game state (click-prompt state :runner "Yes") (is (not (some #{"Barrier" "Code Gate" "Sentry"} (prompt-buttons :runner)))))) (testing "Encountered ice gains the subtype" (do-game state (click-prompt state :runner "Yes") (click-prompt state :runner "AP") (is (has-subtype? (refresh iw) "AP")))) (testing "Encountered ice loses subtype at the end of the run" (do-game state (click-prompt state :runner "Yes") (click-prompt state :runner "AP") (run-continue state) (is (has-subtype? (refresh iw) "AP")) (run-jack-out state) (is (not (has-subtype? (refresh iw) "AP"))))))) (deftest paperclip ;; Paperclip - prompt to install on encounter, but not if another is installed (testing "Basic test" (do-game (new-game {:corp {:deck ["Vanilla"]} :runner {:deck [(qty "Paperclip" 2)]}}) (play-from-hand state :corp "Vanilla" "Archives") (take-credits state :corp) (trash-from-hand state :runner "Paperclip") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (click-prompt state :runner "Yes") ; install paperclip (run-continue state) (run-continue state) (is (not (:run @state)) "Run ended") (trash-from-hand state :runner "Paperclip") (run-on state "Archives") (is (empty? (:prompt (get-runner))) "No prompt to install second Paperclip"))) (testing "firing on facedown ice shouldn't crash" (do-game (new-game {:corp {:deck ["Vanilla"]} :runner {:deck ["Paperclip"]}}) (play-from-hand state :corp "Vanilla" "Archives") (take-credits state :corp) (play-from-hand state :runner "Paperclip") (run-on state "Archives") (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "0"))) (testing "do not show a second install prompt if user said No to first, when multiple are in heap" (do-game (new-game {:corp {:deck [(qty "Vanilla" 2)]} :runner {:deck [(qty "Paperclip" 3)]}}) (play-from-hand state :corp "Vanilla" "Archives") (play-from-hand state :corp "Vanilla" "Archives") (take-credits state :corp) (trash-from-hand state :runner "Paperclip") (trash-from-hand state :runner "Paperclip") (trash-from-hand state :runner "Paperclip") (run-on state "Archives") (rez state :corp (get-ice state :archives 1)) (run-continue state) (click-prompt state :runner "No") (is (empty? (:prompt (get-runner))) "No additional prompts to rez other copies of Paperclip") (run-continue state) (rez state :corp (get-ice state :archives 0)) (run-continue state) ;; we should get the prompt on a second ice even after denying the first (click-prompt state :runner "No") (is (empty? (:prompt (get-runner))) "No additional prompts to rez other copies of Paperclip") (run-jack-out state) ;; Run again, make sure we get the prompt to install again (run-on state "Archives") (run-continue state) (click-prompt state :runner "No") (is (empty? (:prompt (get-runner))) "No additional prompts to rez other copies of Paperclip"))) (testing "auto-pump" (testing "Pumping and breaking for 1" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Vanilla"] :credits 10} :runner {:hand ["Paperclip"] :credits 100}}) (play-from-hand state :corp "Vanilla" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -1 (:credit (get-runner)) "Paid 1 to fully break Vanilla with Paperclip" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh pc)})) (is (= 2 (get-strength (refresh pc))) "Pumped Paperclip up to str 2") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "Pumping for >1 and breaking for 1" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Fire Wall"] :credits 10} :runner {:hand ["Paperclip"] :credits 100}}) (play-from-hand state :corp "Fire Wall" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -4 (:credit (get-runner)) "Paid 4 to fully break Fire Wall with Paperclip" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh pc)})) (is (= 5 (get-strength (refresh pc))) "Pumped Paperclip up to str 5") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "Pumping for 1 and breaking for >1" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Spiderweb"] :credits 10} :runner {:hand ["Paperclip"] :credits 100}}) (play-from-hand state :corp "Spiderweb" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -3 (:credit (get-runner)) "Paid 3 to fully break Spiderweb with Paperclip" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh pc)})) (is (= 4 (get-strength (refresh pc))) "Pumped Paperclip up to str 4") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "Pumping for >1 and breaking for >1" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Chiyashi"] :credits 12} :runner {:hand ["Paperclip"] :credits 100}}) (play-from-hand state :corp "Chiyashi" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -7 (:credit (get-runner)) "Paid 7 to fully break Chiyashi with Paperclip" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh pc)})) (is (= 8 (get-strength (refresh pc))) "Pumped Paperclip up to str 8") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "No auto-pump on unbreakable subs" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Akhet"] :credits 10} :runner {:hand ["Paperclip"] :credits 100}}) (core/gain state :corp :click 1) (play-from-hand state :corp "Akhet" "HQ") (rez state :corp (get-ice state :hq 0)) (dotimes [n 3] (advance state (get-ice state :hq 0))) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (is (empty? (filter #(:dynamic %) (:abilities (refresh pc)))) "No auto-pumping option for Akhet")))) (testing "Orion triggers all heap breakers once" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Orion"] :credits 15} :runner {:discard [(qty "Paperclip" 2) (qty "MKUltra" 2) (qty "Black Orchestra" 2)] :credits 100}}) (play-from-hand state :corp "Orion" "HQ") (take-credits state :corp) (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "No") (click-prompt state :runner "No") (click-prompt state :runner "No") (is (empty? (:prompt (get-runner))) "No further prompts to install heap breakers")))) (testing "Heap Locked" (do-game (new-game {:corp {:deck ["Vanilla" "Blacklist"]} :runner {:deck [(qty "Paperclip" 2)]}}) (play-from-hand state :corp "Vanilla" "Archives") (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (refresh (get-content state :remote1 0))) (take-credits state :corp) (trash-from-hand state :runner "Paperclip") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (is (empty? (:prompt (get-runner))) "Paperclip prompt did not come up") (fire-subs state (get-ice state :archives 0)) (is (not (:run @state)) "Run ended"))) (testing "Breaking some subs" (do-game (new-game {:corp {:hand ["Hive"]} :runner {:hand ["Paperclip"] :credits 10}}) (play-from-hand state :corp "Hive" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -2 (:credit (get-runner)) "Paid 2 to break two of the subs on Hive" (is (= 5 (count (:subroutines (get-ice state :hq 0)))) "Hive starts with 5 subs") (is (= 3 (get-strength (get-ice state :hq 0))) "Hive has strength 3") (card-ability state :runner pc 0) (click-prompt state :runner "2") (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (is (= 3 (get-strength (refresh pc))) "Pumped Paperclip up to str 3") (is (= 3 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broke all but 3 subs")))))) (deftest parasite (testing "Basic functionality: Gain 1 counter every Runner turn" (do-game (new-game {:corp {:deck [(qty "Wraparound" 3) (qty "Hedge Fund" 3)]} :runner {:deck [(qty "Parasite" 3) (qty "Sure Gamble" 3)]}}) (play-from-hand state :corp "Wraparound" "HQ") (let [wrap (get-ice state :hq 0)] (rez state :corp wrap) (take-credits state :corp) (play-from-hand state :runner "Parasite") (click-card state :runner wrap) (is (= 3 (core/available-mu state)) "Parasite consumes 1 MU") (let [psite (first (:hosted (refresh wrap)))] (is (zero? (get-counters psite :virus)) "Parasite has no counters yet") (take-credits state :runner) (take-credits state :corp) (is (= 1 (get-counters (refresh psite) :virus)) "Parasite gained 1 virus counter at start of Runner turn") (is (= 6 (get-strength (refresh wrap))) "Wraparound reduced to 6 strength"))))) (testing "Installed facedown w/ Apex" (do-game (new-game {:runner {:id "Apex: Invasive Predator" :deck ["Parasite"]}}) (take-credits state :corp) (end-phase-12 state :runner) (click-card state :runner (find-card "Parasite" (:hand (get-runner)))) (is (empty? (:prompt (get-runner))) "No prompt to host Parasite") (is (= 1 (count (get-runner-facedown state))) "Parasite installed face down"))) (testing "Installed on untrashable Architect should keep gaining counters past 3 and make strength go negative" (do-game (new-game {:corp {:deck [(qty "Architect" 3) (qty "Hedge Fund" 3)]} :runner {:deck [(qty "Parasite" 3) "Grimoire"]}}) (play-from-hand state :corp "Architect" "HQ") (let [arch (get-ice state :hq 0)] (rez state :corp arch) (take-credits state :corp) (play-from-hand state :runner "Grimoire") (play-from-hand state :runner "Parasite") (click-card state :runner arch) (let [psite (first (:hosted (refresh arch)))] (is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter") (take-credits state :runner) (take-credits state :corp) (take-credits state :runner) (take-credits state :corp) (take-credits state :runner) (take-credits state :corp) (is (= 4 (get-counters (refresh psite) :virus)) "Parasite has 4 counters") (is (= -1 (get-strength (refresh arch))) "Architect at -1 strength"))))) (testing "Should stay on hosted card moved by Builder" (do-game (new-game {:corp {:deck [(qty "Builder" 3) "Ice Wall"]} :runner {:deck [(qty "Parasite" 3)]}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Builder" "Archives") (let [builder (get-ice state :archives 0)] (rez state :corp builder) (take-credits state :corp) (play-from-hand state :runner "Parasite") (click-card state :runner builder) (let [psite (first (:hosted (refresh builder)))] (take-credits state :runner) (take-credits state :corp) (is (= 3 (get-strength (refresh builder))) "Builder reduced to 3 strength") (is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter") (take-credits state :runner)) (let [orig-builder (refresh builder)] (card-ability state :corp builder 0) (click-prompt state :corp "HQ") (let [moved-builder (get-ice state :hq 1)] (is (= (get-strength orig-builder) (get-strength moved-builder)) "Builder's state is maintained") (let [orig-psite (dissoc (first (:hosted orig-builder)) :host) moved-psite (dissoc (first (:hosted moved-builder)) :host)] (is (= orig-psite moved-psite) "Hosted Parasite is maintained")) (take-credits state :corp) (let [updated-builder (refresh moved-builder) updated-psite (first (:hosted updated-builder))] (is (= 2 (get-strength updated-builder)) "Builder strength still reduced") (is (= 2 (get-counters (refresh updated-psite) :virus)) "Parasite counters still incremented"))))))) (testing "Use Hivemind counters when installed; instantly trash ICE if counters >= ICE strength" (do-game (new-game {:corp {:deck [(qty "Enigma" 3) (qty "Hedge Fund" 3)]} :runner {:deck ["Parasite" "Grimoire" "Hivemind" "Sure Gamble"]}}) (play-from-hand state :corp "Enigma" "HQ") (let [enig (get-ice state :hq 0)] (rez state :corp enig) (take-credits state :corp) (play-from-hand state :runner "Sure Gamble") (play-from-hand state :runner "Grimoire") (play-from-hand state :runner "Hivemind") (let [hive (get-program state 0)] (is (= 2 (get-counters (refresh hive) :virus)) "Hivemind has 2 counters") (play-from-hand state :runner "Parasite") (click-card state :runner enig) (is (= 1 (count (:discard (get-corp)))) "Enigma trashed instantly") (is (= 4 (core/available-mu state))) (is (= 2 (count (:discard (get-runner)))) "Parasite trashed when Enigma was trashed"))))) (testing "Trashed along with host ICE when its strength has been reduced to 0" (do-game (new-game {:corp {:deck [(qty "Enigma" 3) (qty "Hedge Fund" 3)]} :runner {:deck [(qty "Parasite" 3) "Grimoire"]}}) (play-from-hand state :corp "Enigma" "HQ") (let [enig (get-ice state :hq 0)] (rez state :corp enig) (take-credits state :corp) (play-from-hand state :runner "Grimoire") (play-from-hand state :runner "Parasite") (click-card state :runner enig) (let [psite (first (:hosted (refresh enig)))] (is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter") (is (= 1 (get-strength (refresh enig))) "Enigma reduced to 1 strength") (take-credits state :runner) (take-credits state :corp) (is (= 1 (count (:discard (get-corp)))) "Enigma trashed") (is (= 1 (count (:discard (get-runner)))) "Parasite trashed when Enigma was trashed"))))) (testing "Interaction with Customized Secretary #2672" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:deck ["Parasite"] :hand ["Djinn" "Customized Secretary"] :credits 10}}) (play-from-hand state :corp "Enigma" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Djinn") (card-ability state :runner (get-program state 0) 1) (is (= "Choose a non-Icebreaker program in your grip" (:msg (prompt-map :runner)))) (click-card state :runner "Customized Secretary") (is (= "Choose a program to host" (:msg (prompt-map :runner)))) (click-prompt state :runner "Parasite") (card-ability state :runner (first (:hosted (get-program state 0))) 0) (is (= "Parasite" (:title (first (:hosted (first (:hosted (get-program state 0)))))))) (is (= "Choose a program to install" (:msg (prompt-map :runner)))) (click-prompt state :runner "Parasite") (is (= "Choose a card to host Parasite on" (:msg (prompt-map :runner)))) (click-card state :runner "Enigma") (is (= "Customized Secretary" (:title (first (:hosted (get-program state 0)))))) (is (empty? (:hosted (first (:hosted (get-program state 0)))))))) (testing "Triggers Hostile Infrastructure" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Hostile Infrastructure" "Vanilla"]} :runner {:deck [(qty "Parasite" 2)]}}) (play-from-hand state :corp "Hostile Infrastructure" "New remote") (play-from-hand state :corp "Vanilla" "HQ") (let [van (get-ice state :hq 0) hi (get-content state :remote1 0)] (rez state :corp hi) (rez state :corp van) (take-credits state :corp) (changes-val-macro 2 (count (:discard (get-runner))) "Took net damage (Parasite on Vanilla was trashed + card from hand" (play-from-hand state :runner "Parasite") (click-card state :runner van)))))) (deftest paricia ;; Paricia (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["PAD Campaign" "Shell Corporation"]} :runner {:hand ["Paricia"]}}) (play-from-hand state :corp "PAD Campaign" "New remote") (play-from-hand state :corp "Shell Corporation" "New remote") (take-credits state :corp) (play-from-hand state :runner "Paricia") (let [pad (get-content state :remote1 0) shell (get-content state :remote2 0) paricia (get-program state 0)] (run-empty-server state :remote2) (click-prompt state :runner "Pay 3 [Credits] to trash") (is (empty? (:prompt (get-runner))) "No pay-credit prompt as it's an upgrade") (is (nil? (refresh shell)) "Shell Corporation successfully trashed") (run-empty-server state :remote1) (is (= 2 (:credit (get-runner))) "Runner can't afford to trash PAD Campaign") (click-prompt state :runner "Pay 4 [Credits] to trash") (dotimes [_ 2] (click-card state :runner "Paricia")) (is (nil? (refresh pad)) "PAD Campaign successfully trashed")))) (deftest pawn ;; Pawn (testing "Happy Path" (do-game (new-game {:corp {:deck ["Enigma" "Blacklist" "Hedge Fund"]} :runner {:deck ["Pawn" "Knight"]}}) (play-from-hand state :corp "Enigma" "Archives") (take-credits state :corp) (trash-from-hand state :runner "Knight") (play-from-hand state :runner "Pawn") ;;currently Pawn successful run check is not implemented, nor is hosted location check (card-ability state :runner (get-program state 0) 2) (click-card state :runner (find-card "Knight" (:discard (get-runner)))) (is (not (nil? (find-card "Pawn" (:discard (get-runner)))))))) (testing "Heap locked" (do-game (new-game {:corp {:deck ["Enigma" "Blacklist" "Hedge Fund"]} :runner {:deck ["Pawn" "Knight"]}}) (play-from-hand state :corp "Enigma" "Archives") (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (refresh (get-content state :remote1 0))) (take-credits state :corp) (trash-from-hand state :runner "Knight") (play-from-hand state :runner "Pawn") (card-ability state :runner (get-program state 0) 2) (is (empty? (:prompt (get-runner))) "Install prompt did not come up") (is (nil? (find-card "Pawn" (:discard (get-runner))))) (is (not (nil? (find-card "Knight" (:discard (get-runner))))))))) (deftest pelangi ;; Pelangi (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 10)] :hand ["Ice Wall"]} :runner {:hand ["Pelangi"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Pelangi") (let [iw (get-ice state :hq 0) pelangi (get-program state 0)] (run-on state "HQ") (rez state :corp iw) (run-continue state) (card-ability state :runner pelangi 0) (click-prompt state :runner "Code Gate") (is (has-subtype? (refresh iw) "Code Gate") "Ice Wall gained Code Gate") (run-continue state) (run-jack-out state) (is (not (has-subtype? (refresh iw) "Code Gate")) "Ice Wall lost Code Gate at the end of the run")))) (deftest penrose ;; Penrose (testing "Pay-credits prompt and first turn ability" (do-game (new-game {:runner {:deck ["Cloak" "Penrose"]} :corp {:deck ["Enigma" "Vanilla"]}}) (play-from-hand state :corp "Enigma" "HQ") (play-from-hand state :corp "Vanilla" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cloak") (play-from-hand state :runner "Penrose") (core/gain state :runner :credit 1) (run-on state :hq) (let [enig (get-ice state :hq 0) van (get-ice state :hq 1) cl (get-program state 0) penr (get-program state 1)] (is (= 3 (count (:abilities penr))) "3 abilities on Penrose") (rez state :corp van) (run-continue state) (is (= 4 (count (:abilities (refresh penr)))) "Auto pump and break ability on Penrose active") (changes-val-macro 0 (:credit (get-runner)) "Used 1 credit from Cloak" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh penr)}) (click-card state :runner cl)) (core/continue state :corp nil) (rez state :corp enig) (run-continue state) (changes-val-macro -2 (:credit (get-runner)) "Paid 2 credits to break all subroutines on Enigma" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh penr)})) (core/continue state :corp nil) (run-jack-out state) (take-credits state :runner) (take-credits state :corp) (run-on state :hq) (is (= 3 (count (:abilities (refresh penr)))) "Auto pump and break ability on Penrose is not active") (card-ability state :runner (refresh penr) 0) (is (empty? (:prompt (get-runner))) "No cloak prompt because the ability to break barriers is not active anymore"))))) (deftest peregrine ;; Peregrine - 2c to return to grip and derez an encountered code gate (do-game (new-game {:corp {:deck ["Paper Wall" (qty "Bandwidth" 2)]} :runner {:deck ["Peregrine"]}}) (play-from-hand state :corp "Bandwidth" "Archives") (play-from-hand state :corp "Bandwidth" "Archives") (play-from-hand state :corp "Paper Wall" "Archives") (take-credits state :corp) (core/gain state :runner :credit 20) (play-from-hand state :runner "Peregrine") (let [bw1 (get-ice state :archives 0) pw (get-ice state :archives 2) per (get-program state 0)] (run-on state "Archives") (rez state :corp pw) (run-continue state) (rez state :corp bw1) (changes-val-macro 0 (:credit (get-runner)) "Can't use Peregrine on a barrier" (card-ability state :runner per 2)) (run-continue state) (run-continue state) (changes-val-macro 0 (:credit (get-runner)) "Can't use Peregrine on an unrezzed code gate" (card-ability state :runner per 2)) (run-continue state) (changes-val-macro -3 (:credit (get-runner)) "Paid 3 to pump strength" (card-ability state :runner per 1)) (changes-val-macro -1 (:credit (get-runner)) "Paid 1 to break sub" (card-ability state :runner per 0) (click-prompt state :runner "Give the Runner 1 tag")) (changes-val-macro -2 (:credit (get-runner)) "Paid 2 to derez Bandwidth" (card-ability state :runner per 2) (run-continue state)) (is (= 1 (count (:hand (get-runner)))) "Peregrine returned to grip") (is (not (rezzed? (refresh bw1))) "Bandwidth derezzed")))) (deftest persephone ;; Persephone's ability trashes cards from R&D (testing "Triggers AR-Enhanced Security. Issue #3187" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Zed 1.0" "Zed 2.0" "AR-Enhanced Security"]} :runner {:deck [(qty "Persephone" 10)]}}) (play-from-hand state :corp "AR-Enhanced Security" "New remote") (score-agenda state :corp (get-content state :remote1 0)) (play-from-hand state :corp "Zed 1.0" "Archives") (rez state :corp (get-ice state :archives 0)) (take-credits state :corp) (play-from-hand state :runner "Persephone") (run-on state "Archives") (run-continue state) (fire-subs state (get-ice state :archives 0)) (run-continue state) (click-prompt state :runner "Yes") (is (= 1 (count-tags state)) "Runner took 1 tag from using Persephone's ability while AR-Enhanced Security is scored") (run-jack-out state) (take-credits state :runner) ;; Gotta move the discarded cards back to the deck (core/move state :corp (find-card "Zed 2.0" (:discard (get-corp))) :deck) (core/move state :corp (find-card "Zed 2.0" (:discard (get-corp))) :deck) (take-credits state :corp) (run-on state "Archives") (run-continue state) (fire-subs state (get-ice state :archives 0)) (run-continue state) (click-prompt state :runner "Yes") (is (= 2 (count-tags state)) "Runner took 1 tag from using Persephone's ability while AR-Enhanced Security is scored")))) (deftest pheromones ;; Pheromones ability shouldn't have a NullPointerException when fired with 0 virus counter (testing "Basic test" (do-game (new-game {:runner {:deck ["Pheromones"]}}) (take-credits state :corp) (play-from-hand state :runner "Pheromones") (let [ph (get-program state 0)] (card-ability state :runner (refresh ph) 0) (run-empty-server state "HQ") (click-prompt state :runner "No action") (is (= 1 (get-counters (refresh ph) :virus)) "Pheromones gained 1 counter") (card-ability state :runner (refresh ph) 0)))) ; this doesn't do anything, but shouldn't crash (testing "Pay-credits prompt" (do-game (new-game {:runner {:deck ["Pheromones" "Inti"]}}) (take-credits state :corp) (play-from-hand state :runner "Pheromones") (play-from-hand state :runner "Inti") (run-empty-server state "HQ") (click-prompt state :runner "No action") (run-empty-server state "HQ") (click-prompt state :runner "No action") (take-credits state :runner) (take-credits state :corp) (let [phero (get-program state 0) inti (get-program state 1)] (is (changes-credits (get-runner) -2 (card-ability state :runner inti 1))) (changes-val-macro 0 (:credit (get-runner)) "Used 2 credits from Pheromones" (run-on state "HQ") (card-ability state :runner inti 1) (click-card state :runner phero) (click-card state :runner phero)))))) (deftest plague ;; Plague (do-game (new-game {:corp {:deck ["Mark Yale"]} :runner {:deck ["Plague"]}}) (play-from-hand state :corp "Mark Yale" "New remote") (take-credits state :corp) (play-from-hand state :runner "Plague") (click-prompt state :runner "Server 1") (let [plague (get-program state 0)] (run-empty-server state "Server 1") (click-prompt state :runner "No action") (is (= 2 (get-counters (refresh plague) :virus)) "Plague gained 2 counters") (run-empty-server state "Server 1") (click-prompt state :runner "No action") (is (= 4 (get-counters (refresh plague) :virus)) "Plague gained 2 counters") (run-empty-server state "Archives") (is (= 4 (get-counters (refresh plague) :virus)) "Plague did not gain counters")))) (deftest progenitor ;; Progenitor (testing "Hosting Hivemind, using Virus Breeding Ground. Issue #738" (do-game (new-game {:runner {:deck ["Progenitor" "Virus Breeding Ground" "Hivemind"]}}) (take-credits state :corp) (play-from-hand state :runner "Progenitor") (play-from-hand state :runner "Virus Breeding Ground") (is (= 4 (core/available-mu state))) (let [prog (get-program state 0) vbg (get-resource state 0)] (card-ability state :runner prog 0) (click-card state :runner (find-card "Hivemind" (:hand (get-runner)))) (is (= 4 (core/available-mu state)) "No memory used to host on Progenitor") (let [hive (first (:hosted (refresh prog)))] (is (= "Hivemind" (:title hive)) "Hivemind is hosted on Progenitor") (is (= 1 (get-counters hive :virus)) "Hivemind has 1 counter") (is (zero? (:credit (get-runner))) "Full cost to host on Progenitor") (take-credits state :runner 1) (take-credits state :corp) (card-ability state :runner vbg 0) ; use VBG to transfer 1 token to Hivemind (click-card state :runner hive) (is (= 2 (get-counters (refresh hive) :virus)) "Hivemind gained 1 counter") (is (zero? (get-counters (refresh vbg) :virus)) "Virus Breeding Ground lost 1 counter"))))) (testing "Keep MU the same when hosting or trashing hosted programs" (do-game (new-game {:runner {:deck ["Progenitor" "Hivemind"]}}) (take-credits state :corp) (play-from-hand state :runner "Progenitor") (let [pro (get-program state 0)] (card-ability state :runner pro 0) (click-card state :runner (find-card "Hivemind" (:hand (get-runner)))) (is (= 2 (:click (get-runner)))) (is (= 2 (:credit (get-runner)))) (is (= 4 (core/available-mu state)) "Hivemind 2 MU not deducted from available MU") ;; Trash Hivemind (core/move state :runner (find-card "Hivemind" (:hosted (refresh pro))) :discard) (is (= 4 (core/available-mu state)) "Hivemind 2 MU not added to available MU"))))) (deftest reaver ;; Reaver - Draw a card the first time you trash an installed card each turn (testing "Basic test" (do-game (new-game {:corp {:deck ["PAD Campaign"]} :runner {:deck ["Reaver" (qty "Fall Guy" 5)]}}) (starting-hand state :runner ["Reaver" "Fall Guy"]) (play-from-hand state :corp "PAD Campaign" "New remote") (take-credits state :corp) (core/gain state :runner :credit 10) (core/gain state :runner :click 1) (play-from-hand state :runner "Reaver") (is (= 1 (count (:hand (get-runner)))) "One card in hand") (run-empty-server state "Server 1") (click-prompt state :runner "Pay 4 [Credits] to trash") ; Trash PAD campaign (is (= 2 (count (:hand (get-runner)))) "Drew a card from trash of corp card") (play-from-hand state :runner "Fall Guy") (play-from-hand state :runner "Fall Guy") (is (zero? (count (:hand (get-runner)))) "No cards in hand") ; No draw from Fall Guy trash as Reaver already fired this turn (card-ability state :runner (get-resource state 0) 1) (is (zero? (count (:hand (get-runner)))) "No cards in hand") (take-credits state :runner) ; Draw from Fall Guy trash on corp turn (card-ability state :runner (get-resource state 0) 1) (is (= 1 (count (:hand (get-runner)))) "One card in hand"))) (testing "with Freelance Coding Construct - should not draw when trash from hand #2671" (do-game (new-game {:runner {:deck [(qty "Reaver" 9) "Imp" "Snitch" "Freelance Coding Contract"]}}) (starting-hand state :runner ["Reaver" "Imp" "Snitch" "Freelance Coding Contract"]) (take-credits state :corp) (play-from-hand state :runner "Reaver") (is (= 3 (count (:hand (get-runner)))) "Four cards in hand") (is (= 3 (:credit (get-runner))) "3 credits") (play-from-hand state :runner "Freelance Coding Contract") (click-card state :runner "Snitch") (click-card state :runner "Imp") (click-prompt state :runner "Done") (is (= 7 (:credit (get-runner))) "7 credits - FCC fired") (is (zero? (count (:hand (get-runner)))) "No cards in hand")))) (deftest rezeki ;; Rezeki - gain 1c when turn begins (do-game (new-game {:runner {:deck ["Rezeki"]}}) (take-credits state :corp) (play-from-hand state :runner "Rezeki") (take-credits state :runner) (let [credits (:credit (get-runner))] (take-credits state :corp) (is (= (:credit (get-runner)) (+ credits 1)) "Gain 1 from Rezeki")))) (deftest rng-key ;; RNG Key - first successful run on RD/HQ, guess a number, gain credits or cards if number matches card cost (testing "Basic behaviour - first successful run on RD/HQ, guess a number, gain credits or cards if number matches card cost" (do-game (new-game {:corp {:deck [(qty "Enigma" 5) "Hedge Fund"]} :runner {:deck ["RNG Key" (qty "Paperclip" 2)]}}) (starting-hand state :corp ["Hedge Fund"]) (starting-hand state :runner ["RNG Key"]) (take-credits state :corp) (testing "Gain 3 credits" (play-from-hand state :runner "RNG Key") (is (= 5 (:credit (get-runner))) "Starts at 5 credits") (run-empty-server state "HQ") (click-prompt state :runner "Yes") (click-prompt state :runner "5") (click-prompt state :runner "Gain 3 [Credits]") (is (= 8 (:credit (get-runner))) "Gained 3 credits") (click-prompt state :runner "No action")) (testing "Do not trigger on second successful run" (run-empty-server state "R&D") (click-prompt state :runner "No action") (take-credits state :runner) (take-credits state :corp)) (testing "Do not trigger on archives" (run-empty-server state "Archives") (take-credits state :runner) (take-credits state :corp)) (testing "Do not get choice if trigger declined" (run-empty-server state "R&D") (click-prompt state :runner "No") (click-prompt state :runner "No action")) (run-empty-server state "R&D") (click-prompt state :runner "No action") (take-credits state :runner) (take-credits state :corp) (testing "Do not gain credits / cards if guess incorrect" (run-empty-server state "R&D") (click-prompt state :runner "Yes") (click-prompt state :runner "2") (click-prompt state :runner "No action")) (take-credits state :runner) (take-credits state :corp) (testing "Gain 2 cards" (is (zero? (count (:hand (get-runner)))) "Started with 0 cards") (run-empty-server state "R&D") (click-prompt state :runner "Yes") (click-prompt state :runner "3") (click-prompt state :runner "Draw 2 cards") (click-prompt state :runner "No action") (is (= 2 (count (:hand (get-runner)))) "Gained 2 cards") (is (zero? (count (:deck (get-runner)))) "Cards came from stack")))) (testing "Pays out when accessing an Upgrade. Issue #4804" (do-game (new-game {:corp {:deck ["Hokusai Grid" "Hedge Fund"]} :runner {:deck ["RNG Key"]}}) (play-from-hand state :corp "Hokusai Grid" "HQ") (take-credits state :corp) (play-from-hand state :runner "RNG Key") (is (= 5 (:credit (get-runner))) "Starts at 5 credits") (run-empty-server state "HQ") (click-prompt state :runner "Yes") (click-prompt state :runner "2") (click-prompt state :runner "Unrezzed upgrade") (is (= "Choose RNG Key reward" (:msg (prompt-map :runner))) "Runner gets RNG Key reward"))) (testing "Works when running a different server first #5292" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Hokusai Grid" "Hedge Fund"]} :runner {:deck ["RNG Key"]}}) (play-from-hand state :corp "Hokusai Grid" "New remote") (take-credits state :corp) (play-from-hand state :runner "RNG Key") (run-empty-server state "Server 1") (click-prompt state :runner "No action") (run-empty-server state "HQ") (click-prompt state :runner "Yes") (click-prompt state :runner "5") (is (= "Choose RNG Key reward" (:msg (prompt-map :runner))) "Runner gets RNG Key reward"))) (testing "Works after running vs Crisium Grid #3772" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Crisium Grid" "Hedge Fund"] :credits 10} :runner {:hand ["RNG Key"] :credits 10}}) (play-from-hand state :corp "Crisium Grid" "HQ") (rez state :corp (get-content state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "RNG Key") (run-empty-server state "HQ") (click-prompt state :runner "Crisium Grid") (click-prompt state :runner "Pay 5 [Credits] to trash") (click-prompt state :runner "No action") (run-empty-server state "HQ") (click-prompt state :runner "Yes") (click-prompt state :runner "5") (is (= "Choose RNG Key reward" (:msg (prompt-map :runner))) "Runner gets RNG Key reward")))) (deftest sadyojata ;; Sadyojata (testing "Swap ability" (testing "Doesnt work if no Deva in hand" (do-game (new-game {:runner {:hand ["Sadyojata" "Corroder"] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Sadyojata") (card-ability state :runner (get-program state 0) 2) (is (empty? (:prompt (get-runner))) "No select prompt as there's no Deva in hand"))) (testing "Works with another deva in hand" (doseq [deva ["Aghora" "Sadyojata" "Vamadeva"]] (do-game (new-game {:runner {:hand ["Sadyojata" deva] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Sadyojata") (let [installed-deva (get-program state 0)] (card-ability state :runner installed-deva 2) (click-card state :runner (first (:hand (get-runner)))) (is (not (utils/same-card? installed-deva (get-program state 0))) "Installed deva is not same as previous deva") (is (= deva (:title (get-program state 0))))))))) (testing "Break ability targets ice with 3 or more subtypes" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Executive Functioning"] :credits 10} :runner {:hand ["Sadyojata"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Executive Functioning" "R&D") (take-credits state :corp) (play-from-hand state :runner "Sadyojata") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "No break prompt") (run-jack-out state) (run-on state "R&D") (rez state :corp (get-ice state :rd 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (seq (:prompt (get-runner))) "Have a break prompt") (click-prompt state :runner "Trace 4 - Do 1 brain damage") (is (:broken (first (:subroutines (get-ice state :rd 0)))) "The break ability worked")))) (deftest sage ;; Sage (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma"] :credits 10} :runner {:deck ["Sage" "Box-E"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Enigma" "R&D") (take-credits state :corp) (play-from-hand state :runner "Sage") (let [sage (get-program state 0) iw (get-ice state :hq 0) engima (get-ice state :rd 0)] (is (= 2 (core/available-mu state))) (is (= 2 (get-strength (refresh sage))) "+2 strength for 2 unused MU") (play-from-hand state :runner "Box-E") (is (= 4 (core/available-mu state))) (is (= 4 (get-strength (refresh sage))) "+4 strength for 4 unused MU") (run-on state :hq) (rez state :corp iw) (run-continue state) (card-ability state :runner (refresh sage) 0) (click-prompt state :runner "End the run") (is (:broken (first (:subroutines (refresh iw)))) "Broke a barrier subroutine") (run-jack-out state) (run-on state :rd) (rez state :corp engima) (run-continue state) (card-ability state :runner (refresh sage) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "Done") (is (:broken (first (:subroutines (refresh engima)))) "Broke a code gate subroutine")))) (deftest sahasrara ;; Sahasrara (testing "Pay-credits prompt" (do-game (new-game {:runner {:deck ["Sahasrara" "Equivocation"]}}) (take-credits state :corp) (play-from-hand state :runner "Sahasrara") (let [rara (get-program state 0)] (changes-val-macro 0 (:credit (get-runner)) "Used 2 credits from Sahasrara" (play-from-hand state :runner "Equivocation") (click-card state :runner rara) (click-card state :runner rara)))))) (deftest savant ;; Savant (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Cobra" "Enigma"] :credits 10} :runner {:deck ["Savant" "Box-E"] :credits 20}}) (play-from-hand state :corp "Cobra" "HQ") (play-from-hand state :corp "Enigma" "R&D") (take-credits state :corp) (play-from-hand state :runner "Savant") (let [savant (get-program state 0) cobra (get-ice state :hq 0) enigma (get-ice state :rd 0)] (is (= 2 (core/available-mu state))) (is (= 3 (get-strength (refresh savant))) "+2 strength for 2 unused MU") (play-from-hand state :runner "Box-E") (is (= 4 (core/available-mu state))) (is (= 5 (get-strength (refresh savant))) "+4 strength for 4 unused MU") (run-on state :hq) (rez state :corp cobra) (run-continue state) (card-ability state :runner (refresh savant) 0) (click-prompt state :runner "Trash a program") (click-prompt state :runner "Done") (is (:broken (first (:subroutines (refresh cobra)))) "Broke a sentry subroutine") (run-jack-out state) (run-on state :rd) (rez state :corp enigma) (run-continue state) (card-ability state :runner (refresh savant) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (is (:broken (first (:subroutines (refresh enigma)))) "Broke a code gate subroutine")))) (deftest scheherazade ;; Scheherazade - Gain 1 credit when it hosts a program (do-game (new-game {:runner {:deck ["Scheherazade" "Cache" "Inti" "Fall Guy"]}}) (take-credits state :corp) (play-from-hand state :runner "Scheherazade") (let [sch (get-program state 0)] (card-ability state :runner sch 0) (click-card state :runner (find-card "Inti" (:hand (get-runner)))) (is (= 1 (count (:hosted (refresh sch))))) (is (= 2 (:click (get-runner))) "Spent 1 click to install and host") (is (= 6 (:credit (get-runner))) "Gained 1 credit") (is (= 3 (core/available-mu state)) "Programs hosted on Scheh consume MU") (card-ability state :runner sch 0) (click-card state :runner (find-card "Cache" (:hand (get-runner)))) (is (= 2 (count (:hosted (refresh sch))))) (is (= 6 (:credit (get-runner))) "Gained 1 credit") (card-ability state :runner sch 0) (click-card state :runner (find-card "Fall Guy" (:hand (get-runner)))) (is (= 2 (count (:hosted (refresh sch)))) "Can't host non-program") (is (= 1 (count (:hand (get-runner)))))))) (deftest self-modifying-code ;; Trash & pay 2 to search deck for a program and install it. Shuffle. (testing "Trash & pay 2 to search deck for a program and install it. Shuffle" (do-game (new-game {:runner {:deck [(qty "Self-modifying Code" 3) "Reaver"]}}) (starting-hand state :runner ["Self-modifying Code" "Self-modifying Code"]) (core/gain state :runner :credit 5) (take-credits state :corp) (play-from-hand state :runner "Self-modifying Code") (play-from-hand state :runner "Self-modifying Code") (let [smc1 (get-program state 0) smc2 (get-program state 1)] (card-ability state :runner smc1 0) (click-prompt state :runner (find-card "Reaver" (:deck (get-runner)))) (is (= 6 (:credit (get-runner))) "Paid 2 for SMC, 2 for install - 6 credits left") (is (= 1 (core/available-mu state)) "SMC MU refunded") (take-credits state :runner) (take-credits state :corp) (card-ability state :runner smc2 0) (is (= 1 (count (:hand (get-runner)))) "1 card drawn due to Reaver before SMC program selection") (is (zero? (count (:deck (get-runner)))) "Deck empty")))) (testing "Pay for SMC with Multithreader. Issue #4961" (do-game (new-game {:runner {:deck [(qty "Self-modifying Code" 3) "Rezeki"] :hand ["Self-modifying Code" "Multithreader"]}}) (take-credits state :corp) (play-from-hand state :runner "Self-modifying Code") (play-from-hand state :runner "Multithreader") (let [smc (get-program state 0) multi (get-program state 1)] (card-ability state :runner smc 0) (click-card state :runner multi) (click-card state :runner multi) (click-prompt state :runner (find-card "Rezeki" (:deck (get-runner)))) (is (= "Rezeki" (:title (get-program state 1))) "Rezeki is installed") (is (= 0 (:credit (get-runner))) "Runner had 2 credits before SMC, paid 2 for SMC from Multithreader, 2 for Rezeki install - 0 credits left"))))) (deftest shiv ;; Shiv - Gain 1 strength for each installed breaker; no MU cost when 2+ link (do-game (new-game {:runner {:id "Nasir Meidan: Cyber Explorer" :deck ["Shiv" (qty "Inti" 2) "Access to Globalsec"]}}) (is (= 1 (get-link state)) "1 link") (take-credits state :corp) (play-from-hand state :runner "Shiv") (let [shiv (get-program state 0)] (is (= 1 (get-strength (refresh shiv))) "1 installed breaker; 1 strength") (play-from-hand state :runner "Inti") (is (= 2 (get-strength (refresh shiv))) "2 installed breakers; 2 strength") (play-from-hand state :runner "Inti") (is (= 3 (get-strength (refresh shiv))) "3 installed breakers; 3 strength") (is (= 1 (core/available-mu state)) "3 MU consumed") (play-from-hand state :runner "Access to Globalsec") (is (= 2 (get-link state)) "2 link") (is (= 2 (core/available-mu state)) "Shiv stops using MU when 2+ link")))) (deftest sneakdoor-beta (testing "Gabriel Santiago, Ash on HQ should prevent Sneakdoor HQ access but still give Gabe credits. Issue #1138." (do-game (new-game {:corp {:deck ["Ash 2X3ZB9CY"]} :runner {:id "Gabriel Santiago: Consummate Professional" :deck ["Sneakdoor Beta"]}}) (play-from-hand state :corp "Ash 2X3ZB9CY" "HQ") (take-credits state :corp) (play-from-hand state :runner "Sneakdoor Beta") (is (= 1 (:credit (get-runner))) "Sneakdoor cost 4 credits") (let [sb (get-program state 0) ash (get-content state :hq 0)] (rez state :corp ash) (card-ability state :runner sb 0) (run-continue state) (click-prompt state :corp "0") (click-prompt state :runner "0") (is (= 3 (:credit (get-runner))) "Gained 2 credits from Gabe's ability") (is (= (:cid ash) (-> (prompt-map :runner) :card :cid)) "Ash interrupted HQ access after Sneakdoor run") (is (= :hq (-> (get-runner) :register :successful-run first)) "Successful Run on HQ recorded")))) (testing "do not switch to HQ if Archives has Crisium Grid. Issue #1229." (do-game (new-game {:corp {:deck ["Crisium Grid" "Priority Requisition" "Private Security Force"]} :runner {:deck ["Sneakdoor Beta"]}}) (play-from-hand state :corp "Crisium Grid" "Archives") (trash-from-hand state :corp "Priority Requisition") (take-credits state :corp) (play-from-hand state :runner "Sneakdoor Beta") (let [sb (get-program state 0) cr (get-content state :archives 0)] (rez state :corp cr) (card-ability state :runner sb 0) (run-continue state) (is (= :archives (get-in @state [:run :server 0])) "Crisium Grid stopped Sneakdoor Beta from switching to HQ")))) (testing "Allow Nerve Agent to gain counters. Issue #1158/#955" (do-game (new-game {:runner {:deck ["Sneakdoor Beta" "Nerve Agent"]}}) (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Nerve Agent") (play-from-hand state :runner "Sneakdoor Beta") (let [nerve (get-program state 0) sb (get-program state 1)] (card-ability state :runner sb 0) (run-continue state) (click-prompt state :runner "No action") (is (= 1 (get-counters (refresh nerve) :virus))) (card-ability state :runner sb 0) (run-continue state) (is (= 2 (get-counters (refresh nerve) :virus)))))) (testing "Grant Security Testing credits on HQ." (do-game (new-game {:runner {:deck ["Security Testing" "Sneakdoor Beta"]}}) (take-credits state :corp) (play-from-hand state :runner "Sneakdoor Beta") (play-from-hand state :runner "Security Testing") (take-credits state :runner) (is (= 3 (:credit (get-runner)))) (take-credits state :corp) (let [sb (get-program state 0)] (click-prompt state :runner "HQ") (card-ability state :runner sb 0) (run-continue state) (is (not (:run @state)) "Switched to HQ and ended the run from Security Testing") (is (= 5 (:credit (get-runner))) "Sneakdoor switched to HQ and earned Security Testing credits")))) (testing "Sneakdoor Beta trashed during run" (do-game (new-game {:runner {:hand ["Sneakdoor Beta"]} :corp {:hand ["Ichi 1.0" "Hedge Fund"]}}) (play-from-hand state :corp "Ichi 1.0" "Archives") (let [ichi (get-ice state :archives 0)] (rez state :corp ichi) (take-credits state :corp) (play-from-hand state :runner "Sneakdoor Beta") (let [sb (get-program state 0)] (card-ability state :runner sb 0) (run-continue state) (fire-subs state (refresh ichi)) (is (= :select (prompt-type :corp)) "Corp has a prompt to select program to delete") (click-card state :corp "Sneakdoor Beta") (click-prompt state :corp "Done") (is (= "Sneakdoor Beta" (-> (get-runner) :discard first :title)) "Sneakdoor was trashed") (click-prompt state :corp "0") (click-prompt state :runner "1") (run-continue state) (run-continue state) (is (= :hq (get-in @state [:run :server 0])) "Run continues on HQ"))))) (testing "Sneakdoor Beta effect ends at end of run" (do-game (new-game {:runner {:hand ["Sneakdoor Beta"]} :corp {:hand ["Rototurret" "Hedge Fund"] :discard ["Hedge Fund"]}}) (play-from-hand state :corp "Rototurret" "Archives") (let [roto (get-ice state :archives 0)] (rez state :corp roto) (take-credits state :corp) (play-from-hand state :runner "Sneakdoor Beta") (let [sb (get-program state 0)] (card-ability state :runner sb 0) (run-continue state) (fire-subs state (refresh roto)) (is (= :select (prompt-type :corp)) "Corp has a prompt to select program to delete") (click-card state :corp "Sneakdoor Beta") (is (= "Sneakdoor Beta" (-> (get-runner) :discard first :title)) "Sneakdoor was trashed") (run-on state "Archives") (run-continue state) (run-continue state) (is (= :approach-server (:phase (get-run))) "Run has bypassed Rototurret") (is (= :archives (get-in @state [:run :server 0])) "Run continues on Archives")))))) (deftest snitch ;; Snitch (testing "Only works on rezzed ice" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Quandary"]} :runner {:deck ["Snitch"]}}) (play-from-hand state :corp "Quandary" "R&D") (take-credits state :corp) (play-from-hand state :runner "Snitch") (let [snitch (get-program state 0)] (run-on state "R&D") (is (prompt-is-card? state :runner snitch) "Option to expose") (is (= "Use Snitch to expose approached ice?" (:msg (prompt-map :runner)))) (click-prompt state :runner "Yes") (is (= "Jack out?" (:msg (prompt-map :runner)))) (click-prompt state :runner "Yes")))) (testing "Doesn't work if ice is rezzed" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Quandary"]} :runner {:deck ["Snitch"]}}) (play-from-hand state :corp "Quandary" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Snitch") (run-on state "HQ") (is (empty? (:prompt (get-runner))) "No option to jack out") (run-continue state) (run-jack-out state))) (testing "Doesn't work if there is no ice" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Hedge Fund"]} :runner {:deck ["Snitch"]}}) (take-credits state :corp) (play-from-hand state :runner "Snitch") (run-on state "Archives") (is (empty? (:prompt (get-runner))) "No option to jack out") (run-continue state)))) (deftest snowball (testing "Strength boost until end of run when used to break a subroutine" (do-game (new-game {:corp {:deck ["Spiderweb" "Fire Wall" "Hedge Fund"] :credits 20} :runner {:deck ["Snowball"]}}) (play-from-hand state :corp "Hedge Fund") (play-from-hand state :corp "Fire Wall" "HQ") (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (core/gain state :corp :credit 1) (play-from-hand state :runner "Snowball") (let [sp (get-ice state :hq 1) fw (get-ice state :hq 0) snow (get-program state 0)] (run-on state "HQ") (rez state :corp sp) (run-continue state) (card-ability state :runner snow 1) ; match strength (is (= 2 (get-strength (refresh snow)))) (card-ability state :runner snow 0) ; strength matched, break a sub (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (is (= 5 (get-strength (refresh snow))) "Broke 3 subs, gained 3 more strength") (run-continue state) (rez state :corp fw) (run-continue state) (is (= 4 (get-strength (refresh snow))) "Has +3 strength until end of run; lost 1 per-encounter boost") (card-ability state :runner snow 1) ; match strength (is (= 5 (get-strength (refresh snow))) "Matched strength, gained 1") (card-ability state :runner snow 0) ; strength matched, break a sub (click-prompt state :runner "End the run") (is (= 6 (get-strength (refresh snow))) "Broke 1 sub, gained 1 more strength") (run-continue state) (is (= 5 (get-strength (refresh snow))) "+4 until-end-of-run strength") (run-jack-out state) (is (= 1 (get-strength (refresh snow))) "Back to default strength")))) (testing "Strength boost until end of run when using dynamic auto-pump-and-break ability" (do-game (new-game {:corp {:deck ["Spiderweb" (qty "Hedge Fund" 2)]} :runner {:deck ["Snowball"]}}) (play-from-hand state :corp "Hedge Fund") (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Snowball") (let [sp (get-ice state :hq 0) snow (get-program state 0)] (run-on state "HQ") (rez state :corp sp) (run-continue state) (is (= 1 (get-strength (refresh snow))) "Snowball starts at 1 strength") (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh snow)}) (is (= 5 (get-strength (refresh snow))) "Snowball was pumped once and gained 3 strength from breaking") (core/process-action "continue" state :corp nil) (is (= 4 (get-strength (refresh snow))) "+3 until-end-of-run strength"))))) (deftest stargate ;; Stargate - once per turn Keyhole which doesn't shuffle (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 10)] :hand ["Herald" "Troll"]} :runner {:deck ["Stargate"]}}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (is (= "Troll" (-> (get-corp) :deck first :title)) "Troll on top of deck") (is (= "Herald" (-> (get-corp) :deck second :title)) "Herald 2nd") (take-credits state :corp) (play-from-hand state :runner "Stargate") (card-ability state :runner (get-program state 0) 0) (is (:run @state) "Run initiated") (run-continue state) (click-prompt state :runner "Troll") (is (empty? (:prompt (get-runner))) "Prompt closed") (is (not (:run @state)) "Run ended") (is (-> (get-corp) :discard first :seen) "Troll is faceup") (is (= "Troll" (-> (get-corp) :discard first :title)) "Troll was trashed") (is (= "Herald" (-> (get-corp) :deck first :title)) "Herald now on top of R&D") (card-ability state :runner (get-program state 0) 0) (is (not (:run @state)) "No run ended, as Stargate is once per turn"))) (testing "Different message on repeating cards" (testing "bottom card" (do-game (new-game {:corp {:deck [(qty "Troll" 10)] :hand ["Herald" "Troll"]} :runner {:deck ["Stargate"]}}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (is (= "Troll" (-> (get-corp) :deck first :title)) "Troll 1st") (is (= "Herald" (-> (get-corp) :deck second :title)) "Herald 2nd") (is (= "Troll" (-> (get-corp) :deck (#(nth % 2)) :title)) "Another Troll 3rd") (take-credits state :corp) (play-from-hand state :runner "Stargate") (card-ability state :runner (get-program state 0) 0) (run-continue state) (click-prompt state :runner (nth (prompt-buttons :runner) 2)) (is (last-log-contains? state "Runner uses Stargate to trash bottom Troll.") "Correct log"))) (testing "middle card" (do-game (new-game {:corp {:deck [(qty "Troll" 10)] :hand ["Herald" "Troll"]} :runner {:deck ["Stargate"]}}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (is (= "Herald" (-> (get-corp) :deck first :title)) "Herald 1st") (is (= "Troll" (-> (get-corp) :deck second :title)) "Troll 2nd") (is (= "Troll" (-> (get-corp) :deck (#(nth % 2)) :title)) "Another Troll 3rd") (take-credits state :corp) (play-from-hand state :runner "Stargate") (card-ability state :runner (get-program state 0) 0) (run-continue state) (click-prompt state :runner (second (prompt-buttons :runner))) (is (last-log-contains? state "Runner uses Stargate to trash middle Troll.") "Correct log"))) (testing "top card" (do-game (new-game {:corp {:deck [(qty "Troll" 10)] :hand ["Herald" "Troll"]} :runner {:deck ["Stargate"]}}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (is (= "Troll" (-> (get-corp) :deck first :title)) "Troll 1st") (is (= "Herald" (-> (get-corp) :deck second :title)) "Herald 2nd") (is (= "Troll" (-> (get-corp) :deck (#(nth % 2)) :title)) "Another Troll 3rd") (take-credits state :corp) (play-from-hand state :runner "Stargate") (card-ability state :runner (get-program state 0) 0) (run-continue state) (click-prompt state :runner (first (prompt-buttons :runner))) (is (last-log-contains? state "Runner uses Stargate to trash top Troll.") "Correct log")))) (testing "No position indicator if non-duplicate selected" (do-game (new-game {:corp {:deck [(qty "Troll" 10)] :hand ["Herald" "Troll"]} :runner {:deck ["Stargate"]}}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (is (= "Troll" (-> (get-corp) :deck first :title)) "Troll 1st") (is (= "Herald" (-> (get-corp) :deck second :title)) "Herald 2nd") (is (= "Troll" (-> (get-corp) :deck (#(nth % 2)) :title)) "Another Troll 3rd") (take-credits state :corp) (play-from-hand state :runner "Stargate") (card-ability state :runner (get-program state 0) 0) (run-continue state) (click-prompt state :runner (second (prompt-buttons :runner))) (is (last-log-contains? state "Runner uses Stargate to trash Herald.") "Correct log")))) (deftest study-guide ;; Study Guide - 2c to add a power counter; +1 strength per counter (do-game (new-game {:runner {:deck ["Study Guide" "Sure Gamble"]}}) (take-credits state :corp) (play-from-hand state :runner "Sure Gamble") (play-from-hand state :runner "Study Guide") (let [sg (get-program state 0)] (card-ability state :runner sg 1) (is (= 4 (:credit (get-runner))) "Paid 2c") (is (= 1 (get-counters (refresh sg) :power)) "Has 1 power counter") (is (= 1 (get-strength (refresh sg))) "1 strength") (card-ability state :runner sg 1) (is (= 2 (:credit (get-runner))) "Paid 2c") (is (= 2 (get-counters (refresh sg) :power)) "Has 2 power counters") (is (= 2 (get-strength (refresh sg))) "2 strength")))) (deftest sunya ;; Sūnya (testing "Basic test" (do-game (new-game {:runner {:deck ["Sūnya"]} :corp {:deck ["Rototurret"]}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Sūnya") (let [sunya (get-program state 0) roto (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh roto)) (run-continue state) (card-ability state :runner (refresh sunya) 0) (click-prompt state :runner "Trash a program") (click-prompt state :runner "End the run") (changes-val-macro 1 (get-counters (refresh sunya) :power) "Got 1 token" (run-continue state)))))) (deftest surfer ;; Surfer - Swap position with ice before or after when encountering a Barrier ICE (testing "Basic test" (do-game (new-game {:corp {:deck ["Ice Wall" "Quandary"]} :runner {:deck ["Surfer"]}}) (play-from-hand state :corp "Quandary" "HQ") (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Surfer") (is (= 3 (:credit (get-runner))) "Paid 2 credits to install Surfer") (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (run-continue state) (is (= 2 (get-in @state [:run :position])) "Starting run at position 2") (let [surf (get-program state 0)] (card-ability state :runner surf 0) (click-card state :runner (get-ice state :hq 0)) (is (= 1 (:credit (get-runner))) "Paid 2 credits to use Surfer") (is (= 1 (get-in @state [:run :position])) "Now at next position (1)") (is (= "Ice Wall" (:title (get-ice state :hq 0))) "Ice Wall now at position 1")))) (testing "Swapping twice across two turns" (do-game (new-game {:corp {:deck ["Ice Wall" "Vanilla"]} :runner {:deck ["Surfer"] :credits 10}}) (play-from-hand state :corp "Vanilla" "HQ") (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Surfer") (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (run-continue state) (let [surf (get-program state 0)] (card-ability state :runner surf 0) (click-card state :runner (get-ice state :hq 0)) (run-jack-out state) (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (run-continue state) (card-ability state :runner surf 0) (click-card state :runner (get-ice state :hq 0)) (is (= ["Vanilla" "Ice Wall"] (map :title (get-ice state :hq))) "Vanilla is innermost, Ice Wall is outermost again") (is (= [0 1] (map :index (get-ice state :hq)))))))) (deftest takobi ;; Takobi - 2 power counter to add +3 strength to a non-AI icebreaker for encounter (testing "+1 counter when breaking all subs" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma"]} :runner {:hand ["Takobi" "Corroder" "Gordian Blade"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Takobi") (play-from-hand state :runner "Corroder") (play-from-hand state :runner "Gordian Blade") (let [tako (get-program state 0) corr (get-program state 1) gord (get-program state 2) enig (get-ice state :hq 1) icew (get-ice state :hq 0)] (run-on state "HQ") (rez state :corp enig) (run-continue state) (card-ability state :runner gord 0) (click-prompt state :runner "End the run") (click-prompt state :runner "Done") (is (empty? (:prompt (get-runner))) "No prompt because not all subs were broken") (is (= 0 (get-counters (refresh tako) :power)) "No counter gained because not all subs were broken") (run-continue state) (rez state :corp icew) (run-continue state) (card-ability state :runner corr 0) (click-prompt state :runner "End the run") (click-prompt state :runner "Yes") (run-continue state) (is (= 1 (get-counters (refresh tako) :power)) "Counter gained from breaking all subs")))) (testing "+3 strength" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Takobi" "Corroder" "Faust"] :credits 10}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Takobi") (play-from-hand state :runner "Corroder") (play-from-hand state :runner "Faust") (let [tako (get-program state 0) corr (get-program state 1) faus (get-program state 2)] (core/add-counter state :runner tako :power 3) (is (= 3 (get-counters (refresh tako) :power)) "3 counters on Takobi") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner tako 0) (click-card state :runner (refresh faus)) (is (not-empty (:prompt (get-runner))) "Can't select AI breakers") (click-card state :runner (refresh corr)) (is (empty? (:prompt (get-runner))) "Can select non-AI breakers") (is (= 5 (get-strength (refresh corr))) "Corroder at +3 strength") (is (= 1 (get-counters (refresh tako) :power)) "1 counter on Takobi") (card-ability state :runner tako 0) (is (empty? (:prompt (get-runner))) "No prompt when too few power counters") (run-continue state) (run-continue state) (is (= 2 (get-strength (refresh corr))) "Corroder returned to normal strength"))))) (deftest tranquilizer ;; Tranquilizer (testing "Basic test" (do-game (new-game {:corp {:hand ["Ice Wall"] :deck [(qty "Hedge Fund" 10)]} :runner {:hand ["Tranquilizer"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Tranquilizer") (click-card state :runner (get-ice state :hq 0)) (let [iw (get-ice state :hq 0) tranquilizer (first (:hosted (refresh iw)))] (is (= 1 (get-counters (refresh tranquilizer) :virus))) (take-credits state :runner) (rez state :corp iw) (take-credits state :corp) (is (= 2 (get-counters (refresh tranquilizer) :virus))) (take-credits state :runner) (take-credits state :corp) (is (= 3 (get-counters (refresh tranquilizer) :virus))) (is (not (rezzed? (refresh iw))) "Ice Wall derezzed") (take-credits state :runner) (rez state :corp iw) (take-credits state :corp) (is (= 4 (get-counters (refresh tranquilizer) :virus))) (is (not (rezzed? (refresh iw))) "Ice Wall derezzed again")))) (testing "Derez on install" (do-game (new-game {:corp {:hand ["Ice Wall"] :deck [(qty "Hedge Fund" 10)]} :runner {:hand ["Tranquilizer" "Hivemind" "Surge"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Hivemind") (let [iw (get-ice state :hq 0) hive (get-program state 0)] (is (= 1 (get-counters (refresh hive) :virus)) "Hivemind starts with 1 virus counter") (play-from-hand state :runner "Surge") (click-card state :runner (refresh hive)) (is (= 3 (get-counters (refresh hive) :virus)) "Hivemind gains 2 virus counters") (rez state :corp iw) (is (rezzed? (refresh iw)) "Ice Wall rezzed") (play-from-hand state :runner "Tranquilizer") (click-card state :runner (get-ice state :hq 0)) (let [tranquilizer (first (:hosted (refresh iw)))] (is (= 1 (get-counters (refresh tranquilizer) :virus))) (is (not (rezzed? (refresh iw))) "Ice Wall derezzed")))))) (deftest trope ;; Trope (testing "Happy Path" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)]} :runner {:hand ["Trope" "Easy Mark"] :discard ["Sure Gamble" "Easy Mark" "Dirty Laundry"]}}) (take-credits state :corp) (play-from-hand state :runner "Trope") ;; wait 3 turns to make Trope have 3 counters (dotimes [n 3] (take-credits state :runner) (take-credits state :corp)) (is (= 3 (get-counters (refresh (get-program state 0)) :power))) (is (zero? (count (:deck (get-runner)))) "0 cards in deck") (is (= 3 (count (:discard (get-runner)))) "3 cards in discard") (card-ability state :runner (get-program state 0) 0) (is (not (empty? (:prompt (get-runner)))) "Shuffle prompt came up") (click-card state :runner (find-card "Easy Mark" (:discard (get-runner)))) (click-card state :runner (find-card "Dirty Laundry" (:discard (get-runner)))) (click-card state :runner (find-card "Sure Gamble" (:discard (get-runner)))) (is (= 3 (count (:deck (get-runner)))) "3 cards in deck") (is (zero? (count (:discard (get-runner)))) "0 cards in discard"))) (testing "Heap Locked" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Blacklist"]} :runner {:hand ["Trope" "Easy Mark"] :discard ["Sure Gamble" "Easy Mark" "Dirty Laundry"]}}) (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (refresh (get-content state :remote1 0))) (take-credits state :corp) (play-from-hand state :runner "Trope") ;; wait 3 turns to make Trope have 3 counters (dotimes [n 3] (take-credits state :runner) (take-credits state :corp)) (is (= 3 (get-counters (refresh (get-program state 0)) :power))) (is (zero? (count (:deck (get-runner)))) "0 cards in deck") (is (= 3 (count (:discard (get-runner)))) "3 cards in discard") (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Shuffle prompt did not come up")))) (deftest trypano (testing "Hivemind and Architect interactions" (do-game (new-game {:corp {:deck [(qty "Architect" 2)]} :runner {:deck [(qty "Trypano" 2) "Hivemind"]}}) (play-from-hand state :corp "Architect" "HQ") (play-from-hand state :corp "Architect" "R&D") (let [architect-rezzed (get-ice state :hq 0) architect-unrezzed (get-ice state :rd 0)] (rez state :corp architect-rezzed) (take-credits state :corp) (play-from-hand state :runner "Trypano") (click-card state :runner (get-card state architect-rezzed)) (play-from-hand state :runner "Trypano") (click-card state :runner architect-unrezzed) (is (= 2 (core/available-mu state)) "Trypano consumes 1 MU")) ;; wait 4 turns to make both Trypanos have 4 counters on them (dotimes [n 4] (take-credits state :runner) (take-credits state :corp) (click-prompt state :runner "Yes") (click-prompt state :runner "Yes")) (is (zero? (count (:discard (get-runner)))) "Trypano not in discard yet") (is (= 1 (count (get-in @state [:corp :servers :rd :ices]))) "Unrezzed Archiect is not trashed") (is (= 1 (count (get-in @state [:corp :servers :hq :ices]))) "Rezzed Archiect is not trashed") (play-from-hand state :runner "Hivemind") ; now Hivemind makes both Trypanos have 5 counters (is (zero? (count (get-in @state [:corp :servers :rd :ices]))) "Unrezzed Archiect was trashed") (is (= 1 (count (get-in @state [:corp :servers :hq :ices]))) "Rezzed Archiect was not trashed") (is (= 1 (count (:discard (get-runner)))) "Trypano went to discard"))) (testing "Fire when Hivemind gains counters" (do-game (new-game {:corp {:deck ["Architect"]} :runner {:deck ["Trypano" "Hivemind" (qty "Surge" 2)]}}) (play-from-hand state :corp "Architect" "R&D") (let [architect-unrezzed (get-ice state :rd 0)] (take-credits state :corp) (play-from-hand state :runner "Trypano") (click-card state :runner architect-unrezzed) (is (zero? (count (:discard (get-runner)))) "Trypano not in discard yet") (is (= 1 (count (get-ice state :rd))) "Unrezzed Architect is not trashed") (play-from-hand state :runner "Hivemind") (let [hive (get-program state 0)] (is (= 1 (get-counters (refresh hive) :virus)) "Hivemind starts with 1 virus counter") (play-from-hand state :runner "Surge") (click-card state :runner (refresh hive)) (is (= 3 (get-counters (refresh hive) :virus)) "Hivemind gains 2 virus counters") (play-from-hand state :runner "Surge") (click-card state :runner (refresh hive)) (is (= 5 (get-counters (refresh hive) :virus)) "Hivemind gains 2 virus counters (now at 5)") (is (zero? (count (get-ice state :rd))) "Unrezzed Architect was trashed") (is (= 3 (count (:discard (get-runner)))) "Trypano went to discard")))))) (deftest tycoon ;; Tycoon (testing "Tycoon gives 2c after using to break ICE" (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["Tycoon"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Tycoon") (let [tycoon (get-program state 0) credits (:credit (get-corp))] (run-on state "HQ") (run-continue state) (card-ability state :runner tycoon 0) (click-prompt state :runner "End the run") (card-ability state :runner tycoon 1) (is (= 4 (get-strength (refresh tycoon))) "Tycoon strength pumped to 4.") (is (= credits (:credit (get-corp))) "Corp doesn't gain credits until encounter is over") (run-continue state) (is (= (+ credits 2) (:credit (get-corp))) "Corp gains 2 credits from Tycoon being used") (is (= 1 (get-strength (refresh tycoon))) "Tycoon strength back down to 1.")))) ;; Issue #4220: Tycoon doesn't fire if Corp ends run before ice is passed (testing "Tycoon gives 2c even if ICE wasn't passed" (do-game (new-game {:corp {:deck ["Ice Wall" "Nisei MK II"]} :runner {:deck ["Tycoon"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (rez state :corp (get-ice state :hq 0)) (play-and-score state "Nisei MK II") (take-credits state :corp) (play-from-hand state :runner "Tycoon") (let [tycoon (get-program state 0) credits (:credit (get-corp)) nisei (get-scored state :corp 0)] (run-on state "HQ") (run-continue state) (card-ability state :runner tycoon 0) (click-prompt state :runner "End the run") (card-ability state :runner tycoon 1) (is (= 4 (get-strength (refresh tycoon))) "Tycoon strength pumped to 4.") (is (= credits (:credit (get-corp))) "Corp doesn't gain credits until encounter is over") (card-ability state :corp (refresh nisei) 0) (is (= (+ credits 2) (:credit (get-corp))) "Corp gains 2 credits from Tycoon being used after Nisei MK II fires") (is (= 1 (get-strength (refresh tycoon))) "Tycoon strength back down to 1.")))) ;; Issue #4423: Tycoon no longer working automatically (testing "Tycoon pays out on auto-pump-and-break" (do-game (new-game {:corp {:deck ["Markus 1.0"]} :runner {:deck ["Tycoon"]}}) (play-from-hand state :corp "Markus 1.0" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Tycoon") (let [tycoon (get-program state 0) credits (:credit (get-corp))] (run-on state "HQ") (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh tycoon)}) (is (= credits (:credit (get-corp))) "Corp doesn't gain credits until encounter is over") (core/continue state :corp nil) (is (= (+ credits 2) (:credit (get-corp))) "Corp gains 2 credits from Tycoon being used"))))) (deftest unity ;; Unity (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Afshar"] :credits 20} :runner {:deck ["Unity"] :credits 20}}) (play-from-hand state :corp "Afshar" "R&D") (rez state :corp (get-ice state :rd 0)) (take-credits state :corp) (play-from-hand state :runner "Unity") (let [unity (get-program state 0) ice (get-ice state :rd 0)] (run-on state :rd) (run-continue state) (is (= 17 (:credit (get-runner))) "17 credits before breaking") (card-ability state :runner unity 1) ;;temp boost because EDN file (card-ability state :runner unity 0) (click-prompt state :runner "Make the Runner lose 2 [Credits]") (card-ability state :runner unity 0) (click-prompt state :runner "End the run") (is (= 14 (:credit (get-runner))) "14 credits after breaking") (is (zero? (count (remove :broken (:subroutines (refresh ice))))) "All subroutines have been broken")))) (testing "Boost test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["DNA Tracker"] :credits 20} :runner {:deck [(qty "Unity" 3)] :credits 20}}) (play-from-hand state :corp "DNA Tracker" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Unity") (play-from-hand state :runner "Unity") (play-from-hand state :runner "Unity") (let [unity (get-program state 0) ice (get-ice state :hq 0)] (run-on state :hq) (run-continue state) (is (= 11 (:credit (get-runner))) "11 credits before breaking") (card-ability state :runner unity 1) (card-ability state :runner unity 1) (card-ability state :runner unity 0) (click-prompt state :runner "Do 1 net damage and make the Runner lose 2 [Credits]") (card-ability state :runner unity 0) (click-prompt state :runner "Do 1 net damage and make the Runner lose 2 [Credits]") (card-ability state :runner unity 0) (click-prompt state :runner "Do 1 net damage and make the Runner lose 2 [Credits]") (is (= 6 (:credit (get-runner))) "6 credits after breaking") (is (zero? (count (remove :broken (:subroutines (refresh ice))))) "All subroutines have been broken"))))) (deftest upya (do-game (new-game {:runner {:deck ["Upya"]}}) (take-credits state :corp) (play-from-hand state :runner "Upya") (dotimes [_ 3] (run-empty-server state "R&D")) (is (= 3 (get-counters (get-program state 0) :power)) "3 counters on Upya") (take-credits state :corp) (dotimes [_ 3] (run-empty-server state "R&D")) (is (= 6 (get-counters (get-program state 0) :power)) "6 counters on Upya") (let [upya (get-program state 0)] (card-ability state :runner upya 0) (is (= 3 (get-counters (refresh upya) :power)) "3 counters spent") (is (= 2 (:click (get-runner))) "Gained 2 clicks") (card-ability state :runner upya 0) (is (= 3 (get-counters (refresh upya) :power)) "Upya not used more than once a turn") (is (= 2 (:click (get-runner))) "Still at 2 clicks")) (take-credits state :runner) (take-credits state :corp) (let [upya (get-program state 0)] (card-ability state :runner upya 0) (is (zero? (get-counters (refresh upya) :power)) "3 counters spent") (is (= 5 (:click (get-runner))) "Gained 2 clicks")))) (deftest utae ;; Utae (do-game (new-game {:corp {:deck ["Enigma"]} :runner {:deck ["Utae" (qty "Logic Bomb" 3)] :credits 10}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Utae") (let [utae (get-program state 0)] (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (let [credits (:credit (get-runner))] (card-ability state :runner utae 2) (is (= (dec credits) (:credit (get-runner))) "Spent 1 credit")) (let [credits (:credit (get-runner))] (card-ability state :runner utae 0) (click-prompt state :runner "2") (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (is (= (- credits 2) (:credit (get-runner))) "Spent 2 credits")) (let [credits (:credit (get-runner))] (card-ability state :runner utae 0) (is (empty? (:prompt (get-runner))) "Can only use ability once per run") (card-ability state :runner utae 1) (is (= credits (:credit (get-runner))) "Cannot use this ability without 3 installed virtual resources")) (run-jack-out state) (core/gain state :runner :click 2) (dotimes [_ 3] (play-from-hand state :runner "Logic Bomb")) (run-on state "HQ") (run-continue state) (card-ability state :runner utae 2) (let [credits (:credit (get-runner))] (card-ability state :runner utae 1) (click-prompt state :runner "End the run") (click-prompt state :runner "Done") (is (= (dec credits) (:credit (get-runner))))) (is (= 3 (:credit (get-runner))) "Able to use ability now")))) (deftest vamadeva ;; Vamadeva (testing "Swap ability" (testing "Doesnt work if no Deva in hand" (do-game (new-game {:runner {:hand ["Vamadeva" "Corroder"] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Vamadeva") (card-ability state :runner (get-program state 0) 2) (is (empty? (:prompt (get-runner))) "No select prompt as there's no Deva in hand"))) (testing "Works with another deva in hand" (doseq [deva ["Aghora" "Sadyojata" "Vamadeva"]] (do-game (new-game {:runner {:hand ["Vamadeva" deva] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Vamadeva") (let [installed-deva (get-program state 0)] (card-ability state :runner installed-deva 2) (click-card state :runner (first (:hand (get-runner)))) (is (not (utils/same-card? installed-deva (get-program state 0))) "Installed deva is not same as previous deva") (is (= deva (:title (get-program state 0))))))))) (testing "Break ability targets ice with 1 subroutine" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma" "Ice Wall"] :credits 10} :runner {:hand ["Vamadeva"] :credits 10}}) (play-from-hand state :corp "Enigma" "HQ") (play-from-hand state :corp "Ice Wall" "R&D") (take-credits state :corp) (play-from-hand state :runner "Vamadeva") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "No break prompt") (run-jack-out state) (run-on state "R&D") (rez state :corp (get-ice state :rd 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (seq (:prompt (get-runner))) "Have a break prompt") (click-prompt state :runner "End the run") (is (:broken (first (:subroutines (get-ice state :rd 0)))) "The break ability worked")))) (deftest wari (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["Wari"]}}) (play-from-hand state :corp "Ice Wall" "R&D") (take-credits state :corp) (play-from-hand state :runner "Wari") (run-empty-server state "HQ") (click-prompt state :runner "Yes") (click-prompt state :runner "Barrier") (click-card state :runner (get-ice state :rd 0)) (is (= 1 (count (:discard (get-runner)))) "Wari in heap") (is (seq (:prompt (get-runner))) "Runner is currently accessing Ice Wall"))) (deftest wyrm ;; Wyrm reduces strength of ice (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["Wyrm"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Wyrm") (run-on state "HQ") (let [ice-wall (get-ice state :hq 0) wyrm (get-program state 0)] (rez state :corp ice-wall) (run-continue state) (card-ability state :runner wyrm 1) (is (zero? (get-strength (refresh ice-wall))) "Strength of Ice Wall reduced to 0") (card-ability state :runner wyrm 1) (is (= -1 (get-strength (refresh ice-wall))) "Strength of Ice Wall reduced to -1")))) (deftest yusuf ;; Yusuf gains virus counters on successful runs and can spend virus counters from any installed card (testing "Yusuf basic tests" (do-game (new-game {:corp {:deck ["Fire Wall"]} :runner {:deck ["Yusuf" "Cache"]}}) (play-from-hand state :corp "Fire Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Yusuf") (play-from-hand state :runner "Cache") (let [fire-wall (get-ice state :hq 0) yusuf (get-program state 0) cache (get-program state 1)] (run-empty-server state "Archives") (is (= 1 (get-counters (refresh yusuf) :virus)) "Yusuf has 1 virus counter") (is (= 3 (get-strength (refresh yusuf))) "Initial Yusuf strength") (is (= 3 (get-counters (refresh cache) :virus)) "Initial Cache virus counters") (run-on state "HQ") (rez state :corp fire-wall) (run-continue state) (card-ability state :runner yusuf 1) (click-card state :runner cache) (card-ability state :runner yusuf 1) (click-card state :runner yusuf) (is (= 2 (get-counters (refresh cache) :virus)) "Cache lost 1 virus counter to pump") (is (= 5 (get-strength (refresh yusuf))) "Yusuf strength 5") (is (zero? (get-counters (refresh yusuf) :virus)) "Yusuf lost 1 virus counter to pump") (is (empty? (:prompt (get-runner))) "No prompt open") (card-ability state :runner yusuf 0) (click-prompt state :runner "End the run") (click-card state :runner cache) (is (= 1 (get-counters (refresh cache) :virus)) "Cache lost its final virus counter")))))
4937
(ns game.cards.programs-test (:require [game.core :as core] [game.core.card :refer :all] [game.macros :refer [req]] [game.utils :as utils] [game.core-test :refer :all] [game.utils-test :refer :all] [game.macros-test :refer :all] [clojure.test :refer :all])) (deftest abagnale ;; Abagnale (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Abagnale"] :credits 10}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Abagnale") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 2) (is (= :approach-server (:phase (get-run))) "Run has bypassed Enigma") (is (find-card "Abagnale" (:discard (get-runner))) "Abagnale is trashed"))) (deftest adept ;; Adept (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Cobra"] :credits 10} :runner {:deck ["Adept" "Box-E"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Cobra" "R&D") (take-credits state :corp) (play-from-hand state :runner "Adept") (let [adept (get-program state 0) iw (get-ice state :hq 0) cobra (get-ice state :rd 0)] (is (= 2 (core/available-mu state))) (is (= 4 (get-strength (refresh adept))) "+2 strength for 2 unused MU") (play-from-hand state :runner "Box-E") (is (= 4 (core/available-mu state))) (is (= 6 (get-strength (refresh adept))) "+4 strength for 4 unused MU") (run-on state :hq) (rez state :corp iw) (run-continue state) (card-ability state :runner (refresh adept) 0) (click-prompt state :runner "End the run") (is (:broken (first (:subroutines (refresh iw)))) "Broke a barrier subroutine") (run-jack-out state) (run-on state :rd) (rez state :corp cobra) (run-continue state) (card-ability state :runner (refresh adept) 0) (click-prompt state :runner "Trash a program") (click-prompt state :runner "Done") (is (:broken (first (:subroutines (refresh cobra)))) "Broke a sentry subroutine")))) (deftest afterimage ;; Afterimage (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"] :credits 10} :runner {:hand ["Afterimage"] :credits 10}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (play-from-hand state :runner "Afterimage") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "Yes") (is (= :approach-server (:phase (get-run))) "Run has bypassed Rototurret"))) (testing "Can only be used once per turn. #5032" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"] :credits 10} :runner {:hand ["Afterimage"] :credits 10}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (play-from-hand state :runner "Afterimage") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "Yes") (is (= :approach-server (:phase (get-run))) "Run has bypassed Rototurret") (run-jack-out state) (run-on state "HQ") (run-continue state) (is (empty? (:prompt (get-runner))) "No bypass prompt")))) (deftest aghora ;; Aghora (testing "Swap ability" (testing "Doesnt work if no Deva in hand" (do-game (new-game {:runner {:hand ["Aghora" "Corroder"] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Aghora") (card-ability state :runner (get-program state 0) 2) (is (empty? (:prompt (get-runner))) "No select prompt as there's no Deva in hand"))) (testing "Works with another deva in hand" (doseq [deva ["Aghora" "<NAME>" "<NAME>"]] (do-game (new-game {:runner {:hand ["Aghora" deva] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Aghora") (let [installed-deva (get-program state 0)] (card-ability state :runner installed-deva 2) (click-card state :runner (first (:hand (get-runner)))) (is (not (utils/same-card? installed-deva (get-program state 0))) "Installed deva is not same as previous deva") (is (= deva (:title (get-program state 0))))))))) (testing "Break ability targets ice with rez cost 5 or higher" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Endless EULA"] :credits 10} :runner {:hand ["Aghora"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Endless EULA" "R&D") (take-credits state :corp) (play-from-hand state :runner "<NAME>") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "No break prompt") (run-jack-out state) (run-on state "R&D") (rez state :corp (get-ice state :rd 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (seq (:prompt (get-runner))) "Have a break prompt") (click-prompt state :runner "End the run unless the Runner pays 1 [Credits]") (click-prompt state :runner "Done") (is (:broken (first (:subroutines (get-ice state :rd 0)))) "The break ability worked")))) (deftest algernon ;; <NAME>non - pay 2 credits to gain a click, trash if no successful run (testing "Use, successful run" (do-game (new-game {:runner {:deck ["<NAME>"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (take-credits state :runner) (take-credits state :corp) (is (= 8 (:credit (get-runner))) "Runner starts with 8 credits") (is (= 4 (:click (get-runner))) "Runner starts with 4 clicks") (click-prompt state :runner "Yes") (is (= 6 (:credit (get-runner))) "Runner pays 2 credits") (is (= 5 (:click (get-runner))) "Runner gains 1 click") (run-empty-server state "Archives") (take-credits state :runner) (is (empty? (:discard (get-runner))) "No cards trashed") (is (= "<NAME>gernon" (:title (get-program state 0))) "Algernon still installed"))) (testing "Use, no successful run" (do-game (new-game {:runner {:deck ["<NAME>"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (take-credits state :runner) (take-credits state :corp) (is (= 8 (:credit (get-runner))) "Runner starts with 8 credits") (is (= 4 (:click (get-runner))) "Runner starts with 4 clicks") (click-prompt state :runner "Yes") (is (= 6 (:credit (get-runner))) "Runner pays 2 credits") (is (= 5 (:click (get-runner))) "Runner gains 1 click") (run-on state "Archives") (run-jack-out state) (take-credits state :runner) (is (= 1 (count (:discard (get-runner)))) "Algernon trashed") (is (empty? (get-program state)) "No programs installed"))) (testing "Not used, no successful run" (do-game (new-game {:runner {:deck ["<NAME>"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (take-credits state :runner) (take-credits state :corp) (is (= 8 (:credit (get-runner))) "Runner starts with 8 credits") (is (= 4 (:click (get-runner))) "Runner starts with 4 clicks") (click-prompt state :runner "No") (is (= 8 (:credit (get-runner))) "No credits spent") (is (= 4 (:click (get-runner))) "No clicks gained") (run-on state "Archives") (run-jack-out state) (take-credits state :runner) (is (empty? (:discard (get-runner))) "No cards trashed") (is (= "Algernon" (:title (get-program state 0))) "Algernon still installed")))) (deftest ^{:card-title "alias"} alias-breaker ;; Alias (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand [(qty "Zed 1.0" 2)]} :runner {:hand ["Alias"] :credits 10}}) (play-from-hand state :corp "Zed 1.0" "HQ") (play-from-hand state :corp "Zed 1.0" "New remote") (take-credits state :corp) (play-from-hand state :runner "Alias") (let [alias (get-program state 0) zed1 (get-ice state :hq 0) zed2 (get-ice state :remote1 0)] (is (= 1 (get-strength (refresh alias))) "Starts with 2 strength") (card-ability state :runner (refresh alias) 1) (is (= 4 (get-strength (refresh alias))) "Can gain strength outside of a run") (run-on state :hq) (rez state :corp (refresh zed1)) (run-continue state) (card-ability state :runner (refresh alias) 0) (click-prompt state :runner "Do 1 brain damage") (click-prompt state :runner "Done") (is (= 1 (count (filter :broken (:subroutines (refresh zed1))))) "The subroutine is broken") (run-jack-out state) (is (= 1 (get-strength (refresh alias))) "Drops back down to base strength on run end") (run-on state :remote1) (rez state :corp (refresh zed2)) (run-continue state) (card-ability state :runner (refresh alias) 0) (is (empty? (:prompt (get-runner))) "No break prompt because we're running a remote")))) (deftest amina ;; Amina ability (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Amina"] :credits 15}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Amina") (let [amina (get-program state 0) enigma (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh enigma)) (is (= 4 (:credit (get-corp)))) (run-continue state) (card-ability state :runner (refresh amina) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "Done") (run-continue state) (is (= 4 (:credit (get-corp))) "Corp did not lose 1c because not all subs were broken") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh amina) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (run-continue state) (is (= 3 (:credit (get-corp))) "Corp lost 1 credit") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh amina) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (run-continue state) (is (= 3 (:credit (get-corp))) "Ability only once per turn"))) (testing "Amina only triggers on itself. Issue #4716" (do-game (new-game {:runner {:deck ["Amina" "Yog.0"]} :corp {:deck ["Enigma"]}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (core/gain state :runner :credit 20 :click 1) (play-from-hand state :runner "Amina") (play-from-hand state :runner "Yog.0") (let [amina (get-program state 0) yog (get-program state 1) enima (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh enima)) (run-continue state) (card-ability state :runner (refresh amina) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh yog) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (changes-val-macro 0 (:credit (get-corp)) "No credit gain from Amina" (click-prompt state :runner "End the run") (run-continue state)) (run-jack-out state))))) (deftest analog-dreamers ;; Analog Dreamers (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Hostile Takeover" "PAD Campaign"]} :runner {:hand ["Analog Dreamers"]}}) (play-from-hand state :corp "Hostile Takeover" "New remote") (play-from-hand state :corp "PAD Campaign" "New remote") (advance state (get-content state :remote1 0) 1) (take-credits state :corp) (play-from-hand state :runner "Analog Dreamers") (card-ability state :runner (get-program state 0) 0) (run-continue state) (click-prompt state :runner "Analog Dreamers") (click-card state :runner "Hostile Takeover") (is (= "Choose a card to shuffle into R&D" (:msg (prompt-map :runner))) "Can't click on Hostile Takeover") (let [number-of-shuffles (count (core/turn-events state :corp :corp-shuffle-deck)) pad (get-content state :remote2 0)] (click-card state :runner "PAD Campaign") (is (< number-of-shuffles (count (core/turn-events state :corp :corp-shuffle-deck))) "Should be shuffled") (is (find-card "PAD Campaign" (:deck (get-corp))) "PAD Campaign is shuffled into R&D") (is (nil? (refresh pad)) "PAD Campaign is shuffled into R&D")))) (deftest ankusa ;; Ankusa (testing "Boost 1 strength for 1 credit" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Battlement"]} :runner {:hand ["Ankusa"] :credits 15}}) (play-from-hand state :corp "Battlement" "HQ") (take-credits state :corp) (play-from-hand state :runner "Ankusa") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (let [ankusa (get-program state 0) credits (:credit (get-runner))] "Boost ability costs 1 credit each" (card-ability state :runner ankusa 1) (is (= (dec credits) (:credit (get-runner))) "Boost 1 for 1 credit") (is (= (inc (get-strength ankusa)) (get-strength (refresh ankusa))) "Ankusa gains 1 strength")))) (testing "Break 1 for 2 credits" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Battlement"]} :runner {:hand ["Ankusa"] :credits 15}}) (play-from-hand state :corp "Battlement" "HQ") (take-credits state :corp) (play-from-hand state :runner "Ankusa") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (let [ankusa (get-program state 0)] (card-ability state :runner ankusa 1) (card-ability state :runner ankusa 1) (changes-val-macro -2 (:credit (get-runner)) "Break ability costs 2 credits" (card-ability state :runner ankusa 0) (click-prompt state :runner "End the run") (click-prompt state :runner "Done"))))) (testing "Breaking an ice fully returns it to hand. Issue #4711" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Battlement"]} :runner {:hand ["Ankusa"] :credits 15}}) (play-from-hand state :corp "Battlement" "HQ") (take-credits state :corp) (play-from-hand state :runner "Ankusa") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (let [ankusa (get-program state 0)] (card-ability state :runner ankusa 1) (card-ability state :runner ankusa 1) (card-ability state :runner ankusa 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (is (find-card "Battlement" (:hand (get-corp))) "Battlement should be back in hand"))))) (deftest atman ;; <NAME>man (testing "Installing with 0 power counters" (do-game (new-game {:runner {:deck ["<NAME>"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (click-prompt state :runner "0") (is (= 3 (core/available-mu state))) (let [atman (get-program state 0)] (is (zero? (get-counters atman :power)) "0 power counters") (is (zero? (get-strength atman)) "0 current strength")))) (testing "Installing with 2 power counters" (do-game (new-game {:runner {:deck ["<NAME>"]}}) (take-credits state :corp) (play-from-hand state :runner "Atman") (click-prompt state :runner "2") (is (= 3 (core/available-mu state))) (let [atman (get-program state 0)] (is (= 2 (get-counters atman :power)) "2 power counters") (is (= 2 (get-strength atman)) "2 current strength"))))) (deftest au-revoir ;; Au Revoir - Gain 1 credit every time you jack out (do-game (new-game {:runner {:deck [(qty "Au Revoir" 2)]}}) (take-credits state :corp) (play-from-hand state :runner "Au Revoir") (run-on state "Archives") (run-jack-out state) (is (= 5 (:credit (get-runner))) "Gained 1 credit from jacking out") (play-from-hand state :runner "Au Revoir") (run-on state "Archives") (run-jack-out state) (is (= 6 (:credit (get-runner))) "Gained 1 credit from each copy of Au Revoir"))) (deftest aumakua ;; Aumakua - Gain credit on no-trash (testing "Gain counter on no trash" (do-game (new-game {:corp {:deck [(qty "PAD Campaign" 3)]} :runner {:deck ["Aumakua"]}}) (play-from-hand state :corp "PAD Campaign" "New remote") (take-credits state :corp) (play-from-hand state :runner "Aumakua") (run-empty-server state "Server 1") (click-prompt state :runner "No action") (is (= 1 (get-counters (get-program state 0) :virus)) "Aumakua gains virus counter from no-trash") (core/gain state :runner :credit 5) (run-empty-server state "Server 1") (click-prompt state :runner "Pay 4 [Credits] to trash") (is (= 1 (get-counters (get-program state 0) :virus)) "Aumakua does not gain virus counter from trash"))) (testing "Gain counters on empty archives" (do-game (new-game {:runner {:deck ["Aumakua"]} :options {:start-as :runner}}) (play-from-hand state :runner "Aumakua") (run-empty-server state :archives) (is (= 1 (get-counters (get-program state 0) :virus)) "Aumakua gains virus counter from accessing empty Archives"))) (testing "Neutralize All Threats interaction" (do-game (new-game {:corp {:deck [(qty "PAD Campaign" 3)]} :runner {:deck ["Aumakua" "Neutralize All Threats"]}}) (play-from-hand state :corp "PAD Campaign" "New remote") (take-credits state :corp) (play-from-hand state :runner "Aumakua") (play-from-hand state :runner "Neutralize All Threats") (core/gain state :runner :credit 5) (run-empty-server state "Server 1") (is (zero? (get-counters (get-program state 0) :virus)) "Aumakua does not gain virus counter from ABT-forced trash")))) (deftest baba-yaga ;; Baba Yaga (do-game (new-game {:runner {:deck ["Baba Yaga" "Faerie" "Yog.0" "Sharpshooter"]}}) (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Baba Yaga") (play-from-hand state :runner "Sharpshooter") (let [baba (get-program state 0) base-abicount (count (:abilities baba))] (card-ability state :runner baba 0) (click-card state :runner "Faerie") (is (= (+ 2 base-abicount) (count (:abilities (refresh baba)))) "Baba Yaga gained 2 subroutines from Faerie") (card-ability state :runner (refresh baba) 0) (click-card state :runner (find-card "Yog.0" (:hand (get-runner)))) (is (= (+ 3 base-abicount) (count (:abilities (refresh baba)))) "Baba Yaga gained 1 subroutine from Yog.0") (trash state :runner (first (:hosted (refresh baba)))) (is (= (inc base-abicount) (count (:abilities (refresh baba)))) "Baba Yaga lost 2 subroutines from trashed Faerie") (card-ability state :runner baba 1) (click-card state :runner (find-card "Sharpshooter" (:program (:rig (get-runner))))) (is (= 2 (count (:hosted (refresh baba)))) "Faerie and Sharpshooter hosted on Baba Yaga") (is (= 1 (core/available-mu state)) "1 MU left with 2 breakers on Baba Yaga") (is (= 4 (:credit (get-runner))) "-5 from Baba, -1 from Sharpshooter played into Rig, -5 from Yog")))) (deftest bankroll ;; Bankroll - Includes check for Issue #4334 (do-game (new-game {:runner {:deck ["Bankroll" "<NAME>"]}}) (take-credits state :corp) (core/gain state :runner :click 10) (play-from-hand state :runner "Bankroll") (play-from-hand state :runner "<NAME>") (is (= 3 (core/available-mu state)) "Bankroll uses up 1 MU") (is (= 1 (:credit (get-runner))) "Bankroll cost 1 to install") (let [bankroll (get-program state 0) hosted-credits #(get-counters (refresh bankroll) :credit)] (is (zero? (hosted-credits)) "No counters on Bankroll on install") (run-empty-server state "Archives") (is (= 1 (hosted-credits)) "One credit counter on Bankroll after one successful run") (run-empty-server state "R&D") (is (= 2 (hosted-credits)) "Two credit counter on Bankroll after two successful runs") (run-empty-server state "HQ") (click-prompt state :runner "No action") (is (= 3 (hosted-credits)) "Three credit counter on Bankroll after three successful runs") (take-credits state :runner) (take-credits state :corp) (end-phase-12 state :runner) (click-prompt state :runner "Yes") (click-prompt state :runner "R&D") (run-continue state) (let [credits (:credit (get-runner))] (is (= 3 (hosted-credits)) "Jak Sinclair didn't trigger Bankroll") (card-ability state :runner bankroll 0) (is (= (+ 3 credits) (:credit (get-runner))) "Gained 3 credits when trashing Bankroll")) (is (= 1 (-> (get-runner) :discard count)) "Bankroll was trashed")))) (deftest berserker ;; <NAME>ker (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Hive" "Enigma"] :credits 100} :runner {:hand ["<NAME>"]}}) (play-from-hand state :corp "Ice Wall" "Archives") (play-from-hand state :corp "Hive" "R&D") (play-from-hand state :corp "Enigma" "HQ") (rez state :corp (get-ice state :archives 0)) (rez state :corp (get-ice state :rd 0)) (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (let [berserker (get-program state 0)] (is (= 2 (get-strength (refresh berserker))) "Berserker strength starts at 2") (run-on state :archives) (run-continue state) (is (= 3 (get-strength (refresh berserker))) "Berserker gains 1 strength from Ice Wall") (run-jack-out state) (is (= 2 (get-strength (refresh berserker))) "Berserker strength resets at end of run") (run-on state :rd) (run-continue state) (is (= 7 (get-strength (refresh berserker))) "Berserker gains 5 strength from Hive") (run-jack-out state) (is (= 2 (get-strength (refresh berserker))) "Berserker strength resets at end of run") (run-on state :hq) (run-continue state) (is (= 2 (get-strength (refresh berserker))) "Berserker gains 0 strength from Enigma (non-barrier)")))) (deftest black-orchestra (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Macrophage"] :credits 10} :runner {:hand ["Black Orchestra"] :credits 100}}) (play-from-hand state :corp "Macrophage" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Black Orchestra") (let [bo (get-program state 0)] (run-on state :hq) (run-continue state) (card-ability state :runner bo 0) (card-ability state :runner bo 0) (is (empty? (:prompt (get-runner))) "Has no break prompt as strength isn't high enough") (card-ability state :runner bo 0) (is (= 8 (get-strength (refresh bo))) "Pumped Black Orchestra up to str 8") (click-prompt state :runner "Trace 4 - Purge virus counters") (click-prompt state :runner "Trace 3 - Trash a virus") (is (= 2 (count (filter :broken (:subroutines (get-ice state :hq 0))))))))) (testing "auto-pump" (testing "Pumping more than once, breaking more than once" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Macrophage"] :credits 10} :runner {:hand ["Black Orchestra"] :credits 100}}) (play-from-hand state :corp "Macrophage" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Black Orchestra") (let [bo (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -12 (:credit (get-runner)) "Paid 12 to fully break Macrophage with Black Orchestra" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh bo)})) (is (= 10 (get-strength (refresh bo))) "Pumped Black Orchestra up to str 10") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "No pumping, breaking more than once" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Aiki"] :credits 10} :runner {:hand ["Black Orchestra"] :credits 100}}) (play-from-hand state :corp "Aiki" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Black Orchestra") (let [bo (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -6 (:credit (get-runner)) "Paid 6 to fully break Aiki with Black Orchestra" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh bo)})) (is (= 6 (get-strength (refresh bo))) "Pumped Black Orchestra up to str 6") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "Pumping and breaking once" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"] :credits 10} :runner {:hand ["Black Orchestra"] :credits 100}}) (play-from-hand state :corp "Enigma" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Black Orchestra") (let [bo (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -3 (:credit (get-runner)) "Paid 3 to fully break Enigma with Black Orchestra" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh bo)})) (is (= 4 (get-strength (refresh bo))) "Pumped Black Orchestra up to str 6") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "No auto-break on unbreakable subs" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Afshar"] :credits 10} :runner {:hand ["Black Orchestra"] :credits 100}}) (play-from-hand state :corp "Afshar" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Black Orchestra") (let [bo (get-program state 0)] (run-on state :hq) (run-continue state) (is (empty? (filter #(:dynamic %) (:abilities (refresh bo)))) "No auto-pumping option for Afshar"))))) (testing "Heap Locked" (do-game (new-game {:corp {:deck ["Enigma" "Blacklist"]} :runner {:deck [(qty "Black Orchestra" 1)]}}) (play-from-hand state :corp "Enigma" "Archives") (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (refresh (get-content state :remote1 0))) (take-credits state :corp) (trash-from-hand state :runner "Black Orchestra") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (is (empty? (:prompt (get-runner))) "Black Orchestra prompt did not come up")))) (deftest botulus ;; Botulus (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:credits 15 :hand ["Botulus"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Botulus") (click-card state :runner (get-ice state :hq 0)) (let [iw (get-ice state :hq 0) bot (first (:hosted (refresh iw)))] (run-on state :hq) (rez state :corp iw) (run-continue state) (card-ability state :runner (refresh bot) 0) (click-prompt state :runner "End the run") (is (zero? (count (remove :broken (:subroutines (refresh iw))))) "All subroutines have been broken")))) (deftest brahman ;; Brahman (testing "Basic test" (do-game (new-game {:runner {:deck ["Brahman" "Paricia" "Cache"]} :corp {:deck ["Ice Wall"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Brahman") (play-from-hand state :runner "<NAME>") (play-from-hand state :runner "<NAME>") (core/gain state :runner :credit 1) (let [brah (get-program state 0) par (get-program state 1) cache (get-program state 2) iw (get-ice state :hq 0)] (run-on state :hq) (rez state :corp iw) (run-continue state) (card-ability state :runner brah 0) ;break sub (click-prompt state :runner "End the run") (run-continue state) (is (= 0 (count (:deck (get-runner)))) "Stack is empty.") (click-card state :runner cache) (is (= 0 (count (:deck (get-runner)))) "Did not put Cache on top.") (click-card state :runner par) (is (= 1 (count (:deck (get-runner)))) "Paricia on top of Stack now.")))) (testing "Prompt on ETR" (do-game (new-game {:runner {:deck ["<NAME>" "<NAME>"]} :corp {:deck ["Spiderweb"]}}) (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (play-from-hand state :runner "<NAME>") (play-from-hand state :runner "<NAME>") (let [brah (get-program state 0) par (get-program state 1) spi (get-ice state :hq 0)] (run-on state :hq) (rez state :corp spi) (run-continue state) (card-ability state :runner brah 0) ;break sub (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (card-subroutine state :corp spi 0) ;ETR (is (= 0 (count (:deck (get-runner)))) "Stack is empty.") (click-card state :runner par) (is (= 1 (count (:deck (get-runner)))) "Paricia on top of Stack now.")))) (testing "Brahman works with Nisei tokens" (do-game (new-game {:corp {:deck ["Ice Wall" "Nisei MK II"]} :runner {:deck ["<NAME>"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-and-score state "Nisei MK II") (take-credits state :corp) (play-from-hand state :runner "<NAME>") (let [brah (get-program state 0) iw (get-ice state :hq 0) nisei (get-scored state :corp 0)] (run-on state "HQ") (rez state :corp iw) (run-continue state) (card-ability state :runner brah 0) ;break sub (click-prompt state :runner "End the run") (card-ability state :corp (refresh nisei) 0) ; Nisei Token (is (= 0 (count (:deck (get-runner)))) "Stack is empty.") (click-card state :runner brah) (is (= 1 (count (:deck (get-runner)))) "Brahman on top of Stack now.")))) (testing "Works with dynamic ability" (do-game (new-game {:runner {:deck ["<NAME>" "<NAME>"]} :corp {:deck ["Spiderweb"]}}) (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (play-from-hand state :runner "<NAME>") (play-from-hand state :runner "<NAME>") (core/gain state :runner :credit 1) (let [brah (get-program state 0) par (get-program state 1) spi (get-ice state :hq 0)] (run-on state :hq) (rez state :corp spi) (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh brah)}) (core/continue state :corp nil) (is (= 0 (count (:deck (get-runner)))) "Stack is empty.") (click-card state :runner par) (is (= 1 (count (:deck (get-runner)))) "Paricia on top of Stack now."))))) (deftest bukhgalter ;; Bukhgalter ability (testing "2c for breaking subs only with Bukhgalter" (do-game (new-game {:runner {:deck ["Bu<NAME>ter" "Mimic"]} :corp {:deck ["Pup"]}}) (play-from-hand state :corp "Pup" "HQ") (take-credits state :corp) (core/gain state :runner :credit 20 :click 1) (play-from-hand state :runner "<NAME>") (play-from-hand state :runner "Mimic") (let [bukhgalter (get-program state 0) mimic (get-program state 1) pup (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh pup)) (run-continue state) (card-ability state :runner (refresh mimic) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (changes-val-macro -1 (:credit (get-runner)) "No credit gain from Bukhgalter for breaking with only Mimic" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]")) (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh bukhgalter) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (click-prompt state :runner "Done") (card-ability state :runner (refresh mimic) 0) (changes-val-macro -1 (:credit (get-runner)) "No credit gain from Bukhgalter" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]")) (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh bukhgalter) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (changes-val-macro (+ 2 -1) (:credit (get-runner)) "2 credits gained from Bukhgalter" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]"))))) (testing "gaining 2c only once per turn" (do-game (new-game {:runner {:deck ["Bukhgalter" "Mimic"]} :corp {:deck ["Pup"]}}) (play-from-hand state :corp "Pup" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Bukhgalter") (let [bukhgalter (get-program state 0) pup (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh pup)) (run-continue state) (card-ability state :runner (refresh bukhgalter) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (changes-val-macro (+ 2 -1) (:credit (get-runner)) "2 credits gained from Bukhgalter" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]")) (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh bukhgalter) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (changes-val-macro -1 (:credit (get-runner)) "No credits gained from Bukhgalter" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]"))))) (testing "Bukhgalter only triggers on itself. Issue #4716" (do-game (new-game {:runner {:deck ["Bukhgalter" "Mimic"]} :corp {:deck ["Pup"]}}) (play-from-hand state :corp "Pup" "HQ") (take-credits state :corp) (core/gain state :runner :credit 20 :click 1) (play-from-hand state :runner "Bukhgalter") (play-from-hand state :runner "Mimic") (let [bukhgalter (get-program state 0) mimic (get-program state 1) pup (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh pup)) (run-continue state) (card-ability state :runner (refresh bukhgalter) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh mimic) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (changes-val-macro -1 (:credit (get-runner)) "No credit gain from Bukhgalter" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]")) (run-jack-out state))))) (deftest buzzsaw ;; Buzzsaw (before-each [state (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"] :credits 20} :runner {:deck ["Buzzsaw"] :credits 20}}) _ (do (play-from-hand state :corp "Enigma" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Buzzsaw") (run-on state :hq) (run-continue state)) enigma (get-ice state :hq 0) buzzsaw (get-program state 0)] (testing "pump ability" (do-game state (changes-val-macro -3 (:credit (get-runner)) "Runner spends 3 credits to pump Buzzsaw" (card-ability state :runner buzzsaw 1)) (changes-val-macro 1 (get-strength (refresh buzzsaw)) "Buzzsaw gains 1 strength per pump" (card-ability state :runner buzzsaw 1)))) (testing "break ability" (do-game state (changes-val-macro -1 (:credit (get-runner)) "Runner spends 1 credits to break with Buzzsaw" (card-ability state :runner buzzsaw 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run")) (is (every? :broken (:subroutines (refresh enigma))) "Buzzsaw breaks 2 subs at once"))))) (deftest carmen ;; Carmen (before-each [state (new-game {:runner {:hand [(qty "Carmen" 2)] :credits 20} :corp {:deck [(qty "Hedge Fund" 5)] :hand ["Swordsman"] :credits 20}}) _ (do (play-from-hand state :corp "Swordsman" "HQ") (take-credits state :corp)) swordsman (get-ice state :hq 0)] (testing "install cost discount" (do-game state (take-credits state :corp) (changes-val-macro -5 (:credit (get-runner)) "Without discount" (play-from-hand state :runner "Carmen")) (take-credits state :runner) (take-credits state :corp) (run-empty-server state :archives) (changes-val-macro -3 (:credit (get-runner)) "With discount" (play-from-hand state :runner "Carmen")))) (testing "pump ability" (do-game state (play-from-hand state :runner "C<NAME>") (let [carmen (get-program state 0)] (run-on state :hq) (rez state :corp swordsman) (run-continue state :encounter-ice) (changes-val-macro -2 (:credit (get-runner)) "Pump costs 2" (card-ability state :runner carmen 1)) (changes-val-macro 3 (get-strength (refresh carmen)) "Carmen gains 3 str" (card-ability state :runner carmen 1))))) (testing "break ability" (do-game state (play-from-hand state :runner "C<NAME>") (let [carmen (get-program state 0)] (run-on state :hq) (rez state :corp swordsman) (run-continue state :encounter-ice) (changes-val-macro -1 (:credit (get-runner)) "Break costs 1" (card-ability state :runner carmen 0) (click-prompt state :runner "Trash an AI program")) (click-prompt state :runner "Do 1 net damage") (is (empty? (:prompt (get-runner))) "Only breaks 1 sub at a time")))))) (deftest cerberus-rex-h2 ;; Cerberus "Rex" H2 - boost 1 for 1 cred, break for 1 counter (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:deck ["Cerberus \"Rex\" H2"]}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cerberus \"Rex\" H2") (is (= 2 (:credit (get-runner))) "2 credits left after install") (let [enigma (get-ice state :hq 0) rex (get-program state 0)] (run-on state "HQ") (rez state :corp enigma) (run-continue state) (is (= 4 (get-counters rex :power)) "Start with 4 counters") ;; boost strength (card-ability state :runner rex 1) (is (= 1 (:credit (get-runner))) "Spend 1 credit to boost") (is (= 2 (get-strength (refresh rex))) "At strength 2 after boost") ;; break (card-ability state :runner rex 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (is (= 1 (:credit (get-runner))) "No credits spent to break") (is (= 3 (get-counters (refresh rex) :power)) "One counter used to break")))) (deftest chakana ;; Chakana (testing "gain counters on r&d runs" (do-game (new-game {:runner {:hand ["Chakana"]}}) (take-credits state :corp) (play-from-hand state :runner "Chakana") (let [chakana (get-program state 0)] (is (zero? (get-counters (refresh chakana) :virus)) "Chakana starts with 0 counters") (run-empty-server state "R&D") (is (= 1 (get-counters (refresh chakana) :virus)) "Chakana starts with 0 counters") (run-empty-server state "R&D") (is (= 2 (get-counters (refresh chakana) :virus)) "Chakana starts with 0 counters") (run-empty-server state "HQ") (is (= 2 (get-counters (refresh chakana) :virus)) "Chakana starts with 0 counters")))) (testing "3 counters increases advancement requirements by 1" (do-game (new-game {:corp {:hand ["Hostile Takeover"]} :runner {:hand ["Chakana"]}}) (play-from-hand state :corp "Hostile Takeover" "New remote") (take-credits state :corp) (play-from-hand state :runner "Chakana") (is (= 2 (core/get-advancement-requirement (get-content state :remote1 0))) "Hostile Takeover is a 2/1 by default") (let [chakana (get-program state 0)] (core/gain state :runner :click 10) (run-empty-server state "R&D") (run-empty-server state "R&D") (run-empty-server state "R&D") (is (= 3 (get-counters (refresh chakana) :virus))) (is (= 3 (core/get-advancement-requirement (get-content state :remote1 0))) "Hostile Takeover is affected by Chakana"))))) (deftest chameleon ;; Chameleon - Install on corp turn, only returns to hand at end of runner's turn (testing "with Clone Chip" (do-game (new-game {:runner {:deck ["Chameleon" "Clone Chip"]}}) (take-credits state :corp) (play-from-hand state :runner "Clone Chip") (core/move state :runner (find-card "Chameleon" (:hand (get-runner))) :discard) (take-credits state :runner) (is (zero? (count (:hand (get-runner))))) ;; Install Chameleon on corp turn (take-credits state :corp 1) (let [chip (get-hardware state 0)] (card-ability state :runner chip 0) (click-card state :runner (find-card "Chameleon" (:discard (get-runner)))) (click-prompt state :runner "Sentry")) (take-credits state :corp) (is (zero? (count (:hand (get-runner)))) "Chameleon not returned to hand at end of corp turn") (take-credits state :runner) (is (= 1 (count (:hand (get-runner)))) "Chameleon returned to hand at end of runner's turn"))) (testing "Returns to hand after hosting. #977" (do-game (new-game {:runner {:deck [(qty "Chameleon" 2) "Scheherazade"]}}) (take-credits state :corp) (play-from-hand state :runner "Chameleon") (click-prompt state :runner "Barrier") (is (= 3 (:credit (get-runner))) "-2 from playing Chameleon") ;; Host the Chameleon on Scheherazade that was just played (as in Personal Workshop/Hayley ability scenarios) (play-from-hand state :runner "Scheherazade") (let [scheherazade (get-program state 1)] (card-ability state :runner scheherazade 1) ; Host an installed program (click-card state :runner (find-card "Chameleon" (:program (:rig (get-runner))))) (is (= 4 (:credit (get-runner))) "+1 from hosting onto Scheherazade") ;; Install another Chameleon directly onto Scheherazade (card-ability state :runner scheherazade 0) ; Install and host a program from Grip (click-card state :runner (find-card "Chameleon" (:hand (get-runner)))) (click-prompt state :runner "Code Gate") (is (= 2 (count (:hosted (refresh scheherazade)))) "2 Chameleons hosted on Scheherazade") (is (= 3 (:credit (get-runner))) "-2 from playing Chameleon, +1 from installing onto Scheherazade")) (is (zero? (count (:hand (get-runner)))) "Both Chameleons in play - hand size 0") (take-credits state :runner) (click-prompt state :runner "Chameleon") (is (= 2 (count (:hand (get-runner)))) "Both Chameleons returned to hand - hand size 2"))) (testing "Can break subroutines only on chosen subtype" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma" "Rototurret"] :credits 10} :runner {:hand ["Chameleon"] :credits 100}}) (play-from-hand state :corp "Ice Wall" "Archives") (play-from-hand state :corp "Enigma" "HQ") (play-from-hand state :corp "Rototurret" "R&D") (rez state :corp (get-ice state :archives 0)) (rez state :corp (get-ice state :hq 0)) (rez state :corp (get-ice state :rd 0)) (take-credits state :corp) (testing "Choosing Barrier" (play-from-hand state :runner "Ch<NAME>leon") (click-prompt state :runner "Barrier") (run-on state :archives) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "End the run") (is (empty? (:prompt (get-runner))) "Broke all subroutines on Ice Wall") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Enigma") (run-jack-out state) (run-on state :rd) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Rototurret") (run-jack-out state)) (take-credits state :runner) (take-credits state :corp) (testing "Choosing Code Gate" (play-from-hand state :runner "Ch<NAME>leon") (click-prompt state :runner "Code Gate") (run-on state :archives) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Ice Wall") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (is (empty? (:prompt (get-runner))) "Broke all subroutines on Engima") (run-jack-out state) (run-on state :rd) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Rototurret") (run-jack-out state)) (take-credits state :runner) (take-credits state :corp) (testing "Choosing Sentry" (play-from-hand state :runner "Chameleon") (click-prompt state :runner "Sentry") (run-on state :archives) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Ice Wall") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Enigma") (run-jack-out state) (run-on state :rd) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "Trash a program") (click-prompt state :runner "End the run") (is (empty? (:prompt (get-runner))) "Broke all subroutines on Rototurret"))))) (deftest chisel ;; Chisel (testing "Basic test" (do-game (new-game {:corp {:hand ["Ice Wall"]} :runner {:hand ["Chisel"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Chisel") (click-card state :runner "Ice Wall") (let [iw (get-ice state :hq 0) chisel (first (:hosted (refresh iw)))] (run-on state "HQ") (rez state :corp iw) (is (zero? (get-counters (refresh chisel) :virus))) (run-continue state) (is (= 1 (get-counters (refresh chisel) :virus))) (is (refresh iw) "Ice Wall still around, just at 0 strength") (run-jack-out state) (run-on state "HQ") (run-continue state) (is (nil? (refresh iw)) "Ice Wall should be trashed") (is (nil? (refresh chisel)) "Chisel should likewise be trashed")))) (testing "Doesn't work if the ice is unrezzed" (do-game (new-game {:corp {:hand ["Ice Wall"]} :runner {:hand ["Chisel"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (core/gain state :runner :click 10) (play-from-hand state :runner "Chisel") (click-card state :runner "Ice Wall") (let [iw (get-ice state :hq 0) chisel (first (:hosted (refresh iw)))] (run-on state "HQ") (is (zero? (get-counters (refresh chisel) :virus))) (is (zero? (get-counters (refresh chisel) :virus)) "Chisel gains no counters as Ice Wall is unrezzed") (is (refresh iw) "Ice Wall still around, still at 1 strength") (core/jack-out state :runner nil) (run-on state "HQ") (rez state :corp iw) (run-continue state) (is (= 1 (get-counters (refresh chisel) :virus)) "Chisel now has 1 counter") (core/jack-out state :runner nil) (derez state :corp iw) (run-on state "HQ") (run-continue state) (is (refresh iw) "Ice Wall should still be around as it's unrezzed")))) (testing "Chisel does not account for other sources of strength modification on hosted ICE #5391" (do-game (new-game {:corp {:hand ["Ice Wall"]} :runner {:hand ["Chisel" "Devil Charm"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Chisel") (play-from-hand state :runner "Devil Charm") (click-card state :runner "Ice Wall") (let [iw (get-ice state :hq 0) chisel (first (:hosted (refresh iw)))] (run-on state "HQ") (rez state :corp iw) (run-continue state) (click-prompt state :runner "Devil Charm") (click-prompt state :runner "Yes") (is (nil? (refresh iw)) "Ice Wall should be trashed") (is (nil? (refresh chisel)) "Chisel should likewise be trashed"))))) (deftest cleaver ;; Cleaver (before-each [state (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Battlement"]} :runner {:hand ["Cleaver"] :credits 15}}) _ (do (play-from-hand state :corp "Battlement" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cleaver") (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state :encounter-ice)) battlement (get-ice state :hq 0) cleaver (get-program state 0)] (testing "pump ability" (do-game state (changes-val-macro -2 (:credit (get-runner)) "costs 2" (card-ability state :runner cleaver 1)) (changes-val-macro 1 (get-strength (refresh cleaver)) "Gains 1 strength" (card-ability state :runner cleaver 1)))) (testing "pump ability" (do-game state (changes-val-macro -1 (:credit (get-runner)) "costs 1" (card-ability state :runner cleaver 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run")) (is (every? :broken (:subroutines (refresh battlement)))))))) (deftest cloak ;; Cloak (testing "Pay-credits prompt" (do-game (new-game {:runner {:deck ["Cloak" "Refractor"]}}) (take-credits state :corp) (play-from-hand state :runner "Cloak") (play-from-hand state :runner "Refractor") (let [cl (get-program state 0) refr (get-program state 1)] (changes-val-macro 0 (:credit (get-runner)) "Used 1 credit from Cloak" (card-ability state :runner refr 1) (click-card state :runner cl)))))) (deftest conduit ;; Conduit (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 8)] :hand ["Hedge Fund"]} :runner {:deck ["Conduit"]}}) (take-credits state :corp) (play-from-hand state :runner "Conduit") (let [conduit (get-program state 0)] (card-ability state :runner conduit 0) (is (:run @state) "Run initiated") (run-continue state) (click-prompt state :runner "No action") (click-prompt state :runner "Yes") (is (empty? (:prompt (get-runner))) "Prompt closed") (is (= 1 (get-counters (refresh conduit) :virus))) (is (not (:run @state)) "Run ended") (card-ability state :runner conduit 0) (run-continue state) (is (= 1 (core/access-bonus-count state :runner :rd)) "Runner should access 1 additional card") (click-prompt state :runner "No action") (click-prompt state :runner "No action") (click-prompt state :runner "Yes") (is (= 2 (get-counters (refresh conduit) :virus))) (run-empty-server state :rd) (is (= 0 (core/access-bonus-count state :runner :rd)) "Runner should access 0 additional card on normal run")))) (testing "Knobkierie interaction (Issue #5748) - Knobkierie before Conduit" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 8)] :hand ["Hedge Fund"]} :runner {:deck ["Conduit" "Knobkierie"] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Conduit") (play-from-hand state :runner "Knobkierie") (let [conduit (get-program state 0) knobkierie (get-hardware state 0)] (card-ability state :runner conduit 0) (is (:run @state) "Run initiated") (run-continue state :access-server) (click-prompt state :runner "Knobkierie") (click-prompt state :runner "Yes") (click-card state :runner (refresh conduit)) (is (= 1 (core/access-bonus-count state :runner :rd)) "Runner should access 1 additional card")))) (testing "Knobkierie interaction (Issue #5748) - Conduit before Knobkierie" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 8)] :hand ["Hedge Fund"]} :runner {:deck ["Conduit" "Knobkierie"] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Conduit") (play-from-hand state :runner "Knobkierie") (let [conduit (get-program state 0) knobkierie (get-hardware state 0)] (card-ability state :runner conduit 0) (is (:run @state) "Run initiated") (run-continue state :access-server) (click-prompt state :runner "Conduit") (click-prompt state :runner "Yes") (click-card state :runner (refresh conduit)) (is (= 0 (core/access-bonus-count state :runner :rd)) "Runner should not access additional cards"))))) (deftest consume ;; Consume - gain virus counter for trashing corp card. click to get 2c per counter. (testing "Trash and cash out" (do-game (new-game {:corp {:deck ["Adonis Campaign"]} :runner {:deck ["Consume"]}}) (play-from-hand state :corp "Adonis Campaign" "New remote") (take-credits state :corp) (play-from-hand state :runner "Consume") (let [c (get-program state 0)] (is (zero? (get-counters (refresh c) :virus)) "Consume starts with no counters") (run-empty-server state "Server 1") (click-prompt state :runner "Pay 3 [Credits] to trash") (click-prompt state :runner "Yes") (is (= 1 (count (:discard (get-corp)))) "Adonis Campaign trashed") (is (= 1 (get-counters (refresh c) :virus)) "Consume gains a counter") (is (zero? (:credit (get-runner))) "Runner starts with no credits") (card-ability state :runner c 0) (is (= 2 (:credit (get-runner))) "Runner gains 2 credits") (is (zero? (get-counters (refresh c) :virus)) "Consume loses counters")))) (testing "Hivemind interaction" (do-game (new-game {:corp {:deck ["Adonis Campaign"]} :runner {:deck ["Consume" "Hivemind"]}}) (play-from-hand state :corp "Adonis Campaign" "New remote") (take-credits state :corp) (core/gain state :runner :credit 3) (play-from-hand state :runner "Consume") (play-from-hand state :runner "Hivemind") (let [c (get-program state 0) h (get-program state 1)] (is (zero? (get-counters (refresh c) :virus)) "Consume starts with no counters") (is (= 1 (get-counters (refresh h) :virus)) "Hivemind starts with a counter") (run-empty-server state "Server 1") (click-prompt state :runner "Pay 3 [Credits] to trash") (click-prompt state :runner "Yes") (is (= 1 (count (:discard (get-corp)))) "Adonis Campaign trashed") (is (= 1 (get-counters (refresh c) :virus)) "Consume gains a counter") (is (= 1 (get-counters (refresh h) :virus)) "Hivemind retains counter") (is (zero? (:credit (get-runner))) "Runner starts with no credits") (card-ability state :runner c 0) (is (= 4 (:credit (get-runner))) "Runner gains 4 credits") (is (zero? (get-counters (refresh c) :virus)) "Consume loses counters") (is (zero? (get-counters (refresh h) :virus)) "Hivemind loses counters")))) (testing "Hivemind counters only" (do-game (new-game {:runner {:deck ["Consume" "Hivemind"]}}) (take-credits state :corp) (play-from-hand state :runner "Consume") (play-from-hand state :runner "Hivemind") (let [c (get-program state 0) h (get-program state 1)] (is (zero? (get-counters (refresh c) :virus)) "Consume starts with no counters") (is (= 1 (get-counters (refresh h) :virus)) "Hivemind starts with a counter") (is (zero? (:credit (get-runner))) "Runner starts with no credits") (card-ability state :runner c 0) (is (= 2 (:credit (get-runner))) "Runner gains 2 credits") (is (zero? (get-counters (refresh c) :virus)) "Consume loses counters") (is (zero? (get-counters (refresh h) :virus)) "Hivemind loses counters"))))) (deftest cordyceps ;; Cordyceps (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma" "Hedge Fund"]} :runner {:hand ["Cordyceps"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cordyceps") (run-on state "HQ") (let [iw (get-ice state :hq 0) enig (get-ice state :hq 1) cor (get-program state 0)] (is (= 2 (get-counters (refresh cor) :virus)) "Cordyceps was installed with 2 virus tokens") (run-continue state) (run-continue state) (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner (refresh enig)) (click-card state :runner (refresh iw)) (click-prompt state :runner "No action")) (let [iw (get-ice state :hq 1) enig (get-ice state :hq 0) cor (get-program state 0)] (is (= "Ice Wall" (:title iw)) "Ice Wall now outermost ice") (is (= "Enigma" (:title enig)) "Enigma now outermost ice") (is (= 1 (get-counters (refresh cor) :virus)) "Used 1 virus token")) (take-credits state :runner) (take-credits state :corp) (run-on state "R&D") (run-continue state) (click-prompt state :runner "No action") (is (empty? (:prompt (get-runner))) "No prompt on uniced server"))) (testing "No prompt with less than 2 ice installed" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Hedge Fund"]} :runner {:hand ["Cordyceps"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cordyceps") (run-on state "HQ") (run-continue state) (run-continue state) (click-prompt state :runner "No action") (is (empty? (:prompt (get-runner))) "No prompt with only 1 installed ice"))) (testing "No prompt when empty" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma" "Hedge Fund"]} :runner {:hand ["Cordyceps"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cordyceps") (core/add-counter state :runner (get-program state 0) :virus -2) (is (= 0 (get-counters (get-program state 0) :virus)) "Has no virus tokens") (run-on state "HQ") (run-continue state) (run-continue state) (run-continue state) (is (= "You accessed Hedge Fund." (:msg (prompt-map :runner)))) (click-prompt state :runner "No action") (is (empty? (:prompt (get-runner))) "No prompt with no virus counters"))) (testing "Works with Hivemind installed" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma" "Hedge Fund"]} :runner {:hand ["Cordyceps" "Hivemind"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cordyceps") (core/add-counter state :runner (get-program state 0) :virus -2) (play-from-hand state :runner "Hivemind") (run-on state "HQ") (run-continue state) (run-continue state) (run-continue state) (is (= "Use Cordyceps to swap ice?" (:msg (prompt-map :runner)))) (click-prompt state :runner "Yes") (is (= "Select ice protecting this server" (:msg (prompt-map :runner)))) (is (= :select (prompt-type :runner))) (click-card state :runner "Ice Wall") (click-card state :runner "Enigma") (is (= "Select a card with virus counters (0 of 1 virus counters)" (:msg (prompt-map :runner)))) (click-card state :runner "Hivemind") (is (= "Enigma" (:title (get-ice state :hq 0)))) (is (= "Ice Wall" (:title (get-ice state :hq 1)))) (click-prompt state :runner "No action") (is (empty? (:prompt (get-runner))) "No prompt with only 1 installed ice")))) (deftest corroder ;; Corroder (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:credits 15 :hand ["Corroder"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Corroder") (run-on state "HQ") (let [iw (get-ice state :hq 0) cor (get-program state 0)] (rez state :corp iw) (run-continue state) (card-ability state :runner cor 1) (card-ability state :runner cor 0) (click-prompt state :runner "End the run") (is (zero? (count (remove :broken (:subroutines (refresh iw))))) "All subroutines have been broken")))) (deftest cradle ;; Cradle (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["Cradle" (qty "Cache" 100)]}}) (starting-hand state :runner ["Cradle"]) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (core/gain state :runner :credit 100 :click 100) (play-from-hand state :runner "Cradle") (let [cradle (get-program state 0) strength (get-strength (refresh cradle))] (dotimes [n 5] (when (pos? n) (core/draw state :runner n)) (core/fake-checkpoint state) (is (= (- strength n) (get-strength (refresh cradle))) (str "Cradle should lose " n " strength")) (starting-hand state :runner []) (core/fake-checkpoint state) (is (= strength (get-strength (refresh cradle))) (str "Cradle should be back to original strength"))) (click-draw state :runner) (is (= (dec strength) (get-strength (refresh cradle))) "Cradle should lose 1 strength") (play-from-hand state :runner "Cache") (is (= strength (get-strength (refresh cradle))) (str "Cradle should be back to original strength"))))) (deftest crescentus ;; Crescentus should only work on rezzed ice (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["Crescentus" "Corroder"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Corroder") (play-from-hand state :runner "Crescentus") (run-on state "HQ") (let [cor (get-program state 0) cres (get-program state 1) iw (get-ice state :hq 0)] (rez state :corp iw) (run-continue state) (is (rezzed? (refresh iw)) "Ice Wall is now rezzed") (card-ability state :runner cor 0) (click-prompt state :runner "End the run") (card-ability state :runner cres 0) (is (nil? (get-program state 1)) "Crescentus could be used because the ICE is rezzed") (is (not (rezzed? (refresh iw))) "Ice Wall is no longer rezzed")))) (deftest crypsis ;; Crypsis - Loses a virus counter after encountering ice it broke (testing "Breaking a sub spends a virus counter" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Crypsis"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "Archives") (take-credits state :corp) (play-from-hand state :runner "Crypsis") (let [crypsis (get-program state 0)] (card-ability state :runner crypsis 2) (is (= 1 (get-counters (refresh crypsis) :virus)) "Crypsis has 1 virus counter") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (card-ability state :runner (refresh crypsis) 1) ; Match strength (card-ability state :runner (refresh crypsis) 0) ; Break (click-prompt state :runner "End the run") (is (= 1 (get-counters (refresh crypsis) :virus)) "Crypsis has 1 virus counter") (run-continue state) (is (zero? (get-counters (refresh crypsis) :virus)) "Crypsis has 0 virus counters")))) (testing "Inability to remove a virus counter trashes Crypsis" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Crypsis"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "Archives") (take-credits state :corp) (play-from-hand state :runner "Crypsis") (let [crypsis (get-program state 0)] (is (zero? (get-counters (refresh crypsis) :virus)) "Crypsis has 0 virus counters") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (card-ability state :runner (refresh crypsis) 1) ; Match strength (card-ability state :runner (refresh crypsis) 0) ; Break (click-prompt state :runner "End the run") (run-continue state) (is (find-card "Crypsis" (:discard (get-runner))) "Crypsis was trashed")))) (testing "Working with auto-pump-and-break" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Crypsis"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Crypsis") (let [crypsis (get-program state 0) iw (get-ice state :hq 0)] (card-ability state :runner crypsis 2) (is (= 1 (get-counters (refresh crypsis) :virus)) "Crypsis has 1 virus counter") (run-on state "HQ") (rez state :corp (refresh iw)) (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh crypsis)}) (core/continue state :corp nil) (is (= 0 (get-counters (refresh crypsis) :virus)) "Used up virus token on Crypsis"))))) (deftest cyber-cypher (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Macrophage" "Macrophage"] :credits 100} :runner {:hand ["Cyber-Cypher"] :credits 100}}) (play-from-hand state :corp "Macrophage" "R&D") (play-from-hand state :corp "Macrophage" "HQ") (rez state :corp (get-ice state :rd 0)) (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Cyber-Cypher") (click-prompt state :runner "HQ") (let [cc (get-program state 0)] (run-on state :hq) (run-continue state) (card-ability state :runner cc 1) (card-ability state :runner cc 1) (card-ability state :runner cc 1) (is (= 7 (get-strength (refresh cc))) "Can pump Cyber-Cypher on the right server") (card-ability state :runner cc 0) (click-prompt state :runner "Trace 4 - Purge virus counters") (click-prompt state :runner "Trace 3 - Trash a virus") (click-prompt state :runner "Done") (is (= 2 (count (filter :broken (:subroutines (get-ice state :hq 0))))) "Can break subs on the right server") (run-jack-out state)) (let [cc (get-program state 0)] (run-on state :rd) (run-continue state) (card-ability state :runner cc 1) (is (= 4 (get-strength (refresh cc))) "Can't pump Cyber-Cyper on a different server") (core/update! state :runner (assoc (refresh cc) :current-strength 7)) (is (= 7 (get-strength (refresh cc))) "Manually set equal strength") (card-ability state :runner cc 0) (is (empty? (:prompt (get-runner))) "Can't break subs on a different server") (is (zero? (count (filter :broken (:subroutines (get-ice state :rd 0))))) "No subs are broken")))) (deftest d4v1d ;; D4v1d (testing "Can break 5+ strength ice" (do-game (new-game {:corp {:deck ["Ice Wall" "Hadrian's Wall"]} :runner {:deck ["D4v1d"]}}) (core/gain state :corp :credit 10) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Hadrian's Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "D4v1d") (let [had (get-ice state :hq 1) iw (get-ice state :hq 0) d4 (get-program state 0)] (is (= 3 (get-counters d4 :power)) "D4v1d installed with 3 power tokens") (run-on state :hq) (rez state :corp had) (run-continue state) (card-ability state :runner d4 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (is (= 1 (get-counters (refresh d4) :power)) "Used 2 power tokens from D4v1d to break") (run-continue state) (rez state :corp iw) (run-continue state) (card-ability state :runner d4 0) (is (empty? (:prompt (get-runner))) "No prompt for breaking 1 strength Ice Wall"))))) (deftest dai-v ;; Dai V (testing "Basic test" (do-game (new-game {:corp {:deck ["Enigma"]} :runner {:deck [(qty "Cloak" 2) "Dai V"]}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Cloak") (play-from-hand state :runner "Cloak") (play-from-hand state :runner "D<NAME>") (run-on state :hq) (let [enig (get-ice state :hq 0) cl1 (get-program state 0) cl2 (get-program state 1) daiv (get-program state 2)] (rez state :corp enig) (run-continue state) (changes-val-macro -1 (:credit (get-runner)) "Used 1 credit to pump and 2 credits from Cloaks to break" (card-ability state :runner daiv 1) (click-prompt state :runner "Done") (card-ability state :runner daiv 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (click-card state :runner cl1) (click-card state :runner cl2)))))) (deftest darwin ;; Darwin - starts at 0 strength (do-game (new-game {:runner {:deck ["Darwin"]}}) (take-credits state :corp) (play-from-hand state :runner "Darwin") (let [darwin (get-program state 0)] (is (zero? (get-counters (refresh darwin) :virus)) "Darwin starts with 0 virus counters") (is (zero? (get-strength (refresh darwin))) "Darwin starts at 0 strength") (take-credits state :runner) (take-credits state :corp) (card-ability state :runner (refresh darwin) 1) ; add counter (is (= 1 (get-counters (refresh darwin) :virus)) "Darwin gains 1 virus counter") (is (= 1 (get-strength (refresh darwin))) "Darwin is at 1 strength")))) (deftest datasucker ;; Datasucker - Reduce strength of encountered ICE (testing "Basic test" (do-game (new-game {:corp {:deck ["Fire Wall"]} :runner {:deck ["Datasucker"]}}) (play-from-hand state :corp "Fire Wall" "New remote") (take-credits state :corp) (core/gain state :runner :click 3) (play-from-hand state :runner "Datasucker") (let [ds (get-program state 0) fw (get-ice state :remote1 0)] (run-empty-server state "Archives") (is (= 1 (get-counters (refresh ds) :virus))) (run-empty-server state "Archives") (is (= 2 (get-counters (refresh ds) :virus))) (run-on state "Server 1") (run-continue state) (run-continue state) (is (= 2 (get-counters (refresh ds) :virus)) "No counter gained, not a central server") (run-on state "Server 1") (rez state :corp fw) (run-continue state) (is (= 5 (get-strength (refresh fw)))) (card-ability state :runner ds 0) (is (= 1 (get-counters (refresh ds) :virus)) "1 counter spent from Datasucker") (is (= 4 (get-strength (refresh fw))) "Fire Wall strength lowered by 1")))) (testing "does not affect next ice when current is trashed. Issue #1788" (do-game (new-game {:corp {:deck ["Wraparound" "Spiderweb"]} :runner {:deck ["Datasucker" "Parasite"]}}) (play-from-hand state :corp "Wraparound" "HQ") (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (core/gain state :corp :credit 10) (play-from-hand state :runner "Datasucker") (let [sucker (get-program state 0) wrap (get-ice state :hq 0) spider (get-ice state :hq 1)] (core/add-counter state :runner sucker :virus 2) (rez state :corp spider) (rez state :corp wrap) (play-from-hand state :runner "Parasite") (click-card state :runner "Spiderweb") (run-on state "HQ") (run-continue state) (card-ability state :runner (refresh sucker) 0) (card-ability state :runner (refresh sucker) 0) (is (find-card "Spiderweb" (:discard (get-corp))) "Spiderweb trashed by Parasite + Datasucker") (is (= 7 (get-strength (refresh wrap))) "Wraparound not reduced by Datasucker"))))) (deftest davinci ;; DaVinci (testing "Gain 1 counter on successful run" (do-game (new-game {:runner {:hand ["DaVinci"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (run-on state "HQ") (changes-val-macro 1 (get-counters (get-program state 0) :power) "DaVinci gains 1 counter on successful run" (run-continue state)))) (testing "Gain no counters on unsuccessful run" (do-game (new-game {:runner {:hand ["DaVinci"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (run-on state "HQ") (run-continue state) (changes-val-macro 0 (get-counters (get-program state 0) :power) "DaVinci does not gain counter on unsuccessful run" (run-jack-out state)))) (testing "Install a card with install cost lower than number of counters" (do-game (new-game {:runner {:hand ["Da<NAME>inci" "The Turning Wheel"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (let [davinci (get-program state 0)] (core/add-counter state :runner davinci :power 2) (changes-val-macro 0 (:credit (get-runner)) "DaVinci installs The Turning Wheel for free" (card-ability state :runner (refresh davinci) 0) (click-card state :runner "The Turning Wheel")) (is (get-resource state 0) "The Turning Wheel is installed") (is (find-card "DaVinci" (:discard (get-runner))) "DaVinci is trashed")))) (testing "Using ability should trigger trash effects first. Issue #4987" (do-game (new-game {:runner {:id "<NAME> \"Ge<NAME>\" Walker: Tech Lord" :deck ["Simulchip"] :hand ["DaVinci" "The Turning Wheel"]}}) (take-credits state :corp) (play-from-hand state :runner "DaVinci") (let [davinci (get-program state 0)] (core/add-counter state :runner davinci :power 2) (changes-val-macro 0 (:credit (get-runner)) "DaVinci installs Simulchip for free" (card-ability state :runner (refresh davinci) 0) (click-card state :runner "Simulchip")) (is (get-hardware state 0) "Simulchip is installed") (is (find-card "DaVinci" (:discard (get-runner))) "DaVinci is trashed"))))) (deftest demara ;; Demara (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Demara"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Demara") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 2) (is (= :approach-server (:phase (get-run))) "Run has bypassed Ice Wall") (is (find-card "Demara" (:discard (get-runner))) "Demara is trashed"))) (deftest deus-x (testing "vs Multiple Hostile Infrastructure" (do-game (new-game {:corp {:deck [(qty "Hostile Infrastructure" 3)]} :runner {:deck [(qty "Deus X" 3) (qty "Sure Gamble" 2)]}}) (play-from-hand state :corp "Hostile Infrastructure" "New remote") (play-from-hand state :corp "Hostile Infrastructure" "New remote") (play-from-hand state :corp "Hostile Infrastructure" "New remote") (core/gain state :corp :credit 10) (rez state :corp (get-content state :remote1 0)) (rez state :corp (get-content state :remote2 0)) (rez state :corp (get-content state :remote3 0)) (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Deus X") (run-empty-server state "Server 1") (click-prompt state :runner "Pay 5 [Credits] to trash") (let [dx (get-program state 0)] (card-ability state :runner dx 1) (is (= 2 (count (:hand (get-runner)))) "Deus X prevented one Hostile net damage")))) (testing "vs Multiple sources of net damage" (do-game (new-game {:corp {:id "Jinteki: Personal Evolution" :deck [(qty "Fetal AI" 6)]} :runner {:deck [(qty "Deus X" 3) (qty "Sure Gamble" 2)]}}) (play-from-hand state :corp "Fetal AI" "New remote") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Deus X") (run-empty-server state "Server 1") (let [dx (get-program state 0)] (card-ability state :runner dx 1) (click-prompt state :runner "Pay to steal") (is (= 3 (count (:hand (get-runner)))) "Deus X prevented net damage from accessing Fetal AI, but not from Personal Evolution") (is (= 1 (count (:scored (get-runner)))) "Fetal AI stolen"))))) (deftest dhegdheer ;; <NAME> - hosting a breaker with strength based on unused MU should calculate correctly (testing "with credit savings" (do-game (new-game {:runner {:deck ["<NAME>dept" "<NAME>"]}}) (take-credits state :corp) (core/gain state :runner :credit 5) (play-from-hand state :runner "<NAME>") (play-from-hand state :runner "<NAME>dept") (is (= 3 (:credit (get-runner))) "3 credits left after individual installs") (is (= 2 (core/available-mu state)) "2 MU used") (let [dheg (get-program state 0) adpt (get-program state 1)] (is (= 4 (get-strength (refresh adpt))) "Adept at 4 strength individually") (card-ability state :runner dheg 1) (click-card state :runner (refresh adpt)) (let [hosted-adpt (first (:hosted (refresh dheg)))] (is (= 4 (:credit (get-runner))) "4 credits left after hosting") (is (= 4 (core/available-mu state)) "0 MU used") (is (= 6 (get-strength (refresh hosted-adpt))) "Adept at 6 strength hosted"))))) (testing "without credit savings" (do-game (new-game {:runner {:deck ["<NAME>dept" "<NAME>"]}}) (take-credits state :corp) (core/gain state :runner :credit 5) (play-from-hand state :runner "<NAME>") (play-from-hand state :runner "Adept") (is (= 3 (:credit (get-runner))) "3 credits left after individual installs") (is (= 2 (core/available-mu state)) "2 MU used") (let [dheg (get-program state 0) adpt (get-program state 1)] (is (= 4 (get-strength (refresh adpt))) "Adept at 4 strength individually") (card-ability state :runner dheg 2) (click-card state :runner (refresh adpt)) (let [hosted-adpt (first (:hosted (refresh dheg)))] (is (= 3 (:credit (get-runner))) "4 credits left after hosting") (is (= 4 (core/available-mu state)) "0 MU used") (is (= 6 (get-strength (refresh hosted-adpt))) "Adept at 6 strength hosted")))))) (deftest disrupter ;; Disrupter (do-game (new-game {:corp {:deck [(qty "SEA Source" 2)]} :runner {:deck ["Disrupter"]}}) (take-credits state :corp) (run-empty-server state "Archives") (play-from-hand state :runner "Disrupter") (take-credits state :runner) (play-from-hand state :corp "SEA Source") (click-prompt state :runner "Yes") (is (zero? (:base (prompt-map :corp))) "Base trace should now be 0") (is (= 1 (-> (get-runner) :discard count)) "Disrupter should be in Heap") (click-prompt state :corp "0") (click-prompt state :runner "0") (is (zero? (count-tags state)) "Runner should gain no tag from beating trace") (play-from-hand state :corp "SEA Source") (is (= 3 (:base (prompt-map :corp))) "Base trace should be reset to 3"))) (deftest diwan ;; Diwan - Full test (do-game (new-game {:corp {:deck [(qty "Ice Wall" 3) (qty "Fire Wall" 3) (qty "Crisium Grid" 2)]} :runner {:deck ["Diwan"]}}) (take-credits state :corp) (play-from-hand state :runner "Diwan") (click-prompt state :runner "HQ") (take-credits state :runner) (is (= 8 (:credit (get-corp))) "8 credits for corp at start of second turn") (play-from-hand state :corp "Ice Wall" "R&D") (is (= 8 (:credit (get-corp))) "Diwan did not charge extra for install on another server") (play-from-hand state :corp "Ice Wall" "HQ") (is (= 7 (:credit (get-corp))) "Diwan charged 1cr to install ice protecting the named server") (play-from-hand state :corp "Crisium Grid" "HQ") (is (= 7 (:credit (get-corp))) "Diwan didn't charge to install another upgrade in root of HQ") (take-credits state :corp) (take-credits state :runner) (play-from-hand state :corp "Ice Wall" "HQ") (is (= 5 (:credit (get-corp))) "Diwan charged 1cr + 1cr to install a second ice protecting the named server") (core/gain state :corp :click 1) (core/purge state :corp) (play-from-hand state :corp "Fire Wall" "HQ") ; 2cr cost from normal install cost (is (= "Diwan" (-> (get-runner) :discard first :title)) "Diwan was trashed from purge") (is (= 3 (:credit (get-corp))) "No charge for installs after Diwan purged"))) (deftest djinn ;; Djinn (testing "Hosted Chakana does not disable advancing agendas. Issue #750" (do-game (new-game {:corp {:deck ["Priority Requisition"]} :runner {:deck ["Djinn" "Chakana"]}}) (play-from-hand state :corp "Priority Requisition" "New remote") (take-credits state :corp 2) (play-from-hand state :runner "Djinn") (let [djinn (get-program state 0) agenda (get-content state :remote1 0)] (is agenda "Agenda was installed") (card-ability state :runner djinn 1) (click-card state :runner (find-card "Chakana" (:hand (get-runner)))) (let [chak (first (:hosted (refresh djinn)))] (is (= "Chakana" (:title chak)) "Djinn has a hosted Chakana") ;; manually add 3 counters (core/add-counter state :runner (first (:hosted (refresh djinn))) :virus 3) (take-credits state :runner 2) (core/advance state :corp {:card agenda}) (is (= 1 (get-counters (refresh agenda) :advancement)) "Agenda was advanced"))))) (testing "Host a non-icebreaker program" (do-game (new-game {:runner {:deck ["<NAME>" "Chakana"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (is (= 3 (core/available-mu state))) (let [djinn (get-program state 0)] (card-ability state :runner djinn 1) (click-card state :runner (find-card "Chakana" (:hand (get-runner)))) (is (= 3 (core/available-mu state)) "No memory used to host on Djinn") (is (= "Chakana" (:title (first (:hosted (refresh djinn))))) "Djinn has a hosted Chakana") (is (= 1 (:credit (get-runner))) "Full cost to host on Djinn")))) (testing "Tutor a virus program" (do-game (new-game {:runner {:deck ["<NAME>" "Parasite"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (core/move state :runner (find-card "Parasite" (:hand (get-runner))) :deck) (is (zero? (count (:hand (get-runner)))) "No cards in hand after moving Parasite to deck") (let [djinn (get-program state 0)] (card-ability state :runner djinn 0) (click-prompt state :runner (find-card "Parasite" (:deck (get-runner)))) (is (= "Parasite" (:title (first (:hand (get-runner))))) "Djinn moved Parasite to hand") (is (= 2 (:credit (get-runner))) "1cr to use Djinn ability") (is (= 2 (:click (get-runner))) "1click to use Djinn ability"))))) (deftest eater (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 2)]} :runner {:deck [(qty "Eater" 2)]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (core/gain state :runner :credit 100) (play-from-hand state :runner "Eater") (let [eater (get-program state 0) iw (get-ice state :hq 0)] (run-on state "HQ") (rez state :corp (refresh iw)) (run-continue state) (card-ability state :runner eater 0) (click-prompt state :runner "End the run") (run-continue state) (run-continue state) (is (empty? (:prompt (get-runner))) "No prompt for accessing cards")))) (testing "Eater interaction with remote server. Issue #4536" (do-game (new-game {:corp {:deck [(qty "Rototurret" 2) "NGO Front"]} :runner {:deck [(qty "Eater" 2)]}}) (play-from-hand state :corp "NGO Front" "New remote") (play-from-hand state :corp "Rototurret" "Server 1") (take-credits state :corp) (core/gain state :runner :credit 100) (play-from-hand state :runner "Eater") (let [eater (get-program state 0) ngo (get-content state :remote1 0) rt (get-ice state :remote1 0)] (run-on state "Server 1") (rez state :corp (refresh rt)) (run-continue state) (card-ability state :runner eater 0) (click-prompt state :runner "End the run") (click-prompt state :runner "Done") (fire-subs state (refresh rt)) (click-card state :corp eater) (run-continue state) (run-continue state) (is (find-card "Eater" (:discard (get-runner))) "Eater is trashed") (is (empty? (:prompt (get-runner))) "No prompt for accessing cards"))))) (deftest echelon ;; Echelon (before-each [state (new-game {:runner {:hand [(qty "Echelon" 5)] :credits 20} :corp {:deck [(qty "Hedge Fund" 5)] :hand ["Owl"] :credits 20}}) _ (do (play-from-hand state :corp "Owl" "HQ") (take-credits state :corp)) owl (get-ice state :hq 0)] (testing "pump ability" (do-game state (play-from-hand state :runner "<NAME>") (let [echelon (get-program state 0)] (run-on state :hq) (rez state :corp owl) (run-continue state :encounter-ice) (changes-val-macro -3 (:credit (get-runner)) "Pump costs 3" (card-ability state :runner echelon 1)) (changes-val-macro 2 (get-strength (refresh echelon)) "Echelon gains 2 str" (card-ability state :runner echelon 1))))) (testing "break ability" (do-game state (play-from-hand state :runner "<NAME>") (let [echelon (get-program state 0)] (run-on state :hq) (rez state :corp owl) (run-continue state :encounter-ice) (changes-val-macro -1 (:credit (get-runner)) "Break costs 1" (card-ability state :runner echelon 0) (click-prompt state :runner "Add installed program to the top of the Runner's Stack")) (is (empty? (:prompt (get-runner))) "Only breaks 1 sub at a time")))) (testing "Gains str per icebreaker" (do-game state (take-credits state :corp) (play-from-hand state :runner "Echelon") (let [echelon (get-program state 0)] (is (= 1 (get-strength (refresh echelon))) "0 + 1 icebreaker installed") (play-from-hand state :runner "Echelon") (is (= 2 (get-strength (refresh echelon))) "0 + 2 icebreaker installed") (play-from-hand state :runner "Echelon") (is (= 3 (get-strength (refresh echelon))) "0 + 3 icebreaker installed")))))) (deftest egret ;; Egret (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Mother Goddess"]} :runner {:hand [(qty "Egret" 2)]}}) (play-from-hand state :corp "Mother Goddess" "HQ") (rez state :corp (get-ice state :hq 0)) (let [mg (get-ice state :hq 0)] (take-credits state :corp) (play-from-hand state :runner "Egret") (click-card state :runner mg) (is (has-subtype? (refresh mg) "Barrier")) (is (has-subtype? (refresh mg) "Code Gate")) (is (has-subtype? (refresh mg) "Sentry")) (trash state :runner (first (:hosted (refresh mg)))) (is (not (has-subtype? (refresh mg) "Barrier"))) (is (not (has-subtype? (refresh mg) "Code Gate"))) (is (not (has-subtype? (refresh mg) "Sentry")))))) (deftest engolo ;; Engolo (testing "Subtype is removed when Engolo is trashed mid-encounter. Issue #4039" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"]} :runner {:hand ["Engolo"] :credits 10}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (play-from-hand state :runner "Engolo") (let [roto (get-ice state :hq 0) engolo (get-program state 0)] (run-on state :hq) (rez state :corp roto) (run-continue state) (click-prompt state :runner "Yes") (is (has-subtype? (refresh roto) "Code Gate")) (card-subroutine state :corp roto 0) (click-card state :corp engolo) (run-continue state) (is (nil? (refresh engolo)) "Engolo is trashed") (is (not (has-subtype? (refresh roto) "Code Gate")) "Rototurret loses subtype even when Engolo is trashed")))) (testing "Marks eid as :ability #4962" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"]} :runner {:hand ["Engolo" "Trickster Taka"] :credits 20}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (play-from-hand state :runner "Trickster Taka") (core/add-counter state :runner (get-resource state 0) :credit 2) (play-from-hand state :runner "Engolo") (let [roto (get-ice state :hq 0) engolo (get-program state 0)] (run-on state :hq) (rez state :corp roto) (run-continue state) (changes-val-macro 0 (:credit (get-runner)) "Runner spends credits on Taka" (click-prompt state :runner "Yes") (click-card state :runner "Trickster Taka") (click-card state :runner "Trickster Taka")) (is (zero? (get-counters (get-resource state 0) :credit)) "Taka has been used") (run-jack-out state) (is (nil? (get-run))) (is (empty? (:prompt (get-corp)))) (is (empty? (:prompt (get-runner)))))))) (deftest equivocation ;; Equivocation - interactions with other successful-run events. (do-game (new-game {:corp {:deck [(qty "Restructure" 3) (qty "Hedge Fund" 3)]} :runner {:id "Laramy Fisk: Savvy Investor" :deck ["Equivocation" "Desperado"]}}) (starting-hand state :corp ["Hedge Fund"]) (take-credits state :corp) (play-from-hand state :runner "Equivocation") (play-from-hand state :runner "Desperado") (run-empty-server state :rd) (click-prompt state :runner "Laramy Fisk: Savvy Investor") (click-prompt state :runner "Yes") (is (= 2 (count (:hand (get-corp)))) "Corp forced to draw by Fisk") (click-prompt state :runner "Yes") ; Equivocation prompt (click-prompt state :runner "Yes") ; force the draw (is (= 1 (:credit (get-runner))) "Runner gained 1cr from Desperado") (is (= 3 (count (:hand (get-corp)))) "Corp forced to draw by Equivocation") (click-prompt state :runner "No action") (is (not (:run @state)) "Run ended"))) (deftest euler ;; Euler (testing "Basic test" (do-game (new-game {:runner {:hand ["Euler"] :credits 20} :corp {:hand ["Enigma"]}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Euler") (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state) (changes-val-macro 0 (:credit (get-runner)) "Broke Enigma for 0c" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (get-program state 0)}) (core/continue state :corp nil)) (run-jack-out state) (take-credits state :runner) (take-credits state :corp) (run-on state :hq) (run-continue state) (changes-val-macro -2 (:credit (get-runner)) "Broke Enigma for 2c" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (get-program state 0)}) (core/continue state :corp nil)))) (testing "Correct log test" (do-game (new-game {:runner {:hand ["Euler"] :credits 20} :corp {:hand ["Enigma"]}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Euler") (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (get-program state 0)}) (is (second-last-log-contains? state "Runner pays 0 \\[Credits\\] to use Euler to break all 2 subroutines on Enigma.") "Correct log with correct cost") (core/continue state :corp nil) (run-jack-out state) (take-credits state :runner) (take-credits state :corp) (run-on state :hq) (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (get-program state 0)}) (is (second-last-log-contains? state "Runner pays 2 \\[Credits\\] to use Euler to break all 2 subroutines on Enigma.") "Correct second log with correct cost") (core/continue state :corp nil)))) (deftest expert-schedule-analyzer ;; Expert Schedule Analyzer (do-game (new-game {:runner {:deck ["Expert Schedule Analyzer"]}}) (take-credits state :corp) (play-from-hand state :runner "Expert Schedule Analyzer") (card-ability state :runner (get-program state 0) 0) (run-continue state) (is (= "Choose an access replacement ability" (:msg (prompt-map :runner))) "Replacement effect is optional") (click-prompt state :runner "Expert Schedule Analyzer") (is (last-log-contains? state "Runner uses Expert Schedule Analyzer to reveal all of the cards cards in HQ:") "All of HQ is revealed correctly"))) (deftest faerie (testing "Trash after encounter is over, not before" (do-game (new-game {:corp {:deck ["<NAME>"]} :runner {:deck ["<NAME>"]}}) (play-from-hand state :corp "<NAME>" "Archives") (take-credits state :corp) (play-from-hand state :runner "<NAME>") (let [fae (get-program state 0)] (run-on state :archives) (rez state :corp (get-ice state :archives 0)) (run-continue state) (card-ability state :runner fae 1) (card-ability state :runner fae 0) (click-prompt state :runner "Trace 3 - Gain 3 [Credits]") (click-prompt state :runner "Trace 2 - End the run") (is (refresh fae) "Faerie not trashed until encounter over") (run-continue state) (is (find-card "<NAME>" (:discard (get-runner))) "Faerie trashed")))) (testing "Works with auto-pump-and-break" (do-game (new-game {:corp {:deck ["<NAME>"]} :runner {:deck ["<NAME>"]}}) (play-from-hand state :corp "<NAME>" "Archives") (take-credits state :corp) (play-from-hand state :runner "Faerie") (let [fae (get-program state 0)] (run-on state :archives) (rez state :corp (get-ice state :archives 0)) (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh fae)}) (core/continue state :corp nil) (is (find-card "Faerie" (:discard (get-runner))) "Faerie trashed"))))) (deftest false-echo ;; False Echo - choice for Corp (testing "Add to HQ" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["False Echo"]}}) (play-from-hand state :corp "Ice Wall" "Archives") (take-credits state :corp) (play-from-hand state :runner "False Echo") (run-on state "Archives") (run-continue state) (click-prompt state :runner "Yes") (click-prompt state :corp "Add to HQ") (is (find-card "Ice Wall" (:hand (get-corp))) "Ice Wall added to HQ") (is (find-card "False Echo" (:discard (get-runner))) "False Echo trashed"))) (testing "Rez" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["False Echo"]}}) (play-from-hand state :corp "Ice Wall" "Archives") (take-credits state :corp) (play-from-hand state :runner "False Echo") (run-on state "Archives") (run-continue state) (click-prompt state :runner "Yes") (click-prompt state :corp "Rez") (is (rezzed? (get-ice state :archives 0)) "Ice Wall rezzed") (is (find-card "False Echo" (:discard (get-runner))) "False Echo trashed")))) (deftest faust (testing "Basic test: Break by discarding" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:deck ["Faust" "Sure Gamble"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Faust") (let [faust (get-program state 0)] (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner faust 0) (click-prompt state :runner "End the run") (click-card state :runner "Sure Gamble") (is (= 1 (count (:discard (get-runner)))) "1 card trashed")))) (testing "Basic test: Pump by discarding" (do-game (new-game {:runner {:deck ["Faust" "Sure Gamble"]}}) (take-credits state :corp) (play-from-hand state :runner "Faust") (let [faust (get-program state 0)] (card-ability state :runner faust 1) (click-card state :runner "Sure Gamble") (is (= 4 (get-strength (refresh faust))) "4 current strength") (is (= 1 (count (:discard (get-runner)))) "1 card trashed")))) (testing "Pump does not trigger trash prevention. #760" (do-game (new-game {:runner {:hand ["Faust" "Sacrificial Construct" "Fall Guy" "Astrolabe" "Gordian Blade" "Armitage Codebusting"]}}) (take-credits state :corp) (play-from-hand state :runner "Faust") (play-from-hand state :runner "Fall Guy") (play-from-hand state :runner "Sacrificial Construct") (is (= 2 (count (get-resource state))) "Resources installed") (let [faust (get-program state 0)] (card-ability state :runner faust 1) (click-card state :runner "Astrolabe") (is (empty? (:prompt (get-runner))) "No trash-prevention prompt for hardware") (card-ability state :runner faust 1) (click-card state :runner "<NAME>") (is (empty? (:prompt (get-runner))) "No trash-prevention prompt for program") (card-ability state :runner faust 1) (click-card state :runner "Armitage Codebusting") (is (empty? (:prompt (get-runner))) "No trash-prevention prompt for resource"))))) (deftest femme-fatale ;; Femme Fatale (testing "Bypass functionality" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Femme Fatale"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (let [iw (get-ice state :hq 0)] (play-from-hand state :runner "Femme Fatale") (click-card state :runner iw) (run-on state "HQ") (rez state :corp iw) (run-continue state) (is (= "Pay 1 [Credits] to bypass Ice Wall?" (:msg (prompt-map :runner)))) (click-prompt state :runner "Yes") (is (= :approach-server (:phase (get-run))) "Femme Fatale has bypassed Ice Wall")))) (testing "Bypass leaves if uninstalled" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Femme Fatale"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (let [iw (get-ice state :hq 0)] (play-from-hand state :runner "Femme Fatale") (click-card state :runner iw) (core/move state :runner (get-program state 0) :deck) (run-on state "HQ") (rez state :corp iw) (run-continue state) (is (nil? (prompt-map :runner)) "Femme ability doesn't fire after uninstall")))) (testing "Bypass doesn't persist if ice is uninstalled and reinstalled" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["<NAME>me Fatale"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Femme Fatale") (click-card state :runner (get-ice state :hq 0)) (core/move state :corp (get-ice state :hq 0) :hand) (take-credits state :runner) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (is (nil? (prompt-map :runner)) "Femme ability doesn't fire after uninstall")))) (deftest fermenter ;; Fermenter - click, trash to get 2c per counter. (testing "Trash and cash out" (do-game (new-game {:runner {:deck ["Fermenter"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (let [fermenter (get-program state 0)] (is (= 1 (get-counters (refresh fermenter) :virus)) "Fermenter has 1 counter from install") (take-credits state :runner) (take-credits state :corp) (is (= 2 (get-counters (refresh fermenter) :virus)) "Fermenter has 2 counters") (changes-val-macro 4 (:credit (get-runner)) "Gain 4 credits from Fermenter ability" (card-ability state :runner fermenter 0)) (is (= 1 (count (:discard (get-runner)))) "Fermenter is trashed")))) (testing "Hivemind interaction" (do-game (new-game {:corp {:deck ["<NAME>"]} :runner {:deck ["<NAME>" "<NAME>"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (play-from-hand state :runner "<NAME>") (take-credits state :runner) (take-credits state :corp) (let [fermenter (get-program state 0) hivemind (get-program state 1)] (is (= 2 (get-counters (refresh fermenter) :virus)) "Fermenter has 2 counters") (is (= 1 (get-counters (refresh hivemind) :virus)) "Hivemind has 1 counter") (changes-val-macro 6 (:credit (get-runner)) "Gain 6 credits from Fermenter ability" (card-ability state :runner fermenter 0)) (is (= 1 (count (:discard (get-runner)))) "Fermenter is trashed") (is (= 1 (get-counters (refresh hivemind) :virus)) "Hivemind has still 1 counter"))))) (deftest gauss ;; Gauss (testing "Loses strength at end of Runner's turn" (do-game (new-game {:runner {:deck ["<NAME>"]} :options {:start-as :runner}}) (play-from-hand state :runner "<NAME>") (let [gauss (get-program state 0)] (is (= 4 (get-strength (refresh gauss))) "+3 base strength") (run-on state :hq) (card-ability state :runner (refresh gauss) 1) ;; boost (is (= 6 (get-strength (refresh gauss))) "+3 base and boosted strength") (run-jack-out state) (is (= 4 (get-strength (refresh gauss))) "Boost lost after run") (take-credits state :runner) (is (= 1 (get-strength (refresh gauss))) "Back to normal strength")))) (testing "Loses strength at end of Corp's turn" (do-game (new-game {:runner {:deck ["Gauss"]}}) (core/gain state :runner :click 1) (play-from-hand state :runner "Gauss") (let [gauss (get-program state 0)] (is (= 4 (get-strength (refresh gauss))) "+3 base strength") (take-credits state :corp) (is (= 1 (get-strength (refresh gauss))) "Back to normal strength"))))) (deftest god-of-war ;; God of War - Take 1 tag to place 2 virus counters (do-game (new-game {:runner {:deck ["God of War"]}}) (take-credits state :corp) (play-from-hand state :runner "God of War") (take-credits state :runner) (take-credits state :corp) (let [gow (get-program state 0)] (card-ability state :runner gow 2) (is (= 1 (count-tags state))) (is (= 2 (get-counters (refresh gow) :virus)) "God of War has 2 virus counters")))) (deftest grappling-hook ;; Grappling Hook (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Little Engine"] :credits 10} :runner {:hand [(qty "Grappling Hook" 2) "Corroder" "Torch"] :credits 100}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Little Engine" "New remote") (take-credits state :corp) (core/gain state :runner :click 10) (play-from-hand state :runner "Grappling Hook") (play-from-hand state :runner "Grappling Hook") (play-from-hand state :runner "Corroder") (play-from-hand state :runner "Torch") (let [iw (get-ice state :hq 0) le (get-ice state :remote1 0) gh1 (get-program state 0) gh2 (get-program state 1) cor (get-program state 2) torch (get-program state 3)] (run-on state :hq) (rez state :corp iw) (run-continue state) (card-ability state :runner gh1 0) (is (empty? (:prompt (get-runner))) "No break prompt as Ice Wall only has 1 subroutine") (is (refresh gh1) "Grappling Hook isn't trashed") (card-ability state :runner cor 0) (click-prompt state :runner "End the run") (card-ability state :runner gh1 0) (is (empty? (:prompt (get-runner))) "No break prompt as Ice Wall has no unbroken subroutines") (is (refresh gh1) "Grappling Hook isn't trashed") (run-jack-out state) (run-on state :remote1) (rez state :corp le) (run-continue state) (card-ability state :runner gh1 0) (is (seq (:prompt (get-runner))) "Grappling Hook creates break prompt") (click-prompt state :runner "End the run") (is (= 2 (count (filter :broken (:subroutines (refresh le))))) "Little Engine has 2 of 3 subroutines broken") (is (nil? (refresh gh1)) "Grappling Hook is now trashed") (run-jack-out state) (run-on state :remote1) (run-continue state) (core/update! state :runner (assoc (refresh torch) :current-strength 7)) (card-ability state :runner torch 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (click-prompt state :runner "Done") (card-ability state :runner gh2 0) (is (empty? (:prompt (get-runner))) "No break prompt as Little Engine has more than 1 broken sub") (is (refresh gh2) "Grappling Hook isn't trashed")))) (testing "Interaction with Fairchild 3.0" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Fairchild 3.0"] :credits 6} :runner {:hand ["Grappling Hook"] }}) (play-from-hand state :corp "Fairchild 3.0" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Grappling Hook") (run-on state "HQ") (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "Do 1 brain damage or end the run") (is (= 1 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broke all but one subroutine") (is (= "Do 1 brain damage or end the run" (:label (first (remove :broken (:subroutines (get-ice state :hq 0)))))) "Broke all but selected sub") (is (nil? (refresh (get-program state 0))) "Grappling Hook is now trashed"))) (testing "interaction with News Hound #4988" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["News Hound" "Surveillance Sweep"] :credits 10} :runner {:hand ["Grappling Hook"] :credits 100}}) (play-from-hand state :corp "News Hound" "HQ") (play-from-hand state :corp "Surveillance Sweep") (take-credits state :corp) (play-from-hand state :runner "Grappling Hook") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "Trace 3 - Give the Runner 1 tag") (fire-subs state (get-ice state :hq 0)) (click-prompt state :runner "10") (click-prompt state :corp "1") (is (zero? (count-tags state)) "Runner gained no tags") (is (get-run) "Run hasn't ended") (is (empty? (:prompt (get-corp))) "Corp shouldn't have a prompt") (is (empty? (:prompt (get-runner))) "Runner shouldn't have a prompt"))) (testing "Selecting a sub when multiple of the same title exist #5291" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Hive"] :credits 10} :runner {:hand ["Grappling Hook" "Gbahali"] :credits 10}}) (play-from-hand state :corp "Hive" "HQ") (take-credits state :corp) (play-from-hand state :runner "Grappling Hook") (play-from-hand state :runner "Gbahali") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) "Break all but 1 subroutine") (click-prompt state :runner "End the run" {:idx 4}) (card-ability state :runner (get-resource state 0) "Break the last subroutine") (is (core/all-subs-broken? (get-ice state :hq 0)) "Grappling Hook and Gbahali worked together")))) (deftest gravedigger ;; Gravedigger - Gain counters when Corp cards are trashed, spend click-counter to mill Corp (do-game (new-game {:corp {:deck [(qty "Launch Campaign" 2) (qty "Enigma" 2)]} :runner {:deck ["Gravedigger"]}}) (play-from-hand state :corp "Launch Campaign" "New remote") (play-from-hand state :corp "Launch Campaign" "New remote") (take-credits state :corp) (play-from-hand state :runner "Gravedigger") (let [gd (get-program state 0)] (trash state :corp (get-content state :remote1 0)) (is (= 1 (get-counters (refresh gd) :virus)) "Gravedigger gained 1 counter") (trash state :corp (get-content state :remote2 0)) (is (= 2 (get-counters (refresh gd) :virus)) "Gravedigger gained 1 counter") (core/move state :corp (find-card "Enigma" (:hand (get-corp))) :deck) (core/move state :corp (find-card "Enigma" (:hand (get-corp))) :deck) (is (= 2 (count (:deck (get-corp))))) (card-ability state :runner gd 0) (is (= 1 (get-counters (refresh gd) :virus)) "Spent 1 counter from Gravedigger") (is (= 2 (:click (get-runner))) "Spent 1 click") (is (= 1 (count (:deck (get-corp))))) (is (= 3 (count (:discard (get-corp)))) "Milled 1 card from R&D")))) (deftest harbinger ;; Harbinger (testing "install facedown when Blacklist installed" (do-game (new-game {:corp {:deck ["Blacklist"]} :runner {:deck ["Harbinger"]}}) (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (get-content state :remote1 0)) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (trash state :runner (-> (get-runner) :rig :program first)) (is (zero? (count (:discard (get-runner)))) "Harbinger not in heap") (is (-> (get-runner) :rig :facedown first :facedown) "Harbinger installed facedown")))) (deftest hyperdriver ;; Hyperdriver - Remove from game to gain 3 clicks (testing "Basic test" (do-game (new-game {:runner {:deck ["Hyperdriver"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>driver") (is (= 1 (core/available-mu state)) "3 MU used") (take-credits state :runner) (take-credits state :corp) (is (:runner-phase-12 @state) "Runner in Step 1.2") (let [hyp (get-program state 0)] (card-ability state :runner hyp 0) (end-phase-12 state :runner) (is (= 7 (:click (get-runner))) "Gained 3 clicks") (is (= 1 (count (:rfg (get-runner)))) "Hyperdriver removed from game")))) (testing "triggering a Dhegdeered Hyperdriver should not grant +3 MU" (do-game (new-game {:runner {:deck ["Hyperdriver" "Dhegdheer"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>gdheer") (let [dheg (get-program state 0)] (card-ability state :runner dheg 0) (click-card state :runner (find-card "Hyperdriver" (:hand (get-runner)))) (is (= 4 (core/available-mu state)) "0 MU used by Hyperdriver hosted on Dhegdheer") (is (= 2 (:click (get-runner))) "2 clicks used") (is (= 3 (:credit (get-runner))) "2 credits used") (take-credits state :runner) (take-credits state :corp) (is (:runner-phase-12 @state) "Runner in Step 1.2") (let [hyp (first (:hosted (refresh dheg)))] (card-ability state :runner hyp 0) (end-phase-12 state :runner) (is (= 7 (:click (get-runner))) "Used Hyperdriver") (is (= 4 (core/available-mu state)) "Still 0 MU used after Hyperdriver removed from game")))))) (deftest ika ;; Ika (testing "Can be hosted on both rezzed/unrezzed ice, respects no-host, is blanked by Magnet" (do-game (new-game {:corp {:deck ["Tithonium" "Enigma" "Magnet"]} :runner {:deck ["Ika"]}}) (play-from-hand state :corp "Enigma" "HQ") (play-from-hand state :corp "Tithonium" "Archives") (play-from-hand state :corp "Magnet" "R&D") (take-credits state :corp) (play-from-hand state :runner "Ika") (core/gain state :runner :credit 100) (core/gain state :corp :credit 100) (let [ika (get-program state 0) enigma (get-ice state :hq 0) tithonium (get-ice state :archives 0) magnet (get-ice state :rd 0)] (let [creds (:credit (get-runner))] (card-ability state :runner ika 0) ; host on a piece of ice (click-card state :runner tithonium) (is (utils/same-card? ika (first (:hosted (refresh tithonium)))) "Ika was rehosted") (is (= (- creds 2) (:credit (get-runner))) "Rehosting from rig cost 2 creds")) (run-on state :archives) (run-continue state) (let [creds (:credit (get-runner)) ika (first (:hosted (refresh tithonium)))] (card-ability state :runner ika 0) (click-card state :runner enigma) (is (utils/same-card? ika (first (:hosted (refresh enigma)))) "Ika was rehosted") (is (= (- creds 2) (:credit (get-runner))) "Rehosting from ice during run cost 2 creds")) (rez state :corp tithonium) (let [creds (:credit (get-runner)) ika (first (:hosted (refresh enigma)))] (card-ability state :runner ika 0) (click-card state :runner tithonium) (is (zero?(count (:hosted (refresh tithonium)))) "Ika was not hosted on Tithonium") (is (= creds (:credit (get-runner))) "Clicking invalid targets is free") (click-prompt state :runner "Done") (rez state :corp magnet) (click-card state :corp ika) (is (zero?(count (:hosted (refresh enigma)))) "Ika was removed from Enigma") (is (= 1 (count (:hosted (refresh magnet)))) "Ika was hosted onto Magnet") (let [ika (first (:hosted (refresh magnet)))] (is (zero?(count (:abilities ika))) "Ika was blanked"))))))) (deftest imp ;; Imp (testing "Full test" (letfn [(imp-test [card] (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand [card]} :runner {:deck ["Imp"]}}) (take-credits state :corp) (play-from-hand state :runner "Imp") (run-empty-server state "HQ") (click-prompt state :runner "[Imp] Hosted virus counter: Trash card") (is (= 1 (count (:discard (get-corp)))))))] (doall (map imp-test ["Hostile Takeover" "Dedicated Response Team" "Beanstalk Royalties" "Ice Wall" "Oberth Protocol"])))) (testing "vs an ambush" (do-game (new-game {:corp {:deck ["Prisec"]} :runner {:deck ["Imp" (qty "Sure Gamble" 3)]}}) (play-from-hand state :corp "Prisec" "New remote") (take-credits state :corp) (let [credits (:credit (get-corp)) tags (count-tags state) grip (count (:hand (get-runner))) archives (count (:discard (get-corp)))] (play-from-hand state :runner "Imp") (run-empty-server state :remote1) (click-prompt state :corp "Yes") (click-prompt state :runner "[Imp] Hosted virus counter: Trash card") (is (= 2 (- credits (:credit (get-corp)))) "Corp paid 2 for Prisec") (is (= 1 (- (count-tags state) tags)) "Runner has 1 tag") (is (= 2 (- grip (count (:hand (get-runner))))) "Runner took 1 meat damage") (is (= 1 (- (count (:discard (get-corp))) archives)) "Used Imp to trash Prisec")))) (testing "vs The Future Perfect" ;; Psi-game happens on access [5.5.1], Imp is a trash ability [5.5.2] (do-game (new-game {:corp {:deck ["The Future Perfect"]} :runner {:deck ["Imp"]}}) (take-credits state :corp) (play-from-hand state :runner "Imp") (testing "Access, corp wins psi-game" (run-empty-server state "HQ") ;; Should access TFP at this point (click-prompt state :corp "1 [Credits]") (click-prompt state :runner "0 [Credits]") (click-prompt state :runner "[Imp] Hosted virus counter: Trash card") (take-credits state :runner) (is (= "The Future Perfect" (get-in @state [:corp :discard 0 :title])) "TFP trashed") (is (zero? (:agenda-point (get-runner))) "Runner did not steal TFP") (core/move state :corp (find-card "The Future Perfect" (:discard (get-corp))) :hand)) (take-credits state :runner) (take-credits state :corp) (testing "Access, runner wins psi-game" (run-empty-server state "HQ") ;; Access prompt for TFP (click-prompt state :corp "0 [Credits]") (click-prompt state :runner "0 [Credits]") ;; Fail psi game (click-prompt state :runner "[Imp] Hosted virus counter: Trash card") (is (= "The Future Perfect" (get-in @state [:corp :discard 0 :title])) "TFP trashed") (is (zero? (:agenda-point (get-runner))) "Runner did not steal TFP")))) (testing "vs cards in Archives" (do-game (new-game {:corp {:deck ["Hostile Takeover"]} :runner {:deck ["Imp"]}}) (core/move state :corp (find-card "Hostile Takeover" (:hand (get-corp))) :discard) (take-credits state :corp) (play-from-hand state :runner "Imp") (run-empty-server state "Archives") (is (= ["Steal"] (prompt-buttons :runner)) "Should only get the option to steal Hostile on access in Archives"))) (testing "Hivemind installed #5000" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:deck ["Imp" "Hivemind"]}}) (take-credits state :corp) (play-from-hand state :runner "Hivemind") (is (= 1 (get-counters (get-program state 0) :virus))) (play-from-hand state :runner "Imp") (core/add-counter state :runner (get-program state 1) :virus -2) (is (= 0 (get-counters (get-program state 1) :virus))) (run-empty-server state "HQ") (click-prompt state :runner "[Imp] Hosted virus counter: Trash card") (click-card state :runner "Hivemind") (is (= 1 (count (:discard (get-corp))))) (is (= 0 (get-counters (get-program state 0) :virus))))) (testing "can't be used when empty #5190" (do-game (new-game {:corp {:hand ["Hostile Takeover"]} :runner {:hand ["Imp" "Cache"]}}) (take-credits state :corp) (play-from-hand state :runner "Cache") (play-from-hand state :runner "Imp") (core/update! state :runner (assoc-in (get-program state 1) [:counter :virus] 0)) (run-empty-server state "HQ") (is (= ["Steal"] (prompt-buttons :runner)) "Should only get the option to steal Hostile on access in Archives")))) (deftest incubator ;; Incubator - Gain 1 virus counter per turn; trash to move them to an installed virus program (do-game (new-game {:runner {:deck ["Incubator" "Datasucker"]}}) (take-credits state :corp) (play-from-hand state :runner "Datasucker") (play-from-hand state :runner "Incubator") (take-credits state :runner) (take-credits state :corp) (let [ds (get-program state 0) incub (get-program state 1)] (is (= 1 (get-counters (refresh incub) :virus)) "Incubator gained 1 virus counter") (take-credits state :runner) (take-credits state :corp) (is (= 2 (get-counters (refresh incub) :virus)) "Incubator has 2 virus counters") (card-ability state :runner incub 0) (click-card state :runner ds) (is (= 2 (get-counters (refresh ds) :virus)) "Datasucker has 2 virus counters moved from Incubator") (is (= 1 (count (get-program state)))) (is (= 1 (count (:discard (get-runner)))) "Incubator trashed") (is (= 3 (:click (get-runner))))))) (deftest inversificator ;; Inversificator (testing "Shouldn't hook up events for unrezzed ice" (do-game (new-game {:corp {:deck ["Turing" "Kakugo"]} :runner {:deck ["Inversificator" "Sure Gamble"]}}) (play-from-hand state :corp "Kakugo" "HQ") (play-from-hand state :corp "Turing" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Inversificator") (let [inv (get-program state 0) tur (get-ice state :hq 1)] (is (= 1 (count (:hand (get-runner)))) "Runner starts with 1 card in hand") (run-on state "HQ") (rez state :corp (refresh tur)) (run-continue state) (card-ability state :runner (refresh inv) 0) (click-prompt state :runner "End the run unless the Runner spends [Click][Click][Click]") (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner (get-ice state :hq 1)) (click-card state :runner (get-ice state :hq 0)) (run-jack-out state) (is (= 1 (count (:hand (get-runner)))) "Runner still has 1 card in hand") (run-on state :hq) (run-continue state) (is (= 1 (count (:hand (get-runner)))) "Kakugo doesn't fire when unrezzed")))) (testing "Switched ice resets broken subs. Issue #4857" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand [(qty "Viktor 1.0" 2)] :credits 20} :runner {:hand ["Inversificator"] :credits 20}}) (play-from-hand state :corp "Viktor 1.0" "HQ") (rez state :corp (get-ice state :hq 0)) (play-from-hand state :corp "Viktor 1.0" "New remote") (rez state :corp (get-ice state :remote1 0)) (take-credits state :corp) (play-from-hand state :runner "Inversificator") (run-on state "HQ") (run-continue state) (let [inv (get-program state 0)] (card-ability state :runner (refresh inv) 1) (card-ability state :runner (refresh inv) 0) (click-prompt state :runner "Do 1 brain damage") (click-prompt state :runner "End the run") (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner (get-ice state :hq 0)) (click-card state :runner (get-ice state :remote1 0)) (run-continue state) (is (not-any? :broken (:subroutines (get-ice state :remote1 0))) "None of the subs are marked as broken anymore")))) (testing "Doesn't fire when other programs break an ice. Issue #4858" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand [(qty "Viktor 1.0" 2)] :credits 20} :runner {:hand ["Inversificator" "Maven" "Cache"] :credits 20}}) (play-from-hand state :corp "Viktor 1.0" "HQ") (rez state :corp (get-ice state :hq 0)) (play-from-hand state :corp "Viktor 1.0" "New remote") (rez state :corp (get-ice state :remote1 0)) (take-credits state :corp) (core/gain state :runner :click 10) (play-from-hand state :runner "Cache") (play-from-hand state :runner "Maven") (play-from-hand state :runner "Inversificator") ;; Use Inversificator in another run first (run-on state "Server 1") (run-continue state) (let [maven (get-program state 1) inv (get-program state 2)] (card-ability state :runner (refresh inv) 1) (card-ability state :runner (refresh inv) 0) (click-prompt state :runner "Do 1 brain damage") (click-prompt state :runner "End the run") (run-continue state) (click-prompt state :runner "No") (run-continue state) ;; Use non-Inversificator breaker (run-on state "HQ") (run-continue state) (card-ability state :runner (refresh maven) 0) (click-prompt state :runner "Do 1 brain damage") (click-prompt state :runner "End the run") (run-continue state) (is (not (prompt-is-card? state :runner inv)) "Prompt shouldn't be Inversificator") (is (empty? (:prompt (get-corp))) "Corp shouldn't have a prompt") (is (empty? (:prompt (get-runner))) "Runner shouldn't have a prompt")))) (testing "Inversificator shouldn't fire when ice is unrezzed. Issue #4859" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Viktor 1.0" "Quandary"] :credits 20} :runner {:hand ["Inversificator"] :credits 20}}) (play-from-hand state :corp "Quandary" "HQ") (play-from-hand state :corp "Viktor 1.0" "HQ") (take-credits state :corp) (play-from-hand state :runner "Inversificator") (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (run-continue state) (let [inv (get-program state 0)] (card-ability state :runner (refresh inv) 1) (card-ability state :runner (refresh inv) 0) (click-prompt state :runner "Do 1 brain damage") (click-prompt state :runner "End the run") (run-continue state) (click-prompt state :runner "No") (run-continue state) (run-continue state) (is (not (prompt-is-card? state :runner inv)) "Prompt shouldn't be Inversificator") (is (empty? (:prompt (get-corp))) "Corp shouldn't have a prompt") (is (empty? (:prompt (get-runner))) "Runner shouldn't have a prompt")))) (testing "shouldn't fire ice's on-pass ability #5143" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Kakugo" "Quandary"] :credits 20} :runner {:hand ["Sure Gamble" "Inversificator"] :credits 20}}) (play-from-hand state :corp "Quandary" "HQ") (play-from-hand state :corp "Kakugo" "HQ") (take-credits state :corp) (play-from-hand state :runner "Inversificator") (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (core/register-floating-effect state :corp nil (let [ice (get-ice state :hq 1)] {:type :gain-subtype :req (req (utils/same-card? ice target)) :value "Code Gate"})) (run-continue state) (let [inv (get-program state 0)] (card-ability state :runner (refresh inv) 1) (card-ability state :runner (refresh inv) 0) (click-prompt state :runner "End the run") (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner (get-ice state :hq 1)) (click-card state :runner (get-ice state :hq 0)) (is (= 1 (count (:hand (get-runner)))))))) (testing "Async issue with Thimblerig #5042" (do-game (new-game {:corp {:hand ["Drafter" "Border Control" "Vanilla" "Thimblerig"] :credits 100} :runner {:hand ["Inversificator"] :credits 100}}) (core/gain state :corp :click 1) (play-from-hand state :corp "Border Control" "R&D") (play-from-hand state :corp "Drafter" "R&D") (play-from-hand state :corp "Vanilla" "HQ") (play-from-hand state :corp "Thimblerig" "HQ") (take-credits state :corp) (play-from-hand state :runner "Inversificator") (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "End the run") (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner "Drafter") (is (= ["Border Control" "Thimblerig"] (map :title (get-ice state :rd)))) (is (= ["Vanilla" "Drafter"] (map :title (get-ice state :hq)))) (is (empty? (:prompt (get-corp))) "Corp gets no Thimblerig prompt") (is (empty? (:prompt (get-runner))) "No more prompts open"))) (testing "Swap vs subtype issues #5170" (do-game (new-game {:corp {:hand ["Drafter" "Data Raven" "Vanilla"] :credits 100} :runner {:id "<NAME> \"Kit\" Peddler: <NAME>uman" :hand ["Inversificator" "Hunting Grounds" "Stargate"] :credits 100}}) (play-from-hand state :corp "Data Raven" "R&D") (play-from-hand state :corp "Drafter" "R&D") (play-from-hand state :corp "Vanilla" "Archives") (take-credits state :corp) (play-from-hand state :runner "Inversificator") (play-from-hand state :runner "Hunting Grounds") (play-from-hand state :runner "Stargate") (core/gain state :runner :click 10) (let [inv (get-program state 0) hg (get-resource state 0) sg (get-program state 1)] (card-ability state :runner sg 0) (run-continue state) (rez state :corp (get-ice state :rd 0)) (card-ability state :runner hg 0) (run-continue state) (card-ability state :runner inv 1) (card-ability state :runner inv 1) (card-ability state :runner inv 0) (click-prompt state :runner "Trace 3 - Add 1 power counter") (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner "Vanilla") (is (= ["Vanilla" "Drafter"] (map :title (get-ice state :rd)))) (is (= ["Data Raven"] (map :title (get-ice state :archives)))))))) (deftest ixodidae ;; Ixodidae should not trigger on psi-games (do-game (new-game {:corp {:deck ["Snowflake"]} :runner {:deck ["Ixodidae" "Lamprey"]}}) (play-from-hand state :corp "Snowflake" "HQ") (take-credits state :corp) (is (= 7 (:credit (get-corp))) "Corp at 7 credits") (play-from-hand state :runner "Ixodidae") (play-from-hand state :runner "Lamprey") (is (= 3 (:credit (get-runner))) "Runner paid 3 credits to install Ixodidae and Lamprey") (run-on state :hq) (let [s (get-ice state :hq 0)] (rez state :corp s) (run-continue state) (card-subroutine state :corp s 0) (is (prompt-is-card? state :corp s) "Corp prompt is on Snowflake") (is (prompt-is-card? state :runner s) "Runner prompt is on Snowflake") (is (= 6 (:credit (get-corp))) "Corp paid 1 credit to rezz Snowflake") (click-prompt state :corp "1 [Credits]") (click-prompt state :runner "1 [Credits]") (is (= 5 (:credit (get-corp))) "Corp paid 1 credit to psi game") (is (= 2 (:credit (get-runner))) "Runner did not gain 1 credit from Ixodidae when corp spent on psi game") (run-continue state) (run-continue state) (is (= 4 (:credit (get-corp))) "Corp lost 1 credit to Lamprey") (is (= 3 (:credit (get-runner))) "Runner gains 1 credit from Ixodidae due to Lamprey")))) (deftest keyhole ;; Keyhole (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 10)] :hand ["Herald" "Troll"]} :runner {:hand ["Keyhole"]}}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (is (= "Troll" (-> (get-corp) :deck first :title)) "Troll on top of deck") (is (= "Herald" (-> (get-corp) :deck second :title)) "Herald 2nd") (take-credits state :corp) (play-from-hand state :runner "Keyhole") (card-ability state :runner (get-program state 0) 0) (is (:run @state) "Run initiated") (run-continue state) (let [number-of-shuffles (count (core/turn-events state :corp :corp-shuffle-deck))] (click-prompt state :runner "Troll") (is (empty? (:prompt (get-runner))) "Prompt closed") (is (not (:run @state)) "Run ended") (is (-> (get-corp) :discard first :seen) "Troll is faceup") (is (= "Troll" (-> (get-corp) :discard first :title)) "Troll was trashed") (is (find-card "Herald" (:deck (get-corp))) "Herald now in R&D") (is (< number-of-shuffles (count (core/turn-events state :corp :corp-shuffle-deck))) "Corp has shuffled R&D")) (card-ability state :runner (get-program state 0) 0) (is (:run @state) "Keyhole can be used multiple times per turn")))) (deftest kyuban ;; Kyuban (testing "Gain creds when passing a piece of ice, both when rezzed and when unrezzed." (do-game (new-game {:corp {:deck [(qty "Lockdown" 3)]} :runner {:deck [(qty "Kyuban" 1)]}}) (play-from-hand state :corp "Lockdown" "HQ") (play-from-hand state :corp "Lockdown" "Archives") (let [ld1 (get-ice state :archives 0) ld2 (get-ice state :hq 0)] (take-credits state :corp) (play-from-hand state :runner "Kyuban") (click-card state :runner ld1) (let [starting-creds (:credit (get-runner))] (run-on state "HQ") (run-continue state) (is (= starting-creds (:credit (get-runner))) "Gained no money for passing other ice") (run-jack-out state) (run-on state "Archives") (run-continue state) (is (= (+ starting-creds 2) (:credit (get-runner))) "Gained 2 creds for passing unrezzed host ice")) (let [starting-creds-2 (:credit (get-runner))] (core/jack-out state :runner nil) (run-on state "Archives") (rez state :corp ld1) (run-continue state) (run-continue state) (run-continue state) (is (= (+ starting-creds-2 2) (:credit (get-runner))) "Gained 2 creds for passing rezzed host ice"))))) (testing "HB: Architects of Tomorrow interaction" (do-game (new-game {:corp {:id "Haas-Bioroid: Architects of Tomorrow" :deck ["Eli 1.0"]} :runner {:deck ["Kyuban"]}}) (play-from-hand state :corp "Eli 1.0" "HQ") (let [eli (get-ice state :hq 0)] (rez state :corp eli) (take-credits state :corp) (play-from-hand state :runner "Kyuban") (click-card state :runner eli)) (let [starting-creds (:credit (get-runner))] (run-on state "HQ") (run-continue state) (run-continue state) (click-prompt state :corp "Done") (run-continue state) (is (= (+ starting-creds 2) (:credit (get-runner))) "Only gained 2 credits for passing Eli"))))) (deftest laamb ;; Laamb (testing "Ability gives an card Barrier subtype" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Laamb"] :credits 30}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Laamb") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "Yes") (is (has-subtype? (get-ice state :hq 0) "Barrier") "Enigma has been given Barrier"))) (testing "Ability only lasts until end of encounter" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Laamb"] :credits 30}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Laamb") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "Yes") (run-continue state) (is (not (has-subtype? (get-ice state :hq 0) "Barrier")) "Enigma no longer has Barrier subtype"))) (testing "Returning the ice to hand after using ability resets subtype. Issue #3193" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Laamb" "Ankusa"] :credits 30}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Laamb") (play-from-hand state :runner "Ankusa") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "Yes") (let [laamb (get-program state 0) ankusa (get-program state 1)] (card-ability state :runner ankusa 1) (card-ability state :runner ankusa 1) (card-ability state :runner ankusa 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (is (nil? (get-ice state :hq 0)) "Enigma has been returned to HQ") (is (find-card "Enigma" (:hand (get-corp))) "Enigma has been returned to HQ") (run-jack-out state) (take-credits state :runner) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (is (not (has-subtype? (get-ice state :hq 0) "Barrier")) "Enigma doesn't has Barrier subtype") (is (prompt-is-card? state :runner laamb) "Laamb opens the prompt a second time"))))) (deftest lamprey ;; Lamprey - Corp loses 1 credit for each successful HQ run; trashed on purge (do-game (new-game {:runner {:deck ["<NAME>"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (let [lamp (get-program state 0)] (run-empty-server state :hq) (is (= 7 (:credit (get-corp))) "Corp lost 1 credit") (click-prompt state :runner "No action") (run-empty-server state :hq) (is (= 6 (:credit (get-corp))) "Corp lost 1 credit") (click-prompt state :runner "No action") (run-empty-server state :hq) (is (= 5 (:credit (get-corp))) "Corp lost 1 credit") (click-prompt state :runner "No action") (take-credits state :runner) (core/purge state :corp) (is (empty? (get-program state)) "Lamprey trashed by purge")))) (deftest leech ;; Leech - Reduce strength of encountered ICE (testing "Basic test" (do-game (new-game {:corp {:deck ["Fire Wall"]} :runner {:deck ["Leech"]}}) (play-from-hand state :corp "Fire Wall" "New remote") (take-credits state :corp) (core/gain state :runner :click 3) (play-from-hand state :runner "L<NAME>ch") (let [le (get-program state 0) fw (get-ice state :remote1 0)] (run-empty-server state "Archives") (is (= 1 (get-counters (refresh le) :virus))) (run-empty-server state "Archives") (is (= 2 (get-counters (refresh le) :virus))) (run-on state "Server 1") (run-continue state) (run-continue state) (is (= 2 (get-counters (refresh le) :virus)) "No counter gained, not a central server") (run-on state "Server 1") (rez state :corp fw) (run-continue state) (is (= 5 (get-strength (refresh fw)))) (card-ability state :runner le 0) (is (= 1 (get-counters (refresh le) :virus)) "1 counter spent from Leech") (is (= 4 (get-strength (refresh fw))) "Fire Wall strength lowered by 1")))) (testing "does not affect next ice when current is trashed. Issue #1788" (do-game (new-game {:corp {:deck ["Wraparound" "Spiderweb"]} :runner {:deck ["Leech" "Parasite"]}}) (play-from-hand state :corp "Wraparound" "HQ") (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (core/gain state :corp :credit 10) (play-from-hand state :runner "Leech") (let [leech (get-program state 0) wrap (get-ice state :hq 0) spider (get-ice state :hq 1)] (core/add-counter state :runner leech :virus 2) (rez state :corp spider) (rez state :corp wrap) (play-from-hand state :runner "Parasite") (click-card state :runner "Spiderweb") (run-on state "HQ") (run-continue state) (card-ability state :runner (refresh leech) 0) (card-ability state :runner (refresh leech) 0) (is (find-card "Spiderweb" (:discard (get-corp))) "Spiderweb trashed by Parasite + Leech") (is (= 7 (get-strength (refresh wrap))) "Wraparound not reduced by Leech"))))) (deftest leprechaun ;; Leprechaun - hosting a breaker with strength based on unused MU should calculate correctly (testing "Basic test" (do-game (new-game {:runner {:deck ["Adept" "Leprechaun"]}}) (take-credits state :corp) (core/gain state :runner :credit 5) (play-from-hand state :runner "<NAME>") (play-from-hand state :runner "Adept") (is (= 1 (core/available-mu state)) "3 MU used") (let [lep (get-program state 0) adpt (get-program state 1)] (is (= 3 (get-strength (refresh adpt))) "Adept at 3 strength individually") (card-ability state :runner lep 1) (click-card state :runner (refresh adpt)) (let [hosted-adpt (first (:hosted (refresh lep)))] (is (= 3 (core/available-mu state)) "1 MU used") (is (= 5 (get-strength (refresh hosted-adpt))) "Adept at 5 strength hosted"))))) (testing "Keep MU the same when hosting or trashing hosted programs" (do-game (new-game {:runner {:deck ["<NAME>" "Hyperdriver" "Imp"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (let [lep (get-program state 0)] (card-ability state :runner lep 0) (click-card state :runner (find-card "Hyperdriver" (:hand (get-runner)))) (is (= 2 (:click (get-runner)))) (is (= 2 (:credit (get-runner)))) (is (= 3 (core/available-mu state)) "Hyperdriver 3 MU not deducted from available MU") (card-ability state :runner lep 0) (click-card state :runner (find-card "Imp" (:hand (get-runner)))) (is (= 1 (:click (get-runner)))) (is (zero? (:credit (get-runner)))) (is (= 3 (core/available-mu state)) "Imp 1 MU not deducted from available MU") ;; Trash Hyperdriver (core/move state :runner (find-card "Hyperdriver" (:hosted (refresh lep))) :discard) (is (= 3 (core/available-mu state)) "Hyperdriver 3 MU not added to available MU") (core/move state :runner (find-card "Imp" (:hosted (refresh lep))) :discard) ; trash Imp (is (= 3 (core/available-mu state)) "Imp 1 MU not added to available MU"))))) (deftest lustig ;; Lustig (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"]} :runner {:hand ["Lustig"] :credits 10}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (play-from-hand state :runner "Lustig") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 2) (is (= :approach-server (:phase (get-run))) "Run has bypassed Rototurret") (is (find-card "Lustig" (:discard (get-runner))) "Lustig is trashed"))) (deftest magnum-opus ;; Magnum Opus - Gain 2 cr (do-game (new-game {:runner {:deck ["Magnum Opus"]}}) (take-credits state :corp) (play-from-hand state :runner "Magnum Opus") (is (= 2 (core/available-mu state))) (is (zero? (:credit (get-runner)))) (let [mopus (get-program state 0)] (card-ability state :runner mopus 0) (is (= 2 (:credit (get-runner))) "Gain 2cr")))) (deftest makler ;; Makler (testing "Break ability costs 2 for 2 subroutines" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Battlement"]} :runner {:hand ["Makler"] :credits 20}}) (play-from-hand state :corp "Battlement" "HQ") (take-credits state :corp) (play-from-hand state :runner "Makler") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (changes-val-macro -2 (:credit (get-runner)) "Break ability costs 2 credits" (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run")))) (testing "Boost ability costs 2 credits, increases strength by 2" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Bastion"]} :runner {:hand ["Makler"] :credits 20}}) (play-from-hand state :corp "Bastion" "HQ") (take-credits state :corp) (play-from-hand state :runner "Makler") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (changes-val-macro -2 (:credit (get-runner)) "Boost ability costs 2 credits" (card-ability state :runner (get-program state 0) 1)) (changes-val-macro 2 (get-strength (get-program state 0)) "Boost ability increases strength by 2" (card-ability state :runner (get-program state 0) 1)))) (testing "Break all subs ability gives 1 credit" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand [(qty "Battlement" 2)]} :runner {:hand ["Makler"] :credits 20}}) (play-from-hand state :corp "Battlement" "HQ") (play-from-hand state :corp "Battlement" "Archives") (take-credits state :corp) (play-from-hand state :runner "Makler") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (changes-val-macro 1 (:credit (get-runner)) "Break all subs ability gives 1 credit" (run-continue state))))) (deftest mammon ;; Mammon - Pay to add X power counters at start of turn, all removed at end of turn (do-game (new-game {:runner {:deck ["Mammon"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>ammon") (take-credits state :runner) (take-credits state :corp) (let [mam (get-program state 0)] (is (= 5 (:credit (get-runner))) "Starts with 5 credits") (card-ability state :runner mam 0) (click-prompt state :runner "3") (is (= 2 (:credit (get-runner))) "Spent 3 credits") (is (= 3 (get-counters (refresh mam) :power)) "Mammon has 3 power counters") (take-credits state :runner) (is (zero? (get-counters (refresh mam) :power)) "All power counters removed")))) (deftest mantle ;; Mantle (testing "Works with programs" (do-game ;; Using Tracker to demonstrate that it's not just icebreakers (new-game {:runner {:hand ["Mantle" "Tracker"]}}) (take-credits state :corp) (play-from-hand state :runner "Mantle") (play-from-hand state :runner "Tracker") (take-credits state :runner) (take-credits state :corp) (click-prompt state :runner "HQ") (let [mantle (get-program state 0) tracker (get-program state 1)] (card-ability state :runner tracker 0) (changes-val-macro -1 (get-counters (refresh mantle) :recurring) "Can spend credits on Mantle for programs" (click-card state :runner mantle))))) (testing "Works with programs" (do-game (new-game {:runner {:deck ["<NAME>"] :hand ["Mantle" "Prognostic Q-Loop"]}}) (take-credits state :corp) (play-from-hand state :runner "Mantle") (play-from-hand state :runner "Prognostic Q-Loop") (take-credits state :runner) (take-credits state :corp) (let [mantle (get-program state 0) qloop (get-hardware state 0)] (card-ability state :runner qloop 1) (changes-val-macro -1 (get-counters (refresh mantle) :recurring) "Can spend credits on Mantle for programs" (click-card state :runner mantle)) (take-credits state :runner) (take-credits state :corp))))) (deftest marjanah ;; <NAME> (before-each [state (new-game {:runner {:hand [(qty "<NAME>" 2)] :credits 20} :corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"] :credits 20}}) _ (do (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "<NAME>") (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state :encounter-ice)) ice-wall (get-ice state :hq 0) marjanah (get-program state 0)] (testing "pump ability" (do-game state (changes-val-macro -1 (:credit (get-runner)) "Pump costs 1" (card-ability state :runner marjanah 1)) (changes-val-macro 1 (get-strength (refresh marjanah)) "Marjanah gains 1 str" (card-ability state :runner marjanah 1)))) (testing "break ability" (do-game state (changes-val-macro -2 (:credit (get-runner)) "Break costs 2" (card-ability state :runner marjanah 0) (click-prompt state :runner "End the run")))) (testing "discount after successful run" (do-game state (run-continue state :approach-server) (run-continue state nil) (run-on state :hq) (run-continue state :encounter-ice) (changes-val-macro -1 (:credit (get-runner)) "Break costs 1 after run" (card-ability state :runner marjanah 0) (click-prompt state :runner "End the run")))))) (deftest mass-driver ;; Mass-Driver (testing "Basic test" (do-game (new-game {:corp {:deck ["Enigma" "Endless EULA"] :credits 20} :runner {:deck ["Mass-Driver"] :credits 20}}) (play-from-hand state :corp "Endless EULA" "HQ") (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Mass-Driver") (let [eula (get-ice state :hq 0) enigma (get-ice state :hq 1) mass-driver (get-program state 0)] (run-on state :hq) (rez state :corp enigma) (run-continue state) (card-ability state :runner mass-driver 1) (card-ability state :runner mass-driver 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (run-continue state) (rez state :corp eula) (run-continue state) (fire-subs state (refresh eula)) ; only resolve 3 subs (click-prompt state :runner "Pay 1 [Credits]") (click-prompt state :runner "Pay 1 [Credits]") (click-prompt state :runner "Pay 1 [Credits]") (is (empty? (:prompt (get-runner))) "No more prompts open")))) (testing "Interaction with Spooned" (do-game (new-game {:corp {:deck ["Enigma" "Endless EULA"]} :runner {:deck ["Mass-Driver" "Spooned"]}}) (play-from-hand state :corp "Endless EULA" "HQ") (play-from-hand state :corp "Enigma" "HQ") (core/gain state :corp :credit 20) (take-credits state :corp) (core/gain state :runner :credit 20) (play-from-hand state :runner "Mass-Driver") (let [eula (get-ice state :hq 0) enigma (get-ice state :hq 1) mass-driver (get-program state 0)] (play-from-hand state :runner "Spooned") (click-prompt state :runner "HQ") (rez state :corp enigma) (run-continue state) (card-ability state :runner mass-driver 1) (card-ability state :runner mass-driver 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (run-continue state) (is (= 1 (count (:discard (get-corp)))) "Enigma is trashed") (rez state :corp eula) (run-continue state) (fire-subs state (refresh eula)) ; only resolve 3 subs (click-prompt state :runner "Pay 1 [Credits]") (click-prompt state :runner "Pay 1 [Credits]") (click-prompt state :runner "Pay 1 [Credits]") (is (empty? (:prompt (get-runner))) "No more prompts open"))))) (deftest maven ;; Maven (testing "Basic test" (do-game (new-game {:corp {:deck ["Border Control"] :credits 20} :runner {:hand ["Maven" "Datasucker"] :credits 20}}) (play-from-hand state :corp "Border Control" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Maven") (let [maven (get-program state 0)] (is (= 1 (get-strength (refresh maven))) "Maven boosts itself") (play-from-hand state :runner "Datas<NAME>") (is (= 2 (get-strength (refresh maven))) "+1 str from Datasucker") (run-on state "HQ") (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh maven)}) (is (second-last-log-contains? state "Runner pays 4 \\[Credits\\] to use Maven to break all 2 subroutines on Border Control.") "Correct log with autopump ability") (run-jack-out state) (run-on state "HQ") (run-continue state) (card-ability state :runner (refresh maven) 0) (click-prompt state :runner "End the run") (is (last-log-contains? state "Runner pays 2 \\[Credits\\] to use Maven to break 1 subroutine on Border Control.") "Correct log with single sub break"))))) (deftest mayfly ;; Mayfly (testing "Basic test" (do-game (new-game {:corp {:deck ["<NAME>"] :credits 20} :runner {:hand ["Mayfly"] :credits 20}}) (play-from-hand state :corp "<NAME>" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Mayfly") (let [mayfly (get-program state 0)] (run-on state "HQ") (run-continue state) (changes-val-macro -7 (:credit (get-runner)) "Paid 7 to fully break Anansi with Mayfly" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh mayfly)})) (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines") (run-jack-out state) (is (= 1 (count (:discard (get-runner)))) "Mayfly trashed when run ends"))))) (deftest mimic ;; Mimic (testing "Basic auto-break test" (do-game (new-game {:corp {:hand ["Pup"]} :runner {:hand [(qty "Mimic" 5)]}}) (play-from-hand state :corp "Pup" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Mimic") (let [mimic (get-program state 0)] (is (= 2 (:credit (get-runner))) "Runner starts with 2 credits") (is (= 4 (count (:hand (get-runner)))) "Runner has 4 cards in hand") (run-on state "HQ") (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh mimic)}) (is (second-last-log-contains? state "Runner pays 2 \\[Credits\\] to use Mimic to break all 2 subroutines on Pup") "Correct log with autopump ability") (run-jack-out state) (is (zero? (:credit (get-runner))) "Runner spent 2 credits to break Pup") (is (= 4 (count (:hand (get-runner)))) "Runner still has 4 cards in hand")))) (testing "No dynamic options if below strength" (do-game (new-game {:corp {:hand ["Anansi"] :credits 10} :runner {:hand [(qty "Mimic" 5)] :credits 10}}) (play-from-hand state :corp "Anansi" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Mimic") (let [mimic (get-program state 0)] (is (= 7 (:credit (get-runner))) "Runner starts with 7 credits") (is (= 4 (count (:hand (get-runner)))) "Runner has 4 cards in hand") (run-on state "HQ") (run-continue state) (is (= 1 (count (:abilities (refresh mimic)))) "Auto pump and break ability on Mimic is not available")))) (testing "Dynamic options when ice weakened" (do-game (new-game {:corp {:hand ["Zed 2.0"] :credits 10} :runner {:hand ["Mimic" "Ice Carver" ] :credits 10}}) (play-from-hand state :corp "Zed 2.0" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Ice Carver") (play-from-hand state :runner "Mimic") (let [mimic (get-program state 0)] (is (= 4 (:credit (get-runner))) "Runner starts with 4 credits") (run-on state "HQ") (run-continue state) (is (= 2 (count (:abilities (refresh mimic)))) "Auto pump and break ability on Mimic is available") (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh mimic)}) (is (second-last-log-contains? state "Runner pays 3 \\[Credits\\] to use Mimic to break all 3 subroutines on Zed 2.0") "Correct log with autopump ability") (run-jack-out state) (is (= 1 (:credit (get-runner))) "Runner spent 3 credits to break Zed 2.0"))))) (deftest misdirection ;; Misdirection (testing "Recurring credits interaction. Issue #4868" (do-game (new-game {:runner {:hand ["Misdirection" "Multithreader"] :credits 10 :tags 2}}) (take-credits state :corp) (core/gain state :runner :click 2) (play-from-hand state :runner "Misdirection") (play-from-hand state :runner "Multithreader") (let [mis (get-program state 0) multi (get-program state 1)] (changes-val-macro 0 (:credit (get-runner)) "Using recurring credits" (card-ability state :runner mis 0) (click-prompt state :runner "2") (is (= "Select a credit providing card (0 of 2 credits)" (:msg (prompt-map :runner))) "Runner has pay-credit prompt") (click-card state :runner multi) (click-card state :runner multi)) (is (zero? (count-tags state)) "Runner has lost both tags")))) (testing "Using credits from Mantle and credit pool" (do-game (new-game {:runner {:hand ["Misdirection" "Mantle"] :credits 10 :tags 4}}) (take-credits state :corp) (core/gain state :runner :click 2) (play-from-hand state :runner "Misdirection") (play-from-hand state :runner "Mantle") (let [mis (get-program state 0) mantle (get-program state 1)] (changes-val-macro -3 (:credit (get-runner)) "Using recurring credits and credits from credit pool" (card-ability state :runner mis 0) (click-prompt state :runner "4") (is (= "Select a credit providing card (0 of 4 credits)" (:msg (prompt-map :runner))) "Runner has pay-credit prompt") (click-card state :runner mantle)) (is (zero? (count-tags state)) "Runner has lost all 4 tags")))) (testing "Basic behavior" (do-game (new-game {:runner {:hand ["Misdirection"] :credits 5 :tags 2}}) (take-credits state :corp) (play-from-hand state :runner "Misdirection") (let [mis (get-program state 0)] (is (= 5 (:credit (get-runner))) "Runner starts with 5 credits") (is (= 3 (:click (get-runner))) "Runner starts with 3 clicks") (card-ability state :runner mis 0) (click-prompt state :runner "2") (is (zero? (count-tags state)) "Runner has lost both tags") (is (= 1 (:click (get-runner))) "Runner spent 2 clicks (1 remaining)") (is (= 3 (:credit (get-runner))) "Runner spent 2 credits (3 remaining)"))))) (deftest mkultra ;; MKUltra (testing "auto-pump" (testing "Pumping and breaking for 1" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"] :credits 10} :runner {:hand ["MKUltra"] :credits 100}}) (play-from-hand state :corp "Rototurret" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "MKUltra") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -3 (:credit (get-runner)) "Paid 3 to fully break Rototurret with MKUltra" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh pc)})) (is (= 3 (get-strength (refresh pc))) "Pumped MKUltra up to str 3") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines"))))) (testing "Heap Locked" (do-game (new-game {:corp {:deck ["Rototurret" "Blacklist"]} :runner {:deck [(qty "MKUltra" 1)]}}) (play-from-hand state :corp "Rototurret" "Archives") (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (refresh (get-content state :remote1 0))) (take-credits state :corp) (trash-from-hand state :runner "MKUltra") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (is (empty? (:prompt (get-runner))) "MKUltra prompt did not come up")))) (deftest multithreader ;; Multithreader (testing "Pay-credits prompt" (do-game (new-game {:runner {:deck ["Multithreader" "Abagnale"]}}) (take-credits state :corp) (core/gain state :runner :credit 20) (play-from-hand state :runner "Multithreader") (play-from-hand state :runner "Abagnale") (let [mt (get-program state 0) ab (get-program state 1)] (changes-val-macro 0 (:credit (get-runner)) "Used 2 credits from Multithreader" (card-ability state :runner ab 1) (is (= "Select a credit providing card (0 of 2 credits)" (:msg (prompt-map :runner))) "Runner has pay-credit prompt") (click-card state :runner mt) (click-card state :runner mt)))))) (deftest musaazi ;; Musaazi gains virus counters on successful runs and can spend virus counters from any installed card (do-game (new-game {:corp {:deck ["Lancelot"]} :runner {:deck ["Musaazi" "Imp"]}}) (play-from-hand state :corp "Lancelot" "HQ") (take-credits state :corp) (play-from-hand state :runner "Musaazi") (play-from-hand state :runner "Imp") (let [lancelot (get-ice state :hq 0) musaazi (get-program state 0) imp (get-program state 1)] (run-empty-server state "Archives") (is (= 1 (get-counters (refresh musaazi) :virus)) "Musaazi has 1 virus counter") (is (= 1 (get-strength (refresh musaazi))) "Initial Musaazi strength") (is (= 2 (get-counters (refresh imp) :virus)) "Initial Imp virus counters") (run-on state "HQ") (rez state :corp lancelot) (run-continue state) (card-ability state :runner musaazi 1) ; match strength (click-card state :runner imp) (is (= 1 (get-counters (refresh imp) :virus)) "Imp lost 1 virus counter to pump") (is (= 2 (get-strength (refresh musaazi))) "Musaazi strength 2") (is (empty? (:prompt (get-runner))) "No prompt open") (card-ability state :runner musaazi 0) (click-prompt state :runner "Trash a program") (click-card state :runner musaazi) (click-prompt state :runner "Resolve a Grail ICE subroutine from HQ") (click-card state :runner imp) (is (zero? (get-counters (refresh imp) :virus)) "Imp lost its final virus counter") (is (zero? (get-counters (refresh imp) :virus)) "Musaazi lost its virus counter")))) (deftest na-not-k ;; Na'Not'K - Strength adjusts accordingly when ice installed during run (testing "Basic test" (do-game (new-game {:corp {:deck ["Architect" "Eli 1.0"]} :runner {:deck ["Na'Not'K"]}}) (play-from-hand state :corp "Architect" "HQ") (take-credits state :corp) (play-from-hand state :runner "Na'Not'K") (let [nanotk (get-program state 0) architect (get-ice state :hq 0)] (is (= 1 (get-strength (refresh nanotk))) "Default strength") (run-on state "HQ") (rez state :corp architect) (run-continue state) (is (= 2 (get-strength (refresh nanotk))) "1 ice on HQ") (card-subroutine state :corp (refresh architect) 1) (click-card state :corp (find-card "Eli 1.0" (:hand (get-corp)))) (click-prompt state :corp "HQ") (is (= 3 (get-strength (refresh nanotk))) "2 ice on HQ") (run-jack-out state) (is (= 1 (get-strength (refresh nanotk))) "Back to default strength")))) (testing "Strength adjusts accordingly when run redirected to another server" (do-game (new-game {:corp {:deck ["Susanoo-no-Mikoto" "Crick" "Cortex Lock"] :credits 20} :runner {:deck ["Na'Not'K"]}}) (play-from-hand state :corp "Cortex Lock" "HQ") (play-from-hand state :corp "Susanoo-no-Mikoto" "HQ") (play-from-hand state :corp "Crick" "Archives") (take-credits state :corp) (play-from-hand state :runner "Na'Not'K") (let [nanotk (get-program state 0) susanoo (get-ice state :hq 1)] (is (= 1 (get-strength (refresh nanotk))) "Default strength") (run-on state "HQ") (rez state :corp susanoo) (run-continue state) (is (= 3 (get-strength (refresh nanotk))) "2 ice on HQ") (card-subroutine state :corp (refresh susanoo) 0) (is (= 2 (get-strength (refresh nanotk))) "1 ice on Archives") (run-jack-out state) (is (= 1 (get-strength (refresh nanotk))) "Back to default strength"))))) (deftest nfr ;; Nfr (testing "Basic test" (do-game (new-game {:runner {:deck ["Nfr"]} :corp {:deck ["Ice Wall"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Nfr") (let [nfr (get-program state 0) icew (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh icew)) (run-continue state) (card-ability state :runner (refresh nfr) 0) (click-prompt state :runner "End the run") (changes-val-macro 1 (get-counters (refresh nfr) :power) "Got 1 token" (run-continue state)))))) (deftest nyashia ;; Nyashia (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 10)] :hand ["Hedge Fund"]} :runner {:deck ["Nyashia"]}}) (take-credits state :corp) (play-from-hand state :runner "Nyashia") (run-on state "R&D") (run-continue state) (click-prompt state :runner "Yes") (is (= 2 (:total (core/num-cards-to-access state :runner :rd nil)))))) (deftest odore (testing "Basic test" (do-game (new-game {:corp {:deck ["Cobra"]} :runner {:deck ["Odore" (qty "Logic Bomb" 3)]}}) (play-from-hand state :corp "Cobra" "HQ") (take-credits state :corp) (play-from-hand state :runner "Odore") (let [odore (get-program state 0) cobra (get-ice state :hq 0)] (core/gain state :runner :click 2 :credit 20) (run-on state "HQ") (rez state :corp cobra) (run-continue state) (changes-val-macro -5 (:credit (get-runner)) "Paid 3 to pump and 2 to break" (card-ability state :runner odore 2) (card-ability state :runner odore 0) (click-prompt state :runner "Trash a program") (click-prompt state :runner "Do 2 net damage"))))) (testing "auto-pump-and-break with and without 3 virtual resources" (do-game (new-game {:corp {:deck ["Cobra"]} :runner {:deck ["Odore" (qty "Logic Bomb" 3)]}}) (play-from-hand state :corp "Cobra" "HQ") (take-credits state :corp) (play-from-hand state :runner "Odore") (let [odore (get-program state 0) cobra (get-ice state :hq 0)] (core/gain state :runner :click 2 :credit 20) (run-on state "HQ") (rez state :corp cobra) (run-continue state) (changes-val-macro -5 (:credit (get-runner)) "Paid 3 to pump and 2 to break" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh odore)})) (core/continue state :corp nil) (run-jack-out state) (dotimes [_ 3] (play-from-hand state :runner "Logic Bomb")) (run-on state "HQ") (run-continue state) (changes-val-macro -3 (:credit (get-runner)) "Paid 3 to pump and 0 to break" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh odore)})))))) (deftest origami ;; Origami - Increases Runner max hand size (do-game (new-game {:runner {:deck [(qty "Origami" 2)]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (is (= 6 (hand-size :runner))) (play-from-hand state :runner "<NAME>") (is (= 9 (hand-size :runner)) "Max hand size increased by 2 for each copy installed"))) (deftest overmind ;; Overmind - Start with counters equal to unused MU (do-game (new-game {:runner {:deck ["Overmind" "Deep Red" "Sure Gamble" "Akamatsu Mem Chip" ]}}) (take-credits state :corp) (play-from-hand state :runner "Sure Gamble") (play-from-hand state :runner "Akamatsu Mem Chip") (is (= 5 (core/available-mu state))) (play-from-hand state :runner "Deep Red") (is (= 8 (core/available-mu state))) (play-from-hand state :runner "Overmind") (is (= 7 (core/available-mu state))) (let [ov (get-program state 0)] (is (= 7 (get-counters (refresh ov) :power)) "Overmind has 5 counters")))) (deftest paintbrush ;; Paintbrush - Give rezzed ICE a chosen subtype until the end of the next run (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["Paintbrush"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Paintbrush") (is (= 2 (core/available-mu state))) (let [iwall (get-ice state :hq 0) pb (get-program state 0)] (card-ability state :runner pb 0) (click-card state :runner iwall) (is (= 3 (:click (get-runner))) "Ice Wall not rezzed, so no click charged") (click-prompt state :runner "Done") ; cancel out (rez state :corp iwall) (card-ability state :runner pb 0) (click-card state :runner iwall) (click-prompt state :runner "Code Gate") (is (= 2 (:click (get-runner))) "Click charged") (is (has-subtype? (refresh iwall) "Code Gate") "Ice Wall gained Code Gate") (run-empty-server state "Archives") (is (not (has-subtype? (refresh iwall) "Code Gate")) "Ice Wall lost Code Gate at the end of the run")))) (deftest panchatantra ;; Panchatantra (before-each [state (new-game {:corp {:hand ["Ice Wall"]} :runner {:hand ["Panchatantra"]}}) _ (do (play-from-hand state :corp "Ice Wall" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Panchatantra") (run-on state :hq) (run-continue state)) iw (get-ice state :hq 0)] (testing "Choices do not include Barrier, Code Gate, or Sentry" (do-game state (click-prompt state :runner "Yes") (is (not (some #{"Barrier" "Code Gate" "Sentry"} (prompt-buttons :runner)))))) (testing "Encountered ice gains the subtype" (do-game state (click-prompt state :runner "Yes") (click-prompt state :runner "AP") (is (has-subtype? (refresh iw) "AP")))) (testing "Encountered ice loses subtype at the end of the run" (do-game state (click-prompt state :runner "Yes") (click-prompt state :runner "AP") (run-continue state) (is (has-subtype? (refresh iw) "AP")) (run-jack-out state) (is (not (has-subtype? (refresh iw) "AP"))))))) (deftest paperclip ;; Paperclip - prompt to install on encounter, but not if another is installed (testing "Basic test" (do-game (new-game {:corp {:deck ["Vanilla"]} :runner {:deck [(qty "Paperclip" 2)]}}) (play-from-hand state :corp "Vanilla" "Archives") (take-credits state :corp) (trash-from-hand state :runner "Paperclip") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (click-prompt state :runner "Yes") ; install paperclip (run-continue state) (run-continue state) (is (not (:run @state)) "Run ended") (trash-from-hand state :runner "Paperclip") (run-on state "Archives") (is (empty? (:prompt (get-runner))) "No prompt to install second Paperclip"))) (testing "firing on facedown ice shouldn't crash" (do-game (new-game {:corp {:deck ["Vanilla"]} :runner {:deck ["Paperclip"]}}) (play-from-hand state :corp "Vanilla" "Archives") (take-credits state :corp) (play-from-hand state :runner "Paperclip") (run-on state "Archives") (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "0"))) (testing "do not show a second install prompt if user said No to first, when multiple are in heap" (do-game (new-game {:corp {:deck [(qty "Vanilla" 2)]} :runner {:deck [(qty "Paperclip" 3)]}}) (play-from-hand state :corp "Vanilla" "Archives") (play-from-hand state :corp "Vanilla" "Archives") (take-credits state :corp) (trash-from-hand state :runner "Paperclip") (trash-from-hand state :runner "Paperclip") (trash-from-hand state :runner "Paperclip") (run-on state "Archives") (rez state :corp (get-ice state :archives 1)) (run-continue state) (click-prompt state :runner "No") (is (empty? (:prompt (get-runner))) "No additional prompts to rez other copies of Paperclip") (run-continue state) (rez state :corp (get-ice state :archives 0)) (run-continue state) ;; we should get the prompt on a second ice even after denying the first (click-prompt state :runner "No") (is (empty? (:prompt (get-runner))) "No additional prompts to rez other copies of Paperclip") (run-jack-out state) ;; Run again, make sure we get the prompt to install again (run-on state "Archives") (run-continue state) (click-prompt state :runner "No") (is (empty? (:prompt (get-runner))) "No additional prompts to rez other copies of Paperclip"))) (testing "auto-pump" (testing "Pumping and breaking for 1" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Vanilla"] :credits 10} :runner {:hand ["Paperclip"] :credits 100}}) (play-from-hand state :corp "Vanilla" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -1 (:credit (get-runner)) "Paid 1 to fully break Vanilla with Paperclip" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh pc)})) (is (= 2 (get-strength (refresh pc))) "Pumped Paperclip up to str 2") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "Pumping for >1 and breaking for 1" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Fire Wall"] :credits 10} :runner {:hand ["Paperclip"] :credits 100}}) (play-from-hand state :corp "Fire Wall" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -4 (:credit (get-runner)) "Paid 4 to fully break Fire Wall with Paperclip" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh pc)})) (is (= 5 (get-strength (refresh pc))) "Pumped Paperclip up to str 5") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "Pumping for 1 and breaking for >1" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Spiderweb"] :credits 10} :runner {:hand ["Paperclip"] :credits 100}}) (play-from-hand state :corp "Spiderweb" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -3 (:credit (get-runner)) "Paid 3 to fully break Spiderweb with Paperclip" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh pc)})) (is (= 4 (get-strength (refresh pc))) "Pumped Paperclip up to str 4") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "Pumping for >1 and breaking for >1" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Chiyashi"] :credits 12} :runner {:hand ["Paperclip"] :credits 100}}) (play-from-hand state :corp "Chiyashi" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -7 (:credit (get-runner)) "Paid 7 to fully break Chiyashi with Paperclip" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh pc)})) (is (= 8 (get-strength (refresh pc))) "Pumped Paperclip up to str 8") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "No auto-pump on unbreakable subs" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Akhet"] :credits 10} :runner {:hand ["Paperclip"] :credits 100}}) (core/gain state :corp :click 1) (play-from-hand state :corp "Akhet" "HQ") (rez state :corp (get-ice state :hq 0)) (dotimes [n 3] (advance state (get-ice state :hq 0))) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (is (empty? (filter #(:dynamic %) (:abilities (refresh pc)))) "No auto-pumping option for Akhet")))) (testing "Orion triggers all heap breakers once" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Orion"] :credits 15} :runner {:discard [(qty "Paperclip" 2) (qty "MKUltra" 2) (qty "Black Orchestra" 2)] :credits 100}}) (play-from-hand state :corp "Orion" "HQ") (take-credits state :corp) (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "No") (click-prompt state :runner "No") (click-prompt state :runner "No") (is (empty? (:prompt (get-runner))) "No further prompts to install heap breakers")))) (testing "Heap Locked" (do-game (new-game {:corp {:deck ["Vanilla" "Blacklist"]} :runner {:deck [(qty "Paperclip" 2)]}}) (play-from-hand state :corp "Vanilla" "Archives") (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (refresh (get-content state :remote1 0))) (take-credits state :corp) (trash-from-hand state :runner "Paperclip") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (is (empty? (:prompt (get-runner))) "Paperclip prompt did not come up") (fire-subs state (get-ice state :archives 0)) (is (not (:run @state)) "Run ended"))) (testing "Breaking some subs" (do-game (new-game {:corp {:hand ["Hive"]} :runner {:hand ["Paperclip"] :credits 10}}) (play-from-hand state :corp "Hive" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -2 (:credit (get-runner)) "Paid 2 to break two of the subs on Hive" (is (= 5 (count (:subroutines (get-ice state :hq 0)))) "Hive starts with 5 subs") (is (= 3 (get-strength (get-ice state :hq 0))) "Hive has strength 3") (card-ability state :runner pc 0) (click-prompt state :runner "2") (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (is (= 3 (get-strength (refresh pc))) "Pumped Paperclip up to str 3") (is (= 3 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broke all but 3 subs")))))) (deftest parasite (testing "Basic functionality: Gain 1 counter every Runner turn" (do-game (new-game {:corp {:deck [(qty "Wraparound" 3) (qty "Hedge Fund" 3)]} :runner {:deck [(qty "Parasite" 3) (qty "Sure Gamble" 3)]}}) (play-from-hand state :corp "Wraparound" "HQ") (let [wrap (get-ice state :hq 0)] (rez state :corp wrap) (take-credits state :corp) (play-from-hand state :runner "Parasite") (click-card state :runner wrap) (is (= 3 (core/available-mu state)) "Parasite consumes 1 MU") (let [psite (first (:hosted (refresh wrap)))] (is (zero? (get-counters psite :virus)) "Parasite has no counters yet") (take-credits state :runner) (take-credits state :corp) (is (= 1 (get-counters (refresh psite) :virus)) "Parasite gained 1 virus counter at start of Runner turn") (is (= 6 (get-strength (refresh wrap))) "Wraparound reduced to 6 strength"))))) (testing "Installed facedown w/ Apex" (do-game (new-game {:runner {:id "Apex: Invasive Predator" :deck ["Parasite"]}}) (take-credits state :corp) (end-phase-12 state :runner) (click-card state :runner (find-card "Parasite" (:hand (get-runner)))) (is (empty? (:prompt (get-runner))) "No prompt to host Parasite") (is (= 1 (count (get-runner-facedown state))) "Parasite installed face down"))) (testing "Installed on untrashable Architect should keep gaining counters past 3 and make strength go negative" (do-game (new-game {:corp {:deck [(qty "Architect" 3) (qty "Hedge Fund" 3)]} :runner {:deck [(qty "Parasite" 3) "Grimoire"]}}) (play-from-hand state :corp "Architect" "HQ") (let [arch (get-ice state :hq 0)] (rez state :corp arch) (take-credits state :corp) (play-from-hand state :runner "Grimoire") (play-from-hand state :runner "Parasite") (click-card state :runner arch) (let [psite (first (:hosted (refresh arch)))] (is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter") (take-credits state :runner) (take-credits state :corp) (take-credits state :runner) (take-credits state :corp) (take-credits state :runner) (take-credits state :corp) (is (= 4 (get-counters (refresh psite) :virus)) "Parasite has 4 counters") (is (= -1 (get-strength (refresh arch))) "Architect at -1 strength"))))) (testing "Should stay on hosted card moved by Builder" (do-game (new-game {:corp {:deck [(qty "Builder" 3) "Ice Wall"]} :runner {:deck [(qty "Parasite" 3)]}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Builder" "Archives") (let [builder (get-ice state :archives 0)] (rez state :corp builder) (take-credits state :corp) (play-from-hand state :runner "Parasite") (click-card state :runner builder) (let [psite (first (:hosted (refresh builder)))] (take-credits state :runner) (take-credits state :corp) (is (= 3 (get-strength (refresh builder))) "Builder reduced to 3 strength") (is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter") (take-credits state :runner)) (let [orig-builder (refresh builder)] (card-ability state :corp builder 0) (click-prompt state :corp "HQ") (let [moved-builder (get-ice state :hq 1)] (is (= (get-strength orig-builder) (get-strength moved-builder)) "Builder's state is maintained") (let [orig-psite (dissoc (first (:hosted orig-builder)) :host) moved-psite (dissoc (first (:hosted moved-builder)) :host)] (is (= orig-psite moved-psite) "Hosted Parasite is maintained")) (take-credits state :corp) (let [updated-builder (refresh moved-builder) updated-psite (first (:hosted updated-builder))] (is (= 2 (get-strength updated-builder)) "Builder strength still reduced") (is (= 2 (get-counters (refresh updated-psite) :virus)) "Parasite counters still incremented"))))))) (testing "Use Hivemind counters when installed; instantly trash ICE if counters >= ICE strength" (do-game (new-game {:corp {:deck [(qty "Enigma" 3) (qty "Hedge Fund" 3)]} :runner {:deck ["Parasite" "Grimoire" "Hivemind" "Sure Gamble"]}}) (play-from-hand state :corp "Enigma" "HQ") (let [enig (get-ice state :hq 0)] (rez state :corp enig) (take-credits state :corp) (play-from-hand state :runner "Sure Gamble") (play-from-hand state :runner "Grimoire") (play-from-hand state :runner "Hivemind") (let [hive (get-program state 0)] (is (= 2 (get-counters (refresh hive) :virus)) "Hivemind has 2 counters") (play-from-hand state :runner "Parasite") (click-card state :runner enig) (is (= 1 (count (:discard (get-corp)))) "Enigma trashed instantly") (is (= 4 (core/available-mu state))) (is (= 2 (count (:discard (get-runner)))) "Parasite trashed when Enigma was trashed"))))) (testing "Trashed along with host ICE when its strength has been reduced to 0" (do-game (new-game {:corp {:deck [(qty "Enigma" 3) (qty "Hedge Fund" 3)]} :runner {:deck [(qty "Parasite" 3) "Grimoire"]}}) (play-from-hand state :corp "Enigma" "HQ") (let [enig (get-ice state :hq 0)] (rez state :corp enig) (take-credits state :corp) (play-from-hand state :runner "Grimoire") (play-from-hand state :runner "Parasite") (click-card state :runner enig) (let [psite (first (:hosted (refresh enig)))] (is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter") (is (= 1 (get-strength (refresh enig))) "Enigma reduced to 1 strength") (take-credits state :runner) (take-credits state :corp) (is (= 1 (count (:discard (get-corp)))) "Enigma trashed") (is (= 1 (count (:discard (get-runner)))) "Parasite trashed when Enigma was trashed"))))) (testing "Interaction with Customized Secretary #2672" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:deck ["Parasite"] :hand ["Djinn" "Customized Secretary"] :credits 10}}) (play-from-hand state :corp "Enigma" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Djinn") (card-ability state :runner (get-program state 0) 1) (is (= "Choose a non-Icebreaker program in your grip" (:msg (prompt-map :runner)))) (click-card state :runner "Customized Secretary") (is (= "Choose a program to host" (:msg (prompt-map :runner)))) (click-prompt state :runner "Parasite") (card-ability state :runner (first (:hosted (get-program state 0))) 0) (is (= "Parasite" (:title (first (:hosted (first (:hosted (get-program state 0)))))))) (is (= "Choose a program to install" (:msg (prompt-map :runner)))) (click-prompt state :runner "Parasite") (is (= "Choose a card to host Parasite on" (:msg (prompt-map :runner)))) (click-card state :runner "Enigma") (is (= "Customized Secretary" (:title (first (:hosted (get-program state 0)))))) (is (empty? (:hosted (first (:hosted (get-program state 0)))))))) (testing "Triggers Hostile Infrastructure" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Hostile Infrastructure" "Vanilla"]} :runner {:deck [(qty "Parasite" 2)]}}) (play-from-hand state :corp "Hostile Infrastructure" "New remote") (play-from-hand state :corp "Vanilla" "HQ") (let [van (get-ice state :hq 0) hi (get-content state :remote1 0)] (rez state :corp hi) (rez state :corp van) (take-credits state :corp) (changes-val-macro 2 (count (:discard (get-runner))) "Took net damage (Parasite on Vanilla was trashed + card from hand" (play-from-hand state :runner "Parasite") (click-card state :runner van)))))) (deftest paricia ;; Paricia (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["PAD Campaign" "Shell Corporation"]} :runner {:hand ["Paricia"]}}) (play-from-hand state :corp "PAD Campaign" "New remote") (play-from-hand state :corp "Shell Corporation" "New remote") (take-credits state :corp) (play-from-hand state :runner "<NAME>") (let [pad (get-content state :remote1 0) shell (get-content state :remote2 0) paricia (get-program state 0)] (run-empty-server state :remote2) (click-prompt state :runner "Pay 3 [Credits] to trash") (is (empty? (:prompt (get-runner))) "No pay-credit prompt as it's an upgrade") (is (nil? (refresh shell)) "Shell Corporation successfully trashed") (run-empty-server state :remote1) (is (= 2 (:credit (get-runner))) "Runner can't afford to trash PAD Campaign") (click-prompt state :runner "Pay 4 [Credits] to trash") (dotimes [_ 2] (click-card state :runner "<NAME>")) (is (nil? (refresh pad)) "PAD Campaign successfully trashed")))) (deftest pawn ;; Pawn (testing "Happy Path" (do-game (new-game {:corp {:deck ["Enigma" "Blacklist" "Hedge Fund"]} :runner {:deck ["Pawn" "Knight"]}}) (play-from-hand state :corp "Enigma" "Archives") (take-credits state :corp) (trash-from-hand state :runner "Knight") (play-from-hand state :runner "Pawn") ;;currently Pawn successful run check is not implemented, nor is hosted location check (card-ability state :runner (get-program state 0) 2) (click-card state :runner (find-card "Knight" (:discard (get-runner)))) (is (not (nil? (find-card "Pawn" (:discard (get-runner)))))))) (testing "Heap locked" (do-game (new-game {:corp {:deck ["Enigma" "Blacklist" "Hedge Fund"]} :runner {:deck ["Pawn" "Knight"]}}) (play-from-hand state :corp "Enigma" "Archives") (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (refresh (get-content state :remote1 0))) (take-credits state :corp) (trash-from-hand state :runner "Knight") (play-from-hand state :runner "Pawn") (card-ability state :runner (get-program state 0) 2) (is (empty? (:prompt (get-runner))) "Install prompt did not come up") (is (nil? (find-card "Pawn" (:discard (get-runner))))) (is (not (nil? (find-card "Knight" (:discard (get-runner))))))))) (deftest pelangi ;; Pelangi (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 10)] :hand ["Ice Wall"]} :runner {:hand ["Pelangi"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Pelangi") (let [iw (get-ice state :hq 0) pelangi (get-program state 0)] (run-on state "HQ") (rez state :corp iw) (run-continue state) (card-ability state :runner pelangi 0) (click-prompt state :runner "Code Gate") (is (has-subtype? (refresh iw) "Code Gate") "Ice Wall gained Code Gate") (run-continue state) (run-jack-out state) (is (not (has-subtype? (refresh iw) "Code Gate")) "Ice Wall lost Code Gate at the end of the run")))) (deftest penrose ;; Penrose (testing "Pay-credits prompt and first turn ability" (do-game (new-game {:runner {:deck ["Cloak" "Penrose"]} :corp {:deck ["Enigma" "Vanilla"]}}) (play-from-hand state :corp "Enigma" "HQ") (play-from-hand state :corp "Vanilla" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cloak") (play-from-hand state :runner "Penrose") (core/gain state :runner :credit 1) (run-on state :hq) (let [enig (get-ice state :hq 0) van (get-ice state :hq 1) cl (get-program state 0) penr (get-program state 1)] (is (= 3 (count (:abilities penr))) "3 abilities on Penrose") (rez state :corp van) (run-continue state) (is (= 4 (count (:abilities (refresh penr)))) "Auto pump and break ability on Penrose active") (changes-val-macro 0 (:credit (get-runner)) "Used 1 credit from Cloak" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh penr)}) (click-card state :runner cl)) (core/continue state :corp nil) (rez state :corp enig) (run-continue state) (changes-val-macro -2 (:credit (get-runner)) "Paid 2 credits to break all subroutines on Enigma" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh penr)})) (core/continue state :corp nil) (run-jack-out state) (take-credits state :runner) (take-credits state :corp) (run-on state :hq) (is (= 3 (count (:abilities (refresh penr)))) "Auto pump and break ability on Penrose is not active") (card-ability state :runner (refresh penr) 0) (is (empty? (:prompt (get-runner))) "No cloak prompt because the ability to break barriers is not active anymore"))))) (deftest peregrine ;; Peregrine - 2c to return to grip and derez an encountered code gate (do-game (new-game {:corp {:deck ["Paper Wall" (qty "Bandwidth" 2)]} :runner {:deck ["Peregrine"]}}) (play-from-hand state :corp "Bandwidth" "Archives") (play-from-hand state :corp "Bandwidth" "Archives") (play-from-hand state :corp "Paper Wall" "Archives") (take-credits state :corp) (core/gain state :runner :credit 20) (play-from-hand state :runner "Peregrine") (let [bw1 (get-ice state :archives 0) pw (get-ice state :archives 2) per (get-program state 0)] (run-on state "Archives") (rez state :corp pw) (run-continue state) (rez state :corp bw1) (changes-val-macro 0 (:credit (get-runner)) "Can't use Peregrine on a barrier" (card-ability state :runner per 2)) (run-continue state) (run-continue state) (changes-val-macro 0 (:credit (get-runner)) "Can't use Peregrine on an unrezzed code gate" (card-ability state :runner per 2)) (run-continue state) (changes-val-macro -3 (:credit (get-runner)) "Paid 3 to pump strength" (card-ability state :runner per 1)) (changes-val-macro -1 (:credit (get-runner)) "Paid 1 to break sub" (card-ability state :runner per 0) (click-prompt state :runner "Give the Runner 1 tag")) (changes-val-macro -2 (:credit (get-runner)) "Paid 2 to derez Bandwidth" (card-ability state :runner per 2) (run-continue state)) (is (= 1 (count (:hand (get-runner)))) "Peregrine returned to grip") (is (not (rezzed? (refresh bw1))) "Bandwidth derezzed")))) (deftest persephone ;; Persephone's ability trashes cards from R&D (testing "Triggers AR-Enhanced Security. Issue #3187" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Zed 1.0" "Zed 2.0" "AR-Enhanced Security"]} :runner {:deck [(qty "Persephone" 10)]}}) (play-from-hand state :corp "AR-Enhanced Security" "New remote") (score-agenda state :corp (get-content state :remote1 0)) (play-from-hand state :corp "Zed 1.0" "Archives") (rez state :corp (get-ice state :archives 0)) (take-credits state :corp) (play-from-hand state :runner "Persephone") (run-on state "Archives") (run-continue state) (fire-subs state (get-ice state :archives 0)) (run-continue state) (click-prompt state :runner "Yes") (is (= 1 (count-tags state)) "Runner took 1 tag from using Persephone's ability while AR-Enhanced Security is scored") (run-jack-out state) (take-credits state :runner) ;; Gotta move the discarded cards back to the deck (core/move state :corp (find-card "Zed 2.0" (:discard (get-corp))) :deck) (core/move state :corp (find-card "Zed 2.0" (:discard (get-corp))) :deck) (take-credits state :corp) (run-on state "Archives") (run-continue state) (fire-subs state (get-ice state :archives 0)) (run-continue state) (click-prompt state :runner "Yes") (is (= 2 (count-tags state)) "Runner took 1 tag from using Persephone's ability while AR-Enhanced Security is scored")))) (deftest pheromones ;; Pheromones ability shouldn't have a NullPointerException when fired with 0 virus counter (testing "Basic test" (do-game (new-game {:runner {:deck ["Pheromones"]}}) (take-credits state :corp) (play-from-hand state :runner "Pheromones") (let [ph (get-program state 0)] (card-ability state :runner (refresh ph) 0) (run-empty-server state "HQ") (click-prompt state :runner "No action") (is (= 1 (get-counters (refresh ph) :virus)) "Pheromones gained 1 counter") (card-ability state :runner (refresh ph) 0)))) ; this doesn't do anything, but shouldn't crash (testing "Pay-credits prompt" (do-game (new-game {:runner {:deck ["Pheromones" "Inti"]}}) (take-credits state :corp) (play-from-hand state :runner "Pheromones") (play-from-hand state :runner "Inti") (run-empty-server state "HQ") (click-prompt state :runner "No action") (run-empty-server state "HQ") (click-prompt state :runner "No action") (take-credits state :runner) (take-credits state :corp) (let [phero (get-program state 0) inti (get-program state 1)] (is (changes-credits (get-runner) -2 (card-ability state :runner inti 1))) (changes-val-macro 0 (:credit (get-runner)) "Used 2 credits from Pheromones" (run-on state "HQ") (card-ability state :runner inti 1) (click-card state :runner phero) (click-card state :runner phero)))))) (deftest plague ;; Plague (do-game (new-game {:corp {:deck ["<NAME>"]} :runner {:deck ["Plague"]}}) (play-from-hand state :corp "<NAME>" "New remote") (take-credits state :corp) (play-from-hand state :runner "Plague") (click-prompt state :runner "Server 1") (let [plague (get-program state 0)] (run-empty-server state "Server 1") (click-prompt state :runner "No action") (is (= 2 (get-counters (refresh plague) :virus)) "Plague gained 2 counters") (run-empty-server state "Server 1") (click-prompt state :runner "No action") (is (= 4 (get-counters (refresh plague) :virus)) "Plague gained 2 counters") (run-empty-server state "Archives") (is (= 4 (get-counters (refresh plague) :virus)) "Plague did not gain counters")))) (deftest progenitor ;; Progenitor (testing "Hosting Hivemind, using Virus Breeding Ground. Issue #738" (do-game (new-game {:runner {:deck ["Progenitor" "Virus Breeding Ground" "Hivemind"]}}) (take-credits state :corp) (play-from-hand state :runner "Progenitor") (play-from-hand state :runner "Virus Breeding Ground") (is (= 4 (core/available-mu state))) (let [prog (get-program state 0) vbg (get-resource state 0)] (card-ability state :runner prog 0) (click-card state :runner (find-card "Hivemind" (:hand (get-runner)))) (is (= 4 (core/available-mu state)) "No memory used to host on Progenitor") (let [hive (first (:hosted (refresh prog)))] (is (= "Hivemind" (:title hive)) "Hivemind is hosted on Progenitor") (is (= 1 (get-counters hive :virus)) "Hivemind has 1 counter") (is (zero? (:credit (get-runner))) "Full cost to host on Progenitor") (take-credits state :runner 1) (take-credits state :corp) (card-ability state :runner vbg 0) ; use VBG to transfer 1 token to Hivemind (click-card state :runner hive) (is (= 2 (get-counters (refresh hive) :virus)) "Hivemind gained 1 counter") (is (zero? (get-counters (refresh vbg) :virus)) "Virus Breeding Ground lost 1 counter"))))) (testing "Keep MU the same when hosting or trashing hosted programs" (do-game (new-game {:runner {:deck ["Progenitor" "Hivemind"]}}) (take-credits state :corp) (play-from-hand state :runner "Progenitor") (let [pro (get-program state 0)] (card-ability state :runner pro 0) (click-card state :runner (find-card "Hivemind" (:hand (get-runner)))) (is (= 2 (:click (get-runner)))) (is (= 2 (:credit (get-runner)))) (is (= 4 (core/available-mu state)) "Hivemind 2 MU not deducted from available MU") ;; Trash Hivemind (core/move state :runner (find-card "Hivemind" (:hosted (refresh pro))) :discard) (is (= 4 (core/available-mu state)) "Hivemind 2 MU not added to available MU"))))) (deftest reaver ;; Reaver - Draw a card the first time you trash an installed card each turn (testing "Basic test" (do-game (new-game {:corp {:deck ["PAD Campaign"]} :runner {:deck ["Reaver" (qty "Fall Guy" 5)]}}) (starting-hand state :runner ["Reaver" "Fall Guy"]) (play-from-hand state :corp "PAD Campaign" "New remote") (take-credits state :corp) (core/gain state :runner :credit 10) (core/gain state :runner :click 1) (play-from-hand state :runner "Reaver") (is (= 1 (count (:hand (get-runner)))) "One card in hand") (run-empty-server state "Server 1") (click-prompt state :runner "Pay 4 [Credits] to trash") ; Trash PAD campaign (is (= 2 (count (:hand (get-runner)))) "Drew a card from trash of corp card") (play-from-hand state :runner "Fall Guy") (play-from-hand state :runner "Fall Guy") (is (zero? (count (:hand (get-runner)))) "No cards in hand") ; No draw from Fall Guy trash as Reaver already fired this turn (card-ability state :runner (get-resource state 0) 1) (is (zero? (count (:hand (get-runner)))) "No cards in hand") (take-credits state :runner) ; Draw from Fall Guy trash on corp turn (card-ability state :runner (get-resource state 0) 1) (is (= 1 (count (:hand (get-runner)))) "One card in hand"))) (testing "with Freelance Coding Construct - should not draw when trash from hand #2671" (do-game (new-game {:runner {:deck [(qty "Reaver" 9) "Imp" "Snitch" "Freelance Coding Contract"]}}) (starting-hand state :runner ["Reaver" "Imp" "Snitch" "Freelance Coding Contract"]) (take-credits state :corp) (play-from-hand state :runner "Reaver") (is (= 3 (count (:hand (get-runner)))) "Four cards in hand") (is (= 3 (:credit (get-runner))) "3 credits") (play-from-hand state :runner "Freelance Coding Contract") (click-card state :runner "Snitch") (click-card state :runner "Imp") (click-prompt state :runner "Done") (is (= 7 (:credit (get-runner))) "7 credits - FCC fired") (is (zero? (count (:hand (get-runner)))) "No cards in hand")))) (deftest rezeki ;; Rezeki - gain 1c when turn begins (do-game (new-game {:runner {:deck ["<NAME>"]}}) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (take-credits state :runner) (let [credits (:credit (get-runner))] (take-credits state :corp) (is (= (:credit (get-runner)) (+ credits 1)) "Gain 1 from Rezeki")))) (deftest rng-key ;; RNG Key - first successful run on RD/HQ, guess a number, gain credits or cards if number matches card cost (testing "Basic behaviour - first successful run on RD/HQ, guess a number, gain credits or cards if number matches card cost" (do-game (new-game {:corp {:deck [(qty "Enigma" 5) "Hedge Fund"]} :runner {:deck ["RNG Key" (qty "Paperclip" 2)]}}) (starting-hand state :corp ["Hedge Fund"]) (starting-hand state :runner ["RNG Key"]) (take-credits state :corp) (testing "Gain 3 credits" (play-from-hand state :runner "RNG Key") (is (= 5 (:credit (get-runner))) "Starts at 5 credits") (run-empty-server state "HQ") (click-prompt state :runner "Yes") (click-prompt state :runner "5") (click-prompt state :runner "Gain 3 [Credits]") (is (= 8 (:credit (get-runner))) "Gained 3 credits") (click-prompt state :runner "No action")) (testing "Do not trigger on second successful run" (run-empty-server state "R&D") (click-prompt state :runner "No action") (take-credits state :runner) (take-credits state :corp)) (testing "Do not trigger on archives" (run-empty-server state "Archives") (take-credits state :runner) (take-credits state :corp)) (testing "Do not get choice if trigger declined" (run-empty-server state "R&D") (click-prompt state :runner "No") (click-prompt state :runner "No action")) (run-empty-server state "R&D") (click-prompt state :runner "No action") (take-credits state :runner) (take-credits state :corp) (testing "Do not gain credits / cards if guess incorrect" (run-empty-server state "R&D") (click-prompt state :runner "Yes") (click-prompt state :runner "2") (click-prompt state :runner "No action")) (take-credits state :runner) (take-credits state :corp) (testing "Gain 2 cards" (is (zero? (count (:hand (get-runner)))) "Started with 0 cards") (run-empty-server state "R&D") (click-prompt state :runner "Yes") (click-prompt state :runner "3") (click-prompt state :runner "Draw 2 cards") (click-prompt state :runner "No action") (is (= 2 (count (:hand (get-runner)))) "Gained 2 cards") (is (zero? (count (:deck (get-runner)))) "Cards came from stack")))) (testing "Pays out when accessing an Upgrade. Issue #4804" (do-game (new-game {:corp {:deck ["Hokusai Grid" "Hedge Fund"]} :runner {:deck ["RNG Key"]}}) (play-from-hand state :corp "Hokusai Grid" "HQ") (take-credits state :corp) (play-from-hand state :runner "RNG Key") (is (= 5 (:credit (get-runner))) "Starts at 5 credits") (run-empty-server state "HQ") (click-prompt state :runner "Yes") (click-prompt state :runner "2") (click-prompt state :runner "Unrezzed upgrade") (is (= "Choose RNG Key reward" (:msg (prompt-map :runner))) "Runner gets RNG Key reward"))) (testing "Works when running a different server first #5292" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Hokusai Grid" "Hedge Fund"]} :runner {:deck ["RNG Key"]}}) (play-from-hand state :corp "Hokusai Grid" "New remote") (take-credits state :corp) (play-from-hand state :runner "RNG Key") (run-empty-server state "Server 1") (click-prompt state :runner "No action") (run-empty-server state "HQ") (click-prompt state :runner "Yes") (click-prompt state :runner "5") (is (= "Choose RNG Key reward" (:msg (prompt-map :runner))) "Runner gets RNG Key reward"))) (testing "Works after running vs Crisium Grid #3772" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Crisium Grid" "Hedge Fund"] :credits 10} :runner {:hand ["RNG Key"] :credits 10}}) (play-from-hand state :corp "Crisium Grid" "HQ") (rez state :corp (get-content state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "RNG Key") (run-empty-server state "HQ") (click-prompt state :runner "Crisium Grid") (click-prompt state :runner "Pay 5 [Credits] to trash") (click-prompt state :runner "No action") (run-empty-server state "HQ") (click-prompt state :runner "Yes") (click-prompt state :runner "5") (is (= "Choose RNG Key reward" (:msg (prompt-map :runner))) "Runner gets RNG Key reward")))) (deftest sadyojata ;; Sadyojata (testing "Swap ability" (testing "Doesnt work if no Deva in hand" (do-game (new-game {:runner {:hand ["Sadyojata" "Corroder"] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Sadyojata") (card-ability state :runner (get-program state 0) 2) (is (empty? (:prompt (get-runner))) "No select prompt as there's no Deva in hand"))) (testing "Works with another deva in hand" (doseq [deva ["<NAME>ghora" "<NAME>adyojata" "<NAME>amadeva"]] (do-game (new-game {:runner {:hand ["Sadyojata" deva] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Sadyojata") (let [installed-deva (get-program state 0)] (card-ability state :runner installed-deva 2) (click-card state :runner (first (:hand (get-runner)))) (is (not (utils/same-card? installed-deva (get-program state 0))) "Installed deva is not same as previous deva") (is (= deva (:title (get-program state 0))))))))) (testing "Break ability targets ice with 3 or more subtypes" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Executive Functioning"] :credits 10} :runner {:hand ["Sadyojata"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Executive Functioning" "R&D") (take-credits state :corp) (play-from-hand state :runner "Sadyojata") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "No break prompt") (run-jack-out state) (run-on state "R&D") (rez state :corp (get-ice state :rd 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (seq (:prompt (get-runner))) "Have a break prompt") (click-prompt state :runner "Trace 4 - Do 1 brain damage") (is (:broken (first (:subroutines (get-ice state :rd 0)))) "The break ability worked")))) (deftest sage ;; Sage (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma"] :credits 10} :runner {:deck ["Sage" "Box-E"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Enigma" "R&D") (take-credits state :corp) (play-from-hand state :runner "Sage") (let [sage (get-program state 0) iw (get-ice state :hq 0) engima (get-ice state :rd 0)] (is (= 2 (core/available-mu state))) (is (= 2 (get-strength (refresh sage))) "+2 strength for 2 unused MU") (play-from-hand state :runner "Box-E") (is (= 4 (core/available-mu state))) (is (= 4 (get-strength (refresh sage))) "+4 strength for 4 unused MU") (run-on state :hq) (rez state :corp iw) (run-continue state) (card-ability state :runner (refresh sage) 0) (click-prompt state :runner "End the run") (is (:broken (first (:subroutines (refresh iw)))) "Broke a barrier subroutine") (run-jack-out state) (run-on state :rd) (rez state :corp engima) (run-continue state) (card-ability state :runner (refresh sage) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "Done") (is (:broken (first (:subroutines (refresh engima)))) "Broke a code gate subroutine")))) (deftest sahasrara ;; Sahasrara (testing "Pay-credits prompt" (do-game (new-game {:runner {:deck ["Sahasrara" "Equivocation"]}}) (take-credits state :corp) (play-from-hand state :runner "Sahasrara") (let [rara (get-program state 0)] (changes-val-macro 0 (:credit (get-runner)) "Used 2 credits from Sahasrara" (play-from-hand state :runner "Equivocation") (click-card state :runner rara) (click-card state :runner rara)))))) (deftest savant ;; Savant (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Cobra" "Enigma"] :credits 10} :runner {:deck ["S<NAME>ant" "Box-E"] :credits 20}}) (play-from-hand state :corp "Cobra" "HQ") (play-from-hand state :corp "Enigma" "R&D") (take-credits state :corp) (play-from-hand state :runner "Savant") (let [savant (get-program state 0) cobra (get-ice state :hq 0) enigma (get-ice state :rd 0)] (is (= 2 (core/available-mu state))) (is (= 3 (get-strength (refresh savant))) "+2 strength for 2 unused MU") (play-from-hand state :runner "Box-E") (is (= 4 (core/available-mu state))) (is (= 5 (get-strength (refresh savant))) "+4 strength for 4 unused MU") (run-on state :hq) (rez state :corp cobra) (run-continue state) (card-ability state :runner (refresh savant) 0) (click-prompt state :runner "Trash a program") (click-prompt state :runner "Done") (is (:broken (first (:subroutines (refresh cobra)))) "Broke a sentry subroutine") (run-jack-out state) (run-on state :rd) (rez state :corp enigma) (run-continue state) (card-ability state :runner (refresh savant) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (is (:broken (first (:subroutines (refresh enigma)))) "Broke a code gate subroutine")))) (deftest scheherazade ;; Scheherazade - Gain 1 credit when it hosts a program (do-game (new-game {:runner {:deck ["Scheherazade" "Cache" "Inti" "Fall Guy"]}}) (take-credits state :corp) (play-from-hand state :runner "Scheherazade") (let [sch (get-program state 0)] (card-ability state :runner sch 0) (click-card state :runner (find-card "Inti" (:hand (get-runner)))) (is (= 1 (count (:hosted (refresh sch))))) (is (= 2 (:click (get-runner))) "Spent 1 click to install and host") (is (= 6 (:credit (get-runner))) "Gained 1 credit") (is (= 3 (core/available-mu state)) "Programs hosted on Scheh consume MU") (card-ability state :runner sch 0) (click-card state :runner (find-card "Cache" (:hand (get-runner)))) (is (= 2 (count (:hosted (refresh sch))))) (is (= 6 (:credit (get-runner))) "Gained 1 credit") (card-ability state :runner sch 0) (click-card state :runner (find-card "Fall Guy" (:hand (get-runner)))) (is (= 2 (count (:hosted (refresh sch)))) "Can't host non-program") (is (= 1 (count (:hand (get-runner)))))))) (deftest self-modifying-code ;; Trash & pay 2 to search deck for a program and install it. Shuffle. (testing "Trash & pay 2 to search deck for a program and install it. Shuffle" (do-game (new-game {:runner {:deck [(qty "Self-modifying Code" 3) "Reaver"]}}) (starting-hand state :runner ["Self-modifying Code" "Self-modifying Code"]) (core/gain state :runner :credit 5) (take-credits state :corp) (play-from-hand state :runner "Self-modifying Code") (play-from-hand state :runner "Self-modifying Code") (let [smc1 (get-program state 0) smc2 (get-program state 1)] (card-ability state :runner smc1 0) (click-prompt state :runner (find-card "Reaver" (:deck (get-runner)))) (is (= 6 (:credit (get-runner))) "Paid 2 for SMC, 2 for install - 6 credits left") (is (= 1 (core/available-mu state)) "SMC MU refunded") (take-credits state :runner) (take-credits state :corp) (card-ability state :runner smc2 0) (is (= 1 (count (:hand (get-runner)))) "1 card drawn due to Reaver before SMC program selection") (is (zero? (count (:deck (get-runner)))) "Deck empty")))) (testing "Pay for SMC with Multithreader. Issue #4961" (do-game (new-game {:runner {:deck [(qty "Self-modifying Code" 3) "Rezeki"] :hand ["Self-modifying Code" "Multithreader"]}}) (take-credits state :corp) (play-from-hand state :runner "Self-modifying Code") (play-from-hand state :runner "Multithreader") (let [smc (get-program state 0) multi (get-program state 1)] (card-ability state :runner smc 0) (click-card state :runner multi) (click-card state :runner multi) (click-prompt state :runner (find-card "Rezeki" (:deck (get-runner)))) (is (= "Rezeki" (:title (get-program state 1))) "Rezeki is installed") (is (= 0 (:credit (get-runner))) "Runner had 2 credits before SMC, paid 2 for SMC from Multithreader, 2 for Rezeki install - 0 credits left"))))) (deftest shiv ;; Shiv - Gain 1 strength for each installed breaker; no MU cost when 2+ link (do-game (new-game {:runner {:id "<NAME>: Cyber Explorer" :deck ["Shiv" (qty "Inti" 2) "Access to Globalsec"]}}) (is (= 1 (get-link state)) "1 link") (take-credits state :corp) (play-from-hand state :runner "Shiv") (let [shiv (get-program state 0)] (is (= 1 (get-strength (refresh shiv))) "1 installed breaker; 1 strength") (play-from-hand state :runner "Inti") (is (= 2 (get-strength (refresh shiv))) "2 installed breakers; 2 strength") (play-from-hand state :runner "Inti") (is (= 3 (get-strength (refresh shiv))) "3 installed breakers; 3 strength") (is (= 1 (core/available-mu state)) "3 MU consumed") (play-from-hand state :runner "Access to Globalsec") (is (= 2 (get-link state)) "2 link") (is (= 2 (core/available-mu state)) "Shiv stops using MU when 2+ link")))) (deftest sneakdoor-beta (testing "<NAME>, Ash on HQ should prevent Sneakdoor HQ access but still give Gabe credits. Issue #1138." (do-game (new-game {:corp {:deck ["Ash 2X3ZB9CY"]} :runner {:id "<NAME>: Consummate Professional" :deck ["Sneakdoor Beta"]}}) (play-from-hand state :corp "Ash 2X3ZB9CY" "HQ") (take-credits state :corp) (play-from-hand state :runner "Sneakdoor Beta") (is (= 1 (:credit (get-runner))) "Sneakdoor cost 4 credits") (let [sb (get-program state 0) ash (get-content state :hq 0)] (rez state :corp ash) (card-ability state :runner sb 0) (run-continue state) (click-prompt state :corp "0") (click-prompt state :runner "0") (is (= 3 (:credit (get-runner))) "Gained 2 credits from Gabe's ability") (is (= (:cid ash) (-> (prompt-map :runner) :card :cid)) "Ash interrupted HQ access after Sneakdoor run") (is (= :hq (-> (get-runner) :register :successful-run first)) "Successful Run on HQ recorded")))) (testing "do not switch to HQ if Archives has Crisium Grid. Issue #1229." (do-game (new-game {:corp {:deck ["Crisium Grid" "Priority Requisition" "Private Security Force"]} :runner {:deck ["Sneakdoor Beta"]}}) (play-from-hand state :corp "Crisium Grid" "Archives") (trash-from-hand state :corp "Priority Requisition") (take-credits state :corp) (play-from-hand state :runner "Sneakdoor Beta") (let [sb (get-program state 0) cr (get-content state :archives 0)] (rez state :corp cr) (card-ability state :runner sb 0) (run-continue state) (is (= :archives (get-in @state [:run :server 0])) "Crisium Grid stopped Sneakdoor Beta from switching to HQ")))) (testing "Allow Nerve Agent to gain counters. Issue #1158/#955" (do-game (new-game {:runner {:deck ["Sneakdoor Beta" "Nerve Agent"]}}) (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Nerve Agent") (play-from-hand state :runner "Sneakdoor Beta") (let [nerve (get-program state 0) sb (get-program state 1)] (card-ability state :runner sb 0) (run-continue state) (click-prompt state :runner "No action") (is (= 1 (get-counters (refresh nerve) :virus))) (card-ability state :runner sb 0) (run-continue state) (is (= 2 (get-counters (refresh nerve) :virus)))))) (testing "Grant Security Testing credits on HQ." (do-game (new-game {:runner {:deck ["Security Testing" "Sneakdoor Beta"]}}) (take-credits state :corp) (play-from-hand state :runner "Sneakdoor Beta") (play-from-hand state :runner "Security Testing") (take-credits state :runner) (is (= 3 (:credit (get-runner)))) (take-credits state :corp) (let [sb (get-program state 0)] (click-prompt state :runner "HQ") (card-ability state :runner sb 0) (run-continue state) (is (not (:run @state)) "Switched to HQ and ended the run from Security Testing") (is (= 5 (:credit (get-runner))) "Sneakdoor switched to HQ and earned Security Testing credits")))) (testing "Sneakdoor Beta trashed during run" (do-game (new-game {:runner {:hand ["Sneakdoor Beta"]} :corp {:hand ["Ichi 1.0" "Hedge Fund"]}}) (play-from-hand state :corp "Ichi 1.0" "Archives") (let [ichi (get-ice state :archives 0)] (rez state :corp ichi) (take-credits state :corp) (play-from-hand state :runner "Sneakdoor Beta") (let [sb (get-program state 0)] (card-ability state :runner sb 0) (run-continue state) (fire-subs state (refresh ichi)) (is (= :select (prompt-type :corp)) "Corp has a prompt to select program to delete") (click-card state :corp "Sneakdoor Beta") (click-prompt state :corp "Done") (is (= "Sneakdoor Beta" (-> (get-runner) :discard first :title)) "Sneakdoor was trashed") (click-prompt state :corp "0") (click-prompt state :runner "1") (run-continue state) (run-continue state) (is (= :hq (get-in @state [:run :server 0])) "Run continues on HQ"))))) (testing "Sneakdoor Beta effect ends at end of run" (do-game (new-game {:runner {:hand ["Sneakdoor Beta"]} :corp {:hand ["Rototurret" "Hedge Fund"] :discard ["Hedge Fund"]}}) (play-from-hand state :corp "Rototurret" "Archives") (let [roto (get-ice state :archives 0)] (rez state :corp roto) (take-credits state :corp) (play-from-hand state :runner "Sneakdoor Beta") (let [sb (get-program state 0)] (card-ability state :runner sb 0) (run-continue state) (fire-subs state (refresh roto)) (is (= :select (prompt-type :corp)) "Corp has a prompt to select program to delete") (click-card state :corp "Sneakdoor Beta") (is (= "Sneakdoor Beta" (-> (get-runner) :discard first :title)) "Sneakdoor was trashed") (run-on state "Archives") (run-continue state) (run-continue state) (is (= :approach-server (:phase (get-run))) "Run has bypassed Rototurret") (is (= :archives (get-in @state [:run :server 0])) "Run continues on Archives")))))) (deftest snitch ;; Snitch (testing "Only works on rezzed ice" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Quandary"]} :runner {:deck ["Snitch"]}}) (play-from-hand state :corp "Quandary" "R&D") (take-credits state :corp) (play-from-hand state :runner "Snitch") (let [snitch (get-program state 0)] (run-on state "R&D") (is (prompt-is-card? state :runner snitch) "Option to expose") (is (= "Use Snitch to expose approached ice?" (:msg (prompt-map :runner)))) (click-prompt state :runner "Yes") (is (= "Jack out?" (:msg (prompt-map :runner)))) (click-prompt state :runner "Yes")))) (testing "Doesn't work if ice is rezzed" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Quandary"]} :runner {:deck ["Snitch"]}}) (play-from-hand state :corp "Quandary" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Snitch") (run-on state "HQ") (is (empty? (:prompt (get-runner))) "No option to jack out") (run-continue state) (run-jack-out state))) (testing "Doesn't work if there is no ice" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Hedge Fund"]} :runner {:deck ["Snitch"]}}) (take-credits state :corp) (play-from-hand state :runner "Snitch") (run-on state "Archives") (is (empty? (:prompt (get-runner))) "No option to jack out") (run-continue state)))) (deftest snowball (testing "Strength boost until end of run when used to break a subroutine" (do-game (new-game {:corp {:deck ["Spiderweb" "Fire Wall" "Hedge Fund"] :credits 20} :runner {:deck ["Snowball"]}}) (play-from-hand state :corp "Hedge Fund") (play-from-hand state :corp "Fire Wall" "HQ") (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (core/gain state :corp :credit 1) (play-from-hand state :runner "Snowball") (let [sp (get-ice state :hq 1) fw (get-ice state :hq 0) snow (get-program state 0)] (run-on state "HQ") (rez state :corp sp) (run-continue state) (card-ability state :runner snow 1) ; match strength (is (= 2 (get-strength (refresh snow)))) (card-ability state :runner snow 0) ; strength matched, break a sub (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (is (= 5 (get-strength (refresh snow))) "Broke 3 subs, gained 3 more strength") (run-continue state) (rez state :corp fw) (run-continue state) (is (= 4 (get-strength (refresh snow))) "Has +3 strength until end of run; lost 1 per-encounter boost") (card-ability state :runner snow 1) ; match strength (is (= 5 (get-strength (refresh snow))) "Matched strength, gained 1") (card-ability state :runner snow 0) ; strength matched, break a sub (click-prompt state :runner "End the run") (is (= 6 (get-strength (refresh snow))) "Broke 1 sub, gained 1 more strength") (run-continue state) (is (= 5 (get-strength (refresh snow))) "+4 until-end-of-run strength") (run-jack-out state) (is (= 1 (get-strength (refresh snow))) "Back to default strength")))) (testing "Strength boost until end of run when using dynamic auto-pump-and-break ability" (do-game (new-game {:corp {:deck ["Spiderweb" (qty "Hedge Fund" 2)]} :runner {:deck ["Snowball"]}}) (play-from-hand state :corp "Hedge Fund") (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Snowball") (let [sp (get-ice state :hq 0) snow (get-program state 0)] (run-on state "HQ") (rez state :corp sp) (run-continue state) (is (= 1 (get-strength (refresh snow))) "Snowball starts at 1 strength") (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh snow)}) (is (= 5 (get-strength (refresh snow))) "Snowball was pumped once and gained 3 strength from breaking") (core/process-action "continue" state :corp nil) (is (= 4 (get-strength (refresh snow))) "+3 until-end-of-run strength"))))) (deftest stargate ;; Stargate - once per turn Keyhole which doesn't shuffle (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 10)] :hand ["Herald" "Troll"]} :runner {:deck ["Stargate"]}}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (is (= "Troll" (-> (get-corp) :deck first :title)) "Troll on top of deck") (is (= "Herald" (-> (get-corp) :deck second :title)) "Herald 2nd") (take-credits state :corp) (play-from-hand state :runner "Stargate") (card-ability state :runner (get-program state 0) 0) (is (:run @state) "Run initiated") (run-continue state) (click-prompt state :runner "Troll") (is (empty? (:prompt (get-runner))) "Prompt closed") (is (not (:run @state)) "Run ended") (is (-> (get-corp) :discard first :seen) "Troll is faceup") (is (= "Troll" (-> (get-corp) :discard first :title)) "Troll was trashed") (is (= "Herald" (-> (get-corp) :deck first :title)) "Herald now on top of R&D") (card-ability state :runner (get-program state 0) 0) (is (not (:run @state)) "No run ended, as Stargate is once per turn"))) (testing "Different message on repeating cards" (testing "bottom card" (do-game (new-game {:corp {:deck [(qty "Troll" 10)] :hand ["Herald" "Troll"]} :runner {:deck ["Stargate"]}}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (is (= "Troll" (-> (get-corp) :deck first :title)) "Troll 1st") (is (= "Herald" (-> (get-corp) :deck second :title)) "Herald 2nd") (is (= "Troll" (-> (get-corp) :deck (#(nth % 2)) :title)) "Another Troll 3rd") (take-credits state :corp) (play-from-hand state :runner "Stargate") (card-ability state :runner (get-program state 0) 0) (run-continue state) (click-prompt state :runner (nth (prompt-buttons :runner) 2)) (is (last-log-contains? state "Runner uses Stargate to trash bottom Troll.") "Correct log"))) (testing "middle card" (do-game (new-game {:corp {:deck [(qty "Troll" 10)] :hand ["Herald" "Troll"]} :runner {:deck ["Stargate"]}}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (is (= "Herald" (-> (get-corp) :deck first :title)) "Herald 1st") (is (= "Troll" (-> (get-corp) :deck second :title)) "Troll 2nd") (is (= "Troll" (-> (get-corp) :deck (#(nth % 2)) :title)) "Another Troll 3rd") (take-credits state :corp) (play-from-hand state :runner "Stargate") (card-ability state :runner (get-program state 0) 0) (run-continue state) (click-prompt state :runner (second (prompt-buttons :runner))) (is (last-log-contains? state "Runner uses Stargate to trash middle Troll.") "Correct log"))) (testing "top card" (do-game (new-game {:corp {:deck [(qty "Troll" 10)] :hand ["Herald" "Troll"]} :runner {:deck ["Stargate"]}}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (is (= "Troll" (-> (get-corp) :deck first :title)) "Troll 1st") (is (= "Herald" (-> (get-corp) :deck second :title)) "Herald 2nd") (is (= "Troll" (-> (get-corp) :deck (#(nth % 2)) :title)) "Another Troll 3rd") (take-credits state :corp) (play-from-hand state :runner "Stargate") (card-ability state :runner (get-program state 0) 0) (run-continue state) (click-prompt state :runner (first (prompt-buttons :runner))) (is (last-log-contains? state "Runner uses Stargate to trash top Troll.") "Correct log")))) (testing "No position indicator if non-duplicate selected" (do-game (new-game {:corp {:deck [(qty "Troll" 10)] :hand ["Herald" "Troll"]} :runner {:deck ["Stargate"]}}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (is (= "Troll" (-> (get-corp) :deck first :title)) "Troll 1st") (is (= "Herald" (-> (get-corp) :deck second :title)) "Herald 2nd") (is (= "Troll" (-> (get-corp) :deck (#(nth % 2)) :title)) "Another Troll 3rd") (take-credits state :corp) (play-from-hand state :runner "Stargate") (card-ability state :runner (get-program state 0) 0) (run-continue state) (click-prompt state :runner (second (prompt-buttons :runner))) (is (last-log-contains? state "Runner uses Stargate to trash Herald.") "Correct log")))) (deftest study-guide ;; Study Guide - 2c to add a power counter; +1 strength per counter (do-game (new-game {:runner {:deck ["Study Guide" "Sure Gamble"]}}) (take-credits state :corp) (play-from-hand state :runner "Sure Gamble") (play-from-hand state :runner "Study Guide") (let [sg (get-program state 0)] (card-ability state :runner sg 1) (is (= 4 (:credit (get-runner))) "Paid 2c") (is (= 1 (get-counters (refresh sg) :power)) "Has 1 power counter") (is (= 1 (get-strength (refresh sg))) "1 strength") (card-ability state :runner sg 1) (is (= 2 (:credit (get-runner))) "Paid 2c") (is (= 2 (get-counters (refresh sg) :power)) "Has 2 power counters") (is (= 2 (get-strength (refresh sg))) "2 strength")))) (deftest sunya ;; Sūnya (testing "Basic test" (do-game (new-game {:runner {:deck ["Sūnya"]} :corp {:deck ["Rototurret"]}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Sūnya") (let [sunya (get-program state 0) roto (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh roto)) (run-continue state) (card-ability state :runner (refresh sunya) 0) (click-prompt state :runner "Trash a program") (click-prompt state :runner "End the run") (changes-val-macro 1 (get-counters (refresh sunya) :power) "Got 1 token" (run-continue state)))))) (deftest surfer ;; Surfer - Swap position with ice before or after when encountering a Barrier ICE (testing "Basic test" (do-game (new-game {:corp {:deck ["Ice Wall" "Quandary"]} :runner {:deck ["Surfer"]}}) (play-from-hand state :corp "Quandary" "HQ") (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Surfer") (is (= 3 (:credit (get-runner))) "Paid 2 credits to install Surfer") (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (run-continue state) (is (= 2 (get-in @state [:run :position])) "Starting run at position 2") (let [surf (get-program state 0)] (card-ability state :runner surf 0) (click-card state :runner (get-ice state :hq 0)) (is (= 1 (:credit (get-runner))) "Paid 2 credits to use Surfer") (is (= 1 (get-in @state [:run :position])) "Now at next position (1)") (is (= "Ice Wall" (:title (get-ice state :hq 0))) "Ice Wall now at position 1")))) (testing "Swapping twice across two turns" (do-game (new-game {:corp {:deck ["Ice Wall" "Vanilla"]} :runner {:deck ["Surfer"] :credits 10}}) (play-from-hand state :corp "Vanilla" "HQ") (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Surfer") (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (run-continue state) (let [surf (get-program state 0)] (card-ability state :runner surf 0) (click-card state :runner (get-ice state :hq 0)) (run-jack-out state) (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (run-continue state) (card-ability state :runner surf 0) (click-card state :runner (get-ice state :hq 0)) (is (= ["Vanilla" "Ice Wall"] (map :title (get-ice state :hq))) "Vanilla is innermost, Ice Wall is outermost again") (is (= [0 1] (map :index (get-ice state :hq)))))))) (deftest takobi ;; Takobi - 2 power counter to add +3 strength to a non-AI icebreaker for encounter (testing "+1 counter when breaking all subs" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma"]} :runner {:hand ["Takobi" "Corroder" "Gordian Blade"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Takobi") (play-from-hand state :runner "Corroder") (play-from-hand state :runner "<NAME>") (let [tako (get-program state 0) corr (get-program state 1) gord (get-program state 2) enig (get-ice state :hq 1) icew (get-ice state :hq 0)] (run-on state "HQ") (rez state :corp enig) (run-continue state) (card-ability state :runner gord 0) (click-prompt state :runner "End the run") (click-prompt state :runner "Done") (is (empty? (:prompt (get-runner))) "No prompt because not all subs were broken") (is (= 0 (get-counters (refresh tako) :power)) "No counter gained because not all subs were broken") (run-continue state) (rez state :corp icew) (run-continue state) (card-ability state :runner corr 0) (click-prompt state :runner "End the run") (click-prompt state :runner "Yes") (run-continue state) (is (= 1 (get-counters (refresh tako) :power)) "Counter gained from breaking all subs")))) (testing "+3 strength" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Takobi" "Corroder" "Faust"] :credits 10}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Takobi") (play-from-hand state :runner "Corroder") (play-from-hand state :runner "Faust") (let [tako (get-program state 0) corr (get-program state 1) faus (get-program state 2)] (core/add-counter state :runner tako :power 3) (is (= 3 (get-counters (refresh tako) :power)) "3 counters on Takobi") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner tako 0) (click-card state :runner (refresh faus)) (is (not-empty (:prompt (get-runner))) "Can't select AI breakers") (click-card state :runner (refresh corr)) (is (empty? (:prompt (get-runner))) "Can select non-AI breakers") (is (= 5 (get-strength (refresh corr))) "Corroder at +3 strength") (is (= 1 (get-counters (refresh tako) :power)) "1 counter on Takobi") (card-ability state :runner tako 0) (is (empty? (:prompt (get-runner))) "No prompt when too few power counters") (run-continue state) (run-continue state) (is (= 2 (get-strength (refresh corr))) "Corroder returned to normal strength"))))) (deftest tranquilizer ;; Tranquilizer (testing "Basic test" (do-game (new-game {:corp {:hand ["Ice Wall"] :deck [(qty "Hedge Fund" 10)]} :runner {:hand ["Tranquilizer"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Tranquilizer") (click-card state :runner (get-ice state :hq 0)) (let [iw (get-ice state :hq 0) tranquilizer (first (:hosted (refresh iw)))] (is (= 1 (get-counters (refresh tranquilizer) :virus))) (take-credits state :runner) (rez state :corp iw) (take-credits state :corp) (is (= 2 (get-counters (refresh tranquilizer) :virus))) (take-credits state :runner) (take-credits state :corp) (is (= 3 (get-counters (refresh tranquilizer) :virus))) (is (not (rezzed? (refresh iw))) "Ice Wall derezzed") (take-credits state :runner) (rez state :corp iw) (take-credits state :corp) (is (= 4 (get-counters (refresh tranquilizer) :virus))) (is (not (rezzed? (refresh iw))) "Ice Wall derezzed again")))) (testing "Derez on install" (do-game (new-game {:corp {:hand ["Ice Wall"] :deck [(qty "Hedge Fund" 10)]} :runner {:hand ["Tranquilizer" "Hivemind" "Surge"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Hivemind") (let [iw (get-ice state :hq 0) hive (get-program state 0)] (is (= 1 (get-counters (refresh hive) :virus)) "Hivemind starts with 1 virus counter") (play-from-hand state :runner "Surge") (click-card state :runner (refresh hive)) (is (= 3 (get-counters (refresh hive) :virus)) "Hivemind gains 2 virus counters") (rez state :corp iw) (is (rezzed? (refresh iw)) "Ice Wall rezzed") (play-from-hand state :runner "Tranquilizer") (click-card state :runner (get-ice state :hq 0)) (let [tranquilizer (first (:hosted (refresh iw)))] (is (= 1 (get-counters (refresh tranquilizer) :virus))) (is (not (rezzed? (refresh iw))) "Ice Wall derezzed")))))) (deftest trope ;; Trope (testing "Happy Path" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)]} :runner {:hand ["Trope" "Easy Mark"] :discard ["Sure Gamble" "Easy Mark" "Dirty Laundry"]}}) (take-credits state :corp) (play-from-hand state :runner "Trope") ;; wait 3 turns to make Trope have 3 counters (dotimes [n 3] (take-credits state :runner) (take-credits state :corp)) (is (= 3 (get-counters (refresh (get-program state 0)) :power))) (is (zero? (count (:deck (get-runner)))) "0 cards in deck") (is (= 3 (count (:discard (get-runner)))) "3 cards in discard") (card-ability state :runner (get-program state 0) 0) (is (not (empty? (:prompt (get-runner)))) "Shuffle prompt came up") (click-card state :runner (find-card "Easy Mark" (:discard (get-runner)))) (click-card state :runner (find-card "Dirty Laundry" (:discard (get-runner)))) (click-card state :runner (find-card "Sure Gamble" (:discard (get-runner)))) (is (= 3 (count (:deck (get-runner)))) "3 cards in deck") (is (zero? (count (:discard (get-runner)))) "0 cards in discard"))) (testing "Heap Locked" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Blacklist"]} :runner {:hand ["Trope" "Easy Mark"] :discard ["Sure Gamble" "Easy Mark" "Dirty Laundry"]}}) (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (refresh (get-content state :remote1 0))) (take-credits state :corp) (play-from-hand state :runner "Trope") ;; wait 3 turns to make Trope have 3 counters (dotimes [n 3] (take-credits state :runner) (take-credits state :corp)) (is (= 3 (get-counters (refresh (get-program state 0)) :power))) (is (zero? (count (:deck (get-runner)))) "0 cards in deck") (is (= 3 (count (:discard (get-runner)))) "3 cards in discard") (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Shuffle prompt did not come up")))) (deftest trypano (testing "Hivemind and Architect interactions" (do-game (new-game {:corp {:deck [(qty "Architect" 2)]} :runner {:deck [(qty "Trypano" 2) "Hivemind"]}}) (play-from-hand state :corp "Architect" "HQ") (play-from-hand state :corp "Architect" "R&D") (let [architect-rezzed (get-ice state :hq 0) architect-unrezzed (get-ice state :rd 0)] (rez state :corp architect-rezzed) (take-credits state :corp) (play-from-hand state :runner "<NAME>") (click-card state :runner (get-card state architect-rezzed)) (play-from-hand state :runner "<NAME>") (click-card state :runner architect-unrezzed) (is (= 2 (core/available-mu state)) "Trypano consumes 1 MU")) ;; wait 4 turns to make both Trypanos have 4 counters on them (dotimes [n 4] (take-credits state :runner) (take-credits state :corp) (click-prompt state :runner "Yes") (click-prompt state :runner "Yes")) (is (zero? (count (:discard (get-runner)))) "Trypano not in discard yet") (is (= 1 (count (get-in @state [:corp :servers :rd :ices]))) "Unrezzed Archiect is not trashed") (is (= 1 (count (get-in @state [:corp :servers :hq :ices]))) "Rezzed Archiect is not trashed") (play-from-hand state :runner "Hivemind") ; now Hivemind makes both Trypanos have 5 counters (is (zero? (count (get-in @state [:corp :servers :rd :ices]))) "Unrezzed Archiect was trashed") (is (= 1 (count (get-in @state [:corp :servers :hq :ices]))) "Rezzed Archiect was not trashed") (is (= 1 (count (:discard (get-runner)))) "Trypano went to discard"))) (testing "Fire when Hivemind gains counters" (do-game (new-game {:corp {:deck ["Architect"]} :runner {:deck ["Tr<NAME>" "Hivemind" (qty "Surge" 2)]}}) (play-from-hand state :corp "Architect" "R&D") (let [architect-unrezzed (get-ice state :rd 0)] (take-credits state :corp) (play-from-hand state :runner "Trypano") (click-card state :runner architect-unrezzed) (is (zero? (count (:discard (get-runner)))) "Trypano not in discard yet") (is (= 1 (count (get-ice state :rd))) "Unrezzed Architect is not trashed") (play-from-hand state :runner "Hivemind") (let [hive (get-program state 0)] (is (= 1 (get-counters (refresh hive) :virus)) "Hivemind starts with 1 virus counter") (play-from-hand state :runner "Surge") (click-card state :runner (refresh hive)) (is (= 3 (get-counters (refresh hive) :virus)) "Hivemind gains 2 virus counters") (play-from-hand state :runner "Surge") (click-card state :runner (refresh hive)) (is (= 5 (get-counters (refresh hive) :virus)) "Hivemind gains 2 virus counters (now at 5)") (is (zero? (count (get-ice state :rd))) "Unrezzed Architect was trashed") (is (= 3 (count (:discard (get-runner)))) "Trypano went to discard")))))) (deftest tycoon ;; Tycoon (testing "Tycoon gives 2c after using to break ICE" (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["Tycoon"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Ty<NAME>") (let [tycoon (get-program state 0) credits (:credit (get-corp))] (run-on state "HQ") (run-continue state) (card-ability state :runner tycoon 0) (click-prompt state :runner "End the run") (card-ability state :runner tycoon 1) (is (= 4 (get-strength (refresh tycoon))) "Tycoon strength pumped to 4.") (is (= credits (:credit (get-corp))) "Corp doesn't gain credits until encounter is over") (run-continue state) (is (= (+ credits 2) (:credit (get-corp))) "Corp gains 2 credits from Tycoon being used") (is (= 1 (get-strength (refresh tycoon))) "Tycoon strength back down to 1.")))) ;; Issue #4220: Tycoon doesn't fire if Corp ends run before ice is passed (testing "Tycoon gives 2c even if ICE wasn't passed" (do-game (new-game {:corp {:deck ["Ice Wall" "Nisei MK II"]} :runner {:deck ["Tycoon"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (rez state :corp (get-ice state :hq 0)) (play-and-score state "Nisei MK II") (take-credits state :corp) (play-from-hand state :runner "Ty<NAME>") (let [tycoon (get-program state 0) credits (:credit (get-corp)) nisei (get-scored state :corp 0)] (run-on state "HQ") (run-continue state) (card-ability state :runner tycoon 0) (click-prompt state :runner "End the run") (card-ability state :runner tycoon 1) (is (= 4 (get-strength (refresh tycoon))) "Tycoon strength pumped to 4.") (is (= credits (:credit (get-corp))) "Corp doesn't gain credits until encounter is over") (card-ability state :corp (refresh nisei) 0) (is (= (+ credits 2) (:credit (get-corp))) "Corp gains 2 credits from Tycoon being used after Nisei MK II fires") (is (= 1 (get-strength (refresh tycoon))) "Tycoon strength back down to 1.")))) ;; Issue #4423: Tycoon no longer working automatically (testing "Tycoon pays out on auto-pump-and-break" (do-game (new-game {:corp {:deck ["<NAME> 1.0"]} :runner {:deck ["Tycoon"]}}) (play-from-hand state :corp "<NAME> 1.0" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Tycoon") (let [tycoon (get-program state 0) credits (:credit (get-corp))] (run-on state "HQ") (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh tycoon)}) (is (= credits (:credit (get-corp))) "Corp doesn't gain credits until encounter is over") (core/continue state :corp nil) (is (= (+ credits 2) (:credit (get-corp))) "Corp gains 2 credits from Tycoon being used"))))) (deftest unity ;; Unity (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Afshar"] :credits 20} :runner {:deck ["Unity"] :credits 20}}) (play-from-hand state :corp "<NAME>" "R&D") (rez state :corp (get-ice state :rd 0)) (take-credits state :corp) (play-from-hand state :runner "Unity") (let [unity (get-program state 0) ice (get-ice state :rd 0)] (run-on state :rd) (run-continue state) (is (= 17 (:credit (get-runner))) "17 credits before breaking") (card-ability state :runner unity 1) ;;temp boost because EDN file (card-ability state :runner unity 0) (click-prompt state :runner "Make the Runner lose 2 [Credits]") (card-ability state :runner unity 0) (click-prompt state :runner "End the run") (is (= 14 (:credit (get-runner))) "14 credits after breaking") (is (zero? (count (remove :broken (:subroutines (refresh ice))))) "All subroutines have been broken")))) (testing "Boost test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["DNA Tracker"] :credits 20} :runner {:deck [(qty "Unity" 3)] :credits 20}}) (play-from-hand state :corp "DNA Tracker" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Unity") (play-from-hand state :runner "Unity") (play-from-hand state :runner "Unity") (let [unity (get-program state 0) ice (get-ice state :hq 0)] (run-on state :hq) (run-continue state) (is (= 11 (:credit (get-runner))) "11 credits before breaking") (card-ability state :runner unity 1) (card-ability state :runner unity 1) (card-ability state :runner unity 0) (click-prompt state :runner "Do 1 net damage and make the Runner lose 2 [Credits]") (card-ability state :runner unity 0) (click-prompt state :runner "Do 1 net damage and make the Runner lose 2 [Credits]") (card-ability state :runner unity 0) (click-prompt state :runner "Do 1 net damage and make the Runner lose 2 [Credits]") (is (= 6 (:credit (get-runner))) "6 credits after breaking") (is (zero? (count (remove :broken (:subroutines (refresh ice))))) "All subroutines have been broken"))))) (deftest upya (do-game (new-game {:runner {:deck ["Upya"]}}) (take-credits state :corp) (play-from-hand state :runner "Upya") (dotimes [_ 3] (run-empty-server state "R&D")) (is (= 3 (get-counters (get-program state 0) :power)) "3 counters on Upya") (take-credits state :corp) (dotimes [_ 3] (run-empty-server state "R&D")) (is (= 6 (get-counters (get-program state 0) :power)) "6 counters on Upya") (let [upya (get-program state 0)] (card-ability state :runner upya 0) (is (= 3 (get-counters (refresh upya) :power)) "3 counters spent") (is (= 2 (:click (get-runner))) "Gained 2 clicks") (card-ability state :runner upya 0) (is (= 3 (get-counters (refresh upya) :power)) "Upya not used more than once a turn") (is (= 2 (:click (get-runner))) "Still at 2 clicks")) (take-credits state :runner) (take-credits state :corp) (let [upya (get-program state 0)] (card-ability state :runner upya 0) (is (zero? (get-counters (refresh upya) :power)) "3 counters spent") (is (= 5 (:click (get-runner))) "Gained 2 clicks")))) (deftest utae ;; Utae (do-game (new-game {:corp {:deck ["Enigma"]} :runner {:deck ["Utae" (qty "Logic Bomb" 3)] :credits 10}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Utae") (let [utae (get-program state 0)] (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (let [credits (:credit (get-runner))] (card-ability state :runner utae 2) (is (= (dec credits) (:credit (get-runner))) "Spent 1 credit")) (let [credits (:credit (get-runner))] (card-ability state :runner utae 0) (click-prompt state :runner "2") (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (is (= (- credits 2) (:credit (get-runner))) "Spent 2 credits")) (let [credits (:credit (get-runner))] (card-ability state :runner utae 0) (is (empty? (:prompt (get-runner))) "Can only use ability once per run") (card-ability state :runner utae 1) (is (= credits (:credit (get-runner))) "Cannot use this ability without 3 installed virtual resources")) (run-jack-out state) (core/gain state :runner :click 2) (dotimes [_ 3] (play-from-hand state :runner "Logic Bomb")) (run-on state "HQ") (run-continue state) (card-ability state :runner utae 2) (let [credits (:credit (get-runner))] (card-ability state :runner utae 1) (click-prompt state :runner "End the run") (click-prompt state :runner "Done") (is (= (dec credits) (:credit (get-runner))))) (is (= 3 (:credit (get-runner))) "Able to use ability now")))) (deftest vamadeva ;; Vamadeva (testing "Swap ability" (testing "Doesnt work if no Deva in hand" (do-game (new-game {:runner {:hand ["Vamadeva" "Corroder"] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "V<NAME>") (card-ability state :runner (get-program state 0) 2) (is (empty? (:prompt (get-runner))) "No select prompt as there's no Deva in hand"))) (testing "Works with another deva in hand" (doseq [deva ["<NAME>" "<NAME>" "<NAME>"]] (do-game (new-game {:runner {:hand ["Vamadeva" deva] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Vamadeva") (let [installed-deva (get-program state 0)] (card-ability state :runner installed-deva 2) (click-card state :runner (first (:hand (get-runner)))) (is (not (utils/same-card? installed-deva (get-program state 0))) "Installed deva is not same as previous deva") (is (= deva (:title (get-program state 0))))))))) (testing "Break ability targets ice with 1 subroutine" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma" "Ice Wall"] :credits 10} :runner {:hand ["Vamadeva"] :credits 10}}) (play-from-hand state :corp "Enigma" "HQ") (play-from-hand state :corp "Ice Wall" "R&D") (take-credits state :corp) (play-from-hand state :runner "Vamadeva") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "No break prompt") (run-jack-out state) (run-on state "R&D") (rez state :corp (get-ice state :rd 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (seq (:prompt (get-runner))) "Have a break prompt") (click-prompt state :runner "End the run") (is (:broken (first (:subroutines (get-ice state :rd 0)))) "The break ability worked")))) (deftest wari (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["<NAME>ari"]}}) (play-from-hand state :corp "Ice Wall" "R&D") (take-credits state :corp) (play-from-hand state :runner "<NAME>ari") (run-empty-server state "HQ") (click-prompt state :runner "Yes") (click-prompt state :runner "Barrier") (click-card state :runner (get-ice state :rd 0)) (is (= 1 (count (:discard (get-runner)))) "Wari in heap") (is (seq (:prompt (get-runner))) "Runner is currently accessing Ice Wall"))) (deftest wyrm ;; Wyrm reduces strength of ice (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["Wyrm"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Wyrm") (run-on state "HQ") (let [ice-wall (get-ice state :hq 0) wyrm (get-program state 0)] (rez state :corp ice-wall) (run-continue state) (card-ability state :runner wyrm 1) (is (zero? (get-strength (refresh ice-wall))) "Strength of Ice Wall reduced to 0") (card-ability state :runner wyrm 1) (is (= -1 (get-strength (refresh ice-wall))) "Strength of Ice Wall reduced to -1")))) (deftest yusuf ;; Yusuf gains virus counters on successful runs and can spend virus counters from any installed card (testing "Yusuf basic tests" (do-game (new-game {:corp {:deck ["Fire Wall"]} :runner {:deck ["Yusuf" "Cache"]}}) (play-from-hand state :corp "Fire Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Yusuf") (play-from-hand state :runner "Cache") (let [fire-wall (get-ice state :hq 0) yusuf (get-program state 0) cache (get-program state 1)] (run-empty-server state "Archives") (is (= 1 (get-counters (refresh yusuf) :virus)) "Yusuf has 1 virus counter") (is (= 3 (get-strength (refresh yusuf))) "Initial Yusuf strength") (is (= 3 (get-counters (refresh cache) :virus)) "Initial Cache virus counters") (run-on state "HQ") (rez state :corp fire-wall) (run-continue state) (card-ability state :runner yusuf 1) (click-card state :runner cache) (card-ability state :runner yusuf 1) (click-card state :runner yusuf) (is (= 2 (get-counters (refresh cache) :virus)) "Cache lost 1 virus counter to pump") (is (= 5 (get-strength (refresh yusuf))) "Yusuf strength 5") (is (zero? (get-counters (refresh yusuf) :virus)) "Yusuf lost 1 virus counter to pump") (is (empty? (:prompt (get-runner))) "No prompt open") (card-ability state :runner yusuf 0) (click-prompt state :runner "End the run") (click-card state :runner cache) (is (= 1 (get-counters (refresh cache) :virus)) "Cache lost its final virus counter")))))
true
(ns game.cards.programs-test (:require [game.core :as core] [game.core.card :refer :all] [game.macros :refer [req]] [game.utils :as utils] [game.core-test :refer :all] [game.utils-test :refer :all] [game.macros-test :refer :all] [clojure.test :refer :all])) (deftest abagnale ;; Abagnale (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Abagnale"] :credits 10}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Abagnale") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 2) (is (= :approach-server (:phase (get-run))) "Run has bypassed Enigma") (is (find-card "Abagnale" (:discard (get-runner))) "Abagnale is trashed"))) (deftest adept ;; Adept (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Cobra"] :credits 10} :runner {:deck ["Adept" "Box-E"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Cobra" "R&D") (take-credits state :corp) (play-from-hand state :runner "Adept") (let [adept (get-program state 0) iw (get-ice state :hq 0) cobra (get-ice state :rd 0)] (is (= 2 (core/available-mu state))) (is (= 4 (get-strength (refresh adept))) "+2 strength for 2 unused MU") (play-from-hand state :runner "Box-E") (is (= 4 (core/available-mu state))) (is (= 6 (get-strength (refresh adept))) "+4 strength for 4 unused MU") (run-on state :hq) (rez state :corp iw) (run-continue state) (card-ability state :runner (refresh adept) 0) (click-prompt state :runner "End the run") (is (:broken (first (:subroutines (refresh iw)))) "Broke a barrier subroutine") (run-jack-out state) (run-on state :rd) (rez state :corp cobra) (run-continue state) (card-ability state :runner (refresh adept) 0) (click-prompt state :runner "Trash a program") (click-prompt state :runner "Done") (is (:broken (first (:subroutines (refresh cobra)))) "Broke a sentry subroutine")))) (deftest afterimage ;; Afterimage (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"] :credits 10} :runner {:hand ["Afterimage"] :credits 10}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (play-from-hand state :runner "Afterimage") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "Yes") (is (= :approach-server (:phase (get-run))) "Run has bypassed Rototurret"))) (testing "Can only be used once per turn. #5032" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"] :credits 10} :runner {:hand ["Afterimage"] :credits 10}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (play-from-hand state :runner "Afterimage") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "Yes") (is (= :approach-server (:phase (get-run))) "Run has bypassed Rototurret") (run-jack-out state) (run-on state "HQ") (run-continue state) (is (empty? (:prompt (get-runner))) "No bypass prompt")))) (deftest aghora ;; Aghora (testing "Swap ability" (testing "Doesnt work if no Deva in hand" (do-game (new-game {:runner {:hand ["Aghora" "Corroder"] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Aghora") (card-ability state :runner (get-program state 0) 2) (is (empty? (:prompt (get-runner))) "No select prompt as there's no Deva in hand"))) (testing "Works with another deva in hand" (doseq [deva ["Aghora" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]] (do-game (new-game {:runner {:hand ["Aghora" deva] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Aghora") (let [installed-deva (get-program state 0)] (card-ability state :runner installed-deva 2) (click-card state :runner (first (:hand (get-runner)))) (is (not (utils/same-card? installed-deva (get-program state 0))) "Installed deva is not same as previous deva") (is (= deva (:title (get-program state 0))))))))) (testing "Break ability targets ice with rez cost 5 or higher" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Endless EULA"] :credits 10} :runner {:hand ["Aghora"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Endless EULA" "R&D") (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "No break prompt") (run-jack-out state) (run-on state "R&D") (rez state :corp (get-ice state :rd 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (seq (:prompt (get-runner))) "Have a break prompt") (click-prompt state :runner "End the run unless the Runner pays 1 [Credits]") (click-prompt state :runner "Done") (is (:broken (first (:subroutines (get-ice state :rd 0)))) "The break ability worked")))) (deftest algernon ;; PI:NAME:<NAME>END_PInon - pay 2 credits to gain a click, trash if no successful run (testing "Use, successful run" (do-game (new-game {:runner {:deck ["PI:NAME:<NAME>END_PI"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (take-credits state :runner) (take-credits state :corp) (is (= 8 (:credit (get-runner))) "Runner starts with 8 credits") (is (= 4 (:click (get-runner))) "Runner starts with 4 clicks") (click-prompt state :runner "Yes") (is (= 6 (:credit (get-runner))) "Runner pays 2 credits") (is (= 5 (:click (get-runner))) "Runner gains 1 click") (run-empty-server state "Archives") (take-credits state :runner) (is (empty? (:discard (get-runner))) "No cards trashed") (is (= "PI:NAME:<NAME>END_PIgernon" (:title (get-program state 0))) "Algernon still installed"))) (testing "Use, no successful run" (do-game (new-game {:runner {:deck ["PI:NAME:<NAME>END_PI"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (take-credits state :runner) (take-credits state :corp) (is (= 8 (:credit (get-runner))) "Runner starts with 8 credits") (is (= 4 (:click (get-runner))) "Runner starts with 4 clicks") (click-prompt state :runner "Yes") (is (= 6 (:credit (get-runner))) "Runner pays 2 credits") (is (= 5 (:click (get-runner))) "Runner gains 1 click") (run-on state "Archives") (run-jack-out state) (take-credits state :runner) (is (= 1 (count (:discard (get-runner)))) "Algernon trashed") (is (empty? (get-program state)) "No programs installed"))) (testing "Not used, no successful run" (do-game (new-game {:runner {:deck ["PI:NAME:<NAME>END_PI"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (take-credits state :runner) (take-credits state :corp) (is (= 8 (:credit (get-runner))) "Runner starts with 8 credits") (is (= 4 (:click (get-runner))) "Runner starts with 4 clicks") (click-prompt state :runner "No") (is (= 8 (:credit (get-runner))) "No credits spent") (is (= 4 (:click (get-runner))) "No clicks gained") (run-on state "Archives") (run-jack-out state) (take-credits state :runner) (is (empty? (:discard (get-runner))) "No cards trashed") (is (= "Algernon" (:title (get-program state 0))) "Algernon still installed")))) (deftest ^{:card-title "alias"} alias-breaker ;; Alias (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand [(qty "Zed 1.0" 2)]} :runner {:hand ["Alias"] :credits 10}}) (play-from-hand state :corp "Zed 1.0" "HQ") (play-from-hand state :corp "Zed 1.0" "New remote") (take-credits state :corp) (play-from-hand state :runner "Alias") (let [alias (get-program state 0) zed1 (get-ice state :hq 0) zed2 (get-ice state :remote1 0)] (is (= 1 (get-strength (refresh alias))) "Starts with 2 strength") (card-ability state :runner (refresh alias) 1) (is (= 4 (get-strength (refresh alias))) "Can gain strength outside of a run") (run-on state :hq) (rez state :corp (refresh zed1)) (run-continue state) (card-ability state :runner (refresh alias) 0) (click-prompt state :runner "Do 1 brain damage") (click-prompt state :runner "Done") (is (= 1 (count (filter :broken (:subroutines (refresh zed1))))) "The subroutine is broken") (run-jack-out state) (is (= 1 (get-strength (refresh alias))) "Drops back down to base strength on run end") (run-on state :remote1) (rez state :corp (refresh zed2)) (run-continue state) (card-ability state :runner (refresh alias) 0) (is (empty? (:prompt (get-runner))) "No break prompt because we're running a remote")))) (deftest amina ;; Amina ability (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Amina"] :credits 15}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Amina") (let [amina (get-program state 0) enigma (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh enigma)) (is (= 4 (:credit (get-corp)))) (run-continue state) (card-ability state :runner (refresh amina) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "Done") (run-continue state) (is (= 4 (:credit (get-corp))) "Corp did not lose 1c because not all subs were broken") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh amina) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (run-continue state) (is (= 3 (:credit (get-corp))) "Corp lost 1 credit") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh amina) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (run-continue state) (is (= 3 (:credit (get-corp))) "Ability only once per turn"))) (testing "Amina only triggers on itself. Issue #4716" (do-game (new-game {:runner {:deck ["Amina" "Yog.0"]} :corp {:deck ["Enigma"]}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (core/gain state :runner :credit 20 :click 1) (play-from-hand state :runner "Amina") (play-from-hand state :runner "Yog.0") (let [amina (get-program state 0) yog (get-program state 1) enima (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh enima)) (run-continue state) (card-ability state :runner (refresh amina) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh yog) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (changes-val-macro 0 (:credit (get-corp)) "No credit gain from Amina" (click-prompt state :runner "End the run") (run-continue state)) (run-jack-out state))))) (deftest analog-dreamers ;; Analog Dreamers (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Hostile Takeover" "PAD Campaign"]} :runner {:hand ["Analog Dreamers"]}}) (play-from-hand state :corp "Hostile Takeover" "New remote") (play-from-hand state :corp "PAD Campaign" "New remote") (advance state (get-content state :remote1 0) 1) (take-credits state :corp) (play-from-hand state :runner "Analog Dreamers") (card-ability state :runner (get-program state 0) 0) (run-continue state) (click-prompt state :runner "Analog Dreamers") (click-card state :runner "Hostile Takeover") (is (= "Choose a card to shuffle into R&D" (:msg (prompt-map :runner))) "Can't click on Hostile Takeover") (let [number-of-shuffles (count (core/turn-events state :corp :corp-shuffle-deck)) pad (get-content state :remote2 0)] (click-card state :runner "PAD Campaign") (is (< number-of-shuffles (count (core/turn-events state :corp :corp-shuffle-deck))) "Should be shuffled") (is (find-card "PAD Campaign" (:deck (get-corp))) "PAD Campaign is shuffled into R&D") (is (nil? (refresh pad)) "PAD Campaign is shuffled into R&D")))) (deftest ankusa ;; Ankusa (testing "Boost 1 strength for 1 credit" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Battlement"]} :runner {:hand ["Ankusa"] :credits 15}}) (play-from-hand state :corp "Battlement" "HQ") (take-credits state :corp) (play-from-hand state :runner "Ankusa") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (let [ankusa (get-program state 0) credits (:credit (get-runner))] "Boost ability costs 1 credit each" (card-ability state :runner ankusa 1) (is (= (dec credits) (:credit (get-runner))) "Boost 1 for 1 credit") (is (= (inc (get-strength ankusa)) (get-strength (refresh ankusa))) "Ankusa gains 1 strength")))) (testing "Break 1 for 2 credits" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Battlement"]} :runner {:hand ["Ankusa"] :credits 15}}) (play-from-hand state :corp "Battlement" "HQ") (take-credits state :corp) (play-from-hand state :runner "Ankusa") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (let [ankusa (get-program state 0)] (card-ability state :runner ankusa 1) (card-ability state :runner ankusa 1) (changes-val-macro -2 (:credit (get-runner)) "Break ability costs 2 credits" (card-ability state :runner ankusa 0) (click-prompt state :runner "End the run") (click-prompt state :runner "Done"))))) (testing "Breaking an ice fully returns it to hand. Issue #4711" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Battlement"]} :runner {:hand ["Ankusa"] :credits 15}}) (play-from-hand state :corp "Battlement" "HQ") (take-credits state :corp) (play-from-hand state :runner "Ankusa") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (let [ankusa (get-program state 0)] (card-ability state :runner ankusa 1) (card-ability state :runner ankusa 1) (card-ability state :runner ankusa 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (is (find-card "Battlement" (:hand (get-corp))) "Battlement should be back in hand"))))) (deftest atman ;; PI:NAME:<NAME>END_PIman (testing "Installing with 0 power counters" (do-game (new-game {:runner {:deck ["PI:NAME:<NAME>END_PI"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (click-prompt state :runner "0") (is (= 3 (core/available-mu state))) (let [atman (get-program state 0)] (is (zero? (get-counters atman :power)) "0 power counters") (is (zero? (get-strength atman)) "0 current strength")))) (testing "Installing with 2 power counters" (do-game (new-game {:runner {:deck ["PI:NAME:<NAME>END_PI"]}}) (take-credits state :corp) (play-from-hand state :runner "Atman") (click-prompt state :runner "2") (is (= 3 (core/available-mu state))) (let [atman (get-program state 0)] (is (= 2 (get-counters atman :power)) "2 power counters") (is (= 2 (get-strength atman)) "2 current strength"))))) (deftest au-revoir ;; Au Revoir - Gain 1 credit every time you jack out (do-game (new-game {:runner {:deck [(qty "Au Revoir" 2)]}}) (take-credits state :corp) (play-from-hand state :runner "Au Revoir") (run-on state "Archives") (run-jack-out state) (is (= 5 (:credit (get-runner))) "Gained 1 credit from jacking out") (play-from-hand state :runner "Au Revoir") (run-on state "Archives") (run-jack-out state) (is (= 6 (:credit (get-runner))) "Gained 1 credit from each copy of Au Revoir"))) (deftest aumakua ;; Aumakua - Gain credit on no-trash (testing "Gain counter on no trash" (do-game (new-game {:corp {:deck [(qty "PAD Campaign" 3)]} :runner {:deck ["Aumakua"]}}) (play-from-hand state :corp "PAD Campaign" "New remote") (take-credits state :corp) (play-from-hand state :runner "Aumakua") (run-empty-server state "Server 1") (click-prompt state :runner "No action") (is (= 1 (get-counters (get-program state 0) :virus)) "Aumakua gains virus counter from no-trash") (core/gain state :runner :credit 5) (run-empty-server state "Server 1") (click-prompt state :runner "Pay 4 [Credits] to trash") (is (= 1 (get-counters (get-program state 0) :virus)) "Aumakua does not gain virus counter from trash"))) (testing "Gain counters on empty archives" (do-game (new-game {:runner {:deck ["Aumakua"]} :options {:start-as :runner}}) (play-from-hand state :runner "Aumakua") (run-empty-server state :archives) (is (= 1 (get-counters (get-program state 0) :virus)) "Aumakua gains virus counter from accessing empty Archives"))) (testing "Neutralize All Threats interaction" (do-game (new-game {:corp {:deck [(qty "PAD Campaign" 3)]} :runner {:deck ["Aumakua" "Neutralize All Threats"]}}) (play-from-hand state :corp "PAD Campaign" "New remote") (take-credits state :corp) (play-from-hand state :runner "Aumakua") (play-from-hand state :runner "Neutralize All Threats") (core/gain state :runner :credit 5) (run-empty-server state "Server 1") (is (zero? (get-counters (get-program state 0) :virus)) "Aumakua does not gain virus counter from ABT-forced trash")))) (deftest baba-yaga ;; Baba Yaga (do-game (new-game {:runner {:deck ["Baba Yaga" "Faerie" "Yog.0" "Sharpshooter"]}}) (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Baba Yaga") (play-from-hand state :runner "Sharpshooter") (let [baba (get-program state 0) base-abicount (count (:abilities baba))] (card-ability state :runner baba 0) (click-card state :runner "Faerie") (is (= (+ 2 base-abicount) (count (:abilities (refresh baba)))) "Baba Yaga gained 2 subroutines from Faerie") (card-ability state :runner (refresh baba) 0) (click-card state :runner (find-card "Yog.0" (:hand (get-runner)))) (is (= (+ 3 base-abicount) (count (:abilities (refresh baba)))) "Baba Yaga gained 1 subroutine from Yog.0") (trash state :runner (first (:hosted (refresh baba)))) (is (= (inc base-abicount) (count (:abilities (refresh baba)))) "Baba Yaga lost 2 subroutines from trashed Faerie") (card-ability state :runner baba 1) (click-card state :runner (find-card "Sharpshooter" (:program (:rig (get-runner))))) (is (= 2 (count (:hosted (refresh baba)))) "Faerie and Sharpshooter hosted on Baba Yaga") (is (= 1 (core/available-mu state)) "1 MU left with 2 breakers on Baba Yaga") (is (= 4 (:credit (get-runner))) "-5 from Baba, -1 from Sharpshooter played into Rig, -5 from Yog")))) (deftest bankroll ;; Bankroll - Includes check for Issue #4334 (do-game (new-game {:runner {:deck ["Bankroll" "PI:NAME:<NAME>END_PI"]}}) (take-credits state :corp) (core/gain state :runner :click 10) (play-from-hand state :runner "Bankroll") (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (is (= 3 (core/available-mu state)) "Bankroll uses up 1 MU") (is (= 1 (:credit (get-runner))) "Bankroll cost 1 to install") (let [bankroll (get-program state 0) hosted-credits #(get-counters (refresh bankroll) :credit)] (is (zero? (hosted-credits)) "No counters on Bankroll on install") (run-empty-server state "Archives") (is (= 1 (hosted-credits)) "One credit counter on Bankroll after one successful run") (run-empty-server state "R&D") (is (= 2 (hosted-credits)) "Two credit counter on Bankroll after two successful runs") (run-empty-server state "HQ") (click-prompt state :runner "No action") (is (= 3 (hosted-credits)) "Three credit counter on Bankroll after three successful runs") (take-credits state :runner) (take-credits state :corp) (end-phase-12 state :runner) (click-prompt state :runner "Yes") (click-prompt state :runner "R&D") (run-continue state) (let [credits (:credit (get-runner))] (is (= 3 (hosted-credits)) "Jak Sinclair didn't trigger Bankroll") (card-ability state :runner bankroll 0) (is (= (+ 3 credits) (:credit (get-runner))) "Gained 3 credits when trashing Bankroll")) (is (= 1 (-> (get-runner) :discard count)) "Bankroll was trashed")))) (deftest berserker ;; PI:NAME:<NAME>END_PIker (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Hive" "Enigma"] :credits 100} :runner {:hand ["PI:NAME:<NAME>END_PI"]}}) (play-from-hand state :corp "Ice Wall" "Archives") (play-from-hand state :corp "Hive" "R&D") (play-from-hand state :corp "Enigma" "HQ") (rez state :corp (get-ice state :archives 0)) (rez state :corp (get-ice state :rd 0)) (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (let [berserker (get-program state 0)] (is (= 2 (get-strength (refresh berserker))) "Berserker strength starts at 2") (run-on state :archives) (run-continue state) (is (= 3 (get-strength (refresh berserker))) "Berserker gains 1 strength from Ice Wall") (run-jack-out state) (is (= 2 (get-strength (refresh berserker))) "Berserker strength resets at end of run") (run-on state :rd) (run-continue state) (is (= 7 (get-strength (refresh berserker))) "Berserker gains 5 strength from Hive") (run-jack-out state) (is (= 2 (get-strength (refresh berserker))) "Berserker strength resets at end of run") (run-on state :hq) (run-continue state) (is (= 2 (get-strength (refresh berserker))) "Berserker gains 0 strength from Enigma (non-barrier)")))) (deftest black-orchestra (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Macrophage"] :credits 10} :runner {:hand ["Black Orchestra"] :credits 100}}) (play-from-hand state :corp "Macrophage" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Black Orchestra") (let [bo (get-program state 0)] (run-on state :hq) (run-continue state) (card-ability state :runner bo 0) (card-ability state :runner bo 0) (is (empty? (:prompt (get-runner))) "Has no break prompt as strength isn't high enough") (card-ability state :runner bo 0) (is (= 8 (get-strength (refresh bo))) "Pumped Black Orchestra up to str 8") (click-prompt state :runner "Trace 4 - Purge virus counters") (click-prompt state :runner "Trace 3 - Trash a virus") (is (= 2 (count (filter :broken (:subroutines (get-ice state :hq 0))))))))) (testing "auto-pump" (testing "Pumping more than once, breaking more than once" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Macrophage"] :credits 10} :runner {:hand ["Black Orchestra"] :credits 100}}) (play-from-hand state :corp "Macrophage" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Black Orchestra") (let [bo (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -12 (:credit (get-runner)) "Paid 12 to fully break Macrophage with Black Orchestra" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh bo)})) (is (= 10 (get-strength (refresh bo))) "Pumped Black Orchestra up to str 10") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "No pumping, breaking more than once" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Aiki"] :credits 10} :runner {:hand ["Black Orchestra"] :credits 100}}) (play-from-hand state :corp "Aiki" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Black Orchestra") (let [bo (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -6 (:credit (get-runner)) "Paid 6 to fully break Aiki with Black Orchestra" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh bo)})) (is (= 6 (get-strength (refresh bo))) "Pumped Black Orchestra up to str 6") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "Pumping and breaking once" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"] :credits 10} :runner {:hand ["Black Orchestra"] :credits 100}}) (play-from-hand state :corp "Enigma" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Black Orchestra") (let [bo (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -3 (:credit (get-runner)) "Paid 3 to fully break Enigma with Black Orchestra" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh bo)})) (is (= 4 (get-strength (refresh bo))) "Pumped Black Orchestra up to str 6") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "No auto-break on unbreakable subs" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Afshar"] :credits 10} :runner {:hand ["Black Orchestra"] :credits 100}}) (play-from-hand state :corp "Afshar" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Black Orchestra") (let [bo (get-program state 0)] (run-on state :hq) (run-continue state) (is (empty? (filter #(:dynamic %) (:abilities (refresh bo)))) "No auto-pumping option for Afshar"))))) (testing "Heap Locked" (do-game (new-game {:corp {:deck ["Enigma" "Blacklist"]} :runner {:deck [(qty "Black Orchestra" 1)]}}) (play-from-hand state :corp "Enigma" "Archives") (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (refresh (get-content state :remote1 0))) (take-credits state :corp) (trash-from-hand state :runner "Black Orchestra") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (is (empty? (:prompt (get-runner))) "Black Orchestra prompt did not come up")))) (deftest botulus ;; Botulus (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:credits 15 :hand ["Botulus"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Botulus") (click-card state :runner (get-ice state :hq 0)) (let [iw (get-ice state :hq 0) bot (first (:hosted (refresh iw)))] (run-on state :hq) (rez state :corp iw) (run-continue state) (card-ability state :runner (refresh bot) 0) (click-prompt state :runner "End the run") (is (zero? (count (remove :broken (:subroutines (refresh iw))))) "All subroutines have been broken")))) (deftest brahman ;; Brahman (testing "Basic test" (do-game (new-game {:runner {:deck ["Brahman" "Paricia" "Cache"]} :corp {:deck ["Ice Wall"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Brahman") (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (core/gain state :runner :credit 1) (let [brah (get-program state 0) par (get-program state 1) cache (get-program state 2) iw (get-ice state :hq 0)] (run-on state :hq) (rez state :corp iw) (run-continue state) (card-ability state :runner brah 0) ;break sub (click-prompt state :runner "End the run") (run-continue state) (is (= 0 (count (:deck (get-runner)))) "Stack is empty.") (click-card state :runner cache) (is (= 0 (count (:deck (get-runner)))) "Did not put Cache on top.") (click-card state :runner par) (is (= 1 (count (:deck (get-runner)))) "Paricia on top of Stack now.")))) (testing "Prompt on ETR" (do-game (new-game {:runner {:deck ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]} :corp {:deck ["Spiderweb"]}}) (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (let [brah (get-program state 0) par (get-program state 1) spi (get-ice state :hq 0)] (run-on state :hq) (rez state :corp spi) (run-continue state) (card-ability state :runner brah 0) ;break sub (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (card-subroutine state :corp spi 0) ;ETR (is (= 0 (count (:deck (get-runner)))) "Stack is empty.") (click-card state :runner par) (is (= 1 (count (:deck (get-runner)))) "Paricia on top of Stack now.")))) (testing "Brahman works with Nisei tokens" (do-game (new-game {:corp {:deck ["Ice Wall" "Nisei MK II"]} :runner {:deck ["PI:NAME:<NAME>END_PI"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-and-score state "Nisei MK II") (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (let [brah (get-program state 0) iw (get-ice state :hq 0) nisei (get-scored state :corp 0)] (run-on state "HQ") (rez state :corp iw) (run-continue state) (card-ability state :runner brah 0) ;break sub (click-prompt state :runner "End the run") (card-ability state :corp (refresh nisei) 0) ; Nisei Token (is (= 0 (count (:deck (get-runner)))) "Stack is empty.") (click-card state :runner brah) (is (= 1 (count (:deck (get-runner)))) "Brahman on top of Stack now.")))) (testing "Works with dynamic ability" (do-game (new-game {:runner {:deck ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]} :corp {:deck ["Spiderweb"]}}) (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (core/gain state :runner :credit 1) (let [brah (get-program state 0) par (get-program state 1) spi (get-ice state :hq 0)] (run-on state :hq) (rez state :corp spi) (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh brah)}) (core/continue state :corp nil) (is (= 0 (count (:deck (get-runner)))) "Stack is empty.") (click-card state :runner par) (is (= 1 (count (:deck (get-runner)))) "Paricia on top of Stack now."))))) (deftest bukhgalter ;; Bukhgalter ability (testing "2c for breaking subs only with Bukhgalter" (do-game (new-game {:runner {:deck ["BuPI:NAME:<NAME>END_PIter" "Mimic"]} :corp {:deck ["Pup"]}}) (play-from-hand state :corp "Pup" "HQ") (take-credits state :corp) (core/gain state :runner :credit 20 :click 1) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (play-from-hand state :runner "Mimic") (let [bukhgalter (get-program state 0) mimic (get-program state 1) pup (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh pup)) (run-continue state) (card-ability state :runner (refresh mimic) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (changes-val-macro -1 (:credit (get-runner)) "No credit gain from Bukhgalter for breaking with only Mimic" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]")) (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh bukhgalter) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (click-prompt state :runner "Done") (card-ability state :runner (refresh mimic) 0) (changes-val-macro -1 (:credit (get-runner)) "No credit gain from Bukhgalter" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]")) (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh bukhgalter) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (changes-val-macro (+ 2 -1) (:credit (get-runner)) "2 credits gained from Bukhgalter" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]"))))) (testing "gaining 2c only once per turn" (do-game (new-game {:runner {:deck ["Bukhgalter" "Mimic"]} :corp {:deck ["Pup"]}}) (play-from-hand state :corp "Pup" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Bukhgalter") (let [bukhgalter (get-program state 0) pup (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh pup)) (run-continue state) (card-ability state :runner (refresh bukhgalter) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (changes-val-macro (+ 2 -1) (:credit (get-runner)) "2 credits gained from Bukhgalter" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]")) (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh bukhgalter) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (changes-val-macro -1 (:credit (get-runner)) "No credits gained from Bukhgalter" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]"))))) (testing "Bukhgalter only triggers on itself. Issue #4716" (do-game (new-game {:runner {:deck ["Bukhgalter" "Mimic"]} :corp {:deck ["Pup"]}}) (play-from-hand state :corp "Pup" "HQ") (take-credits state :corp) (core/gain state :runner :credit 20 :click 1) (play-from-hand state :runner "Bukhgalter") (play-from-hand state :runner "Mimic") (let [bukhgalter (get-program state 0) mimic (get-program state 1) pup (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh pup)) (run-continue state) (card-ability state :runner (refresh bukhgalter) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (refresh mimic) 0) (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]") (changes-val-macro -1 (:credit (get-runner)) "No credit gain from Bukhgalter" (click-prompt state :runner "Do 1 net damage unless the Runner pays 1 [Credits]")) (run-jack-out state))))) (deftest buzzsaw ;; Buzzsaw (before-each [state (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"] :credits 20} :runner {:deck ["Buzzsaw"] :credits 20}}) _ (do (play-from-hand state :corp "Enigma" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Buzzsaw") (run-on state :hq) (run-continue state)) enigma (get-ice state :hq 0) buzzsaw (get-program state 0)] (testing "pump ability" (do-game state (changes-val-macro -3 (:credit (get-runner)) "Runner spends 3 credits to pump Buzzsaw" (card-ability state :runner buzzsaw 1)) (changes-val-macro 1 (get-strength (refresh buzzsaw)) "Buzzsaw gains 1 strength per pump" (card-ability state :runner buzzsaw 1)))) (testing "break ability" (do-game state (changes-val-macro -1 (:credit (get-runner)) "Runner spends 1 credits to break with Buzzsaw" (card-ability state :runner buzzsaw 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run")) (is (every? :broken (:subroutines (refresh enigma))) "Buzzsaw breaks 2 subs at once"))))) (deftest carmen ;; Carmen (before-each [state (new-game {:runner {:hand [(qty "Carmen" 2)] :credits 20} :corp {:deck [(qty "Hedge Fund" 5)] :hand ["Swordsman"] :credits 20}}) _ (do (play-from-hand state :corp "Swordsman" "HQ") (take-credits state :corp)) swordsman (get-ice state :hq 0)] (testing "install cost discount" (do-game state (take-credits state :corp) (changes-val-macro -5 (:credit (get-runner)) "Without discount" (play-from-hand state :runner "Carmen")) (take-credits state :runner) (take-credits state :corp) (run-empty-server state :archives) (changes-val-macro -3 (:credit (get-runner)) "With discount" (play-from-hand state :runner "Carmen")))) (testing "pump ability" (do-game state (play-from-hand state :runner "CPI:NAME:<NAME>END_PI") (let [carmen (get-program state 0)] (run-on state :hq) (rez state :corp swordsman) (run-continue state :encounter-ice) (changes-val-macro -2 (:credit (get-runner)) "Pump costs 2" (card-ability state :runner carmen 1)) (changes-val-macro 3 (get-strength (refresh carmen)) "Carmen gains 3 str" (card-ability state :runner carmen 1))))) (testing "break ability" (do-game state (play-from-hand state :runner "CPI:NAME:<NAME>END_PI") (let [carmen (get-program state 0)] (run-on state :hq) (rez state :corp swordsman) (run-continue state :encounter-ice) (changes-val-macro -1 (:credit (get-runner)) "Break costs 1" (card-ability state :runner carmen 0) (click-prompt state :runner "Trash an AI program")) (click-prompt state :runner "Do 1 net damage") (is (empty? (:prompt (get-runner))) "Only breaks 1 sub at a time")))))) (deftest cerberus-rex-h2 ;; Cerberus "Rex" H2 - boost 1 for 1 cred, break for 1 counter (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:deck ["Cerberus \"Rex\" H2"]}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cerberus \"Rex\" H2") (is (= 2 (:credit (get-runner))) "2 credits left after install") (let [enigma (get-ice state :hq 0) rex (get-program state 0)] (run-on state "HQ") (rez state :corp enigma) (run-continue state) (is (= 4 (get-counters rex :power)) "Start with 4 counters") ;; boost strength (card-ability state :runner rex 1) (is (= 1 (:credit (get-runner))) "Spend 1 credit to boost") (is (= 2 (get-strength (refresh rex))) "At strength 2 after boost") ;; break (card-ability state :runner rex 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (is (= 1 (:credit (get-runner))) "No credits spent to break") (is (= 3 (get-counters (refresh rex) :power)) "One counter used to break")))) (deftest chakana ;; Chakana (testing "gain counters on r&d runs" (do-game (new-game {:runner {:hand ["Chakana"]}}) (take-credits state :corp) (play-from-hand state :runner "Chakana") (let [chakana (get-program state 0)] (is (zero? (get-counters (refresh chakana) :virus)) "Chakana starts with 0 counters") (run-empty-server state "R&D") (is (= 1 (get-counters (refresh chakana) :virus)) "Chakana starts with 0 counters") (run-empty-server state "R&D") (is (= 2 (get-counters (refresh chakana) :virus)) "Chakana starts with 0 counters") (run-empty-server state "HQ") (is (= 2 (get-counters (refresh chakana) :virus)) "Chakana starts with 0 counters")))) (testing "3 counters increases advancement requirements by 1" (do-game (new-game {:corp {:hand ["Hostile Takeover"]} :runner {:hand ["Chakana"]}}) (play-from-hand state :corp "Hostile Takeover" "New remote") (take-credits state :corp) (play-from-hand state :runner "Chakana") (is (= 2 (core/get-advancement-requirement (get-content state :remote1 0))) "Hostile Takeover is a 2/1 by default") (let [chakana (get-program state 0)] (core/gain state :runner :click 10) (run-empty-server state "R&D") (run-empty-server state "R&D") (run-empty-server state "R&D") (is (= 3 (get-counters (refresh chakana) :virus))) (is (= 3 (core/get-advancement-requirement (get-content state :remote1 0))) "Hostile Takeover is affected by Chakana"))))) (deftest chameleon ;; Chameleon - Install on corp turn, only returns to hand at end of runner's turn (testing "with Clone Chip" (do-game (new-game {:runner {:deck ["Chameleon" "Clone Chip"]}}) (take-credits state :corp) (play-from-hand state :runner "Clone Chip") (core/move state :runner (find-card "Chameleon" (:hand (get-runner))) :discard) (take-credits state :runner) (is (zero? (count (:hand (get-runner))))) ;; Install Chameleon on corp turn (take-credits state :corp 1) (let [chip (get-hardware state 0)] (card-ability state :runner chip 0) (click-card state :runner (find-card "Chameleon" (:discard (get-runner)))) (click-prompt state :runner "Sentry")) (take-credits state :corp) (is (zero? (count (:hand (get-runner)))) "Chameleon not returned to hand at end of corp turn") (take-credits state :runner) (is (= 1 (count (:hand (get-runner)))) "Chameleon returned to hand at end of runner's turn"))) (testing "Returns to hand after hosting. #977" (do-game (new-game {:runner {:deck [(qty "Chameleon" 2) "Scheherazade"]}}) (take-credits state :corp) (play-from-hand state :runner "Chameleon") (click-prompt state :runner "Barrier") (is (= 3 (:credit (get-runner))) "-2 from playing Chameleon") ;; Host the Chameleon on Scheherazade that was just played (as in Personal Workshop/Hayley ability scenarios) (play-from-hand state :runner "Scheherazade") (let [scheherazade (get-program state 1)] (card-ability state :runner scheherazade 1) ; Host an installed program (click-card state :runner (find-card "Chameleon" (:program (:rig (get-runner))))) (is (= 4 (:credit (get-runner))) "+1 from hosting onto Scheherazade") ;; Install another Chameleon directly onto Scheherazade (card-ability state :runner scheherazade 0) ; Install and host a program from Grip (click-card state :runner (find-card "Chameleon" (:hand (get-runner)))) (click-prompt state :runner "Code Gate") (is (= 2 (count (:hosted (refresh scheherazade)))) "2 Chameleons hosted on Scheherazade") (is (= 3 (:credit (get-runner))) "-2 from playing Chameleon, +1 from installing onto Scheherazade")) (is (zero? (count (:hand (get-runner)))) "Both Chameleons in play - hand size 0") (take-credits state :runner) (click-prompt state :runner "Chameleon") (is (= 2 (count (:hand (get-runner)))) "Both Chameleons returned to hand - hand size 2"))) (testing "Can break subroutines only on chosen subtype" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma" "Rototurret"] :credits 10} :runner {:hand ["Chameleon"] :credits 100}}) (play-from-hand state :corp "Ice Wall" "Archives") (play-from-hand state :corp "Enigma" "HQ") (play-from-hand state :corp "Rototurret" "R&D") (rez state :corp (get-ice state :archives 0)) (rez state :corp (get-ice state :hq 0)) (rez state :corp (get-ice state :rd 0)) (take-credits state :corp) (testing "Choosing Barrier" (play-from-hand state :runner "ChPI:NAME:<NAME>END_PIleon") (click-prompt state :runner "Barrier") (run-on state :archives) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "End the run") (is (empty? (:prompt (get-runner))) "Broke all subroutines on Ice Wall") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Enigma") (run-jack-out state) (run-on state :rd) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Rototurret") (run-jack-out state)) (take-credits state :runner) (take-credits state :corp) (testing "Choosing Code Gate" (play-from-hand state :runner "ChPI:NAME:<NAME>END_PIleon") (click-prompt state :runner "Code Gate") (run-on state :archives) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Ice Wall") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (is (empty? (:prompt (get-runner))) "Broke all subroutines on Engima") (run-jack-out state) (run-on state :rd) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Rototurret") (run-jack-out state)) (take-credits state :runner) (take-credits state :corp) (testing "Choosing Sentry" (play-from-hand state :runner "Chameleon") (click-prompt state :runner "Sentry") (run-on state :archives) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Ice Wall") (run-jack-out state) (run-on state :hq) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Can't use Chameleon on Enigma") (run-jack-out state) (run-on state :rd) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "Trash a program") (click-prompt state :runner "End the run") (is (empty? (:prompt (get-runner))) "Broke all subroutines on Rototurret"))))) (deftest chisel ;; Chisel (testing "Basic test" (do-game (new-game {:corp {:hand ["Ice Wall"]} :runner {:hand ["Chisel"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Chisel") (click-card state :runner "Ice Wall") (let [iw (get-ice state :hq 0) chisel (first (:hosted (refresh iw)))] (run-on state "HQ") (rez state :corp iw) (is (zero? (get-counters (refresh chisel) :virus))) (run-continue state) (is (= 1 (get-counters (refresh chisel) :virus))) (is (refresh iw) "Ice Wall still around, just at 0 strength") (run-jack-out state) (run-on state "HQ") (run-continue state) (is (nil? (refresh iw)) "Ice Wall should be trashed") (is (nil? (refresh chisel)) "Chisel should likewise be trashed")))) (testing "Doesn't work if the ice is unrezzed" (do-game (new-game {:corp {:hand ["Ice Wall"]} :runner {:hand ["Chisel"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (core/gain state :runner :click 10) (play-from-hand state :runner "Chisel") (click-card state :runner "Ice Wall") (let [iw (get-ice state :hq 0) chisel (first (:hosted (refresh iw)))] (run-on state "HQ") (is (zero? (get-counters (refresh chisel) :virus))) (is (zero? (get-counters (refresh chisel) :virus)) "Chisel gains no counters as Ice Wall is unrezzed") (is (refresh iw) "Ice Wall still around, still at 1 strength") (core/jack-out state :runner nil) (run-on state "HQ") (rez state :corp iw) (run-continue state) (is (= 1 (get-counters (refresh chisel) :virus)) "Chisel now has 1 counter") (core/jack-out state :runner nil) (derez state :corp iw) (run-on state "HQ") (run-continue state) (is (refresh iw) "Ice Wall should still be around as it's unrezzed")))) (testing "Chisel does not account for other sources of strength modification on hosted ICE #5391" (do-game (new-game {:corp {:hand ["Ice Wall"]} :runner {:hand ["Chisel" "Devil Charm"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Chisel") (play-from-hand state :runner "Devil Charm") (click-card state :runner "Ice Wall") (let [iw (get-ice state :hq 0) chisel (first (:hosted (refresh iw)))] (run-on state "HQ") (rez state :corp iw) (run-continue state) (click-prompt state :runner "Devil Charm") (click-prompt state :runner "Yes") (is (nil? (refresh iw)) "Ice Wall should be trashed") (is (nil? (refresh chisel)) "Chisel should likewise be trashed"))))) (deftest cleaver ;; Cleaver (before-each [state (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Battlement"]} :runner {:hand ["Cleaver"] :credits 15}}) _ (do (play-from-hand state :corp "Battlement" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cleaver") (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state :encounter-ice)) battlement (get-ice state :hq 0) cleaver (get-program state 0)] (testing "pump ability" (do-game state (changes-val-macro -2 (:credit (get-runner)) "costs 2" (card-ability state :runner cleaver 1)) (changes-val-macro 1 (get-strength (refresh cleaver)) "Gains 1 strength" (card-ability state :runner cleaver 1)))) (testing "pump ability" (do-game state (changes-val-macro -1 (:credit (get-runner)) "costs 1" (card-ability state :runner cleaver 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run")) (is (every? :broken (:subroutines (refresh battlement)))))))) (deftest cloak ;; Cloak (testing "Pay-credits prompt" (do-game (new-game {:runner {:deck ["Cloak" "Refractor"]}}) (take-credits state :corp) (play-from-hand state :runner "Cloak") (play-from-hand state :runner "Refractor") (let [cl (get-program state 0) refr (get-program state 1)] (changes-val-macro 0 (:credit (get-runner)) "Used 1 credit from Cloak" (card-ability state :runner refr 1) (click-card state :runner cl)))))) (deftest conduit ;; Conduit (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 8)] :hand ["Hedge Fund"]} :runner {:deck ["Conduit"]}}) (take-credits state :corp) (play-from-hand state :runner "Conduit") (let [conduit (get-program state 0)] (card-ability state :runner conduit 0) (is (:run @state) "Run initiated") (run-continue state) (click-prompt state :runner "No action") (click-prompt state :runner "Yes") (is (empty? (:prompt (get-runner))) "Prompt closed") (is (= 1 (get-counters (refresh conduit) :virus))) (is (not (:run @state)) "Run ended") (card-ability state :runner conduit 0) (run-continue state) (is (= 1 (core/access-bonus-count state :runner :rd)) "Runner should access 1 additional card") (click-prompt state :runner "No action") (click-prompt state :runner "No action") (click-prompt state :runner "Yes") (is (= 2 (get-counters (refresh conduit) :virus))) (run-empty-server state :rd) (is (= 0 (core/access-bonus-count state :runner :rd)) "Runner should access 0 additional card on normal run")))) (testing "Knobkierie interaction (Issue #5748) - Knobkierie before Conduit" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 8)] :hand ["Hedge Fund"]} :runner {:deck ["Conduit" "Knobkierie"] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Conduit") (play-from-hand state :runner "Knobkierie") (let [conduit (get-program state 0) knobkierie (get-hardware state 0)] (card-ability state :runner conduit 0) (is (:run @state) "Run initiated") (run-continue state :access-server) (click-prompt state :runner "Knobkierie") (click-prompt state :runner "Yes") (click-card state :runner (refresh conduit)) (is (= 1 (core/access-bonus-count state :runner :rd)) "Runner should access 1 additional card")))) (testing "Knobkierie interaction (Issue #5748) - Conduit before Knobkierie" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 8)] :hand ["Hedge Fund"]} :runner {:deck ["Conduit" "Knobkierie"] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Conduit") (play-from-hand state :runner "Knobkierie") (let [conduit (get-program state 0) knobkierie (get-hardware state 0)] (card-ability state :runner conduit 0) (is (:run @state) "Run initiated") (run-continue state :access-server) (click-prompt state :runner "Conduit") (click-prompt state :runner "Yes") (click-card state :runner (refresh conduit)) (is (= 0 (core/access-bonus-count state :runner :rd)) "Runner should not access additional cards"))))) (deftest consume ;; Consume - gain virus counter for trashing corp card. click to get 2c per counter. (testing "Trash and cash out" (do-game (new-game {:corp {:deck ["Adonis Campaign"]} :runner {:deck ["Consume"]}}) (play-from-hand state :corp "Adonis Campaign" "New remote") (take-credits state :corp) (play-from-hand state :runner "Consume") (let [c (get-program state 0)] (is (zero? (get-counters (refresh c) :virus)) "Consume starts with no counters") (run-empty-server state "Server 1") (click-prompt state :runner "Pay 3 [Credits] to trash") (click-prompt state :runner "Yes") (is (= 1 (count (:discard (get-corp)))) "Adonis Campaign trashed") (is (= 1 (get-counters (refresh c) :virus)) "Consume gains a counter") (is (zero? (:credit (get-runner))) "Runner starts with no credits") (card-ability state :runner c 0) (is (= 2 (:credit (get-runner))) "Runner gains 2 credits") (is (zero? (get-counters (refresh c) :virus)) "Consume loses counters")))) (testing "Hivemind interaction" (do-game (new-game {:corp {:deck ["Adonis Campaign"]} :runner {:deck ["Consume" "Hivemind"]}}) (play-from-hand state :corp "Adonis Campaign" "New remote") (take-credits state :corp) (core/gain state :runner :credit 3) (play-from-hand state :runner "Consume") (play-from-hand state :runner "Hivemind") (let [c (get-program state 0) h (get-program state 1)] (is (zero? (get-counters (refresh c) :virus)) "Consume starts with no counters") (is (= 1 (get-counters (refresh h) :virus)) "Hivemind starts with a counter") (run-empty-server state "Server 1") (click-prompt state :runner "Pay 3 [Credits] to trash") (click-prompt state :runner "Yes") (is (= 1 (count (:discard (get-corp)))) "Adonis Campaign trashed") (is (= 1 (get-counters (refresh c) :virus)) "Consume gains a counter") (is (= 1 (get-counters (refresh h) :virus)) "Hivemind retains counter") (is (zero? (:credit (get-runner))) "Runner starts with no credits") (card-ability state :runner c 0) (is (= 4 (:credit (get-runner))) "Runner gains 4 credits") (is (zero? (get-counters (refresh c) :virus)) "Consume loses counters") (is (zero? (get-counters (refresh h) :virus)) "Hivemind loses counters")))) (testing "Hivemind counters only" (do-game (new-game {:runner {:deck ["Consume" "Hivemind"]}}) (take-credits state :corp) (play-from-hand state :runner "Consume") (play-from-hand state :runner "Hivemind") (let [c (get-program state 0) h (get-program state 1)] (is (zero? (get-counters (refresh c) :virus)) "Consume starts with no counters") (is (= 1 (get-counters (refresh h) :virus)) "Hivemind starts with a counter") (is (zero? (:credit (get-runner))) "Runner starts with no credits") (card-ability state :runner c 0) (is (= 2 (:credit (get-runner))) "Runner gains 2 credits") (is (zero? (get-counters (refresh c) :virus)) "Consume loses counters") (is (zero? (get-counters (refresh h) :virus)) "Hivemind loses counters"))))) (deftest cordyceps ;; Cordyceps (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma" "Hedge Fund"]} :runner {:hand ["Cordyceps"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cordyceps") (run-on state "HQ") (let [iw (get-ice state :hq 0) enig (get-ice state :hq 1) cor (get-program state 0)] (is (= 2 (get-counters (refresh cor) :virus)) "Cordyceps was installed with 2 virus tokens") (run-continue state) (run-continue state) (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner (refresh enig)) (click-card state :runner (refresh iw)) (click-prompt state :runner "No action")) (let [iw (get-ice state :hq 1) enig (get-ice state :hq 0) cor (get-program state 0)] (is (= "Ice Wall" (:title iw)) "Ice Wall now outermost ice") (is (= "Enigma" (:title enig)) "Enigma now outermost ice") (is (= 1 (get-counters (refresh cor) :virus)) "Used 1 virus token")) (take-credits state :runner) (take-credits state :corp) (run-on state "R&D") (run-continue state) (click-prompt state :runner "No action") (is (empty? (:prompt (get-runner))) "No prompt on uniced server"))) (testing "No prompt with less than 2 ice installed" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Hedge Fund"]} :runner {:hand ["Cordyceps"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cordyceps") (run-on state "HQ") (run-continue state) (run-continue state) (click-prompt state :runner "No action") (is (empty? (:prompt (get-runner))) "No prompt with only 1 installed ice"))) (testing "No prompt when empty" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma" "Hedge Fund"]} :runner {:hand ["Cordyceps"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cordyceps") (core/add-counter state :runner (get-program state 0) :virus -2) (is (= 0 (get-counters (get-program state 0) :virus)) "Has no virus tokens") (run-on state "HQ") (run-continue state) (run-continue state) (run-continue state) (is (= "You accessed Hedge Fund." (:msg (prompt-map :runner)))) (click-prompt state :runner "No action") (is (empty? (:prompt (get-runner))) "No prompt with no virus counters"))) (testing "Works with Hivemind installed" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma" "Hedge Fund"]} :runner {:hand ["Cordyceps" "Hivemind"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cordyceps") (core/add-counter state :runner (get-program state 0) :virus -2) (play-from-hand state :runner "Hivemind") (run-on state "HQ") (run-continue state) (run-continue state) (run-continue state) (is (= "Use Cordyceps to swap ice?" (:msg (prompt-map :runner)))) (click-prompt state :runner "Yes") (is (= "Select ice protecting this server" (:msg (prompt-map :runner)))) (is (= :select (prompt-type :runner))) (click-card state :runner "Ice Wall") (click-card state :runner "Enigma") (is (= "Select a card with virus counters (0 of 1 virus counters)" (:msg (prompt-map :runner)))) (click-card state :runner "Hivemind") (is (= "Enigma" (:title (get-ice state :hq 0)))) (is (= "Ice Wall" (:title (get-ice state :hq 1)))) (click-prompt state :runner "No action") (is (empty? (:prompt (get-runner))) "No prompt with only 1 installed ice")))) (deftest corroder ;; Corroder (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:credits 15 :hand ["Corroder"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Corroder") (run-on state "HQ") (let [iw (get-ice state :hq 0) cor (get-program state 0)] (rez state :corp iw) (run-continue state) (card-ability state :runner cor 1) (card-ability state :runner cor 0) (click-prompt state :runner "End the run") (is (zero? (count (remove :broken (:subroutines (refresh iw))))) "All subroutines have been broken")))) (deftest cradle ;; Cradle (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["Cradle" (qty "Cache" 100)]}}) (starting-hand state :runner ["Cradle"]) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (core/gain state :runner :credit 100 :click 100) (play-from-hand state :runner "Cradle") (let [cradle (get-program state 0) strength (get-strength (refresh cradle))] (dotimes [n 5] (when (pos? n) (core/draw state :runner n)) (core/fake-checkpoint state) (is (= (- strength n) (get-strength (refresh cradle))) (str "Cradle should lose " n " strength")) (starting-hand state :runner []) (core/fake-checkpoint state) (is (= strength (get-strength (refresh cradle))) (str "Cradle should be back to original strength"))) (click-draw state :runner) (is (= (dec strength) (get-strength (refresh cradle))) "Cradle should lose 1 strength") (play-from-hand state :runner "Cache") (is (= strength (get-strength (refresh cradle))) (str "Cradle should be back to original strength"))))) (deftest crescentus ;; Crescentus should only work on rezzed ice (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["Crescentus" "Corroder"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Corroder") (play-from-hand state :runner "Crescentus") (run-on state "HQ") (let [cor (get-program state 0) cres (get-program state 1) iw (get-ice state :hq 0)] (rez state :corp iw) (run-continue state) (is (rezzed? (refresh iw)) "Ice Wall is now rezzed") (card-ability state :runner cor 0) (click-prompt state :runner "End the run") (card-ability state :runner cres 0) (is (nil? (get-program state 1)) "Crescentus could be used because the ICE is rezzed") (is (not (rezzed? (refresh iw))) "Ice Wall is no longer rezzed")))) (deftest crypsis ;; Crypsis - Loses a virus counter after encountering ice it broke (testing "Breaking a sub spends a virus counter" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Crypsis"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "Archives") (take-credits state :corp) (play-from-hand state :runner "Crypsis") (let [crypsis (get-program state 0)] (card-ability state :runner crypsis 2) (is (= 1 (get-counters (refresh crypsis) :virus)) "Crypsis has 1 virus counter") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (card-ability state :runner (refresh crypsis) 1) ; Match strength (card-ability state :runner (refresh crypsis) 0) ; Break (click-prompt state :runner "End the run") (is (= 1 (get-counters (refresh crypsis) :virus)) "Crypsis has 1 virus counter") (run-continue state) (is (zero? (get-counters (refresh crypsis) :virus)) "Crypsis has 0 virus counters")))) (testing "Inability to remove a virus counter trashes Crypsis" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Crypsis"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "Archives") (take-credits state :corp) (play-from-hand state :runner "Crypsis") (let [crypsis (get-program state 0)] (is (zero? (get-counters (refresh crypsis) :virus)) "Crypsis has 0 virus counters") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (card-ability state :runner (refresh crypsis) 1) ; Match strength (card-ability state :runner (refresh crypsis) 0) ; Break (click-prompt state :runner "End the run") (run-continue state) (is (find-card "Crypsis" (:discard (get-runner))) "Crypsis was trashed")))) (testing "Working with auto-pump-and-break" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Crypsis"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Crypsis") (let [crypsis (get-program state 0) iw (get-ice state :hq 0)] (card-ability state :runner crypsis 2) (is (= 1 (get-counters (refresh crypsis) :virus)) "Crypsis has 1 virus counter") (run-on state "HQ") (rez state :corp (refresh iw)) (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh crypsis)}) (core/continue state :corp nil) (is (= 0 (get-counters (refresh crypsis) :virus)) "Used up virus token on Crypsis"))))) (deftest cyber-cypher (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Macrophage" "Macrophage"] :credits 100} :runner {:hand ["Cyber-Cypher"] :credits 100}}) (play-from-hand state :corp "Macrophage" "R&D") (play-from-hand state :corp "Macrophage" "HQ") (rez state :corp (get-ice state :rd 0)) (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Cyber-Cypher") (click-prompt state :runner "HQ") (let [cc (get-program state 0)] (run-on state :hq) (run-continue state) (card-ability state :runner cc 1) (card-ability state :runner cc 1) (card-ability state :runner cc 1) (is (= 7 (get-strength (refresh cc))) "Can pump Cyber-Cypher on the right server") (card-ability state :runner cc 0) (click-prompt state :runner "Trace 4 - Purge virus counters") (click-prompt state :runner "Trace 3 - Trash a virus") (click-prompt state :runner "Done") (is (= 2 (count (filter :broken (:subroutines (get-ice state :hq 0))))) "Can break subs on the right server") (run-jack-out state)) (let [cc (get-program state 0)] (run-on state :rd) (run-continue state) (card-ability state :runner cc 1) (is (= 4 (get-strength (refresh cc))) "Can't pump Cyber-Cyper on a different server") (core/update! state :runner (assoc (refresh cc) :current-strength 7)) (is (= 7 (get-strength (refresh cc))) "Manually set equal strength") (card-ability state :runner cc 0) (is (empty? (:prompt (get-runner))) "Can't break subs on a different server") (is (zero? (count (filter :broken (:subroutines (get-ice state :rd 0))))) "No subs are broken")))) (deftest d4v1d ;; D4v1d (testing "Can break 5+ strength ice" (do-game (new-game {:corp {:deck ["Ice Wall" "Hadrian's Wall"]} :runner {:deck ["D4v1d"]}}) (core/gain state :corp :credit 10) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Hadrian's Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "D4v1d") (let [had (get-ice state :hq 1) iw (get-ice state :hq 0) d4 (get-program state 0)] (is (= 3 (get-counters d4 :power)) "D4v1d installed with 3 power tokens") (run-on state :hq) (rez state :corp had) (run-continue state) (card-ability state :runner d4 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (is (= 1 (get-counters (refresh d4) :power)) "Used 2 power tokens from D4v1d to break") (run-continue state) (rez state :corp iw) (run-continue state) (card-ability state :runner d4 0) (is (empty? (:prompt (get-runner))) "No prompt for breaking 1 strength Ice Wall"))))) (deftest dai-v ;; Dai V (testing "Basic test" (do-game (new-game {:corp {:deck ["Enigma"]} :runner {:deck [(qty "Cloak" 2) "Dai V"]}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Cloak") (play-from-hand state :runner "Cloak") (play-from-hand state :runner "DPI:NAME:<NAME>END_PI") (run-on state :hq) (let [enig (get-ice state :hq 0) cl1 (get-program state 0) cl2 (get-program state 1) daiv (get-program state 2)] (rez state :corp enig) (run-continue state) (changes-val-macro -1 (:credit (get-runner)) "Used 1 credit to pump and 2 credits from Cloaks to break" (card-ability state :runner daiv 1) (click-prompt state :runner "Done") (card-ability state :runner daiv 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (click-card state :runner cl1) (click-card state :runner cl2)))))) (deftest darwin ;; Darwin - starts at 0 strength (do-game (new-game {:runner {:deck ["Darwin"]}}) (take-credits state :corp) (play-from-hand state :runner "Darwin") (let [darwin (get-program state 0)] (is (zero? (get-counters (refresh darwin) :virus)) "Darwin starts with 0 virus counters") (is (zero? (get-strength (refresh darwin))) "Darwin starts at 0 strength") (take-credits state :runner) (take-credits state :corp) (card-ability state :runner (refresh darwin) 1) ; add counter (is (= 1 (get-counters (refresh darwin) :virus)) "Darwin gains 1 virus counter") (is (= 1 (get-strength (refresh darwin))) "Darwin is at 1 strength")))) (deftest datasucker ;; Datasucker - Reduce strength of encountered ICE (testing "Basic test" (do-game (new-game {:corp {:deck ["Fire Wall"]} :runner {:deck ["Datasucker"]}}) (play-from-hand state :corp "Fire Wall" "New remote") (take-credits state :corp) (core/gain state :runner :click 3) (play-from-hand state :runner "Datasucker") (let [ds (get-program state 0) fw (get-ice state :remote1 0)] (run-empty-server state "Archives") (is (= 1 (get-counters (refresh ds) :virus))) (run-empty-server state "Archives") (is (= 2 (get-counters (refresh ds) :virus))) (run-on state "Server 1") (run-continue state) (run-continue state) (is (= 2 (get-counters (refresh ds) :virus)) "No counter gained, not a central server") (run-on state "Server 1") (rez state :corp fw) (run-continue state) (is (= 5 (get-strength (refresh fw)))) (card-ability state :runner ds 0) (is (= 1 (get-counters (refresh ds) :virus)) "1 counter spent from Datasucker") (is (= 4 (get-strength (refresh fw))) "Fire Wall strength lowered by 1")))) (testing "does not affect next ice when current is trashed. Issue #1788" (do-game (new-game {:corp {:deck ["Wraparound" "Spiderweb"]} :runner {:deck ["Datasucker" "Parasite"]}}) (play-from-hand state :corp "Wraparound" "HQ") (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (core/gain state :corp :credit 10) (play-from-hand state :runner "Datasucker") (let [sucker (get-program state 0) wrap (get-ice state :hq 0) spider (get-ice state :hq 1)] (core/add-counter state :runner sucker :virus 2) (rez state :corp spider) (rez state :corp wrap) (play-from-hand state :runner "Parasite") (click-card state :runner "Spiderweb") (run-on state "HQ") (run-continue state) (card-ability state :runner (refresh sucker) 0) (card-ability state :runner (refresh sucker) 0) (is (find-card "Spiderweb" (:discard (get-corp))) "Spiderweb trashed by Parasite + Datasucker") (is (= 7 (get-strength (refresh wrap))) "Wraparound not reduced by Datasucker"))))) (deftest davinci ;; DaVinci (testing "Gain 1 counter on successful run" (do-game (new-game {:runner {:hand ["DaVinci"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (run-on state "HQ") (changes-val-macro 1 (get-counters (get-program state 0) :power) "DaVinci gains 1 counter on successful run" (run-continue state)))) (testing "Gain no counters on unsuccessful run" (do-game (new-game {:runner {:hand ["DaVinci"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (run-on state "HQ") (run-continue state) (changes-val-macro 0 (get-counters (get-program state 0) :power) "DaVinci does not gain counter on unsuccessful run" (run-jack-out state)))) (testing "Install a card with install cost lower than number of counters" (do-game (new-game {:runner {:hand ["DaPI:NAME:<NAME>END_PIinci" "The Turning Wheel"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (let [davinci (get-program state 0)] (core/add-counter state :runner davinci :power 2) (changes-val-macro 0 (:credit (get-runner)) "DaVinci installs The Turning Wheel for free" (card-ability state :runner (refresh davinci) 0) (click-card state :runner "The Turning Wheel")) (is (get-resource state 0) "The Turning Wheel is installed") (is (find-card "DaVinci" (:discard (get-runner))) "DaVinci is trashed")))) (testing "Using ability should trigger trash effects first. Issue #4987" (do-game (new-game {:runner {:id "PI:NAME:<NAME>END_PI \"GePI:NAME:<NAME>END_PI\" Walker: Tech Lord" :deck ["Simulchip"] :hand ["DaVinci" "The Turning Wheel"]}}) (take-credits state :corp) (play-from-hand state :runner "DaVinci") (let [davinci (get-program state 0)] (core/add-counter state :runner davinci :power 2) (changes-val-macro 0 (:credit (get-runner)) "DaVinci installs Simulchip for free" (card-ability state :runner (refresh davinci) 0) (click-card state :runner "Simulchip")) (is (get-hardware state 0) "Simulchip is installed") (is (find-card "DaVinci" (:discard (get-runner))) "DaVinci is trashed"))))) (deftest demara ;; Demara (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Demara"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Demara") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 2) (is (= :approach-server (:phase (get-run))) "Run has bypassed Ice Wall") (is (find-card "Demara" (:discard (get-runner))) "Demara is trashed"))) (deftest deus-x (testing "vs Multiple Hostile Infrastructure" (do-game (new-game {:corp {:deck [(qty "Hostile Infrastructure" 3)]} :runner {:deck [(qty "Deus X" 3) (qty "Sure Gamble" 2)]}}) (play-from-hand state :corp "Hostile Infrastructure" "New remote") (play-from-hand state :corp "Hostile Infrastructure" "New remote") (play-from-hand state :corp "Hostile Infrastructure" "New remote") (core/gain state :corp :credit 10) (rez state :corp (get-content state :remote1 0)) (rez state :corp (get-content state :remote2 0)) (rez state :corp (get-content state :remote3 0)) (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Deus X") (run-empty-server state "Server 1") (click-prompt state :runner "Pay 5 [Credits] to trash") (let [dx (get-program state 0)] (card-ability state :runner dx 1) (is (= 2 (count (:hand (get-runner)))) "Deus X prevented one Hostile net damage")))) (testing "vs Multiple sources of net damage" (do-game (new-game {:corp {:id "Jinteki: Personal Evolution" :deck [(qty "Fetal AI" 6)]} :runner {:deck [(qty "Deus X" 3) (qty "Sure Gamble" 2)]}}) (play-from-hand state :corp "Fetal AI" "New remote") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Deus X") (run-empty-server state "Server 1") (let [dx (get-program state 0)] (card-ability state :runner dx 1) (click-prompt state :runner "Pay to steal") (is (= 3 (count (:hand (get-runner)))) "Deus X prevented net damage from accessing Fetal AI, but not from Personal Evolution") (is (= 1 (count (:scored (get-runner)))) "Fetal AI stolen"))))) (deftest dhegdheer ;; PI:NAME:<NAME>END_PI - hosting a breaker with strength based on unused MU should calculate correctly (testing "with credit savings" (do-game (new-game {:runner {:deck ["PI:NAME:<NAME>END_PIdept" "PI:NAME:<NAME>END_PI"]}}) (take-credits state :corp) (core/gain state :runner :credit 5) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (play-from-hand state :runner "PI:NAME:<NAME>END_PIdept") (is (= 3 (:credit (get-runner))) "3 credits left after individual installs") (is (= 2 (core/available-mu state)) "2 MU used") (let [dheg (get-program state 0) adpt (get-program state 1)] (is (= 4 (get-strength (refresh adpt))) "Adept at 4 strength individually") (card-ability state :runner dheg 1) (click-card state :runner (refresh adpt)) (let [hosted-adpt (first (:hosted (refresh dheg)))] (is (= 4 (:credit (get-runner))) "4 credits left after hosting") (is (= 4 (core/available-mu state)) "0 MU used") (is (= 6 (get-strength (refresh hosted-adpt))) "Adept at 6 strength hosted"))))) (testing "without credit savings" (do-game (new-game {:runner {:deck ["PI:NAME:<NAME>END_PIdept" "PI:NAME:<NAME>END_PI"]}}) (take-credits state :corp) (core/gain state :runner :credit 5) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (play-from-hand state :runner "Adept") (is (= 3 (:credit (get-runner))) "3 credits left after individual installs") (is (= 2 (core/available-mu state)) "2 MU used") (let [dheg (get-program state 0) adpt (get-program state 1)] (is (= 4 (get-strength (refresh adpt))) "Adept at 4 strength individually") (card-ability state :runner dheg 2) (click-card state :runner (refresh adpt)) (let [hosted-adpt (first (:hosted (refresh dheg)))] (is (= 3 (:credit (get-runner))) "4 credits left after hosting") (is (= 4 (core/available-mu state)) "0 MU used") (is (= 6 (get-strength (refresh hosted-adpt))) "Adept at 6 strength hosted")))))) (deftest disrupter ;; Disrupter (do-game (new-game {:corp {:deck [(qty "SEA Source" 2)]} :runner {:deck ["Disrupter"]}}) (take-credits state :corp) (run-empty-server state "Archives") (play-from-hand state :runner "Disrupter") (take-credits state :runner) (play-from-hand state :corp "SEA Source") (click-prompt state :runner "Yes") (is (zero? (:base (prompt-map :corp))) "Base trace should now be 0") (is (= 1 (-> (get-runner) :discard count)) "Disrupter should be in Heap") (click-prompt state :corp "0") (click-prompt state :runner "0") (is (zero? (count-tags state)) "Runner should gain no tag from beating trace") (play-from-hand state :corp "SEA Source") (is (= 3 (:base (prompt-map :corp))) "Base trace should be reset to 3"))) (deftest diwan ;; Diwan - Full test (do-game (new-game {:corp {:deck [(qty "Ice Wall" 3) (qty "Fire Wall" 3) (qty "Crisium Grid" 2)]} :runner {:deck ["Diwan"]}}) (take-credits state :corp) (play-from-hand state :runner "Diwan") (click-prompt state :runner "HQ") (take-credits state :runner) (is (= 8 (:credit (get-corp))) "8 credits for corp at start of second turn") (play-from-hand state :corp "Ice Wall" "R&D") (is (= 8 (:credit (get-corp))) "Diwan did not charge extra for install on another server") (play-from-hand state :corp "Ice Wall" "HQ") (is (= 7 (:credit (get-corp))) "Diwan charged 1cr to install ice protecting the named server") (play-from-hand state :corp "Crisium Grid" "HQ") (is (= 7 (:credit (get-corp))) "Diwan didn't charge to install another upgrade in root of HQ") (take-credits state :corp) (take-credits state :runner) (play-from-hand state :corp "Ice Wall" "HQ") (is (= 5 (:credit (get-corp))) "Diwan charged 1cr + 1cr to install a second ice protecting the named server") (core/gain state :corp :click 1) (core/purge state :corp) (play-from-hand state :corp "Fire Wall" "HQ") ; 2cr cost from normal install cost (is (= "Diwan" (-> (get-runner) :discard first :title)) "Diwan was trashed from purge") (is (= 3 (:credit (get-corp))) "No charge for installs after Diwan purged"))) (deftest djinn ;; Djinn (testing "Hosted Chakana does not disable advancing agendas. Issue #750" (do-game (new-game {:corp {:deck ["Priority Requisition"]} :runner {:deck ["Djinn" "Chakana"]}}) (play-from-hand state :corp "Priority Requisition" "New remote") (take-credits state :corp 2) (play-from-hand state :runner "Djinn") (let [djinn (get-program state 0) agenda (get-content state :remote1 0)] (is agenda "Agenda was installed") (card-ability state :runner djinn 1) (click-card state :runner (find-card "Chakana" (:hand (get-runner)))) (let [chak (first (:hosted (refresh djinn)))] (is (= "Chakana" (:title chak)) "Djinn has a hosted Chakana") ;; manually add 3 counters (core/add-counter state :runner (first (:hosted (refresh djinn))) :virus 3) (take-credits state :runner 2) (core/advance state :corp {:card agenda}) (is (= 1 (get-counters (refresh agenda) :advancement)) "Agenda was advanced"))))) (testing "Host a non-icebreaker program" (do-game (new-game {:runner {:deck ["PI:NAME:<NAME>END_PI" "Chakana"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (is (= 3 (core/available-mu state))) (let [djinn (get-program state 0)] (card-ability state :runner djinn 1) (click-card state :runner (find-card "Chakana" (:hand (get-runner)))) (is (= 3 (core/available-mu state)) "No memory used to host on Djinn") (is (= "Chakana" (:title (first (:hosted (refresh djinn))))) "Djinn has a hosted Chakana") (is (= 1 (:credit (get-runner))) "Full cost to host on Djinn")))) (testing "Tutor a virus program" (do-game (new-game {:runner {:deck ["PI:NAME:<NAME>END_PI" "Parasite"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (core/move state :runner (find-card "Parasite" (:hand (get-runner))) :deck) (is (zero? (count (:hand (get-runner)))) "No cards in hand after moving Parasite to deck") (let [djinn (get-program state 0)] (card-ability state :runner djinn 0) (click-prompt state :runner (find-card "Parasite" (:deck (get-runner)))) (is (= "Parasite" (:title (first (:hand (get-runner))))) "Djinn moved Parasite to hand") (is (= 2 (:credit (get-runner))) "1cr to use Djinn ability") (is (= 2 (:click (get-runner))) "1click to use Djinn ability"))))) (deftest eater (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 2)]} :runner {:deck [(qty "Eater" 2)]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (core/gain state :runner :credit 100) (play-from-hand state :runner "Eater") (let [eater (get-program state 0) iw (get-ice state :hq 0)] (run-on state "HQ") (rez state :corp (refresh iw)) (run-continue state) (card-ability state :runner eater 0) (click-prompt state :runner "End the run") (run-continue state) (run-continue state) (is (empty? (:prompt (get-runner))) "No prompt for accessing cards")))) (testing "Eater interaction with remote server. Issue #4536" (do-game (new-game {:corp {:deck [(qty "Rototurret" 2) "NGO Front"]} :runner {:deck [(qty "Eater" 2)]}}) (play-from-hand state :corp "NGO Front" "New remote") (play-from-hand state :corp "Rototurret" "Server 1") (take-credits state :corp) (core/gain state :runner :credit 100) (play-from-hand state :runner "Eater") (let [eater (get-program state 0) ngo (get-content state :remote1 0) rt (get-ice state :remote1 0)] (run-on state "Server 1") (rez state :corp (refresh rt)) (run-continue state) (card-ability state :runner eater 0) (click-prompt state :runner "End the run") (click-prompt state :runner "Done") (fire-subs state (refresh rt)) (click-card state :corp eater) (run-continue state) (run-continue state) (is (find-card "Eater" (:discard (get-runner))) "Eater is trashed") (is (empty? (:prompt (get-runner))) "No prompt for accessing cards"))))) (deftest echelon ;; Echelon (before-each [state (new-game {:runner {:hand [(qty "Echelon" 5)] :credits 20} :corp {:deck [(qty "Hedge Fund" 5)] :hand ["Owl"] :credits 20}}) _ (do (play-from-hand state :corp "Owl" "HQ") (take-credits state :corp)) owl (get-ice state :hq 0)] (testing "pump ability" (do-game state (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (let [echelon (get-program state 0)] (run-on state :hq) (rez state :corp owl) (run-continue state :encounter-ice) (changes-val-macro -3 (:credit (get-runner)) "Pump costs 3" (card-ability state :runner echelon 1)) (changes-val-macro 2 (get-strength (refresh echelon)) "Echelon gains 2 str" (card-ability state :runner echelon 1))))) (testing "break ability" (do-game state (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (let [echelon (get-program state 0)] (run-on state :hq) (rez state :corp owl) (run-continue state :encounter-ice) (changes-val-macro -1 (:credit (get-runner)) "Break costs 1" (card-ability state :runner echelon 0) (click-prompt state :runner "Add installed program to the top of the Runner's Stack")) (is (empty? (:prompt (get-runner))) "Only breaks 1 sub at a time")))) (testing "Gains str per icebreaker" (do-game state (take-credits state :corp) (play-from-hand state :runner "Echelon") (let [echelon (get-program state 0)] (is (= 1 (get-strength (refresh echelon))) "0 + 1 icebreaker installed") (play-from-hand state :runner "Echelon") (is (= 2 (get-strength (refresh echelon))) "0 + 2 icebreaker installed") (play-from-hand state :runner "Echelon") (is (= 3 (get-strength (refresh echelon))) "0 + 3 icebreaker installed")))))) (deftest egret ;; Egret (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Mother Goddess"]} :runner {:hand [(qty "Egret" 2)]}}) (play-from-hand state :corp "Mother Goddess" "HQ") (rez state :corp (get-ice state :hq 0)) (let [mg (get-ice state :hq 0)] (take-credits state :corp) (play-from-hand state :runner "Egret") (click-card state :runner mg) (is (has-subtype? (refresh mg) "Barrier")) (is (has-subtype? (refresh mg) "Code Gate")) (is (has-subtype? (refresh mg) "Sentry")) (trash state :runner (first (:hosted (refresh mg)))) (is (not (has-subtype? (refresh mg) "Barrier"))) (is (not (has-subtype? (refresh mg) "Code Gate"))) (is (not (has-subtype? (refresh mg) "Sentry")))))) (deftest engolo ;; Engolo (testing "Subtype is removed when Engolo is trashed mid-encounter. Issue #4039" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"]} :runner {:hand ["Engolo"] :credits 10}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (play-from-hand state :runner "Engolo") (let [roto (get-ice state :hq 0) engolo (get-program state 0)] (run-on state :hq) (rez state :corp roto) (run-continue state) (click-prompt state :runner "Yes") (is (has-subtype? (refresh roto) "Code Gate")) (card-subroutine state :corp roto 0) (click-card state :corp engolo) (run-continue state) (is (nil? (refresh engolo)) "Engolo is trashed") (is (not (has-subtype? (refresh roto) "Code Gate")) "Rototurret loses subtype even when Engolo is trashed")))) (testing "Marks eid as :ability #4962" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"]} :runner {:hand ["Engolo" "Trickster Taka"] :credits 20}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (play-from-hand state :runner "Trickster Taka") (core/add-counter state :runner (get-resource state 0) :credit 2) (play-from-hand state :runner "Engolo") (let [roto (get-ice state :hq 0) engolo (get-program state 0)] (run-on state :hq) (rez state :corp roto) (run-continue state) (changes-val-macro 0 (:credit (get-runner)) "Runner spends credits on Taka" (click-prompt state :runner "Yes") (click-card state :runner "Trickster Taka") (click-card state :runner "Trickster Taka")) (is (zero? (get-counters (get-resource state 0) :credit)) "Taka has been used") (run-jack-out state) (is (nil? (get-run))) (is (empty? (:prompt (get-corp)))) (is (empty? (:prompt (get-runner)))))))) (deftest equivocation ;; Equivocation - interactions with other successful-run events. (do-game (new-game {:corp {:deck [(qty "Restructure" 3) (qty "Hedge Fund" 3)]} :runner {:id "Laramy Fisk: Savvy Investor" :deck ["Equivocation" "Desperado"]}}) (starting-hand state :corp ["Hedge Fund"]) (take-credits state :corp) (play-from-hand state :runner "Equivocation") (play-from-hand state :runner "Desperado") (run-empty-server state :rd) (click-prompt state :runner "Laramy Fisk: Savvy Investor") (click-prompt state :runner "Yes") (is (= 2 (count (:hand (get-corp)))) "Corp forced to draw by Fisk") (click-prompt state :runner "Yes") ; Equivocation prompt (click-prompt state :runner "Yes") ; force the draw (is (= 1 (:credit (get-runner))) "Runner gained 1cr from Desperado") (is (= 3 (count (:hand (get-corp)))) "Corp forced to draw by Equivocation") (click-prompt state :runner "No action") (is (not (:run @state)) "Run ended"))) (deftest euler ;; Euler (testing "Basic test" (do-game (new-game {:runner {:hand ["Euler"] :credits 20} :corp {:hand ["Enigma"]}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Euler") (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state) (changes-val-macro 0 (:credit (get-runner)) "Broke Enigma for 0c" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (get-program state 0)}) (core/continue state :corp nil)) (run-jack-out state) (take-credits state :runner) (take-credits state :corp) (run-on state :hq) (run-continue state) (changes-val-macro -2 (:credit (get-runner)) "Broke Enigma for 2c" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (get-program state 0)}) (core/continue state :corp nil)))) (testing "Correct log test" (do-game (new-game {:runner {:hand ["Euler"] :credits 20} :corp {:hand ["Enigma"]}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Euler") (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (get-program state 0)}) (is (second-last-log-contains? state "Runner pays 0 \\[Credits\\] to use Euler to break all 2 subroutines on Enigma.") "Correct log with correct cost") (core/continue state :corp nil) (run-jack-out state) (take-credits state :runner) (take-credits state :corp) (run-on state :hq) (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (get-program state 0)}) (is (second-last-log-contains? state "Runner pays 2 \\[Credits\\] to use Euler to break all 2 subroutines on Enigma.") "Correct second log with correct cost") (core/continue state :corp nil)))) (deftest expert-schedule-analyzer ;; Expert Schedule Analyzer (do-game (new-game {:runner {:deck ["Expert Schedule Analyzer"]}}) (take-credits state :corp) (play-from-hand state :runner "Expert Schedule Analyzer") (card-ability state :runner (get-program state 0) 0) (run-continue state) (is (= "Choose an access replacement ability" (:msg (prompt-map :runner))) "Replacement effect is optional") (click-prompt state :runner "Expert Schedule Analyzer") (is (last-log-contains? state "Runner uses Expert Schedule Analyzer to reveal all of the cards cards in HQ:") "All of HQ is revealed correctly"))) (deftest faerie (testing "Trash after encounter is over, not before" (do-game (new-game {:corp {:deck ["PI:NAME:<NAME>END_PI"]} :runner {:deck ["PI:NAME:<NAME>END_PI"]}}) (play-from-hand state :corp "PI:NAME:<NAME>END_PI" "Archives") (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (let [fae (get-program state 0)] (run-on state :archives) (rez state :corp (get-ice state :archives 0)) (run-continue state) (card-ability state :runner fae 1) (card-ability state :runner fae 0) (click-prompt state :runner "Trace 3 - Gain 3 [Credits]") (click-prompt state :runner "Trace 2 - End the run") (is (refresh fae) "Faerie not trashed until encounter over") (run-continue state) (is (find-card "PI:NAME:<NAME>END_PI" (:discard (get-runner))) "Faerie trashed")))) (testing "Works with auto-pump-and-break" (do-game (new-game {:corp {:deck ["PI:NAME:<NAME>END_PI"]} :runner {:deck ["PI:NAME:<NAME>END_PI"]}}) (play-from-hand state :corp "PI:NAME:<NAME>END_PI" "Archives") (take-credits state :corp) (play-from-hand state :runner "Faerie") (let [fae (get-program state 0)] (run-on state :archives) (rez state :corp (get-ice state :archives 0)) (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh fae)}) (core/continue state :corp nil) (is (find-card "Faerie" (:discard (get-runner))) "Faerie trashed"))))) (deftest false-echo ;; False Echo - choice for Corp (testing "Add to HQ" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["False Echo"]}}) (play-from-hand state :corp "Ice Wall" "Archives") (take-credits state :corp) (play-from-hand state :runner "False Echo") (run-on state "Archives") (run-continue state) (click-prompt state :runner "Yes") (click-prompt state :corp "Add to HQ") (is (find-card "Ice Wall" (:hand (get-corp))) "Ice Wall added to HQ") (is (find-card "False Echo" (:discard (get-runner))) "False Echo trashed"))) (testing "Rez" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["False Echo"]}}) (play-from-hand state :corp "Ice Wall" "Archives") (take-credits state :corp) (play-from-hand state :runner "False Echo") (run-on state "Archives") (run-continue state) (click-prompt state :runner "Yes") (click-prompt state :corp "Rez") (is (rezzed? (get-ice state :archives 0)) "Ice Wall rezzed") (is (find-card "False Echo" (:discard (get-runner))) "False Echo trashed")))) (deftest faust (testing "Basic test: Break by discarding" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:deck ["Faust" "Sure Gamble"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Faust") (let [faust (get-program state 0)] (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner faust 0) (click-prompt state :runner "End the run") (click-card state :runner "Sure Gamble") (is (= 1 (count (:discard (get-runner)))) "1 card trashed")))) (testing "Basic test: Pump by discarding" (do-game (new-game {:runner {:deck ["Faust" "Sure Gamble"]}}) (take-credits state :corp) (play-from-hand state :runner "Faust") (let [faust (get-program state 0)] (card-ability state :runner faust 1) (click-card state :runner "Sure Gamble") (is (= 4 (get-strength (refresh faust))) "4 current strength") (is (= 1 (count (:discard (get-runner)))) "1 card trashed")))) (testing "Pump does not trigger trash prevention. #760" (do-game (new-game {:runner {:hand ["Faust" "Sacrificial Construct" "Fall Guy" "Astrolabe" "Gordian Blade" "Armitage Codebusting"]}}) (take-credits state :corp) (play-from-hand state :runner "Faust") (play-from-hand state :runner "Fall Guy") (play-from-hand state :runner "Sacrificial Construct") (is (= 2 (count (get-resource state))) "Resources installed") (let [faust (get-program state 0)] (card-ability state :runner faust 1) (click-card state :runner "Astrolabe") (is (empty? (:prompt (get-runner))) "No trash-prevention prompt for hardware") (card-ability state :runner faust 1) (click-card state :runner "PI:NAME:<NAME>END_PI") (is (empty? (:prompt (get-runner))) "No trash-prevention prompt for program") (card-ability state :runner faust 1) (click-card state :runner "Armitage Codebusting") (is (empty? (:prompt (get-runner))) "No trash-prevention prompt for resource"))))) (deftest femme-fatale ;; Femme Fatale (testing "Bypass functionality" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Femme Fatale"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (let [iw (get-ice state :hq 0)] (play-from-hand state :runner "Femme Fatale") (click-card state :runner iw) (run-on state "HQ") (rez state :corp iw) (run-continue state) (is (= "Pay 1 [Credits] to bypass Ice Wall?" (:msg (prompt-map :runner)))) (click-prompt state :runner "Yes") (is (= :approach-server (:phase (get-run))) "Femme Fatale has bypassed Ice Wall")))) (testing "Bypass leaves if uninstalled" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["Femme Fatale"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (let [iw (get-ice state :hq 0)] (play-from-hand state :runner "Femme Fatale") (click-card state :runner iw) (core/move state :runner (get-program state 0) :deck) (run-on state "HQ") (rez state :corp iw) (run-continue state) (is (nil? (prompt-map :runner)) "Femme ability doesn't fire after uninstall")))) (testing "Bypass doesn't persist if ice is uninstalled and reinstalled" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:hand ["PI:NAME:<NAME>END_PIme Fatale"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Femme Fatale") (click-card state :runner (get-ice state :hq 0)) (core/move state :corp (get-ice state :hq 0) :hand) (take-credits state :runner) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (is (nil? (prompt-map :runner)) "Femme ability doesn't fire after uninstall")))) (deftest fermenter ;; Fermenter - click, trash to get 2c per counter. (testing "Trash and cash out" (do-game (new-game {:runner {:deck ["Fermenter"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (let [fermenter (get-program state 0)] (is (= 1 (get-counters (refresh fermenter) :virus)) "Fermenter has 1 counter from install") (take-credits state :runner) (take-credits state :corp) (is (= 2 (get-counters (refresh fermenter) :virus)) "Fermenter has 2 counters") (changes-val-macro 4 (:credit (get-runner)) "Gain 4 credits from Fermenter ability" (card-ability state :runner fermenter 0)) (is (= 1 (count (:discard (get-runner)))) "Fermenter is trashed")))) (testing "Hivemind interaction" (do-game (new-game {:corp {:deck ["PI:NAME:<NAME>END_PI"]} :runner {:deck ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (take-credits state :runner) (take-credits state :corp) (let [fermenter (get-program state 0) hivemind (get-program state 1)] (is (= 2 (get-counters (refresh fermenter) :virus)) "Fermenter has 2 counters") (is (= 1 (get-counters (refresh hivemind) :virus)) "Hivemind has 1 counter") (changes-val-macro 6 (:credit (get-runner)) "Gain 6 credits from Fermenter ability" (card-ability state :runner fermenter 0)) (is (= 1 (count (:discard (get-runner)))) "Fermenter is trashed") (is (= 1 (get-counters (refresh hivemind) :virus)) "Hivemind has still 1 counter"))))) (deftest gauss ;; Gauss (testing "Loses strength at end of Runner's turn" (do-game (new-game {:runner {:deck ["PI:NAME:<NAME>END_PI"]} :options {:start-as :runner}}) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (let [gauss (get-program state 0)] (is (= 4 (get-strength (refresh gauss))) "+3 base strength") (run-on state :hq) (card-ability state :runner (refresh gauss) 1) ;; boost (is (= 6 (get-strength (refresh gauss))) "+3 base and boosted strength") (run-jack-out state) (is (= 4 (get-strength (refresh gauss))) "Boost lost after run") (take-credits state :runner) (is (= 1 (get-strength (refresh gauss))) "Back to normal strength")))) (testing "Loses strength at end of Corp's turn" (do-game (new-game {:runner {:deck ["Gauss"]}}) (core/gain state :runner :click 1) (play-from-hand state :runner "Gauss") (let [gauss (get-program state 0)] (is (= 4 (get-strength (refresh gauss))) "+3 base strength") (take-credits state :corp) (is (= 1 (get-strength (refresh gauss))) "Back to normal strength"))))) (deftest god-of-war ;; God of War - Take 1 tag to place 2 virus counters (do-game (new-game {:runner {:deck ["God of War"]}}) (take-credits state :corp) (play-from-hand state :runner "God of War") (take-credits state :runner) (take-credits state :corp) (let [gow (get-program state 0)] (card-ability state :runner gow 2) (is (= 1 (count-tags state))) (is (= 2 (get-counters (refresh gow) :virus)) "God of War has 2 virus counters")))) (deftest grappling-hook ;; Grappling Hook (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Little Engine"] :credits 10} :runner {:hand [(qty "Grappling Hook" 2) "Corroder" "Torch"] :credits 100}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Little Engine" "New remote") (take-credits state :corp) (core/gain state :runner :click 10) (play-from-hand state :runner "Grappling Hook") (play-from-hand state :runner "Grappling Hook") (play-from-hand state :runner "Corroder") (play-from-hand state :runner "Torch") (let [iw (get-ice state :hq 0) le (get-ice state :remote1 0) gh1 (get-program state 0) gh2 (get-program state 1) cor (get-program state 2) torch (get-program state 3)] (run-on state :hq) (rez state :corp iw) (run-continue state) (card-ability state :runner gh1 0) (is (empty? (:prompt (get-runner))) "No break prompt as Ice Wall only has 1 subroutine") (is (refresh gh1) "Grappling Hook isn't trashed") (card-ability state :runner cor 0) (click-prompt state :runner "End the run") (card-ability state :runner gh1 0) (is (empty? (:prompt (get-runner))) "No break prompt as Ice Wall has no unbroken subroutines") (is (refresh gh1) "Grappling Hook isn't trashed") (run-jack-out state) (run-on state :remote1) (rez state :corp le) (run-continue state) (card-ability state :runner gh1 0) (is (seq (:prompt (get-runner))) "Grappling Hook creates break prompt") (click-prompt state :runner "End the run") (is (= 2 (count (filter :broken (:subroutines (refresh le))))) "Little Engine has 2 of 3 subroutines broken") (is (nil? (refresh gh1)) "Grappling Hook is now trashed") (run-jack-out state) (run-on state :remote1) (run-continue state) (core/update! state :runner (assoc (refresh torch) :current-strength 7)) (card-ability state :runner torch 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (click-prompt state :runner "Done") (card-ability state :runner gh2 0) (is (empty? (:prompt (get-runner))) "No break prompt as Little Engine has more than 1 broken sub") (is (refresh gh2) "Grappling Hook isn't trashed")))) (testing "Interaction with Fairchild 3.0" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Fairchild 3.0"] :credits 6} :runner {:hand ["Grappling Hook"] }}) (play-from-hand state :corp "Fairchild 3.0" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Grappling Hook") (run-on state "HQ") (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "Do 1 brain damage or end the run") (is (= 1 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broke all but one subroutine") (is (= "Do 1 brain damage or end the run" (:label (first (remove :broken (:subroutines (get-ice state :hq 0)))))) "Broke all but selected sub") (is (nil? (refresh (get-program state 0))) "Grappling Hook is now trashed"))) (testing "interaction with News Hound #4988" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["News Hound" "Surveillance Sweep"] :credits 10} :runner {:hand ["Grappling Hook"] :credits 100}}) (play-from-hand state :corp "News Hound" "HQ") (play-from-hand state :corp "Surveillance Sweep") (take-credits state :corp) (play-from-hand state :runner "Grappling Hook") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "Trace 3 - Give the Runner 1 tag") (fire-subs state (get-ice state :hq 0)) (click-prompt state :runner "10") (click-prompt state :corp "1") (is (zero? (count-tags state)) "Runner gained no tags") (is (get-run) "Run hasn't ended") (is (empty? (:prompt (get-corp))) "Corp shouldn't have a prompt") (is (empty? (:prompt (get-runner))) "Runner shouldn't have a prompt"))) (testing "Selecting a sub when multiple of the same title exist #5291" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Hive"] :credits 10} :runner {:hand ["Grappling Hook" "Gbahali"] :credits 10}}) (play-from-hand state :corp "Hive" "HQ") (take-credits state :corp) (play-from-hand state :runner "Grappling Hook") (play-from-hand state :runner "Gbahali") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) "Break all but 1 subroutine") (click-prompt state :runner "End the run" {:idx 4}) (card-ability state :runner (get-resource state 0) "Break the last subroutine") (is (core/all-subs-broken? (get-ice state :hq 0)) "Grappling Hook and Gbahali worked together")))) (deftest gravedigger ;; Gravedigger - Gain counters when Corp cards are trashed, spend click-counter to mill Corp (do-game (new-game {:corp {:deck [(qty "Launch Campaign" 2) (qty "Enigma" 2)]} :runner {:deck ["Gravedigger"]}}) (play-from-hand state :corp "Launch Campaign" "New remote") (play-from-hand state :corp "Launch Campaign" "New remote") (take-credits state :corp) (play-from-hand state :runner "Gravedigger") (let [gd (get-program state 0)] (trash state :corp (get-content state :remote1 0)) (is (= 1 (get-counters (refresh gd) :virus)) "Gravedigger gained 1 counter") (trash state :corp (get-content state :remote2 0)) (is (= 2 (get-counters (refresh gd) :virus)) "Gravedigger gained 1 counter") (core/move state :corp (find-card "Enigma" (:hand (get-corp))) :deck) (core/move state :corp (find-card "Enigma" (:hand (get-corp))) :deck) (is (= 2 (count (:deck (get-corp))))) (card-ability state :runner gd 0) (is (= 1 (get-counters (refresh gd) :virus)) "Spent 1 counter from Gravedigger") (is (= 2 (:click (get-runner))) "Spent 1 click") (is (= 1 (count (:deck (get-corp))))) (is (= 3 (count (:discard (get-corp)))) "Milled 1 card from R&D")))) (deftest harbinger ;; Harbinger (testing "install facedown when Blacklist installed" (do-game (new-game {:corp {:deck ["Blacklist"]} :runner {:deck ["Harbinger"]}}) (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (get-content state :remote1 0)) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (trash state :runner (-> (get-runner) :rig :program first)) (is (zero? (count (:discard (get-runner)))) "Harbinger not in heap") (is (-> (get-runner) :rig :facedown first :facedown) "Harbinger installed facedown")))) (deftest hyperdriver ;; Hyperdriver - Remove from game to gain 3 clicks (testing "Basic test" (do-game (new-game {:runner {:deck ["Hyperdriver"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PIdriver") (is (= 1 (core/available-mu state)) "3 MU used") (take-credits state :runner) (take-credits state :corp) (is (:runner-phase-12 @state) "Runner in Step 1.2") (let [hyp (get-program state 0)] (card-ability state :runner hyp 0) (end-phase-12 state :runner) (is (= 7 (:click (get-runner))) "Gained 3 clicks") (is (= 1 (count (:rfg (get-runner)))) "Hyperdriver removed from game")))) (testing "triggering a Dhegdeered Hyperdriver should not grant +3 MU" (do-game (new-game {:runner {:deck ["Hyperdriver" "Dhegdheer"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PIgdheer") (let [dheg (get-program state 0)] (card-ability state :runner dheg 0) (click-card state :runner (find-card "Hyperdriver" (:hand (get-runner)))) (is (= 4 (core/available-mu state)) "0 MU used by Hyperdriver hosted on Dhegdheer") (is (= 2 (:click (get-runner))) "2 clicks used") (is (= 3 (:credit (get-runner))) "2 credits used") (take-credits state :runner) (take-credits state :corp) (is (:runner-phase-12 @state) "Runner in Step 1.2") (let [hyp (first (:hosted (refresh dheg)))] (card-ability state :runner hyp 0) (end-phase-12 state :runner) (is (= 7 (:click (get-runner))) "Used Hyperdriver") (is (= 4 (core/available-mu state)) "Still 0 MU used after Hyperdriver removed from game")))))) (deftest ika ;; Ika (testing "Can be hosted on both rezzed/unrezzed ice, respects no-host, is blanked by Magnet" (do-game (new-game {:corp {:deck ["Tithonium" "Enigma" "Magnet"]} :runner {:deck ["Ika"]}}) (play-from-hand state :corp "Enigma" "HQ") (play-from-hand state :corp "Tithonium" "Archives") (play-from-hand state :corp "Magnet" "R&D") (take-credits state :corp) (play-from-hand state :runner "Ika") (core/gain state :runner :credit 100) (core/gain state :corp :credit 100) (let [ika (get-program state 0) enigma (get-ice state :hq 0) tithonium (get-ice state :archives 0) magnet (get-ice state :rd 0)] (let [creds (:credit (get-runner))] (card-ability state :runner ika 0) ; host on a piece of ice (click-card state :runner tithonium) (is (utils/same-card? ika (first (:hosted (refresh tithonium)))) "Ika was rehosted") (is (= (- creds 2) (:credit (get-runner))) "Rehosting from rig cost 2 creds")) (run-on state :archives) (run-continue state) (let [creds (:credit (get-runner)) ika (first (:hosted (refresh tithonium)))] (card-ability state :runner ika 0) (click-card state :runner enigma) (is (utils/same-card? ika (first (:hosted (refresh enigma)))) "Ika was rehosted") (is (= (- creds 2) (:credit (get-runner))) "Rehosting from ice during run cost 2 creds")) (rez state :corp tithonium) (let [creds (:credit (get-runner)) ika (first (:hosted (refresh enigma)))] (card-ability state :runner ika 0) (click-card state :runner tithonium) (is (zero?(count (:hosted (refresh tithonium)))) "Ika was not hosted on Tithonium") (is (= creds (:credit (get-runner))) "Clicking invalid targets is free") (click-prompt state :runner "Done") (rez state :corp magnet) (click-card state :corp ika) (is (zero?(count (:hosted (refresh enigma)))) "Ika was removed from Enigma") (is (= 1 (count (:hosted (refresh magnet)))) "Ika was hosted onto Magnet") (let [ika (first (:hosted (refresh magnet)))] (is (zero?(count (:abilities ika))) "Ika was blanked"))))))) (deftest imp ;; Imp (testing "Full test" (letfn [(imp-test [card] (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand [card]} :runner {:deck ["Imp"]}}) (take-credits state :corp) (play-from-hand state :runner "Imp") (run-empty-server state "HQ") (click-prompt state :runner "[Imp] Hosted virus counter: Trash card") (is (= 1 (count (:discard (get-corp)))))))] (doall (map imp-test ["Hostile Takeover" "Dedicated Response Team" "Beanstalk Royalties" "Ice Wall" "Oberth Protocol"])))) (testing "vs an ambush" (do-game (new-game {:corp {:deck ["Prisec"]} :runner {:deck ["Imp" (qty "Sure Gamble" 3)]}}) (play-from-hand state :corp "Prisec" "New remote") (take-credits state :corp) (let [credits (:credit (get-corp)) tags (count-tags state) grip (count (:hand (get-runner))) archives (count (:discard (get-corp)))] (play-from-hand state :runner "Imp") (run-empty-server state :remote1) (click-prompt state :corp "Yes") (click-prompt state :runner "[Imp] Hosted virus counter: Trash card") (is (= 2 (- credits (:credit (get-corp)))) "Corp paid 2 for Prisec") (is (= 1 (- (count-tags state) tags)) "Runner has 1 tag") (is (= 2 (- grip (count (:hand (get-runner))))) "Runner took 1 meat damage") (is (= 1 (- (count (:discard (get-corp))) archives)) "Used Imp to trash Prisec")))) (testing "vs The Future Perfect" ;; Psi-game happens on access [5.5.1], Imp is a trash ability [5.5.2] (do-game (new-game {:corp {:deck ["The Future Perfect"]} :runner {:deck ["Imp"]}}) (take-credits state :corp) (play-from-hand state :runner "Imp") (testing "Access, corp wins psi-game" (run-empty-server state "HQ") ;; Should access TFP at this point (click-prompt state :corp "1 [Credits]") (click-prompt state :runner "0 [Credits]") (click-prompt state :runner "[Imp] Hosted virus counter: Trash card") (take-credits state :runner) (is (= "The Future Perfect" (get-in @state [:corp :discard 0 :title])) "TFP trashed") (is (zero? (:agenda-point (get-runner))) "Runner did not steal TFP") (core/move state :corp (find-card "The Future Perfect" (:discard (get-corp))) :hand)) (take-credits state :runner) (take-credits state :corp) (testing "Access, runner wins psi-game" (run-empty-server state "HQ") ;; Access prompt for TFP (click-prompt state :corp "0 [Credits]") (click-prompt state :runner "0 [Credits]") ;; Fail psi game (click-prompt state :runner "[Imp] Hosted virus counter: Trash card") (is (= "The Future Perfect" (get-in @state [:corp :discard 0 :title])) "TFP trashed") (is (zero? (:agenda-point (get-runner))) "Runner did not steal TFP")))) (testing "vs cards in Archives" (do-game (new-game {:corp {:deck ["Hostile Takeover"]} :runner {:deck ["Imp"]}}) (core/move state :corp (find-card "Hostile Takeover" (:hand (get-corp))) :discard) (take-credits state :corp) (play-from-hand state :runner "Imp") (run-empty-server state "Archives") (is (= ["Steal"] (prompt-buttons :runner)) "Should only get the option to steal Hostile on access in Archives"))) (testing "Hivemind installed #5000" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"]} :runner {:deck ["Imp" "Hivemind"]}}) (take-credits state :corp) (play-from-hand state :runner "Hivemind") (is (= 1 (get-counters (get-program state 0) :virus))) (play-from-hand state :runner "Imp") (core/add-counter state :runner (get-program state 1) :virus -2) (is (= 0 (get-counters (get-program state 1) :virus))) (run-empty-server state "HQ") (click-prompt state :runner "[Imp] Hosted virus counter: Trash card") (click-card state :runner "Hivemind") (is (= 1 (count (:discard (get-corp))))) (is (= 0 (get-counters (get-program state 0) :virus))))) (testing "can't be used when empty #5190" (do-game (new-game {:corp {:hand ["Hostile Takeover"]} :runner {:hand ["Imp" "Cache"]}}) (take-credits state :corp) (play-from-hand state :runner "Cache") (play-from-hand state :runner "Imp") (core/update! state :runner (assoc-in (get-program state 1) [:counter :virus] 0)) (run-empty-server state "HQ") (is (= ["Steal"] (prompt-buttons :runner)) "Should only get the option to steal Hostile on access in Archives")))) (deftest incubator ;; Incubator - Gain 1 virus counter per turn; trash to move them to an installed virus program (do-game (new-game {:runner {:deck ["Incubator" "Datasucker"]}}) (take-credits state :corp) (play-from-hand state :runner "Datasucker") (play-from-hand state :runner "Incubator") (take-credits state :runner) (take-credits state :corp) (let [ds (get-program state 0) incub (get-program state 1)] (is (= 1 (get-counters (refresh incub) :virus)) "Incubator gained 1 virus counter") (take-credits state :runner) (take-credits state :corp) (is (= 2 (get-counters (refresh incub) :virus)) "Incubator has 2 virus counters") (card-ability state :runner incub 0) (click-card state :runner ds) (is (= 2 (get-counters (refresh ds) :virus)) "Datasucker has 2 virus counters moved from Incubator") (is (= 1 (count (get-program state)))) (is (= 1 (count (:discard (get-runner)))) "Incubator trashed") (is (= 3 (:click (get-runner))))))) (deftest inversificator ;; Inversificator (testing "Shouldn't hook up events for unrezzed ice" (do-game (new-game {:corp {:deck ["Turing" "Kakugo"]} :runner {:deck ["Inversificator" "Sure Gamble"]}}) (play-from-hand state :corp "Kakugo" "HQ") (play-from-hand state :corp "Turing" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Inversificator") (let [inv (get-program state 0) tur (get-ice state :hq 1)] (is (= 1 (count (:hand (get-runner)))) "Runner starts with 1 card in hand") (run-on state "HQ") (rez state :corp (refresh tur)) (run-continue state) (card-ability state :runner (refresh inv) 0) (click-prompt state :runner "End the run unless the Runner spends [Click][Click][Click]") (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner (get-ice state :hq 1)) (click-card state :runner (get-ice state :hq 0)) (run-jack-out state) (is (= 1 (count (:hand (get-runner)))) "Runner still has 1 card in hand") (run-on state :hq) (run-continue state) (is (= 1 (count (:hand (get-runner)))) "Kakugo doesn't fire when unrezzed")))) (testing "Switched ice resets broken subs. Issue #4857" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand [(qty "Viktor 1.0" 2)] :credits 20} :runner {:hand ["Inversificator"] :credits 20}}) (play-from-hand state :corp "Viktor 1.0" "HQ") (rez state :corp (get-ice state :hq 0)) (play-from-hand state :corp "Viktor 1.0" "New remote") (rez state :corp (get-ice state :remote1 0)) (take-credits state :corp) (play-from-hand state :runner "Inversificator") (run-on state "HQ") (run-continue state) (let [inv (get-program state 0)] (card-ability state :runner (refresh inv) 1) (card-ability state :runner (refresh inv) 0) (click-prompt state :runner "Do 1 brain damage") (click-prompt state :runner "End the run") (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner (get-ice state :hq 0)) (click-card state :runner (get-ice state :remote1 0)) (run-continue state) (is (not-any? :broken (:subroutines (get-ice state :remote1 0))) "None of the subs are marked as broken anymore")))) (testing "Doesn't fire when other programs break an ice. Issue #4858" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand [(qty "Viktor 1.0" 2)] :credits 20} :runner {:hand ["Inversificator" "Maven" "Cache"] :credits 20}}) (play-from-hand state :corp "Viktor 1.0" "HQ") (rez state :corp (get-ice state :hq 0)) (play-from-hand state :corp "Viktor 1.0" "New remote") (rez state :corp (get-ice state :remote1 0)) (take-credits state :corp) (core/gain state :runner :click 10) (play-from-hand state :runner "Cache") (play-from-hand state :runner "Maven") (play-from-hand state :runner "Inversificator") ;; Use Inversificator in another run first (run-on state "Server 1") (run-continue state) (let [maven (get-program state 1) inv (get-program state 2)] (card-ability state :runner (refresh inv) 1) (card-ability state :runner (refresh inv) 0) (click-prompt state :runner "Do 1 brain damage") (click-prompt state :runner "End the run") (run-continue state) (click-prompt state :runner "No") (run-continue state) ;; Use non-Inversificator breaker (run-on state "HQ") (run-continue state) (card-ability state :runner (refresh maven) 0) (click-prompt state :runner "Do 1 brain damage") (click-prompt state :runner "End the run") (run-continue state) (is (not (prompt-is-card? state :runner inv)) "Prompt shouldn't be Inversificator") (is (empty? (:prompt (get-corp))) "Corp shouldn't have a prompt") (is (empty? (:prompt (get-runner))) "Runner shouldn't have a prompt")))) (testing "Inversificator shouldn't fire when ice is unrezzed. Issue #4859" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Viktor 1.0" "Quandary"] :credits 20} :runner {:hand ["Inversificator"] :credits 20}}) (play-from-hand state :corp "Quandary" "HQ") (play-from-hand state :corp "Viktor 1.0" "HQ") (take-credits state :corp) (play-from-hand state :runner "Inversificator") (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (run-continue state) (let [inv (get-program state 0)] (card-ability state :runner (refresh inv) 1) (card-ability state :runner (refresh inv) 0) (click-prompt state :runner "Do 1 brain damage") (click-prompt state :runner "End the run") (run-continue state) (click-prompt state :runner "No") (run-continue state) (run-continue state) (is (not (prompt-is-card? state :runner inv)) "Prompt shouldn't be Inversificator") (is (empty? (:prompt (get-corp))) "Corp shouldn't have a prompt") (is (empty? (:prompt (get-runner))) "Runner shouldn't have a prompt")))) (testing "shouldn't fire ice's on-pass ability #5143" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Kakugo" "Quandary"] :credits 20} :runner {:hand ["Sure Gamble" "Inversificator"] :credits 20}}) (play-from-hand state :corp "Quandary" "HQ") (play-from-hand state :corp "Kakugo" "HQ") (take-credits state :corp) (play-from-hand state :runner "Inversificator") (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (core/register-floating-effect state :corp nil (let [ice (get-ice state :hq 1)] {:type :gain-subtype :req (req (utils/same-card? ice target)) :value "Code Gate"})) (run-continue state) (let [inv (get-program state 0)] (card-ability state :runner (refresh inv) 1) (card-ability state :runner (refresh inv) 0) (click-prompt state :runner "End the run") (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner (get-ice state :hq 1)) (click-card state :runner (get-ice state :hq 0)) (is (= 1 (count (:hand (get-runner)))))))) (testing "Async issue with Thimblerig #5042" (do-game (new-game {:corp {:hand ["Drafter" "Border Control" "Vanilla" "Thimblerig"] :credits 100} :runner {:hand ["Inversificator"] :credits 100}}) (core/gain state :corp :click 1) (play-from-hand state :corp "Border Control" "R&D") (play-from-hand state :corp "Drafter" "R&D") (play-from-hand state :corp "Vanilla" "HQ") (play-from-hand state :corp "Thimblerig" "HQ") (take-credits state :corp) (play-from-hand state :runner "Inversificator") (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "End the run") (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner "Drafter") (is (= ["Border Control" "Thimblerig"] (map :title (get-ice state :rd)))) (is (= ["Vanilla" "Drafter"] (map :title (get-ice state :hq)))) (is (empty? (:prompt (get-corp))) "Corp gets no Thimblerig prompt") (is (empty? (:prompt (get-runner))) "No more prompts open"))) (testing "Swap vs subtype issues #5170" (do-game (new-game {:corp {:hand ["Drafter" "Data Raven" "Vanilla"] :credits 100} :runner {:id "PI:NAME:<NAME>END_PI \"Kit\" Peddler: PI:NAME:<NAME>END_PIuman" :hand ["Inversificator" "Hunting Grounds" "Stargate"] :credits 100}}) (play-from-hand state :corp "Data Raven" "R&D") (play-from-hand state :corp "Drafter" "R&D") (play-from-hand state :corp "Vanilla" "Archives") (take-credits state :corp) (play-from-hand state :runner "Inversificator") (play-from-hand state :runner "Hunting Grounds") (play-from-hand state :runner "Stargate") (core/gain state :runner :click 10) (let [inv (get-program state 0) hg (get-resource state 0) sg (get-program state 1)] (card-ability state :runner sg 0) (run-continue state) (rez state :corp (get-ice state :rd 0)) (card-ability state :runner hg 0) (run-continue state) (card-ability state :runner inv 1) (card-ability state :runner inv 1) (card-ability state :runner inv 0) (click-prompt state :runner "Trace 3 - Add 1 power counter") (run-continue state) (click-prompt state :runner "Yes") (click-card state :runner "Vanilla") (is (= ["Vanilla" "Drafter"] (map :title (get-ice state :rd)))) (is (= ["Data Raven"] (map :title (get-ice state :archives)))))))) (deftest ixodidae ;; Ixodidae should not trigger on psi-games (do-game (new-game {:corp {:deck ["Snowflake"]} :runner {:deck ["Ixodidae" "Lamprey"]}}) (play-from-hand state :corp "Snowflake" "HQ") (take-credits state :corp) (is (= 7 (:credit (get-corp))) "Corp at 7 credits") (play-from-hand state :runner "Ixodidae") (play-from-hand state :runner "Lamprey") (is (= 3 (:credit (get-runner))) "Runner paid 3 credits to install Ixodidae and Lamprey") (run-on state :hq) (let [s (get-ice state :hq 0)] (rez state :corp s) (run-continue state) (card-subroutine state :corp s 0) (is (prompt-is-card? state :corp s) "Corp prompt is on Snowflake") (is (prompt-is-card? state :runner s) "Runner prompt is on Snowflake") (is (= 6 (:credit (get-corp))) "Corp paid 1 credit to rezz Snowflake") (click-prompt state :corp "1 [Credits]") (click-prompt state :runner "1 [Credits]") (is (= 5 (:credit (get-corp))) "Corp paid 1 credit to psi game") (is (= 2 (:credit (get-runner))) "Runner did not gain 1 credit from Ixodidae when corp spent on psi game") (run-continue state) (run-continue state) (is (= 4 (:credit (get-corp))) "Corp lost 1 credit to Lamprey") (is (= 3 (:credit (get-runner))) "Runner gains 1 credit from Ixodidae due to Lamprey")))) (deftest keyhole ;; Keyhole (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 10)] :hand ["Herald" "Troll"]} :runner {:hand ["Keyhole"]}}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (is (= "Troll" (-> (get-corp) :deck first :title)) "Troll on top of deck") (is (= "Herald" (-> (get-corp) :deck second :title)) "Herald 2nd") (take-credits state :corp) (play-from-hand state :runner "Keyhole") (card-ability state :runner (get-program state 0) 0) (is (:run @state) "Run initiated") (run-continue state) (let [number-of-shuffles (count (core/turn-events state :corp :corp-shuffle-deck))] (click-prompt state :runner "Troll") (is (empty? (:prompt (get-runner))) "Prompt closed") (is (not (:run @state)) "Run ended") (is (-> (get-corp) :discard first :seen) "Troll is faceup") (is (= "Troll" (-> (get-corp) :discard first :title)) "Troll was trashed") (is (find-card "Herald" (:deck (get-corp))) "Herald now in R&D") (is (< number-of-shuffles (count (core/turn-events state :corp :corp-shuffle-deck))) "Corp has shuffled R&D")) (card-ability state :runner (get-program state 0) 0) (is (:run @state) "Keyhole can be used multiple times per turn")))) (deftest kyuban ;; Kyuban (testing "Gain creds when passing a piece of ice, both when rezzed and when unrezzed." (do-game (new-game {:corp {:deck [(qty "Lockdown" 3)]} :runner {:deck [(qty "Kyuban" 1)]}}) (play-from-hand state :corp "Lockdown" "HQ") (play-from-hand state :corp "Lockdown" "Archives") (let [ld1 (get-ice state :archives 0) ld2 (get-ice state :hq 0)] (take-credits state :corp) (play-from-hand state :runner "Kyuban") (click-card state :runner ld1) (let [starting-creds (:credit (get-runner))] (run-on state "HQ") (run-continue state) (is (= starting-creds (:credit (get-runner))) "Gained no money for passing other ice") (run-jack-out state) (run-on state "Archives") (run-continue state) (is (= (+ starting-creds 2) (:credit (get-runner))) "Gained 2 creds for passing unrezzed host ice")) (let [starting-creds-2 (:credit (get-runner))] (core/jack-out state :runner nil) (run-on state "Archives") (rez state :corp ld1) (run-continue state) (run-continue state) (run-continue state) (is (= (+ starting-creds-2 2) (:credit (get-runner))) "Gained 2 creds for passing rezzed host ice"))))) (testing "HB: Architects of Tomorrow interaction" (do-game (new-game {:corp {:id "Haas-Bioroid: Architects of Tomorrow" :deck ["Eli 1.0"]} :runner {:deck ["Kyuban"]}}) (play-from-hand state :corp "Eli 1.0" "HQ") (let [eli (get-ice state :hq 0)] (rez state :corp eli) (take-credits state :corp) (play-from-hand state :runner "Kyuban") (click-card state :runner eli)) (let [starting-creds (:credit (get-runner))] (run-on state "HQ") (run-continue state) (run-continue state) (click-prompt state :corp "Done") (run-continue state) (is (= (+ starting-creds 2) (:credit (get-runner))) "Only gained 2 credits for passing Eli"))))) (deftest laamb ;; Laamb (testing "Ability gives an card Barrier subtype" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Laamb"] :credits 30}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Laamb") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "Yes") (is (has-subtype? (get-ice state :hq 0) "Barrier") "Enigma has been given Barrier"))) (testing "Ability only lasts until end of encounter" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Laamb"] :credits 30}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Laamb") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "Yes") (run-continue state) (is (not (has-subtype? (get-ice state :hq 0) "Barrier")) "Enigma no longer has Barrier subtype"))) (testing "Returning the ice to hand after using ability resets subtype. Issue #3193" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Laamb" "Ankusa"] :credits 30}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Laamb") (play-from-hand state :runner "Ankusa") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "Yes") (let [laamb (get-program state 0) ankusa (get-program state 1)] (card-ability state :runner ankusa 1) (card-ability state :runner ankusa 1) (card-ability state :runner ankusa 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (is (nil? (get-ice state :hq 0)) "Enigma has been returned to HQ") (is (find-card "Enigma" (:hand (get-corp))) "Enigma has been returned to HQ") (run-jack-out state) (take-credits state :runner) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (is (not (has-subtype? (get-ice state :hq 0) "Barrier")) "Enigma doesn't has Barrier subtype") (is (prompt-is-card? state :runner laamb) "Laamb opens the prompt a second time"))))) (deftest lamprey ;; Lamprey - Corp loses 1 credit for each successful HQ run; trashed on purge (do-game (new-game {:runner {:deck ["PI:NAME:<NAME>END_PI"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (let [lamp (get-program state 0)] (run-empty-server state :hq) (is (= 7 (:credit (get-corp))) "Corp lost 1 credit") (click-prompt state :runner "No action") (run-empty-server state :hq) (is (= 6 (:credit (get-corp))) "Corp lost 1 credit") (click-prompt state :runner "No action") (run-empty-server state :hq) (is (= 5 (:credit (get-corp))) "Corp lost 1 credit") (click-prompt state :runner "No action") (take-credits state :runner) (core/purge state :corp) (is (empty? (get-program state)) "Lamprey trashed by purge")))) (deftest leech ;; Leech - Reduce strength of encountered ICE (testing "Basic test" (do-game (new-game {:corp {:deck ["Fire Wall"]} :runner {:deck ["Leech"]}}) (play-from-hand state :corp "Fire Wall" "New remote") (take-credits state :corp) (core/gain state :runner :click 3) (play-from-hand state :runner "LPI:NAME:<NAME>END_PIch") (let [le (get-program state 0) fw (get-ice state :remote1 0)] (run-empty-server state "Archives") (is (= 1 (get-counters (refresh le) :virus))) (run-empty-server state "Archives") (is (= 2 (get-counters (refresh le) :virus))) (run-on state "Server 1") (run-continue state) (run-continue state) (is (= 2 (get-counters (refresh le) :virus)) "No counter gained, not a central server") (run-on state "Server 1") (rez state :corp fw) (run-continue state) (is (= 5 (get-strength (refresh fw)))) (card-ability state :runner le 0) (is (= 1 (get-counters (refresh le) :virus)) "1 counter spent from Leech") (is (= 4 (get-strength (refresh fw))) "Fire Wall strength lowered by 1")))) (testing "does not affect next ice when current is trashed. Issue #1788" (do-game (new-game {:corp {:deck ["Wraparound" "Spiderweb"]} :runner {:deck ["Leech" "Parasite"]}}) (play-from-hand state :corp "Wraparound" "HQ") (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (core/gain state :corp :credit 10) (play-from-hand state :runner "Leech") (let [leech (get-program state 0) wrap (get-ice state :hq 0) spider (get-ice state :hq 1)] (core/add-counter state :runner leech :virus 2) (rez state :corp spider) (rez state :corp wrap) (play-from-hand state :runner "Parasite") (click-card state :runner "Spiderweb") (run-on state "HQ") (run-continue state) (card-ability state :runner (refresh leech) 0) (card-ability state :runner (refresh leech) 0) (is (find-card "Spiderweb" (:discard (get-corp))) "Spiderweb trashed by Parasite + Leech") (is (= 7 (get-strength (refresh wrap))) "Wraparound not reduced by Leech"))))) (deftest leprechaun ;; Leprechaun - hosting a breaker with strength based on unused MU should calculate correctly (testing "Basic test" (do-game (new-game {:runner {:deck ["Adept" "Leprechaun"]}}) (take-credits state :corp) (core/gain state :runner :credit 5) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (play-from-hand state :runner "Adept") (is (= 1 (core/available-mu state)) "3 MU used") (let [lep (get-program state 0) adpt (get-program state 1)] (is (= 3 (get-strength (refresh adpt))) "Adept at 3 strength individually") (card-ability state :runner lep 1) (click-card state :runner (refresh adpt)) (let [hosted-adpt (first (:hosted (refresh lep)))] (is (= 3 (core/available-mu state)) "1 MU used") (is (= 5 (get-strength (refresh hosted-adpt))) "Adept at 5 strength hosted"))))) (testing "Keep MU the same when hosting or trashing hosted programs" (do-game (new-game {:runner {:deck ["PI:NAME:<NAME>END_PI" "Hyperdriver" "Imp"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (let [lep (get-program state 0)] (card-ability state :runner lep 0) (click-card state :runner (find-card "Hyperdriver" (:hand (get-runner)))) (is (= 2 (:click (get-runner)))) (is (= 2 (:credit (get-runner)))) (is (= 3 (core/available-mu state)) "Hyperdriver 3 MU not deducted from available MU") (card-ability state :runner lep 0) (click-card state :runner (find-card "Imp" (:hand (get-runner)))) (is (= 1 (:click (get-runner)))) (is (zero? (:credit (get-runner)))) (is (= 3 (core/available-mu state)) "Imp 1 MU not deducted from available MU") ;; Trash Hyperdriver (core/move state :runner (find-card "Hyperdriver" (:hosted (refresh lep))) :discard) (is (= 3 (core/available-mu state)) "Hyperdriver 3 MU not added to available MU") (core/move state :runner (find-card "Imp" (:hosted (refresh lep))) :discard) ; trash Imp (is (= 3 (core/available-mu state)) "Imp 1 MU not added to available MU"))))) (deftest lustig ;; Lustig (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"]} :runner {:hand ["Lustig"] :credits 10}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (play-from-hand state :runner "Lustig") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 2) (is (= :approach-server (:phase (get-run))) "Run has bypassed Rototurret") (is (find-card "Lustig" (:discard (get-runner))) "Lustig is trashed"))) (deftest magnum-opus ;; Magnum Opus - Gain 2 cr (do-game (new-game {:runner {:deck ["Magnum Opus"]}}) (take-credits state :corp) (play-from-hand state :runner "Magnum Opus") (is (= 2 (core/available-mu state))) (is (zero? (:credit (get-runner)))) (let [mopus (get-program state 0)] (card-ability state :runner mopus 0) (is (= 2 (:credit (get-runner))) "Gain 2cr")))) (deftest makler ;; Makler (testing "Break ability costs 2 for 2 subroutines" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Battlement"]} :runner {:hand ["Makler"] :credits 20}}) (play-from-hand state :corp "Battlement" "HQ") (take-credits state :corp) (play-from-hand state :runner "Makler") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (changes-val-macro -2 (:credit (get-runner)) "Break ability costs 2 credits" (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run")))) (testing "Boost ability costs 2 credits, increases strength by 2" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Bastion"]} :runner {:hand ["Makler"] :credits 20}}) (play-from-hand state :corp "Bastion" "HQ") (take-credits state :corp) (play-from-hand state :runner "Makler") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (changes-val-macro -2 (:credit (get-runner)) "Boost ability costs 2 credits" (card-ability state :runner (get-program state 0) 1)) (changes-val-macro 2 (get-strength (get-program state 0)) "Boost ability increases strength by 2" (card-ability state :runner (get-program state 0) 1)))) (testing "Break all subs ability gives 1 credit" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand [(qty "Battlement" 2)]} :runner {:hand ["Makler"] :credits 20}}) (play-from-hand state :corp "Battlement" "HQ") (play-from-hand state :corp "Battlement" "Archives") (take-credits state :corp) (play-from-hand state :runner "Makler") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (changes-val-macro 1 (:credit (get-runner)) "Break all subs ability gives 1 credit" (run-continue state))))) (deftest mammon ;; Mammon - Pay to add X power counters at start of turn, all removed at end of turn (do-game (new-game {:runner {:deck ["Mammon"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PIammon") (take-credits state :runner) (take-credits state :corp) (let [mam (get-program state 0)] (is (= 5 (:credit (get-runner))) "Starts with 5 credits") (card-ability state :runner mam 0) (click-prompt state :runner "3") (is (= 2 (:credit (get-runner))) "Spent 3 credits") (is (= 3 (get-counters (refresh mam) :power)) "Mammon has 3 power counters") (take-credits state :runner) (is (zero? (get-counters (refresh mam) :power)) "All power counters removed")))) (deftest mantle ;; Mantle (testing "Works with programs" (do-game ;; Using Tracker to demonstrate that it's not just icebreakers (new-game {:runner {:hand ["Mantle" "Tracker"]}}) (take-credits state :corp) (play-from-hand state :runner "Mantle") (play-from-hand state :runner "Tracker") (take-credits state :runner) (take-credits state :corp) (click-prompt state :runner "HQ") (let [mantle (get-program state 0) tracker (get-program state 1)] (card-ability state :runner tracker 0) (changes-val-macro -1 (get-counters (refresh mantle) :recurring) "Can spend credits on Mantle for programs" (click-card state :runner mantle))))) (testing "Works with programs" (do-game (new-game {:runner {:deck ["PI:NAME:<NAME>END_PI"] :hand ["Mantle" "Prognostic Q-Loop"]}}) (take-credits state :corp) (play-from-hand state :runner "Mantle") (play-from-hand state :runner "Prognostic Q-Loop") (take-credits state :runner) (take-credits state :corp) (let [mantle (get-program state 0) qloop (get-hardware state 0)] (card-ability state :runner qloop 1) (changes-val-macro -1 (get-counters (refresh mantle) :recurring) "Can spend credits on Mantle for programs" (click-card state :runner mantle)) (take-credits state :runner) (take-credits state :corp))))) (deftest marjanah ;; PI:NAME:<NAME>END_PI (before-each [state (new-game {:runner {:hand [(qty "PI:NAME:<NAME>END_PI" 2)] :credits 20} :corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall"] :credits 20}}) _ (do (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state :encounter-ice)) ice-wall (get-ice state :hq 0) marjanah (get-program state 0)] (testing "pump ability" (do-game state (changes-val-macro -1 (:credit (get-runner)) "Pump costs 1" (card-ability state :runner marjanah 1)) (changes-val-macro 1 (get-strength (refresh marjanah)) "Marjanah gains 1 str" (card-ability state :runner marjanah 1)))) (testing "break ability" (do-game state (changes-val-macro -2 (:credit (get-runner)) "Break costs 2" (card-ability state :runner marjanah 0) (click-prompt state :runner "End the run")))) (testing "discount after successful run" (do-game state (run-continue state :approach-server) (run-continue state nil) (run-on state :hq) (run-continue state :encounter-ice) (changes-val-macro -1 (:credit (get-runner)) "Break costs 1 after run" (card-ability state :runner marjanah 0) (click-prompt state :runner "End the run")))))) (deftest mass-driver ;; Mass-Driver (testing "Basic test" (do-game (new-game {:corp {:deck ["Enigma" "Endless EULA"] :credits 20} :runner {:deck ["Mass-Driver"] :credits 20}}) (play-from-hand state :corp "Endless EULA" "HQ") (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Mass-Driver") (let [eula (get-ice state :hq 0) enigma (get-ice state :hq 1) mass-driver (get-program state 0)] (run-on state :hq) (rez state :corp enigma) (run-continue state) (card-ability state :runner mass-driver 1) (card-ability state :runner mass-driver 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (run-continue state) (rez state :corp eula) (run-continue state) (fire-subs state (refresh eula)) ; only resolve 3 subs (click-prompt state :runner "Pay 1 [Credits]") (click-prompt state :runner "Pay 1 [Credits]") (click-prompt state :runner "Pay 1 [Credits]") (is (empty? (:prompt (get-runner))) "No more prompts open")))) (testing "Interaction with Spooned" (do-game (new-game {:corp {:deck ["Enigma" "Endless EULA"]} :runner {:deck ["Mass-Driver" "Spooned"]}}) (play-from-hand state :corp "Endless EULA" "HQ") (play-from-hand state :corp "Enigma" "HQ") (core/gain state :corp :credit 20) (take-credits state :corp) (core/gain state :runner :credit 20) (play-from-hand state :runner "Mass-Driver") (let [eula (get-ice state :hq 0) enigma (get-ice state :hq 1) mass-driver (get-program state 0)] (play-from-hand state :runner "Spooned") (click-prompt state :runner "HQ") (rez state :corp enigma) (run-continue state) (card-ability state :runner mass-driver 1) (card-ability state :runner mass-driver 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (run-continue state) (is (= 1 (count (:discard (get-corp)))) "Enigma is trashed") (rez state :corp eula) (run-continue state) (fire-subs state (refresh eula)) ; only resolve 3 subs (click-prompt state :runner "Pay 1 [Credits]") (click-prompt state :runner "Pay 1 [Credits]") (click-prompt state :runner "Pay 1 [Credits]") (is (empty? (:prompt (get-runner))) "No more prompts open"))))) (deftest maven ;; Maven (testing "Basic test" (do-game (new-game {:corp {:deck ["Border Control"] :credits 20} :runner {:hand ["Maven" "Datasucker"] :credits 20}}) (play-from-hand state :corp "Border Control" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Maven") (let [maven (get-program state 0)] (is (= 1 (get-strength (refresh maven))) "Maven boosts itself") (play-from-hand state :runner "DatasPI:NAME:<NAME>END_PI") (is (= 2 (get-strength (refresh maven))) "+1 str from Datasucker") (run-on state "HQ") (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh maven)}) (is (second-last-log-contains? state "Runner pays 4 \\[Credits\\] to use Maven to break all 2 subroutines on Border Control.") "Correct log with autopump ability") (run-jack-out state) (run-on state "HQ") (run-continue state) (card-ability state :runner (refresh maven) 0) (click-prompt state :runner "End the run") (is (last-log-contains? state "Runner pays 2 \\[Credits\\] to use Maven to break 1 subroutine on Border Control.") "Correct log with single sub break"))))) (deftest mayfly ;; Mayfly (testing "Basic test" (do-game (new-game {:corp {:deck ["PI:NAME:<NAME>END_PI"] :credits 20} :runner {:hand ["Mayfly"] :credits 20}}) (play-from-hand state :corp "PI:NAME:<NAME>END_PI" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Mayfly") (let [mayfly (get-program state 0)] (run-on state "HQ") (run-continue state) (changes-val-macro -7 (:credit (get-runner)) "Paid 7 to fully break Anansi with Mayfly" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh mayfly)})) (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines") (run-jack-out state) (is (= 1 (count (:discard (get-runner)))) "Mayfly trashed when run ends"))))) (deftest mimic ;; Mimic (testing "Basic auto-break test" (do-game (new-game {:corp {:hand ["Pup"]} :runner {:hand [(qty "Mimic" 5)]}}) (play-from-hand state :corp "Pup" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Mimic") (let [mimic (get-program state 0)] (is (= 2 (:credit (get-runner))) "Runner starts with 2 credits") (is (= 4 (count (:hand (get-runner)))) "Runner has 4 cards in hand") (run-on state "HQ") (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh mimic)}) (is (second-last-log-contains? state "Runner pays 2 \\[Credits\\] to use Mimic to break all 2 subroutines on Pup") "Correct log with autopump ability") (run-jack-out state) (is (zero? (:credit (get-runner))) "Runner spent 2 credits to break Pup") (is (= 4 (count (:hand (get-runner)))) "Runner still has 4 cards in hand")))) (testing "No dynamic options if below strength" (do-game (new-game {:corp {:hand ["Anansi"] :credits 10} :runner {:hand [(qty "Mimic" 5)] :credits 10}}) (play-from-hand state :corp "Anansi" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Mimic") (let [mimic (get-program state 0)] (is (= 7 (:credit (get-runner))) "Runner starts with 7 credits") (is (= 4 (count (:hand (get-runner)))) "Runner has 4 cards in hand") (run-on state "HQ") (run-continue state) (is (= 1 (count (:abilities (refresh mimic)))) "Auto pump and break ability on Mimic is not available")))) (testing "Dynamic options when ice weakened" (do-game (new-game {:corp {:hand ["Zed 2.0"] :credits 10} :runner {:hand ["Mimic" "Ice Carver" ] :credits 10}}) (play-from-hand state :corp "Zed 2.0" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Ice Carver") (play-from-hand state :runner "Mimic") (let [mimic (get-program state 0)] (is (= 4 (:credit (get-runner))) "Runner starts with 4 credits") (run-on state "HQ") (run-continue state) (is (= 2 (count (:abilities (refresh mimic)))) "Auto pump and break ability on Mimic is available") (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh mimic)}) (is (second-last-log-contains? state "Runner pays 3 \\[Credits\\] to use Mimic to break all 3 subroutines on Zed 2.0") "Correct log with autopump ability") (run-jack-out state) (is (= 1 (:credit (get-runner))) "Runner spent 3 credits to break Zed 2.0"))))) (deftest misdirection ;; Misdirection (testing "Recurring credits interaction. Issue #4868" (do-game (new-game {:runner {:hand ["Misdirection" "Multithreader"] :credits 10 :tags 2}}) (take-credits state :corp) (core/gain state :runner :click 2) (play-from-hand state :runner "Misdirection") (play-from-hand state :runner "Multithreader") (let [mis (get-program state 0) multi (get-program state 1)] (changes-val-macro 0 (:credit (get-runner)) "Using recurring credits" (card-ability state :runner mis 0) (click-prompt state :runner "2") (is (= "Select a credit providing card (0 of 2 credits)" (:msg (prompt-map :runner))) "Runner has pay-credit prompt") (click-card state :runner multi) (click-card state :runner multi)) (is (zero? (count-tags state)) "Runner has lost both tags")))) (testing "Using credits from Mantle and credit pool" (do-game (new-game {:runner {:hand ["Misdirection" "Mantle"] :credits 10 :tags 4}}) (take-credits state :corp) (core/gain state :runner :click 2) (play-from-hand state :runner "Misdirection") (play-from-hand state :runner "Mantle") (let [mis (get-program state 0) mantle (get-program state 1)] (changes-val-macro -3 (:credit (get-runner)) "Using recurring credits and credits from credit pool" (card-ability state :runner mis 0) (click-prompt state :runner "4") (is (= "Select a credit providing card (0 of 4 credits)" (:msg (prompt-map :runner))) "Runner has pay-credit prompt") (click-card state :runner mantle)) (is (zero? (count-tags state)) "Runner has lost all 4 tags")))) (testing "Basic behavior" (do-game (new-game {:runner {:hand ["Misdirection"] :credits 5 :tags 2}}) (take-credits state :corp) (play-from-hand state :runner "Misdirection") (let [mis (get-program state 0)] (is (= 5 (:credit (get-runner))) "Runner starts with 5 credits") (is (= 3 (:click (get-runner))) "Runner starts with 3 clicks") (card-ability state :runner mis 0) (click-prompt state :runner "2") (is (zero? (count-tags state)) "Runner has lost both tags") (is (= 1 (:click (get-runner))) "Runner spent 2 clicks (1 remaining)") (is (= 3 (:credit (get-runner))) "Runner spent 2 credits (3 remaining)"))))) (deftest mkultra ;; MKUltra (testing "auto-pump" (testing "Pumping and breaking for 1" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Rototurret"] :credits 10} :runner {:hand ["MKUltra"] :credits 100}}) (play-from-hand state :corp "Rototurret" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "MKUltra") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -3 (:credit (get-runner)) "Paid 3 to fully break Rototurret with MKUltra" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh pc)})) (is (= 3 (get-strength (refresh pc))) "Pumped MKUltra up to str 3") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines"))))) (testing "Heap Locked" (do-game (new-game {:corp {:deck ["Rototurret" "Blacklist"]} :runner {:deck [(qty "MKUltra" 1)]}}) (play-from-hand state :corp "Rototurret" "Archives") (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (refresh (get-content state :remote1 0))) (take-credits state :corp) (trash-from-hand state :runner "MKUltra") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (is (empty? (:prompt (get-runner))) "MKUltra prompt did not come up")))) (deftest multithreader ;; Multithreader (testing "Pay-credits prompt" (do-game (new-game {:runner {:deck ["Multithreader" "Abagnale"]}}) (take-credits state :corp) (core/gain state :runner :credit 20) (play-from-hand state :runner "Multithreader") (play-from-hand state :runner "Abagnale") (let [mt (get-program state 0) ab (get-program state 1)] (changes-val-macro 0 (:credit (get-runner)) "Used 2 credits from Multithreader" (card-ability state :runner ab 1) (is (= "Select a credit providing card (0 of 2 credits)" (:msg (prompt-map :runner))) "Runner has pay-credit prompt") (click-card state :runner mt) (click-card state :runner mt)))))) (deftest musaazi ;; Musaazi gains virus counters on successful runs and can spend virus counters from any installed card (do-game (new-game {:corp {:deck ["Lancelot"]} :runner {:deck ["Musaazi" "Imp"]}}) (play-from-hand state :corp "Lancelot" "HQ") (take-credits state :corp) (play-from-hand state :runner "Musaazi") (play-from-hand state :runner "Imp") (let [lancelot (get-ice state :hq 0) musaazi (get-program state 0) imp (get-program state 1)] (run-empty-server state "Archives") (is (= 1 (get-counters (refresh musaazi) :virus)) "Musaazi has 1 virus counter") (is (= 1 (get-strength (refresh musaazi))) "Initial Musaazi strength") (is (= 2 (get-counters (refresh imp) :virus)) "Initial Imp virus counters") (run-on state "HQ") (rez state :corp lancelot) (run-continue state) (card-ability state :runner musaazi 1) ; match strength (click-card state :runner imp) (is (= 1 (get-counters (refresh imp) :virus)) "Imp lost 1 virus counter to pump") (is (= 2 (get-strength (refresh musaazi))) "Musaazi strength 2") (is (empty? (:prompt (get-runner))) "No prompt open") (card-ability state :runner musaazi 0) (click-prompt state :runner "Trash a program") (click-card state :runner musaazi) (click-prompt state :runner "Resolve a Grail ICE subroutine from HQ") (click-card state :runner imp) (is (zero? (get-counters (refresh imp) :virus)) "Imp lost its final virus counter") (is (zero? (get-counters (refresh imp) :virus)) "Musaazi lost its virus counter")))) (deftest na-not-k ;; Na'Not'K - Strength adjusts accordingly when ice installed during run (testing "Basic test" (do-game (new-game {:corp {:deck ["Architect" "Eli 1.0"]} :runner {:deck ["Na'Not'K"]}}) (play-from-hand state :corp "Architect" "HQ") (take-credits state :corp) (play-from-hand state :runner "Na'Not'K") (let [nanotk (get-program state 0) architect (get-ice state :hq 0)] (is (= 1 (get-strength (refresh nanotk))) "Default strength") (run-on state "HQ") (rez state :corp architect) (run-continue state) (is (= 2 (get-strength (refresh nanotk))) "1 ice on HQ") (card-subroutine state :corp (refresh architect) 1) (click-card state :corp (find-card "Eli 1.0" (:hand (get-corp)))) (click-prompt state :corp "HQ") (is (= 3 (get-strength (refresh nanotk))) "2 ice on HQ") (run-jack-out state) (is (= 1 (get-strength (refresh nanotk))) "Back to default strength")))) (testing "Strength adjusts accordingly when run redirected to another server" (do-game (new-game {:corp {:deck ["Susanoo-no-Mikoto" "Crick" "Cortex Lock"] :credits 20} :runner {:deck ["Na'Not'K"]}}) (play-from-hand state :corp "Cortex Lock" "HQ") (play-from-hand state :corp "Susanoo-no-Mikoto" "HQ") (play-from-hand state :corp "Crick" "Archives") (take-credits state :corp) (play-from-hand state :runner "Na'Not'K") (let [nanotk (get-program state 0) susanoo (get-ice state :hq 1)] (is (= 1 (get-strength (refresh nanotk))) "Default strength") (run-on state "HQ") (rez state :corp susanoo) (run-continue state) (is (= 3 (get-strength (refresh nanotk))) "2 ice on HQ") (card-subroutine state :corp (refresh susanoo) 0) (is (= 2 (get-strength (refresh nanotk))) "1 ice on Archives") (run-jack-out state) (is (= 1 (get-strength (refresh nanotk))) "Back to default strength"))))) (deftest nfr ;; Nfr (testing "Basic test" (do-game (new-game {:runner {:deck ["Nfr"]} :corp {:deck ["Ice Wall"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Nfr") (let [nfr (get-program state 0) icew (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh icew)) (run-continue state) (card-ability state :runner (refresh nfr) 0) (click-prompt state :runner "End the run") (changes-val-macro 1 (get-counters (refresh nfr) :power) "Got 1 token" (run-continue state)))))) (deftest nyashia ;; Nyashia (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 10)] :hand ["Hedge Fund"]} :runner {:deck ["Nyashia"]}}) (take-credits state :corp) (play-from-hand state :runner "Nyashia") (run-on state "R&D") (run-continue state) (click-prompt state :runner "Yes") (is (= 2 (:total (core/num-cards-to-access state :runner :rd nil)))))) (deftest odore (testing "Basic test" (do-game (new-game {:corp {:deck ["Cobra"]} :runner {:deck ["Odore" (qty "Logic Bomb" 3)]}}) (play-from-hand state :corp "Cobra" "HQ") (take-credits state :corp) (play-from-hand state :runner "Odore") (let [odore (get-program state 0) cobra (get-ice state :hq 0)] (core/gain state :runner :click 2 :credit 20) (run-on state "HQ") (rez state :corp cobra) (run-continue state) (changes-val-macro -5 (:credit (get-runner)) "Paid 3 to pump and 2 to break" (card-ability state :runner odore 2) (card-ability state :runner odore 0) (click-prompt state :runner "Trash a program") (click-prompt state :runner "Do 2 net damage"))))) (testing "auto-pump-and-break with and without 3 virtual resources" (do-game (new-game {:corp {:deck ["Cobra"]} :runner {:deck ["Odore" (qty "Logic Bomb" 3)]}}) (play-from-hand state :corp "Cobra" "HQ") (take-credits state :corp) (play-from-hand state :runner "Odore") (let [odore (get-program state 0) cobra (get-ice state :hq 0)] (core/gain state :runner :click 2 :credit 20) (run-on state "HQ") (rez state :corp cobra) (run-continue state) (changes-val-macro -5 (:credit (get-runner)) "Paid 3 to pump and 2 to break" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh odore)})) (core/continue state :corp nil) (run-jack-out state) (dotimes [_ 3] (play-from-hand state :runner "Logic Bomb")) (run-on state "HQ") (run-continue state) (changes-val-macro -3 (:credit (get-runner)) "Paid 3 to pump and 0 to break" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh odore)})))))) (deftest origami ;; Origami - Increases Runner max hand size (do-game (new-game {:runner {:deck [(qty "Origami" 2)]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (is (= 6 (hand-size :runner))) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (is (= 9 (hand-size :runner)) "Max hand size increased by 2 for each copy installed"))) (deftest overmind ;; Overmind - Start with counters equal to unused MU (do-game (new-game {:runner {:deck ["Overmind" "Deep Red" "Sure Gamble" "Akamatsu Mem Chip" ]}}) (take-credits state :corp) (play-from-hand state :runner "Sure Gamble") (play-from-hand state :runner "Akamatsu Mem Chip") (is (= 5 (core/available-mu state))) (play-from-hand state :runner "Deep Red") (is (= 8 (core/available-mu state))) (play-from-hand state :runner "Overmind") (is (= 7 (core/available-mu state))) (let [ov (get-program state 0)] (is (= 7 (get-counters (refresh ov) :power)) "Overmind has 5 counters")))) (deftest paintbrush ;; Paintbrush - Give rezzed ICE a chosen subtype until the end of the next run (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["Paintbrush"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Paintbrush") (is (= 2 (core/available-mu state))) (let [iwall (get-ice state :hq 0) pb (get-program state 0)] (card-ability state :runner pb 0) (click-card state :runner iwall) (is (= 3 (:click (get-runner))) "Ice Wall not rezzed, so no click charged") (click-prompt state :runner "Done") ; cancel out (rez state :corp iwall) (card-ability state :runner pb 0) (click-card state :runner iwall) (click-prompt state :runner "Code Gate") (is (= 2 (:click (get-runner))) "Click charged") (is (has-subtype? (refresh iwall) "Code Gate") "Ice Wall gained Code Gate") (run-empty-server state "Archives") (is (not (has-subtype? (refresh iwall) "Code Gate")) "Ice Wall lost Code Gate at the end of the run")))) (deftest panchatantra ;; Panchatantra (before-each [state (new-game {:corp {:hand ["Ice Wall"]} :runner {:hand ["Panchatantra"]}}) _ (do (play-from-hand state :corp "Ice Wall" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Panchatantra") (run-on state :hq) (run-continue state)) iw (get-ice state :hq 0)] (testing "Choices do not include Barrier, Code Gate, or Sentry" (do-game state (click-prompt state :runner "Yes") (is (not (some #{"Barrier" "Code Gate" "Sentry"} (prompt-buttons :runner)))))) (testing "Encountered ice gains the subtype" (do-game state (click-prompt state :runner "Yes") (click-prompt state :runner "AP") (is (has-subtype? (refresh iw) "AP")))) (testing "Encountered ice loses subtype at the end of the run" (do-game state (click-prompt state :runner "Yes") (click-prompt state :runner "AP") (run-continue state) (is (has-subtype? (refresh iw) "AP")) (run-jack-out state) (is (not (has-subtype? (refresh iw) "AP"))))))) (deftest paperclip ;; Paperclip - prompt to install on encounter, but not if another is installed (testing "Basic test" (do-game (new-game {:corp {:deck ["Vanilla"]} :runner {:deck [(qty "Paperclip" 2)]}}) (play-from-hand state :corp "Vanilla" "Archives") (take-credits state :corp) (trash-from-hand state :runner "Paperclip") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (click-prompt state :runner "Yes") ; install paperclip (run-continue state) (run-continue state) (is (not (:run @state)) "Run ended") (trash-from-hand state :runner "Paperclip") (run-on state "Archives") (is (empty? (:prompt (get-runner))) "No prompt to install second Paperclip"))) (testing "firing on facedown ice shouldn't crash" (do-game (new-game {:corp {:deck ["Vanilla"]} :runner {:deck ["Paperclip"]}}) (play-from-hand state :corp "Vanilla" "Archives") (take-credits state :corp) (play-from-hand state :runner "Paperclip") (run-on state "Archives") (run-continue state) (card-ability state :runner (get-program state 0) 0) (click-prompt state :runner "0"))) (testing "do not show a second install prompt if user said No to first, when multiple are in heap" (do-game (new-game {:corp {:deck [(qty "Vanilla" 2)]} :runner {:deck [(qty "Paperclip" 3)]}}) (play-from-hand state :corp "Vanilla" "Archives") (play-from-hand state :corp "Vanilla" "Archives") (take-credits state :corp) (trash-from-hand state :runner "Paperclip") (trash-from-hand state :runner "Paperclip") (trash-from-hand state :runner "Paperclip") (run-on state "Archives") (rez state :corp (get-ice state :archives 1)) (run-continue state) (click-prompt state :runner "No") (is (empty? (:prompt (get-runner))) "No additional prompts to rez other copies of Paperclip") (run-continue state) (rez state :corp (get-ice state :archives 0)) (run-continue state) ;; we should get the prompt on a second ice even after denying the first (click-prompt state :runner "No") (is (empty? (:prompt (get-runner))) "No additional prompts to rez other copies of Paperclip") (run-jack-out state) ;; Run again, make sure we get the prompt to install again (run-on state "Archives") (run-continue state) (click-prompt state :runner "No") (is (empty? (:prompt (get-runner))) "No additional prompts to rez other copies of Paperclip"))) (testing "auto-pump" (testing "Pumping and breaking for 1" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Vanilla"] :credits 10} :runner {:hand ["Paperclip"] :credits 100}}) (play-from-hand state :corp "Vanilla" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -1 (:credit (get-runner)) "Paid 1 to fully break Vanilla with Paperclip" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh pc)})) (is (= 2 (get-strength (refresh pc))) "Pumped Paperclip up to str 2") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "Pumping for >1 and breaking for 1" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Fire Wall"] :credits 10} :runner {:hand ["Paperclip"] :credits 100}}) (play-from-hand state :corp "Fire Wall" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -4 (:credit (get-runner)) "Paid 4 to fully break Fire Wall with Paperclip" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh pc)})) (is (= 5 (get-strength (refresh pc))) "Pumped Paperclip up to str 5") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "Pumping for 1 and breaking for >1" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Spiderweb"] :credits 10} :runner {:hand ["Paperclip"] :credits 100}}) (play-from-hand state :corp "Spiderweb" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -3 (:credit (get-runner)) "Paid 3 to fully break Spiderweb with Paperclip" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh pc)})) (is (= 4 (get-strength (refresh pc))) "Pumped Paperclip up to str 4") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "Pumping for >1 and breaking for >1" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Chiyashi"] :credits 12} :runner {:hand ["Paperclip"] :credits 100}}) (play-from-hand state :corp "Chiyashi" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -7 (:credit (get-runner)) "Paid 7 to fully break Chiyashi with Paperclip" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh pc)})) (is (= 8 (get-strength (refresh pc))) "Pumped Paperclip up to str 8") (is (= 0 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broken all subroutines")))) (testing "No auto-pump on unbreakable subs" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Akhet"] :credits 10} :runner {:hand ["Paperclip"] :credits 100}}) (core/gain state :corp :click 1) (play-from-hand state :corp "Akhet" "HQ") (rez state :corp (get-ice state :hq 0)) (dotimes [n 3] (advance state (get-ice state :hq 0))) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (is (empty? (filter #(:dynamic %) (:abilities (refresh pc)))) "No auto-pumping option for Akhet")))) (testing "Orion triggers all heap breakers once" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Orion"] :credits 15} :runner {:discard [(qty "Paperclip" 2) (qty "MKUltra" 2) (qty "Black Orchestra" 2)] :credits 100}}) (play-from-hand state :corp "Orion" "HQ") (take-credits state :corp) (run-on state :hq) (rez state :corp (get-ice state :hq 0)) (run-continue state) (click-prompt state :runner "No") (click-prompt state :runner "No") (click-prompt state :runner "No") (is (empty? (:prompt (get-runner))) "No further prompts to install heap breakers")))) (testing "Heap Locked" (do-game (new-game {:corp {:deck ["Vanilla" "Blacklist"]} :runner {:deck [(qty "Paperclip" 2)]}}) (play-from-hand state :corp "Vanilla" "Archives") (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (refresh (get-content state :remote1 0))) (take-credits state :corp) (trash-from-hand state :runner "Paperclip") (run-on state "Archives") (rez state :corp (get-ice state :archives 0)) (run-continue state) (is (empty? (:prompt (get-runner))) "Paperclip prompt did not come up") (fire-subs state (get-ice state :archives 0)) (is (not (:run @state)) "Run ended"))) (testing "Breaking some subs" (do-game (new-game {:corp {:hand ["Hive"]} :runner {:hand ["Paperclip"] :credits 10}}) (play-from-hand state :corp "Hive" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Paperclip") (let [pc (get-program state 0)] (run-on state :hq) (run-continue state) (changes-val-macro -2 (:credit (get-runner)) "Paid 2 to break two of the subs on Hive" (is (= 5 (count (:subroutines (get-ice state :hq 0)))) "Hive starts with 5 subs") (is (= 3 (get-strength (get-ice state :hq 0))) "Hive has strength 3") (card-ability state :runner pc 0) (click-prompt state :runner "2") (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (is (= 3 (get-strength (refresh pc))) "Pumped Paperclip up to str 3") (is (= 3 (count (remove :broken (:subroutines (get-ice state :hq 0))))) "Broke all but 3 subs")))))) (deftest parasite (testing "Basic functionality: Gain 1 counter every Runner turn" (do-game (new-game {:corp {:deck [(qty "Wraparound" 3) (qty "Hedge Fund" 3)]} :runner {:deck [(qty "Parasite" 3) (qty "Sure Gamble" 3)]}}) (play-from-hand state :corp "Wraparound" "HQ") (let [wrap (get-ice state :hq 0)] (rez state :corp wrap) (take-credits state :corp) (play-from-hand state :runner "Parasite") (click-card state :runner wrap) (is (= 3 (core/available-mu state)) "Parasite consumes 1 MU") (let [psite (first (:hosted (refresh wrap)))] (is (zero? (get-counters psite :virus)) "Parasite has no counters yet") (take-credits state :runner) (take-credits state :corp) (is (= 1 (get-counters (refresh psite) :virus)) "Parasite gained 1 virus counter at start of Runner turn") (is (= 6 (get-strength (refresh wrap))) "Wraparound reduced to 6 strength"))))) (testing "Installed facedown w/ Apex" (do-game (new-game {:runner {:id "Apex: Invasive Predator" :deck ["Parasite"]}}) (take-credits state :corp) (end-phase-12 state :runner) (click-card state :runner (find-card "Parasite" (:hand (get-runner)))) (is (empty? (:prompt (get-runner))) "No prompt to host Parasite") (is (= 1 (count (get-runner-facedown state))) "Parasite installed face down"))) (testing "Installed on untrashable Architect should keep gaining counters past 3 and make strength go negative" (do-game (new-game {:corp {:deck [(qty "Architect" 3) (qty "Hedge Fund" 3)]} :runner {:deck [(qty "Parasite" 3) "Grimoire"]}}) (play-from-hand state :corp "Architect" "HQ") (let [arch (get-ice state :hq 0)] (rez state :corp arch) (take-credits state :corp) (play-from-hand state :runner "Grimoire") (play-from-hand state :runner "Parasite") (click-card state :runner arch) (let [psite (first (:hosted (refresh arch)))] (is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter") (take-credits state :runner) (take-credits state :corp) (take-credits state :runner) (take-credits state :corp) (take-credits state :runner) (take-credits state :corp) (is (= 4 (get-counters (refresh psite) :virus)) "Parasite has 4 counters") (is (= -1 (get-strength (refresh arch))) "Architect at -1 strength"))))) (testing "Should stay on hosted card moved by Builder" (do-game (new-game {:corp {:deck [(qty "Builder" 3) "Ice Wall"]} :runner {:deck [(qty "Parasite" 3)]}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Builder" "Archives") (let [builder (get-ice state :archives 0)] (rez state :corp builder) (take-credits state :corp) (play-from-hand state :runner "Parasite") (click-card state :runner builder) (let [psite (first (:hosted (refresh builder)))] (take-credits state :runner) (take-credits state :corp) (is (= 3 (get-strength (refresh builder))) "Builder reduced to 3 strength") (is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter") (take-credits state :runner)) (let [orig-builder (refresh builder)] (card-ability state :corp builder 0) (click-prompt state :corp "HQ") (let [moved-builder (get-ice state :hq 1)] (is (= (get-strength orig-builder) (get-strength moved-builder)) "Builder's state is maintained") (let [orig-psite (dissoc (first (:hosted orig-builder)) :host) moved-psite (dissoc (first (:hosted moved-builder)) :host)] (is (= orig-psite moved-psite) "Hosted Parasite is maintained")) (take-credits state :corp) (let [updated-builder (refresh moved-builder) updated-psite (first (:hosted updated-builder))] (is (= 2 (get-strength updated-builder)) "Builder strength still reduced") (is (= 2 (get-counters (refresh updated-psite) :virus)) "Parasite counters still incremented"))))))) (testing "Use Hivemind counters when installed; instantly trash ICE if counters >= ICE strength" (do-game (new-game {:corp {:deck [(qty "Enigma" 3) (qty "Hedge Fund" 3)]} :runner {:deck ["Parasite" "Grimoire" "Hivemind" "Sure Gamble"]}}) (play-from-hand state :corp "Enigma" "HQ") (let [enig (get-ice state :hq 0)] (rez state :corp enig) (take-credits state :corp) (play-from-hand state :runner "Sure Gamble") (play-from-hand state :runner "Grimoire") (play-from-hand state :runner "Hivemind") (let [hive (get-program state 0)] (is (= 2 (get-counters (refresh hive) :virus)) "Hivemind has 2 counters") (play-from-hand state :runner "Parasite") (click-card state :runner enig) (is (= 1 (count (:discard (get-corp)))) "Enigma trashed instantly") (is (= 4 (core/available-mu state))) (is (= 2 (count (:discard (get-runner)))) "Parasite trashed when Enigma was trashed"))))) (testing "Trashed along with host ICE when its strength has been reduced to 0" (do-game (new-game {:corp {:deck [(qty "Enigma" 3) (qty "Hedge Fund" 3)]} :runner {:deck [(qty "Parasite" 3) "Grimoire"]}}) (play-from-hand state :corp "Enigma" "HQ") (let [enig (get-ice state :hq 0)] (rez state :corp enig) (take-credits state :corp) (play-from-hand state :runner "Grimoire") (play-from-hand state :runner "Parasite") (click-card state :runner enig) (let [psite (first (:hosted (refresh enig)))] (is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter") (is (= 1 (get-strength (refresh enig))) "Enigma reduced to 1 strength") (take-credits state :runner) (take-credits state :corp) (is (= 1 (count (:discard (get-corp)))) "Enigma trashed") (is (= 1 (count (:discard (get-runner)))) "Parasite trashed when Enigma was trashed"))))) (testing "Interaction with Customized Secretary #2672" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:deck ["Parasite"] :hand ["Djinn" "Customized Secretary"] :credits 10}}) (play-from-hand state :corp "Enigma" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Djinn") (card-ability state :runner (get-program state 0) 1) (is (= "Choose a non-Icebreaker program in your grip" (:msg (prompt-map :runner)))) (click-card state :runner "Customized Secretary") (is (= "Choose a program to host" (:msg (prompt-map :runner)))) (click-prompt state :runner "Parasite") (card-ability state :runner (first (:hosted (get-program state 0))) 0) (is (= "Parasite" (:title (first (:hosted (first (:hosted (get-program state 0)))))))) (is (= "Choose a program to install" (:msg (prompt-map :runner)))) (click-prompt state :runner "Parasite") (is (= "Choose a card to host Parasite on" (:msg (prompt-map :runner)))) (click-card state :runner "Enigma") (is (= "Customized Secretary" (:title (first (:hosted (get-program state 0)))))) (is (empty? (:hosted (first (:hosted (get-program state 0)))))))) (testing "Triggers Hostile Infrastructure" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Hostile Infrastructure" "Vanilla"]} :runner {:deck [(qty "Parasite" 2)]}}) (play-from-hand state :corp "Hostile Infrastructure" "New remote") (play-from-hand state :corp "Vanilla" "HQ") (let [van (get-ice state :hq 0) hi (get-content state :remote1 0)] (rez state :corp hi) (rez state :corp van) (take-credits state :corp) (changes-val-macro 2 (count (:discard (get-runner))) "Took net damage (Parasite on Vanilla was trashed + card from hand" (play-from-hand state :runner "Parasite") (click-card state :runner van)))))) (deftest paricia ;; Paricia (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["PAD Campaign" "Shell Corporation"]} :runner {:hand ["Paricia"]}}) (play-from-hand state :corp "PAD Campaign" "New remote") (play-from-hand state :corp "Shell Corporation" "New remote") (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (let [pad (get-content state :remote1 0) shell (get-content state :remote2 0) paricia (get-program state 0)] (run-empty-server state :remote2) (click-prompt state :runner "Pay 3 [Credits] to trash") (is (empty? (:prompt (get-runner))) "No pay-credit prompt as it's an upgrade") (is (nil? (refresh shell)) "Shell Corporation successfully trashed") (run-empty-server state :remote1) (is (= 2 (:credit (get-runner))) "Runner can't afford to trash PAD Campaign") (click-prompt state :runner "Pay 4 [Credits] to trash") (dotimes [_ 2] (click-card state :runner "PI:NAME:<NAME>END_PI")) (is (nil? (refresh pad)) "PAD Campaign successfully trashed")))) (deftest pawn ;; Pawn (testing "Happy Path" (do-game (new-game {:corp {:deck ["Enigma" "Blacklist" "Hedge Fund"]} :runner {:deck ["Pawn" "Knight"]}}) (play-from-hand state :corp "Enigma" "Archives") (take-credits state :corp) (trash-from-hand state :runner "Knight") (play-from-hand state :runner "Pawn") ;;currently Pawn successful run check is not implemented, nor is hosted location check (card-ability state :runner (get-program state 0) 2) (click-card state :runner (find-card "Knight" (:discard (get-runner)))) (is (not (nil? (find-card "Pawn" (:discard (get-runner)))))))) (testing "Heap locked" (do-game (new-game {:corp {:deck ["Enigma" "Blacklist" "Hedge Fund"]} :runner {:deck ["Pawn" "Knight"]}}) (play-from-hand state :corp "Enigma" "Archives") (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (refresh (get-content state :remote1 0))) (take-credits state :corp) (trash-from-hand state :runner "Knight") (play-from-hand state :runner "Pawn") (card-ability state :runner (get-program state 0) 2) (is (empty? (:prompt (get-runner))) "Install prompt did not come up") (is (nil? (find-card "Pawn" (:discard (get-runner))))) (is (not (nil? (find-card "Knight" (:discard (get-runner))))))))) (deftest pelangi ;; Pelangi (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 10)] :hand ["Ice Wall"]} :runner {:hand ["Pelangi"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Pelangi") (let [iw (get-ice state :hq 0) pelangi (get-program state 0)] (run-on state "HQ") (rez state :corp iw) (run-continue state) (card-ability state :runner pelangi 0) (click-prompt state :runner "Code Gate") (is (has-subtype? (refresh iw) "Code Gate") "Ice Wall gained Code Gate") (run-continue state) (run-jack-out state) (is (not (has-subtype? (refresh iw) "Code Gate")) "Ice Wall lost Code Gate at the end of the run")))) (deftest penrose ;; Penrose (testing "Pay-credits prompt and first turn ability" (do-game (new-game {:runner {:deck ["Cloak" "Penrose"]} :corp {:deck ["Enigma" "Vanilla"]}}) (play-from-hand state :corp "Enigma" "HQ") (play-from-hand state :corp "Vanilla" "HQ") (take-credits state :corp) (play-from-hand state :runner "Cloak") (play-from-hand state :runner "Penrose") (core/gain state :runner :credit 1) (run-on state :hq) (let [enig (get-ice state :hq 0) van (get-ice state :hq 1) cl (get-program state 0) penr (get-program state 1)] (is (= 3 (count (:abilities penr))) "3 abilities on Penrose") (rez state :corp van) (run-continue state) (is (= 4 (count (:abilities (refresh penr)))) "Auto pump and break ability on Penrose active") (changes-val-macro 0 (:credit (get-runner)) "Used 1 credit from Cloak" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh penr)}) (click-card state :runner cl)) (core/continue state :corp nil) (rez state :corp enig) (run-continue state) (changes-val-macro -2 (:credit (get-runner)) "Paid 2 credits to break all subroutines on Enigma" (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh penr)})) (core/continue state :corp nil) (run-jack-out state) (take-credits state :runner) (take-credits state :corp) (run-on state :hq) (is (= 3 (count (:abilities (refresh penr)))) "Auto pump and break ability on Penrose is not active") (card-ability state :runner (refresh penr) 0) (is (empty? (:prompt (get-runner))) "No cloak prompt because the ability to break barriers is not active anymore"))))) (deftest peregrine ;; Peregrine - 2c to return to grip and derez an encountered code gate (do-game (new-game {:corp {:deck ["Paper Wall" (qty "Bandwidth" 2)]} :runner {:deck ["Peregrine"]}}) (play-from-hand state :corp "Bandwidth" "Archives") (play-from-hand state :corp "Bandwidth" "Archives") (play-from-hand state :corp "Paper Wall" "Archives") (take-credits state :corp) (core/gain state :runner :credit 20) (play-from-hand state :runner "Peregrine") (let [bw1 (get-ice state :archives 0) pw (get-ice state :archives 2) per (get-program state 0)] (run-on state "Archives") (rez state :corp pw) (run-continue state) (rez state :corp bw1) (changes-val-macro 0 (:credit (get-runner)) "Can't use Peregrine on a barrier" (card-ability state :runner per 2)) (run-continue state) (run-continue state) (changes-val-macro 0 (:credit (get-runner)) "Can't use Peregrine on an unrezzed code gate" (card-ability state :runner per 2)) (run-continue state) (changes-val-macro -3 (:credit (get-runner)) "Paid 3 to pump strength" (card-ability state :runner per 1)) (changes-val-macro -1 (:credit (get-runner)) "Paid 1 to break sub" (card-ability state :runner per 0) (click-prompt state :runner "Give the Runner 1 tag")) (changes-val-macro -2 (:credit (get-runner)) "Paid 2 to derez Bandwidth" (card-ability state :runner per 2) (run-continue state)) (is (= 1 (count (:hand (get-runner)))) "Peregrine returned to grip") (is (not (rezzed? (refresh bw1))) "Bandwidth derezzed")))) (deftest persephone ;; Persephone's ability trashes cards from R&D (testing "Triggers AR-Enhanced Security. Issue #3187" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Zed 1.0" "Zed 2.0" "AR-Enhanced Security"]} :runner {:deck [(qty "Persephone" 10)]}}) (play-from-hand state :corp "AR-Enhanced Security" "New remote") (score-agenda state :corp (get-content state :remote1 0)) (play-from-hand state :corp "Zed 1.0" "Archives") (rez state :corp (get-ice state :archives 0)) (take-credits state :corp) (play-from-hand state :runner "Persephone") (run-on state "Archives") (run-continue state) (fire-subs state (get-ice state :archives 0)) (run-continue state) (click-prompt state :runner "Yes") (is (= 1 (count-tags state)) "Runner took 1 tag from using Persephone's ability while AR-Enhanced Security is scored") (run-jack-out state) (take-credits state :runner) ;; Gotta move the discarded cards back to the deck (core/move state :corp (find-card "Zed 2.0" (:discard (get-corp))) :deck) (core/move state :corp (find-card "Zed 2.0" (:discard (get-corp))) :deck) (take-credits state :corp) (run-on state "Archives") (run-continue state) (fire-subs state (get-ice state :archives 0)) (run-continue state) (click-prompt state :runner "Yes") (is (= 2 (count-tags state)) "Runner took 1 tag from using Persephone's ability while AR-Enhanced Security is scored")))) (deftest pheromones ;; Pheromones ability shouldn't have a NullPointerException when fired with 0 virus counter (testing "Basic test" (do-game (new-game {:runner {:deck ["Pheromones"]}}) (take-credits state :corp) (play-from-hand state :runner "Pheromones") (let [ph (get-program state 0)] (card-ability state :runner (refresh ph) 0) (run-empty-server state "HQ") (click-prompt state :runner "No action") (is (= 1 (get-counters (refresh ph) :virus)) "Pheromones gained 1 counter") (card-ability state :runner (refresh ph) 0)))) ; this doesn't do anything, but shouldn't crash (testing "Pay-credits prompt" (do-game (new-game {:runner {:deck ["Pheromones" "Inti"]}}) (take-credits state :corp) (play-from-hand state :runner "Pheromones") (play-from-hand state :runner "Inti") (run-empty-server state "HQ") (click-prompt state :runner "No action") (run-empty-server state "HQ") (click-prompt state :runner "No action") (take-credits state :runner) (take-credits state :corp) (let [phero (get-program state 0) inti (get-program state 1)] (is (changes-credits (get-runner) -2 (card-ability state :runner inti 1))) (changes-val-macro 0 (:credit (get-runner)) "Used 2 credits from Pheromones" (run-on state "HQ") (card-ability state :runner inti 1) (click-card state :runner phero) (click-card state :runner phero)))))) (deftest plague ;; Plague (do-game (new-game {:corp {:deck ["PI:NAME:<NAME>END_PI"]} :runner {:deck ["Plague"]}}) (play-from-hand state :corp "PI:NAME:<NAME>END_PI" "New remote") (take-credits state :corp) (play-from-hand state :runner "Plague") (click-prompt state :runner "Server 1") (let [plague (get-program state 0)] (run-empty-server state "Server 1") (click-prompt state :runner "No action") (is (= 2 (get-counters (refresh plague) :virus)) "Plague gained 2 counters") (run-empty-server state "Server 1") (click-prompt state :runner "No action") (is (= 4 (get-counters (refresh plague) :virus)) "Plague gained 2 counters") (run-empty-server state "Archives") (is (= 4 (get-counters (refresh plague) :virus)) "Plague did not gain counters")))) (deftest progenitor ;; Progenitor (testing "Hosting Hivemind, using Virus Breeding Ground. Issue #738" (do-game (new-game {:runner {:deck ["Progenitor" "Virus Breeding Ground" "Hivemind"]}}) (take-credits state :corp) (play-from-hand state :runner "Progenitor") (play-from-hand state :runner "Virus Breeding Ground") (is (= 4 (core/available-mu state))) (let [prog (get-program state 0) vbg (get-resource state 0)] (card-ability state :runner prog 0) (click-card state :runner (find-card "Hivemind" (:hand (get-runner)))) (is (= 4 (core/available-mu state)) "No memory used to host on Progenitor") (let [hive (first (:hosted (refresh prog)))] (is (= "Hivemind" (:title hive)) "Hivemind is hosted on Progenitor") (is (= 1 (get-counters hive :virus)) "Hivemind has 1 counter") (is (zero? (:credit (get-runner))) "Full cost to host on Progenitor") (take-credits state :runner 1) (take-credits state :corp) (card-ability state :runner vbg 0) ; use VBG to transfer 1 token to Hivemind (click-card state :runner hive) (is (= 2 (get-counters (refresh hive) :virus)) "Hivemind gained 1 counter") (is (zero? (get-counters (refresh vbg) :virus)) "Virus Breeding Ground lost 1 counter"))))) (testing "Keep MU the same when hosting or trashing hosted programs" (do-game (new-game {:runner {:deck ["Progenitor" "Hivemind"]}}) (take-credits state :corp) (play-from-hand state :runner "Progenitor") (let [pro (get-program state 0)] (card-ability state :runner pro 0) (click-card state :runner (find-card "Hivemind" (:hand (get-runner)))) (is (= 2 (:click (get-runner)))) (is (= 2 (:credit (get-runner)))) (is (= 4 (core/available-mu state)) "Hivemind 2 MU not deducted from available MU") ;; Trash Hivemind (core/move state :runner (find-card "Hivemind" (:hosted (refresh pro))) :discard) (is (= 4 (core/available-mu state)) "Hivemind 2 MU not added to available MU"))))) (deftest reaver ;; Reaver - Draw a card the first time you trash an installed card each turn (testing "Basic test" (do-game (new-game {:corp {:deck ["PAD Campaign"]} :runner {:deck ["Reaver" (qty "Fall Guy" 5)]}}) (starting-hand state :runner ["Reaver" "Fall Guy"]) (play-from-hand state :corp "PAD Campaign" "New remote") (take-credits state :corp) (core/gain state :runner :credit 10) (core/gain state :runner :click 1) (play-from-hand state :runner "Reaver") (is (= 1 (count (:hand (get-runner)))) "One card in hand") (run-empty-server state "Server 1") (click-prompt state :runner "Pay 4 [Credits] to trash") ; Trash PAD campaign (is (= 2 (count (:hand (get-runner)))) "Drew a card from trash of corp card") (play-from-hand state :runner "Fall Guy") (play-from-hand state :runner "Fall Guy") (is (zero? (count (:hand (get-runner)))) "No cards in hand") ; No draw from Fall Guy trash as Reaver already fired this turn (card-ability state :runner (get-resource state 0) 1) (is (zero? (count (:hand (get-runner)))) "No cards in hand") (take-credits state :runner) ; Draw from Fall Guy trash on corp turn (card-ability state :runner (get-resource state 0) 1) (is (= 1 (count (:hand (get-runner)))) "One card in hand"))) (testing "with Freelance Coding Construct - should not draw when trash from hand #2671" (do-game (new-game {:runner {:deck [(qty "Reaver" 9) "Imp" "Snitch" "Freelance Coding Contract"]}}) (starting-hand state :runner ["Reaver" "Imp" "Snitch" "Freelance Coding Contract"]) (take-credits state :corp) (play-from-hand state :runner "Reaver") (is (= 3 (count (:hand (get-runner)))) "Four cards in hand") (is (= 3 (:credit (get-runner))) "3 credits") (play-from-hand state :runner "Freelance Coding Contract") (click-card state :runner "Snitch") (click-card state :runner "Imp") (click-prompt state :runner "Done") (is (= 7 (:credit (get-runner))) "7 credits - FCC fired") (is (zero? (count (:hand (get-runner)))) "No cards in hand")))) (deftest rezeki ;; Rezeki - gain 1c when turn begins (do-game (new-game {:runner {:deck ["PI:NAME:<NAME>END_PI"]}}) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (take-credits state :runner) (let [credits (:credit (get-runner))] (take-credits state :corp) (is (= (:credit (get-runner)) (+ credits 1)) "Gain 1 from Rezeki")))) (deftest rng-key ;; RNG Key - first successful run on RD/HQ, guess a number, gain credits or cards if number matches card cost (testing "Basic behaviour - first successful run on RD/HQ, guess a number, gain credits or cards if number matches card cost" (do-game (new-game {:corp {:deck [(qty "Enigma" 5) "Hedge Fund"]} :runner {:deck ["RNG Key" (qty "Paperclip" 2)]}}) (starting-hand state :corp ["Hedge Fund"]) (starting-hand state :runner ["RNG Key"]) (take-credits state :corp) (testing "Gain 3 credits" (play-from-hand state :runner "RNG Key") (is (= 5 (:credit (get-runner))) "Starts at 5 credits") (run-empty-server state "HQ") (click-prompt state :runner "Yes") (click-prompt state :runner "5") (click-prompt state :runner "Gain 3 [Credits]") (is (= 8 (:credit (get-runner))) "Gained 3 credits") (click-prompt state :runner "No action")) (testing "Do not trigger on second successful run" (run-empty-server state "R&D") (click-prompt state :runner "No action") (take-credits state :runner) (take-credits state :corp)) (testing "Do not trigger on archives" (run-empty-server state "Archives") (take-credits state :runner) (take-credits state :corp)) (testing "Do not get choice if trigger declined" (run-empty-server state "R&D") (click-prompt state :runner "No") (click-prompt state :runner "No action")) (run-empty-server state "R&D") (click-prompt state :runner "No action") (take-credits state :runner) (take-credits state :corp) (testing "Do not gain credits / cards if guess incorrect" (run-empty-server state "R&D") (click-prompt state :runner "Yes") (click-prompt state :runner "2") (click-prompt state :runner "No action")) (take-credits state :runner) (take-credits state :corp) (testing "Gain 2 cards" (is (zero? (count (:hand (get-runner)))) "Started with 0 cards") (run-empty-server state "R&D") (click-prompt state :runner "Yes") (click-prompt state :runner "3") (click-prompt state :runner "Draw 2 cards") (click-prompt state :runner "No action") (is (= 2 (count (:hand (get-runner)))) "Gained 2 cards") (is (zero? (count (:deck (get-runner)))) "Cards came from stack")))) (testing "Pays out when accessing an Upgrade. Issue #4804" (do-game (new-game {:corp {:deck ["Hokusai Grid" "Hedge Fund"]} :runner {:deck ["RNG Key"]}}) (play-from-hand state :corp "Hokusai Grid" "HQ") (take-credits state :corp) (play-from-hand state :runner "RNG Key") (is (= 5 (:credit (get-runner))) "Starts at 5 credits") (run-empty-server state "HQ") (click-prompt state :runner "Yes") (click-prompt state :runner "2") (click-prompt state :runner "Unrezzed upgrade") (is (= "Choose RNG Key reward" (:msg (prompt-map :runner))) "Runner gets RNG Key reward"))) (testing "Works when running a different server first #5292" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Hokusai Grid" "Hedge Fund"]} :runner {:deck ["RNG Key"]}}) (play-from-hand state :corp "Hokusai Grid" "New remote") (take-credits state :corp) (play-from-hand state :runner "RNG Key") (run-empty-server state "Server 1") (click-prompt state :runner "No action") (run-empty-server state "HQ") (click-prompt state :runner "Yes") (click-prompt state :runner "5") (is (= "Choose RNG Key reward" (:msg (prompt-map :runner))) "Runner gets RNG Key reward"))) (testing "Works after running vs Crisium Grid #3772" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Crisium Grid" "Hedge Fund"] :credits 10} :runner {:hand ["RNG Key"] :credits 10}}) (play-from-hand state :corp "Crisium Grid" "HQ") (rez state :corp (get-content state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "RNG Key") (run-empty-server state "HQ") (click-prompt state :runner "Crisium Grid") (click-prompt state :runner "Pay 5 [Credits] to trash") (click-prompt state :runner "No action") (run-empty-server state "HQ") (click-prompt state :runner "Yes") (click-prompt state :runner "5") (is (= "Choose RNG Key reward" (:msg (prompt-map :runner))) "Runner gets RNG Key reward")))) (deftest sadyojata ;; Sadyojata (testing "Swap ability" (testing "Doesnt work if no Deva in hand" (do-game (new-game {:runner {:hand ["Sadyojata" "Corroder"] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Sadyojata") (card-ability state :runner (get-program state 0) 2) (is (empty? (:prompt (get-runner))) "No select prompt as there's no Deva in hand"))) (testing "Works with another deva in hand" (doseq [deva ["PI:NAME:<NAME>END_PIghora" "PI:NAME:<NAME>END_PIadyojata" "PI:NAME:<NAME>END_PIamadeva"]] (do-game (new-game {:runner {:hand ["Sadyojata" deva] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Sadyojata") (let [installed-deva (get-program state 0)] (card-ability state :runner installed-deva 2) (click-card state :runner (first (:hand (get-runner)))) (is (not (utils/same-card? installed-deva (get-program state 0))) "Installed deva is not same as previous deva") (is (= deva (:title (get-program state 0))))))))) (testing "Break ability targets ice with 3 or more subtypes" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Executive Functioning"] :credits 10} :runner {:hand ["Sadyojata"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Executive Functioning" "R&D") (take-credits state :corp) (play-from-hand state :runner "Sadyojata") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "No break prompt") (run-jack-out state) (run-on state "R&D") (rez state :corp (get-ice state :rd 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (seq (:prompt (get-runner))) "Have a break prompt") (click-prompt state :runner "Trace 4 - Do 1 brain damage") (is (:broken (first (:subroutines (get-ice state :rd 0)))) "The break ability worked")))) (deftest sage ;; Sage (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma"] :credits 10} :runner {:deck ["Sage" "Box-E"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Enigma" "R&D") (take-credits state :corp) (play-from-hand state :runner "Sage") (let [sage (get-program state 0) iw (get-ice state :hq 0) engima (get-ice state :rd 0)] (is (= 2 (core/available-mu state))) (is (= 2 (get-strength (refresh sage))) "+2 strength for 2 unused MU") (play-from-hand state :runner "Box-E") (is (= 4 (core/available-mu state))) (is (= 4 (get-strength (refresh sage))) "+4 strength for 4 unused MU") (run-on state :hq) (rez state :corp iw) (run-continue state) (card-ability state :runner (refresh sage) 0) (click-prompt state :runner "End the run") (is (:broken (first (:subroutines (refresh iw)))) "Broke a barrier subroutine") (run-jack-out state) (run-on state :rd) (rez state :corp engima) (run-continue state) (card-ability state :runner (refresh sage) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "Done") (is (:broken (first (:subroutines (refresh engima)))) "Broke a code gate subroutine")))) (deftest sahasrara ;; Sahasrara (testing "Pay-credits prompt" (do-game (new-game {:runner {:deck ["Sahasrara" "Equivocation"]}}) (take-credits state :corp) (play-from-hand state :runner "Sahasrara") (let [rara (get-program state 0)] (changes-val-macro 0 (:credit (get-runner)) "Used 2 credits from Sahasrara" (play-from-hand state :runner "Equivocation") (click-card state :runner rara) (click-card state :runner rara)))))) (deftest savant ;; Savant (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Cobra" "Enigma"] :credits 10} :runner {:deck ["SPI:NAME:<NAME>END_PIant" "Box-E"] :credits 20}}) (play-from-hand state :corp "Cobra" "HQ") (play-from-hand state :corp "Enigma" "R&D") (take-credits state :corp) (play-from-hand state :runner "Savant") (let [savant (get-program state 0) cobra (get-ice state :hq 0) enigma (get-ice state :rd 0)] (is (= 2 (core/available-mu state))) (is (= 3 (get-strength (refresh savant))) "+2 strength for 2 unused MU") (play-from-hand state :runner "Box-E") (is (= 4 (core/available-mu state))) (is (= 5 (get-strength (refresh savant))) "+4 strength for 4 unused MU") (run-on state :hq) (rez state :corp cobra) (run-continue state) (card-ability state :runner (refresh savant) 0) (click-prompt state :runner "Trash a program") (click-prompt state :runner "Done") (is (:broken (first (:subroutines (refresh cobra)))) "Broke a sentry subroutine") (run-jack-out state) (run-on state :rd) (rez state :corp enigma) (run-continue state) (card-ability state :runner (refresh savant) 0) (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (is (:broken (first (:subroutines (refresh enigma)))) "Broke a code gate subroutine")))) (deftest scheherazade ;; Scheherazade - Gain 1 credit when it hosts a program (do-game (new-game {:runner {:deck ["Scheherazade" "Cache" "Inti" "Fall Guy"]}}) (take-credits state :corp) (play-from-hand state :runner "Scheherazade") (let [sch (get-program state 0)] (card-ability state :runner sch 0) (click-card state :runner (find-card "Inti" (:hand (get-runner)))) (is (= 1 (count (:hosted (refresh sch))))) (is (= 2 (:click (get-runner))) "Spent 1 click to install and host") (is (= 6 (:credit (get-runner))) "Gained 1 credit") (is (= 3 (core/available-mu state)) "Programs hosted on Scheh consume MU") (card-ability state :runner sch 0) (click-card state :runner (find-card "Cache" (:hand (get-runner)))) (is (= 2 (count (:hosted (refresh sch))))) (is (= 6 (:credit (get-runner))) "Gained 1 credit") (card-ability state :runner sch 0) (click-card state :runner (find-card "Fall Guy" (:hand (get-runner)))) (is (= 2 (count (:hosted (refresh sch)))) "Can't host non-program") (is (= 1 (count (:hand (get-runner)))))))) (deftest self-modifying-code ;; Trash & pay 2 to search deck for a program and install it. Shuffle. (testing "Trash & pay 2 to search deck for a program and install it. Shuffle" (do-game (new-game {:runner {:deck [(qty "Self-modifying Code" 3) "Reaver"]}}) (starting-hand state :runner ["Self-modifying Code" "Self-modifying Code"]) (core/gain state :runner :credit 5) (take-credits state :corp) (play-from-hand state :runner "Self-modifying Code") (play-from-hand state :runner "Self-modifying Code") (let [smc1 (get-program state 0) smc2 (get-program state 1)] (card-ability state :runner smc1 0) (click-prompt state :runner (find-card "Reaver" (:deck (get-runner)))) (is (= 6 (:credit (get-runner))) "Paid 2 for SMC, 2 for install - 6 credits left") (is (= 1 (core/available-mu state)) "SMC MU refunded") (take-credits state :runner) (take-credits state :corp) (card-ability state :runner smc2 0) (is (= 1 (count (:hand (get-runner)))) "1 card drawn due to Reaver before SMC program selection") (is (zero? (count (:deck (get-runner)))) "Deck empty")))) (testing "Pay for SMC with Multithreader. Issue #4961" (do-game (new-game {:runner {:deck [(qty "Self-modifying Code" 3) "Rezeki"] :hand ["Self-modifying Code" "Multithreader"]}}) (take-credits state :corp) (play-from-hand state :runner "Self-modifying Code") (play-from-hand state :runner "Multithreader") (let [smc (get-program state 0) multi (get-program state 1)] (card-ability state :runner smc 0) (click-card state :runner multi) (click-card state :runner multi) (click-prompt state :runner (find-card "Rezeki" (:deck (get-runner)))) (is (= "Rezeki" (:title (get-program state 1))) "Rezeki is installed") (is (= 0 (:credit (get-runner))) "Runner had 2 credits before SMC, paid 2 for SMC from Multithreader, 2 for Rezeki install - 0 credits left"))))) (deftest shiv ;; Shiv - Gain 1 strength for each installed breaker; no MU cost when 2+ link (do-game (new-game {:runner {:id "PI:NAME:<NAME>END_PI: Cyber Explorer" :deck ["Shiv" (qty "Inti" 2) "Access to Globalsec"]}}) (is (= 1 (get-link state)) "1 link") (take-credits state :corp) (play-from-hand state :runner "Shiv") (let [shiv (get-program state 0)] (is (= 1 (get-strength (refresh shiv))) "1 installed breaker; 1 strength") (play-from-hand state :runner "Inti") (is (= 2 (get-strength (refresh shiv))) "2 installed breakers; 2 strength") (play-from-hand state :runner "Inti") (is (= 3 (get-strength (refresh shiv))) "3 installed breakers; 3 strength") (is (= 1 (core/available-mu state)) "3 MU consumed") (play-from-hand state :runner "Access to Globalsec") (is (= 2 (get-link state)) "2 link") (is (= 2 (core/available-mu state)) "Shiv stops using MU when 2+ link")))) (deftest sneakdoor-beta (testing "PI:NAME:<NAME>END_PI, Ash on HQ should prevent Sneakdoor HQ access but still give Gabe credits. Issue #1138." (do-game (new-game {:corp {:deck ["Ash 2X3ZB9CY"]} :runner {:id "PI:NAME:<NAME>END_PI: Consummate Professional" :deck ["Sneakdoor Beta"]}}) (play-from-hand state :corp "Ash 2X3ZB9CY" "HQ") (take-credits state :corp) (play-from-hand state :runner "Sneakdoor Beta") (is (= 1 (:credit (get-runner))) "Sneakdoor cost 4 credits") (let [sb (get-program state 0) ash (get-content state :hq 0)] (rez state :corp ash) (card-ability state :runner sb 0) (run-continue state) (click-prompt state :corp "0") (click-prompt state :runner "0") (is (= 3 (:credit (get-runner))) "Gained 2 credits from Gabe's ability") (is (= (:cid ash) (-> (prompt-map :runner) :card :cid)) "Ash interrupted HQ access after Sneakdoor run") (is (= :hq (-> (get-runner) :register :successful-run first)) "Successful Run on HQ recorded")))) (testing "do not switch to HQ if Archives has Crisium Grid. Issue #1229." (do-game (new-game {:corp {:deck ["Crisium Grid" "Priority Requisition" "Private Security Force"]} :runner {:deck ["Sneakdoor Beta"]}}) (play-from-hand state :corp "Crisium Grid" "Archives") (trash-from-hand state :corp "Priority Requisition") (take-credits state :corp) (play-from-hand state :runner "Sneakdoor Beta") (let [sb (get-program state 0) cr (get-content state :archives 0)] (rez state :corp cr) (card-ability state :runner sb 0) (run-continue state) (is (= :archives (get-in @state [:run :server 0])) "Crisium Grid stopped Sneakdoor Beta from switching to HQ")))) (testing "Allow Nerve Agent to gain counters. Issue #1158/#955" (do-game (new-game {:runner {:deck ["Sneakdoor Beta" "Nerve Agent"]}}) (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Nerve Agent") (play-from-hand state :runner "Sneakdoor Beta") (let [nerve (get-program state 0) sb (get-program state 1)] (card-ability state :runner sb 0) (run-continue state) (click-prompt state :runner "No action") (is (= 1 (get-counters (refresh nerve) :virus))) (card-ability state :runner sb 0) (run-continue state) (is (= 2 (get-counters (refresh nerve) :virus)))))) (testing "Grant Security Testing credits on HQ." (do-game (new-game {:runner {:deck ["Security Testing" "Sneakdoor Beta"]}}) (take-credits state :corp) (play-from-hand state :runner "Sneakdoor Beta") (play-from-hand state :runner "Security Testing") (take-credits state :runner) (is (= 3 (:credit (get-runner)))) (take-credits state :corp) (let [sb (get-program state 0)] (click-prompt state :runner "HQ") (card-ability state :runner sb 0) (run-continue state) (is (not (:run @state)) "Switched to HQ and ended the run from Security Testing") (is (= 5 (:credit (get-runner))) "Sneakdoor switched to HQ and earned Security Testing credits")))) (testing "Sneakdoor Beta trashed during run" (do-game (new-game {:runner {:hand ["Sneakdoor Beta"]} :corp {:hand ["Ichi 1.0" "Hedge Fund"]}}) (play-from-hand state :corp "Ichi 1.0" "Archives") (let [ichi (get-ice state :archives 0)] (rez state :corp ichi) (take-credits state :corp) (play-from-hand state :runner "Sneakdoor Beta") (let [sb (get-program state 0)] (card-ability state :runner sb 0) (run-continue state) (fire-subs state (refresh ichi)) (is (= :select (prompt-type :corp)) "Corp has a prompt to select program to delete") (click-card state :corp "Sneakdoor Beta") (click-prompt state :corp "Done") (is (= "Sneakdoor Beta" (-> (get-runner) :discard first :title)) "Sneakdoor was trashed") (click-prompt state :corp "0") (click-prompt state :runner "1") (run-continue state) (run-continue state) (is (= :hq (get-in @state [:run :server 0])) "Run continues on HQ"))))) (testing "Sneakdoor Beta effect ends at end of run" (do-game (new-game {:runner {:hand ["Sneakdoor Beta"]} :corp {:hand ["Rototurret" "Hedge Fund"] :discard ["Hedge Fund"]}}) (play-from-hand state :corp "Rototurret" "Archives") (let [roto (get-ice state :archives 0)] (rez state :corp roto) (take-credits state :corp) (play-from-hand state :runner "Sneakdoor Beta") (let [sb (get-program state 0)] (card-ability state :runner sb 0) (run-continue state) (fire-subs state (refresh roto)) (is (= :select (prompt-type :corp)) "Corp has a prompt to select program to delete") (click-card state :corp "Sneakdoor Beta") (is (= "Sneakdoor Beta" (-> (get-runner) :discard first :title)) "Sneakdoor was trashed") (run-on state "Archives") (run-continue state) (run-continue state) (is (= :approach-server (:phase (get-run))) "Run has bypassed Rototurret") (is (= :archives (get-in @state [:run :server 0])) "Run continues on Archives")))))) (deftest snitch ;; Snitch (testing "Only works on rezzed ice" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Quandary"]} :runner {:deck ["Snitch"]}}) (play-from-hand state :corp "Quandary" "R&D") (take-credits state :corp) (play-from-hand state :runner "Snitch") (let [snitch (get-program state 0)] (run-on state "R&D") (is (prompt-is-card? state :runner snitch) "Option to expose") (is (= "Use Snitch to expose approached ice?" (:msg (prompt-map :runner)))) (click-prompt state :runner "Yes") (is (= "Jack out?" (:msg (prompt-map :runner)))) (click-prompt state :runner "Yes")))) (testing "Doesn't work if ice is rezzed" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Quandary"]} :runner {:deck ["Snitch"]}}) (play-from-hand state :corp "Quandary" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Snitch") (run-on state "HQ") (is (empty? (:prompt (get-runner))) "No option to jack out") (run-continue state) (run-jack-out state))) (testing "Doesn't work if there is no ice" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Hedge Fund"]} :runner {:deck ["Snitch"]}}) (take-credits state :corp) (play-from-hand state :runner "Snitch") (run-on state "Archives") (is (empty? (:prompt (get-runner))) "No option to jack out") (run-continue state)))) (deftest snowball (testing "Strength boost until end of run when used to break a subroutine" (do-game (new-game {:corp {:deck ["Spiderweb" "Fire Wall" "Hedge Fund"] :credits 20} :runner {:deck ["Snowball"]}}) (play-from-hand state :corp "Hedge Fund") (play-from-hand state :corp "Fire Wall" "HQ") (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (core/gain state :corp :credit 1) (play-from-hand state :runner "Snowball") (let [sp (get-ice state :hq 1) fw (get-ice state :hq 0) snow (get-program state 0)] (run-on state "HQ") (rez state :corp sp) (run-continue state) (card-ability state :runner snow 1) ; match strength (is (= 2 (get-strength (refresh snow)))) (card-ability state :runner snow 0) ; strength matched, break a sub (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (click-prompt state :runner "End the run") (is (= 5 (get-strength (refresh snow))) "Broke 3 subs, gained 3 more strength") (run-continue state) (rez state :corp fw) (run-continue state) (is (= 4 (get-strength (refresh snow))) "Has +3 strength until end of run; lost 1 per-encounter boost") (card-ability state :runner snow 1) ; match strength (is (= 5 (get-strength (refresh snow))) "Matched strength, gained 1") (card-ability state :runner snow 0) ; strength matched, break a sub (click-prompt state :runner "End the run") (is (= 6 (get-strength (refresh snow))) "Broke 1 sub, gained 1 more strength") (run-continue state) (is (= 5 (get-strength (refresh snow))) "+4 until-end-of-run strength") (run-jack-out state) (is (= 1 (get-strength (refresh snow))) "Back to default strength")))) (testing "Strength boost until end of run when using dynamic auto-pump-and-break ability" (do-game (new-game {:corp {:deck ["Spiderweb" (qty "Hedge Fund" 2)]} :runner {:deck ["Snowball"]}}) (play-from-hand state :corp "Hedge Fund") (play-from-hand state :corp "Spiderweb" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Snowball") (let [sp (get-ice state :hq 0) snow (get-program state 0)] (run-on state "HQ") (rez state :corp sp) (run-continue state) (is (= 1 (get-strength (refresh snow))) "Snowball starts at 1 strength") (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh snow)}) (is (= 5 (get-strength (refresh snow))) "Snowball was pumped once and gained 3 strength from breaking") (core/process-action "continue" state :corp nil) (is (= 4 (get-strength (refresh snow))) "+3 until-end-of-run strength"))))) (deftest stargate ;; Stargate - once per turn Keyhole which doesn't shuffle (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Ice Wall" 10)] :hand ["Herald" "Troll"]} :runner {:deck ["Stargate"]}}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (is (= "Troll" (-> (get-corp) :deck first :title)) "Troll on top of deck") (is (= "Herald" (-> (get-corp) :deck second :title)) "Herald 2nd") (take-credits state :corp) (play-from-hand state :runner "Stargate") (card-ability state :runner (get-program state 0) 0) (is (:run @state) "Run initiated") (run-continue state) (click-prompt state :runner "Troll") (is (empty? (:prompt (get-runner))) "Prompt closed") (is (not (:run @state)) "Run ended") (is (-> (get-corp) :discard first :seen) "Troll is faceup") (is (= "Troll" (-> (get-corp) :discard first :title)) "Troll was trashed") (is (= "Herald" (-> (get-corp) :deck first :title)) "Herald now on top of R&D") (card-ability state :runner (get-program state 0) 0) (is (not (:run @state)) "No run ended, as Stargate is once per turn"))) (testing "Different message on repeating cards" (testing "bottom card" (do-game (new-game {:corp {:deck [(qty "Troll" 10)] :hand ["Herald" "Troll"]} :runner {:deck ["Stargate"]}}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (is (= "Troll" (-> (get-corp) :deck first :title)) "Troll 1st") (is (= "Herald" (-> (get-corp) :deck second :title)) "Herald 2nd") (is (= "Troll" (-> (get-corp) :deck (#(nth % 2)) :title)) "Another Troll 3rd") (take-credits state :corp) (play-from-hand state :runner "Stargate") (card-ability state :runner (get-program state 0) 0) (run-continue state) (click-prompt state :runner (nth (prompt-buttons :runner) 2)) (is (last-log-contains? state "Runner uses Stargate to trash bottom Troll.") "Correct log"))) (testing "middle card" (do-game (new-game {:corp {:deck [(qty "Troll" 10)] :hand ["Herald" "Troll"]} :runner {:deck ["Stargate"]}}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (is (= "Herald" (-> (get-corp) :deck first :title)) "Herald 1st") (is (= "Troll" (-> (get-corp) :deck second :title)) "Troll 2nd") (is (= "Troll" (-> (get-corp) :deck (#(nth % 2)) :title)) "Another Troll 3rd") (take-credits state :corp) (play-from-hand state :runner "Stargate") (card-ability state :runner (get-program state 0) 0) (run-continue state) (click-prompt state :runner (second (prompt-buttons :runner))) (is (last-log-contains? state "Runner uses Stargate to trash middle Troll.") "Correct log"))) (testing "top card" (do-game (new-game {:corp {:deck [(qty "Troll" 10)] :hand ["Herald" "Troll"]} :runner {:deck ["Stargate"]}}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (is (= "Troll" (-> (get-corp) :deck first :title)) "Troll 1st") (is (= "Herald" (-> (get-corp) :deck second :title)) "Herald 2nd") (is (= "Troll" (-> (get-corp) :deck (#(nth % 2)) :title)) "Another Troll 3rd") (take-credits state :corp) (play-from-hand state :runner "Stargate") (card-ability state :runner (get-program state 0) 0) (run-continue state) (click-prompt state :runner (first (prompt-buttons :runner))) (is (last-log-contains? state "Runner uses Stargate to trash top Troll.") "Correct log")))) (testing "No position indicator if non-duplicate selected" (do-game (new-game {:corp {:deck [(qty "Troll" 10)] :hand ["Herald" "Troll"]} :runner {:deck ["Stargate"]}}) (core/move state :corp (find-card "Herald" (:hand (get-corp))) :deck {:front true}) (core/move state :corp (find-card "Troll" (:hand (get-corp))) :deck {:front true}) (is (= "Troll" (-> (get-corp) :deck first :title)) "Troll 1st") (is (= "Herald" (-> (get-corp) :deck second :title)) "Herald 2nd") (is (= "Troll" (-> (get-corp) :deck (#(nth % 2)) :title)) "Another Troll 3rd") (take-credits state :corp) (play-from-hand state :runner "Stargate") (card-ability state :runner (get-program state 0) 0) (run-continue state) (click-prompt state :runner (second (prompt-buttons :runner))) (is (last-log-contains? state "Runner uses Stargate to trash Herald.") "Correct log")))) (deftest study-guide ;; Study Guide - 2c to add a power counter; +1 strength per counter (do-game (new-game {:runner {:deck ["Study Guide" "Sure Gamble"]}}) (take-credits state :corp) (play-from-hand state :runner "Sure Gamble") (play-from-hand state :runner "Study Guide") (let [sg (get-program state 0)] (card-ability state :runner sg 1) (is (= 4 (:credit (get-runner))) "Paid 2c") (is (= 1 (get-counters (refresh sg) :power)) "Has 1 power counter") (is (= 1 (get-strength (refresh sg))) "1 strength") (card-ability state :runner sg 1) (is (= 2 (:credit (get-runner))) "Paid 2c") (is (= 2 (get-counters (refresh sg) :power)) "Has 2 power counters") (is (= 2 (get-strength (refresh sg))) "2 strength")))) (deftest sunya ;; Sūnya (testing "Basic test" (do-game (new-game {:runner {:deck ["Sūnya"]} :corp {:deck ["Rototurret"]}}) (play-from-hand state :corp "Rototurret" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Sūnya") (let [sunya (get-program state 0) roto (get-ice state :hq 0)] (run-on state :hq) (rez state :corp (refresh roto)) (run-continue state) (card-ability state :runner (refresh sunya) 0) (click-prompt state :runner "Trash a program") (click-prompt state :runner "End the run") (changes-val-macro 1 (get-counters (refresh sunya) :power) "Got 1 token" (run-continue state)))))) (deftest surfer ;; Surfer - Swap position with ice before or after when encountering a Barrier ICE (testing "Basic test" (do-game (new-game {:corp {:deck ["Ice Wall" "Quandary"]} :runner {:deck ["Surfer"]}}) (play-from-hand state :corp "Quandary" "HQ") (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Surfer") (is (= 3 (:credit (get-runner))) "Paid 2 credits to install Surfer") (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (run-continue state) (is (= 2 (get-in @state [:run :position])) "Starting run at position 2") (let [surf (get-program state 0)] (card-ability state :runner surf 0) (click-card state :runner (get-ice state :hq 0)) (is (= 1 (:credit (get-runner))) "Paid 2 credits to use Surfer") (is (= 1 (get-in @state [:run :position])) "Now at next position (1)") (is (= "Ice Wall" (:title (get-ice state :hq 0))) "Ice Wall now at position 1")))) (testing "Swapping twice across two turns" (do-game (new-game {:corp {:deck ["Ice Wall" "Vanilla"]} :runner {:deck ["Surfer"] :credits 10}}) (play-from-hand state :corp "Vanilla" "HQ") (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Surfer") (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (run-continue state) (let [surf (get-program state 0)] (card-ability state :runner surf 0) (click-card state :runner (get-ice state :hq 0)) (run-jack-out state) (run-on state "HQ") (rez state :corp (get-ice state :hq 1)) (run-continue state) (card-ability state :runner surf 0) (click-card state :runner (get-ice state :hq 0)) (is (= ["Vanilla" "Ice Wall"] (map :title (get-ice state :hq))) "Vanilla is innermost, Ice Wall is outermost again") (is (= [0 1] (map :index (get-ice state :hq)))))))) (deftest takobi ;; Takobi - 2 power counter to add +3 strength to a non-AI icebreaker for encounter (testing "+1 counter when breaking all subs" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Ice Wall" "Enigma"]} :runner {:hand ["Takobi" "Corroder" "Gordian Blade"] :credits 20}}) (play-from-hand state :corp "Ice Wall" "HQ") (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Takobi") (play-from-hand state :runner "Corroder") (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (let [tako (get-program state 0) corr (get-program state 1) gord (get-program state 2) enig (get-ice state :hq 1) icew (get-ice state :hq 0)] (run-on state "HQ") (rez state :corp enig) (run-continue state) (card-ability state :runner gord 0) (click-prompt state :runner "End the run") (click-prompt state :runner "Done") (is (empty? (:prompt (get-runner))) "No prompt because not all subs were broken") (is (= 0 (get-counters (refresh tako) :power)) "No counter gained because not all subs were broken") (run-continue state) (rez state :corp icew) (run-continue state) (card-ability state :runner corr 0) (click-prompt state :runner "End the run") (click-prompt state :runner "Yes") (run-continue state) (is (= 1 (get-counters (refresh tako) :power)) "Counter gained from breaking all subs")))) (testing "+3 strength" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma"]} :runner {:hand ["Takobi" "Corroder" "Faust"] :credits 10}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Takobi") (play-from-hand state :runner "Corroder") (play-from-hand state :runner "Faust") (let [tako (get-program state 0) corr (get-program state 1) faus (get-program state 2)] (core/add-counter state :runner tako :power 3) (is (= 3 (get-counters (refresh tako) :power)) "3 counters on Takobi") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner tako 0) (click-card state :runner (refresh faus)) (is (not-empty (:prompt (get-runner))) "Can't select AI breakers") (click-card state :runner (refresh corr)) (is (empty? (:prompt (get-runner))) "Can select non-AI breakers") (is (= 5 (get-strength (refresh corr))) "Corroder at +3 strength") (is (= 1 (get-counters (refresh tako) :power)) "1 counter on Takobi") (card-ability state :runner tako 0) (is (empty? (:prompt (get-runner))) "No prompt when too few power counters") (run-continue state) (run-continue state) (is (= 2 (get-strength (refresh corr))) "Corroder returned to normal strength"))))) (deftest tranquilizer ;; Tranquilizer (testing "Basic test" (do-game (new-game {:corp {:hand ["Ice Wall"] :deck [(qty "Hedge Fund" 10)]} :runner {:hand ["Tranquilizer"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Tranquilizer") (click-card state :runner (get-ice state :hq 0)) (let [iw (get-ice state :hq 0) tranquilizer (first (:hosted (refresh iw)))] (is (= 1 (get-counters (refresh tranquilizer) :virus))) (take-credits state :runner) (rez state :corp iw) (take-credits state :corp) (is (= 2 (get-counters (refresh tranquilizer) :virus))) (take-credits state :runner) (take-credits state :corp) (is (= 3 (get-counters (refresh tranquilizer) :virus))) (is (not (rezzed? (refresh iw))) "Ice Wall derezzed") (take-credits state :runner) (rez state :corp iw) (take-credits state :corp) (is (= 4 (get-counters (refresh tranquilizer) :virus))) (is (not (rezzed? (refresh iw))) "Ice Wall derezzed again")))) (testing "Derez on install" (do-game (new-game {:corp {:hand ["Ice Wall"] :deck [(qty "Hedge Fund" 10)]} :runner {:hand ["Tranquilizer" "Hivemind" "Surge"] :credits 10}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Hivemind") (let [iw (get-ice state :hq 0) hive (get-program state 0)] (is (= 1 (get-counters (refresh hive) :virus)) "Hivemind starts with 1 virus counter") (play-from-hand state :runner "Surge") (click-card state :runner (refresh hive)) (is (= 3 (get-counters (refresh hive) :virus)) "Hivemind gains 2 virus counters") (rez state :corp iw) (is (rezzed? (refresh iw)) "Ice Wall rezzed") (play-from-hand state :runner "Tranquilizer") (click-card state :runner (get-ice state :hq 0)) (let [tranquilizer (first (:hosted (refresh iw)))] (is (= 1 (get-counters (refresh tranquilizer) :virus))) (is (not (rezzed? (refresh iw))) "Ice Wall derezzed")))))) (deftest trope ;; Trope (testing "Happy Path" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)]} :runner {:hand ["Trope" "Easy Mark"] :discard ["Sure Gamble" "Easy Mark" "Dirty Laundry"]}}) (take-credits state :corp) (play-from-hand state :runner "Trope") ;; wait 3 turns to make Trope have 3 counters (dotimes [n 3] (take-credits state :runner) (take-credits state :corp)) (is (= 3 (get-counters (refresh (get-program state 0)) :power))) (is (zero? (count (:deck (get-runner)))) "0 cards in deck") (is (= 3 (count (:discard (get-runner)))) "3 cards in discard") (card-ability state :runner (get-program state 0) 0) (is (not (empty? (:prompt (get-runner)))) "Shuffle prompt came up") (click-card state :runner (find-card "Easy Mark" (:discard (get-runner)))) (click-card state :runner (find-card "Dirty Laundry" (:discard (get-runner)))) (click-card state :runner (find-card "Sure Gamble" (:discard (get-runner)))) (is (= 3 (count (:deck (get-runner)))) "3 cards in deck") (is (zero? (count (:discard (get-runner)))) "0 cards in discard"))) (testing "Heap Locked" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Blacklist"]} :runner {:hand ["Trope" "Easy Mark"] :discard ["Sure Gamble" "Easy Mark" "Dirty Laundry"]}}) (play-from-hand state :corp "Blacklist" "New remote") (rez state :corp (refresh (get-content state :remote1 0))) (take-credits state :corp) (play-from-hand state :runner "Trope") ;; wait 3 turns to make Trope have 3 counters (dotimes [n 3] (take-credits state :runner) (take-credits state :corp)) (is (= 3 (get-counters (refresh (get-program state 0)) :power))) (is (zero? (count (:deck (get-runner)))) "0 cards in deck") (is (= 3 (count (:discard (get-runner)))) "3 cards in discard") (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "Shuffle prompt did not come up")))) (deftest trypano (testing "Hivemind and Architect interactions" (do-game (new-game {:corp {:deck [(qty "Architect" 2)]} :runner {:deck [(qty "Trypano" 2) "Hivemind"]}}) (play-from-hand state :corp "Architect" "HQ") (play-from-hand state :corp "Architect" "R&D") (let [architect-rezzed (get-ice state :hq 0) architect-unrezzed (get-ice state :rd 0)] (rez state :corp architect-rezzed) (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (click-card state :runner (get-card state architect-rezzed)) (play-from-hand state :runner "PI:NAME:<NAME>END_PI") (click-card state :runner architect-unrezzed) (is (= 2 (core/available-mu state)) "Trypano consumes 1 MU")) ;; wait 4 turns to make both Trypanos have 4 counters on them (dotimes [n 4] (take-credits state :runner) (take-credits state :corp) (click-prompt state :runner "Yes") (click-prompt state :runner "Yes")) (is (zero? (count (:discard (get-runner)))) "Trypano not in discard yet") (is (= 1 (count (get-in @state [:corp :servers :rd :ices]))) "Unrezzed Archiect is not trashed") (is (= 1 (count (get-in @state [:corp :servers :hq :ices]))) "Rezzed Archiect is not trashed") (play-from-hand state :runner "Hivemind") ; now Hivemind makes both Trypanos have 5 counters (is (zero? (count (get-in @state [:corp :servers :rd :ices]))) "Unrezzed Archiect was trashed") (is (= 1 (count (get-in @state [:corp :servers :hq :ices]))) "Rezzed Archiect was not trashed") (is (= 1 (count (:discard (get-runner)))) "Trypano went to discard"))) (testing "Fire when Hivemind gains counters" (do-game (new-game {:corp {:deck ["Architect"]} :runner {:deck ["TrPI:NAME:<NAME>END_PI" "Hivemind" (qty "Surge" 2)]}}) (play-from-hand state :corp "Architect" "R&D") (let [architect-unrezzed (get-ice state :rd 0)] (take-credits state :corp) (play-from-hand state :runner "Trypano") (click-card state :runner architect-unrezzed) (is (zero? (count (:discard (get-runner)))) "Trypano not in discard yet") (is (= 1 (count (get-ice state :rd))) "Unrezzed Architect is not trashed") (play-from-hand state :runner "Hivemind") (let [hive (get-program state 0)] (is (= 1 (get-counters (refresh hive) :virus)) "Hivemind starts with 1 virus counter") (play-from-hand state :runner "Surge") (click-card state :runner (refresh hive)) (is (= 3 (get-counters (refresh hive) :virus)) "Hivemind gains 2 virus counters") (play-from-hand state :runner "Surge") (click-card state :runner (refresh hive)) (is (= 5 (get-counters (refresh hive) :virus)) "Hivemind gains 2 virus counters (now at 5)") (is (zero? (count (get-ice state :rd))) "Unrezzed Architect was trashed") (is (= 3 (count (:discard (get-runner)))) "Trypano went to discard")))))) (deftest tycoon ;; Tycoon (testing "Tycoon gives 2c after using to break ICE" (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["Tycoon"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "TyPI:NAME:<NAME>END_PI") (let [tycoon (get-program state 0) credits (:credit (get-corp))] (run-on state "HQ") (run-continue state) (card-ability state :runner tycoon 0) (click-prompt state :runner "End the run") (card-ability state :runner tycoon 1) (is (= 4 (get-strength (refresh tycoon))) "Tycoon strength pumped to 4.") (is (= credits (:credit (get-corp))) "Corp doesn't gain credits until encounter is over") (run-continue state) (is (= (+ credits 2) (:credit (get-corp))) "Corp gains 2 credits from Tycoon being used") (is (= 1 (get-strength (refresh tycoon))) "Tycoon strength back down to 1.")))) ;; Issue #4220: Tycoon doesn't fire if Corp ends run before ice is passed (testing "Tycoon gives 2c even if ICE wasn't passed" (do-game (new-game {:corp {:deck ["Ice Wall" "Nisei MK II"]} :runner {:deck ["Tycoon"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (rez state :corp (get-ice state :hq 0)) (play-and-score state "Nisei MK II") (take-credits state :corp) (play-from-hand state :runner "TyPI:NAME:<NAME>END_PI") (let [tycoon (get-program state 0) credits (:credit (get-corp)) nisei (get-scored state :corp 0)] (run-on state "HQ") (run-continue state) (card-ability state :runner tycoon 0) (click-prompt state :runner "End the run") (card-ability state :runner tycoon 1) (is (= 4 (get-strength (refresh tycoon))) "Tycoon strength pumped to 4.") (is (= credits (:credit (get-corp))) "Corp doesn't gain credits until encounter is over") (card-ability state :corp (refresh nisei) 0) (is (= (+ credits 2) (:credit (get-corp))) "Corp gains 2 credits from Tycoon being used after Nisei MK II fires") (is (= 1 (get-strength (refresh tycoon))) "Tycoon strength back down to 1.")))) ;; Issue #4423: Tycoon no longer working automatically (testing "Tycoon pays out on auto-pump-and-break" (do-game (new-game {:corp {:deck ["PI:NAME:<NAME>END_PI 1.0"]} :runner {:deck ["Tycoon"]}}) (play-from-hand state :corp "PI:NAME:<NAME>END_PI 1.0" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Tycoon") (let [tycoon (get-program state 0) credits (:credit (get-corp))] (run-on state "HQ") (run-continue state) (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh tycoon)}) (is (= credits (:credit (get-corp))) "Corp doesn't gain credits until encounter is over") (core/continue state :corp nil) (is (= (+ credits 2) (:credit (get-corp))) "Corp gains 2 credits from Tycoon being used"))))) (deftest unity ;; Unity (testing "Basic test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Afshar"] :credits 20} :runner {:deck ["Unity"] :credits 20}}) (play-from-hand state :corp "PI:NAME:<NAME>END_PI" "R&D") (rez state :corp (get-ice state :rd 0)) (take-credits state :corp) (play-from-hand state :runner "Unity") (let [unity (get-program state 0) ice (get-ice state :rd 0)] (run-on state :rd) (run-continue state) (is (= 17 (:credit (get-runner))) "17 credits before breaking") (card-ability state :runner unity 1) ;;temp boost because EDN file (card-ability state :runner unity 0) (click-prompt state :runner "Make the Runner lose 2 [Credits]") (card-ability state :runner unity 0) (click-prompt state :runner "End the run") (is (= 14 (:credit (get-runner))) "14 credits after breaking") (is (zero? (count (remove :broken (:subroutines (refresh ice))))) "All subroutines have been broken")))) (testing "Boost test" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["DNA Tracker"] :credits 20} :runner {:deck [(qty "Unity" 3)] :credits 20}}) (play-from-hand state :corp "DNA Tracker" "HQ") (rez state :corp (get-ice state :hq 0)) (take-credits state :corp) (play-from-hand state :runner "Unity") (play-from-hand state :runner "Unity") (play-from-hand state :runner "Unity") (let [unity (get-program state 0) ice (get-ice state :hq 0)] (run-on state :hq) (run-continue state) (is (= 11 (:credit (get-runner))) "11 credits before breaking") (card-ability state :runner unity 1) (card-ability state :runner unity 1) (card-ability state :runner unity 0) (click-prompt state :runner "Do 1 net damage and make the Runner lose 2 [Credits]") (card-ability state :runner unity 0) (click-prompt state :runner "Do 1 net damage and make the Runner lose 2 [Credits]") (card-ability state :runner unity 0) (click-prompt state :runner "Do 1 net damage and make the Runner lose 2 [Credits]") (is (= 6 (:credit (get-runner))) "6 credits after breaking") (is (zero? (count (remove :broken (:subroutines (refresh ice))))) "All subroutines have been broken"))))) (deftest upya (do-game (new-game {:runner {:deck ["Upya"]}}) (take-credits state :corp) (play-from-hand state :runner "Upya") (dotimes [_ 3] (run-empty-server state "R&D")) (is (= 3 (get-counters (get-program state 0) :power)) "3 counters on Upya") (take-credits state :corp) (dotimes [_ 3] (run-empty-server state "R&D")) (is (= 6 (get-counters (get-program state 0) :power)) "6 counters on Upya") (let [upya (get-program state 0)] (card-ability state :runner upya 0) (is (= 3 (get-counters (refresh upya) :power)) "3 counters spent") (is (= 2 (:click (get-runner))) "Gained 2 clicks") (card-ability state :runner upya 0) (is (= 3 (get-counters (refresh upya) :power)) "Upya not used more than once a turn") (is (= 2 (:click (get-runner))) "Still at 2 clicks")) (take-credits state :runner) (take-credits state :corp) (let [upya (get-program state 0)] (card-ability state :runner upya 0) (is (zero? (get-counters (refresh upya) :power)) "3 counters spent") (is (= 5 (:click (get-runner))) "Gained 2 clicks")))) (deftest utae ;; Utae (do-game (new-game {:corp {:deck ["Enigma"]} :runner {:deck ["Utae" (qty "Logic Bomb" 3)] :credits 10}}) (play-from-hand state :corp "Enigma" "HQ") (take-credits state :corp) (play-from-hand state :runner "Utae") (let [utae (get-program state 0)] (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (let [credits (:credit (get-runner))] (card-ability state :runner utae 2) (is (= (dec credits) (:credit (get-runner))) "Spent 1 credit")) (let [credits (:credit (get-runner))] (card-ability state :runner utae 0) (click-prompt state :runner "2") (click-prompt state :runner "Force the Runner to lose 1 [Click]") (click-prompt state :runner "End the run") (is (= (- credits 2) (:credit (get-runner))) "Spent 2 credits")) (let [credits (:credit (get-runner))] (card-ability state :runner utae 0) (is (empty? (:prompt (get-runner))) "Can only use ability once per run") (card-ability state :runner utae 1) (is (= credits (:credit (get-runner))) "Cannot use this ability without 3 installed virtual resources")) (run-jack-out state) (core/gain state :runner :click 2) (dotimes [_ 3] (play-from-hand state :runner "Logic Bomb")) (run-on state "HQ") (run-continue state) (card-ability state :runner utae 2) (let [credits (:credit (get-runner))] (card-ability state :runner utae 1) (click-prompt state :runner "End the run") (click-prompt state :runner "Done") (is (= (dec credits) (:credit (get-runner))))) (is (= 3 (:credit (get-runner))) "Able to use ability now")))) (deftest vamadeva ;; Vamadeva (testing "Swap ability" (testing "Doesnt work if no Deva in hand" (do-game (new-game {:runner {:hand ["Vamadeva" "Corroder"] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "VPI:NAME:<NAME>END_PI") (card-ability state :runner (get-program state 0) 2) (is (empty? (:prompt (get-runner))) "No select prompt as there's no Deva in hand"))) (testing "Works with another deva in hand" (doseq [deva ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]] (do-game (new-game {:runner {:hand ["Vamadeva" deva] :credits 10}}) (take-credits state :corp) (play-from-hand state :runner "Vamadeva") (let [installed-deva (get-program state 0)] (card-ability state :runner installed-deva 2) (click-card state :runner (first (:hand (get-runner)))) (is (not (utils/same-card? installed-deva (get-program state 0))) "Installed deva is not same as previous deva") (is (= deva (:title (get-program state 0))))))))) (testing "Break ability targets ice with 1 subroutine" (do-game (new-game {:corp {:deck [(qty "Hedge Fund" 5)] :hand ["Enigma" "Ice Wall"] :credits 10} :runner {:hand ["Vamadeva"] :credits 10}}) (play-from-hand state :corp "Enigma" "HQ") (play-from-hand state :corp "Ice Wall" "R&D") (take-credits state :corp) (play-from-hand state :runner "Vamadeva") (run-on state "HQ") (rez state :corp (get-ice state :hq 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (empty? (:prompt (get-runner))) "No break prompt") (run-jack-out state) (run-on state "R&D") (rez state :corp (get-ice state :rd 0)) (run-continue state) (card-ability state :runner (get-program state 0) 0) (is (seq (:prompt (get-runner))) "Have a break prompt") (click-prompt state :runner "End the run") (is (:broken (first (:subroutines (get-ice state :rd 0)))) "The break ability worked")))) (deftest wari (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["PI:NAME:<NAME>END_PIari"]}}) (play-from-hand state :corp "Ice Wall" "R&D") (take-credits state :corp) (play-from-hand state :runner "PI:NAME:<NAME>END_PIari") (run-empty-server state "HQ") (click-prompt state :runner "Yes") (click-prompt state :runner "Barrier") (click-card state :runner (get-ice state :rd 0)) (is (= 1 (count (:discard (get-runner)))) "Wari in heap") (is (seq (:prompt (get-runner))) "Runner is currently accessing Ice Wall"))) (deftest wyrm ;; Wyrm reduces strength of ice (do-game (new-game {:corp {:deck ["Ice Wall"]} :runner {:deck ["Wyrm"]}}) (play-from-hand state :corp "Ice Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Wyrm") (run-on state "HQ") (let [ice-wall (get-ice state :hq 0) wyrm (get-program state 0)] (rez state :corp ice-wall) (run-continue state) (card-ability state :runner wyrm 1) (is (zero? (get-strength (refresh ice-wall))) "Strength of Ice Wall reduced to 0") (card-ability state :runner wyrm 1) (is (= -1 (get-strength (refresh ice-wall))) "Strength of Ice Wall reduced to -1")))) (deftest yusuf ;; Yusuf gains virus counters on successful runs and can spend virus counters from any installed card (testing "Yusuf basic tests" (do-game (new-game {:corp {:deck ["Fire Wall"]} :runner {:deck ["Yusuf" "Cache"]}}) (play-from-hand state :corp "Fire Wall" "HQ") (take-credits state :corp) (play-from-hand state :runner "Yusuf") (play-from-hand state :runner "Cache") (let [fire-wall (get-ice state :hq 0) yusuf (get-program state 0) cache (get-program state 1)] (run-empty-server state "Archives") (is (= 1 (get-counters (refresh yusuf) :virus)) "Yusuf has 1 virus counter") (is (= 3 (get-strength (refresh yusuf))) "Initial Yusuf strength") (is (= 3 (get-counters (refresh cache) :virus)) "Initial Cache virus counters") (run-on state "HQ") (rez state :corp fire-wall) (run-continue state) (card-ability state :runner yusuf 1) (click-card state :runner cache) (card-ability state :runner yusuf 1) (click-card state :runner yusuf) (is (= 2 (get-counters (refresh cache) :virus)) "Cache lost 1 virus counter to pump") (is (= 5 (get-strength (refresh yusuf))) "Yusuf strength 5") (is (zero? (get-counters (refresh yusuf) :virus)) "Yusuf lost 1 virus counter to pump") (is (empty? (:prompt (get-runner))) "No prompt open") (card-ability state :runner yusuf 0) (click-prompt state :runner "End the run") (click-card state :runner cache) (is (= 1 (get-counters (refresh cache) :virus)) "Cache lost its final virus counter")))))
[ { "context": "ent.))\n;;=> #'clojure-scala.core/s\n\n(.name_$eq s \"Nico\")\n;;=> nil\n\n(.name s)\n;;=> \"Nico\"\n\n(def p (Person", "end": 746, "score": 0.9105836749076843, "start": 742, "tag": "NAME", "value": "Nico" }, { "context": "s\n\n(.name_$eq s \"Nico\")\n;;=> nil\n\n(.name s)\n;;=> \"Nico\"\n\n(def p (Person.))\n;;=> #'clojure-scala.core/per", "end": 779, "score": 0.9694544076919556, "start": 775, "tag": "NAME", "value": "Nico" }, { "context": "))\n;;=> #'clojure-scala.core/person\n\n(.setName p \"Makoto\")\n;;=> nil\n\n(.getName p)\n;;=> \"Makoto\"\n\n(.address", "end": 853, "score": 0.7432467937469482, "start": 847, "tag": "NAME", "value": "Makoto" } ]
Chapter 05 Code/clojure-scala/src/clojure_scala/core.clj
PacktPublishing/Clojure-Programming-Cookbook
14
(ns clojure-scala.core) ;;=> nil (import 'chapter05.Calculation) ;;=> chapter05.Calculation (.add calc 10 2) ;;=> 12 (import 'scala.math.BigInt) ;;=> scala.math.BigInt (import 'java.math.BigInteger) ;;=> java.math.BigInteger (.factorial calc (BigInt. (BigInteger. "25"))) ;;=> 15511210043330985984000000 (import 'chapter05.Main) ;;=> chapter05.Main (Main/hello "Makoto") ;;=> "hello from Scala: Makoto !" (import 'chapter05.MyTuple) ;;=> chapter05.MyTuple (def tuple1 (.tuple (MyTuple.) 1 5)) ;;=> #'clojure-scala.core/tuple1 (._1 tuple1) ;;=> 1 (._2 tuple1) ;;=> 5 (import 'chapter05.Person) ;;=> chapter05.Person (import 'chapter05.Student) ;;=> chapter05.Student (def s (Student.)) ;;=> #'clojure-scala.core/s (.name_$eq s "Nico") ;;=> nil (.name s) ;;=> "Nico" (def p (Person.)) ;;=> #'clojure-scala.core/person (.setName p "Makoto") ;;=> nil (.getName p) ;;=> "Makoto" (.address_$eq p "Japan") ;;=> nil (.address p) ;;=> "Japan"
88190
(ns clojure-scala.core) ;;=> nil (import 'chapter05.Calculation) ;;=> chapter05.Calculation (.add calc 10 2) ;;=> 12 (import 'scala.math.BigInt) ;;=> scala.math.BigInt (import 'java.math.BigInteger) ;;=> java.math.BigInteger (.factorial calc (BigInt. (BigInteger. "25"))) ;;=> 15511210043330985984000000 (import 'chapter05.Main) ;;=> chapter05.Main (Main/hello "Makoto") ;;=> "hello from Scala: Makoto !" (import 'chapter05.MyTuple) ;;=> chapter05.MyTuple (def tuple1 (.tuple (MyTuple.) 1 5)) ;;=> #'clojure-scala.core/tuple1 (._1 tuple1) ;;=> 1 (._2 tuple1) ;;=> 5 (import 'chapter05.Person) ;;=> chapter05.Person (import 'chapter05.Student) ;;=> chapter05.Student (def s (Student.)) ;;=> #'clojure-scala.core/s (.name_$eq s "<NAME>") ;;=> nil (.name s) ;;=> "<NAME>" (def p (Person.)) ;;=> #'clojure-scala.core/person (.setName p "<NAME>") ;;=> nil (.getName p) ;;=> "Makoto" (.address_$eq p "Japan") ;;=> nil (.address p) ;;=> "Japan"
true
(ns clojure-scala.core) ;;=> nil (import 'chapter05.Calculation) ;;=> chapter05.Calculation (.add calc 10 2) ;;=> 12 (import 'scala.math.BigInt) ;;=> scala.math.BigInt (import 'java.math.BigInteger) ;;=> java.math.BigInteger (.factorial calc (BigInt. (BigInteger. "25"))) ;;=> 15511210043330985984000000 (import 'chapter05.Main) ;;=> chapter05.Main (Main/hello "Makoto") ;;=> "hello from Scala: Makoto !" (import 'chapter05.MyTuple) ;;=> chapter05.MyTuple (def tuple1 (.tuple (MyTuple.) 1 5)) ;;=> #'clojure-scala.core/tuple1 (._1 tuple1) ;;=> 1 (._2 tuple1) ;;=> 5 (import 'chapter05.Person) ;;=> chapter05.Person (import 'chapter05.Student) ;;=> chapter05.Student (def s (Student.)) ;;=> #'clojure-scala.core/s (.name_$eq s "PI:NAME:<NAME>END_PI") ;;=> nil (.name s) ;;=> "PI:NAME:<NAME>END_PI" (def p (Person.)) ;;=> #'clojure-scala.core/person (.setName p "PI:NAME:<NAME>END_PI") ;;=> nil (.getName p) ;;=> "Makoto" (.address_$eq p "Japan") ;;=> nil (.address p) ;;=> "Japan"
[ { "context": "loop [response (async/<! (requester {\"screen_name\" user \"count\" 200}))]\n (if (> (count response) 0)\n", "end": 4311, "score": 0.8559616208076477, "start": 4307, "tag": "NAME", "value": "user" }, { "context": " (recur (async/<! (requester {\"screen_name\" user \"count\" 200 \"max_id\" (dec lowest-id)}))))\n ", "end": 4667, "score": 0.4041461646556854, "start": 4663, "tag": "NAME", "value": "user" } ]
src/clj/com/beardandcode/twitter_news/api.clj
beardandcode/twitter-news
0
(ns com.beardandcode.twitter-news.api (:import [org.apache.http.client HttpClient] [org.apache.http.client.methods HttpGet] [org.apache.http.impl.client HttpClients] [org.apache.http.util EntityUtils] [com.twitter.hbc.httpclient.auth OAuth1]) (:require [clojure.core.async :as async] [clojure.tools.logging :as log] [cheshire.core :as json] [com.stuartsierra.component :as component] [metrics.core :refer [new-registry]] [metrics.meters :refer [mark! meter]] [metrics.timers :refer [timer] :as timers] [throttler.core :refer [throttle-chan]] [com.beardandcode.twitter-news.stats :as stats])) (defn make-auth [consumer-key consumer-secret token secret] (OAuth1. consumer-key consumer-secret token secret)) (defn- get-request [base path] (fn [auth parameters] (let [url (format "%s%s?%s" base path (->> parameters (map (fn [[k v]] (str k "=" v))) (clojure.string/join "&"))) request (HttpGet. url)] (.signRequest auth request nil) request))) ;; from the twitter api documentation (def all-statuses [200 304 400 401 403 404 406 410 420 422 429 500 502 503 504]) (defn- execute->json [request status-meters] (async/go (log/infof "Requesting from %s" (.toString request)) (let [response (.execute (HttpClients/createDefault) request) status-code (.getStatusCode (.getStatusLine response)) body-string (EntityUtils/toString (.getEntity response) "UTF-8")] (.close response) (if-let [meter (status-meters status-code)] (mark! meter)) (cond (= status-code 200) (json/parse-string body-string) (= status-code 429) (let [limit-cleared-ms (-> response (.getHeaders "X-Rate-Limit-Reset") first (.getValue) Long/parseLong (* 1000)) until-cleared-ms (- limit-cleared-ms (System/currentTimeMillis))] (log/infof "Rate was limited, clearing at %d so we are waiting for %dms" limit-cleared-ms until-cleared-ms) (if (> until-cleared-ms 0) (async/<! (async/timeout until-cleared-ms))) (async/<! (execute->json request status-meters))) (> status-code 500) (do (async/<! (async/timeout 1000)) (async/<! (execute->json request status-meters))) :else (log/warnf "Response returned %d: %s" status-code body-string))))) (defn- dispatch-requests [request-chan request-fn auth name metrics-registry] (let [control-chan (async/chan) request-rate (meter metrics-registry (str name ".rate")) response-timer (timer metrics-registry (str name ".response-time")) status-meters (reduce #(assoc %1 %2 (meter metrics-registry (str name ".status." %2))) {} all-statuses)] (log/infof "Dispatch[%s] starting" name) (async/go-loop [] (let [[v ch] (async/alts! [request-chan control-chan])] (if (= ch request-chan) (let [{:keys [params out-chan]} v timing (timers/start response-timer) response (async/<! (execute->json (request-fn auth params) status-meters))] (timers/stop timing) (async/>! out-chan response) (async/close! out-chan) (mark! request-rate) (recur)) (log/infof "Dispatch[%s] stopping" name)))) control-chan)) (defn- throttled-requester [name metrics-registry auth request-fn num per-period] (let [request-chan (async/chan (stats/buffer (str name ".waiting") 100 metrics-registry)) throttled-chan (throttle-chan request-chan num per-period) control-chan (dispatch-requests throttled-chan request-fn auth name metrics-registry)] (fn ([] (async/>!! control-chan :kill)) ([params] (let [out-chan (async/chan)] (async/go (async/>! request-chan {:params params :out-chan out-chan})) out-chan))))) (defn- all-tweets-from [requester user] (let [out-chan (async/chan)] (async/go-loop [response (async/<! (requester {"screen_name" user "count" 200}))] (if (> (count response) 0) (let [lowest-id (->> response (map #(get % "id_str")) (map #(Long/parseLong %)) sort first)] (doseq [tweet response] (async/>! out-chan tweet)) (recur (async/<! (requester {"screen_name" user "count" 200 "max_id" (dec lowest-id)})))) (async/close! out-chan))) out-chan)) (defprotocol TwitterClient (tweets [_ user] "Returns a stream of a users tweets") (favourites [_ user] "Returns a stream of a users favourites")) (defrecord HttpTwitterClient [base-url auth metrics-registry tweets-requester favourites-requester] component/Lifecycle (start [client] (if tweets-requester client (let [metrics-registry (new-registry)] (assoc client :metrics-registry metrics-registry :tweets-requester (throttled-requester "tweets" metrics-registry auth (get-request base-url "/statuses/user_timeline.json") 12 :minute) :favourites-requester (throttled-requester "favourites" metrics-registry auth (get-request base-url "/favorites/list.json") 1 :minute))))) (stop [client] (if (not tweets-requester) client (do (tweets-requester) (favourites-requester) (dissoc client :metrics-registry :tweets-requester :favourites-requester)))) TwitterClient (tweets [_ user] (all-tweets-from tweets-requester user)) (favourites [_ user] (all-tweets-from favourites-requester user)) stats/StatsProvider (stats [_] (stats/from-registry metrics-registry))) (defn new-client [auth] (map->HttpTwitterClient {:base-url "https://api.twitter.com/1.1" :auth auth}))
81934
(ns com.beardandcode.twitter-news.api (:import [org.apache.http.client HttpClient] [org.apache.http.client.methods HttpGet] [org.apache.http.impl.client HttpClients] [org.apache.http.util EntityUtils] [com.twitter.hbc.httpclient.auth OAuth1]) (:require [clojure.core.async :as async] [clojure.tools.logging :as log] [cheshire.core :as json] [com.stuartsierra.component :as component] [metrics.core :refer [new-registry]] [metrics.meters :refer [mark! meter]] [metrics.timers :refer [timer] :as timers] [throttler.core :refer [throttle-chan]] [com.beardandcode.twitter-news.stats :as stats])) (defn make-auth [consumer-key consumer-secret token secret] (OAuth1. consumer-key consumer-secret token secret)) (defn- get-request [base path] (fn [auth parameters] (let [url (format "%s%s?%s" base path (->> parameters (map (fn [[k v]] (str k "=" v))) (clojure.string/join "&"))) request (HttpGet. url)] (.signRequest auth request nil) request))) ;; from the twitter api documentation (def all-statuses [200 304 400 401 403 404 406 410 420 422 429 500 502 503 504]) (defn- execute->json [request status-meters] (async/go (log/infof "Requesting from %s" (.toString request)) (let [response (.execute (HttpClients/createDefault) request) status-code (.getStatusCode (.getStatusLine response)) body-string (EntityUtils/toString (.getEntity response) "UTF-8")] (.close response) (if-let [meter (status-meters status-code)] (mark! meter)) (cond (= status-code 200) (json/parse-string body-string) (= status-code 429) (let [limit-cleared-ms (-> response (.getHeaders "X-Rate-Limit-Reset") first (.getValue) Long/parseLong (* 1000)) until-cleared-ms (- limit-cleared-ms (System/currentTimeMillis))] (log/infof "Rate was limited, clearing at %d so we are waiting for %dms" limit-cleared-ms until-cleared-ms) (if (> until-cleared-ms 0) (async/<! (async/timeout until-cleared-ms))) (async/<! (execute->json request status-meters))) (> status-code 500) (do (async/<! (async/timeout 1000)) (async/<! (execute->json request status-meters))) :else (log/warnf "Response returned %d: %s" status-code body-string))))) (defn- dispatch-requests [request-chan request-fn auth name metrics-registry] (let [control-chan (async/chan) request-rate (meter metrics-registry (str name ".rate")) response-timer (timer metrics-registry (str name ".response-time")) status-meters (reduce #(assoc %1 %2 (meter metrics-registry (str name ".status." %2))) {} all-statuses)] (log/infof "Dispatch[%s] starting" name) (async/go-loop [] (let [[v ch] (async/alts! [request-chan control-chan])] (if (= ch request-chan) (let [{:keys [params out-chan]} v timing (timers/start response-timer) response (async/<! (execute->json (request-fn auth params) status-meters))] (timers/stop timing) (async/>! out-chan response) (async/close! out-chan) (mark! request-rate) (recur)) (log/infof "Dispatch[%s] stopping" name)))) control-chan)) (defn- throttled-requester [name metrics-registry auth request-fn num per-period] (let [request-chan (async/chan (stats/buffer (str name ".waiting") 100 metrics-registry)) throttled-chan (throttle-chan request-chan num per-period) control-chan (dispatch-requests throttled-chan request-fn auth name metrics-registry)] (fn ([] (async/>!! control-chan :kill)) ([params] (let [out-chan (async/chan)] (async/go (async/>! request-chan {:params params :out-chan out-chan})) out-chan))))) (defn- all-tweets-from [requester user] (let [out-chan (async/chan)] (async/go-loop [response (async/<! (requester {"screen_name" <NAME> "count" 200}))] (if (> (count response) 0) (let [lowest-id (->> response (map #(get % "id_str")) (map #(Long/parseLong %)) sort first)] (doseq [tweet response] (async/>! out-chan tweet)) (recur (async/<! (requester {"screen_name" <NAME> "count" 200 "max_id" (dec lowest-id)})))) (async/close! out-chan))) out-chan)) (defprotocol TwitterClient (tweets [_ user] "Returns a stream of a users tweets") (favourites [_ user] "Returns a stream of a users favourites")) (defrecord HttpTwitterClient [base-url auth metrics-registry tweets-requester favourites-requester] component/Lifecycle (start [client] (if tweets-requester client (let [metrics-registry (new-registry)] (assoc client :metrics-registry metrics-registry :tweets-requester (throttled-requester "tweets" metrics-registry auth (get-request base-url "/statuses/user_timeline.json") 12 :minute) :favourites-requester (throttled-requester "favourites" metrics-registry auth (get-request base-url "/favorites/list.json") 1 :minute))))) (stop [client] (if (not tweets-requester) client (do (tweets-requester) (favourites-requester) (dissoc client :metrics-registry :tweets-requester :favourites-requester)))) TwitterClient (tweets [_ user] (all-tweets-from tweets-requester user)) (favourites [_ user] (all-tweets-from favourites-requester user)) stats/StatsProvider (stats [_] (stats/from-registry metrics-registry))) (defn new-client [auth] (map->HttpTwitterClient {:base-url "https://api.twitter.com/1.1" :auth auth}))
true
(ns com.beardandcode.twitter-news.api (:import [org.apache.http.client HttpClient] [org.apache.http.client.methods HttpGet] [org.apache.http.impl.client HttpClients] [org.apache.http.util EntityUtils] [com.twitter.hbc.httpclient.auth OAuth1]) (:require [clojure.core.async :as async] [clojure.tools.logging :as log] [cheshire.core :as json] [com.stuartsierra.component :as component] [metrics.core :refer [new-registry]] [metrics.meters :refer [mark! meter]] [metrics.timers :refer [timer] :as timers] [throttler.core :refer [throttle-chan]] [com.beardandcode.twitter-news.stats :as stats])) (defn make-auth [consumer-key consumer-secret token secret] (OAuth1. consumer-key consumer-secret token secret)) (defn- get-request [base path] (fn [auth parameters] (let [url (format "%s%s?%s" base path (->> parameters (map (fn [[k v]] (str k "=" v))) (clojure.string/join "&"))) request (HttpGet. url)] (.signRequest auth request nil) request))) ;; from the twitter api documentation (def all-statuses [200 304 400 401 403 404 406 410 420 422 429 500 502 503 504]) (defn- execute->json [request status-meters] (async/go (log/infof "Requesting from %s" (.toString request)) (let [response (.execute (HttpClients/createDefault) request) status-code (.getStatusCode (.getStatusLine response)) body-string (EntityUtils/toString (.getEntity response) "UTF-8")] (.close response) (if-let [meter (status-meters status-code)] (mark! meter)) (cond (= status-code 200) (json/parse-string body-string) (= status-code 429) (let [limit-cleared-ms (-> response (.getHeaders "X-Rate-Limit-Reset") first (.getValue) Long/parseLong (* 1000)) until-cleared-ms (- limit-cleared-ms (System/currentTimeMillis))] (log/infof "Rate was limited, clearing at %d so we are waiting for %dms" limit-cleared-ms until-cleared-ms) (if (> until-cleared-ms 0) (async/<! (async/timeout until-cleared-ms))) (async/<! (execute->json request status-meters))) (> status-code 500) (do (async/<! (async/timeout 1000)) (async/<! (execute->json request status-meters))) :else (log/warnf "Response returned %d: %s" status-code body-string))))) (defn- dispatch-requests [request-chan request-fn auth name metrics-registry] (let [control-chan (async/chan) request-rate (meter metrics-registry (str name ".rate")) response-timer (timer metrics-registry (str name ".response-time")) status-meters (reduce #(assoc %1 %2 (meter metrics-registry (str name ".status." %2))) {} all-statuses)] (log/infof "Dispatch[%s] starting" name) (async/go-loop [] (let [[v ch] (async/alts! [request-chan control-chan])] (if (= ch request-chan) (let [{:keys [params out-chan]} v timing (timers/start response-timer) response (async/<! (execute->json (request-fn auth params) status-meters))] (timers/stop timing) (async/>! out-chan response) (async/close! out-chan) (mark! request-rate) (recur)) (log/infof "Dispatch[%s] stopping" name)))) control-chan)) (defn- throttled-requester [name metrics-registry auth request-fn num per-period] (let [request-chan (async/chan (stats/buffer (str name ".waiting") 100 metrics-registry)) throttled-chan (throttle-chan request-chan num per-period) control-chan (dispatch-requests throttled-chan request-fn auth name metrics-registry)] (fn ([] (async/>!! control-chan :kill)) ([params] (let [out-chan (async/chan)] (async/go (async/>! request-chan {:params params :out-chan out-chan})) out-chan))))) (defn- all-tweets-from [requester user] (let [out-chan (async/chan)] (async/go-loop [response (async/<! (requester {"screen_name" PI:NAME:<NAME>END_PI "count" 200}))] (if (> (count response) 0) (let [lowest-id (->> response (map #(get % "id_str")) (map #(Long/parseLong %)) sort first)] (doseq [tweet response] (async/>! out-chan tweet)) (recur (async/<! (requester {"screen_name" PI:NAME:<NAME>END_PI "count" 200 "max_id" (dec lowest-id)})))) (async/close! out-chan))) out-chan)) (defprotocol TwitterClient (tweets [_ user] "Returns a stream of a users tweets") (favourites [_ user] "Returns a stream of a users favourites")) (defrecord HttpTwitterClient [base-url auth metrics-registry tweets-requester favourites-requester] component/Lifecycle (start [client] (if tweets-requester client (let [metrics-registry (new-registry)] (assoc client :metrics-registry metrics-registry :tweets-requester (throttled-requester "tweets" metrics-registry auth (get-request base-url "/statuses/user_timeline.json") 12 :minute) :favourites-requester (throttled-requester "favourites" metrics-registry auth (get-request base-url "/favorites/list.json") 1 :minute))))) (stop [client] (if (not tweets-requester) client (do (tweets-requester) (favourites-requester) (dissoc client :metrics-registry :tweets-requester :favourites-requester)))) TwitterClient (tweets [_ user] (all-tweets-from tweets-requester user)) (favourites [_ user] (all-tweets-from favourites-requester user)) stats/StatsProvider (stats [_] (stats/from-registry metrics-registry))) (defn new-client [auth] (map->HttpTwitterClient {:base-url "https://api.twitter.com/1.1" :auth auth}))
[ { "context": "RAM usage for various containers.\"\n {:author \"palisades dot lakes at gmail dot com\"\n :version \"2021-01-29\"}\n \n (:require [clojur", "end": 279, "score": 0.6762719750404358, "start": 246, "tag": "EMAIL", "value": "isades dot lakes at gmail dot com" } ]
src/scripts/clojure/palisades/lakes/collex/scripts/sizeof.clj
palisades-lakes/collection-experiments
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.collex.scripts.sizeof "Estimate RAM usage for various containers." {:author "palisades dot lakes at gmail dot com" :version "2021-01-29"} (:require [clojure.string :as s] [palisades.lakes.bench.core :as bench] [palisades.lakes.collex.containers :as containers] [palisades.lakes.collex.scripts.defs :as defs]) (:import [com.carrotsearch.sizeof RamUsageEstimator])) ;; clj src\scripts\clojure\palisades\lakes\collex\scripts\sizeof.clj > sizeof.csv ;;---------------------------------------------------------------- (println "container,type,length,size,per-element") (let [general [containers/array-list containers/immutable-list containers/persistent-vector containers/persistent-list containers/lazy-sequence containers/realized] nn (take 5 (iterate (partial * 4) (* 8 8 8 8 8)))] (doseq [container (concat [containers/array-of-float containers/array-of-boxed-float] general)] (doseq [^long n nn] (let [fname (bench/fn-name container) data (container defs/ufloat n) sizeof (RamUsageEstimator/sizeOf data) dname (.getCanonicalName (class data))] (println (s/join "," [fname dname n sizeof (float (/ sizeof n))]))))) (doseq [container (concat [containers/array-of-int containers/array-of-boxed-int] general)] (doseq [^long n nn] (let [fname (bench/fn-name container) data (container defs/uint n) sizeof (RamUsageEstimator/sizeOf data) dname (.getCanonicalName (class data))] (println (s/join "," [fname dname n sizeof (float (/ sizeof n))])))))) ;;----------------------------------------------------------------
50294
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.collex.scripts.sizeof "Estimate RAM usage for various containers." {:author "pal<EMAIL>" :version "2021-01-29"} (:require [clojure.string :as s] [palisades.lakes.bench.core :as bench] [palisades.lakes.collex.containers :as containers] [palisades.lakes.collex.scripts.defs :as defs]) (:import [com.carrotsearch.sizeof RamUsageEstimator])) ;; clj src\scripts\clojure\palisades\lakes\collex\scripts\sizeof.clj > sizeof.csv ;;---------------------------------------------------------------- (println "container,type,length,size,per-element") (let [general [containers/array-list containers/immutable-list containers/persistent-vector containers/persistent-list containers/lazy-sequence containers/realized] nn (take 5 (iterate (partial * 4) (* 8 8 8 8 8)))] (doseq [container (concat [containers/array-of-float containers/array-of-boxed-float] general)] (doseq [^long n nn] (let [fname (bench/fn-name container) data (container defs/ufloat n) sizeof (RamUsageEstimator/sizeOf data) dname (.getCanonicalName (class data))] (println (s/join "," [fname dname n sizeof (float (/ sizeof n))]))))) (doseq [container (concat [containers/array-of-int containers/array-of-boxed-int] general)] (doseq [^long n nn] (let [fname (bench/fn-name container) data (container defs/uint n) sizeof (RamUsageEstimator/sizeOf data) dname (.getCanonicalName (class data))] (println (s/join "," [fname dname n sizeof (float (/ sizeof n))])))))) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.collex.scripts.sizeof "Estimate RAM usage for various containers." {:author "palPI:EMAIL:<EMAIL>END_PI" :version "2021-01-29"} (:require [clojure.string :as s] [palisades.lakes.bench.core :as bench] [palisades.lakes.collex.containers :as containers] [palisades.lakes.collex.scripts.defs :as defs]) (:import [com.carrotsearch.sizeof RamUsageEstimator])) ;; clj src\scripts\clojure\palisades\lakes\collex\scripts\sizeof.clj > sizeof.csv ;;---------------------------------------------------------------- (println "container,type,length,size,per-element") (let [general [containers/array-list containers/immutable-list containers/persistent-vector containers/persistent-list containers/lazy-sequence containers/realized] nn (take 5 (iterate (partial * 4) (* 8 8 8 8 8)))] (doseq [container (concat [containers/array-of-float containers/array-of-boxed-float] general)] (doseq [^long n nn] (let [fname (bench/fn-name container) data (container defs/ufloat n) sizeof (RamUsageEstimator/sizeOf data) dname (.getCanonicalName (class data))] (println (s/join "," [fname dname n sizeof (float (/ sizeof n))]))))) (doseq [container (concat [containers/array-of-int containers/array-of-boxed-int] general)] (doseq [^long n nn] (let [fname (bench/fn-name container) data (container defs/uint n) sizeof (RamUsageEstimator/sizeOf data) dname (.getCanonicalName (class data))] (println (s/join "," [fname dname n sizeof (float (/ sizeof n))])))))) ;;----------------------------------------------------------------
[ { "context": "\"Elapsed time: 2867.337816 msecs\"\n[23\n (\"machamp\"\n \"pinsir\"\n \"relicanth\"\n \"heatmor\"\n \"registee", "end": 48, "score": 0.786510705947876, "start": 41, "tag": "NAME", "value": "machamp" }, { "context": "apsed time: 2867.337816 msecs\"\n[23\n (\"machamp\"\n \"pinsir\"\n \"relicanth\"\n \"heatmor\"\n \"registeel\"\n \"lando", "end": 59, "score": 0.9103392958641052, "start": 53, "tag": "NAME", "value": "pinsir" }, { "context": " 2867.337816 msecs\"\n[23\n (\"machamp\"\n \"pinsir\"\n \"relicanth\"\n \"heatmor\"\n \"registeel\"\n \"landorus\"\n \"seakin", "end": 73, "score": 0.8413812518119812, "start": 64, "tag": "NAME", "value": "relicanth" }, { "context": "mor\"\n \"registeel\"\n \"landorus\"\n \"seaking\"\n \"girafarig\"\n \"gabite\"\n \"exeggcute\"\n \"emboar\"\n \"rufflet\"\n", "end": 138, "score": 0.7766897082328796, "start": 132, "tag": "NAME", "value": "afarig" }, { "context": "eel\"\n \"landorus\"\n \"seaking\"\n \"girafarig\"\n \"gabite\"\n \"exeggcute\"\n \"emboar\"\n \"rufflet\"\n \"trapinch", "end": 149, "score": 0.7852965593338013, "start": 146, "tag": "NAME", "value": "ite" }, { "context": "orus\"\n \"seaking\"\n \"girafarig\"\n \"gabite\"\n \"exeggcute\"\n \"emboar\"\n \"rufflet\"\n \"trapinch\"\n \"haxoru", "end": 160, "score": 0.5453816652297974, "start": 158, "tag": "NAME", "value": "gc" }, { "context": "king\"\n \"girafarig\"\n \"gabite\"\n \"exeggcute\"\n \"emboar\"\n \"rufflet\"\n \"trapinch\"\n \"haxorus\"\n \"simise", "end": 172, "score": 0.5297032594680786, "start": 170, "tag": "NAME", "value": "bo" }, { "context": "rafarig\"\n \"gabite\"\n \"exeggcute\"\n \"emboar\"\n \"rufflet\"\n \"trapinch\"\n \"haxorus\"\n \"simisear\"\n \"remorai", "end": 186, "score": 0.5335533022880554, "start": 181, "tag": "NAME", "value": "fflet" }, { "context": "bite\"\n \"exeggcute\"\n \"emboar\"\n \"rufflet\"\n \"trapinch\"\n \"haxorus\"\n \"simisear\"\n \"remoraid\"\n \"darmani", "end": 199, "score": 0.6596188545227051, "start": 195, "tag": "NAME", "value": "inch" }, { "context": "xeggcute\"\n \"emboar\"\n \"rufflet\"\n \"trapinch\"\n \"haxorus\"\n \"simisear\"\n \"remoraid\"\n \"darmanitan\"\n \"nose", "end": 211, "score": 0.7310044169425964, "start": 205, "tag": "NAME", "value": "axorus" }, { "context": " \"emboar\"\n \"rufflet\"\n \"trapinch\"\n \"haxorus\"\n \"simisear\"\n \"remoraid\"\n \"darmanitan\"\n \"nosepass\"\n \"scra", "end": 224, "score": 0.7111327648162842, "start": 216, "tag": "NAME", "value": "simisear" }, { "context": "flet\"\n \"trapinch\"\n \"haxorus\"\n \"simisear\"\n \"remoraid\"\n \"darmanitan\"\n \"nosepass\"\n \"scrafty\"\n \"yamas", "end": 237, "score": 0.5597650408744812, "start": 232, "tag": "NAME", "value": "oraid" }, { "context": "rapinch\"\n \"haxorus\"\n \"simisear\"\n \"remoraid\"\n \"darmanitan\"\n \"nosepass\"\n \"scrafty\"\n \"yamask\"\n \"kricketun", "end": 252, "score": 0.8500465750694275, "start": 242, "tag": "NAME", "value": "darmanitan" }, { "context": "ass\"\n \"scrafty\"\n \"yamask\"\n \"kricketune\"\n \"emolga\"\n \"audino\")]\n", "end": 314, "score": 0.758582592010498, "start": 312, "tag": "NAME", "value": "ga" }, { "context": "rafty\"\n \"yamask\"\n \"kricketune\"\n \"emolga\"\n \"audino\")]\n", "end": 325, "score": 0.5530709028244019, "start": 322, "tag": "NAME", "value": "ino" } ]
Task/Last-letter-first-letter/Clojure/last-letter-first-letter-2.clj
LaudateCorpus1/RosettaCodeData
1
"Elapsed time: 2867.337816 msecs" [23 ("machamp" "pinsir" "relicanth" "heatmor" "registeel" "landorus" "seaking" "girafarig" "gabite" "exeggcute" "emboar" "rufflet" "trapinch" "haxorus" "simisear" "remoraid" "darmanitan" "nosepass" "scrafty" "yamask" "kricketune" "emolga" "audino")]
100712
"Elapsed time: 2867.337816 msecs" [23 ("<NAME>" "<NAME>" "<NAME>" "heatmor" "registeel" "landorus" "seaking" "gir<NAME>" "gab<NAME>" "exeg<NAME>ute" "em<NAME>ar" "ru<NAME>" "trap<NAME>" "h<NAME>" "<NAME>" "rem<NAME>" "<NAME>" "nosepass" "scrafty" "yamask" "kricketune" "emol<NAME>" "aud<NAME>")]
true
"Elapsed time: 2867.337816 msecs" [23 ("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "heatmor" "registeel" "landorus" "seaking" "girPI:NAME:<NAME>END_PI" "gabPI:NAME:<NAME>END_PI" "exegPI:NAME:<NAME>END_PIute" "emPI:NAME:<NAME>END_PIar" "ruPI:NAME:<NAME>END_PI" "trapPI:NAME:<NAME>END_PI" "hPI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "remPI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "nosepass" "scrafty" "yamask" "kricketune" "emolPI:NAME:<NAME>END_PI" "audPI:NAME:<NAME>END_PI")]
[ { "context": " (is (= 200 status))\n (is (= [{:full_name \"Ludmila\"\n :gender \"female\"\n :", "end": 2260, "score": 0.9997884035110474, "start": 2253, "tag": "NAME", "value": "Ludmila" }, { "context": "ce \"1234567890129456\"}\n {:full_name \"Vasya\"\n :gender \"male\"\n :bi", "end": 2443, "score": 0.9997910857200623, "start": 2438, "tag": "NAME", "value": "Vasya" }, { "context": "ting \"create patient\"\n (let [data {:full_name \"Vasya\"\n :gender \"male\"\n :", "end": 2698, "score": 0.9997698664665222, "start": 2693, "tag": "NAME", "value": "Vasya" }, { "context": " db-options)\n expected {:full_name \"Maria\"\n :gender \"female\"\n ", "end": 4483, "score": 0.9996378421783447, "start": 4478, "tag": "NAME", "value": "Maria" } ]
test/patients/server_test.clj
Romez/patients
0
(ns patients.server-test (:require [ring.mock.request :as mock] [clojure.data.json :as json] [clojure.test :refer [deftest is testing use-fixtures]] [patients.migration :refer [migrate]] [patients.server :refer [app]] [patients.utils :refer [unparse-date]] [environ.core :refer [env]] [next.jdbc :as jdbc] [next.jdbc.result-set :as rs] [honeysql.core :as sql])) (def db-spec {:dbtype "postgresql" :dbname "patients_test" :host (:db-host env) :port (:db-port env) :user (:db-user env) :password (:db-password env) :stringtype "unspecified"}) (def db-options {:builder-fn rs/as-unqualified-maps :return-keys true}) (def ^:dynamic *db* nil) (defn with-connection [fn] (jdbc/with-transaction [tx (jdbc/get-datasource db-spec) {:rollback-only true}] (binding [*db* tx] (fn)))) (defn fix-migrate [fn] (migrate) (fn)) (use-fixtures :once fix-migrate) (use-fixtures :each with-connection) (deftest test-app-200 (testing "check main page success" (let [{:keys [status]} ((app {:db *db*}) (mock/request :get "/"))] (is (= status 200))))) (deftest test-app-404 (is (= (:status ((app {:db *db*}) (mock/request :get "/wrong-path"))) 404))) (deftest test-patients [] (testing "get patients" (let [_ (jdbc/execute! *db* (sql/format {:insert-into :patient :columns [:full_name :gender :birthday :address :insurance] :values [["Vasya" "male" "1966-01-03" "homeless" "1234567890123456"] ["Ludmila" "female" "1986-01-05" "Moscow" "1234567890129456"]]})) {:keys [status body]} ((app {:db *db*}) (mock/request :get "/api/v1/patients?page=1&per-page=2&sort=desc")) result (->> (json/read-str body :key-fn keyword) :data (map #(:attributes %)) (map #(dissoc % :id)))] (is (= 200 status)) (is (= [{:full_name "Ludmila" :gender "female" :birthday "1986-01-05" :address "Moscow" :insurance "1234567890129456"} {:full_name "Vasya" :gender "male" :birthday "1966-01-03" :address "homeless" :insurance "1234567890123456"}] result))))) (deftest test-create-patient (testing "create patient" (let [data {:full_name "Vasya" :gender "male" :birthday "1945-11-19" :address "homeless" :insurance "1234567890123456"} {:keys [status body]} ((app {:db *db*}) (-> (mock/request :post "/api/v1/patients") (mock/json-body {:data {:attributes data}}))) {:keys [attributes]} (:data (json/read-str body :key-fn keyword))] (is (= 201 status)) (is (= data attributes))))) (deftest test-patient-delete (testing "delete patient" (let [{:keys [id]} (jdbc/execute-one! *db* (sql/format {:insert-into :patient :columns [:full_name :gender :birthday :address :insurance] :values [["Vasya" "male" "1966-01-03" "homeless" "1234567890123456"]]}) db-options) {:keys [status]} ((app {:db *db*}) (mock/request :delete (str "/api/v1/patients/" id)))] (is (= 204 status)) (is (nil? (jdbc/execute-one! *db* (sql/format {:select [:*] :from [:patient] :where [:= :id id]}) db-options)))))) (deftest test-patient-update (testing "update patient" (let [{:keys [id]} (jdbc/execute-one! *db* (sql/format {:insert-into :patient :columns [:full_name :gender :birthday :address :insurance] :values [["Vasya" "male" "1966-01-03" "homeless" "1234567890123456"]]}) db-options) expected {:full_name "Maria" :gender "female" :birthday "1996-02-04" :address "Moscow" :insurance "6543210987654321"} {:keys [status]} ((app {:db *db*}) (-> (mock/request :patch (str "/api/v1/patients/" id)) (mock/json-body {:data {:attributes expected}}))) result (-> (jdbc/execute-one! *db* (sql/format {:select [:full_name :gender :birthday :address :insurance] :from [:patient] :where [:= :id id]}) db-options) (update :birthday unparse-date))] (is (= 200 status)) (is (= result expected)))))
68487
(ns patients.server-test (:require [ring.mock.request :as mock] [clojure.data.json :as json] [clojure.test :refer [deftest is testing use-fixtures]] [patients.migration :refer [migrate]] [patients.server :refer [app]] [patients.utils :refer [unparse-date]] [environ.core :refer [env]] [next.jdbc :as jdbc] [next.jdbc.result-set :as rs] [honeysql.core :as sql])) (def db-spec {:dbtype "postgresql" :dbname "patients_test" :host (:db-host env) :port (:db-port env) :user (:db-user env) :password (:db-password env) :stringtype "unspecified"}) (def db-options {:builder-fn rs/as-unqualified-maps :return-keys true}) (def ^:dynamic *db* nil) (defn with-connection [fn] (jdbc/with-transaction [tx (jdbc/get-datasource db-spec) {:rollback-only true}] (binding [*db* tx] (fn)))) (defn fix-migrate [fn] (migrate) (fn)) (use-fixtures :once fix-migrate) (use-fixtures :each with-connection) (deftest test-app-200 (testing "check main page success" (let [{:keys [status]} ((app {:db *db*}) (mock/request :get "/"))] (is (= status 200))))) (deftest test-app-404 (is (= (:status ((app {:db *db*}) (mock/request :get "/wrong-path"))) 404))) (deftest test-patients [] (testing "get patients" (let [_ (jdbc/execute! *db* (sql/format {:insert-into :patient :columns [:full_name :gender :birthday :address :insurance] :values [["Vasya" "male" "1966-01-03" "homeless" "1234567890123456"] ["Ludmila" "female" "1986-01-05" "Moscow" "1234567890129456"]]})) {:keys [status body]} ((app {:db *db*}) (mock/request :get "/api/v1/patients?page=1&per-page=2&sort=desc")) result (->> (json/read-str body :key-fn keyword) :data (map #(:attributes %)) (map #(dissoc % :id)))] (is (= 200 status)) (is (= [{:full_name "<NAME>" :gender "female" :birthday "1986-01-05" :address "Moscow" :insurance "1234567890129456"} {:full_name "<NAME>" :gender "male" :birthday "1966-01-03" :address "homeless" :insurance "1234567890123456"}] result))))) (deftest test-create-patient (testing "create patient" (let [data {:full_name "<NAME>" :gender "male" :birthday "1945-11-19" :address "homeless" :insurance "1234567890123456"} {:keys [status body]} ((app {:db *db*}) (-> (mock/request :post "/api/v1/patients") (mock/json-body {:data {:attributes data}}))) {:keys [attributes]} (:data (json/read-str body :key-fn keyword))] (is (= 201 status)) (is (= data attributes))))) (deftest test-patient-delete (testing "delete patient" (let [{:keys [id]} (jdbc/execute-one! *db* (sql/format {:insert-into :patient :columns [:full_name :gender :birthday :address :insurance] :values [["Vasya" "male" "1966-01-03" "homeless" "1234567890123456"]]}) db-options) {:keys [status]} ((app {:db *db*}) (mock/request :delete (str "/api/v1/patients/" id)))] (is (= 204 status)) (is (nil? (jdbc/execute-one! *db* (sql/format {:select [:*] :from [:patient] :where [:= :id id]}) db-options)))))) (deftest test-patient-update (testing "update patient" (let [{:keys [id]} (jdbc/execute-one! *db* (sql/format {:insert-into :patient :columns [:full_name :gender :birthday :address :insurance] :values [["Vasya" "male" "1966-01-03" "homeless" "1234567890123456"]]}) db-options) expected {:full_name "<NAME>" :gender "female" :birthday "1996-02-04" :address "Moscow" :insurance "6543210987654321"} {:keys [status]} ((app {:db *db*}) (-> (mock/request :patch (str "/api/v1/patients/" id)) (mock/json-body {:data {:attributes expected}}))) result (-> (jdbc/execute-one! *db* (sql/format {:select [:full_name :gender :birthday :address :insurance] :from [:patient] :where [:= :id id]}) db-options) (update :birthday unparse-date))] (is (= 200 status)) (is (= result expected)))))
true
(ns patients.server-test (:require [ring.mock.request :as mock] [clojure.data.json :as json] [clojure.test :refer [deftest is testing use-fixtures]] [patients.migration :refer [migrate]] [patients.server :refer [app]] [patients.utils :refer [unparse-date]] [environ.core :refer [env]] [next.jdbc :as jdbc] [next.jdbc.result-set :as rs] [honeysql.core :as sql])) (def db-spec {:dbtype "postgresql" :dbname "patients_test" :host (:db-host env) :port (:db-port env) :user (:db-user env) :password (:db-password env) :stringtype "unspecified"}) (def db-options {:builder-fn rs/as-unqualified-maps :return-keys true}) (def ^:dynamic *db* nil) (defn with-connection [fn] (jdbc/with-transaction [tx (jdbc/get-datasource db-spec) {:rollback-only true}] (binding [*db* tx] (fn)))) (defn fix-migrate [fn] (migrate) (fn)) (use-fixtures :once fix-migrate) (use-fixtures :each with-connection) (deftest test-app-200 (testing "check main page success" (let [{:keys [status]} ((app {:db *db*}) (mock/request :get "/"))] (is (= status 200))))) (deftest test-app-404 (is (= (:status ((app {:db *db*}) (mock/request :get "/wrong-path"))) 404))) (deftest test-patients [] (testing "get patients" (let [_ (jdbc/execute! *db* (sql/format {:insert-into :patient :columns [:full_name :gender :birthday :address :insurance] :values [["Vasya" "male" "1966-01-03" "homeless" "1234567890123456"] ["Ludmila" "female" "1986-01-05" "Moscow" "1234567890129456"]]})) {:keys [status body]} ((app {:db *db*}) (mock/request :get "/api/v1/patients?page=1&per-page=2&sort=desc")) result (->> (json/read-str body :key-fn keyword) :data (map #(:attributes %)) (map #(dissoc % :id)))] (is (= 200 status)) (is (= [{:full_name "PI:NAME:<NAME>END_PI" :gender "female" :birthday "1986-01-05" :address "Moscow" :insurance "1234567890129456"} {:full_name "PI:NAME:<NAME>END_PI" :gender "male" :birthday "1966-01-03" :address "homeless" :insurance "1234567890123456"}] result))))) (deftest test-create-patient (testing "create patient" (let [data {:full_name "PI:NAME:<NAME>END_PI" :gender "male" :birthday "1945-11-19" :address "homeless" :insurance "1234567890123456"} {:keys [status body]} ((app {:db *db*}) (-> (mock/request :post "/api/v1/patients") (mock/json-body {:data {:attributes data}}))) {:keys [attributes]} (:data (json/read-str body :key-fn keyword))] (is (= 201 status)) (is (= data attributes))))) (deftest test-patient-delete (testing "delete patient" (let [{:keys [id]} (jdbc/execute-one! *db* (sql/format {:insert-into :patient :columns [:full_name :gender :birthday :address :insurance] :values [["Vasya" "male" "1966-01-03" "homeless" "1234567890123456"]]}) db-options) {:keys [status]} ((app {:db *db*}) (mock/request :delete (str "/api/v1/patients/" id)))] (is (= 204 status)) (is (nil? (jdbc/execute-one! *db* (sql/format {:select [:*] :from [:patient] :where [:= :id id]}) db-options)))))) (deftest test-patient-update (testing "update patient" (let [{:keys [id]} (jdbc/execute-one! *db* (sql/format {:insert-into :patient :columns [:full_name :gender :birthday :address :insurance] :values [["Vasya" "male" "1966-01-03" "homeless" "1234567890123456"]]}) db-options) expected {:full_name "PI:NAME:<NAME>END_PI" :gender "female" :birthday "1996-02-04" :address "Moscow" :insurance "6543210987654321"} {:keys [status]} ((app {:db *db*}) (-> (mock/request :patch (str "/api/v1/patients/" id)) (mock/json-body {:data {:attributes expected}}))) result (-> (jdbc/execute-one! *db* (sql/format {:select [:full_name :gender :birthday :address :insurance] :from [:patient] :where [:= :id id]}) db-options) (update :birthday unparse-date))] (is (= 200 status)) (is (= result expected)))))
[ { "context": "; License: BSD 2-Clause\n; Copyright (c) 2014-2015 Andrey Antukh <niwi@niwi.nz>\n; https://github.com/funcool/cuerd", "end": 63, "score": 0.999885082244873, "start": 50, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "2-Clause\n; Copyright (c) 2014-2015 Andrey Antukh <niwi@niwi.nz>\n; https://github.com/funcool/cuerdas\n;\n(ns oops.", "end": 77, "score": 0.9999321699142456, "start": 65, "tag": "EMAIL", "value": "niwi@niwi.nz" }, { "context": "Andrey Antukh <niwi@niwi.nz>\n; https://github.com/funcool/cuerdas\n;\n(ns oops.cuerdas\n \"This is our strippe", "end": 107, "score": 0.9976263046264648, "start": 100, "tag": "USERNAME", "value": "funcool" } ]
src/lib/oops/cuerdas.clj
binaryage/cljs-oops
325
; License: BSD 2-Clause ; Copyright (c) 2014-2015 Andrey Antukh <niwi@niwi.nz> ; https://github.com/funcool/cuerdas ; (ns oops.cuerdas "This is our stripped down version of the cuerdas library to avoid bringing in an extra dependency." (:refer-clojure :exclude [repeat regexp?]) (:require [clojure.string :as str]) (:import (java.util.regex Pattern))) (defn escape "Escapes characters in the string that are not safe to use in a RegExp." [s] (Pattern/quote ^String s)) (defn regexp? "Return `true` if `x` is a regexp pattern instance." [x] (instance? Pattern x)) (defn join "Joins strings together with given separator." ([coll] (apply str coll)) ([separator coll] (apply str (interpose separator coll)))) (defn repeat "Repeats string n times." ([s] (repeat s 1)) ([s n] (when (string? s) (join (clojure.core/repeat n s))))) (defn split "Splits a string on a separator a limited number of times. The separator can be a string, character or Pattern (clj) / RegExp (cljs) instance." ([s] (split s #"\s+")) ([s ^Object sep] (cond (nil? s) s (regexp? sep) (str/split s sep) (string? sep) (str/split s (re-pattern (escape sep))) (char? sep) (str/split s (re-pattern (escape (.toString sep)))) :else (throw (ex-info "Invalid arguments" {:sep sep})))) ([s ^Object sep num] (cond (nil? s) s (regexp? sep) (str/split s sep num) (string? sep) (str/split s (re-pattern (escape sep)) num) (char? sep) (str/split s (re-pattern (escape (.toString sep))) num) :else (throw (ex-info "Invalid arguments" {:sep sep}))))) (defn lines "Return a list of the lines in the string." [s] (split s #"\n|\r\n")) (defn unlines "Returns a new string joining a list of strings with a newline char (\\n)." [s] (when (sequential? s) (str/join "\n" s)))
54851
; License: BSD 2-Clause ; Copyright (c) 2014-2015 <NAME> <<EMAIL>> ; https://github.com/funcool/cuerdas ; (ns oops.cuerdas "This is our stripped down version of the cuerdas library to avoid bringing in an extra dependency." (:refer-clojure :exclude [repeat regexp?]) (:require [clojure.string :as str]) (:import (java.util.regex Pattern))) (defn escape "Escapes characters in the string that are not safe to use in a RegExp." [s] (Pattern/quote ^String s)) (defn regexp? "Return `true` if `x` is a regexp pattern instance." [x] (instance? Pattern x)) (defn join "Joins strings together with given separator." ([coll] (apply str coll)) ([separator coll] (apply str (interpose separator coll)))) (defn repeat "Repeats string n times." ([s] (repeat s 1)) ([s n] (when (string? s) (join (clojure.core/repeat n s))))) (defn split "Splits a string on a separator a limited number of times. The separator can be a string, character or Pattern (clj) / RegExp (cljs) instance." ([s] (split s #"\s+")) ([s ^Object sep] (cond (nil? s) s (regexp? sep) (str/split s sep) (string? sep) (str/split s (re-pattern (escape sep))) (char? sep) (str/split s (re-pattern (escape (.toString sep)))) :else (throw (ex-info "Invalid arguments" {:sep sep})))) ([s ^Object sep num] (cond (nil? s) s (regexp? sep) (str/split s sep num) (string? sep) (str/split s (re-pattern (escape sep)) num) (char? sep) (str/split s (re-pattern (escape (.toString sep))) num) :else (throw (ex-info "Invalid arguments" {:sep sep}))))) (defn lines "Return a list of the lines in the string." [s] (split s #"\n|\r\n")) (defn unlines "Returns a new string joining a list of strings with a newline char (\\n)." [s] (when (sequential? s) (str/join "\n" s)))
true
; License: BSD 2-Clause ; Copyright (c) 2014-2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ; https://github.com/funcool/cuerdas ; (ns oops.cuerdas "This is our stripped down version of the cuerdas library to avoid bringing in an extra dependency." (:refer-clojure :exclude [repeat regexp?]) (:require [clojure.string :as str]) (:import (java.util.regex Pattern))) (defn escape "Escapes characters in the string that are not safe to use in a RegExp." [s] (Pattern/quote ^String s)) (defn regexp? "Return `true` if `x` is a regexp pattern instance." [x] (instance? Pattern x)) (defn join "Joins strings together with given separator." ([coll] (apply str coll)) ([separator coll] (apply str (interpose separator coll)))) (defn repeat "Repeats string n times." ([s] (repeat s 1)) ([s n] (when (string? s) (join (clojure.core/repeat n s))))) (defn split "Splits a string on a separator a limited number of times. The separator can be a string, character or Pattern (clj) / RegExp (cljs) instance." ([s] (split s #"\s+")) ([s ^Object sep] (cond (nil? s) s (regexp? sep) (str/split s sep) (string? sep) (str/split s (re-pattern (escape sep))) (char? sep) (str/split s (re-pattern (escape (.toString sep)))) :else (throw (ex-info "Invalid arguments" {:sep sep})))) ([s ^Object sep num] (cond (nil? s) s (regexp? sep) (str/split s sep num) (string? sep) (str/split s (re-pattern (escape sep)) num) (char? sep) (str/split s (re-pattern (escape (.toString sep))) num) :else (throw (ex-info "Invalid arguments" {:sep sep}))))) (defn lines "Return a list of the lines in the string." [s] (split s #"\n|\r\n")) (defn unlines "Returns a new string joining a list of strings with a newline char (\\n)." [s] (when (sequential? s) (str/join "\n" s)))
[ { "context": " :type :clean-monday}]}]})))))\n\n\n;; Copyright 2018 Frederic Merizen\n;;\n;; Licensed under the Apache License, Version ", "end": 13712, "score": 0.999852180480957, "start": 13696, "tag": "NAME", "value": "Frederic Merizen" } ]
test/ferje/config/core_test.clj
chourave/clojyday
0
;; Copyright and license information at end of file (ns ferje.config.core-test (:require [clojure.test :refer [deftest is testing use-fixtures]] [clojure.walk :refer [prewalk]] [ferje.core :as ferje] [ferje.config.core :as config] [ferje.place :as place] [ferje.spec-test-utils :refer [instrument-fixture]] [java-time :as time]) (:import (de.jollyday.config ChristianHoliday ChristianHolidayType ChronologyType Configuration EthiopianOrthodoxHoliday EthiopianOrthodoxHolidayType Fixed FixedWeekdayBetweenFixed FixedWeekdayInMonth FixedWeekdayRelativeToFixed HebrewHoliday HinduHoliday HinduHolidayType Holidays HolidayType IslamicHoliday IslamicHolidayType Month MovingCondition RelativeToEasterSunday RelativeToFixed RelativeToWeekdayInMonth Weekday When Which With))) ;; Fixtures (use-fixtures :once instrument-fixture) ;; (defn config? "is x a Jollyday configuration object?" [x] (and x (= "de.jollyday.config" (-> x class .getPackage .getName)))) (defn config-bean "Create a clojure persistent map / vector representation of a given Jollyday configuration bean" [x] (prewalk #(cond (or (instance? Enum %) (string? %) (nil? %)) % (config? %) (into {} (bean %)) (seqable? %) (vec %) :else %) x)) (deftest named?-test (is (config/named? :a)) (is (config/named? 'a)) (is (config/named? "a"))) (deftest ->const-name-test (is (= "OCTOBER_DAYE" (config/->const-name :october-daye)))) (deftest ->enum-test (is (= Month/AUGUST (config/->enum :august Month)))) (deftest set-common-holiday-attributes!-test (testing "Respect default values" (is (= (config-bean (doto (Fixed.) (.setEvery "EVERY_YEAR") (.setLocalizedType HolidayType/OFFICIAL_HOLIDAY))) (config-bean (doto (Fixed.) (config/set-common-holiday-attributes! {}))))))) (deftest ->Holiday-test (testing "For fixed" (is (= (config-bean (doto (Fixed.) (.setMonth Month/FEBRUARY) (.setDay (int 28)))) (config-bean (config/->Holiday {:holiday :fixed, :month :february, :day 28})))) (is (= (config-bean (doto (Fixed.) (.setMonth Month/FEBRUARY) (.setDay (int 28)) (-> (.getMovingCondition) (.add (doto (MovingCondition.) (.setSubstitute Weekday/SATURDAY) (.setWith With/NEXT) (.setWeekday Weekday/MONDAY)))))) (config-bean (config/->Holiday {:holiday :fixed :month :february :day 28 :moving-conditions [{:substitute :saturday, :with :next, :weekday :monday}]}))))) (testing "For relative to fixed" (is (= (config-bean (doto (RelativeToFixed.) (.setDescriptionPropertiesKey "VICTORIA_DAY") (.setWeekday Weekday/MONDAY) (.setWhen When/BEFORE) (.setDate (doto (Fixed.) (.setMonth Month/MAY) (.setDay (int 24)))))) (config-bean (config/->Holiday {:holiday :relative-to-fixed :description-key :victoria-day :weekday :monday :when :before :date {:month :may, :day 24}})))) (is (= (config-bean (doto (RelativeToFixed.) (.setDays (int 5)) (.setWhen When/AFTER) (.setDate (doto (Fixed.) (.setMonth Month/NOVEMBER) (.setDay (int 23)))))) (config-bean (config/->Holiday {:holiday :relative-to-fixed :days 5 :when :after :date {:month :november, :day 23}}))))) (testing "For fixed weekday in month" (is (= (config-bean (doto (FixedWeekdayInMonth.) (.setWhich Which/LAST) (.setWeekday Weekday/MONDAY) (.setMonth Month/MAY) (.setValidFrom (int 1968)) (.setDescriptionPropertiesKey "MEMORIAL"))) (config-bean (config/->Holiday {:holiday :fixed-weekday :which :last :weekday :monday :month :may :valid-from 1968 :description-key :memorial}))))) (testing "For relative to weekday in month" (is (= (config-bean (doto (RelativeToWeekdayInMonth.) (.setWeekday Weekday/TUESDAY) (.setWhen When/AFTER) (.setDescriptionPropertiesKey "ELECTION") (.setFixedWeekday (doto (FixedWeekdayInMonth.) (.setWhich Which/FIRST) (.setWeekday Weekday/MONDAY) (.setMonth Month/MAY))))) (config-bean (config/->Holiday {:holiday :relative-to-weekday-in-month :weekday :tuesday :when :after :description-key :election :fixed-weekday {:which :first :weekday :monday :month :may}}))))) (testing "For christian holiday" (is (= (config-bean (doto (ChristianHoliday.) (.setType ChristianHolidayType/CLEAN_MONDAY))) (config-bean (config/->Holiday {:holiday :christian-holiday :type :clean-monday})))) (is (= (config-bean (doto (ChristianHoliday.) (.setType ChristianHolidayType/CLEAN_MONDAY) (.setChronology ChronologyType/JULIAN))) (config-bean (config/->Holiday {:holiday :christian-holiday :type :clean-monday :chronology :julian})))) (is (= (config-bean (doto (ChristianHoliday.) (.setType ChristianHolidayType/CLEAN_MONDAY) (.setChronology ChronologyType/JULIAN) (-> (.getMovingCondition) (.add (doto (MovingCondition.) (.setSubstitute Weekday/SATURDAY) (.setWith With/NEXT) (.setWeekday Weekday/MONDAY)))))) (config-bean (config/->Holiday {:holiday :christian-holiday :type :clean-monday :chronology :julian :moving-conditions [{:substitute :saturday, :with :next, :weekday :monday}]}))))) (testing "For islamic holiday" (is (= (config-bean (doto (IslamicHoliday.) (.setType IslamicHolidayType/ID_UL_ADHA))) (config-bean (config/->Holiday {:holiday :islamic-holiday :type :id-ul-adha}))))) (testing "For fixed weekday between fixed" (is (= (config-bean (doto (FixedWeekdayBetweenFixed.) (.setWeekday Weekday/SATURDAY) (.setDescriptionPropertiesKey "ALL_SAINTS") (.setFrom (doto (Fixed.) (.setMonth Month/OCTOBER) (.setDay (int 31)))) (.setTo (doto (Fixed.) (.setMonth Month/NOVEMBER) (.setDay (int 6)))))) (config-bean (config/->Holiday {:holiday :fixed-weekday-between-fixed :weekday :saturday :description-key :all-saints :from {:month :october, :day 31} :to {:month :november, :day 6}}))))) (testing "For fixed weekday relative to fixed" (is (= (config-bean (doto (FixedWeekdayRelativeToFixed.) (.setWhich Which/FIRST) (.setWeekday Weekday/THURSDAY) (.setWhen When/AFTER) (.setDescriptionPropertiesKey "FIRST_DAY_SUMMER") (.setDay (doto (Fixed.) (.setMonth Month/APRIL) (.setDay (int 18)))))) (config-bean (config/->Holiday {:holiday :fixed-weekday-relative-to-fixed :which :first :weekday :thursday :when :after :description-key :first-day-summer :date {:month :april, :day 18}}))))) (testing "For hindu holiday" (is (= (config-bean (doto (HinduHoliday.) (.setType HinduHolidayType/HOLI))) (config-bean (config/->Holiday {:holiday :hindu-holiday :type :holi}))))) (testing "For hebrew holiday" (is (= (config-bean (doto (HebrewHoliday.) (.setType "YOM_KIPPUR"))) (config-bean (config/->Holiday {:holiday :hebrew-holiday :type :yom-kippur}))))) (testing "For ethiopian orthodox holiday" (is (= (config-bean (doto (EthiopianOrthodoxHoliday.) (.setType EthiopianOrthodoxHolidayType/TIMKAT))) (config-bean (config/->Holiday {:holiday :ethiopian-orthodox-holiday :type :timkat}))))) (testing "For relative to easter sunday" (is (= (config-bean (doto (RelativeToEasterSunday.) (.setChronology ChronologyType/JULIAN) (.setDays (int 12)))) (config-bean (config/->Holiday {:holiday :relative-to-easter-sunday :chronology :julian :days 12})))))) (deftest ->Configuration-test (is (= (config-bean (doto (Configuration.) (.setDescription "France") (.setHierarchy "fr") (.setHolidays (doto (Holidays.) (-> (.getFixed) (.add (doto (Fixed.) (.setDescriptionPropertiesKey "NEW_YEAR") (.setMonth Month/JANUARY) (.setDay (int 1))))))) (-> (.getSubConfigurations) (.add (doto (Configuration.) (.setDescription "Martinique") (.setHierarchy "ma") (.setHolidays (doto (Holidays.) (-> (.getChristianHoliday) (.add (doto (ChristianHoliday.) (.setType ChristianHolidayType/CLEAN_MONDAY))))))))))) (config-bean (config/->Configuration {:description "France", :hierarchy :fr, :holidays [{:holiday :fixed, :description-key :new-year, :month :january, :day 1}] :sub-configurations [{:description "Martinique", :hierarchy :ma, :holidays [{:holiday :christian-holiday, :type :clean-monday}]}]}))))) ;; 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.
76108
;; Copyright and license information at end of file (ns ferje.config.core-test (:require [clojure.test :refer [deftest is testing use-fixtures]] [clojure.walk :refer [prewalk]] [ferje.core :as ferje] [ferje.config.core :as config] [ferje.place :as place] [ferje.spec-test-utils :refer [instrument-fixture]] [java-time :as time]) (:import (de.jollyday.config ChristianHoliday ChristianHolidayType ChronologyType Configuration EthiopianOrthodoxHoliday EthiopianOrthodoxHolidayType Fixed FixedWeekdayBetweenFixed FixedWeekdayInMonth FixedWeekdayRelativeToFixed HebrewHoliday HinduHoliday HinduHolidayType Holidays HolidayType IslamicHoliday IslamicHolidayType Month MovingCondition RelativeToEasterSunday RelativeToFixed RelativeToWeekdayInMonth Weekday When Which With))) ;; Fixtures (use-fixtures :once instrument-fixture) ;; (defn config? "is x a Jollyday configuration object?" [x] (and x (= "de.jollyday.config" (-> x class .getPackage .getName)))) (defn config-bean "Create a clojure persistent map / vector representation of a given Jollyday configuration bean" [x] (prewalk #(cond (or (instance? Enum %) (string? %) (nil? %)) % (config? %) (into {} (bean %)) (seqable? %) (vec %) :else %) x)) (deftest named?-test (is (config/named? :a)) (is (config/named? 'a)) (is (config/named? "a"))) (deftest ->const-name-test (is (= "OCTOBER_DAYE" (config/->const-name :october-daye)))) (deftest ->enum-test (is (= Month/AUGUST (config/->enum :august Month)))) (deftest set-common-holiday-attributes!-test (testing "Respect default values" (is (= (config-bean (doto (Fixed.) (.setEvery "EVERY_YEAR") (.setLocalizedType HolidayType/OFFICIAL_HOLIDAY))) (config-bean (doto (Fixed.) (config/set-common-holiday-attributes! {}))))))) (deftest ->Holiday-test (testing "For fixed" (is (= (config-bean (doto (Fixed.) (.setMonth Month/FEBRUARY) (.setDay (int 28)))) (config-bean (config/->Holiday {:holiday :fixed, :month :february, :day 28})))) (is (= (config-bean (doto (Fixed.) (.setMonth Month/FEBRUARY) (.setDay (int 28)) (-> (.getMovingCondition) (.add (doto (MovingCondition.) (.setSubstitute Weekday/SATURDAY) (.setWith With/NEXT) (.setWeekday Weekday/MONDAY)))))) (config-bean (config/->Holiday {:holiday :fixed :month :february :day 28 :moving-conditions [{:substitute :saturday, :with :next, :weekday :monday}]}))))) (testing "For relative to fixed" (is (= (config-bean (doto (RelativeToFixed.) (.setDescriptionPropertiesKey "VICTORIA_DAY") (.setWeekday Weekday/MONDAY) (.setWhen When/BEFORE) (.setDate (doto (Fixed.) (.setMonth Month/MAY) (.setDay (int 24)))))) (config-bean (config/->Holiday {:holiday :relative-to-fixed :description-key :victoria-day :weekday :monday :when :before :date {:month :may, :day 24}})))) (is (= (config-bean (doto (RelativeToFixed.) (.setDays (int 5)) (.setWhen When/AFTER) (.setDate (doto (Fixed.) (.setMonth Month/NOVEMBER) (.setDay (int 23)))))) (config-bean (config/->Holiday {:holiday :relative-to-fixed :days 5 :when :after :date {:month :november, :day 23}}))))) (testing "For fixed weekday in month" (is (= (config-bean (doto (FixedWeekdayInMonth.) (.setWhich Which/LAST) (.setWeekday Weekday/MONDAY) (.setMonth Month/MAY) (.setValidFrom (int 1968)) (.setDescriptionPropertiesKey "MEMORIAL"))) (config-bean (config/->Holiday {:holiday :fixed-weekday :which :last :weekday :monday :month :may :valid-from 1968 :description-key :memorial}))))) (testing "For relative to weekday in month" (is (= (config-bean (doto (RelativeToWeekdayInMonth.) (.setWeekday Weekday/TUESDAY) (.setWhen When/AFTER) (.setDescriptionPropertiesKey "ELECTION") (.setFixedWeekday (doto (FixedWeekdayInMonth.) (.setWhich Which/FIRST) (.setWeekday Weekday/MONDAY) (.setMonth Month/MAY))))) (config-bean (config/->Holiday {:holiday :relative-to-weekday-in-month :weekday :tuesday :when :after :description-key :election :fixed-weekday {:which :first :weekday :monday :month :may}}))))) (testing "For christian holiday" (is (= (config-bean (doto (ChristianHoliday.) (.setType ChristianHolidayType/CLEAN_MONDAY))) (config-bean (config/->Holiday {:holiday :christian-holiday :type :clean-monday})))) (is (= (config-bean (doto (ChristianHoliday.) (.setType ChristianHolidayType/CLEAN_MONDAY) (.setChronology ChronologyType/JULIAN))) (config-bean (config/->Holiday {:holiday :christian-holiday :type :clean-monday :chronology :julian})))) (is (= (config-bean (doto (ChristianHoliday.) (.setType ChristianHolidayType/CLEAN_MONDAY) (.setChronology ChronologyType/JULIAN) (-> (.getMovingCondition) (.add (doto (MovingCondition.) (.setSubstitute Weekday/SATURDAY) (.setWith With/NEXT) (.setWeekday Weekday/MONDAY)))))) (config-bean (config/->Holiday {:holiday :christian-holiday :type :clean-monday :chronology :julian :moving-conditions [{:substitute :saturday, :with :next, :weekday :monday}]}))))) (testing "For islamic holiday" (is (= (config-bean (doto (IslamicHoliday.) (.setType IslamicHolidayType/ID_UL_ADHA))) (config-bean (config/->Holiday {:holiday :islamic-holiday :type :id-ul-adha}))))) (testing "For fixed weekday between fixed" (is (= (config-bean (doto (FixedWeekdayBetweenFixed.) (.setWeekday Weekday/SATURDAY) (.setDescriptionPropertiesKey "ALL_SAINTS") (.setFrom (doto (Fixed.) (.setMonth Month/OCTOBER) (.setDay (int 31)))) (.setTo (doto (Fixed.) (.setMonth Month/NOVEMBER) (.setDay (int 6)))))) (config-bean (config/->Holiday {:holiday :fixed-weekday-between-fixed :weekday :saturday :description-key :all-saints :from {:month :october, :day 31} :to {:month :november, :day 6}}))))) (testing "For fixed weekday relative to fixed" (is (= (config-bean (doto (FixedWeekdayRelativeToFixed.) (.setWhich Which/FIRST) (.setWeekday Weekday/THURSDAY) (.setWhen When/AFTER) (.setDescriptionPropertiesKey "FIRST_DAY_SUMMER") (.setDay (doto (Fixed.) (.setMonth Month/APRIL) (.setDay (int 18)))))) (config-bean (config/->Holiday {:holiday :fixed-weekday-relative-to-fixed :which :first :weekday :thursday :when :after :description-key :first-day-summer :date {:month :april, :day 18}}))))) (testing "For hindu holiday" (is (= (config-bean (doto (HinduHoliday.) (.setType HinduHolidayType/HOLI))) (config-bean (config/->Holiday {:holiday :hindu-holiday :type :holi}))))) (testing "For hebrew holiday" (is (= (config-bean (doto (HebrewHoliday.) (.setType "YOM_KIPPUR"))) (config-bean (config/->Holiday {:holiday :hebrew-holiday :type :yom-kippur}))))) (testing "For ethiopian orthodox holiday" (is (= (config-bean (doto (EthiopianOrthodoxHoliday.) (.setType EthiopianOrthodoxHolidayType/TIMKAT))) (config-bean (config/->Holiday {:holiday :ethiopian-orthodox-holiday :type :timkat}))))) (testing "For relative to easter sunday" (is (= (config-bean (doto (RelativeToEasterSunday.) (.setChronology ChronologyType/JULIAN) (.setDays (int 12)))) (config-bean (config/->Holiday {:holiday :relative-to-easter-sunday :chronology :julian :days 12})))))) (deftest ->Configuration-test (is (= (config-bean (doto (Configuration.) (.setDescription "France") (.setHierarchy "fr") (.setHolidays (doto (Holidays.) (-> (.getFixed) (.add (doto (Fixed.) (.setDescriptionPropertiesKey "NEW_YEAR") (.setMonth Month/JANUARY) (.setDay (int 1))))))) (-> (.getSubConfigurations) (.add (doto (Configuration.) (.setDescription "Martinique") (.setHierarchy "ma") (.setHolidays (doto (Holidays.) (-> (.getChristianHoliday) (.add (doto (ChristianHoliday.) (.setType ChristianHolidayType/CLEAN_MONDAY))))))))))) (config-bean (config/->Configuration {:description "France", :hierarchy :fr, :holidays [{:holiday :fixed, :description-key :new-year, :month :january, :day 1}] :sub-configurations [{:description "Martinique", :hierarchy :ma, :holidays [{:holiday :christian-holiday, :type :clean-monday}]}]}))))) ;; 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-test (:require [clojure.test :refer [deftest is testing use-fixtures]] [clojure.walk :refer [prewalk]] [ferje.core :as ferje] [ferje.config.core :as config] [ferje.place :as place] [ferje.spec-test-utils :refer [instrument-fixture]] [java-time :as time]) (:import (de.jollyday.config ChristianHoliday ChristianHolidayType ChronologyType Configuration EthiopianOrthodoxHoliday EthiopianOrthodoxHolidayType Fixed FixedWeekdayBetweenFixed FixedWeekdayInMonth FixedWeekdayRelativeToFixed HebrewHoliday HinduHoliday HinduHolidayType Holidays HolidayType IslamicHoliday IslamicHolidayType Month MovingCondition RelativeToEasterSunday RelativeToFixed RelativeToWeekdayInMonth Weekday When Which With))) ;; Fixtures (use-fixtures :once instrument-fixture) ;; (defn config? "is x a Jollyday configuration object?" [x] (and x (= "de.jollyday.config" (-> x class .getPackage .getName)))) (defn config-bean "Create a clojure persistent map / vector representation of a given Jollyday configuration bean" [x] (prewalk #(cond (or (instance? Enum %) (string? %) (nil? %)) % (config? %) (into {} (bean %)) (seqable? %) (vec %) :else %) x)) (deftest named?-test (is (config/named? :a)) (is (config/named? 'a)) (is (config/named? "a"))) (deftest ->const-name-test (is (= "OCTOBER_DAYE" (config/->const-name :october-daye)))) (deftest ->enum-test (is (= Month/AUGUST (config/->enum :august Month)))) (deftest set-common-holiday-attributes!-test (testing "Respect default values" (is (= (config-bean (doto (Fixed.) (.setEvery "EVERY_YEAR") (.setLocalizedType HolidayType/OFFICIAL_HOLIDAY))) (config-bean (doto (Fixed.) (config/set-common-holiday-attributes! {}))))))) (deftest ->Holiday-test (testing "For fixed" (is (= (config-bean (doto (Fixed.) (.setMonth Month/FEBRUARY) (.setDay (int 28)))) (config-bean (config/->Holiday {:holiday :fixed, :month :february, :day 28})))) (is (= (config-bean (doto (Fixed.) (.setMonth Month/FEBRUARY) (.setDay (int 28)) (-> (.getMovingCondition) (.add (doto (MovingCondition.) (.setSubstitute Weekday/SATURDAY) (.setWith With/NEXT) (.setWeekday Weekday/MONDAY)))))) (config-bean (config/->Holiday {:holiday :fixed :month :february :day 28 :moving-conditions [{:substitute :saturday, :with :next, :weekday :monday}]}))))) (testing "For relative to fixed" (is (= (config-bean (doto (RelativeToFixed.) (.setDescriptionPropertiesKey "VICTORIA_DAY") (.setWeekday Weekday/MONDAY) (.setWhen When/BEFORE) (.setDate (doto (Fixed.) (.setMonth Month/MAY) (.setDay (int 24)))))) (config-bean (config/->Holiday {:holiday :relative-to-fixed :description-key :victoria-day :weekday :monday :when :before :date {:month :may, :day 24}})))) (is (= (config-bean (doto (RelativeToFixed.) (.setDays (int 5)) (.setWhen When/AFTER) (.setDate (doto (Fixed.) (.setMonth Month/NOVEMBER) (.setDay (int 23)))))) (config-bean (config/->Holiday {:holiday :relative-to-fixed :days 5 :when :after :date {:month :november, :day 23}}))))) (testing "For fixed weekday in month" (is (= (config-bean (doto (FixedWeekdayInMonth.) (.setWhich Which/LAST) (.setWeekday Weekday/MONDAY) (.setMonth Month/MAY) (.setValidFrom (int 1968)) (.setDescriptionPropertiesKey "MEMORIAL"))) (config-bean (config/->Holiday {:holiday :fixed-weekday :which :last :weekday :monday :month :may :valid-from 1968 :description-key :memorial}))))) (testing "For relative to weekday in month" (is (= (config-bean (doto (RelativeToWeekdayInMonth.) (.setWeekday Weekday/TUESDAY) (.setWhen When/AFTER) (.setDescriptionPropertiesKey "ELECTION") (.setFixedWeekday (doto (FixedWeekdayInMonth.) (.setWhich Which/FIRST) (.setWeekday Weekday/MONDAY) (.setMonth Month/MAY))))) (config-bean (config/->Holiday {:holiday :relative-to-weekday-in-month :weekday :tuesday :when :after :description-key :election :fixed-weekday {:which :first :weekday :monday :month :may}}))))) (testing "For christian holiday" (is (= (config-bean (doto (ChristianHoliday.) (.setType ChristianHolidayType/CLEAN_MONDAY))) (config-bean (config/->Holiday {:holiday :christian-holiday :type :clean-monday})))) (is (= (config-bean (doto (ChristianHoliday.) (.setType ChristianHolidayType/CLEAN_MONDAY) (.setChronology ChronologyType/JULIAN))) (config-bean (config/->Holiday {:holiday :christian-holiday :type :clean-monday :chronology :julian})))) (is (= (config-bean (doto (ChristianHoliday.) (.setType ChristianHolidayType/CLEAN_MONDAY) (.setChronology ChronologyType/JULIAN) (-> (.getMovingCondition) (.add (doto (MovingCondition.) (.setSubstitute Weekday/SATURDAY) (.setWith With/NEXT) (.setWeekday Weekday/MONDAY)))))) (config-bean (config/->Holiday {:holiday :christian-holiday :type :clean-monday :chronology :julian :moving-conditions [{:substitute :saturday, :with :next, :weekday :monday}]}))))) (testing "For islamic holiday" (is (= (config-bean (doto (IslamicHoliday.) (.setType IslamicHolidayType/ID_UL_ADHA))) (config-bean (config/->Holiday {:holiday :islamic-holiday :type :id-ul-adha}))))) (testing "For fixed weekday between fixed" (is (= (config-bean (doto (FixedWeekdayBetweenFixed.) (.setWeekday Weekday/SATURDAY) (.setDescriptionPropertiesKey "ALL_SAINTS") (.setFrom (doto (Fixed.) (.setMonth Month/OCTOBER) (.setDay (int 31)))) (.setTo (doto (Fixed.) (.setMonth Month/NOVEMBER) (.setDay (int 6)))))) (config-bean (config/->Holiday {:holiday :fixed-weekday-between-fixed :weekday :saturday :description-key :all-saints :from {:month :october, :day 31} :to {:month :november, :day 6}}))))) (testing "For fixed weekday relative to fixed" (is (= (config-bean (doto (FixedWeekdayRelativeToFixed.) (.setWhich Which/FIRST) (.setWeekday Weekday/THURSDAY) (.setWhen When/AFTER) (.setDescriptionPropertiesKey "FIRST_DAY_SUMMER") (.setDay (doto (Fixed.) (.setMonth Month/APRIL) (.setDay (int 18)))))) (config-bean (config/->Holiday {:holiday :fixed-weekday-relative-to-fixed :which :first :weekday :thursday :when :after :description-key :first-day-summer :date {:month :april, :day 18}}))))) (testing "For hindu holiday" (is (= (config-bean (doto (HinduHoliday.) (.setType HinduHolidayType/HOLI))) (config-bean (config/->Holiday {:holiday :hindu-holiday :type :holi}))))) (testing "For hebrew holiday" (is (= (config-bean (doto (HebrewHoliday.) (.setType "YOM_KIPPUR"))) (config-bean (config/->Holiday {:holiday :hebrew-holiday :type :yom-kippur}))))) (testing "For ethiopian orthodox holiday" (is (= (config-bean (doto (EthiopianOrthodoxHoliday.) (.setType EthiopianOrthodoxHolidayType/TIMKAT))) (config-bean (config/->Holiday {:holiday :ethiopian-orthodox-holiday :type :timkat}))))) (testing "For relative to easter sunday" (is (= (config-bean (doto (RelativeToEasterSunday.) (.setChronology ChronologyType/JULIAN) (.setDays (int 12)))) (config-bean (config/->Holiday {:holiday :relative-to-easter-sunday :chronology :julian :days 12})))))) (deftest ->Configuration-test (is (= (config-bean (doto (Configuration.) (.setDescription "France") (.setHierarchy "fr") (.setHolidays (doto (Holidays.) (-> (.getFixed) (.add (doto (Fixed.) (.setDescriptionPropertiesKey "NEW_YEAR") (.setMonth Month/JANUARY) (.setDay (int 1))))))) (-> (.getSubConfigurations) (.add (doto (Configuration.) (.setDescription "Martinique") (.setHierarchy "ma") (.setHolidays (doto (Holidays.) (-> (.getChristianHoliday) (.add (doto (ChristianHoliday.) (.setType ChristianHolidayType/CLEAN_MONDAY))))))))))) (config-bean (config/->Configuration {:description "France", :hierarchy :fr, :holidays [{:holiday :fixed, :description-key :new-year, :month :january, :day 1}] :sub-configurations [{:description "Martinique", :hierarchy :ma, :holidays [{:holiday :christian-holiday, :type :clean-monday}]}]}))))) ;; 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": "ame (apply str (drop 1 (.getPath uri)))\n :user username\n :password password\n :host (.getHost uri)", "end": 724, "score": 0.9969876408576965, "start": 716, "tag": "USERNAME", "value": "username" }, { "context": ".getPath uri)))\n :user username\n :password password\n :host (.getHost uri)\n :port (.getPort ur", "end": 748, "score": 0.9761788845062256, "start": 740, "tag": "PASSWORD", "value": "password" }, { "context": "r\n :password password})\n db-ents (into {} (map (partial crea", "end": 1390, "score": 0.9971280097961426, "start": 1382, "tag": "PASSWORD", "value": "password" } ]
src/zoo_event/component/database.clj
zooniverse/zoo-event
0
(ns zoo-event.component.database (:require [korma.db :as db] [korma.core :refer :all] [clojure.tools.logging :as log] [pg-json.core :refer :all] [clojure.string :as str] [com.stuartsierra.component :as component])) (defn json-transformer [obj] (update-in obj [:data] from-json-column)) (defn- create-event-entity [db-conn event] [event (-> (create-entity (str "events_" event)) (database db-conn) (transform json-transformer))]) (defn- uri-to-db-map [uri] (let [uri (java.net.URI. uri) [username password] (str/split (.getUserInfo uri) #":")] {:db-name (apply str (drop 1 (.getPath uri))) :user username :password password :host (.getHost uri) :port (.getPort uri)})) (defn- db-connection [conn-map] (db/create-db (db/postgres conn-map))) (defn- db-log-name [{:keys [db-name host port]}] (str db-name " at " host ":" port)) (defrecord Database [events host port db-name user password connection db-ents] component/Lifecycle (start [component] (if connection component (let [connection (db-connection {:host host :port port :db db-name :user user :password password}) db-ents (into {} (map (partial create-event-entity connection) events))] (do (log/info (str "Connecting to " (db-log-name component))) (-> (assoc component :connection connection) (assoc :db-ents db-ents)))))) (stop [component] (if-not connection component (do (log/info (str "Closing connection to " (db-log-name component))) (dissoc component :connection))))) (defn new-database [events jdbc-uri] (map->Database (merge {:events events} (uri-to-db-map jdbc-uri))))
67111
(ns zoo-event.component.database (:require [korma.db :as db] [korma.core :refer :all] [clojure.tools.logging :as log] [pg-json.core :refer :all] [clojure.string :as str] [com.stuartsierra.component :as component])) (defn json-transformer [obj] (update-in obj [:data] from-json-column)) (defn- create-event-entity [db-conn event] [event (-> (create-entity (str "events_" event)) (database db-conn) (transform json-transformer))]) (defn- uri-to-db-map [uri] (let [uri (java.net.URI. uri) [username password] (str/split (.getUserInfo uri) #":")] {:db-name (apply str (drop 1 (.getPath uri))) :user username :password <PASSWORD> :host (.getHost uri) :port (.getPort uri)})) (defn- db-connection [conn-map] (db/create-db (db/postgres conn-map))) (defn- db-log-name [{:keys [db-name host port]}] (str db-name " at " host ":" port)) (defrecord Database [events host port db-name user password connection db-ents] component/Lifecycle (start [component] (if connection component (let [connection (db-connection {:host host :port port :db db-name :user user :password <PASSWORD>}) db-ents (into {} (map (partial create-event-entity connection) events))] (do (log/info (str "Connecting to " (db-log-name component))) (-> (assoc component :connection connection) (assoc :db-ents db-ents)))))) (stop [component] (if-not connection component (do (log/info (str "Closing connection to " (db-log-name component))) (dissoc component :connection))))) (defn new-database [events jdbc-uri] (map->Database (merge {:events events} (uri-to-db-map jdbc-uri))))
true
(ns zoo-event.component.database (:require [korma.db :as db] [korma.core :refer :all] [clojure.tools.logging :as log] [pg-json.core :refer :all] [clojure.string :as str] [com.stuartsierra.component :as component])) (defn json-transformer [obj] (update-in obj [:data] from-json-column)) (defn- create-event-entity [db-conn event] [event (-> (create-entity (str "events_" event)) (database db-conn) (transform json-transformer))]) (defn- uri-to-db-map [uri] (let [uri (java.net.URI. uri) [username password] (str/split (.getUserInfo uri) #":")] {:db-name (apply str (drop 1 (.getPath uri))) :user username :password PI:PASSWORD:<PASSWORD>END_PI :host (.getHost uri) :port (.getPort uri)})) (defn- db-connection [conn-map] (db/create-db (db/postgres conn-map))) (defn- db-log-name [{:keys [db-name host port]}] (str db-name " at " host ":" port)) (defrecord Database [events host port db-name user password connection db-ents] component/Lifecycle (start [component] (if connection component (let [connection (db-connection {:host host :port port :db db-name :user user :password PI:PASSWORD:<PASSWORD>END_PI}) db-ents (into {} (map (partial create-event-entity connection) events))] (do (log/info (str "Connecting to " (db-log-name component))) (-> (assoc component :connection connection) (assoc :db-ents db-ents)))))) (stop [component] (if-not connection component (do (log/info (str "Closing connection to " (db-log-name component))) (dissoc component :connection))))) (defn new-database [events jdbc-uri] (map->Database (merge {:events events} (uri-to-db-map jdbc-uri))))