node-gyp c++ leak test with valgrind - c++

Quite simply, how can I do a leak test for a node-gyp c++ module I've just written? Most of the imported c++ code has been tested in different projects, but I would like to make sure there are no leaks.
AFAIK, the only execution mode I've seen is via node:
var wv = require('./build/Release/word_vec.node');
var json = JSON.parse(require('fs').readFileSync('amazon.json', 'utf8'));
var res = wv.convert_sparse(json, 5, 6, 0);
var fs = require('fs');
fs.writeFile("output", JSON.stringify(res), function(err) {
if(err) {
return console.log(err);
}
});
The function I want checked is convert_sparse which resides in word_vec.cpp and is compiled in ./build/Release/word_vec.node or the equivalent debug sub-directory.

Related

.net core 6 jwt token mocking

I am looking for a tutorial on how to mock authentication tokens for .net core 6 web services. Some years ago, at a previous job, I looked up how to do this with .net 3 and got it to work. But 6 removed the startup.cs file and seems to have shifted things around quite a bit. There are very few examples of doing this for 6.
I am in the process of creating a series of unit tests for the endpoints in a new web application. I am starting over from bare bones. Here is the code example. I know that it is possible to recreate the Startup.cs file, but for the time being I would prefer to do it without that. Are there any examples of this for a .net 6 specific architecture?
internal class DssiApiTest : WebApplicationFactory<Program>
{
private readonly string _environment;
public DssiApiTest(string environment = "Development")
{
_environment = environment;
}
protected override IHost CreateHost(IHostBuilder builder)
{
builder.UseEnvironment(_environment);
var settings = new ApiSettings();
// Add mock/test services to the builder here
builder.ConfigureServices(services =>
{
services.AddScoped(sp =>
{
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase("Tests")
.UseApplicationServiceProvider(sp)
.Options;
using (var context = new ApplicationDbContext(options,
MakeMockTenantService(),
(Microsoft.Extensions.Options.IOptions<ApiSettings>)settings))
{
context.PartCustomers.Add(CreatePartCustomer(1, 1));
context.PartCustomers.Add(CreatePartCustomer(2, 1));
context.SaveChanges();
}
// Replace SQLite with in-memory database for tests
return options;
});
});
return base.CreateHost(builder);
}
}
I think I found the answer to what I needed to do. I have not been able to fully test it yet, however, because I am running into another issue that is throwing an error. Will have to ask another question for that one. Here is what I have so far. If anyone can elaborate or correct this please feel free to do so. Like I said, I have not fully tested it and don't want to lead others astray. Will update once I have it worked out.
I added a new TestAuthHandler to the virtual client that returns a mock auth result like so :
using var application = new TestWebApplicationFactory();
var client = application.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
services.AddAuthentication("Test")
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
"Test", options => { });
});
})
.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false,
});
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Test");
Here is the code for the TestAuthHandler
public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
public TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var claims = new[] { new Claim(ClaimTypes.Name, "Test user") };
var identity = new ClaimsIdentity(claims, "Test");
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, "Test");
var result = AuthenticateResult.Success(ticket);
return Task.FromResult(result);
}
}

host.json not respected by Visual Studio or web job

I have a queue processing application which is workign fine. I am now trying to persuade the queue trigger to only process one item at a time. My host.json is set up correctly, I think:
But when I run the app (either in Azure as a web job, or locally in Visual Studio), I see this:
I suspect that I am missing something really obvious, so wondering whether anyone has come across this before. I have found a few articles, but nothing that gives me any insight into what I am doing wrong.
Adding the contents of program.cs. I have tried adding "host.json" after the AddAzureAppConfiguration entry, but that makes no difference.
class Program
{
static async Task Main()
{
//var builder = new HostBuilder();
var builder = Host.CreateDefaultBuilder();
builder.ConfigureLogging((context, a) =>
{
a.AddConsole();
});
builder.ConfigureAppConfiguration((hostContext, config) =>
{
config.AddUserSecrets(
"5aa19112-5ff7-467b-b062-f37c3654872d"); // This is automatic for a web app, but not for a console app
var settings = config.Build();
var connectionString = settings.GetConnectionString("AzureAppConfiguration");
config.AddAzureAppConfiguration(connectionString);
});
builder.ConfigureWebJobs(b =>
{
b.AddAzureStorageCoreServices();
b.AddAzureStorage();
});
builder.ConfigureServices((hostContext, services) =>
{
services.AddMemoryCache();
});
var host = builder.Build();
using (host)
{
await host.RunAsync();
}
}
}
I think you are using the Azure WebJobs SDK v3.x. In v3.x, hosts.json does not work for WebJob.
Instead, version 3.x uses the standard ASP.NET Core APIs, so you need to configure it using the ConfigureWebJobs method:
static async Task Main()
{
var builder = new HostBuilder();
builder.ConfigureWebJobs(b =>
{
b.AddAzureStorageCoreServices();
b.AddAzureStorage(a => {
a.BatchSize = 8;
a.NewBatchThreshold = 4;
a.MaxDequeueCount = 4;
a.MaxPollingInterval = TimeSpan.FromSeconds(15);
});
});
var host = builder.Build();
using (host)
{
await host.RunAsync();
}
}
Docs: https://learn.microsoft.com/pt-pt/azure/app-service/webjobs-sdk-how-to#queue-storage-trigger-configuration

Embedded Node execute .node file

