hy/tests/native_tests/with_decorator.hy
Kodi Arfer e4a7b317e1 Make fn work like lambda and remove lambda (#1228)
* with-decorator: Allow a `setv` form as the form to be decorated

This feature is of dubious value by itself, but it's necessary to allow `defn` to create a lambda instead of a `def`.

* Make `fn` work the same as `lambda`

That is, allow it to generate a `lambda` instead of a `def` statement if the function body is just an expression.

I've removed two uses of with_decorator in hy.compiler because they'd require adding another case to HyASTCompiler.compile_decorate_expression and they have no ultimate effect, anyway.

In a few tests, I've added a meaningless statement in `fn` bodies to force generation of a `def`.

I've removed `test_fn_compiler_empty_function` rather than rewrite it because it seems like a pain to maintain and not very useful.

* Remove `lambda`, now that `fn` does the same thing
2017-02-22 17:36:52 -06:00

48 lines
1.0 KiB
Hy

(defn test-decorated-1line-function []
(defn foodec [func]
(fn [] (+ (func) 1)))
(with-decorator foodec
(defn tfunction []
(* 2 2)))
(assert (= (tfunction) 5)))
(defn test-decorated-multiline-function []
(defn bazdec [func]
(fn [] (+ (func) "x")))
(with-decorator bazdec
(defn f []
(setv intermediate "i")
(+ intermediate "b")))
(assert (= (f) "ibx")))
(defn test-decorated-class []
(defn bardec [cls]
(setv cls.attr2 456)
cls)
(with-decorator bardec
(defclass cls []
[attr1 123]))
(assert (= cls.attr1 123))
(assert (= cls.attr2 456)))
(defn test-decorated-setv []
(defn d [func]
(fn [] (+ (func) "z")))
(with-decorator d
(setv f (fn [] "hello")))
(assert (= (f) "helloz")))
(defn test-decorator-clobbing []
"NATIVE: Tests whether nested decorators work"
(do
(defn dec1 [f] (defn k [] (+ (f) 1)))
(defn dec2 [f] (defn k [] (+ (f) 2)))
(with-decorator dec1
(with-decorator dec2
(defn f [] 1)))
(assert (= (f) 4))))