solcover fail to generate test coverage with my simple add contract - test-coverage

I want to use solcover to generate test coverage of my contract.
https://github.com/JoinColony/solcover
I test it with the simple one:
contract Add {
function Add() {
}
function sum(uint x, uint y) returns (uint) {
return (x+y);
}
}
And here is my test code:
contract('Add', function(accounts) {
it("should return 5 when add 2 and 3", function() {
var add = Add.deployed();
return add.sum.call(2,3).then(function(res){
assert.equal(res.valueOf(), 5, "add result is 5");
});
});
});
But there are some errs when compile it.
Add.sol:2:1: Warning: Source file does not specify required compiler version!Consider adding "pragma solidity ^0.4.6
contract Add {
^
Spanning multiple lines.
Compilation failed. See above.
fs.js:549
Then i add compile version like this:
pragma solidity ^0.4.6;
contract Add {
function Add() {
}
function sum(uint x, uint y) returns (uint) {
return (x+y);
}
}
And now it pass the compile. But this time I got the error:
cp: no such file or directory: ./../originalContracts/Migrations.sol
rm: no such file or directory: ./allFiredEvents
Compiling Add.sol...
Contract: Add
✓ should return 5 when add 2 and 3
1 passing (15s)
fs.js:549
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
^
Error: ENOENT: no such file or directory, open './allFiredEvents'
at Error (native)
at Object.fs.openSync (fs.js:549:18)
at Object.fs.readFileSync (fs.js:397:15)
at Object.<anonymous> (/Users/maiffany/graduate/mytest/solcover/runCoveredTests.js:60:13)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
And in the runCoveredTests.js I found this:
55:shell.cp("./../originalContracts/Migrations.sol",./../contracts/Migrations.sol");
56:
57:shell.rm('./allFiredEvents'); //Delete previous results
58:shell.exec('truffle test --network coverage');
59:
60:events = fs.readFileSync('./allFiredEvents').toString().split('\n')
I guess maybe it is this command that generate file "allFiredEvents". So i try this in my command line:
truffle test --network coverage
Compiling Add.sol...
Contract: Add
✓ should return 5 when add 2 and 3
1 passing (24s)
But i still can't find the file "allFiredEvents".
So where did i get wrong?

Related

How to pass to Frida a .ts file which depends on another .ts

I have following .ts files
core.ts
interface Signature {
args: string[];
ret?: string;
}
const subject = 'hook'
const now = () => (new Date()).getTime()
const readable = (type: string, arg: NativePointer) => (type === 'char *' ? arg.readUtf8String() : arg)
export function hook(mod: string | null, symbol: string, signature: Signature) {
const p = Module.findExportByName(mod, symbol)
if (!p) throw new Error(`Function ${mod || 'global'}!${symbol} not found`)
const range = Process.findRangeByAddress(p)
if (!range?.protection.includes('x')) throw new Error('Invalid symbol, expected a function but received a data pointer')
const id = p.toString()
const lib = mod || Process.getModuleByAddress(p)!.name
const listener = Interceptor.attach(p, {
onEnter(args) {
const time = now()
const pretty = signature.args.map((type, i) => readable(type, args[i]))
const backtrace = Thread.backtrace(this.context, Backtracer.ACCURATE)
.map(DebugSymbol.fromAddress).filter(e => e.name)
this.backtrace = backtrace
send({
subject,
event: 'call',
args: pretty,
lib,
symbol,
backtrace,
time
})
},
onLeave(retVal) {
if (!signature.ret) return
const time = now()
const ret = readable(signature.ret, retVal)
send({
subject,
event: 'return',
lib,
symbol,
time,
backtrace: this.backtrace,
ret
})
}
})
return listener
}
sql-hooks.ts
// import { hook } from './core'
const { hook } = require('./core.ts')
ObjC.schedule(ObjC.mainQueue, function () {
enable()
});
function enable() {
console.log('enabled')
hook('libsqlite3.dylib', 'sqlite3_open', { args: ['char *', 'int'], ret: 'int' })
hook('libsqlite3.dylib', 'sqlite3_prepare_v2', { args: ['pointer', 'char *', 'int', 'pointer', 'pointer'] })
hook('libsqlite3.dylib', 'sqlite3_bind_int', { args: ['pointer', 'int', 'int'] })
hook('libsqlite3.dylib', 'sqlite3_bind_null', { args: ['pointer', 'int'] })
hook('libsqlite3.dylib', 'sqlite3_bind_text', { args: ['pointer', 'int', 'char *', 'int', 'pointer'] })
}
Then I used following command to connect these two files
frida-compile '/path/to/sql-hooks.ts' -o out.ts
Finally I used following command to actually use out.ts
frida -U -F -l '/path/to/out.ts'
But unfortunately I get this error
out.ts:1:1 - error TS1127: Invalid character.
out.ts:2:6 - error TS2304: Cannot find name 'sql'.
out.ts:2:10 - error TS2552: Cannot find name 'hooks'. Did you mean 'hook'?
out.ts:3:6 - error TS2304: Cannot find name 'sql'.
out.ts:3:10 - error TS2552: Cannot find name 'hooks'. Did you mean 'hook'?
out.ts:4:1 - error TS1127: Invalid character.
out.ts:5:11 - error TS1005: ';' expected.
out.ts:5:12 - error TS2695: Left side of comma operator is unused and has no side effects.
out.ts:5:20 - error TS1005: ';' expected.
out.ts:5:21 - error TS2695: Left side of comma operator is unused and has no side effects.
out.ts:5:48 - error TS1005: ';' expected.
out.ts:5:49 - error TS2695: Left side of comma operator is unused and has no side effects.
out.ts:5:105 - error TS1005: ';' expected.
out.ts:5:106 - error TS2695: Left side of comma operator is unused and has no side effects.
out.ts:5:130 - error TS1005: ';' expected.
out.ts:5:131 - error TS2695: Left side of comma operator is unused and has no side effects.
out.ts:5:144 - error TS1005: ';' expected.
out.ts:6:1 - error TS1127: Invalid character.
What am I doing wrong?
I bumped into a frida-compile example (from oleavr) and I found out I was doing a couple of things wrong. In particular I took a look at the agent folder and at the package.json scripts region.
I'm going to mention two files: sql-hooks.ts (which is my main.ts) and core.ts (which is my module.ts); both of them are inside the same folder.
I changed first line of sql-hooks.ts from
const { hook } = require('./core.ts')
to
import { hook } from './core.js'
Notice I imported core.ts as a .js
Then I used following command to connect sql-hooks.ts and core.ts
frida-compile '/path/to/sql-hooks.ts' -o out.js
Notice output extension is .js
And that's it, everything's gonna work fine.

In Playwright, how do I fix the error locator.evaluateAll: Evaluation failed: ReferenceError: _test is not defined?

I'm just getting started with Playwright so I don't know if there is something I'm missing. I do not have any other testing framework wired up to it. I'm using #playwright/test v1.14.1.
This test:
import { test, expect } from "#playwright/test";
test("focus sets tab indexes appropriately", async ({ page }) => {
await page.goto("http://localhost:3000/test");
const inputs = page.locator("input");
await expect(inputs).toHaveCount(5);
await inputs.evaluateAll(async (nodes) => {
console.log(nodes);
for (const node of nodes) {
console.log(node);
await expect(node.tabIndex).toBe(0);
}
});
});
is producing the following error:
locator.evaluateAll: Evaluation failed: ReferenceError: _test is not defined
at eval (eval at evaluate (:3:1339), <anonymous>:6:7)
at t.default.evaluate (<anonymous>:3:1362)
at t.default.<anonymous> (<anonymous>:1:44)
5 | const inputs = page.locator("input");
6 | await expect(inputs).toHaveCount(5);
> 7 | await inputs.evaluateAll(async (nodes) => {
| ^
8 | console.log(nodes);
9 | for (const node of nodes) {
10 | console.log(node);
If I remove the call to expect, the test passes but the console.log still will not fire off.
input.evaluateAll gets executed inside the browser which is a different execution context in which expect is not available (Node.js vs. e.g. Chromium).
See here: https://playwright.dev/docs/evaluating

Enum initializer as const

Are vala enums not integer based? This example generates a "c" compile error. Not a big deal, but would like to understand why.
const int INT_UNINITIALIZED = 999;
public enum ScopeTypes {
/*OSS:Fix:GLib requires a default value, set GLOBALS = 0
(VSCodeDbgSvr.exe:31979): GLib-GObject-CRITICAL **: g_param_spec_enum: assertion 'g_enum_get_value (enum_class, default_value) != NULL' failed*/
NONE = INT_UNINITIALIZED,
GLOBALS = 0,
ARGUMENTS,
LOCALS,
EXCEPTIONS,
TOT_SCOPE_TYPES;
//Vala enums may have methods:
public bool is_global() {
return (this == GLOBALS || this == EXCEPTIONS);
}
public bool is_function() {
return (this == ARGUMENTS || this == LOCALS);
}
public bool is_valid() {
return (this != NONE);
}
}
The compile output:
> Executing task: /opt/vala/bin/valac helloworld.vala class1.vala --pkg libvala-0.40 -X -I/opt/vala/include/vala-0.40 -X -O0 --vapidir=/opt/vala/share/vala/vapi --debug --save-temps -o helloworld.exe <
/media/george/SharedData/Projects/Vala/Examples/playground-2/helloworld.c:82:21: error: ‘INT_UNINITIALIZED’ undeclared here (not in a function)
SCOPE_TYPES_NONE = INT_UNINITIALIZED,
^~~~~~~~~~~~~~~~~
error: cc exited with status 256
Compilation failed: 1 error(s), 1 warning(s)
The terminal process terminated with exit code: 1
The relevant part of the error message is:
error: ‘INT_UNINITIALIZED’ undeclared here (not in a function)
The C compiler is complaining that it can not find the declaration of your constant. So it is not a type problem at all.
It is a scope / ordering problem.
If you compile the code with valac -C you get a .c file that looks something like this:
typedef enum {
SCOPE_TYPES_NONE = INT_UNINITIALIZED,
SCOPE_TYPES_GLOBALS = 0,
SCOPE_TYPES_ARGUMENTS,
SCOPE_TYPES_LOCALS,
SCOPE_TYPES_EXCEPTIONS,
SCOPE_TYPES_TOT_SCOPE_TYPES
} ScopeTypes;
#define INT_UNINITIALIZED 999
Note how the Vala compiler has reordered the code to declare the enum first and the constant later.
Since in C the order of declarations in a file is important this can not compile.
I would consider this to be a compiler bug and you may want to report this to the GNOME bugtracker (product Vala).

'Trying to open unclosed connection' error' using Mongoose and embedded documents

I'm getting a connection related error when defining a static query that filters an embedded document field.
I've tried to separate the embedded document in a separate schema file but didn't resolve the issue. Any ideas?
Error follows:
C:\development_GIT\myproject\app\models\mymodel.js:40
this.find({ text.lang_code: langCode }).sort('text.name').exec(callback);
^
Error: Trying to open unclosed connection.
at NativeConnection.Connection.open (C:\development_GIT\myproject\node_
modules\mongoose\lib\connection.js:205:15)
at Mongoose.connect (C:\development_GIT\myproject\node_modules\mongoose
\lib\index.js:156:15)
at Object.<anonymous> (C:\development_GIT\myproject\server.js:13:10)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at repl:1:1
The error is launched when using the filter { text.lang_code: langCode }
option in the following model. If I don't use the embedded document and try to filter for exampe { _id: langCode } it does not throw errors.
//MyModel.js located at ./app/models
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var MyModelSchema = new Schema({
name: { type: String, trim: true },
text: [{ name: String, lang_code: String }]
});
MyModelSchema .static({
findByLangCode : function(langCode, callback) {
this.find({ text.lang_code: langCode }).sort('text.name').exec(callback);
}
});
mongoose.model('MyModel', CategorySchema);
The first lines of my main file server.js are:
//server.js
var express = require('express');
var env = process.env.NODE_ENV || 'development';
var config = require('./config/config')[env];
var mongoose = require('mongoose');
var fs = require('fs');
require('express-namespace');
mongoose.connect(config.db);
// Bootstrap models
fs.readdirSync(__dirname + '/app/models').forEach(function (file) {
if (~file.indexOf('.js')) require(__dirname + '/app/models/' + file)
});
Solution was building the query in a different way. It seems that subdocuments can not be used inside find().
Before: (not working)
this.find({ text.lang_code: langCode }).sort('text.name').exec(callback);
After (working)
this.find().where('text.lang_code').equals(langCode).sort('text.name').exec(callback);
Im using this all the time and it works fine for me.
this.find({ 'text.lang_code': langCode }).sort('text.name').exec(callback);
MongoDb can only handle one lvl of objects, but if you give it a string like you are doing in the .where function, mongodb will do magic and match it to subdocuments :)

Node.js consumption of json from Rails app

I have a json string (coming from my Rails app):
http://localhost:3000/employees/1.json
How do I get my Node.js app to consume this data?
This is the code I have in my Node.js app right now:
var employees = JSON.parse("http://localhost:3000/employees.json")
This is the error I'm getting:
prompt$ node app.js
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
SyntaxError: Unexpected token h
- at Object.parse (native)
- at Object. (/Documents/Coding/dustin/employees.js:19:22)
- at Module._compile (module.js:441:26)
- at Object..js (module.js:459:10)
- at Module.load (module.js:348:31)
- at Function._load (module.js:308:12)
- at Module.require (module.js:354:17)
- at require (module.js:370:17)
- at Object. (/Documents/Coding/dustin/app.js:34:17)
- at Module._compile (module.js:441:26)
See this question:
Using Node.JS, how do I read a JSON object into (server) memory?
You should read the file first and then parse it.
var employees = JSON.parse(fs.readFileSync('employees.json', 'utf8'));
If for some reason your Rails app runs on some other machine, you need to make a http request for that. You could try this:
var site = http.createClient(port, host);
var request = site.request("GET", pathname, {'host' : host});
request.end();
request.on('response', function(response) {
var json = '';
response.on('data', function(chunk) {
json += chunk;
});
response.on('end', function () {
employees = JSON.parse(json);
});
});

Resources