Firestore emulator for testing security rules - running the tests - google-cloud-firestore

I have installed the emulator following the instructions at enter link description here and I can start it, so far so good.
After picking some code here and there I have written my first test, here it is:
import * as firebasetesting from '#firebase/testing';
import * as firebase from 'firebase';
import * as fs from 'fs';
const projectId = 'my-firebase-project';
const rules = fs.readFileSync('firestore.rules', 'utf8');
beforeAll(async () => {
// Make your test app load your firestore rules
await firebasetesting.loadFirestoreRules({ projectId, rules });
});
beforeEach(async () => {
// Reset our data from our test database
await firebasetesting.clearFirestoreData({ projectId });
});
after(async () => {
// Shut down all testing Firestore applications after testing is done.
await Promise.all(firebasetesting.apps().map(app => app.delete()));
});
describe("TRACKERS AND ALLIES", () => {
it('TRACKER UP', async () => {
let user = {username: "Bob", uid: 'bobuid'}
let target = { username: "Alice", uid: 'aliceuid'}
const auth = { uid: bob.uid, token: {isadmin: false} };
const app = firebasetesting.initializeTestApp({ projectId, auth }).firestore();
const ref = app.doc('users/'+ user.uid + '/contact/' + target.uid);
await firebasetesting.assertSucceeds(ref.update({ up: true, username: target.uid, timestamp: firebase.firestore.FieldValue.serverTimestamp() }));
});
})
And my question is very simple: how do I run it?
EDIT: I may just add that I am new to Firestore and Javascript in general... The link above simply states
After running a suite of tests, you can access test coverage reports that show how each of your security rules was evaluated.
So I guess it must be simple, but I cannot find the "run" command anywhere...

If you have a nodejs script, run it with node your-script.js. You must have node installed.
If you want to run the script along with the emulator, and shut the emulator down after the script finishes, the page you linked to says:
In many cases you want to start the emulator, run a test suite, and
then shut down the emulator after the tests run. You can do this
easily using the emulators:exec command:
firebase emulators:exec --only firestore "./my-test-script.sh"
If you found the documentation confusing or incomplete, you should use the "send feedback" button at the top right of the page.

Related

My 'deployed' contract still won't show up on Etherscan. Been about 1.5 hours

