code
stringlengths 66
870k
| docstring
stringlengths 19
26.7k
| func_name
stringlengths 1
138
| language
stringclasses 1
value | repo
stringlengths 7
68
| path
stringlengths 5
324
| url
stringlengths 46
389
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def _get_grid_lines(grid: list[list[int]]) -> tuple[list[ColRowGridLines], list[ColRowGridLines]]:
"""Gets list of ColRowGridLines for components and spaces on screen for validation and placement."""
component_grid_lines = []
unique_grid_idx = _get_unique_grid_component_ids(grid)
for component_idx in unique_grid_idx:
matrix = ma.masked_equal(grid, component_idx)
component_grid_lines.append(_convert_to_combined_grid_coord(matrix))
matrix = ma.masked_equal(grid, EMPTY_SPACE_CONST)
space_grid_lines = _convert_to_single_grid_coord(matrix=matrix)
return component_grid_lines, space_grid_lines
|
Gets list of ColRowGridLines for components and spaces on screen for validation and placement.
|
_get_grid_lines
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_grid.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_grid.py
|
Apache-2.0
|
def build(self):
"""Creates empty container with inline style to later position components in."""
components_content = [
html.Div(
id=f"{self.id}_{component_idx}",
style={
"gridColumn": f"{grid_coord.col_start}/{grid_coord.col_end}",
"gridRow": f"{grid_coord.row_start}/{grid_coord.row_end}",
"height": "100%",
"width": "100%",
},
className="grid-item",
)
for component_idx, grid_coord in enumerate(self.component_grid_lines)
]
component_container = html.Div(
components_content,
style={
"gridRowGap": self.row_gap,
"gridColumnGap": self.col_gap,
"gridTemplateColumns": f"repeat({len(self.grid[0])},minmax({self.col_min_width}, 1fr))",
"gridTemplateRows": f"repeat({len(self.grid)},minmax({self.row_min_height}, 1fr))",
},
className="grid-layout",
id=self.id,
)
return component_container
|
Creates empty container with inline style to later position components in.
|
build
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_grid.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_grid.py
|
Apache-2.0
|
def _build_inner_layout(layout, components):
"""Builds inner layout and adds components to grid or flex. Used inside `Page`, `Container` and `Form`."""
from vizro.models import Grid
components_container = layout.build()
if isinstance(layout, Grid):
for idx, component in enumerate(components):
components_container[f"{layout.id}_{idx}"].children = component.build()
else:
components_container.children = [html.Div(component.build(), className="flex-item") for component in components]
return components_container
|
Builds inner layout and adds components to grid or flex. Used inside `Page`, `Container` and `Form`.
|
_build_inner_layout
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_models_utils.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_models_utils.py
|
Apache-2.0
|
def model_post_init(self, context: Any) -> None:
"""Adds the model instance to the model manager."""
try:
super().model_post_init(context)
except DuplicateIDError as exc:
raise ValueError(
f"Page with id={self.id} already exists. Page id is automatically set to the same "
f"as the page title. If you have multiple pages with the same title then you must assign a unique id."
) from exc
|
Adds the model instance to the model manager.
|
model_post_init
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_page.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_page.py
|
Apache-2.0
|
def _get_control_states(self, control_type: ControlType) -> list[State]:
"""Gets list of `States` for selected `control_type` that appear on page where this Action is defined."""
# Possibly the code that specifies the state associated with a control will move to an inputs property
# of the filter and parameter models in future. This property could match outputs and return just a dotted
# string that is then transformed to State inside _transformed_inputs. This would prevent us from using
# pattern-matching callback here though.
# See also notes in filter_interaction._get_triggered_model.
page = model_manager._get_model_page(self)
return [
State(*control.selector._action_inputs["__default__"].split("."))
for control in cast(Iterable[ControlType], model_manager._get_models(control_type, page))
]
|
Gets list of `States` for selected `control_type` that appear on page where this Action is defined.
|
_get_control_states
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_action/_action.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_action/_action.py
|
Apache-2.0
|
def _get_filter_interaction_states(self) -> list[dict[str, State]]:
"""Gets list of `States` for selected chart interaction `filter_interaction`."""
from vizro.actions import filter_interaction
page = model_manager._get_model_page(self)
return [
action._get_triggered_model()._filter_interaction_input
for action in model_manager._get_models(filter_interaction, root_model=page)
]
|
Gets list of `States` for selected chart interaction `filter_interaction`.
|
_get_filter_interaction_states
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_action/_action.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_action/_action.py
|
Apache-2.0
|
def _transform_dependency(dependency: _IdOrIdProperty, type: Literal["output", "input"]) -> _IdProperty:
"""Transform a component dependency into its mapped property value.
This method handles two formats of component dependencies:
1. Explicit format: "component-id.component-property" (e.g. "graph-1.figure")
- Returns the mapped value if it exists in the component's _action_outputs/_action_inputs
- Returns the original dependency otherwise
2. Implicit format: "component-id" (e.g. "card-id")
- Returns the value of "__default__" key from the component's _action_outputs/_action_inputs
- Raises an error if the component doesn't exist or doesn't have the required property
Args:
dependency: A string in either "component-id.component-property" or "component-id" format
type: Either "input" or "output" to determine which property (_action_inputs or _action_outputs) to check
Returns:
The mapped property value for implicit format, or the original dependency for explicit format
Raises:
KeyError: If component does not exist in model_manager
KeyError: If component exists but has no "__default__" key in its _action_outputs/_action_inputs
AttributeError: If component exists but has no _action_outputs/_action_inputs property defined
ValueError: If dependency format is invalid (e.g. "id.prop.prop" or "id..prop")
"""
attribute_type = "_action_outputs" if type == "output" else "_action_inputs"
# Validate that the dependency is in one of two valid formats: id.property ("graph-1.figure") or id ("card-id").
# By this point we have already validation dependency is a str.
if not re.match(r"^[^.]+$|^[^.]+[.][^.]+$", dependency):
raise ValueError(
f"Invalid {type} format '{dependency}'. Expected format is '<model_id>' or "
f"'<model_id>.<argument_name>'."
)
if "." in dependency:
component_id, component_property = dependency.split(".")
try:
return getattr(model_manager[component_id], attribute_type)[component_property]
except (KeyError, AttributeError):
# Captures these cases and returns dependency unchanged, as we want to allow the user to target
# Dash components, that are not registered in the model_manager (e.g. theme-selector).
# 1. component_id is not in model_manager
# 2. component doesn't have _action_outputs/_action_inputs defined
# 3. component_property is not in the _action_outputs/inputs dictionary
return dependency
component_id, component_property = dependency, "__default__"
try:
return getattr(model_manager[component_id], attribute_type)[component_property]
except (KeyError, AttributeError) as exc:
if isinstance(exc, KeyError):
if component_property in str(exc):
raise KeyError(
f"Model with ID `{component_id}` has no `{component_property}` key inside its "
f"`{attribute_type}` property. Please specify the {type} explicitly as "
f"`{component_id}.<property>`."
) from exc
raise KeyError(
f"Model with ID `{component_id}` not found. Please provide a valid component ID."
) from exc
raise AttributeError(
f"Model with ID '{component_id}' does not have implicit {type} properties defined. "
f"Please specify the {type} explicitly as '{component_id}.<property>'."
) from exc
|
Transform a component dependency into its mapped property value.
This method handles two formats of component dependencies:
1. Explicit format: "component-id.component-property" (e.g. "graph-1.figure")
- Returns the mapped value if it exists in the component's _action_outputs/_action_inputs
- Returns the original dependency otherwise
2. Implicit format: "component-id" (e.g. "card-id")
- Returns the value of "__default__" key from the component's _action_outputs/_action_inputs
- Raises an error if the component doesn't exist or doesn't have the required property
Args:
dependency: A string in either "component-id.component-property" or "component-id" format
type: Either "input" or "output" to determine which property (_action_inputs or _action_outputs) to check
Returns:
The mapped property value for implicit format, or the original dependency for explicit format
Raises:
KeyError: If component does not exist in model_manager
KeyError: If component exists but has no "__default__" key in its _action_outputs/_action_inputs
AttributeError: If component exists but has no _action_outputs/_action_inputs property defined
ValueError: If dependency format is invalid (e.g. "id.prop.prop" or "id..prop")
|
_transform_dependency
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_action/_action.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_action/_action.py
|
Apache-2.0
|
def _transformed_inputs(self) -> Union[list[State], dict[str, Union[State, ControlsStates]]]:
"""Creates Dash States given the user-specified runtime arguments and built in ones.
Return type is list only for legacy actions. Otherwise, it will always be a dictionary (unlike
for _transformed_outputs, where new behavior can still give a list). Keys are the parameter names. For
user-specified inputs, values are Dash States. For built-in inputs, values can be more complicated nested
structure of states.
"""
if self._legacy:
# Must be an Action rather than _AbstractAction, so has already been validated by pydantic field annotation.
return [
State(*self._transform_dependency(input, type="input").split("."))
for input in cast(Action, self).inputs
]
from vizro.models import Filter, Parameter
builtin_args = {
"_controls": {
"filters": self._get_control_states(control_type=Filter),
"parameters": self._get_control_states(control_type=Parameter),
"filter_interaction": self._get_filter_interaction_states(),
}
}
# Work out which built in arguments are actually required for this function.
builtin_args = {
arg_name: arg_value for arg_name, arg_value in builtin_args.items() if arg_name in self._parameters
}
# Validate that the runtime arguments are in the same form as the legacy Action.inputs field (str).
# Currently, this code only runs for subclasses of _AbstractAction but not vm.Action instances because a
# vm.Action that does not pass this check will have already been classified as legacy in Action._legacy.
# In future when vm.Action.inputs is deprecated then this will be used for vm.Action instances also.
TypeAdapter(dict[str, str]).validate_python(self._runtime_args)
# User specified arguments runtime_args take precedence over built in reserved arguments. No static arguments
# ar relevant here, just Dash States. Static arguments values are stored in the state of the relevant
# _AbstractAction instance.
runtime_args = {
arg_name: State(*self._transform_dependency(arg_value, type="input").split("."))
for arg_name, arg_value in self._runtime_args.items()
}
return builtin_args | runtime_args
|
Creates Dash States given the user-specified runtime arguments and built in ones.
Return type is list only for legacy actions. Otherwise, it will always be a dictionary (unlike
for _transformed_outputs, where new behavior can still give a list). Keys are the parameter names. For
user-specified inputs, values are Dash States. For built-in inputs, values can be more complicated nested
structure of states.
|
_transformed_inputs
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_action/_action.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_action/_action.py
|
Apache-2.0
|
def _transformed_outputs(self) -> Union[list[Output], dict[str, Output]]:
"""Creates Dash Output objects from string specifications in self.outputs.
Converts self.outputs (list of strings or dictionary of strings where each string is in the format
'<component_id>.<property>' or '<component_id>') and converts into Dash Output objects.
For example, ['my_graph.figure'] becomes [Output('my_graph', 'figure', allow_duplicate=True)].
Returns:
Union[list[Output], dict[str, Output]]: A list of Output objects if self.outputs is a list of strings,
or a dictionary mapping keys to Output objects if self.outputs is a dictionary of strings.
"""
def _transform_output(output):
# Action.outputs is already validated by pydantic as list[str] or dict[str, str]
# _AbstractAction._transformed_outputs does the same validation manually with TypeAdapter.
return Output(*self._transform_dependency(output, type="output").split("."), allow_duplicate=True)
if isinstance(self.outputs, list):
callback_outputs = [_transform_output(output) for output in self.outputs]
# Need to use a single Output in the @callback decorator rather than a single element list for the case
# of a single output. This means the action function can return a single value (e.g. "text") rather than a
# single element list (e.g. ["text"]).
if len(callback_outputs) == 1:
callback_outputs = callback_outputs[0]
return callback_outputs
return {output_name: _transform_output(output) for output_name, output in self.outputs.items()}
|
Creates Dash Output objects from string specifications in self.outputs.
Converts self.outputs (list of strings or dictionary of strings where each string is in the format
'<component_id>.<property>' or '<component_id>') and converts into Dash Output objects.
For example, ['my_graph.figure'] becomes [Output('my_graph', 'figure', allow_duplicate=True)].
Returns:
Union[list[Output], dict[str, Output]]: A list of Output objects if self.outputs is a list of strings,
or a dictionary mapping keys to Output objects if self.outputs is a dictionary of strings.
|
_transformed_outputs
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_action/_action.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_action/_action.py
|
Apache-2.0
|
def build(self) -> html.Div:
"""Builds a callback for the Action model and returns required components for the callback.
Returns:
Div containing a list of required components (e.g. dcc.Download) for the Action model
"""
# TODO: after sorting out model manager and pre-build order, lots of this should probably move to happen
# some time before the build phase.
external_callback_inputs = self._transformed_inputs
external_callback_outputs = self._transformed_outputs
callback_inputs = {
"external": external_callback_inputs,
"internal": {"trigger": Input({"type": "action_trigger", "action_name": self.id}, "data")},
}
callback_outputs: dict[str, Union[list[Output], dict[str, Output]]] = {
"internal": {"action_finished": Output("action_finished", "data", allow_duplicate=True)},
}
# If there are no outputs then we don't want the external part of callback_outputs to exist at all.
# This allows the action function to return None and match correctly on to the callback_outputs dictionary
# The (probably better) alternative to this would be just to define a dummy output for all such functions
# so that the external key always exists.
# Note that it's still possible to explicitly return None as a value when an output is specified.
if external_callback_outputs:
callback_outputs["external"] = external_callback_outputs
logger.debug(
"===== Building callback for Action with id %s, function %s =====",
self.id,
self._action_name,
)
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Callback inputs:\n%s", pformat(callback_inputs["external"], width=200))
logger.debug("Callback outputs:\n%s", pformat(callback_outputs.get("external"), width=200))
@callback(output=callback_outputs, inputs=callback_inputs, prevent_initial_call=True)
def callback_wrapper(external: Union[list[Any], dict[str, Any]], internal: dict[str, Any]) -> dict[str, Any]:
return_value = self._action_callback_function(inputs=external, outputs=callback_outputs.get("external"))
if "external" in callback_outputs:
return {"internal": {"action_finished": None}, "external": return_value}
return {"internal": {"action_finished": None}}
return html.Div(id=f"{self.id}_action_model_components_div", children=self._dash_components, hidden=True)
|
Builds a callback for the Action model and returns required components for the callback.
Returns:
Div containing a list of required components (e.g. dcc.Download) for the Action model
|
build
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_action/_action.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_action/_action.py
|
Apache-2.0
|
def _filter_interaction(
self, data_frame: pd.DataFrame, target: str, ctd_filter_interaction: dict[str, CallbackTriggerDict]
) -> pd.DataFrame:
"""Function to be carried out for `filter_interaction`."""
# data_frame is the DF of the target, ie the data to be filtered, hence we cannot get the DF from this model
ctd_cellClicked = ctd_filter_interaction["cellClicked"]
if not ctd_cellClicked["value"]:
return data_frame
# ctd_active_cell["id"] represents the underlying table id, so we need to fetch its parent Vizro Table actions.
source_table_actions = _get_component_actions(_get_parent_model(ctd_cellClicked["id"]))
for action in source_table_actions:
# TODO-AV2 A 1: simplify this as in
# https://github.com/mckinsey/vizro/pull/1054/commits/f4c8c5b153f3a71b93c018e9f8c6f1b918ca52f6
# Potentially this function would move to the filter_interaction action. That will be deprecated so
# no need to worry too much if it doesn't work well, but we'll need to do something similar for the
# new interaction functionality anyway.
if not isinstance(action, filter_interaction) or target not in action.targets:
continue
column = ctd_cellClicked["value"]["colId"]
clicked_data = ctd_cellClicked["value"]["value"]
data_frame = data_frame[data_frame[column].isin([clicked_data])]
return data_frame
|
Function to be carried out for `filter_interaction`.
|
_filter_interaction
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_components/ag_grid.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/ag_grid.py
|
Apache-2.0
|
def _build_container(self):
"""Returns a collapsible container based on the `collapsed` state.
If `collapsed` is `None`, returns a non-collapsible container.
Otherwise, returns a collapsible container with visibility controlled by the `collapsed` flag.
"""
if self.collapsed is None:
return _build_inner_layout(self.layout, self.components)
return dbc.Collapse(
id=f"{self.id}_collapse",
children=_build_inner_layout(self.layout, self.components),
is_open=not self.collapsed,
className="collapsible-container",
key=self.id,
)
|
Returns a collapsible container based on the `collapsed` state.
If `collapsed` is `None`, returns a non-collapsible container.
Otherwise, returns a collapsible container with visibility controlled by the `collapsed` flag.
|
_build_container
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_components/container.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/container.py
|
Apache-2.0
|
def _build_container_title(self):
"""Builds and returns the container title, including an optional icon and tooltip if collapsed."""
description = self.description.build().children if self.description is not None else [None]
title_content = [
html.Div(
[html.Span(id=f"{self.id}_title", children=self.title), *description], className="inner-container-title"
)
]
if self.collapsed is not None:
# collapse_container is not run when page is initially loaded, so we set the content correctly conditional
# on self.collapsed upfront. This prevents the up/down arrow rotating on in initial load.
title_content.extend(
[
html.Span(
"keyboard_arrow_down" if self.collapsed else "keyboard_arrow_up",
className="material-symbols-outlined",
id=f"{self.id}_icon",
),
dbc.Tooltip(
id=f"{self.id}_tooltip",
children="Show Content" if self.collapsed else "Hide Content",
target=f"{self.id}_icon",
),
]
)
return html.H3(
children=title_content,
className="container-title-collapse" if self.collapsed is not None else "container-title",
id=f"{self.id}_title_content",
)
|
Builds and returns the container title, including an optional icon and tooltip if collapsed.
|
_build_container_title
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_components/container.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/container.py
|
Apache-2.0
|
def _filter_interaction(
self, data_frame: pd.DataFrame, target: str, ctd_filter_interaction: dict[str, CallbackTriggerDict]
) -> pd.DataFrame:
"""Function to be carried out for `filter_interaction`."""
# data_frame is the DF of the target, ie the data to be filtered, hence we cannot get the DF from this model
ctd_click_data = ctd_filter_interaction["clickData"]
if not ctd_click_data["value"]:
return data_frame
source_graph_id: ModelID = ctd_click_data["id"]
source_graph_actions = _get_component_actions(model_manager[source_graph_id])
try:
custom_data_columns = cast(Graph, model_manager[source_graph_id])["custom_data"]
except KeyError as exc:
raise KeyError(
f"Missing 'custom_data' for the source graph with id {source_graph_id}. "
"Ensure that `custom_data` is an argument of the custom chart function, and that the relevant entry is "
"then passed to the underlying plotly function. When configuring the custom chart in `vm.Graph`, "
"ensure that `custom_data` is passed. Example usage: "
"vm.Graph(figure=my_custom_chart(df, custom_data=['column_1'], actions=[...]))"
) from exc
customdata = ctd_click_data["value"]["points"][0]["customdata"]
for action in source_graph_actions:
# TODO-AV2 A 1: simplify this as in
# https://github.com/mckinsey/vizro/pull/1054/commits/f4c8c5b153f3a71b93c018e9f8c6f1b918ca52f6
# Potentially this function would move to the filter_interaction action. That will be deprecated so
# no need to worry too much if it doesn't work well, but we'll need to do something similar for the
# new interaction functionality anyway.
if not isinstance(action, filter_interaction) or target not in action.targets:
continue
for custom_data_idx, column in enumerate(custom_data_columns):
data_frame = data_frame[data_frame[column].isin([customdata[custom_data_idx]])]
return data_frame
|
Function to be carried out for `filter_interaction`.
|
_filter_interaction
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_components/graph.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/graph.py
|
Apache-2.0
|
def _optimise_fig_layout_for_dashboard(fig):
"""Post layout updates to visually enhance charts used inside dashboard."""
# Determine if a title is present
has_title = bool(fig.layout.title.text)
# TODO: Check whether we should increase margins for all chart types in template_dashboard_overrides.py instead
if any(isinstance(plotly_obj, go.Parcoords) for plotly_obj in fig.data):
# Avoid hidden labels in Parcoords figures by increasing margins compared to dashboard defaults
fig.update_layout(
margin={
"t": fig.layout.margin.t or (92 if has_title else 40),
"l": fig.layout.margin.l or 36,
"b": fig.layout.margin.b or 24,
},
)
if has_title and fig.layout.margin.t is None:
# Reduce `margin_t` if not explicitly set.
fig.update_layout(margin_t=64)
return fig
|
Post layout updates to visually enhance charts used inside dashboard.
|
_optimise_fig_layout_for_dashboard
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_components/graph.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/graph.py
|
Apache-2.0
|
def _filter_interaction(
self, data_frame: pd.DataFrame, target: str, ctd_filter_interaction: dict[str, CallbackTriggerDict]
) -> pd.DataFrame:
"""Function to be carried out for `filter_interaction`."""
# data_frame is the DF of the target, ie the data to be filtered, hence we cannot get the DF from this model
ctd_active_cell = ctd_filter_interaction["active_cell"]
ctd_derived_viewport_data = ctd_filter_interaction["derived_viewport_data"]
if not ctd_active_cell["value"] or not ctd_derived_viewport_data["value"]:
return data_frame
# ctd_active_cell["id"] represents the underlying table id, so we need to fetch its parent Vizro Table actions.
source_table_actions = _get_component_actions(_get_parent_model(ctd_active_cell["id"]))
for action in source_table_actions:
# TODO-AV2 A 1: simplify this as in
# https://github.com/mckinsey/vizro/pull/1054/commits/f4c8c5b153f3a71b93c018e9f8c6f1b918ca52f6
# Potentially this function would move to the filter_interaction action. That will be deprecated so
# no need to worry too much if it doesn't work well, but we'll need to do something similar for the
# new interaction functionality anyway.
if not isinstance(action, filter_interaction) or target not in action.targets:
continue
column = ctd_active_cell["value"]["column_id"]
derived_viewport_data_row = ctd_active_cell["value"]["row"]
clicked_data = ctd_derived_viewport_data["value"][derived_viewport_data_row][column]
data_frame = data_frame[data_frame[column].isin([clicked_data])]
return data_frame
|
Function to be carried out for `filter_interaction`.
|
_filter_interaction
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_components/table.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/table.py
|
Apache-2.0
|
def _get_list_of_labels(full_options: OptionsType) -> Union[list[StrictBool], list[float], list[str], list[date]]:
"""Returns a list of labels from the selector options provided."""
if all(isinstance(option, dict) for option in full_options):
return [option["label"] for option in full_options] # type: ignore[index]
else:
return cast(Union[list[StrictBool], list[float], list[str], list[date]], full_options)
|
Returns a list of labels from the selector options provided.
|
_get_list_of_labels
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_components/form/dropdown.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/dropdown.py
|
Apache-2.0
|
def _calculate_option_height(full_options: OptionsType) -> int:
"""Calculates the height of the dropdown options based on the longest option."""
# 30 characters is roughly the number of "A" characters you can fit comfortably on a line in the dropdown.
# "A" is representative of a slightly wider than average character:
# https://stackoverflow.com/questions/3949422/which-letter-of-the-english-alphabet-takes-up-most-pixels
# We look at the longest option to find number_of_lines it requires. Option height is the same for all options
# and needs 24px for each line + 8px padding.
list_of_labels = _get_list_of_labels(full_options)
max_length = max(len(str(option)) for option in list_of_labels)
number_of_lines = math.ceil(max_length / 30)
return 8 + 24 * number_of_lines
|
Calculates the height of the dropdown options based on the longest option.
|
_calculate_option_height
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_components/form/dropdown.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/dropdown.py
|
Apache-2.0
|
def _add_select_all_option(full_options: OptionsType) -> OptionsType:
"""Adds a 'Select All' option to the list of options."""
# TODO: Move option to dictionary conversion within `get_options_and_default` function as here: https://github.com/mckinsey/vizro/pull/961#discussion_r1923356781
options_dict = [
cast(OptionsDictType, {"label": option, "value": option}) if not isinstance(option, dict) else option
for option in full_options
]
options_dict[0] = {"label": html.Div(["ALL"]), "value": "ALL"}
return options_dict
|
Adds a 'Select All' option to the list of options.
|
_add_select_all_option
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_components/form/dropdown.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/dropdown.py
|
Apache-2.0
|
def get_options_and_default(options: OptionsType, multi: bool = False) -> tuple[OptionsType, SingleValueType]:
"""Gets list of full options and default value based on user input type of `options`."""
if multi:
if all(isinstance(option, dict) for option in options):
options = [{"label": ALL_OPTION, "value": ALL_OPTION}, *options]
else:
options = [ALL_OPTION, *options]
if all(isinstance(option, dict) for option in options):
# Each option is a OptionsDictType
default_value = options[0]["value"] # type: ignore[index]
else:
default_value = options[0]
return options, default_value
|
Gets list of full options and default value based on user input type of `options`.
|
get_options_and_default
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_components/form/_form_utils.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/_form_utils.py
|
Apache-2.0
|
def is_value_contained(value: Union[SingleValueType, MultiValueType], options: OptionsType):
"""Checks if value is contained in a list."""
if isinstance(value, list):
return all(item in options for item in value)
else:
return value in options
|
Checks if value is contained in a list.
|
is_value_contained
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_components/form/_form_utils.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/_form_utils.py
|
Apache-2.0
|
def validate_options_dict(cls, data: Any) -> Any:
"""Reusable validator for the "options" argument of categorical selectors."""
if "options" not in data or not isinstance(data["options"], list):
return data
for entry in data["options"]:
if isinstance(entry, dict) and not set(entry.keys()) == {"label", "value"}:
raise ValueError("Invalid argument `options` passed. Expected a dict with keys `label` and `value`.")
return data
|
Reusable validator for the "options" argument of categorical selectors.
|
validate_options_dict
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_components/form/_form_utils.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/_form_utils.py
|
Apache-2.0
|
def validate_value(value, info: ValidationInfo):
"""Reusable validator for the "value" argument of categorical selectors."""
if "options" not in info.data or not info.data["options"]:
return value
possible_values = (
[entry["value"] for entry in info.data["options"]]
if isinstance(info.data["options"][0], dict)
else info.data["options"]
)
if hasattr(value, "__iter__") and ALL_OPTION in value:
return value
if value and not is_value_contained(value, possible_values):
raise ValueError("Please provide a valid value from `options`.")
return value
|
Reusable validator for the "value" argument of categorical selectors.
|
validate_value
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_components/form/_form_utils.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/_form_utils.py
|
Apache-2.0
|
def validate_max(max, info: ValidationInfo):
"""Validates that the `max` is not below the `min` for a range-based input."""
if max is None:
return max
if info.data["min"] is not None and max < info.data["min"]:
raise ValueError("Maximum value of selector is required to be larger than minimum value.")
return max
|
Validates that the `max` is not below the `min` for a range-based input.
|
validate_max
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_components/form/_form_utils.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/_form_utils.py
|
Apache-2.0
|
def validate_range_value(value, info: ValidationInfo):
"""Validates a value or range of values to ensure they lie within specified bounds (min/max)."""
EXPECTED_VALUE_LENGTH = 2
if value is None:
return value
lvalue, hvalue = (
(value[0], value[1])
if isinstance(value, list) and len(value) == EXPECTED_VALUE_LENGTH
# TODO: I am not sure the below makes sense.
# The field constraint on value means that it should always be a list of length 2.
# The unit tests even check for the case where value is a list of length 1 (and it should raise an error).
else (value[0], value[0])
if isinstance(value, list) and len(value) == 1
else (value, value)
)
if (info.data["min"] is not None and not lvalue >= info.data["min"]) or (
info.data["max"] is not None and not hvalue <= info.data["max"]
):
raise ValueError("Please provide a valid value between the min and max value.")
return value
|
Validates a value or range of values to ensure they lie within specified bounds (min/max).
|
validate_range_value
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_components/form/_form_utils.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/_form_utils.py
|
Apache-2.0
|
def validate_step(step, info: ValidationInfo):
"""Reusable validator for the "step" argument for sliders."""
if step is None:
return step
if info.data["max"] is not None and step > (info.data["max"] - info.data["min"]):
raise ValueError(
"The step value of the slider must be less than or equal to the difference between max and min."
)
return step
|
Reusable validator for the "step" argument for sliders.
|
validate_step
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_components/form/_form_utils.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/_form_utils.py
|
Apache-2.0
|
def _get_proposed_targets(self):
"""Get all valid figure model targets for this control based on its location in the page hierarchy."""
page = model_manager._get_model_page(self)
page_containers = model_manager._get_models(model_type=Container, root_model=page)
# Find the control's parent model. Set it as the control's parent container it exists.
# Otherwise set it as the control's page.
root_model = next(
(container for container in page_containers if self in container.controls),
page,
)
return [model.id for model in cast(Iterable[FigureType], model_manager._get_models(FIGURE_MODELS, root_model))]
|
Get all valid figure model targets for this control based on its location in the page hierarchy.
|
_get_proposed_targets
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_controls/filter.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_controls/filter.py
|
Apache-2.0
|
def _get_control_parent(control: ControlType) -> Optional[VizroBaseModel]:
"""Get the parent model of a control."""
# Return None if the control is not part of any page.
if (page := model_manager._get_model_page(model=control)) is None:
return None
# Return the Page if the control is its direct child.
if control in page.controls:
return page
# Otherwise, return the Container that contains the control.
page_containers = model_manager._get_models(model_type=Container, root_model=page)
return next(container for container in page_containers if control in container.controls)
|
Get the parent model of a control.
|
_get_control_parent
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_controls/_controls_utils.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_controls/_controls_utils.py
|
Apache-2.0
|
def _create_nav_links(self, pages: list[ModelID]):
"""Creates a `NavLink` for each provided page."""
from vizro.models import Page
nav_links = []
for page_id in pages:
page = cast(Page, model_manager[page_id])
nav_links.append(
dbc.NavLink(
children=page.title,
className="accordion-item-link",
active="exact",
href=get_relative_path(page.path),
)
)
return nav_links
|
Creates a `NavLink` for each provided page.
|
_create_nav_links
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_navigation/accordion.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_navigation/accordion.py
|
Apache-2.0
|
def _validate_pages(pages: NavPagesType) -> NavPagesType:
"""Reusable validator to check if provided Page IDs exist as registered pages."""
from vizro.models import Page
pages_as_list = list(itertools.chain(*pages.values())) if isinstance(pages, dict) else pages
# Ideally we would use dashboard.pages in the model manager here, but we only register pages in
# dashboard.pre_build and model manager cannot find a Dashboard at validation time.
registered_pages = [page.id for page in cast(Iterable[Page], model_manager._get_models(Page))]
if not pages_as_list:
raise ValueError("Ensure this value has at least 1 item.")
if unknown_pages := [page for page in pages_as_list if page not in registered_pages]:
raise ValueError(f"Unknown page ID {unknown_pages} provided to argument 'pages'.")
return pages
|
Reusable validator to check if provided Page IDs exist as registered pages.
|
_validate_pages
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/models/_navigation/_navigation_utils.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_navigation/_navigation_utils.py
|
Apache-2.0
|
def dash_ag_grid(data_frame: pd.DataFrame, **kwargs: Any) -> dag.AgGrid:
"""Implementation of `dash_ag_grid.AgGrid` with sensible defaults to be used in [`AgGrid`][vizro.models.AgGrid].
Args:
data_frame: DataFrame containing the data to be displayed.
kwargs: Additional keyword arguments to be passed to the `dash_ag_grid.AgGrid` component.
Returns:
A `dash_ag_grid.AgGrid` component with sensible defaults.
Examples:
Wrap inside `vm.AgGrid` to use as a component inside `vm.Page` or `vm.Container`.
>>> import vizro.models as vm
>>> from vizro.tables import dash_ag_grid
>>> vm.Page(title="Page", components=[vm.AgGrid(figure=dash_ag_grid(...))])
"""
defaults = {
"className": "ag-theme-quartz-dark ag-theme-vizro",
"columnDefs": [{"field": col} for col in data_frame.columns],
"rowData": data_frame.apply(
lambda x: (
x.dt.strftime("%Y-%m-%d") # set date columns to `dateString` for AG Grid filtering to function
if pd.api.types.is_datetime64_any_dtype(x)
else x
)
).to_dict("records"),
"defaultColDef": {
"resizable": True,
"sortable": True,
"filter": True,
"flex": 1,
"filterParams": {
"buttons": ["apply", "reset"],
"closeOnApply": True,
},
},
"dashGridOptions": {
"dataTypeDefinitions": _DATA_TYPE_DEFINITIONS,
"animateRows": False,
},
}
kwargs = _set_defaults_nested(kwargs, defaults)
return dag.AgGrid(**kwargs)
|
Implementation of `dash_ag_grid.AgGrid` with sensible defaults to be used in [`AgGrid`][vizro.models.AgGrid].
Args:
data_frame: DataFrame containing the data to be displayed.
kwargs: Additional keyword arguments to be passed to the `dash_ag_grid.AgGrid` component.
Returns:
A `dash_ag_grid.AgGrid` component with sensible defaults.
Examples:
Wrap inside `vm.AgGrid` to use as a component inside `vm.Page` or `vm.Container`.
>>> import vizro.models as vm
>>> from vizro.tables import dash_ag_grid
>>> vm.Page(title="Page", components=[vm.AgGrid(figure=dash_ag_grid(...))])
|
dash_ag_grid
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/tables/_dash_ag_grid.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/tables/_dash_ag_grid.py
|
Apache-2.0
|
def dash_data_table(data_frame: pd.DataFrame, **kwargs: Any) -> dash_table.DataTable:
"""Standard `dash.dash_table.DataTable` with sensible defaults to be used in [`Table`][vizro.models.Table].
Args:
data_frame: DataFrame containing the data to be displayed.
kwargs: Additional keyword arguments to be passed to the `dash_table.DataTable` component.
Returns:
A `dash.dash_table.DataTable` component with sensible defaults.
Examples:
Wrap inside `vm.Table` to use as a component inside `vm.Page` or `vm.Container`.
>>> import vizro.models as vm
>>> from vizro.table import dash_data_table
>>> vm.Page(title="Page", components=[vm.Table(figure=dash_data_table(...))])
"""
defaults = {
"columns": [{"name": col, "id": col} for col in data_frame.columns],
"style_as_list_view": True,
"style_cell": {"position": "static"},
"style_data": {"border_bottom": "1px solid var(--border-subtleAlpha01)", "height": "40px"},
"style_header": {
"border_bottom": "1px solid var(--stateOverlays-selectedHover)",
"border_top": "None",
"height": "32px",
},
"style_data_conditional": [
{
"if": {"state": "active"},
"backgroundColor": "var(--stateOverlays-selected)",
"border": "1px solid var(--stateOverlays-selected)",
}
],
}
kwargs = _set_defaults_nested(kwargs, defaults)
return dash_table.DataTable(data=data_frame.to_dict("records"), **kwargs)
|
Standard `dash.dash_table.DataTable` with sensible defaults to be used in [`Table`][vizro.models.Table].
Args:
data_frame: DataFrame containing the data to be displayed.
kwargs: Additional keyword arguments to be passed to the `dash_table.DataTable` component.
Returns:
A `dash.dash_table.DataTable` component with sensible defaults.
Examples:
Wrap inside `vm.Table` to use as a component inside `vm.Page` or `vm.Container`.
>>> import vizro.models as vm
>>> from vizro.table import dash_data_table
>>> vm.Page(title="Page", components=[vm.Table(figure=dash_data_table(...))])
|
dash_data_table
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/tables/_dash_table.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/tables/_dash_table.py
|
Apache-2.0
|
def _extract_last_two_occurrences(variable: str, css_content: str) -> tuple[Optional[str], Optional[str]]:
"""Extracts the last two occurrences of a variable from the CSS content.
Within the `vizro-bootstrap.min.css` file, variables appear multiple times: initially from the default Bootstrap
values, followed by the dark theme, and lastly the light theme. We are interested in the final two occurrences,
as these represent the values for our dark and light themes.
"""
matches = re.findall(rf"{variable}:\s*([^;]+);", css_content)
if len(matches) >= 2: # noqa: PLR2004
return matches[-2], matches[-1]
return None, None
|
Extracts the last two occurrences of a variable from the CSS content.
Within the `vizro-bootstrap.min.css` file, variables appear multiple times: initially from the default Bootstrap
values, followed by the dark theme, and lastly the light theme. We are interested in the final two occurrences,
as these represent the values for our dark and light themes.
|
_extract_last_two_occurrences
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/_themes/generate_plotly_templates.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/_themes/generate_plotly_templates.py
|
Apache-2.0
|
def extract_bs_variables_from_css(variables: list[str], css_content: str) -> tuple[dict[str, str], dict[str, str]]:
"""Extract the last two occurrences for each variable in the CSS file."""
extracted_dark = {}
extracted_light = {}
for variable in variables:
dark_value, light_value = _extract_last_two_occurrences(variable, css_content)
cleaned_variable = variable.replace("--", "").upper()
if dark_value and light_value:
extracted_dark[cleaned_variable] = dark_value
extracted_light[cleaned_variable] = light_value
return extracted_dark, extracted_light
|
Extract the last two occurrences for each variable in the CSS file.
|
extract_bs_variables_from_css
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/_themes/generate_plotly_templates.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/_themes/generate_plotly_templates.py
|
Apache-2.0
|
def generate_json_template(extracted_values: dict[str, str]) -> go.layout.Template:
"""Generates the Plotly JSON chart template."""
FONT_COLOR_PRIMARY = extracted_values["BS-PRIMARY"]
BG_COLOR = extracted_values["BS-BODY-BG"]
FONT_COLOR_SECONDARY = extracted_values["BS-SECONDARY"]
GRID_COLOR = extracted_values["BS-BORDER-COLOR"]
AXIS_COLOR = extracted_values["BS-TERTIARY-COLOR"]
# Apply common values
COLORS = get_colors()
template = create_template_common()
layout = template.layout
layout.update(
annotationdefaults_font_color=FONT_COLOR_PRIMARY,
coloraxis_colorbar_tickcolor=AXIS_COLOR,
coloraxis_colorbar_tickfont_color=FONT_COLOR_SECONDARY,
coloraxis_colorbar_title_font_color=FONT_COLOR_SECONDARY,
font_color=FONT_COLOR_PRIMARY,
geo_bgcolor=BG_COLOR,
geo_lakecolor=BG_COLOR,
geo_landcolor=BG_COLOR,
legend_font_color=FONT_COLOR_PRIMARY,
legend_title_font_color=FONT_COLOR_PRIMARY,
paper_bgcolor=BG_COLOR,
plot_bgcolor=BG_COLOR,
polar_angularaxis_gridcolor=GRID_COLOR,
polar_angularaxis_linecolor=AXIS_COLOR,
polar_bgcolor=BG_COLOR,
polar_radialaxis_gridcolor=GRID_COLOR,
polar_radialaxis_linecolor=AXIS_COLOR,
ternary_aaxis_gridcolor=GRID_COLOR,
ternary_aaxis_linecolor=AXIS_COLOR,
ternary_baxis_gridcolor=GRID_COLOR,
ternary_baxis_linecolor=AXIS_COLOR,
ternary_bgcolor=BG_COLOR,
ternary_caxis_gridcolor=GRID_COLOR,
ternary_caxis_linecolor=AXIS_COLOR,
title_font_color=FONT_COLOR_PRIMARY,
xaxis_gridcolor=GRID_COLOR,
xaxis_linecolor=AXIS_COLOR,
xaxis_tickcolor=AXIS_COLOR,
xaxis_tickfont_color=FONT_COLOR_SECONDARY,
xaxis_title_font_color=FONT_COLOR_PRIMARY,
yaxis_gridcolor=GRID_COLOR,
yaxis_linecolor=AXIS_COLOR,
yaxis_tickcolor=AXIS_COLOR,
yaxis_tickfont_color=FONT_COLOR_SECONDARY,
yaxis_title_font_color=FONT_COLOR_PRIMARY,
)
template.data.bar = [go.Bar(marker_line_color=BG_COLOR)]
template.data.waterfall = [
go.Waterfall(
decreasing={"marker": {"color": COLORS["DISCRETE_10"][1]}},
increasing={"marker": {"color": COLORS["DISCRETE_10"][0]}},
totals={"marker": {"color": "grey"}},
textfont_color=FONT_COLOR_PRIMARY,
textposition="outside",
connector={"line": {"color": AXIS_COLOR, "width": 1}},
)
]
return template
|
Generates the Plotly JSON chart template.
|
generate_json_template
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/_themes/generate_plotly_templates.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/_themes/generate_plotly_templates.py
|
Apache-2.0
|
def create_template_common() -> go.layout.Template:
"""Creates template with common values for dark and light theme.
Returns: A plotly template object, see https://plotly.com/python/reference/layout/.
"""
COLORS = get_colors()
template_common = go.layout.Template()
template_common.layout = go.Layout(
annotationdefaults_font_size=14,
annotationdefaults_showarrow=False,
bargroupgap=0.1,
coloraxis_autocolorscale=False, # Set to False as otherwise users cannot customize via `color_continous_scale`
coloraxis_colorbar_outlinewidth=0,
coloraxis_colorbar_showticklabels=True,
coloraxis_colorbar_thickness=20,
coloraxis_colorbar_tickfont_size=14,
coloraxis_colorbar_ticklabelposition="outside",
coloraxis_colorbar_ticklen=8,
coloraxis_colorbar_ticks="outside",
coloraxis_colorbar_tickwidth=1,
coloraxis_colorbar_title_font_size=14,
# Diverging, sequential and sequentialminus colorscale will only be applied automatically if
# `coloraxis_autocolorscale=True`. Otherwise, they have no effect, and the default for continuous color scales
# will be the color sequence applied to ["colorscale"]["sequential"].
colorscale_diverging=COLORS["DIVERGING_RED_CYAN"],
colorscale_sequential=COLORS["SEQUENTIAL_CYAN"],
colorscale_sequentialminus=COLORS["SEQUENTIAL_RED"][::-1],
colorway=COLORS["DISCRETE_10"],
font_family="Inter, sans-serif, Arial",
font_size=14,
legend_bgcolor=COLORS["TRANSPARENT"],
legend_font_size=14,
legend_orientation="h",
legend_title_font_size=14,
legend_y=-0.20,
map_style="carto-darkmatter",
margin_autoexpand=True,
margin_b=64,
margin_l=80,
margin_pad=0,
margin_r=24,
margin_t=64,
# Normally, we should use the primary and secondary color for activecolor and color.
# However, our rgba values are not displayed correctly with a transparent bg color.
# Hence, we use darkgrey and dimgrey for now, which seems to work fine.
modebar_activecolor="darkgrey",
modebar_bgcolor=COLORS["TRANSPARENT"],
modebar_color="dimgrey",
showlegend=True,
title_font_size=20,
title_pad_b=0,
title_pad_l=24,
title_pad_r=24,
title_pad_t=24,
title_x=0,
title_xanchor="left",
title_xref="container",
title_y=1,
title_yanchor="top",
title_yref="container",
uniformtext_minsize=12,
uniformtext_mode="hide",
xaxis_automargin=True,
xaxis_layer="below traces",
xaxis_linewidth=1,
xaxis_showline=True,
xaxis_showticklabels=True,
xaxis_tickfont_size=14,
xaxis_ticklabelposition="outside",
xaxis_ticklen=8,
xaxis_ticks="outside",
xaxis_tickwidth=1,
xaxis_title_font_size=16,
xaxis_title_standoff=8,
xaxis_visible=True,
xaxis_zeroline=False,
yaxis_automargin=True,
yaxis_layer="below traces",
yaxis_linewidth=1,
yaxis_showline=False,
yaxis_showticklabels=True,
yaxis_tickfont_size=14,
yaxis_ticklabelposition="outside",
yaxis_ticklen=8,
yaxis_ticks="outside",
yaxis_tickwidth=1,
yaxis_title_font_size=16,
yaxis_title_standoff=8,
yaxis_visible=True,
yaxis_zeroline=False,
)
return template_common
|
Creates template with common values for dark and light theme.
Returns: A plotly template object, see https://plotly.com/python/reference/layout/.
|
create_template_common
|
python
|
mckinsey/vizro
|
vizro-core/src/vizro/_themes/_common_template.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/_themes/_common_template.py
|
Apache-2.0
|
def dash_br_driver(dash_br, request):
"""Built-in driver from the dash library."""
port = request.param.get("port", cnst.DEFAULT_PORT) if hasattr(request, "param") else cnst.DEFAULT_PORT
path = request.param.get("path", "") if hasattr(request, "param") else ""
dash_br.driver.set_window_size(1920, 1080)
dash_br.server_url = f"http://127.0.0.1:{port}/{path}"
return dash_br
|
Built-in driver from the dash library.
|
dash_br_driver
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/conftest.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/conftest.py
|
Apache-2.0
|
def teardown_method(dash_br):
"""Fixture checks log errors and quits the driver after each test."""
yield
# checking for browser console errors
if os.getenv("BROWSER") in ["chrome", "chrome_mobile"]:
try:
error_logs = [log for log in dash_br.get_logs() if log["level"] == "SEVERE" or "WARNING"]
for log in error_logs:
browser_console_warnings_checker(log, error_logs)
except WebDriverException:
pass
|
Fixture checks log errors and quits the driver after each test.
|
teardown_method
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/conftest.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/conftest.py
|
Apache-2.0
|
def bar_with_highlight(data_frame, x, highlight_bar=None):
"""Custom chart to test using DatePicker with Parameter."""
fig = px.bar(data_frame=data_frame, x=x)
fig["data"][0]["marker"]["color"] = ["orange" if c == highlight_bar else "blue" for c in fig["data"][0]["x"]]
return fig
|
Custom chart to test using DatePicker with Parameter.
|
bar_with_highlight
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/custom_components/custom_charts/bar_custom.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/custom_components/custom_charts/bar_custom.py
|
Apache-2.0
|
def test_export_filtered_data(dash_br):
"""Test exporting filtered data. It is prefiltered in dashboard config."""
page_select(
dash_br,
page_path=cnst.FILTERS_PAGE_PATH,
page_name=cnst.FILTERS_PAGE,
)
# download files and compare it with base ones
dash_br.multiple_click(button_path(), 1)
check_exported_file_exists(f"{dash_br.download_path}/{cnst.FILTERED_CSV}")
check_exported_file_exists(f"{dash_br.download_path}/{cnst.FILTERED_XLSX}")
assert_files_equal(cnst.FILTERED_BASE_CSV, f"{dash_br.download_path}/{cnst.FILTERED_CSV}")
|
Test exporting filtered data. It is prefiltered in dashboard config.
|
test_export_filtered_data
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_actions.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_actions.py
|
Apache-2.0
|
def test_scatter_click_data_custom_action(dash_br):
"""Test custom action for changing data in card by interacting with graph."""
page_select(
dash_br,
page_name=cnst.FILTER_INTERACTIONS_PAGE,
)
# click on the dot in the scatter graph and check card text values
dash_br.click_at_coord_fractions(f"#{cnst.SCATTER_INTERACTIONS_ID} path:nth-of-type(20)", 0, 1)
dash_br.wait_for_text_to_equal(f"#{cnst.CARD_INTERACTIONS_ID} p", "Scatter chart clicked data:")
dash_br.wait_for_text_to_equal(f"#{cnst.CARD_INTERACTIONS_ID} h3", 'Species: "setosa"')
|
Test custom action for changing data in card by interacting with graph.
|
test_scatter_click_data_custom_action
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_actions.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_actions.py
|
Apache-2.0
|
def test_modebar(dash_br):
"""Check that modebar element exist for the chart."""
dash_br.multiple_click(f"a[href='{cnst.FILTERS_PAGE_PATH}']", 1)
dash_br.wait_for_element(f"#{cnst.SCATTER_GRAPH_ID} .modebar-container div[id^='modebar']")
|
Check that modebar element exist for the chart.
|
test_modebar
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_charts.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_charts.py
|
Apache-2.0
|
def test_modebar_false(dash_br):
"""Check that modebar element disabled for the chart."""
dash_br.multiple_click(f"a[href='{cnst.FILTERS_PAGE_PATH}']", 1)
graph_load_waiter(dash_br, cnst.BOX_GRAPH_ID)
dash_br.wait_for_no_elements(f'div[id="{cnst.BOX_GRAPH_ID}"] .modebar-container div[id^="modebar"]')
|
Check that modebar element disabled for the chart.
|
test_modebar_false
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_charts.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_charts.py
|
Apache-2.0
|
def test_custom_dropdown(dash_br):
"""Testing setting up and filter of the custom dropdown."""
page_select(
dash_br,
page_name=cnst.CUSTOM_COMPONENTS_PAGE,
)
# choose 'versicolor' value
select_dropdown_value(dash_br, value=2, dropdown_id=cnst.CUSTOM_DROPDOWN_ID)
check_graph_is_loading(dash_br, cnst.SCATTER_CUSTOM_COMPONENTS_ID)
check_selected_dropdown(
dash_br,
dropdown_id=cnst.CUSTOM_DROPDOWN_ID,
expected_selected_options=["versicolor"],
)
|
Testing setting up and filter of the custom dropdown.
|
test_custom_dropdown
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_custom_components.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_custom_components.py
|
Apache-2.0
|
def test_custom_range_slider(dash_br):
"""Testing setting up and filter of the custom range slider."""
page_select(
dash_br,
page_name=cnst.CUSTOM_COMPONENTS_PAGE,
)
dash_br.multiple_click(slider_value_path(elem_id=cnst.CUSTOM_RANGE_SLIDER_ID, value=4), 1)
check_graph_is_loading(dash_br, graph_id=cnst.SCATTER_CUSTOM_COMPONENTS_ID)
check_slider_value(dash_br, elem_id=cnst.CUSTOM_RANGE_SLIDER_ID, expected_start_value="4", expected_end_value="7")
|
Testing setting up and filter of the custom range slider.
|
test_custom_range_slider
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_custom_components.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_custom_components.py
|
Apache-2.0
|
def test_single_date(dash_br):
"""Tests that single datepicker as filter works correctly."""
accordion_select(dash_br, accordion_name=cnst.DATEPICKER_ACCORDION)
page_select(
dash_br,
page_name=cnst.DATEPICKER_PAGE,
)
# open datepicker calendar and choose date 17 May 2016
dash_br.multiple_click(f'button[id="{cnst.DATEPICKER_SINGLE_ID}"]', 1)
dash_br.wait_for_element('div[data-calendar="true"]')
dash_br.multiple_click('button[aria-label="17 May 2016"]', 1)
dash_br.wait_for_text_to_equal(f'button[id="{cnst.DATEPICKER_SINGLE_ID}"]', "May 17, 2016")
# check bar graph has bar with light blue color
dash_br.wait_for_element(f"div[id='{cnst.BAR_POP_DATE_ID}'] path[style*='rgb(13, 142, 209)']:nth-of-type(1)")
# check that date in the row is correct
# we're using 'row_number=2' because the first row is a header
dash_br.wait_for_text_to_equal(
table_cell_value_path(table_id=cnst.TABLE_POP_DATE_ID, row_number=2, column_number=1), "2016-05-17T00:00:00"
)
# check that we have only 1 row in the table
# we're using 'expected_rows_num=2' because the first row is a header
check_table_rows_number(dash_br, table_id=cnst.TABLE_POP_DATE_ID, expected_rows_num=2)
|
Tests that single datepicker as filter works correctly.
|
test_single_date
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_datepicker.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_datepicker.py
|
Apache-2.0
|
def test_single_date_param(dash_br):
"""Tests that single datepicker as parameter works correctly."""
accordion_select(dash_br, accordion_name=cnst.DATEPICKER_ACCORDION)
page_select(
dash_br,
page_name=cnst.DATEPICKER_PARAMS_PAGE,
)
# check that specific bar has blue color
dash_br.wait_for_element(f"div[id='{cnst.BAR_CUSTOM_ID}'] g:nth-of-type(14) path[style*='(0, 0, 255)'")
# open datepicker calendar and choose date 2 May 2018
dash_br.multiple_click(f'button[id="{cnst.DATEPICKER_PARAMS_ID}"]', 1)
dash_br.wait_for_element('div[data-calendar="true"]')
dash_br.multiple_click('button[aria-label="2 April 2018"]', 1)
# check that specific bar change color from blue to orange
dash_br.wait_for_element(f"div[id='{cnst.BAR_CUSTOM_ID}'] g:nth-of-type(14) path[style*='(255, 165, 0)'")
|
Tests that single datepicker as parameter works correctly.
|
test_single_date_param
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_datepicker.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_datepicker.py
|
Apache-2.0
|
def test_data_dynamic_parametrization(dash_br, cache, slider_id):
"""This test checks parametrized data loading and how it is working with and without cache."""
first_screen = f"{cache}_screen_first_test_data_dynamic_parametrization.png"
second_screen = f"{cache}_screen_second_test_data_dynamic_parametrization.png"
third_screen = f"{cache}_screen_third_test_data_dynamic_parametrization.png"
accordion_select(dash_br, accordion_name=cnst.DYNAMIC_DATA_ACCORDION)
page_select(
dash_br,
page_name=cnst.DYNAMIC_DATA_PAGE,
)
# move slider to value '20'
select_slider_handler(dash_br, elem_id=slider_id, value=2)
callbacks_finish_waiter(dash_br)
dash_br.driver.save_screenshot(first_screen)
# move slider to value '60'
select_slider_handler(dash_br, elem_id=slider_id, value=6)
callbacks_finish_waiter(dash_br)
dash_br.driver.save_screenshot(second_screen)
# move slider to value '20'
select_slider_handler(dash_br, elem_id=slider_id, value=2)
callbacks_finish_waiter(dash_br)
dash_br.driver.save_screenshot(third_screen)
# first and second screens should be different
assert_image_not_equal(first_screen, second_screen)
if cache == "cached":
# first and third screens should be the same
assert_pixelmatch(first_screen, third_screen)
if cache == "not_cached":
# first and third screens should be different
assert_image_not_equal(first_screen, third_screen)
for file in Path(".").glob("*test_data_dynamic_parametrization*"):
file.unlink()
|
This test checks parametrized data loading and how it is working with and without cache.
|
test_data_dynamic_parametrization
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_dynamic_data.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_dynamic_data.py
|
Apache-2.0
|
def test_numerical_filters(dash_br):
"""Initial selected value for slider is 6. Initial selected values for range_slider are 6 and 7."""
accordion_select(dash_br, accordion_name=cnst.DYNAMIC_DATA_ACCORDION)
page_select(
dash_br,
page_name=cnst.DYNAMIC_FILTERS_NUMERICAL_PAGE,
)
# Set "min" option to "5" for the dynamic data and simulate refreshing the page
page_select(
dash_br,
page_name=cnst.DYNAMIC_FILTERS_CATEGORICAL_PAGE,
)
dynamic_filters_data_config_manipulation(key="min", set_value=5)
page_select(
dash_br,
page_name=cnst.DYNAMIC_FILTERS_NUMERICAL_PAGE,
)
# Check slider value
check_slider_value(dash_br, expected_end_value="6", elem_id=cnst.SLIDER_DYNAMIC_FILTER_ID)
# Check range slider values
check_slider_value(
dash_br, elem_id=cnst.RANGE_SLIDER_DYNAMIC_FILTER_ID, expected_start_value="6", expected_end_value="7"
)
# Change "min" slider and range slider values to "5"
dash_br.multiple_click(slider_value_path(elem_id=cnst.SLIDER_DYNAMIC_FILTER_ID, value=1), 1)
check_graph_is_loading(dash_br, graph_id=cnst.BAR_DYNAMIC_FILTER_ID)
dash_br.multiple_click(slider_value_path(elem_id=cnst.RANGE_SLIDER_DYNAMIC_FILTER_ID, value=1), 1)
check_graph_is_loading(dash_br, graph_id=cnst.BAR_DYNAMIC_FILTER_ID)
# Check slider value
check_slider_value(dash_br, expected_end_value="5", elem_id=cnst.SLIDER_DYNAMIC_FILTER_ID)
# Check range slider values
check_slider_value(
dash_br, elem_id=cnst.RANGE_SLIDER_DYNAMIC_FILTER_ID, expected_start_value="5", expected_end_value="7"
)
# Set "min" option to "6" for the dynamic data and simulate refreshing the page
page_select(
dash_br,
page_name=cnst.DYNAMIC_FILTERS_CATEGORICAL_PAGE,
)
dynamic_filters_data_config_manipulation(key="min", set_value=6)
page_select(
dash_br,
page_name=cnst.DYNAMIC_FILTERS_NUMERICAL_PAGE,
)
# Check slider value
check_slider_value(dash_br, expected_end_value="5", elem_id=cnst.SLIDER_DYNAMIC_FILTER_ID)
# Check range slider values
check_slider_value(
dash_br, elem_id=cnst.RANGE_SLIDER_DYNAMIC_FILTER_ID, expected_start_value="5", expected_end_value="7"
)
|
Initial selected value for slider is 6. Initial selected values for range_slider are 6 and 7.
|
test_numerical_filters
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_dynamic_data.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_dynamic_data.py
|
Apache-2.0
|
def test_dynamic_data_parameter_refresh_dynamic_filters(dash_br):
"""Test automatic refreshing of the dynamic filters and their targets when the data_frame parameter is changed.
Page configuration includes dynamic data scatter chart which controls by slider parameter and static data scatter
which has 'virginica' data only.
"""
accordion_select(dash_br, accordion_name=cnst.DYNAMIC_DATA_ACCORDION.upper())
page_select(
dash_br,
page_name=cnst.DYNAMIC_DATA_DF_PARAMETER_PAGE,
)
# select 'virginica' value and check scatter graph point color
dash_br.multiple_click(categorical_components_value_path(elem_id=cnst.RADIOITEMS_FILTER_DF_PARAMETER, value=3), 1)
dash_br.wait_for_element(f"div[id='{cnst.SCATTER_DF_PARAMETER}'] path[style*='rgb(57, 73, 171)']:nth-of-type(1)")
dash_br.wait_for_element(f"div[id='{cnst.SCATTER_DF_STATIC}'] path[style*='rgb(57, 73, 171)']:nth-of-type(1)")
# select '10' points for slider which is showing only 'setosa' data and check that scatter graph
# with dynamic data is empty and that scatter graph with static data is the same
select_slider_handler(dash_br, elem_id=cnst.SLIDER_DF_PARAMETER, value=2)
check_graph_is_loading(dash_br, graph_id=cnst.SCATTER_DF_STATIC)
check_graph_is_empty(dash_br, graph_id=cnst.SCATTER_DF_PARAMETER)
dash_br.wait_for_element(f"div[id='{cnst.SCATTER_DF_STATIC}'] path[style*='rgb(57, 73, 171)']:nth-of-type(1)")
# Check that "setosa" and "virginica" is the only listed options
check_selected_categorical_component(
dash_br,
component_id=cnst.RADIOITEMS_FILTER_DF_PARAMETER,
options_value_status=[
{"value": 1, "selected": False, "value_name": "setosa"},
{"value": 2, "selected": True, "value_name": "virginica"},
],
)
# simulate refreshing the page to check if filters and graphs stays the same
page_select(dash_br, page_name=cnst.DYNAMIC_FILTERS_CATEGORICAL_PAGE)
page_select(dash_br, page_name=cnst.DYNAMIC_DATA_DF_PARAMETER_PAGE)
# check that dynamic data graph is empty and static data graph stays the same
check_graph_is_empty(dash_br, graph_id=cnst.SCATTER_DF_PARAMETER)
dash_br.wait_for_element(f"div[id='{cnst.SCATTER_DF_STATIC}'] path[style*='rgb(57, 73, 171)']:nth-of-type(1)")
# Check that "setosa" and "virginica" is the only listed options
check_selected_categorical_component(
dash_br,
component_id=cnst.RADIOITEMS_FILTER_DF_PARAMETER,
options_value_status=[
{"value": 1, "selected": False, "value_name": "setosa"},
{"value": 2, "selected": True, "value_name": "virginica"},
],
)
# select 'setosa' value and check dynamic scatter graph point color and that static scatter graph is empty
dash_br.multiple_click(categorical_components_value_path(elem_id=cnst.RADIOITEMS_FILTER_DF_PARAMETER, value=1), 1)
dash_br.wait_for_element(f"div[id='{cnst.SCATTER_DF_PARAMETER}'] path[style*='rgb(0, 180, 255)']:nth-of-type(1)")
check_graph_is_empty(dash_br, graph_id=cnst.SCATTER_DF_STATIC)
# Check that "setosa" and "virginica" is the only listed options
check_selected_categorical_component(
dash_br,
component_id=cnst.RADIOITEMS_FILTER_DF_PARAMETER,
options_value_status=[
{"value": 1, "selected": True, "value_name": "setosa"},
{"value": 2, "selected": False, "value_name": "virginica"},
],
)
|
Test automatic refreshing of the dynamic filters and their targets when the data_frame parameter is changed.
Page configuration includes dynamic data scatter chart which controls by slider parameter and static data scatter
which has 'virginica' data only.
|
test_dynamic_data_parameter_refresh_dynamic_filters
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_dynamic_data.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_dynamic_data.py
|
Apache-2.0
|
def test_dropdown_homepage(dash_br):
"""Test dropdown filter for the homepage."""
graph_load_waiter(dash_br, graph_id=cnst.AREA_GRAPH_ID)
# select 'setosa'
select_dropdown_value(dash_br, value=2, dropdown_id=cnst.DROPDOWN_FILTER_HOMEPAGEPAGE)
check_graph_is_loading(dash_br, cnst.AREA_GRAPH_ID)
|
Test dropdown filter for the homepage.
|
test_dropdown_homepage
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_filters.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_filters.py
|
Apache-2.0
|
def test_filter_and_parameter(dash_br):
"""Testing filter and parameter on the same page."""
page_select(
dash_br,
page_name=cnst.FILTER_AND_PARAM_PAGE,
)
# check that title of the graph is 'blue'
dash_br.wait_for_text_to_equal(".gtitle", "blue")
# select 'red' value in the radio item parameter selector and the title of the graph
dash_br.multiple_click(categorical_components_value_path(elem_id=cnst.RADIO_ITEMS_FILTER_AND_PARAM, value=1), 1)
check_graph_is_loading(dash_br, graph_id=cnst.BOX_FILTER_AND_PARAM_ID)
dash_br.wait_for_text_to_equal(".gtitle", "red")
# select 'setosa' in dropdown filter selector
select_dropdown_value(dash_br, value=1, dropdown_id=cnst.DROPDOWN_FILTER_AND_PARAM)
check_graph_is_loading(dash_br, graph_id=cnst.BOX_FILTER_AND_PARAM_ID)
|
Testing filter and parameter on the same page.
|
test_filter_and_parameter
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_filter_and_param_config.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_filter_and_param_config.py
|
Apache-2.0
|
def test_interactions(dash_br):
"""Test filter interactions between two graphs."""
page_select(
dash_br,
page_name=cnst.FILTER_INTERACTIONS_PAGE,
)
# click on the 'setosa' data in scatter graph and check result for box graph
dash_br.click_at_coord_fractions(f"#{cnst.SCATTER_INTERACTIONS_ID} path:nth-of-type(20)", 0, 1)
check_graph_is_loading(dash_br, cnst.BOX_INTERACTIONS_ID)
dash_br.wait_for_element(f"div[id='{cnst.BOX_INTERACTIONS_ID}'] path[style*='rgb(0, 180, 255)']:nth-of-type(14)")
# select 'setosa' in dropdown filter and check result for box graph
select_dropdown_value(dash_br, value=2, dropdown_id=cnst.DROPDOWN_INTER_FILTER)
check_graph_is_loading(dash_br, cnst.BOX_INTERACTIONS_ID)
dash_br.wait_for_element(f"div[id='{cnst.BOX_INTERACTIONS_ID}'] path[style*='rgb(0, 180, 255)']:nth-of-type(14)")
# select 'red' title for the box graph
dash_br.multiple_click(categorical_components_value_path(elem_id=cnst.RADIOITEM_INTER_PARAM, value=1), 1)
check_graph_is_loading(dash_br, cnst.BOX_INTERACTIONS_ID)
dash_br.wait_for_text_to_equal(".gtitle", "red")
|
Test filter interactions between two graphs.
|
test_interactions
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_interactions.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_interactions.py
|
Apache-2.0
|
def test_pages(dash_br):
"""Test of going from homepage to filters page and back using card link."""
# open homepage and check title text
graph_load_waiter(dash_br, graph_id=cnst.AREA_GRAPH_ID)
dash_br.wait_for_text_to_equal(page_title_path(), cnst.HOME_PAGE)
# open filters page using card link and check title text
dash_br.multiple_click(nav_card_link_path(href=cnst.FILTERS_PAGE_PATH), 1)
graph_load_waiter(dash_br, graph_id=cnst.SCATTER_GRAPH_ID)
dash_br.wait_for_text_to_equal(page_title_path(), text=cnst.FILTERS_PAGE)
# open homepage using card link and check title text
dash_br.multiple_click(nav_card_link_path(href=cnst.HOME_PAGE_PATH), 1)
graph_load_waiter(dash_br, graph_id=cnst.AREA_GRAPH_ID)
dash_br.wait_for_text_to_equal(page_title_path(), cnst.HOME_PAGE)
|
Test of going from homepage to filters page and back using card link.
|
test_pages
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_pages.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_pages.py
|
Apache-2.0
|
def test_active_accordion(dash_br):
"""Test opening page from card link and checking appropriate accordion is opened."""
graph_load_waiter(dash_br, graph_id=cnst.AREA_GRAPH_ID)
dash_br.multiple_click(nav_card_link_path(href=f"/{cnst.DATEPICKER_PAGE}"), 1)
graph_load_waiter(dash_br, graph_id=cnst.BAR_POP_DATE_ID)
dash_br.wait_for_text_to_equal(page_title_path(), cnst.DATEPICKER_PAGE)
check_accordion_active(dash_br, accordion_name=cnst.DATEPICKER_ACCORDION.upper())
|
Test opening page from card link and checking appropriate accordion is opened.
|
test_active_accordion
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_pages.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_pages.py
|
Apache-2.0
|
def test_404_page(dash_br):
"""Test opening page that doesn't exist."""
graph_load_waiter(dash_br, graph_id=cnst.AREA_GRAPH_ID)
dash_br.multiple_click(nav_card_link_path(href=cnst.PAGE_404_PATH), 1)
dash_br.wait_for_text_to_equal("a[class='mt-4 btn btn-primary']", "Take me home")
dash_br.multiple_click("a[class='mt-4 btn btn-primary']", 1)
graph_load_waiter(dash_br, graph_id=cnst.AREA_GRAPH_ID)
dash_br.wait_for_text_to_equal(page_title_path(), cnst.HOME_PAGE)
|
Test opening page that doesn't exist.
|
test_404_page
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_pages.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_pages.py
|
Apache-2.0
|
def test_sliders_state(dash_br):
"""Verify that sliders values stays the same after page reload."""
page_select(
dash_br,
page_path=cnst.PARAMETERS_PAGE_PATH,
page_name=cnst.PARAMETERS_PAGE,
)
# change slider value to '0.4'
dash_br.multiple_click(slider_value_path(elem_id=cnst.SLIDER_PARAMETERS, value=3), 1)
check_graph_is_loading(dash_br, graph_id=cnst.BAR_GRAPH_ID)
# change range slider max value to '7'
dash_br.multiple_click(slider_value_path(elem_id=cnst.RANGE_SLIDER_PARAMETERS, value=4), 1)
check_graph_is_loading(dash_br, graph_id=cnst.HISTOGRAM_GRAPH_ID)
# refresh the page
page_select(dash_br, page_path=cnst.FILTERS_PAGE_PATH, page_name=cnst.FILTERS_PAGE)
page_select(
dash_br,
page_path=cnst.PARAMETERS_PAGE_PATH,
page_name=cnst.PARAMETERS_PAGE,
)
# check that slider value still '0.4'
check_slider_value(dash_br, expected_end_value="0.4", elem_id=cnst.SLIDER_PARAMETERS)
# check that range slider max value still '7'
check_slider_value(dash_br, elem_id=cnst.RANGE_SLIDER_PARAMETERS, expected_start_value="4", expected_end_value="7")
|
Verify that sliders values stays the same after page reload.
|
test_sliders_state
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_parameters.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_parameters.py
|
Apache-2.0
|
def test_none_parameter(dash_br):
"""Test if one of the parameter values is NONE."""
page_select(
dash_br,
page_path=cnst.PARAMETERS_PAGE_PATH,
page_name=cnst.PARAMETERS_PAGE,
)
# check that specific bar has blue color
dash_br.wait_for_element(
f"div[id='{cnst.BAR_GRAPH_ID}'] g:nth-of-type(3) g:nth-of-type(45) path[style*='(0, 0, 255)'"
)
# choose NONE parameter
select_dropdown_value(dash_br, value=1, dropdown_id=cnst.DROPDOWN_PARAMETERS_TWO)
check_graph_is_loading(dash_br, graph_id=cnst.BAR_GRAPH_ID)
# check that specific bar has cerulean blue color
dash_br.wait_for_element(
f"div[id='{cnst.BAR_GRAPH_ID}'] g:nth-of-type(3) g:nth-of-type(45) path[style*='(57, 73, 171)'"
)
|
Test if one of the parameter values is NONE.
|
test_none_parameter
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_parameters.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_parameters.py
|
Apache-2.0
|
def test_parameters_title(chrome_driver, dash_br):
"""Tests that graph title is changing by parameter independently for every user."""
# select parameters page for the first user
page_select_selenium(
chrome_driver,
page_path=cnst.PARAMETERS_PAGE_PATH,
page_name=cnst.PARAMETERS_PAGE,
)
# select parameters page for the second user
page_select(
dash_br,
page_path=cnst.PARAMETERS_PAGE_PATH,
page_name=cnst.PARAMETERS_PAGE,
)
# set bar graph title for the first user as 'red'
WebDriverWait(chrome_driver, cnst.SELENIUM_WAITERS_TIMEOUT).until(
expected_conditions.element_to_be_clickable(
(By.CSS_SELECTOR, categorical_components_value_path(elem_id=cnst.RADIO_ITEMS_PARAMETERS_ONE, value=1))
)
).click()
check_graph_is_loading_selenium(chrome_driver, graph_id=cnst.BAR_GRAPH_ID)
WebDriverWait(chrome_driver, cnst.SELENIUM_WAITERS_TIMEOUT).until(
expected_conditions.text_to_be_present_in_element((By.CSS_SELECTOR, ".gtitle"), "red")
)
# change slider value from the second user and check that bar graph title is default ('blue')
dash_br.multiple_click(slider_value_path(elem_id=cnst.SLIDER_PARAMETERS, value=3), 1)
check_graph_is_loading(dash_br, graph_id=cnst.BAR_GRAPH_ID)
dash_br.wait_for_text_to_equal(".gtitle", "blue")
|
Tests that graph title is changing by parameter independently for every user.
|
test_parameters_title
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_statelessness.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_statelessness.py
|
Apache-2.0
|
def test_theme_color(chrome_driver, dash_br):
"""Tests that theme color is changing independently for every user."""
# select parameters page for the first user
page_select_selenium(
chrome_driver,
page_path=cnst.PARAMETERS_PAGE_PATH,
page_name=cnst.PARAMETERS_PAGE,
)
# select parameters page for the second user
page_select(
dash_br,
page_path=cnst.PARAMETERS_PAGE_PATH,
page_name=cnst.PARAMETERS_PAGE,
)
# change theme to dark for the first user
WebDriverWait(chrome_driver, cnst.SELENIUM_WAITERS_TIMEOUT).until(
expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, theme_toggle_path()))
).click()
check_graph_color_selenium(chrome_driver, style_background=cnst.STYLE_TRANSPARENT, color=cnst.RGBA_TRANSPARENT)
WebDriverWait(chrome_driver, cnst.SELENIUM_WAITERS_TIMEOUT).until(
expected_conditions.presence_of_element_located((By.CSS_SELECTOR, f"html[data-bs-theme='{cnst.THEME_DARK}']"))
)
# change slider value for the second user and check that theme is default ('light')
dash_br.multiple_click(slider_value_path(elem_id=cnst.SLIDER_PARAMETERS, value=3), 1)
check_graph_is_loading(dash_br, graph_id=cnst.BAR_GRAPH_ID)
check_graph_color(dash_br, style_background=cnst.STYLE_TRANSPARENT, color=cnst.RGBA_TRANSPARENT)
check_theme_color(dash_br, color=cnst.THEME_LIGHT)
|
Tests that theme color is changing independently for every user.
|
test_theme_color
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_statelessness.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_statelessness.py
|
Apache-2.0
|
def test_export_action(chrome_driver, dash_br):
"""Tests that export action is giving different results according to what every user filters."""
# select filters page for the first user
page_select_selenium(
chrome_driver,
page_path=cnst.FILTERS_PAGE_PATH,
page_name=cnst.FILTERS_PAGE,
)
# select filters page for the second user
page_select(
dash_br,
page_path=cnst.FILTERS_PAGE_PATH,
page_name=cnst.FILTERS_PAGE,
)
# change slider values for scatter graph for the first user
WebDriverWait(chrome_driver, cnst.SELENIUM_WAITERS_TIMEOUT).until(
expected_conditions.element_to_be_clickable(
(By.CSS_SELECTOR, slider_value_path(elem_id=cnst.SLIDER_FILTER_FILTERS_PAGE, value=3))
)
).click()
check_graph_is_loading_selenium(chrome_driver, graph_id=cnst.SCATTER_GRAPH_ID)
# export scatter data for the second user without changing anything and check if data is correct
dash_br.multiple_click(button_path(), 1)
check_exported_file_exists(f"{dash_br.download_path}/{cnst.FILTERED_CSV}")
check_exported_file_exists(f"{dash_br.download_path}/{cnst.FILTERED_XLSX}")
assert_files_equal(cnst.FILTERED_BASE_CSV, f"{dash_br.download_path}/{cnst.FILTERED_CSV}")
|
Tests that export action is giving different results according to what every user filters.
|
test_export_action
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_statelessness.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_statelessness.py
|
Apache-2.0
|
def test_interactions(dash_br):
"""Test filter interaction between table and line graph."""
accordion_select(dash_br, accordion_name=cnst.AG_GRID_ACCORDION)
page_select(
dash_br,
page_name=cnst.TABLE_INTERACTIONS_PAGE,
)
# click on Bosnia and Herzegovina country
dash_br.multiple_click(
f"div[id='{cnst.TABLE_INTERACTIONS_ID}'] tr:nth-of-type(5) div[class='unfocused selectable dash-cell-value']", 1
)
check_graph_is_loading(dash_br, cnst.LINE_INTERACTIONS_ID)
check_table_rows_number(dash_br, table_id=cnst.TABLE_INTERACTIONS_ID, expected_rows_num=31)
|
Test filter interaction between table and line graph.
|
test_interactions
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_table.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_table.py
|
Apache-2.0
|
def test_interactions(dash_br):
"""Test filter interaction between ag_grid and line graph."""
accordion_select(dash_br, accordion_name=cnst.AG_GRID_ACCORDION)
page_select(
dash_br,
page_name=cnst.TABLE_AG_GRID_INTERACTIONS_PAGE,
)
# check if column 'country' is available
dash_br.wait_for_element(f"div[id='{cnst.TABLE_AG_GRID_INTERACTIONS_ID}'] div:nth-of-type(1) div[col-id='country']")
# click on Bosnia and Herzegovina country
dash_br.multiple_click(
f"div[id='{cnst.TABLE_AG_GRID_INTERACTIONS_ID}'] div[class='ag-center-cols-container'] "
f"div:nth-of-type(4) div[col-id='country']",
1,
)
check_graph_is_loading(dash_br, cnst.LINE_AG_GRID_INTERACTIONS_ID)
|
Test filter interaction between ag_grid and line graph.
|
test_interactions
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_table_ag_grid.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_table_ag_grid.py
|
Apache-2.0
|
def test_themes(dash_br_driver, dashboard_id):
"""Test switching the themes and checking the graph and theme color."""
page_select(dash_br_driver, page_path=cnst.FILTERS_PAGE_PATH, page_name=cnst.FILTERS_PAGE)
if dashboard_id == cnst.DASHBOARD_DEFAULT:
# dashboard loaded with light theme
check_graph_color(dash_br_driver, style_background=cnst.STYLE_TRANSPARENT, color=cnst.RGBA_TRANSPARENT)
check_theme_color(dash_br_driver, color=cnst.THEME_LIGHT)
# switch theme to dark
dash_br_driver.multiple_click(theme_toggle_path(), 1)
check_graph_color(dash_br_driver, style_background=cnst.STYLE_TRANSPARENT, color=cnst.RGBA_TRANSPARENT)
check_theme_color(dash_br_driver, color=cnst.THEME_DARK)
# switch theme back to light
dash_br_driver.multiple_click(theme_toggle_path(), 1)
check_graph_color(dash_br_driver, style_background=cnst.STYLE_TRANSPARENT, color=cnst.RGBA_TRANSPARENT)
check_theme_color(dash_br_driver, color=cnst.THEME_LIGHT)
else:
# dashboard loaded with dark theme
check_graph_color(dash_br_driver, style_background=cnst.STYLE_TRANSPARENT, color=cnst.RGBA_TRANSPARENT)
check_theme_color(dash_br_driver, color=cnst.THEME_DARK)
# switch theme to light
dash_br_driver.multiple_click(theme_toggle_path(), 1)
check_graph_color(dash_br_driver, style_background=cnst.STYLE_TRANSPARENT, color=cnst.RGBA_TRANSPARENT)
check_theme_color(dash_br_driver, color=cnst.THEME_LIGHT)
# switch theme back to dark
dash_br_driver.multiple_click(theme_toggle_path(), 1)
check_graph_color(dash_br_driver, style_background=cnst.STYLE_TRANSPARENT, color=cnst.RGBA_TRANSPARENT)
check_theme_color(dash_br_driver, color=cnst.THEME_DARK)
|
Test switching the themes and checking the graph and theme color.
|
test_themes
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_themes.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_themes.py
|
Apache-2.0
|
def test_themes_page_change(dash_br_driver, dashboard_id):
"""Test switching themes after reloading the page with two tabs."""
page_select(
dash_br_driver,
page_path=cnst.PARAMETERS_PAGE_PATH,
page_name=cnst.PARAMETERS_PAGE,
)
def _logic(style_background, graph_color, theme_color):
check_graph_color(dash_br_driver, style_background=style_background, color=graph_color)
check_theme_color(dash_br_driver, color=theme_color)
# switch to the second tab
dash_br_driver.multiple_click(tab_path(tab_id=cnst.PARAMETERS_SUB_TAB_ID, classname="nav-link"), 1)
check_graph_color(dash_br_driver, style_background=style_background, color=graph_color)
# simulate reloading the page
page_select(
dash_br_driver,
page_path=cnst.FILTERS_PAGE_PATH,
page_name=cnst.FILTERS_PAGE,
)
page_select(
dash_br_driver,
page_path=cnst.PARAMETERS_PAGE_PATH,
page_name=cnst.PARAMETERS_PAGE,
)
# check that second tab still active
dash_br_driver.wait_for_text_to_equal(
tab_path(tab_id=cnst.PARAMETERS_SUB_TAB_ID, classname="active nav-link"),
cnst.PARAMETERS_SUB_TAB_CONTAINER_TWO,
)
# check that graph and theme color is the same as before page reload
check_graph_color(dash_br_driver, style_background=style_background, color=graph_color)
check_theme_color(dash_br_driver, color=theme_color)
if dashboard_id == cnst.DASHBOARD_DEFAULT:
# dashboard switched to dark theme
dash_br_driver.multiple_click(theme_toggle_path(), 1)
_logic(style_background=cnst.STYLE_TRANSPARENT, graph_color=cnst.RGBA_TRANSPARENT, theme_color=cnst.THEME_DARK)
else:
# dashboard switched to light theme
dash_br_driver.multiple_click(theme_toggle_path(), 1)
_logic(style_background=cnst.STYLE_TRANSPARENT, graph_color=cnst.RGBA_TRANSPARENT, theme_color=cnst.THEME_LIGHT)
|
Test switching themes after reloading the page with two tabs.
|
test_themes_page_change
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_dom_elements/test_themes.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_dom_elements/test_themes.py
|
Apache-2.0
|
def image_assertion(func):
"""Wait until all callbacks are finished and compare screenshots."""
def wrapper(dash_br, request):
result = func(dash_br)
callbacks_finish_waiter(dash_br)
time.sleep(1) # to finish page loading
result_image_path, expected_image_path = make_screenshot_and_paths(dash_br.driver, request.node.name)
assert_image_equal(result_image_path, expected_image_path)
return result
return wrapper
|
Wait until all callbacks are finished and compare screenshots.
|
image_assertion
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_screenshots/test_screenshots.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_screenshots/test_screenshots.py
|
Apache-2.0
|
def test_collapsible_subcontainers_flex(dash_br):
"""Test that after closing subcontainer the parent container is still open."""
accordion_select(dash_br, accordion_name=cnst.LAYOUT_ACCORDION)
page_select(dash_br, page_name=cnst.COLLAPSIBLE_CONTAINERS_FLEX)
# close subcontainer
dash_br.multiple_click("#flex_subcontainer_icon", 1)
# move mouse to different location of the screen to prevent flakiness because of tooltip.
dash_br.click_at_coord_fractions(theme_toggle_path(), 0, 1)
dash_br.wait_for_no_elements('span[aria-describedby*="tooltip"]')
|
Test that after closing subcontainer the parent container is still open.
|
test_collapsible_subcontainers_flex
|
python
|
mckinsey/vizro
|
vizro-core/tests/e2e/vizro/test_screenshots/test_screenshots.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/e2e/vizro/test_screenshots/test_screenshots.py
|
Apache-2.0
|
def _strip_keys(object, keys):
"""Strips from a JSON `object` all entries where the key is in keys, regardless of how deeply it's nested."""
if isinstance(object, dict):
object = {key: _strip_keys(value, keys) for key, value in object.items() if key not in keys}
elif isinstance(object, list):
object = [_strip_keys(item, keys) for item in object]
return object
|
Strips from a JSON `object` all entries where the key is in keys, regardless of how deeply it's nested.
|
_strip_keys
|
python
|
mckinsey/vizro
|
vizro-core/tests/tests_utils/asserts.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/tests_utils/asserts.py
|
Apache-2.0
|
def assert_component_equal(left, right, *, keys_to_strip=None):
"""Checks that the `left` and `right` Dash components are equal, ignoring `keys_to_strip`.
Args:
left: Dash component to compare.
right: Dash component to compare.
keys_to_strip: Keys to strip from the component dictionary before comparison.
If keys_to_strip is set to STRIP_ALL then only the type and namespace of component will
be compared, similar to doing isinstance.
Examples:
>>> from dash import html
>>> assert_component_equal(html.Div(), html.Div())
>>> assert_component_equal(html.Div(id="a"), html.Div(), keys_to_strip={"id"})
>>> assert_component_equal(html.Div([html.P(), html.P()], id="a"), html.Div(id="a"), keys_to_strip={"children"})
>>> assert_component_equal(html.Div(html.P(), className="blah", id="a"), html.Div(), keys_to_strip=STRIP_ALL)
"""
keys_to_strip = keys_to_strip or {}
if keys_to_strip is STRIP_ALL:
# Remove all properties from the component dictionary, leaving just "type" and "namespace" behind.
keys_to_strip = {"props"}
left = _strip_keys(_component_to_dict(left), keys_to_strip)
right = _strip_keys(_component_to_dict(right), keys_to_strip)
assert left == right
|
Checks that the `left` and `right` Dash components are equal, ignoring `keys_to_strip`.
Args:
left: Dash component to compare.
right: Dash component to compare.
keys_to_strip: Keys to strip from the component dictionary before comparison.
If keys_to_strip is set to STRIP_ALL then only the type and namespace of component will
be compared, similar to doing isinstance.
Examples:
>>> from dash import html
>>> assert_component_equal(html.Div(), html.Div())
>>> assert_component_equal(html.Div(id="a"), html.Div(), keys_to_strip={"id"})
>>> assert_component_equal(html.Div([html.P(), html.P()], id="a"), html.Div(id="a"), keys_to_strip={"children"})
>>> assert_component_equal(html.Div(html.P(), className="blah", id="a"), html.Div(), keys_to_strip=STRIP_ALL)
|
assert_component_equal
|
python
|
mckinsey/vizro
|
vizro-core/tests/tests_utils/asserts.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/tests_utils/asserts.py
|
Apache-2.0
|
def make_screenshot_and_paths(driver, request_node_name):
"""Creates image paths and makes screenshot during the test run."""
result_image_path = f"{request_node_name}_branch.png"
expected_image_path = (
f"tests/e2e/screenshots/{os.getenv('BROWSER', 'chrome')}/{request_node_name.replace('test', 'main')}.png"
)
driver.save_screenshot(result_image_path)
return result_image_path, expected_image_path
|
Creates image paths and makes screenshot during the test run.
|
make_screenshot_and_paths
|
python
|
mckinsey/vizro
|
vizro-core/tests/tests_utils/e2e/asserts.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/tests_utils/e2e/asserts.py
|
Apache-2.0
|
def assert_image_equal(result_image_path, expected_image_path):
"""Comparison logic and diff files creation."""
expected_image_name = Path(expected_image_path).name
try:
assert_pixelmatch(result_image_path, expected_image_path)
Path(result_image_path).unlink()
except subprocess.CalledProcessError as err:
shutil.copy(result_image_path, expected_image_name)
shutil.copy(expected_image_path, f"{expected_image_name.replace('.', '_old.')}")
Path(result_image_path).unlink()
raise Exception(err.stdout)
|
Comparison logic and diff files creation.
|
assert_image_equal
|
python
|
mckinsey/vizro
|
vizro-core/tests/tests_utils/e2e/asserts.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/tests_utils/e2e/asserts.py
|
Apache-2.0
|
def browser_console_warnings_checker(log_level, log_levels):
"""Whitelist for browser console errors and its assert."""
assert_that(
log_level["message"],
any_of(
contains_string(cnst.INVALID_PROP_ERROR),
contains_string(cnst.REACT_NOT_RECOGNIZE_ERROR),
contains_string(cnst.SCROLL_ZOOM_ERROR),
contains_string(cnst.REACT_RENDERING_ERROR),
contains_string(cnst.UNMOUNT_COMPONENTS_ERROR),
contains_string(cnst.WILLMOUNT_RENAMED_WARNING),
contains_string(cnst.WILLRECEIVEPROPS_RENAMED_WARNING),
contains_string(cnst.READPIXELS_WARNING),
contains_string(cnst.WEBGL_WARNING),
),
reason=f"Error outoput: {log_levels}",
)
|
Whitelist for browser console errors and its assert.
|
browser_console_warnings_checker
|
python
|
mckinsey/vizro
|
vizro-core/tests/tests_utils/e2e/vizro/checkers.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/tests_utils/e2e/vizro/checkers.py
|
Apache-2.0
|
def check_graph_is_loading_selenium(driver, graph_id, timeout=cnst.SELENIUM_WAITERS_TIMEOUT):
"""Waiting for graph to start reloading for pure selenium."""
WebDriverWait(driver, timeout).until(
expected_conditions.presence_of_element_located(
(By.CSS_SELECTOR, f"div[id='{graph_id}'][data-dash-is-loading='true']")
)
)
graph_load_waiter_selenium(driver, graph_id, timeout)
|
Waiting for graph to start reloading for pure selenium.
|
check_graph_is_loading_selenium
|
python
|
mckinsey/vizro
|
vizro-core/tests/tests_utils/e2e/vizro/checkers.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/tests_utils/e2e/vizro/checkers.py
|
Apache-2.0
|
def check_selected_categorical_component(driver, component_id, options_value_status):
"""Checks what selected and what is not for checklist and radio items.
Args:
driver: dash_br fixture
component_id: id of checklist or radio items
options_value_status: list of dicts with the next syntax
[{
"value": int, number of the value inside dom structure,
"selected": bool, checks if value selected or not,
"value_name": str, component value name,
}]
"""
values = driver.find_elements(f"div[id='{component_id}'] div")
assert_that(len(values), equal_to(len(options_value_status)))
for option in options_value_status:
driver.wait_for_text_to_equal(
categorical_components_value_name_path(elem_id=component_id, value=option["value"]), option["value_name"]
)
status = driver.find_element(categorical_components_value_path(elem_id=component_id, value=option["value"]))
assert_that(status.is_selected(), equal_to(option["selected"]))
|
Checks what selected and what is not for checklist and radio items.
Args:
driver: dash_br fixture
component_id: id of checklist or radio items
options_value_status: list of dicts with the next syntax
[{
"value": int, number of the value inside dom structure,
"selected": bool, checks if value selected or not,
"value_name": str, component value name,
}]
|
check_selected_categorical_component
|
python
|
mckinsey/vizro
|
vizro-core/tests/tests_utils/e2e/vizro/checkers.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/tests_utils/e2e/vizro/checkers.py
|
Apache-2.0
|
def accordion_select(driver, accordion_name):
"""Selecting accordion and checking if it is active."""
accordion_name = accordion_name.upper()
click_element_by_xpath_selenium(driver, f"//button[text()='{accordion_name}']")
check_accordion_active(driver, accordion_name)
# to let accordion open
time.sleep(1)
|
Selecting accordion and checking if it is active.
|
accordion_select
|
python
|
mckinsey/vizro
|
vizro-core/tests/tests_utils/e2e/vizro/navigation.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/tests_utils/e2e/vizro/navigation.py
|
Apache-2.0
|
def page_select(driver, page_name, graph_check=True, page_path=None):
"""Selecting page and checking if it has proper title."""
page_path = page_path if page_path else f"/{page_name}"
driver.multiple_click(f"a[href='{page_path}']", 1)
driver.wait_for_contains_text(page_title_path(), page_name)
if graph_check:
driver.wait_for_element("div[class='dash-graph'] path[class='xtick ticks crisp']")
|
Selecting page and checking if it has proper title.
|
page_select
|
python
|
mckinsey/vizro
|
vizro-core/tests/tests_utils/e2e/vizro/navigation.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/tests_utils/e2e/vizro/navigation.py
|
Apache-2.0
|
def page_select_selenium(driver, page_path, page_name, timeout=cnst.SELENIUM_WAITERS_TIMEOUT, graph_check=True):
"""Selecting page and checking if it has proper title for pure selenium."""
WebDriverWait(driver, timeout).until(
expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, f"a[href='{page_path}']"))
).click()
WebDriverWait(driver, timeout).until(
expected_conditions.text_to_be_present_in_element((By.CSS_SELECTOR, page_title_path()), page_name)
)
if graph_check:
WebDriverWait(driver, timeout).until(
expected_conditions.presence_of_element_located(
(By.CSS_SELECTOR, "div[class='dash-graph'] path[class='xtick ticks crisp']")
)
)
|
Selecting page and checking if it has proper title for pure selenium.
|
page_select_selenium
|
python
|
mckinsey/vizro
|
vizro-core/tests/tests_utils/e2e/vizro/navigation.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/tests_utils/e2e/vizro/navigation.py
|
Apache-2.0
|
def select_dropdown_value(driver, value, dropdown_id, multi=True):
"""Steps to select value in dropdown."""
dropdown_path = f"div[id='{dropdown_id}']"
if multi:
driver.multiple_click(f"{dropdown_path} .Select-clear", 1)
driver.multiple_click(f"{dropdown_path} .Select-arrow", 1)
driver.multiple_click(f"{dropdown_path} .ReactVirtualized__Grid__innerScrollContainer div:nth-of-type({value})", 1)
|
Steps to select value in dropdown.
|
select_dropdown_value
|
python
|
mckinsey/vizro
|
vizro-core/tests/tests_utils/e2e/vizro/navigation.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/tests_utils/e2e/vizro/navigation.py
|
Apache-2.0
|
def graph_load_waiter_selenium(driver, graph_id, timeout=cnst.SELENIUM_WAITERS_TIMEOUT):
"""Waiting for graph's x-axis to appear for pure selenium."""
WebDriverWait(driver, timeout).until(
expected_conditions.presence_of_element_located(
(By.CSS_SELECTOR, f"div[id='{graph_id}'] path[class='xtick ticks crisp']")
)
)
|
Waiting for graph's x-axis to appear for pure selenium.
|
graph_load_waiter_selenium
|
python
|
mckinsey/vizro
|
vizro-core/tests/tests_utils/e2e/vizro/waiters.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/tests_utils/e2e/vizro/waiters.py
|
Apache-2.0
|
def managers_one_page_two_graphs_with_dynamic_data(box_chart_dynamic_data_frame, scatter_chart_dynamic_data_frame):
"""Instantiates a simple model_manager and data_manager with a page, two graph models and the button component."""
vm.Page(
id="test_page",
title="My first dashboard",
components=[
vm.Graph(id="box_chart", figure=box_chart_dynamic_data_frame),
vm.Graph(id="scatter_chart", figure=scatter_chart_dynamic_data_frame),
vm.Button(id="button"),
],
)
Vizro._pre_build()
|
Instantiates a simple model_manager and data_manager with a page, two graph models and the button component.
|
managers_one_page_two_graphs_with_dynamic_data
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/conftest.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/conftest.py
|
Apache-2.0
|
def page_actions_builtin_controls(standard_px_chart):
"""Instantiates managers with one page that contains filter, parameter, and filter_interaction actions."""
vm.Page(
title="title",
components=[
vm.Graph(
id="graph_1",
figure=standard_px_chart,
actions=[filter_interaction(id="graph_filter_interaction", targets=["graph_2"])],
),
vm.Graph(id="graph_2", figure=standard_px_chart),
],
controls=[
vm.Filter(id="filter", column="continent", selector=vm.Dropdown(id="filter_selector")),
vm.Parameter(
id="parameter",
targets=["graph_1.x"],
selector=vm.Checklist(
id="parameter_selector",
options=["lifeExp", "gdpPercap", "pop"],
),
),
],
)
Vizro._pre_build()
return {
"_controls": {
"filters": [
State("filter_selector", "value"),
],
"parameters": [
State("parameter_selector", "value"),
],
"filter_interaction": [
{"clickData": State("graph_1", "clickData"), "modelID": State("graph_1", "id")},
],
}
}
|
Instantiates managers with one page that contains filter, parameter, and filter_interaction actions.
|
page_actions_builtin_controls
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/conftest.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/conftest.py
|
Apache-2.0
|
def manager_for_testing_actions_output_input_prop(ag_grid_with_id):
"""Instantiates the model_manager using a Dropdown (has default input and output properties)."""
# We have to use one of the selectors as the known-model as currently only the selectors have both
# input and output properties defined. Therefore, the configuration currently requires components and controls.
vm.Page(
id="test_page",
title="My first dashboard",
components=[
vm.Button(id="known_model_with_no_default_props"),
vm.AgGrid(id="known_ag_grid_id", figure=ag_grid_with_id),
],
controls=[vm.Filter(column="continent", selector=vm.Dropdown(id="known_dropdown_filter_id"))],
)
Vizro._pre_build()
|
Instantiates the model_manager using a Dropdown (has default input and output properties).
|
manager_for_testing_actions_output_input_prop
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/conftest.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/conftest.py
|
Apache-2.0
|
def managers_one_page_two_graphs_one_button(box_chart, scatter_chart):
"""Instantiates a simple model_manager and data_manager with a page, two graph models and the button component."""
vm.Page(
id="test_page",
title="My first dashboard",
components=[
vm.Graph(id="box_chart", figure=box_chart),
vm.Graph(id="scatter_chart", figure=scatter_chart),
vm.Button(id="button"),
],
)
Vizro._pre_build()
|
Instantiates a simple model_manager and data_manager with a page, two graph models and the button component.
|
managers_one_page_two_graphs_one_button
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/conftest.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/conftest.py
|
Apache-2.0
|
def managers_one_page_two_graphs_one_table_one_aggrid_one_button(
box_chart, scatter_chart, dash_data_table_with_id, ag_grid_with_id
):
"""Instantiates a simple model_manager and data_manager with: page, graphs, table, aggrid and button component."""
vm.Page(
id="test_page",
title="My first dashboard",
components=[
vm.Graph(id="box_chart", figure=box_chart),
vm.Graph(id="scatter_chart", figure=scatter_chart),
vm.Table(id="vizro_table", figure=dash_data_table_with_id),
vm.AgGrid(id="ag_grid", figure=ag_grid_with_id),
vm.Button(id="button"),
],
)
Vizro._pre_build()
|
Instantiates a simple model_manager and data_manager with: page, graphs, table, aggrid and button component.
|
managers_one_page_two_graphs_one_table_one_aggrid_one_button
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/conftest.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/conftest.py
|
Apache-2.0
|
def managers_one_page_one_graph_with_dict_param_input(scatter_matrix_chart):
"""Instantiates a model_manager and data_manager with a page and a graph that requires a list input."""
vm.Page(
id="test_page",
title="My first dashboard",
components=[
vm.Graph(id="scatter_matrix_chart", figure=scatter_matrix_chart),
],
)
Vizro._pre_build()
|
Instantiates a model_manager and data_manager with a page and a graph that requires a list input.
|
managers_one_page_one_graph_with_dict_param_input
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/conftest.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/conftest.py
|
Apache-2.0
|
def ctx_export_data(request):
"""Mock dash.ctx that represents filters and filter interactions applied."""
targets, pop_filter, continent_filter_interaction, country_table_filter_interaction = request.param
args_grouping_filter_interaction = []
if continent_filter_interaction:
args_grouping_filter_interaction.append(
{
"clickData": CallbackTriggerDict(
id="box_chart",
property="clickData",
value={"points": [{"customdata": [continent_filter_interaction]}]},
str_id="box_chart",
triggered=False,
),
"modelID": CallbackTriggerDict(
id="box_chart", property="id", value="box_chart", str_id="box_chart", triggered=False
),
},
)
if country_table_filter_interaction:
args_grouping_filter_interaction.append(
{
"active_cell": CallbackTriggerDict(
id="underlying_table_id",
property="active_cell",
value={"row": 0, "column": 0, "column_id": "country"},
str_id="underlying_table_id",
triggered=False,
),
"derived_viewport_data": CallbackTriggerDict(
id="underlying_table_id",
property="derived_viewport_data",
value=[
{"country": "Algeria", "continent": "Africa", "year": 2007},
{"country": "Egypt", "continent": "Africa", "year": 2007},
],
str_id="underlying_table_id",
triggered=False,
),
"modelID": CallbackTriggerDict(
id="vizro_table", property="id", value="vizro_table", str_id="vizro_table", triggered=False
),
}
)
mock_ctx = {
"args_grouping": {
"external": {
"_controls": {
"filters": (
[
CallbackTriggerDict(
id="pop_filter",
property="value",
value=pop_filter,
str_id="pop_filter",
triggered=False,
)
]
if pop_filter
else []
),
"parameters": [],
"filter_interaction": args_grouping_filter_interaction,
}
}
},
"outputs_list": [
{"id": {"action_id": "test_action", "target_id": target, "type": "download_dataframe"}, "property": "data"}
for target in targets
],
}
context_value.set(AttributeDict(**mock_ctx))
return context_value
|
Mock dash.ctx that represents filters and filter interactions applied.
|
ctx_export_data
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/test_export_data.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/test_export_data.py
|
Apache-2.0
|
def ctx_export_data_filter_and_parameter(request):
"""Mock dash.ctx that represents filters and parameter applied."""
targets, pop_filter, first_n_parameter = request.param
mock_ctx = {
"args_grouping": {
"external": {
"_controls": {
"filters": (
[
CallbackTriggerDict(
id="pop_filter",
property="value",
value=pop_filter,
str_id="pop_filter",
triggered=False,
)
]
if pop_filter
else []
),
"parameters": (
[
CallbackTriggerDict(
id="first_n_parameter",
property="value",
value=first_n_parameter,
str_id="first_n_parameter",
triggered=False,
)
]
if first_n_parameter
else []
),
"filter_interaction": [],
}
}
},
"outputs_list": [
{"id": {"action_id": "test_action", "target_id": target, "type": "download_dataframe"}, "property": "data"}
for target in targets
],
}
context_value.set(AttributeDict(**mock_ctx))
return context_value
|
Mock dash.ctx that represents filters and parameter applied.
|
ctx_export_data_filter_and_parameter
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/test_export_data.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/test_export_data.py
|
Apache-2.0
|
def config_for_testing_all_components_with_actions(request, standard_px_chart, ag_grid_with_id):
"""Instantiates managers with one page that contains four controls, two graphs and filter interaction."""
# If the fixture is parametrised set the targets. Otherwise, set export_data without targets.
export_data_action_function = (
export_data(id="export_data_action", targets=request.param)
if hasattr(request, "param") and request.param is not None
else export_data(id="export_data_action")
)
vm.Page(
title="title",
components=[
vm.Graph(
id="scatter_chart",
figure=standard_px_chart,
actions=[filter_interaction(id="graph_filter_interaction", targets=["ag_grid"])],
),
vm.AgGrid(id="ag_grid", figure=ag_grid_with_id),
vm.Button(
id="export_data_button",
actions=[
vm.Action(function=export_data_action_function),
],
),
],
)
Vizro._pre_build()
|
Instantiates managers with one page that contains four controls, two graphs and filter interaction.
|
config_for_testing_all_components_with_actions
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/test_export_data.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/test_export_data.py
|
Apache-2.0
|
def ctx_filter_continent(request):
"""Mock dash.ctx that represents continent Filter value selection."""
continent = request.param
mock_ctx = {
"args_grouping": {
"external": {
"_controls": {
"filter_interaction": [],
"filters": [
CallbackTriggerDict(
id="continent_filter",
property="value",
value=continent,
str_id="continent_filter",
triggered=False,
)
],
"parameters": [],
}
}
}
}
context_value.set(AttributeDict(**mock_ctx))
return context_value
|
Mock dash.ctx that represents continent Filter value selection.
|
ctx_filter_continent
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/test_filter_action.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/test_filter_action.py
|
Apache-2.0
|
def ctx_filter_continent_and_pop(request):
"""Mock dash.ctx that represents continent and pop Filter value selection."""
continent, pop = request.param
mock_ctx = {
"args_grouping": {
"external": {
"_controls": {
"filter_interaction": [],
"filters": [
CallbackTriggerDict(
id="continent_filter",
property="value",
value=continent,
str_id="continent_filter",
triggered=False,
),
CallbackTriggerDict(
id="pop_filter",
property="value",
value=pop,
str_id="pop_filter",
triggered=False,
),
],
"parameters": [],
}
}
}
}
context_value.set(AttributeDict(**mock_ctx))
return context_value
|
Mock dash.ctx that represents continent and pop Filter value selection.
|
ctx_filter_continent_and_pop
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/test_filter_action.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/test_filter_action.py
|
Apache-2.0
|
def ctx_filter_interaction(request):
"""Mock dash.ctx that represents a click on a continent data-point and table selected cell."""
continent_filter_interaction, country_table_filter_interaction, country_aggrid_filter_interaction = request.param
args_grouping_filter_interaction = []
if continent_filter_interaction:
args_grouping_filter_interaction.append(
{
"clickData": CallbackTriggerDict(
id="box_chart",
property="clickData",
value={"points": [{"customdata": [continent_filter_interaction]}]},
str_id="box_chart",
triggered=False,
),
"modelID": CallbackTriggerDict(
id="box_chart", property="id", value="box_chart", str_id="box_chart", triggered=False
),
}
)
if country_table_filter_interaction:
args_grouping_filter_interaction.append(
{
"active_cell": CallbackTriggerDict(
id="underlying_table_id",
property="active_cell",
value={"row": 0, "column": 0, "column_id": "country"},
str_id="underlying_table_id",
triggered=False,
),
"derived_viewport_data": CallbackTriggerDict(
id="underlying_table_id",
property="derived_viewport_data",
value=[
{"country": country_table_filter_interaction, "continent": "Africa", "year": 2007},
{"country": "Egypt", "continent": "Africa", "year": 2007},
],
str_id="underlying_table_id",
triggered=False,
),
"modelID": CallbackTriggerDict(
id="vizro_table", property="id", value="vizro_table", str_id="vizro_table", triggered=False
),
}
)
if country_aggrid_filter_interaction:
args_grouping_filter_interaction.append(
{
"cellClicked": CallbackTriggerDict(
id="underlying_ag_grid_id",
property="cellClicked",
value={
"value": country_aggrid_filter_interaction,
"colId": "country",
"rowIndex": 0,
"rowId": "0",
"timestamp": 1708697920849,
},
str_id="underlying_ag_grid_id",
triggered=False,
),
"modelID": CallbackTriggerDict(
id="ag_grid", property="id", value="ag_grid", str_id="ag_grid", triggered=False
),
}
)
mock_ctx = {
"args_grouping": {
"external": {
"_controls": {
"filters": [],
"filter_interaction": args_grouping_filter_interaction,
"parameters": [],
}
}
}
}
context_value.set(AttributeDict(**mock_ctx))
return context_value
|
Mock dash.ctx that represents a click on a continent data-point and table selected cell.
|
ctx_filter_interaction
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/test_filter_interaction.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/test_filter_interaction.py
|
Apache-2.0
|
def ctx_export_data(request):
"""Mock dash.ctx that represents filters and filter interactions applied."""
targets, pop_filter, continent_filter_interaction, country_table_filter_interaction = request.param
args_grouping_filter_interaction = []
if continent_filter_interaction:
args_grouping_filter_interaction.append(
{
"clickData": CallbackTriggerDict(
id="box_chart",
property="clickData",
value={"points": [{"customdata": [continent_filter_interaction]}]},
str_id="box_chart",
triggered=False,
),
"modelID": CallbackTriggerDict(
id="box_chart", property="id", value="box_chart", str_id="box_chart", triggered=False
),
},
)
if country_table_filter_interaction:
args_grouping_filter_interaction.append(
{
"active_cell": CallbackTriggerDict(
id="underlying_table_id",
property="active_cell",
value={"row": 0, "column": 0, "column_id": "country"},
str_id="underlying_table_id",
triggered=False,
),
"derived_viewport_data": CallbackTriggerDict(
id="underlying_table_id",
property="derived_viewport_data",
value=[
{"country": "Algeria", "continent": "Africa", "year": 2007},
{"country": "Egypt", "continent": "Africa", "year": 2007},
],
str_id="underlying_table_id",
triggered=False,
),
"modelID": CallbackTriggerDict(
id="vizro_table", property="id", value="vizro_table", str_id="vizro_table", triggered=False
),
}
)
mock_ctx = {
"args_grouping": {
"external": {
"_controls": {
"filters": (
[
CallbackTriggerDict(
id="pop_filter",
property="value",
value=pop_filter,
str_id="pop_filter",
triggered=False,
)
]
if pop_filter
else []
),
"parameters": [],
"filter_interaction": args_grouping_filter_interaction,
}
}
},
"outputs_list": [
{"id": {"action_id": "test_action", "target_id": target, "type": "download_dataframe"}, "property": "data"}
for target in targets
],
}
context_value.set(AttributeDict(**mock_ctx))
return context_value
|
Mock dash.ctx that represents filters and filter interactions applied.
|
ctx_export_data
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/test_legacy_export_data.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/test_legacy_export_data.py
|
Apache-2.0
|
def ctx_export_data_filter_and_parameter(request):
"""Mock dash.ctx that represents filters and parameter applied."""
targets, pop_filter, first_n_parameter = request.param
mock_ctx = {
"args_grouping": {
"external": {
"_controls": {
"filters": (
[
CallbackTriggerDict(
id="pop_filter",
property="value",
value=pop_filter,
str_id="pop_filter",
triggered=False,
)
]
if pop_filter
else []
),
"parameters": (
[
CallbackTriggerDict(
id="first_n_parameter",
property="value",
value=first_n_parameter,
str_id="first_n_parameter",
triggered=False,
)
]
if first_n_parameter
else []
),
"filter_interaction": [],
}
}
},
"outputs_list": [
{"id": {"action_id": "test_action", "target_id": target, "type": "download_dataframe"}, "property": "data"}
for target in targets
],
}
context_value.set(AttributeDict(**mock_ctx))
return context_value
|
Mock dash.ctx that represents filters and parameter applied.
|
ctx_export_data_filter_and_parameter
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/test_legacy_export_data.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/test_legacy_export_data.py
|
Apache-2.0
|
def ctx_filter_interaction(request):
"""Mock dash.ctx that represents a click on a continent data-point and table selected cell."""
continent_filter_interaction, country_table_filter_interaction, country_aggrid_filter_interaction = request.param
args_grouping_filter_interaction = []
if continent_filter_interaction:
args_grouping_filter_interaction.append(
{
"clickData": CallbackTriggerDict(
id="box_chart",
property="clickData",
value={"points": [{"customdata": [continent_filter_interaction]}]},
str_id="box_chart",
triggered=False,
),
"modelID": CallbackTriggerDict(
id="box_chart", property="id", value="box_chart", str_id="box_chart", triggered=False
),
}
)
if country_table_filter_interaction:
args_grouping_filter_interaction.append(
{
"active_cell": CallbackTriggerDict(
id="underlying_table_id",
property="active_cell",
value={"row": 0, "column": 0, "column_id": "country"},
str_id="underlying_table_id",
triggered=False,
),
"derived_viewport_data": CallbackTriggerDict(
id="underlying_table_id",
property="derived_viewport_data",
value=[
{"country": country_table_filter_interaction, "continent": "Africa", "year": 2007},
{"country": "Egypt", "continent": "Africa", "year": 2007},
],
str_id="underlying_table_id",
triggered=False,
),
"modelID": CallbackTriggerDict(
id="vizro_table", property="id", value="vizro_table", str_id="vizro_table", triggered=False
),
}
)
if country_aggrid_filter_interaction:
args_grouping_filter_interaction.append(
{
"cellClicked": CallbackTriggerDict(
id="underlying_ag_grid_id",
property="cellClicked",
value={
"value": country_aggrid_filter_interaction,
"colId": "country",
"rowIndex": 0,
"rowId": "0",
"timestamp": 1708697920849,
},
str_id="underlying_ag_grid_id",
triggered=False,
),
"modelID": CallbackTriggerDict(
id="ag_grid", property="id", value="ag_grid", str_id="ag_grid", triggered=False
),
}
)
mock_ctx = {
"args_grouping": {
"external": {
"_controls": {
"filters": [],
"filter_interaction": args_grouping_filter_interaction,
"parameters": [],
}
}
}
}
context_value.set(AttributeDict(**mock_ctx))
return context_value
|
Mock dash.ctx that represents a click on a continent data-point and table selected cell.
|
ctx_filter_interaction
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/test_legacy_filter_interaction.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/test_legacy_filter_interaction.py
|
Apache-2.0
|
def ctx_on_page_load(request):
"""Mock dash.ctx that represents on page load."""
continent_filter, pop, y, x = request.param
mock_ctx = {
"args_grouping": {
"external": {
"_controls": {
"filter_interaction": [],
"filters": [
CallbackTriggerDict(
id="continent_filter",
property="value",
value=continent_filter,
str_id="continent_filter",
triggered=False,
),
CallbackTriggerDict(
id="pop_filter",
property="value",
value=pop,
str_id="pop_filter",
triggered=False,
),
],
"parameters": [
CallbackTriggerDict(
id="y_parameter",
property="value",
value=y,
str_id="y_parameter",
triggered=False,
),
CallbackTriggerDict(
id="x_parameter",
property="value",
value=x,
str_id="x_parameter",
triggered=False,
),
],
}
}
}
}
context_value.set(AttributeDict(**mock_ctx))
return context_value
|
Mock dash.ctx that represents on page load.
|
ctx_on_page_load
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/test_on_page_load.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/test_on_page_load.py
|
Apache-2.0
|
def ctx_parameter_y(request):
"""Mock dash.ctx that represents y-axis Parameter value selection."""
y = request.param
mock_ctx = {
"args_grouping": {
"external": {
"_controls": {
"filter_interaction": [],
"filters": [],
"parameters": [
CallbackTriggerDict(
id="y_parameter",
property="value",
value=y,
str_id="y_parameter",
triggered=False,
)
],
}
}
}
}
context_value.set(AttributeDict(**mock_ctx))
return context_value
|
Mock dash.ctx that represents y-axis Parameter value selection.
|
ctx_parameter_y
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/test_parameter_action.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/test_parameter_action.py
|
Apache-2.0
|
def ctx_parameter_dimensions(request):
"""Mock dash.ctx that represents `dimensions` Parameter value selection."""
y = request.param
mock_ctx = {
"args_grouping": {
"external": {
"_controls": {
"filter_interaction": [],
"filters": [],
"parameters": [
CallbackTriggerDict(
id="dimensions_parameter",
property="value",
value=y,
str_id="dimensions_parameter",
triggered=False,
)
],
}
}
}
}
context_value.set(AttributeDict(**mock_ctx))
return context_value
|
Mock dash.ctx that represents `dimensions` Parameter value selection.
|
ctx_parameter_dimensions
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/test_parameter_action.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/test_parameter_action.py
|
Apache-2.0
|
def ctx_parameter_hover_data(request):
"""Mock dash.ctx that represents hover_data Parameter value selection."""
hover_data = request.param
mock_ctx = {
"args_grouping": {
"external": {
"_controls": {
"filter_interaction": [],
"filters": [],
"parameters": [
CallbackTriggerDict(
id="hover_data_parameter",
property="value",
value=hover_data,
str_id="hover_data_parameter",
triggered=False,
)
],
}
}
}
}
context_value.set(AttributeDict(**mock_ctx))
return context_value
|
Mock dash.ctx that represents hover_data Parameter value selection.
|
ctx_parameter_hover_data
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/test_parameter_action.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/test_parameter_action.py
|
Apache-2.0
|
def ctx_parameter_y_and_x(request):
"""Mock dash.ctx that represents y-axis Parameter value selection."""
y, x = request.param
mock_ctx = {
"args_grouping": {
"external": {
"_controls": {
"filter_interaction": [],
"filters": [],
"parameters": [
CallbackTriggerDict(
id="y_parameter",
property="value",
value=y,
str_id="y_parameter",
triggered=False,
),
CallbackTriggerDict(
id="x_parameter",
property="value",
value=x,
str_id="x_parameter",
triggered=False,
),
],
}
}
}
}
context_value.set(AttributeDict(**mock_ctx))
return context_value
|
Mock dash.ctx that represents y-axis Parameter value selection.
|
ctx_parameter_y_and_x
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/test_parameter_action.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/test_parameter_action.py
|
Apache-2.0
|
def ctx_parameter_data_frame_argument(request):
"""Mock dash.ctx that represents parameter applied."""
targets, first_n_last_n_args = request.param
dynamic_filters = []
parameters = [
CallbackTriggerDict(
id="first_n_parameter",
property="value",
value=first_n_last_n_args["first_n"],
str_id="first_n_parameter",
triggered=False,
)
]
if last_n := first_n_last_n_args.get("last_n"):
parameters.append(
CallbackTriggerDict(
id="last_n_parameter",
property="value",
value=last_n,
str_id="last_n_parameter",
triggered=False,
)
)
if dynamic_filter_value := first_n_last_n_args.get("dynamic_filter_value"):
dynamic_filters.append(
CallbackTriggerDict(
id="dynamic_filter_id_selector",
property="value",
value=dynamic_filter_value,
str_id="dynamic_filter_id_selector",
triggered=False,
)
)
mock_ctx = {
"args_grouping": {
"external": {"_controls": {"filters": dynamic_filters, "filter_interaction": [], "parameters": parameters}}
},
"outputs_list": [
{"id": {"action_id": "test_action", "target_id": target, "type": "download_dataframe"}, "property": "data"}
for target in targets
],
}
context_value.set(AttributeDict(**mock_ctx))
return context_value
|
Mock dash.ctx that represents parameter applied.
|
ctx_parameter_data_frame_argument
|
python
|
mckinsey/vizro
|
vizro-core/tests/unit/vizro/actions/test_parameter_action.py
|
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/test_parameter_action.py
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.