Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MockPromptForString + doctor to work with ValidatePathError. #325

Merged
merged 11 commits into from
Sep 10, 2020
Merged
4 changes: 2 additions & 2 deletions packages/cli/src/lib/cmds/doctor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ import {enUS as messages} from '../strings';
async function jdkDoctor(config: Config, log: Log): Promise<boolean> {
const result = await JdkHelper.validatePath(config.jdkPath);
if (result.isError()) {
if (result.unwrapError().message === 'jdkPathIsNotCorrect') {
if (result.unwrapError().getErrorCode() === 'PathIsNotCorrect') {
log.error(messages.jdkPathIsNotCorrect);
return false;
} else if (result.unwrapError().message === 'jdkIsNotSupported') {
} else if (result.unwrapError().getErrorCode() === 'PathIsNotSupported') {
log.error(messages.jdkIsNotSupported);
return false;
} else { // Error while reading the file, will print the error message.
Expand Down
107 changes: 107 additions & 0 deletions packages/cli/src/spec/mock/MockPromptForStrings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
* Copyright 2020 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import {Prompt, ValidateFunction} from '../../lib/Prompt';

/**
* A class which used for testing and which mocks user's input.
*/
export class MockPromptForStrings implements Prompt {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just realised this isn't actually "for strings" anymore - it can just be called MockPrompt now.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But the messages are always strings

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had thought that the "ForStrings" was about the return type of the methods - for example that promptInput would always return a string (as opposed to a Color or something). The version we've got now works if it's used in a place that returns a Color.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The "forStrings" was for the input we accept, and as for now it's only strings

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had the same impression about T always being a string, which affects the validateFunction input and the Promise<T> output. But T can now have any values and we could drop ForStrings. The fact that addMessages() is always a string seems to be more of an implementation detail?

private responses: string[] = [];

/**
* Sets the next answer of this class to be the given message.
* @param message the message to be returned in the next prompt message.
*/
addMessage(message: string): void {
this.responses.push(message);
}

async printMessage(): Promise<void> {
// An empty function for testing.
}

/**
* Sets the output to be the given message.
* @param message the message to be prompt. Not relevant for tests.
* @param {string | null} defaultValue a default value or null.
* @param {ValidateFunction<T>} validateFunction a function to validate the input.
* @returns {Promise<T>} a {@link Promise} that resolves to the validated loaded message,
* converted to `T` by the `validateFunction`.
*/
async promptInput<T>(_message: string,
_defaultValue: string | null,
validateFunction: ValidateFunction<T>): Promise<T> {
const nextResponse = this.getNextMessage();
return (await validateFunction(nextResponse)).unwrap();
}

/**
* Sets the output to be the given message.
* @param message the message to be prompt. Not relevant for tests.
* @param {string[]} choices a list of choices. Not relevant for testing.
* @param {string | null} defaultValue a default value or null.
* @param {ValidateFunction<T>} validateFunction a function to validate the input.
* @returns {Promise<T>} a {@link Promise} that resolves to the validated loaded message,
* converted to `T` by the `validateFunction`.
*/
async promptChoice<T>(_message: string,
_choices: string[],
_defaultValue: string | null,
validateFunction: ValidateFunction<T>): Promise<T> {
const nextResponse = this.getNextMessage();
return (await validateFunction(nextResponse)).unwrap();
}

/**
* Sets the output to be the given message.
* @param message the message to be prompt. Not relevant for tests.
* @param defaultValue the value to be returned
* @returns {Promise<boolean>} a {@link Promise} that resolves to a {@link boolean} value. The
* value will the `true` if the user answers `Yes` and `false` for `No`.
*/
async promptConfirm(_message: string, defaultValue: boolean): Promise<boolean> {
return defaultValue;
}

/**
* Sets the output to be the given message.
* @param message the message to be prompt. Not relevant for tests.
* @param {ValidateFunction<T>} validateFunction a function to validate the input.
* @returns {Promise<string>} a {@link Promise} that resolves to the user input validated by
* `validateFunction`.
*/
async promptPassword(_message: string, validateFunction: ValidateFunction<string>,
): Promise<string> {
const nextResponse = this.getNextMessage();
return (await validateFunction(nextResponse)).unwrap();
}

/**
* Sets the output to be the given message.
* @param {ValidateFunction<T>} validateFunction a function to validate the input.
* @returns {string} which is the next message to be prompted`.
*/
private getNextMessage(): string {
if (this.responses.length === 0) {
throw new Error('No answer was given. Please use addMessage(nextMessage) before' +
' using this function');
}
const nextResponse = this.responses[0];
this.responses.shift();
chenlevy24 marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason why we're not just calling shift() and assigning the return value to nextResponse?

Suggested change
const nextResponse = this.responses[0];
this.responses.shift();
const nextResponse = this.responses.shift();

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, if I do as you say, I get an error because the value could be undefined or string.. Even if I check that it isn't empty before.. this is the only way I could make this work

return nextResponse;
}
}
36 changes: 36 additions & 0 deletions packages/cli/src/spec/mockPromptSpec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
chenlevy24 marked this conversation as resolved.
Show resolved Hide resolved
* Copyright 2020 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import {Result} from '@bubblewrap/core';
import {MockPromptForStrings} from './mock/MockPromptForStrings';

async function validationFunction(message: string): Promise<Result<string, Error>> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we test with a validationFunction that returns something other than a string?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see how it could change the bottom line.. every case depends on the implementation but with those tests I made sure that the logic of the class is good and functioning (At least I think so)

return Result.ok(message);
}

describe('MockPromptForStrings', () => {
describe('#promptInput', () => {
it('Checks if the correct messages are being prompted using promptInput function', async () => {
const mock = new MockPromptForStrings();
mock.addMessage('first');
mock.addMessage('second');
expect(await mock.promptInput('', null, validationFunction)).toBe('first');
expect(await mock.promptInput('', null, validationFunction)).toBe('second');
mock.addMessage('third');
expect(await mock.promptInput('', null, validationFunction)).toBe('third');
});
});
});
2 changes: 0 additions & 2 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import {TwaGenerator} from './lib/TwaGenerator';
import {DigitalAssetLinks} from './lib/DigitalAssetLinks';
import * as util from './lib/util';
import {Result} from './lib/Result';
import {ValidatePathError} from './lib/errors/ValidatePathError';

export {AndroidSdkTools,
Config,
Expand All @@ -48,5 +47,4 @@ export {AndroidSdkTools,
util,
Result,
SigningKeyInfo,
ValidatePathError,
};