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

Allow Boolean and Null Values to be Set from the Web UI #2507

Merged
merged 5 commits into from
Dec 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions locust/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,8 +227,14 @@ def swarm() -> Response:
return jsonify({"success": False, "message": err_msg, "host": environment.host})
elif key in parsed_options_dict:
# update the value in environment.parsed_options, but dont change the type.
# This won't work for parameters that are None
parsed_options_dict[key] = type(parsed_options_dict[key])(value)
parsed_options_value = parsed_options_dict[key]

if isinstance(parsed_options_value, bool):
parsed_options_dict[key] = value == "true"
elif parsed_options_value is None:
parsed_options_dict[key] = parsed_options_value
else:
parsed_options_dict[key] = type(parsed_options_dict[key])(value)

if environment.shape_class and environment.runner is not None:
environment.runner.start_shape()
Expand Down

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion locust/webui/dist/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<meta name="theme-color" content="#000000" />

<title>Locust</title>
<script type="module" crossorigin src="/assets/index-d0af3b25.js"></script>
<script type="module" crossorigin src="/assets/index-e50b96a2.js"></script>
</head>
<body>
<div id="root"></div>
Expand Down
38 changes: 24 additions & 14 deletions locust/webui/src/components/Form/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,20 @@ interface IForm<IInputData extends BaseInputData> {
onSubmit: (inputData: IInputData) => void;
}

const FORM_INPUT_ELEMENTS = 'input, select, textarea';

const getInputValue = (inputElement: HTMLInputElement | HTMLSelectElement) => {
if (inputElement instanceof HTMLInputElement && inputElement.type === 'checkbox') {
return inputElement.checked;
}

if (inputElement instanceof HTMLSelectElement && inputElement.multiple) {
return Array.from(inputElement.selectedOptions).map(option => option.value);
}

return inputElement.value;
};

