diff --git a/src/darkleaf/di/core.clj b/src/darkleaf/di/core.clj index df2c317e..74a5c718 100644 --- a/src/darkleaf/di/core.clj +++ b/src/darkleaf/di/core.clj @@ -601,12 +601,19 @@ (defn- stop-fn [variable] (-> variable meta (::stop (fn no-op [_])))) +(defn- validate-obj! [obj variable] + (when (nil? obj) + (throw (ex-info "A component fn must not return nil" + {:type ::nil-return + :variable variable})))) + (defn- var->0-component [variable] (let [stop (stop-fn variable)] (reify p/Factory (dependencies [_]) (build [_ _] - (variable)) + (doto (variable) + (validate-obj! variable))) (demolish [_ obj] (stop obj))))) @@ -617,7 +624,8 @@ (dependencies [_] deps) (build [_ deps] - (variable deps)) + (doto (variable deps) + (validate-obj! variable))) (demolish [_ obj] (stop obj))))) @@ -650,8 +658,9 @@ [0] (var->0-component variable) [1] (var->1-component variable) (throw (ex-info - "The component must only have 0 or 1 arity" - {:variable variable + "A component fn must only have 0 or 1 arity" + {:type ::invalid-arity + :variable variable :arities arities}))) #_service (case arities [0] (var->0-service variable) diff --git a/test/darkleaf/di/component_test.clj b/test/darkleaf/di/component_test.clj new file mode 100644 index 00000000..9049661e --- /dev/null +++ b/test/darkleaf/di/component_test.clj @@ -0,0 +1,33 @@ +(ns darkleaf.di.component-test + (:require + [clojure.test :as t] + [darkleaf.di.core :as di] + [darkleaf.di.test-utils :refer [catch-some]])) + +(defn nil-component-0-arity + {::di/kind :component} + [] + nil) + +(defn nil-component-1-arity + {::di/kind :component} + [-deps] + nil) + +(t/deftest nil-component-0-arity-test + (let [ex (catch-some (di/start `nil-component-0-arity))] + (t/is (= ::di/nil-return (-> ex ex-cause ex-data :type))))) + +(t/deftest nil-component-1-arity-test + (let [ex (catch-some (di/start `nil-component-1-arity))] + (t/is (= ::di/nil-return (-> ex ex-cause ex-data :type))))) + + +(defn component-2-arity + {::di/kind :component} + [deps extra-arg] + :smth) + +(t/deftest component-2-arity-test + (let [ex (catch-some (di/start `component-2-arity))] + (t/is (= ::di/invalid-arity (-> ex ex-data :type)))))