need help figuring out why my supposedly 'deployed' contract will still not appear in Etherscan.
Overview:
I used hardhat with following code and got back confirmation:
$ npx hardhat run scripts/deployRoboPunksNFT.js --network rinkeby
RoboPunksNFT deployed to: 0xaBDe0c1A9F7589f21818287287885a2Fef32E3f0
Clearly, it confirms as fully deployed but when I check this contract address at Etherscan (Rinkeby)...nothing: https://rinkeby.etherscan.io/address/0xaBDe0c1A9F7589f21818287287885a2Fef32E3f0
The deployment script used:
const hre = require("hardhat");
async function main() {
const RoboPunksNFT = await hre.ethers.getContractFactory("RoboPunksNFT");
const roboPunksNFT = await RoboPunksNFT.deploy();
await roboPunksNFT.deployed();
console.log("RoboPunksNFT deployed to:", roboPunksNFT.address);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
My hardhat.config.js
require("#nomiclabs/hardhat-waffle");
const dotenv = require("dotenv");
require("#nomiclabs/hardhat-etherscan");
dotenv.config();
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
const accounts = await hre.ethers.getSigners();
for (const account of accounts) {
console.log(account.address);
}
});
/**
* #type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.8.4",
networks: {
rinkeby: {
url: process.env.REACT_APP_RINKEBY_RPC_URL,
accounts: [process.env.REACT_APP_PRIVATE_KEY]
},
},
etherscan: {
apiKey: process.env.REACT_APP_ETHERSCAN_KEY,
}
};
I got so frustrated that I deployed it again (Code above is 2nd attempt/2nd deployed contract. The first deployed contract address was at 0x9F6040234728493121BCB9A1EaFDBa5E494bB3ed.
Please let me know if anyone sees something that I missed. Hopefully there's enuf info I've submitted here to determine...
Thanks very much!
Problem solved. Rinkeby happened to be down for 6 whole hours. But once it came back up, had 2 freshly deployed contracts on Rinkeby ready to go...

Android Enterprises Device Enrollment Stuck with NodeJs Generated QR Code with Service Account Authentication

As mentioned in the google documents i have tested the following process
URL to quick start: https://colab.research.google.com/github/google/android-management-api-samples/blob/master/notebooks/quickstart.ipynb#scrollTo=pjHfDSb8BoBP
Create Enterprise
Create Policy
Enroll the device
Then I have used the NODEJS API of Android Enterprises to develop the server based solution, which is working fine as per the documentation for all the functions such as get, create, delete the policy, devices, enterprises.
The issue i am facing is with the QR code generated from NODE application, when i scan the QR code generated from NODEJS application, the device got stuck at system update.
Following is my Policy update function
router.post('/update/:id', async function(req, res) {
const {title,policy_body,update_mask,enroll_url} = req.body;
// here we are callng the android managment API to and then the response we will update to database
const amApiBody = {
name: policy_body.name,
updateMask:update_mask,
requestBody:policy_body
}
const policy_update_response = await amApi.updatePolicy(amApiBody);
const p = await policyModel.update(req.params.id,title,policy_update_response,enroll_url);
res.json(p)
});
AmAPI file
this.updatePolicy = async function (body)
{
const auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/androidmanagement'],
});
const authClient = await auth.getClient();
google.options({auth: authClient});
// Get the list of available policies
const res = await androidmanagement.enterprises.policies.patch(body);
console.log('requestFinalBody=',body);
return res.data;
}
Following is my policy data obtained by running above function
policy_create_response= {
name: 'enterprises/LC019rjnor/policies/policy1',
version: '14',
applications: [
{
packageName: 'com.google.samples.apps.iosched',
installType: 'FORCE_INSTALLED',
autoUpdateMode: 'AUTO_UPDATE_HIGH_PRIORITY'
},
{
packageName: 'com.dekaisheng.courier',
installType: 'FORCE_INSTALLED',
autoUpdateMode: 'AUTO_UPDATE_HIGH_PRIORITY'
}
],
keyguardDisabledFeatures: [ 'KEYGUARD_DISABLED_FEATURE_UNSPECIFIED' ],
defaultPermissionPolicy: 'GRANT',
uninstallAppsDisabled: true,
keyguardDisabled: true,
tetheringConfigDisabled: true,
dataRoamingDisabled: true,
networkEscapeHatchEnabled: true,
bluetoothDisabled: true,
debuggingFeaturesAllowed: true,
funDisabled: true,
kioskCustomLauncherEnabled: true
}
Note i have exported the variable to the terminal as follows before running the app, the auth.json is the service account credential file.
export GOOGLE_APPLICATION_CREDENTIALS="/Users/Mac/Projects/wajid/mdm/server/env/auth.json"
Thanks for the help in advance
I figured out that in nodeJS API I was passing wrong property name of Policy value in the request body.
Code before fix
parent: this.getParent(policyName),
requestBody:{
“name”: “my_policy"
}
Code after fix
parent: this.getParent(policyName),
requestBody:{
"policyName”: “my_policy"
}

NestJS: e2e testing using an axios-based client is not working as expected

I have a NestJS application that exposes some endpoints, and I have written a client application that I plan on releasing as an NPM package to work with the nest server. I am attempting to write end-to-end tests that start the nest server, connect it to a test database in a local docker container, and test it using the client. Here are some snippets of what I'm attempting to do:
Controller:
#Controller('/api/v1/messages')
export class MessagesController {
constructor(
private messagesService: MessagesService
) {}
#Get()
#UsePipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }))
private findAll(
#Query() searchCriteria: MessageSearchDto
): Promise<MessageDto[]> {
if (Object.keys(searchCriteria).length > 0)
return this.messagesService.search(searchCriteria);
return this.messagesService.findAll();
}
}
Client:
const http = require('axios');
const dotenv = require('dotenv');
dotenv.config();
export class MessageClient {
public baseUri: string = process.env.MessageClientTarget ?? './';
constructor() {}
public async findAll() {
return await http.get(this.baseTarget());
}
private baseTarget() {
return `${this.baseUri}/api/v1/messages`;
}
}
e2e Test:
describe('MessageController (e2e)', () => {
let app: INestApplication;
let client: MessageClient = new MessageClient();
beforeAll(async () => {
let moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule, MessagesModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
afterAll(async () => {
await app.close();
});
it('/ (GET)', async done => {
const { data: messages } = await client.findAll()
expect(messages).toEqual([]);
done();
});
});
And .env:
MessageClientTarget=http://localhost:3000
When I attempt to run this, I get the following error: "connect ECONNREFUSED 127.0.0.1:3000"
From what I understand, this is because the createNestApplication method doesn't actually start a server but instead creates a mocked version of the application.
My question is how can I work with INestApplication or TestingModule in order to start the application or what other way do I have to programmatically start a NestJS application. It is important to me that I perform the e2e testing with the Axios based client rather than supertest as a way of testing both the client and the server.
I have verified that the server is supposed to start on port 3000 locally, and I have verified that the client has the correct baseUri set. The address used by the client during testing is: http://localhost:3000/api/v1/messages and was verified by outputting the value to the console during the test. Also, only the database currently lives in a docker container and I have that running correctly. The whole application works perfectly when ran locally and it is only in the test that it is failing.
Please make sure that the test environment where you are running tests is set to node. Add testEnvironemnt:'node' jest parameter in your jest configuration file.
You can run e2e tests with any client of your choice regardless of whether or not you are running a nestjs testing module or the actual nestjs application instance.
I personally use testing module as it makes very easy to mock any third-party dependencies of the application when testing it (that is the main purpose of the testing module, providing an elegant manner to substitute or mock any component that you may want to).

Loopback 4: Test never end when there is a connection with a MongoDB

Launch npm test, but it never end. It happens when there is a connection with a MongoDB involve. It is rare because the test works, but it never ends.
before('setupApplication', async () => {
({ app, client } = await setupApplication());
//await prepareTestData()
});
after(async () => {
//await cleanupTestData();
await app.stop();
});
it('login with a test user', async () => {
const res = await client.post('/user-accounts/login').set('urlLogin', TEST_TENANT_URL)
.send({
email: TEST_EMAIL,
password: TEST_PASS
}).expect(200);
token = res.body.token;
expect(res.body).to.ownProperty("token").and.length(EXPECTED_TOKEN_LENGTH);
console.log("Logged in with token ", res.body.token);
});
The problem: The terminal never end. Is like a thread still working. I don´t know if it is a problem with loopback or what.
Any idea? I hope somebody could help me.
Thanks.
Cross-posting my comment from the discussion in https://github.com/strongloop/loopback-next/issues/3672:
Please use Mocha option exit, it will end the process after all tests (and after/afterEach hooks) have finished. See https://mochajs.org/#configuring-mocha-nodejs to learn more. Alternatively, you can add --exit option to mocha CLI, e.g. mocha --exit src/__tests__/**/*.js.

