azure-sdk-for-node: virtualMachines.get does not return VM status (stopped, running, deallocated, etc.) - azure-node-sdk

I've made the call to virtualMachines.get to retrieve instance information about my VM. In the output I don't see where you get the status of the VM (stopped, running, deallocated). Is there another way to get the status that I'm looking for?

use the optional query parameter $expand=instanceView.
Example:
//assuming you have instantiated the client ...
let options = {expand: 'instanceView'};
client.virtualMachines.get('rg-name', 'vm-name', options).then((vminfo) => {
console.dir(vminfo, {depth: null, colors: true});
}).catch((err) => {
console.dir(err, {depth: null, colors: true});
});
Documentation found here.

Related

Flutter how to test Either<Failure,List<Object>>

it seems to have the same value with matcher but still can't pass the test probably cuz of the memory address stuff. can anyone let me know how i can test the result when a list is in Either<< Right >>
test('get board list from remote data source', () async {
when(mockBoardRemoteDataSource.getBoards())
.thenAnswer((_) async => tBoardModels);
final result = await repository.getBoards();
verify(mockBoardRemoteDataSource.getBoards());
expect(result, equals(Right(toBoards)));
// Either<Failure, List<BoardInfo>> result;
// (new) Right<dynamic, List<BoardInfo>> Right(List<BoardInfo> _r)
});
//console result
Expected: Right<dynamic, List<BoardInfo>>:<Right([_$_BoardInfo(1, name1, address1), _$_BoardInfo(2, name2, address2)])>
Actual: Right<Failure, List<BoardInfo>>:<Right([_$_BoardInfo(1, name1, address1), _$_BoardInfo(2, name2, address2)])>
package:test_api expect
package:flutter_test/src/widget_tester.dart 455:16 expect
test\features\nurban_honey\data\repositories\board_repository_impl_test.dart 58:9 main.<fn>.<fn>.<fn>
//BoardInfo Implementation
import 'package:equatable/equatable.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'board_info.freezed.dart';
#freezed
class BoardInfo extends Equatable with _$BoardInfo {
BoardInfo._();
factory BoardInfo(int id, String name, String address) = _BoardInfo;
#override
List<Object?> get props => [id, name, address];
}
Thanks to Jay, his answer helps me to made my resolution.
This is how i made the test act:
// Act
var results = (await repository.fetch()).fold(
(failure) => failure,
(response) => response,
);
Then I made a type expectation, matching to the failure type declared on my use case:
In the case of the successful execution
// Assert
expect(results, isA<ResultType>());
In the case of the failure expectation
// Assert
expect(results, isA<FailureType>());
The entire test case looks like the following
test('On successful execution, should returns a SuccessResultType', () async {
// Arrange
repository = MyUseCaseRepository();
// Act
var results = (await repository.fetch()).fold(
(failure) => failure,
(response) => response,
);
// Assert
expect(results, isA<SuccessResultType>());
});
I hope this approach can help anybody!
I've made the test pass by doing this:
result.fold(
(l) => null,
(resultR) => Right(toBoards)
.fold((l) => null, (matcherR) => expect(resultR, matcherR)));
is there better way to do it?

systematic failure when trying to execute a system command with Cypress

