I get this error when I Deploy a Hello World contract with Kadena Chainweaver on VM (https://chainweaver-builds.s3.amazonaws.com/2.2/kadena-chainweaver-vm-2.2.0.1.ova):
Failure: Tx Failed: Keyset failure (keys-any)
This is the contract I'm trying to Deploy(It's the default hello world that exists when you create a chainweaver account):
;;
;; "Hello, world!" smart contract/module
;;
;; To try it out, click "Load into REPL" and type into the repl:
;; (free.hello-world.set-message "universe")
;; (free.hello-world.greet)
;;
;; Check lines 21 and 34 to play with Formal Verification
;;
(namespace "free")
;; Define the module.
(module hello-world MODULE_ADMIN
"A smart contract to greet the world."
; no-op module admin for example purposes.
; in a real contract this could enforce a keyset, or
; tally votes, etc.
(defcap MODULE_ADMIN () true)
(defschema message-schema
#doc "Message schema"
#model [(invariant (!= msg ""))]
msg:string)
(deftable
message:{message-schema})
(defun set-message
(
m:string
)
"Set the message that will be used next"
; uncomment the following to make the model happy!
;(enforce (!= m "") "set-message: must not be empty")
(write message "0" {"msg": m})
)
(defun greet ()
"Do the hello-world dance"
(with-default-read message "0" { "msg": "" } { "msg":= msg }
(format "Hello {}!" [msg])))
)
(create-table message)
(set-message "world")
(greet)
Failure: Tx Failed: Keyset failure (keys-any)
The problem is sovled when I changed the module name from hello-world to something else.
Change this:
;; Define the module.
(module hello-world MODULE_ADMIN
"A smart contract to greet the world."
to this:
;; Define the module.
(module hello-world-YOUR-UNIQUE-NAME MODULE_ADMIN
"A smart contract to greet the world."
Related
When running a janet test suite with the jpm command there is no listing of test cases.
$ jpm test
running test/test.janet ...
Failed: (= "hello" "holla")
Expected: "hello"
Actual: "holla"
Test: this should faild
Tests: 1/3 passed
Duration: 0.000 seconds
What I am looking for is to have an output similar to the one that you see when you run go test -v or pytest -v.
This is possible if one uses testament:
With testament the tests are written as:
(import testament :prefix "" :exit true)
(deftest one-plus-one
(is (= 2 (+ 1 1)) "1 + 1 = 2"))
(deftest two-plus-two
(is (= 5 (+ 2 2)) "2 + 2 = 5"))
(deftest test-should-fail
(is (= "hello" "holla") "should fail"))
Each test case is defined as:
(deftest <testname> (is <assertion>) <note>)
Testament allows defining a function which will be called after each test:
(set-on-result-hook reporter)
(run-tests!)
In this case, reporter can be defined as:
(defn reporter
"pretty report"
[result]
(var symbol "\e[31m✕\e[0m")
(if (result :passed?) (set symbol "\e[32m✓\e[0m"))
(print symbol " " (result :note))
)
The result will be:
$ jpm test
running test/test.janet ...
✓ 1 + 1 = 2
✕ should fail
✕ 2 + 2 = 5
> Failed: two-plus-two
Assertion: 2 + 2 = 5
Expect: 5
Actual: 4
> Failed: test-should-fail
Assertion: should fail
Expect: "hello"
Actual: "holla"
-----------------------------------
3 tests run containing 3 assertions
1 tests passed, 2 tests failed
-----------------------------------
In a Linux terminal the x will be red, and ✓ will be green.
The complete test code:
$ cat test/testam.janet
(import testament :prefix "" :exit true)
(deftest one-plus-one
(is (= 2 (+ 1 1)) "1 + 1 = 2"))
(deftest two-plus-two
(is (= 5 (+ 2 2)) "2 + 2 = 5"))
(deftest test-should-fail
(is (= "hello" "holla") "should fail"))
(defn reporter
"pretty report"
[result]
(var symbol "\e[31m✕\e[0m")
(if (result :passed?) (set symbol "\e[32m✓\e[0m"))
(print symbol " " (result :note))
)
(set-on-result-hook reporter)
(run-tests!)
I am trying usgin library clj-kafka.
Here my code
(use [clj-kafka.producer]
[clj-kafka.zk]
[clj-kafka.consumer.zk]
[clj-kafka.core]))
(brokers {"zookeeper.connect" "localhost:2181"})
(def p (producer {"metadata.broker.list" "localhost:9092"
"serializer.class" "kafka.serializer.DefaultEncoder"
"partitioner.class" "kafka.producer.DefaultPartitioner"}))
(send-message p (message "test" (.getBytes "this is my message")))
(def config {"zookeeper.connect" "localhost:2181"
"group.id" "clj-kafka.consumer"
"auto.offset.reset" "smallest"
"auto.commit.enable" "false"})
(with-resource [c (consumer config)]
shutdown
(take 2 (messages c "test"))) ;; return ()
I start zookepper-server and kafka itself with
bin/zookeeper-server-start.sh config/zookeeper.properties
bin/kafka-server-start.sh config/server.properties
The config/zookepper.properties:
dataDir=/tmp/zookeeper
clientPort=2181
maxClientCnxns=0
and config/server.properties:
broker.id=0
listeners=PLAINTEXT://:9092
num.network.threads=3
num.io.threads=8
socket.send.buffer.bytes=102400
zocket.receive.buffer.bytes=102400
socket.request.max.bytes=104857600
log.dirs=/tmp/kafka-logs
num.partitions=1
num.recovery.threads.per.data.dir=1
log.retention.hours=168
log.segment.bytes=1073741824
log.retention.check.interval.ms=300000
zookeeper.connect=localhost:2181
zookeeper.connection.timeout.ms=6000
The 'problem' is when I execute:
(with-resource [c (consumer config)]
shutdown
(take 2 (messages c "test"))) ;; return empty ()
Any idea here?
Thanks in advance
See this github issue. Seems the documentation isn't great. You have to force the realization of the sequence (which is lazy) with doall. try this:
(with-resource [c (consumer config)]
shutdown
(doall (take 2 (messages c "test"))))
I'm just started to learn Elixir.
I'm trying to test exception with espec (https://github.com/antonmi/espec) and I stucked.
Here is my function
defp call_xml(request_body) do
resp = HTTPotion.post("http://foo.bar", [body: request_body, headers: ["Content-Type": "text/xml"]])
if resp.status_code in [200, 201] do
{:ok, elem(XMLRPC.decode(resp.body), 1).param}
else
raise AbpError, message: "Message body"
end
end
def create_some_stuff(a, b, c) do
req = %XMLRPC.MethodCall{method_name: "Foo.Bar",
params:[a, b, c]} |> XMLPRC.encode!
call_xml(req)
end
# tests
use ESpec
use HyperMock
import :meck
context "when exception rised" do
it "returns err message" do
# stubbed with :meck
expect(MyModule, : create_some_stuff, fn("foo", "bar", "baz") -> raise CustomError end)
expect(MyModule. create_some_stuff("foo", "bar", "baz")).to eq("???")
end # it
end
In that case I'm getting error raised in my expectation
** (AbpError) Error occured!
spec/lib/ex_abpclient_spec.exs:135: anonymous fn/7 in ExAbpclientSpec.example_returns_created_payback_eqcpjlrszudikwyovtmxbgfnha/1
(ex_abpclient) ExAbpclient.create_payment_payback("tr-TR", 10966, 10, "R", 495, 10, "DESC")
spec/lib/ex_abpclient_spec.exs:136: ExAbpclientSpec.example_returns_created_payback_eqcpjlrszudikwyovtmxbgfnha/1
(espec) lib/espec/example_runner.ex:33: ESpec.ExampleRunner.run_example/2
(elixir) lib/enum.ex:1088: Enum."-map/2-lists^map/1-0-"/2
(elixir) lib/enum.ex:1088: Enum."-map/2-lists^map/1-0-"/2
(espec) lib/espec/runner.ex:70: ESpec.Runner.run_examples/1
(espec) lib/espec/runner.ex:43: ESpec.Runner.do_run/2
How can I get stubbed exception?
Thanks in advance.
UPDATE
I tried to use HyperMock (https://github.com/stevegraham/hypermock) to stub the request, but with no luck too
context "when payback created" do
it "returns created payback" do
HyperMock.intercept do
request = %Request{body: "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall>.....",
headers: ["Content-Type": "text/xml"],
method: :post,
uri: "http://foo.bar/webApiXmlRpcServlet"}
response = %Response{body: "fooooo", status: 500}
stub_request request, response
expect MyModule.create_some_stuff("a", "b", "c") |> to(raise_exception AbpError, "fooooo")
end
end # it
end # exception
Here is the result
/Users/retgoat/workspace/offside/ex_abpclient/spec/lib/ex_abpclient_spec.exs:135
** (AbpError) Error: "fooooo"
(ex_abpclient) lib/ex_abpclient.ex:55: ExAbpclient.call_xml/1
spec/lib/ex_abpclient_spec.exs:143: ExAbpclientSpec.example_returns_created_payback_nqfwohpurlvtzskdjxigeybamc/1
(espec) lib/espec/example_runner.ex:33: ESpec.ExampleRunner.run_example/2
(elixir) lib/enum.ex:1088: Enum."-map/2-lists^map/1-0-"/2
(elixir) lib/enum.ex:1088: Enum."-map/2-lists^map/1-0-"/2
(espec) lib/espec/runner.ex:70: ESpec.Runner.run_examples/1
(espec) lib/espec/runner.ex:43: ESpec.Runner.do_run/2
(espec) lib/espec/runner.ex:28: ESpec.Runner.handle_call/3
10 examples, 1 failures
Finished in 1.28 seconds (0.14s on load, 1.14s on specs)
Exception is rised, but I can't test it.
Roman!
You must pass a function to expect, not a result of a function call.
So, just wrap MyModule.create_some_stuff("a", "b", "c") by fn -> end like you do in the ExUnit expample:
elixir
it "raises exception" do
expect(fn -> MyModule.create_some_stuff("a", "b", "c") end)
|> to(raise_exception AbpError, "fooooo")
end
I'm trying to found a better way of handle exceptions in clojure, I'm using https://github.com/alaisi/postgres.async which thrown an exeption when fail, but I would prefer return false (because I'm using a validator) or even better something like a Either monad (or something more simple like this http://adambard.com/blog/acceptable-error-handling-in-clojure/ )
1) I'm trying to catch the exception and if exist return false, but the code doesnt works (doesnt return false and thrown the exception).
(try
(dosql [tx (<begin! db)
ucount (<execute! tx ["UPDATE groups SET garticlescounter=garticlescounter + 1 WHERE gid=$1"
groupid])
uartc (<execute! tx ["UPDATE subtopics SET starticlescount=starticlescount + 1 WHERE stid=$1"
sid])
uartins (<insert! tx
{:table "articles"}
{:aurl url :atitle title :asuttopicid sid :acommentcount 0 :alikescount 0 :auid uid})
ok? (<commit! tx)]
ok?)
(catch Exception _ false))
2)would be possible wrap in a way where if works return ok? and if doesnt works return false, or maybe [ok? nil] and [nil error] maybe a macro?
----thanks to swinn I did this
;must receive an optional parameter for error response or
; build a [nil ok] response but just know this works for me...
(defmacro async-try-block! [block]
`(let [chn# (!/chan 1)]
(!/go
(let [response# (try
~block
(catch Throwable e#))]
(if (instance? Throwable response#) (!/put! chn# false) (!/put! chn# response#))))
chn#))
(async-try-block!
(dosql [tx (<begin! db)
ucount (<execute! tx ["UPDATE groups SET garticlescounter=garticlescounter + 1 WHERE gid=$1"
groupid])
uartc (<execute! tx ["UPDATE subtopics SET starticlescount=starticlescount + 1 WHERE stid=$1"
sid])
uartins (<insert! tx
{:table "articles"}
{:aurl url :atitle title :asuttopicid sid :acommentcount 0 :alikescount 0 :auid uid})
ok? (<commit! tx)]
ok?))
I'm not familiar with the postgres.async library, butException is not the root of all Exceptions in the JVM, Throwable is.
Changing your catch to Throwable would be the first change I would suggest, but it seems that (<execute! ...) actually catches the exception for you and returns it, so you need to check the return value using (instance? Throwable)
New to Clojure and wondering how to use it to make other languages I program in easier.
One thing I would like to be able to do is use Clojure for code generation.
For example, given the input from a data file (EDN format) how should I (1) walk this structure or (2) push the data into an existing templating mechanism?
Data below would be for defining simple REST API so that you could generate Clients from it. Generate clients in multiple languages by using different templates.
(:restcall "GetAccountBalance"
{:method "GET" :path "account/balance"}
{:id int})
(:restcall "GetLastTransactions"
{:method "GET" :path "account/transactions"}
{:page int})
resulting code would be something like
public void GetAccountBalance(int id)
{
var input = new { id = id };
callIntoRestLibrary("GET", "account/balance", input);
}
public void GetLastTransactions(int page)
{
var input = new { page = page };
callIntoRestLibrary("GET", "account/transactions", input);
}
Note: my end goal would having these as System.Net.Http.HttpClient calls via C#, but also be able to translate these into JavaScript/Ajax calls also
You have several choices for templating with Clojure. One place to look is the Clojure Toolbox.
Here is an example with clostache, a small library (358 loc) implementation of mustache.
(ns so.core
(:require [clostache.parser :refer (render)]))
(def template "
public void {{restcall}}({{id}} id)
{
var input = new { id = id };
callIntoRestLibrary(\"{{method}}\", \"{{path}}\", input);
}")
(def data
{:restcall "GetAccountBalance"
:method "GET" :path "account/balance" :id "int"})
(print (render template data))
Output:
public void GetAccountBalance(int id)
{
var input = new { id = id };
callIntoRestLibrary("GET", "account/balance", input);
}
To clear up confusion about what it means to read EDN.
(spit "foo.txt" (prn-str data))
Now the file foo.txt contains a textual representation of data, presumably your starting point.
(def data2 (with-open [r (java.io.PushbackReader. (java.io.FileReader. "foo.txt"))]
(clojure.edn/read r)))
(= data data2) ;=> true
So, read doesn't just pull in text, but also parses it into its data representation.