How to make browser close and open for each scenario in a feature - protractor and cucumberjs

This question might be a duplicate, but i am not as expected, so raising again.
I am creating a new protractor framework in our project. My application has login screen which i need to login with different user details for each case in a feature. I have two scenarios in a feature file. When i run, the browser should open the login page and do some action and close the browser for each scenario, and it has to do the same thing for every scenario, but am not seeing this happen. When i run, it happens for first scenario and from second it fails. Could someone help me on this?
i have tried with different options with After hook, restartBrowserBetweenTests but no luck.
conf.js
import { browser } from "protractor";
export const config = {
// chromeDriver: './drivers/chromedriver',
// seleniumServerJar: './drivers/selenium-server-standalone-3.12.0.jar',
seleniumAddress: 'http://localhost:4444/wd/hub',
// baseUrl: '<url>',
SELENIUM_PROMISE_MANAGER: false,
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'args': ['--disable-extensions=true']
}
},
// restartBrowserBetweenTests: true,
specs: [
'./features/*.feature'
],
cucumberOpts: {
require: [
'./features/step_definitions/*.js',
'./support/*.js'
],
format: ['json:results/report.json'],
tags: [
//"#smoke",
//"#regression"
],
strict: true
},
disableChecks: true,
onPrepare: function () {
browser.manage().deleteAllCookies();
browser.manage().window().maximize();
browser.ignoreSynchronization = true;
},
getPageTimeout: 100000,
allScriptsTimeout: 500000
}
hooks.ks
import { Before, BeforeAll, After, AfterAll } from "cucumber";
import { browser } from "protractor";
import { config } from "../protractorConf"
Before( {timeout: 2 * 20000}, async () => {
// await browser.get(config.baseUrl)
})
// After( {timeout: 2 * 5000}, async () => {
// await browser.close()
// })
AfterAll( {timeout: 2 * 5000}, async () => {
await browser.quit()
})
steps.js
import { Given, When, Then } from "cucumber"
import { expect } from "chai";
import { browser } from "protractor";
import * as loginPage from "../pages/loginPage"
import * as welcomePage from "../pages/welcomePage"
import * as verificationPage from "../pages/verificationPanelPage"
import * as homePage from "../pages/homePage";
const stepTimeoutExpiry = {timeout: 2 * 5000}
let globalLoanNumber = ""
Given(/^Launch SATURN app with "(.*?)" and "(.*?)"$/, stepTimeoutExpiry, async (user, pass) => {
await browser.get('<url>')
await loginPage.login(user, pass)
})
When(/^I search a loan by "(.*?)" as "(.*?)" in search page$/, stepTimeoutExpiry, async (searchType, loanNumber) => {
globalLoanNumber = loanNumber
await welcomePage.selectSearchType()
if (searchType === "Loan Number") {
await welcomePage.selectLoanNumber()
}
await welcomePage.enterLoanNumber(loanNumber)
await welcomePage.clickSearchAccountBtn()
})
When(/^I skip the verification details on verification page$/, stepTimeoutExpiry, async () => {
await verificationPage.skipVerification()
})
Then(/^I must see the Saturn "(.*?)" page for this account$/, stepTimeoutExpiry, async (homeText) => {
// await homePage.isHomeLinkAvailable()
expect(await homePage.isHomeLinkAvailable()).to.be.true
expect(await homePage.getAccountNumberText()).to.equal(globalLoanNumber)
})
feature file
Feature: Running sample feature
Scenario: Login to Saturn and verify it works
Given Launch SATURN app with "user" and "pass"
When I search a loan by "Loan Number" as "0535003974" in search page
And I skip the verification details on verification page
Then I must see the Saturn "Home" page for this account
Scenario: Login to Saturn and verify it works for the second time
Given Launch SATURN app with "user" and "pass"
When I search a loan by "Loan Number" as "0535003974" in search page
And I skip the verification details on verification page
Then I must see the Saturn "Home" page for this account
below is the error, when i run.
λ npm run test
> protractortest#1.0.0 test c:\<user>\ATDDProtractorTest
> babel-node node_modules/protractor/bin/protractor protractorConf.js --presets-env
(node:12828) [DEP0022] DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.
[10:55:12] I/launcher - Running 1 instances of WebDriver
[10:55:12] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
.......F---.
Failures:
1) Scenario: Login to Saturn and verify it works for the second time # features\testone.feature:9
√ Before # support\hooks.js:5
× Given Launch SATURN app with "user" and "pass" # features\step_definitions\testOne.steps.js:13
Error: function timed out, ensure the promise resolves within 10000 milliseconds
at Timeout._onTimeout (c:\Manimaran\ATDDProtractorTest\node_modules\cucumber\src\user_code_runner.js:61:18)
at ontimeout (timers.js:475:11)
at tryOnTimeout (timers.js:310:5)
at Timer.listOnTimeout (timers.js:270:5)
- When I search a loan by "Loan Number" as "0535003974" in search page # features\step_definitions\testOne.steps.js:19
- And I skip the verification details on verification page # features\step_definitions\testOne.steps.js:30
- Then I must see the Saturn "Home" page for this account # features\step_definitions\testOne.steps.js:34
√ After # node_modules\protractor-cucumber-framework\lib\resultsCapturer.js:25
2 scenarios (1 failed, 1 passed)
8 steps (1 failed, 3 skipped, 4 passed)
0m20.442s
[10:55:40] I/launcher - 0 instance(s) of WebDriver still running
[10:55:40] I/launcher - chrome #01 failed 1 test(s)
[10:55:40] I/launcher - overall: 1 failed spec(s)
loginpage.js
import { element, by, browser } from "protractor";
const userName = element(by.id('username'));
const passWord = element(by.id('password'));
const signOn = element(by.xpath('.//a[contains(#title,"Sign In")]'));
const EC = protractor.ExpectedConditions
const isVisibilityOf = EC.visibilityOf(userName)
export const login = async (user, pass) => {
await browser.wait(isVisibilityOf, 10000)
await userName.sendKeys(user);
await passWord.sendKeys(pass);
await signOn.click();
}
For protractor, before any spec be executed, an browser instance(session) will be init and hand over the session to spec runner which manage to execute specs.
If you want to close session after each scenario/feature, you have to create an new session and pass down the new session to the original spec runner. I think it's not easy to implement this for us without learning protractor source code deeply.
I prefer to recommend following solutions more easy from our side:
1) delete cookie in After hook, protractor supply such API to do that
2) open logout url in After hook if your app has such url, otherwise you
can click logout button.
Actually, you can put the delete cookie, open logout url or click logout button at the beginning of your login function, then open login url. With that After hook is unnecessary.