I've built an embedded instance of Node using the Embed_Test example from the Node repository.
Using this instance, I am trying to execute some C++ code.
I have a generated .node and .dll, and I have webpack'd my Javascript file.
When I run,
node dist/bundle.js
It runs fine. However, when I start up my embedded NodeJS application and attempt to run bundle.js, I get the following error (it's as if it cannot load the .node file?):
TypeError: Cannot read property 'testCppCode' of undefined
at evalmachine.<anonymous>:154:2305
at s.handle_request (evalmachine.<anonymous>:120:782)
at s (evalmachine.<anonymous>:113:879)
at p.dispatch (evalmachine.<anonymous>:113:901)
at s.handle_request (evalmachine.<anonymous>:120:782)
at evalmachine.<anonymous>:106:2533
at Function.v.process_params (evalmachine.<anonymous>:106:3436)
at g (evalmachine.<anonymous>:106:2476)
at evalmachine.<anonymous>:259:218
at s.handle_request (evalmachine.<anonymous>:120:782)
This is my App.js, before a webpack:
var myArgs = process.argv.slice(2);
var ip = myArgs.length >= 1 ? myArgs[0] : "localhost";
var port = myArgs.length >= 2 ? myArgs[1] : "5555";
var fs = require("fs");
var path = require("path");
const express = require("express");
var addon = require("../build/Release/test.node");
const server = express();
server.get("/", (req, res) => {
var res = addon.testCppCode("Sample", function (err, cpp) {
var capabilitiesResult = cpp;
if (err) {
console.log("Error!");
console.log(err);
console.log(cpp);
} else {
console.log("Success!");
}
});
});
I've tried sticking the test.node and test.dll in the same folder as the embedded instance of node, I've tried putting it in the same dir as the webpack, I've tried sticking it in a relative dir to the embedded node (so it would be at ../build/Release/) -- but the error is always the same. What do I need to do in order to get it to "see" the .node file?

How can I see the file system nature of my Node.js Cloud Function environment?

When I deploy my Cloud Function to GCP (written in Node.js), how can I see my file system environment for debugging purposes? What if I want to know what my current directory is or what files are present alongside my application?
When we deploy a Cloud Function, the full Node.js environment is present. We can run arbitrary Node.js logic within. This includes logging information which will then show in the Stackdriver logs. We can thus log our current working directory path as well as a list of all the files in our current directory. We can use this as a diagnostic aid. Here is an example:
const fs = require('fs');
exports.helloWorld = (req, res) => {
console.log(`CWD: ${process.cwd()}`);
fs.readdir('.', function (err, files) {
if (err) {
return console.log('Unable to scan directory: ' + err);
}
files.forEach(function (file) {
console.log(file);
});
res.status(200).send('Done!');
});
};
You can incorporate this logic in your own apps for testing.
And here is an alternate version which shows a recursive listing of all files and sub directories.
const fs = require('fs');
const walk = function(dir) {
var results = [];
var list = fs.readdirSync(dir);
list.forEach(function(file) {
file = dir + '/' + file;
var stat = fs.statSync(file);
if (stat && stat.isDirectory()) {
results = results.concat(walk(file));
} else {
results.push(file);
}
});
return results;
}
exports.helloWorld = (req, res) => {
let message = req.query.message || req.body.message || 'Hello World!';
console.log(`CWD: ${process.cwd()}`);
console.log(`Dir Listing: ${walk('.')}`);
res.status(200).send('Done!');
};
All credit to the above algorithm to node.js fs.readdir recursive directory search.

How to generate icon for onesignal using ionic

I am using ionic 2.
I need generate the icon for one signal notification.
I tried to this
Add a file to your hooks directory inside the after_prepare folder called 030_copy_android_notification_icons.js
Put the following code in it:
var filestocopy = [{
"resources/android/icon/drawable-hdpi-icon.png":
"platforms/android/res/drawable-hdpi/ic_stat_onesignal_default.png"
}, {
"resources/android/icon/drawable-mdpi-icon.png":
"platforms/android/res/drawable-mdpi/ic_stat_onesignal_default.png"
}, {
"resources/android/icon/drawable-xhdpi-icon.png":
"platforms/android/res/drawable-xhdpi/ic_stat_onesignal_default.png"
}, {
"resources/android/icon/drawable-xxhdpi-icon.png":
"platforms/android/res/drawable-xxhdpi/ic_stat_onesignal_default.png"
}, {
"resources/android/icon/drawable-xxxhdpi-icon.png":
"platforms/android/res/drawable-xxxhdpi/ic_stat_onesignal_default.png"
} ];
var fs = require('fs');
var path = require('path');
// no need to configure below
var rootdir = process.argv[2];
filestocopy.forEach(function(obj) {
Object.keys(obj).forEach(function(key) {
var val = obj[key];
var srcfile = path.join(rootdir, key);
var destfile = path.join(rootdir, val);
//console.log("copying "+srcfile+" to "+destfile);
var destdir = path.dirname(destfile);
if (fs.existsSync(srcfile) && fs.existsSync(destdir)) {
fs.createReadStream(srcfile).pipe(
fs.createWriteStream(destfile));
}
});
});
I have no idea.
Kindly advice me,
Thanks
I have faced with same issue. Your way is correct, putting 030_copy_android_notification_icons.js file under {root}/hooks/after_prepare. Also note that, filename is not important.
Then to run script you need to run below comment:
ionic cordova prepare android
With this, your script will be run. But maybe your problem may be similar to mine. If you use windows, while coping files from resources/android/icon/ to platforms/android/res/, because of missing of target folders, script is not able to copy operation. That's why a simple code should be added to code.
var destdir = path.dirname(destfile);
if (!fs.existsSync(destdir)){
fs.mkdirSync(destdir);
}