GitHub unit test can't access a file - electron

I work on an app in electron which need to read a CSV file, I have a few unit tests that work well on any device, but once in GitHub unit tests it can't find the file to read, even if it finds its folder, and even if the file has been pushed as intended etc.
I logged on my test both the folder and the file path and their existence, here what I get in output
const CSV_FOLDER = "./test/ressources/file/importCSV/"
const CSV_FILES = {
"ONE_PROJECT": CSV_FOLDER + "1ProjectExample.csv",
"MULTI_PROJECT": CSV_FOLDER + "MultipleProjectsExample.csv"
}
let testFolderAccess, testFileAccess = "untested";
beforeAll(async () => {
testFolderAccess = await checkPathAccessibility(CSV_FOLDER)
testFileAccess = await checkPathAccessibility(CSV_FILES.ONE_PROJECT)
})
test('Path are good', () => {
console.log(CSV_FOLDER)
console.log(testFolderAccess)
console.log(CSV_FILES.ONE_PROJECT)
console.log(testFileAccess)
})
Any idea on what could be the cause to all this?
Thanks!

Related

Run several insert/update at once with typeorm

I'm facing an issue with typeorm.
In order to init my database for my repository tests, I wanted to create a sql file with several inserts, and execute the file directly with the entity manager.
It seams that it allows only one query at the time.
Somebody has an idea how to digest directly an sql file in one execution?
Here is an example I'm trying to do.
(it works well with entities and saving them, but for more complicated tests, I'd rather use an sql file).
I don't want to use migration globally because I want all the tests to be independant.
describe('Lead time repository', () => {
let app: INestApplication;
let leadTimeRepository: LeadTimeRepository;
function populateDB() {
const initScript = fs.readFileSync(path.join(__dirname, 'populate.sql'), 'utf-8');
console.log(initScript);
leadTimeRepository.manager.query(initScript);
}
beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [DatabaseModule, LeadTimeModule],
}).compile();
app = module.createNestApplication();
await app.init();
leadTimeRepository = app.get<LeadTimeRepository>(LeadTimeRepository);
populateDB();
});
afterAll(async () => {
await app.close();
});
describe('findLeadTimeForEvent', () => {
it('Should do something.', () => {
console.log('should do something');
});
});
});
Thanks by advance.

Trouble reading user accessible files

I am using nativescript-mediafilepicker as means of choosing a file, and this can read external storage successfully (I have downloaded a PDF to the 'downloads' folder on iOS and I am able to pick it.) I then try to load the file using the file system module from nativescript library, and this fails because it is listed as NativeScript encountered a fatal error: Uncaught Error: You can’t save the file “com.xxxxxx” because the volume is read only. This doesn't make sense as I am trying to read anyway - I don't understand where the saving part is from. The error comes from fileSystemModule.File.fromPath() line.
Something to note that file['file'] is file:///Users/adair/Library/Developer/CoreSimulator/Devices/82F397CE-B0B3-4ADD-AD52-805265C7AC49/data/Containers/Data/Application/7B47A8BD-6DBA-42CF-8792-38A8C5E61174/tmp/com.xxxxxx/test.pdf
Is the file automatically being pulled to an application specific directory after this media picker?
getFiles() {
let extensions = [];
if (app.ios) {
extensions = [kUTTypePDF]; // you can get more types from here: https://developer.apple.com/documentation/mobilecoreservices/uttype
} else {
extensions = ["pdf"];
}
const mediaFilePicker = new Mediafilepicker();
const filePickerOptions = {
android: {
extensions,
maxNumberFiles: 1,
},
ios: {
extensions,
maxNumberFiles: 1,
},
};
masterPermissions
.requestPermissions([masterPermissions.PERMISSIONS.READ_EXTERNAL_STORAGE,masterPermissions.PERMISSIONS.WRITE_EXTERNAL_STORAGE])
.then((fulfilled) => {
console.log(fulfilled);
mediaFilePicker.openFilePicker(filePickerOptions);
mediaFilePicker.on("getFiles", function (res) {
let results = res.object.get("results");
let file = results[0];
console.dir(file);
let fileObject = fileSystemModule.File.fromPath(file["file"]);
console.log(fileObject);
});
mediaFilePicker.on("error", function (res) {
let msg = res.object.get("msg");
console.log(msg);
});
mediaFilePicker.on("cancel", function (res) {
let msg = res.object.get("msg");
console.log(msg);
});
})
.catch((e) => {
console.log(e);
});
},
The issue I have experienced is resultant of the expectation of File.fromPath and what is returned by the file picker. File picker is returning a "file://path" URI, and File.fromPath is expecting a string of just "path".
Simply using the following instead is enough.
let fileObject = fileSystemModule.File.fromPath(file["file"].replace("file://","");

Playwright : How to run the same test on multiple url in the same browser on different tabs and in parallel

I'm looking to run the same test for serverals url (~20) and I want to be the quickest as possible.
I would like to run my 20 tests in parallel in one browser and in a new tab (page) for each but I can't achieve it.
Here my code that open a new browser for each test :
const urlList: string[] = [
'url1',
'url2',
...
];
test.describe.parallel("Same test for multiple url", async () => {
let context;
test.beforeAll(async ({ browser }) => {
context = await browser.newContext();
});
for (const url of urlList) {
test(`${url}`, async () => {
let page = await context.newPage();
await page.goto(url);
});
}
});
This is expected. https://playwright.dev/docs/test-parallel
Every worker starts it own browser.
If you put console.log("Log Before all"): in "Before All" you will see that it will be printed 20 times, in terminal. Even maybe you will expect to execute it only once.
So you must renounce something. You will have parallel execution or you will have one browser. Think that new browsers will not border you. :-)