I'm new to Cypress and Javascript
I'm trying to send system commands through Cypress. I've been through several examples but even the simplest does not work.
it always fails with the following message
Information about the failure:
Code: 127
Stderr:
/c/Program: Files\Git\usr\bin\bash.exe: No such file or directory`
I'm trying cy.exec('pwd') or 'ls' to see where it is launched from but it does not work.
Is there a particular include I am missing ? some particular configuration ?
EDIT :
indeed, I'm not clear about the context I'm trying to use the command in. However, I don't set any path explicitely.
I send requests on a linux server but I also would like to send system commands.
My cypress project is in /c/Cypress/test_integration/cypress
I work with a .feature file located in /c/Cypress/test_integration/cypress/features/System and my scenario calls a function in a file system.js located in /c/Cypress/test_integration/cypress/step_definitions/generic.
System_operations.features:
Scenario: [0004] - Restore HBox configuration
Given I am logging with "Administrator" account from API
And I store the actual configuration
...
Then I my .js file, I want to send a system command
system.js:
Given('I store the actual configuration', () => {
let nb_elem = 0
cy.exec('ls -l')
...
})
I did no particular path configuration in VS Code for the use of bash command (I just configured the terminal in bash instead of powershell)
Finally, with some help, I managed to call system functions by using tasks.
In my function I call :
cy.task('send_system_cmd', 'pwd').then((output) => {
console.log("output = ", output)
})
with a task created as follows:
on('task', {
send_system_cmd(cmd) {
console.log("task test command system")
const execSync = require('child_process').execSync;
const output = execSync(cmd, { encoding: 'utf-8' });
return output
}
})
this works at least for simple commands, I haven't tried much further for the moment.
UPDATE for LINUX system commands as the previous method works for WINDOWS
(sorry, I can't remember where I found this method, it's not my credit. though it fulfills my needs)
This case requires node-ssh
Still using tasks, the function call is done like this
cy.task('send_system_cmd', {cmd:"<my_command>", endpoint:<address>,user:<ssh_login>, pwd:<ssh_password>}).then((output) => {
<process output.stdout or output.stderr>
})
with the task being build like this:
// send system command - remote
on('task', {
send_system_cmd({cmd, endpoint, user, pwd}) {
return new Promise((resolve, reject) => {
const { NodeSSH } = require('node-ssh')
const ssh = new NodeSSH()
let ssh_output = {}
ssh.connect({
host: endpoint,
username: user,
password: pwd
})
.then(() => {
if(!ssh.isConnected())
reject("ssh connection not set")
//console.log("ssh connection OK, send command")
ssh.execCommand(cmd).then(function (result) {
ssh_output["stderr"] = result.stderr
ssh_output["stdout"] = result.stdout
resolve(ssh_output)
});
})
.catch((err)=>{
console.log(err)
reject(err)
})
})
}
})

Cypress: cy.window(): Unable to get property values

Goal
Hello, I wish to gather custom property values for a window object of a page using cy.window().
Issue
When using cy.log() jointly with JSON.stringify(), it presents that it does have properties with values; however, when using lodash _.has(), does not have these properties and thereby no value because these properties are not found.
Code
The following Cypress custom command using cy.window() gathers custom window's property
export function cmdCypressWindow($propName: string) {
cy.window()
.its($propName)
.then(($propValue: Cypress.AUTWindow) => {
cy.log('props names:', JSON.stringify(Object.getOwnPropertyNames($propValue), null, 2));
cy.log('props values:', JSON.stringify($propValue, null, 2));
cy.log('VERSION prop:', _.has($propValue, 'VERSION'));
cy.log('HOST prop:', _.has($propValue, 'HOST'));
cy.log('VERSION value:', _.get($propValue, 'VERSION'));
cy.log('HOST value:', _.get($propValue, 'HOST'));
});
}
Passed in for parameter $propName value 'ACT', because I am expecting the page's window object to contain window.ACT["VERSION"].
Using the example code, the log output shows that the page's window does contain property ACT["VERSION"].
However, when accessing this window object, listed properties are unavailable and undefined:
window
- its .ACT
log props names:, [ "__esModule", "VERSION", "HOST", "RulesList", "RulesAddEdit", "AppsList", "AppsOAuth", "AppsAdd" ]
log props values:, { "VERSION": "0.2.11", "HOST": "radmin" }
log VERSION prop:, false
log HOST prop:, false
log VERSION value:
log HOST value:
How do I resolve this? Thank you, all feedback is very much appreciated.
Found part of the solution here:
TypeScript: Find Key / Value in Object (list comprehension?)
Modified the function:
export function cmdCypressWindow($propName: string) {
cy.window()
.its($propName)
.then(($propValue: Cypress.AUTWindow) => {
const actValues: Record<string, string> = {};
Object.keys($propValue).forEach(key => {
// #ts-ignore
if (typeof $propValue[key] !== 'function') {
// #ts-ignore
actValues[key as string] = $propValue[key];
}
});
cy.log(`window.${$propName}`, JSON.stringify(actValues, null, 2));
cy.wrap(actValues);
});
}
Results show that I was able to acquire values from window object:
log props names:, [ "__esModule", "VERSION", "HOST", "RulesList", "RulesAddEdit", "AppsList", "AppsOAuth", "AppsAdd" ]
log window.ACT, { "VERSION": "0.2.11", "HOST": "radmin" }
wrap {version: 0.2.11, host: radmin}

Says Jasmine spy is not being called, but I can see that its being called

I can't figure out why Jasmine is claiming that the function I'm spying on isn't being called, especially since it is logging in buildLinksObj when called through and not calling when I remove .and.callThrough() I feel like I've written similar code a bunch of times before without any problem. I'm using Jasmine 2.9
The error message I'm getting is:
1) addToLinks should call buildLinksObj if its given an object with children
it should add the personalized links to PageApp.meta.analytics.links
Expected spy buildLinksObj to have been called.
at UserContext.<anonymous> (http://localhost:9877webpack:///tests/specs/common/FetchPersonalContent.spec.js:854:0 <- tests/app-mcom.js:104553:48)
Here's the except of my code:
FetchPersonalContent.js
const buildLinksObj = (responseObj = {}, targetObj, PageApp) => {
console.log('it logs in buildLinksObj') // This is logging!
}
const addToLinks = (responseArr, personalizedLinks) => {
responseArr.forEach((media) => {
const type = media.type;
const typeObj = media[type];
buildLinksObj(typeObj, personalizedLinks, PageApp);
if (typeObj && typeObj.children) {
console.log('has children!')
console.log('typeObj.children is: ', typeObj.children);
typeObj.children.forEach((child) => {
console.log('has a child')
buildLinksObj(child, personalizedLinks, PageApp);
console.log('buildLinksObj was definitely called. what the heck?')
});
}
});
}
export {buildLinksObj, addToLinks, FetchPersonalContent as default,
};
FetchPersonalContent.spec.js
import * as FetchPersonalContent from '../../../src/FetchPersonalContent'; // my path is definitely correct
describe('it should add the personalized links to PageApp.meta.analytics.links', () => {
it('addToLinks should call buildLinksObj if its given an object with children ', () => {
spyOn(FetchPersonalContent, 'buildLinksObj').and.callThrough();
FetchPersonalContent.addToLinks([{
"personalId": 30718,
"type": "carousel",
"carousel": {}
}], {});
expect(FetchPersonalContent.buildLinksObj).toHaveBeenCalled();
});
});
I'd really appreciate any help!
I have a feeling FetchPersonalContent.buildLinksObj in the spec file is not pointing to the same instance as buildLinksObj in the FetchPersonalContent.js file.
Why is export {FetchPersonalContent as default} required? I am assuming you have shared the complete content of FetchPersonalContent.js in your question.
Possible solutions:
You can try removing FetchPersonalContent from the export statement.
Or
Instead of
export {buildLinksObj, addToLinks, FetchPersonalContent as default,
};
You can directly export the constants in FetchPersonalContent.js file.

Why can't I use `useMasterKey()` in a `beforeSave` function?

My Parse app has a GiftCode collection which disallows the find operation at the class-level.
I am writing a beforeSave cloud function that prevents duplicate codes from being entered by our team from Parse's dashboard:
Parse.Cloud.beforeSave('GiftCode', function (req, res) {
Parse.Cloud.useMasterKey();
const code = req.object.get('code');
if (!code) {
res.success();
} else {
const finalCode = code.toUpperCase().trim();
req.object.set('code', finalCode);
(new Parse.Query('GiftCode'))
.equalTo('code', finalCode)
.first()
.then((gift) => {
if (!gift) {
res.success();
} else {
res.error(`GiftCode with code=${finalCode} already exists (objectId=${gift.id})`);
}
}, (err) => {
console.error(err);
res.error(err);
});
}
});
As you can see, I am calling Parse.Cloud.useMasterKey() (and this is running in the Parse cloud), but I am still getting the following error:
This user is not allowed to perform the find operation on GiftCode.
I use useMasterKey() in other normal cloud functions and am able to perform find operations as needed.
Is useMasterKey() not applicable to beforeSave functions?
I've never tried to use the master key in a beforeSave function but I wouldn't be surprised if there's some extra safeguards in place to prevent it. From a security standpoint, it seems like it could make all write-based CLPs and ACLs worthless for that class.
Try selectively using the master key by passing it as an option to the query like so
(new Parse.Query('GiftCode'))
.equalTo('code', finalCode)
.first({ useMasterKey: true })
.then((gift) => {
...
Parse.Cloud.useMasterKey(); has been deprecated in Parse Server version 2.3.0 (Dec 7, 2016). From that version on, it is a no-op (it does nothing). You should now insert the {useMasterKey:true} optional parameter to each of the methods that need to override the ACL or CLP in your code.

Resources