export default function Form<IInputData extends BaseInputData>({
children,
onSubmit,
Expand All @@ -16,20 +30,16 @@ export default function Form<IInputData extends BaseInputData>({
async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();

const formData = new FormData(event.target as HTMLFormElement);
const inputData: IInputData = {} as IInputData;

for (const [key, value] of formData.entries()) {
if (inputData.hasOwnProperty(key)) {
if (!Array.isArray(inputData[key])) {
(inputData[key as keyof IInputData] as unknown) = [inputData[key]];
}

(inputData[key] as string[]).push(value as string);
} else {
inputData[key as keyof IInputData] = value as IInputData[keyof IInputData];
}
}
const form = event.target as HTMLFormElement;
const inputData: IInputData = [
...form.querySelectorAll<HTMLInputElement | HTMLSelectElement>(FORM_INPUT_ELEMENTS),
].reduce(
(inputData, inputElement) => ({
...inputData,
[inputElement.name]: getInputValue(inputElement),
}),
{} as IInputData,
);

onSubmit(inputData);
},
Expand Down
86 changes: 86 additions & 0 deletions locust/webui/src/components/Form/tests/Form.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { render, fireEvent, act, RenderResult } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';

import Form from 'components/Form/Form';

describe('Form component', () => {
const onSubmitMock = vi.fn();
let component: RenderResult;

beforeEach(() => {
component = render(
<Form onSubmit={onSubmitMock}>
<input data-testid='textInput' defaultValue='Text' name='textInput' type='text' />
<textarea data-testid='textArea' defaultValue='Text Area' name='textArea' />
<input
data-testid='checkboxInput'
defaultChecked={true}
name='checkboxInput'
type='checkbox'
/>
<select data-testid='selectInput' defaultValue='option1' name='selectInput'>
<option value='option1'>Option 1</option>
<option value='option2'>Option 2</option>
<option value='option3'>Option 3</option>
</select>
<select
data-testid='multipleSelectInput'
defaultValue={['option2', 'option2']}
multiple
name='multipleSelectInput'
>
<option value='option1'>Option 1</option>
<option value='option2'>Option 2</option>
<option value='option3'>Option 3</option>
</select>
<button data-testid='submitButton' type='submit'>
Submit
</button>
</Form>,
);
});

test('should handle all input types with defaultValues', async () => {
const { getByTestId } = component;

act(() => {
fireEvent.click(getByTestId('submitButton'));
});

expect(onSubmitMock).toHaveBeenCalledWith({
textInput: 'Text',
textArea: 'Text Area',
checkboxInput: true,
selectInput: 'option1',
multipleSelectInput: ['option2'],
});
});

test('should handle all input types with changed values', async () => {
const { getByTestId } = component;

act(() => {
fireEvent.change(getByTestId('textInput'), {
target: { value: 'Changed Text' },
});
fireEvent.change(getByTestId('textArea'), {
target: { value: 'Changed Text Area' },
});
fireEvent.click(getByTestId('checkboxInput'));
fireEvent.change(getByTestId('selectInput'), {
target: { value: 'option2' },
});
fireEvent.change(getByTestId('multipleSelectInput'), { target: { value: 'option3' } });

fireEvent.click(getByTestId('submitButton'));
});

expect(onSubmitMock).toHaveBeenCalledWith({
textInput: 'Changed Text',
textArea: 'Changed Text Area',
checkboxInput: false,
selectInput: 'option2',
multipleSelectInput: ['option3'],
});
});
});
63 changes: 63 additions & 0 deletions locust/webui/src/components/Form/tests/Select.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { render } from '@testing-library/react';
import { describe, expect, test } from 'vitest';

import Select from 'components/Form/Select';

const selectedOptionsToArray = (selectElement: HTMLSelectElement) =>
Array.from(selectElement.selectedOptions).map(option => option.value);

describe('Select component', () => {
test('should set defaultValue as first option', () => {
const options = ['Option 1', 'Option 2', 'Option 3'];

const { getByLabelText } = render(
<Select label='Select Input' name='selectInput' options={options} />,
);

expect((getByLabelText('Select Input') as HTMLSelectElement).value).toBe(options[0]);
});

test('should set defaultValue as all provided option in multi-select', () => {
const options = ['Option 1', 'Option 2', 'Option 3'];

const { getByLabelText } = render(
<Select label='Select Input' multiple name='selectInput' options={options} />,
);

expect(selectedOptionsToArray(getByLabelText('Select Input') as HTMLSelectElement)).toEqual(
options,
);
});

test('should allow defaultValue to be set', async () => {
const options = ['Option 1', 'Option 2', 'Option 3'];

const { getByLabelText } = render(
<Select
defaultValue={options[1]}
label='Select Input'
name='selectInput'
options={options}
/>,
);

expect((getByLabelText('Select Input') as HTMLSelectElement).value).toBe(options[1]);
});

test('should allow defaultValue to be set in multi-select', async () => {
const options = ['Option 1', 'Option 2', 'Option 3'];

const { getByLabelText } = render(
<Select
defaultValue={options[1]}
label='Select Input'
name='selectInput'
options={options}
/>,
);

expect(selectedOptionsToArray(getByLabelText('Select Input') as HTMLSelectElement)).toEqual([
options[1],
]);
});
});
61 changes: 15 additions & 46 deletions locust/webui/src/components/SwarmForm/SwarmCustomParameters.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { useMemo } from 'react';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import {
Accordion,
AccordionDetails,
AccordionSummary,
Box,
Checkbox,
FormControlLabel,
TextField,
Typography,
} from '@mui/material';
Expand All @@ -19,20 +20,16 @@ interface ICustomParameters {

interface ICustomInputProps extends IExtraOptionParameter {
label: string;
defaultValue: string;
}

const isParamterValid = (parameter: IExtraOptionParameter) =>
parameter.defaultValue !== null && typeof parameter.defaultValue !== 'boolean';

function CustomInput({ label, defaultValue, choices, helpText, isSecret }: ICustomInputProps) {
const labelTitle = toTitleCase(label);
const labelWithOptionalHelpText = helpText ? `${labelTitle} (${helpText})` : labelTitle;

if (choices) {
return (
<Select
defaultValue={defaultValue}
defaultValue={defaultValue as string}
label={labelWithOptionalHelpText}
name={label}
options={choices}
Expand All @@ -41,6 +38,16 @@ function CustomInput({ label, defaultValue, choices, helpText, isSecret }: ICust
);
}

if (typeof defaultValue === 'boolean') {
return (
<FormControlLabel
control={<Checkbox defaultChecked={defaultValue} />}
label={labelWithOptionalHelpText}
name={label}
/>
);
}

return (
<TextField
defaultValue={defaultValue}
Expand All @@ -53,54 +60,16 @@ function CustomInput({ label, defaultValue, choices, helpText, isSecret }: ICust
}

export default function CustomParameters({ extraOptions }: ICustomParameters) {
const validParameters = useMemo<ICustomInputProps[]>(
() =>
Object.entries(extraOptions).reduce(
(filteredParamaters: ICustomInputProps[], [key, value]) =>
isParamterValid(value)
? ([...filteredParamaters, { label: key, ...value }] as ICustomInputProps[])
: filteredParamaters,
[],
),
[extraOptions],
);
const invalidParameters = useMemo<string[]>(
() =>
Object.keys(extraOptions).reduce(
(filteredParamaters: string[], key) =>
isParamterValid(extraOptions[key]) ? filteredParamaters : [...filteredParamaters, key],
[],
),
[extraOptions],
);

return (
<Accordion>
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<Typography>Custom parameters</Typography>
</AccordionSummary>
<AccordionDetails>
<Box sx={{ display: 'flex', flexDirection: 'column', rowGap: 4 }}>
{validParameters.map((parameter, index) => (
<CustomInput key={`valid-parameter-${index}`} {...parameter} />
{Object.entries(extraOptions).map(([label, inputProps], index) => (
<CustomInput key={`valid-parameter-${index}`} label={label} {...inputProps} />
))}
<Box>
{invalidParameters && (
<>
<Typography>
The following custom parameters can't be set in the Web UI, because it is a
boolean or None type:
</Typography>
<ul>
{invalidParameters.map((parameter, index) => (
<li key={`invalid-parameter-${index}`}>
<Typography>{parameter}</Typography>
</li>
))}
</ul>
</>
)}
</Box>
</Box>
</AccordionDetails>
</Accordion>
Expand Down
Loading