Random image from folder

How can I make possible that the app will load all of the images from the specific folder and then put in array and choose one image randomly? When chose one then pass to the fronted to show the image. How to do that too?
I am C# developer but not long time ago I found ElectronJS and this framework does everything easier so therefore I am moving to this framework.
I did in C# programming this way:
// basic settings.
var ext = new List<string> { ".jpg", ".gif", ".png" };
// we use same directory where program is.
string targetDirectory = Directory.GetCurrentDirectory() + "\\assets\\" + "images\\" + "animals\\";
// Here we create our list of files
// New list
// Use GetFiles to getfilenames
// Filter unwanted stuff away (like our program)
if (Directory.Exists(targetDirectory))
{
Files = new List<string>
(Directory.GetFiles(targetDirectory, "*.*", SearchOption.TopDirectoryOnly)
.Where(s => ext.Any(es => s.EndsWith(es))));
// Show first picture so we dont need wait 3 secs.
ChangePicture();
}
else
{
panel5.BackgroundImage = new Bitmap(Resources.doggy);
}
I don't know how to do in ElectronJS.
Thank you in advance the answers.
Alright. I found the solution.
However I don't understand the people who are giving negative reputation for the opened question. If they are giving negative reputation then they could explain why.
Well anyway, I did fix this issue with this way:
I created images.js file and added this:
var fs = require('fs');
function getRandImage() {
var files = fs.readdirSync('./assets/images/animals/')
/* now files is an Array of the name of the files in the folder and you can pick a random name inside of that array */
let chosenFile = files[Math.floor(Math.random() * files.length)]
console.log('../assets/images/animals/' + chosenFile);
return '../assets/images/animals/' + chosenFile;
}
module.exports = { getRandImage }
I used console to see if the value is correct, otherwise others can delete that part.
Sending the data to the renderer process:
const { getRandImage } = require('./images');
child.webContents.send('random-image', getRandImage());
I did put in the preload.js file the following (I used the starter pack electronjs github to start with something):
var { ipcRenderer } = require('electron');
ipcRenderer.on('random-image', function (event, store) {
document.getElementById("randompic").src = store;
console.log(store);
});
Same here, I did use console.log just for test the value is correct and I used to change the randompic ID related image src html to the randomly chosen image.
Hopefully I did helping those people who are newbie as me.

Copy all files but change the name of some automatically in yeoman

I am trying to create a yeoman generator where I have to copy from templatePath to destinationPath some files and folders, but I would want to have some of this files with a variable that yeoman could change by one of the user's inputs.
like: "<%=name%>-plugin.php" -> "hello-plugin.php"
I saw some references that this can be done but I can't find how.
I am doing right now:
//Copy the configuration files
app: function () {
this.fs.copyTpl(
this.templatePath('**'),
this.destinationPath(),
{
name: this.props.pluginName,
name_function: this.props.pluginName.replace('-', '_'),
name_class: this.props.className,
description: this.props.pluginDescription
}
);
}
I thought that with that code my <%=name%> would magically changed on copyTpl but it doesn't work
I've just found the solution:
Use this.registerTransformStream(); to pipe all files through some node.js script.
var rename = require("gulp-rename");
//other dependecies...
module.exports = yeoman.Base.extend({
//some other things generator do...
writing: function() {
var THAT = this;
this.registerTransformStream(rename(function(path) {
path.basename = path.basename.replace(/(666replacethat666)/g, THAT.props.appName);
path.dirname = path.dirname.replace(/(666replacethat666)/g, THAT.props.appName);
}));
this.fs.copyTpl(
this.templatePath(),
this.destinationPath(), {
appName: this.props.appName
});
}
});
I'm using here gulp-rename to change file names to something else.
Assuming that this.props.appName == "myFirstApp", this:
666replacethat666-controller.html
will change its name to
myFirstApp-controller.html
Following #piotrek answer, I made a function to replace all props with some pattern (like ejs does) -> $$[your prop name]$$. warning: ES6 inside
var rename = require("gulp-rename");
//other dependecies...
module.exports = yeoman.Base.extend({
//some other things generator do...
writing: function() {
this.registerTransformStream(rename((path) => {
for (let prop in this.props) {
let regexp = new RegExp('\\$\\$' + prop + '\\$\\$', 'g')
path.basename = path.basename.replace(regexp, this.props[prop]);
path.dirname = path.dirname.replace(regexp, this.props[prop]);
}
}));
this.fs.copyTpl(
this.templatePath(),
this.destinationPath(), {
appName: this.props.appName
});
}
});
Example:
Let's assume you have this.props.appname = MyApp and this.props.AnotherProps = Test and you want to rename file or folder.
Name your file or folder MyFile$$appname$$.js -> MyFileMyApp.js
Name your file or folder $$appname$$.js -> MyApp.js
Name your file or folder $$AnotherProps$$.js -> Test.js
This is not possible anymore. The feature was bloated and was removed at some point in 2015.
For now, just rename the file:
this.fs.copy('name.js', 'new-name.js')

Resources