Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .clj-kondo/imports/io.github.noahtheduke/lazytest/config.edn
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@
lazytest.extensions.expectations/more-of hooks.lazytest.expectations/more-of
lazytest.experimental.interfaces.expectations/more-> hooks.lazytest.expectations/more->
lazytest.experimental.interfaces.expectations/more-of hooks.lazytest.expectations/interface-more-of
lazytest.hooks/defhook hooks.lazytest.hooks/defhook
}}
:linters {:clojure-lsp/unused-public-var
:linters {:lazytest/hook-impl {:level :error}
:clojure-lsp/unused-public-var
{:exclude-when-defined-by #{lazytest.core/defdescribe
lazytest.experimental.interfaces.xunit/defsuite
lazytest.experimental.interfaces.clojure-test/deftest
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
(ns hooks.lazytest.hooks
(:require [clj-kondo.hooks-api :as api]))

(defn get-arg
[args pred]
(if (pred (first args))
[(first args) (next args)]
[nil args]))

(defn defhook
[{:keys [node]}]
(let [[_defmulti hook-name & hook-impls] (:children node)
[docstring hook-impls] (get-arg hook-impls api/string-node?)
new-node (api/list-node
(concat
[(api/token-node 'do)
(api/list-node
(concat
[(api/token-node 'defmulti) hook-name]
(when docstring [docstring])
[(api/coerce {:arglists '([config m hook-type])})
(api/coerce (list 'var 'lazytest.hooks/hook-dispatch))]))
(api/coerce (list 'defmethod (api/sexpr hook-name) (api/keyword-node :default) '[_config m _hook-type] 'm))]
(map (fn [impl]
(if-not (api/list-node? impl)
(let [{:keys [row col end-row end-col]} (meta impl)]
(api/reg-finding!
{:type :lazytest/hook-impl
:message (str "Expected list, received " (type (api/sexpr impl)))
:row row :col col :end-row end-row :end-col end-col}))
(let [[hook-key hook-args & hook-body] (:children impl)
hook-key' (with-meta (api/keyword-node (keyword (api/sexpr hook-key))) (meta hook-key))]
(api/reg-keyword! hook-key' true)
(with-meta
(api/list-node
(list*
(api/token-node 'defmethod)
(with-meta hook-name (meta hook-key))
hook-key'
(update hook-args :children #(conj (vec %) (api/coerce (gensym "_hook-type"))))
hook-body))
(meta impl)))))
hook-impls)
[(api/coerce (list 'var (api/sexpr hook-name)))]))]
{:node (with-meta new-node (meta node))}))
17 changes: 16 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,22 @@

## Unreleased

- Fix bug with ordering of `before-each`/`after-each` and `around` in test cases. (See [#31](https://github.com/NoahTheDuke/lazytest/issues/31).)
Big feature: Hooks! Or plugins, as they're sometimes called. These are entrypoints into the running state of lazytest, called on a given object (the config, the current suite, etc), that allow an author to inspect and/or update that object before it's evaluated or before it's returned. It should allow for better extensibility and configurability.

### Added

- Add `around-each` context functions. (See [#31](https://github.com/NoahTheDuke/lazytest/issues/31), and PR [#34](https://github.com/NoahTheDuke/lazytest/issues/34) by [@edenworky](https://github.com/edenworky)!)
- Add `lazytest.hooks` to support writing plugins/hooks that modify the run.
- Write initial demonstration hooks, `profiling` and `randomize`.

### Changed/Fixed

- Correct the order of `around` and `before-each`/`after-each` in test cases. (See [#31](https://github.com/NoahTheDuke/lazytest/issues/31).)
- Fix `expect-it` to handle `:context` in the attr-map.
- Change the config object to use `:reporters`, not `:reporter`.
- Add clj-kondo hook for `lazytest.hooks/defhook`.
- Change documentation (readme, docstrings) to use `context` instead of `hook` for `before`/`after`/etc.
- BREAKING: Change the order of context hook calls so that `around` wraps `before` and `after`. There are very few use cases where this will matter, so I am not too worried about it.

## 1.9.1

Expand Down
216 changes: 201 additions & 15 deletions README.md

Large diffs are not rendered by default.

6 changes: 2 additions & 4 deletions corpus/context_tests/use_fixture.clj
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
(ns context-tests.use-fixture
(:require
[lazytest.core :refer [around defdescribe expect it set-ns-context!]]))
[lazytest.core :refer [around defdescribe expect it set-ns-context!]]
[lazytest.test-utils :refer [vconj!]]))

(def use-fixture-state (volatile! []))

(defn vconj! [volatile value]
(vswap! volatile conj value))

(set-ns-context!
[(around [f]
(vconj! use-fixture-state :around-before)
Expand Down
7 changes: 5 additions & 2 deletions deps.edn
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,14 @@
;; Development tools
:dev {:extra-paths ["dev" "corpus" "docs"]
:extra-deps {org.clojure/spec.alpha {:mvn/version "0.5.238"}
criterium/criterium {:mvn/version "0.4.6"}
com.clojure-goes-fast/clj-java-decompiler {:mvn/version "0.3.7"}
com.github.seancorfield/honeysql {:mvn/version "2.7.1310"}
org.clojure/tools.gitlibs {:mvn/version "2.6.206"}}}

:bench {:extra-deps {criterium/criterium {:mvn/version "0.5.153-ALPHA"}}
:jvm-opts ["-XX:+UnlockExperimentalVMOptions"
"-XX:CompileCommand=blackhole,criterium.blackhole.Blackhole::consume"]}

;; I like nrepl and rebel-readline.
:repl {:extra-deps {nrepl/nrepl {:mvn/version "1.3.1"}
cider/cider-nrepl {:mvn/version "0.57.0"}
Expand All @@ -32,7 +35,7 @@
;; Run the tests with `-M:provided:dev:test:run`.
:test {:extra-paths ["test/clojure"]}

:splint {:extra-deps {io.github.noahtheduke/splint {:mvn/version "1.21.0"}}
:splint {:extra-deps {io.github.noahtheduke/splint {:mvn/version "1.23.1"}}
:main-opts ["-m" "noahtheduke.splint"]}

:cljfmt {:deps {dev.weavejester/cljfmt {:mvn/version "0.12.0"}}
Expand Down
54 changes: 54 additions & 0 deletions dev/lazytest/scratch.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
(ns lazytest.scratch
(:require
[criterium.bench :refer [bench]])
(:import
[java.util ArrayList]))

(set! *warn-on-reflection* true)

(def l (range 100))

(defn group-seq-by-1
[pred coll]
[(into [] (filter pred) coll)
(into [] (remove pred) coll)])

(defn group-seq-by-2
[pred coll]
(->> coll
(reduce
(fn [acc cur]
(if (pred cur)
(update acc 0 conj cur)
(update acc 1 conj cur)))
[[] []])))

(defn group-seq-by-3
[pred coll]
(let [t (ArrayList/new)
f (ArrayList/new)]
(reduce
(fn [_ cur]
(if (pred cur)
(.add t cur)
(.add f cur)))
nil
coll)
[(vec t)
(vec f)]))

(comment
(prn (= (group-seq-by-1 even? (doall (range 1000)))
(group-seq-by-2 even? (doall (range 1000)))
(group-seq-by-3 even? (doall (range 1000)))))
(do
(bench (group-seq-by-1 even? (doall (range 1000)))
:limit-time-s 17.3)
(flush)
(bench (group-seq-by-2 even? (doall (range 1000)))
:limit-time-s 17.3)
(flush)
(bench (group-seq-by-3 even? (doall (range 1000)))
:limit-time-s 17.3)
(flush))
)
4 changes: 2 additions & 2 deletions docs/core.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

In short: Tests are defined with `defdescribe`, suites (groups of nested suites and test cases) are defined with `describe`, test cases are defined with `it`, and assertions are defined with `expect` but can be any function that throws an exception on failure. When `lazytest.main/run` is called, all loaded namespaces are checked for tests, and the contained test cases are run (with suites providing context and additional documentation).

Hooks can be used in `:context` metadata on suites, and assertion helpers can be used in test cases.
Context functions can be used in `:context` metadata on suites, and assertion helpers can be used in test cases.

```clojure
(require '[lazytest.core :refer :all])
Expand Down Expand Up @@ -81,7 +81,7 @@ temp-test
=> lazytest.suite/suite?
```

# Hooks
# Context

## `before` & `after`

Expand Down
3 changes: 2 additions & 1 deletion justfile
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ splint:

prep:
clojure -X:deps prep
clojure -T:build compile-java

clean:
clojure -T:build clean
Expand Down Expand Up @@ -66,7 +67,7 @@ test-all *args:

repl arg="":
@just prep
clojure -M:provided:dev:test{{arg}}:repl
clojure -M:provided:dev:test{{arg}}:bench:repl

@clojars:
env CLOJARS_USERNAME='noahtheduke' CLOJARS_PASSWORD=`cat ../clojars.txt` clojure -T:build deploy
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@
lazytest.extensions.expectations/more-of hooks.lazytest.expectations/more-of
lazytest.experimental.interfaces.expectations/more-> hooks.lazytest.expectations/more->
lazytest.experimental.interfaces.expectations/more-of hooks.lazytest.expectations/interface-more-of
lazytest.hooks/defhook hooks.lazytest.hooks/defhook
}}
:linters {:clojure-lsp/unused-public-var
:linters {:lazytest/hook-impl {:level :error}
:clojure-lsp/unused-public-var
{:exclude-when-defined-by #{lazytest.core/defdescribe
lazytest.experimental.interfaces.xunit/defsuite
lazytest.experimental.interfaces.clojure-test/deftest
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
(ns hooks.lazytest.hooks
(:require [clj-kondo.hooks-api :as api]))

(defn get-arg
[args pred]
(if (pred (first args))
[(first args) (next args)]
[nil args]))

(defn defhook
[{:keys [node]}]
(let [[_defmulti hook-name & hook-impls] (:children node)
[docstring hook-impls] (get-arg hook-impls api/string-node?)
new-node (api/list-node
(concat
[(api/token-node 'do)
(api/list-node
(concat
[(api/token-node 'defmulti) hook-name]
(when docstring [docstring])
[(api/coerce {:arglists '([config m hook-type])})
(api/coerce (list 'var 'lazytest.hooks/hook-dispatch))]))
(api/coerce (list 'defmethod (api/sexpr hook-name) (api/keyword-node :default) '[_config m _hook-type] 'm))]
(map (fn [impl]
(if-not (api/list-node? impl)
(let [{:keys [row col end-row end-col]} (meta impl)]
(api/reg-finding!
{:type :lazytest/hook-impl
:message (str "Expected list, received " (type (api/sexpr impl)))
:row row :col col :end-row end-row :end-col end-col}))
(let [[hook-key hook-args & hook-body] (:children impl)
hook-key' (with-meta (api/keyword-node (keyword (api/sexpr hook-key))) (meta hook-key))]
(api/reg-keyword! hook-key' true)
(with-meta
(api/list-node
(list*
(api/token-node 'defmethod)
(with-meta hook-name (meta hook-key))
hook-key'
(update hook-args :children #(conj (vec %) (api/coerce (gensym "_hook-type"))))
hook-body))
(meta impl)))))
hook-impls)
[(api/coerce (list 'var (api/sexpr hook-name)))]))]
{:node (with-meta new-node (meta node))}))
37 changes: 26 additions & 11 deletions src/clojure/lazytest/cli.clj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.tools.cli :as cli]
[lazytest.config :refer [lazytest-version]]))
[lazytest.clojure-ext.core :refer [->keyword]]
[lazytest.config :refer [lazytest-version resolve-hooks]]
[lazytest.hooks :refer [run-hooks]]))

(set! *warn-on-reflection* true)

Expand All @@ -15,6 +17,7 @@

(def cli-options
[["-d" "--dir DIR" "Directory containing tests."
:id :dirs
:assoc-fn update-vec]
["-n" "--namespace SYMBOL" "Run only the specified test namespaces. Can be given multiple times."
:id :ns-filter
Expand All @@ -25,20 +28,27 @@
:parse-fn symbol
:assoc-fn update-set]
["-i" "--include KEYWORD" "Run only test sequences or vars with this metadata keyword."
:parse-fn #(keyword (if (str/starts-with? % ":") (subs % 1) %))
:parse-fn ->keyword
:assoc-fn update-set]
["-e" "--exclude KEYWORD" "Exclude test sequences or vars with this metadata keyword."
:parse-fn #(keyword (if (str/starts-with? % ":") (subs % 1) %))
:parse-fn ->keyword
:assoc-fn update-set]
[nil "--output SYMBOL" "Output format. Can be given multiple times. (Defaults to \"nested\".)"
[nil "--output SYMBOL" "Output format. Can be given multiple times."
:parse-fn symbol
:default nil
:default-desc "nested"
:assoc-fn update-vec]
[nil "--hook SYMBOL" "Custom hooks to run. Can be given multiple times."
:id :hooks
:parse-fn symbol
:assoc-fn update-vec]
[nil "--md FILE" "Run doctests for given markdown file. Can be given multiple times."
:parse-fn io/file
:assoc-fn update-vec]
[nil "--doctests" "Run doctests for vars and markdown files found in paths."]
[nil "--watch" "Run under Watch mode. Uses clj-reload to reload changed and dependent namespaces, then reruns test suite."]
[nil "--delay NUM" "(Watch mode) How many milliseconds to wait before checking for changes. (Defaults to 500.)"
[nil "--delay NUM" "(Watch mode) How many milliseconds to wait before checking for changes."
:default 500
:parse-fn #(Long/parseLong %)]
[nil "--help" "Print help information."]
[nil "--version" "Print version information."]])
Expand Down Expand Up @@ -71,13 +81,18 @@
or {map of cli opts}.

:ok is false if given invalid options."
[opts]
(let [{:keys [options errors summary arguments]}
(cli/parse-opts opts cli-options :strict true :summary-fn identity)]
[raw-args]
(let [opts (cli/parse-opts raw-args cli-options :strict true :summary-fn identity)
hooks (-> opts :options :hooks not-empty (some-> resolve-hooks))
hook-cli-opts (when hooks
(run-hooks {:hooks hooks} [] :cli-opts))
opts (if-let [new-opts (not-empty hook-cli-opts)]
(cli/parse-opts raw-args (into cli-options new-opts) :strict true :summary-fn identity)
opts)
{:keys [options errors summary arguments]} opts]
(cond
(:help options) (help-message summary)
(:version options) {:exit-message "lazytest 0.0" :ok true}
(:version options) {:exit-message (lazytest-version) :ok true}
errors (print-errors errors)
:else (-> options
(update :dir (comp not-empty vec concat) arguments)
(update :delay #(or % 500))))))
(update :dirs (comp not-empty vec concat) arguments)))))
26 changes: 24 additions & 2 deletions src/clojure/lazytest/clojure_ext/core.clj
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
(ns lazytest.clojure-ext.core
(:require
[clojure.string :as str])
(:import
(java.util.regex Pattern)))

Expand All @@ -16,8 +18,11 @@
:comments Pattern/COMMENTS})

(defn re-compile
([s] (re-pattern s))
([s & flags]
"Returns an instance of java.util.regex.Pattern, for use, e.g. in `re-matcher`.

If given only a string, acts as `re-pattern`. If given a string and trailing keywords, treats the keywords as java.util.regex.Pattern flags (cf. [[pattern-flags]]), using `bit-and` to merge them before passing them to `Pattern/compile`."
(^Pattern [s] (re-pattern s))
(^Pattern [s & flags]
(assert (every? pattern-flags flags))
(let [flags (map pattern-flags flags)]
(if (= 1 (count flags))
Expand All @@ -26,3 +31,20 @@

(comment
(re-find (re-compile ".*#comment\n" :dotall :comments) "a\nb"))

(defn ^:no-doc get-arg
"For internal use only.
Pops first argument from args if (pred arg) is true.
Returns a vector [first-arg remaining-args] or [nil args]."
[args pred]
(if (pred (first args))
[(first args) (next args)]
[nil args]))

(defn ->keyword
"Convert strings with optional leading colons to keywords.

\"foo\" -> :foo
\":foo\" -> :foo"
[s]
(keyword (if (str/starts-with? s ":") (subs s 1) s)))
Loading
Loading