forked from clj-python/libpython-clj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclasses_test.clj
72 lines (66 loc) · 3.29 KB
/
classes_test.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
(ns libpython-clj2.classes-test
(:require [libpython-clj2.python :as py]
[clojure.test :refer :all]
[clojure.edn :as edn]))
(py/initialize!)
(deftest new-cls-test
;;The crux of this is making instance functions to get the 'self' parameter
;;passed in.
(let [cls-obj (py/create-class
"Stock" nil
{"__init__" (py/make-instance-fn
(fn [self name shares price]
;;Because we did not use an arg-converter, all the
;;arguments above are raw jna Pointers - borrowed
;;references.
(py/set-attrs! self {"name" name
"shares" shares
"price" price})
;;If you don't return nil from __init__ that is an
;;error.
nil))
"cost" (py/make-instance-fn
(fn [self]
(* (py/py.- self shares)
(py/py.- self price)))
{:name "cost"})
"__str__" (py/make-instance-fn
(fn [self]
(pr-str {"name" (py/py.- self name)
"shares" (py/py.- self shares)
"price" (py/py.- self price)})))
"kw_clj_fn" (py/make-kw-instance-fn
(fn [pos-args kw-args]
(let [self (first pos-args)
price (double (py/py.- self price))]
;;keywords become strings!!
(apply + price (get kw-args "a" 5)
(drop 1 pos-args)))))
"clsattr" 55})
new-instance (cls-obj "ACME" 50 90)]
(is (= 4500
(py/$a new-instance cost)))
(is (= 55 (py/py.- new-instance clsattr)))
(is (= {"name" "ACME", "shares" 50, "price" 90}
(edn/read-string (.toString new-instance))))
(is (= 116.0 (py/call-attr-kw new-instance "kw_clj_fn" [1 2 3] {:a 20})))
(is (= 101.0 (py/call-attr-kw new-instance "kw_clj_fn" [1 2 3] nil)))
))
(deftest new-kw-init-cls-test
;;The crux of this is making instance functions to get the 'self' parameter
;;passed in.
(let [cls-obj (py/create-class
"Stock" nil
{"__init__" (py/make-kw-instance-fn
(fn [[self :as args] {:as kwargs}]
(py/set-attr! self "kwargs" kwargs)
;;Because we did not use an arg-converter, all the
;;arguments above are raw jna Pointers - borrowed
;;references.
;;If you don't return nil from __init__ that is an
;;error.
nil))})
new-instance (py/cfn cls-obj "ACME" 50 :a 1 :b 2)
dict (py/get-attr new-instance "kwargs")]
(is (= {"a" 1 "b" 2}
(py/->jvm dict)))))