From 9601dea58049713bcdfe48250ea8e9c3bc888287 Mon Sep 17 00:00:00 2001 From: Rambaud Pierrick <12rambau@users.noreply.github.com> Date: Fri, 10 May 2024 07:29:44 +0000 Subject: [PATCH] refactor: extend the length of the black lines to 100 chars --- noxfile.py | 6 +-- pyproject.toml | 3 ++ sepal_ui/aoi/aoi_model.py | 32 ++++----------- sepal_ui/aoi/aoi_view.py | 24 +++-------- sepal_ui/bin/activate_venv.py | 14 ++----- sepal_ui/bin/module_deploy.py | 16 ++------ sepal_ui/bin/module_factory.py | 8 +--- sepal_ui/frontend/resize_trigger.py | 3 +- sepal_ui/mapping/aoi_control.py | 8 +--- sepal_ui/mapping/fullscreen_control.py | 4 +- sepal_ui/mapping/inspector_control.py | 19 +++------ sepal_ui/mapping/layers_control.py | 9 +---- sepal_ui/mapping/sepal_map.py | 36 +++++------------ sepal_ui/planetapi/planet_model.py | 16 ++------ sepal_ui/planetapi/planet_view.py | 8 +--- sepal_ui/planetapi/planet_widgets.py | 9 +---- sepal_ui/scripts/decorator.py | 26 +++--------- sepal_ui/scripts/utils.py | 20 +++------- sepal_ui/sepalwidgets/alert.py | 8 +--- sepal_ui/sepalwidgets/app.py | 36 +++++------------ sepal_ui/sepalwidgets/btn.py | 4 +- sepal_ui/sepalwidgets/inputs.py | 40 +++++-------------- sepal_ui/sepalwidgets/sepalwidget.py | 14 ++----- sepal_ui/sepalwidgets/tile.py | 4 +- sepal_ui/sepalwidgets/widget.py | 8 +--- .../map_app/component/tile/map_tile.py | 4 +- tests/conftest.py | 4 +- tests/test_aoi/test_AoiModel.py | 8 +--- tests/test_aoi/test_AoiView.py | 12 ++---- tests/test_mapping/test_AoiControl.py | 4 +- tests/test_mapping/test_InspectorControl.py | 4 +- tests/test_mapping/test_LayersControl.py | 8 +--- tests/test_mapping/test_MenuControl.py | 4 +- tests/test_planetapi/test_PlanetView.py | 12 ++---- tests/test_planetapi/test_PlanetWidgets.py | 4 +- tests/test_scripts/test_decorator.py | 4 +- tests/test_scripts/test_gee.py | 4 +- tests/test_scripts/test_utils.py | 8 +--- tests/test_sepalwidgets/test_AssetSelect.py | 10 +---- tests/test_sepalwidgets/test_Banner.py | 4 +- tests/test_sepalwidgets/test_DatePicker.py | 4 +- tests/test_sepalwidgets/test_FileInput.py | 4 +- 42 files changed, 120 insertions(+), 357 deletions(-) diff --git a/noxfile.py b/noxfile.py index 2bf03e21..10d08f11 100644 --- a/noxfile.py +++ b/noxfile.py @@ -13,7 +13,7 @@ def lint(session): """Apply the pre-commits.""" session.install("pre-commit") - session.run("pre-commit", "run", "--a", *session.posargs) + session.run("pre-commit", "run", "--all-files", *session.posargs) @nox.session(reuse_venv=True) @@ -56,9 +56,7 @@ def docs(session): # build the api doc files templates = "docs/source/_templates/apidoc" modules = "docs/source/modules" - session.run( - "sphinx-apidoc", f"--templatedir={templates}", "-o", modules, "sepal_ui" - ) + session.run("sphinx-apidoc", f"--templatedir={templates}", "-o", modules, "sepal_ui") # build the documentation source = "docs/source" diff --git a/pyproject.toml b/pyproject.toml index 7db8bb9c..8584a006 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -181,3 +181,6 @@ using = "PEP631:test;dev;doc" [tool.codespell] skip = 'CHANGELOG.md,sepal_ui/message/**/*.json,sepal_ui/data/gaul_iso.json' + +[tool.black] +line-length = 100 diff --git a/sepal_ui/aoi/aoi_model.py b/sepal_ui/aoi/aoi_model.py index 9f513810..aa1921f0 100644 --- a/sepal_ui/aoi/aoi_model.py +++ b/sepal_ui/aoi/aoi_model.py @@ -154,9 +154,7 @@ def __init__( self.gee = gee if gee: su.init_ee() - self.folder = ( - str(folder) or f"projects/{ee.data._cloud_api_user_project}/assets/" - ) + self.folder = str(folder) or f"projects/{ee.data._cloud_api_user_project}/assets/" # set default values self.set_default(vector, admin, asset) @@ -177,22 +175,16 @@ def set_default( # save the default values self.default_vector = vector self.default_asset = self.asset_name = str(asset) if asset else None - self.asset_json = ( - {"pathname": asset, "column": "ALL", "value": None} if asset else None - ) + self.asset_json = {"pathname": asset, "column": "ALL", "value": None} if asset else None self.default_admin = self.admin = admin # cast the vector to json self.vector_json = ( - {"pathname": str(vector), "column": "ALL", "value": None} - if vector - else None + {"pathname": str(vector), "column": "ALL", "value": None} if vector else None ) # cast the asset to json - self.asset_json = ( - {"pathname": asset, "column": "ALL", "value": None} if asset else None - ) + self.asset_json = {"pathname": asset, "column": "ALL", "value": None} if asset else None # set the default gdf if possible if self.vector_json is not None: @@ -285,9 +277,7 @@ def _from_points(self, point_json: dict) -> Self: self.gdf = gpd.GeoDataFrame( df, crs="EPSG:4326", - geometry=gpd.points_from_xy( - df[point_json["lng_column"]], df[point_json["lat_column"]] - ), + geometry=gpd.points_from_xy(df[point_json["lng_column"]], df[point_json["lat_column"]]), ) # set the name @@ -449,9 +439,7 @@ def get_columns(self) -> List[str]: if self.gee: aoi_ee = ee.Feature(self.feature_collection.first()) columns = aoi_ee.propertyNames().getInfo() - list_ = [ - col for col in columns if col not in ["system:index", "Shape_Area"] - ] + list_ = [col for col in columns if col not in ["system:index", "Shape_Area"]] else: list_ = list(set(["geometry"]) ^ set(self.gdf.columns.to_list())) @@ -478,9 +466,7 @@ def get_fields(self, column: str) -> List[str]: return sorted(list_) - def get_selected( - self, column: str, field: str - ) -> Union[ee.Feature, gpd.GeoDataFrame]: + def get_selected(self, column: str, field: str) -> Union[ee.Feature, gpd.GeoDataFrame]: """Select an ee object based on selected column and field. Args: @@ -494,9 +480,7 @@ def get_selected( raise Exception(ms.aoi_sel.exception.no_gdf) if self.gee: - selected_feature = self.feature_collection.filterMetadata( - column, "equals", field - ) + selected_feature = self.feature_collection.filterMetadata(column, "equals", field) else: selected_feature = self.gdf[self.gdf[column] == field] diff --git a/sepal_ui/aoi/aoi_view.py b/sepal_ui/aoi/aoi_view.py index 65cd4c0c..601411a3 100644 --- a/sepal_ui/aoi/aoi_view.py +++ b/sepal_ui/aoi/aoi_view.py @@ -50,13 +50,9 @@ def __init__( if methods == "ALL": self.methods = select_methods elif methods == "ADMIN": - self.methods = { - k: v for k, v in select_methods.items() if v["type"] == ADMIN - } + self.methods = {k: v for k, v in select_methods.items() if v["type"] == ADMIN} elif methods == "CUSTOM": - self.methods = { - k: v for k, v in select_methods.items() if v["type"] == CUSTOM - } + self.methods = {k: v for k, v in select_methods.items() if v["type"] == CUSTOM} elif type(methods) == list: if any(m[0] == "-" for m in methods) != all(m[0] == "-" for m in methods): raise Exception("You mixed adding and removing, punk") @@ -65,9 +61,7 @@ def __init__( to_remove = [method[1:] for method in methods] # Rewrite the methods instead of mutate the class methods - self.methods = { - k: v for k, v in select_methods.items() if k not in to_remove - } + self.methods = {k: v for k, v in select_methods.items() if k not in to_remove} else: self.methods = {k: select_methods[k] for k in methods} @@ -104,9 +98,7 @@ class AdminField(sw.Select): parent: Optional[sw.Select] = None "The parent adminfield object" - def __init__( - self, level: int, parent: Optional[sw.Select] = None, gee: bool = True - ) -> None: + def __init__(self, level: int, parent: Optional[sw.Select] = None, gee: bool = True) -> None: """An admin level selector. It is binded to ee (GAUL 2015) or not (GADM). Allows to select administrative codes taking into account the administrative parent code and displaying humanly readable administrative names. @@ -124,9 +116,7 @@ def __init__( self.parent = parent # init an empty widget - super().__init__( - v_model=None, items=[], clearable=True, label=ms.aoi_sel.adm[level] - ) + super().__init__(v_model=None, items=[], clearable=True, label=ms.aoi_sel.adm[level]) # add js behaviour self.parent is None or self.parent.observe(self._update, "v_model") @@ -333,9 +323,7 @@ def __init__( self.btn = sw.Btn(msg=ms.aoi_sel.btn) # create the widget - self.children = ( - [self.w_method] + [*self.components.values()] + [self.btn, self.alert] - ) + self.children = [self.w_method] + [*self.components.values()] + [self.btn, self.alert] super().__init__(**kwargs) diff --git a/sepal_ui/bin/activate_venv.py b/sepal_ui/bin/activate_venv.py index 778c907e..19bb302e 100644 --- a/sepal_ui/bin/activate_venv.py +++ b/sepal_ui/bin/activate_venv.py @@ -41,11 +41,7 @@ def main() -> None: test_venv_path = Path.home() / "module-venv" if test_venv_path.exists(): test_envs = pd.DataFrame( - list( - [f"test {el.name}", str(el)] - for el in test_venv_path.glob("[!.]*") - if el.is_dir() - ) + list([f"test {el.name}", str(el)] for el in test_venv_path.glob("[!.]*") if el.is_dir()) ) venvs = pd.concat([venvs, test_envs]) venvs = venvs.reset_index(drop=True) @@ -59,9 +55,7 @@ def main() -> None: while not valid: selection = int( - input( - f"{Fore.CYAN} Select the venv number you want to activate: \n{Fore.RESET}" - ) + input(f"{Fore.CYAN} Select the venv number you want to activate: \n{Fore.RESET}") ) if selection not in venvs.index.unique(): @@ -84,9 +78,7 @@ def main() -> None: # The following lines won't be executed because the previous subprocess kill the kernel # Confirm that we are in the new env - result = subprocess.run( - ["echo", "$VIRTUAL_ENV"], shell=True, stdout=subprocess.PIPE - ) + result = subprocess.run(["echo", "$VIRTUAL_ENV"], shell=True, stdout=subprocess.PIPE) print(f"The current env is: {result.stdout!r}") diff --git a/sepal_ui/bin/module_deploy.py b/sepal_ui/bin/module_deploy.py index 56e54412..e648cb97 100755 --- a/sepal_ui/bin/module_deploy.py +++ b/sepal_ui/bin/module_deploy.py @@ -46,9 +46,7 @@ def write_reqs(file: Union[str, Path]) -> None: # add the custom libs tmp_file = Path.cwd() / "req_tmp.txt" - subprocess.run( - ["pipreqs", "--savepath", str(tmp_file), str(Path.cwd())], cwd=Path.cwd() - ) + subprocess.run(["pipreqs", "--savepath", str(tmp_file), str(Path.cwd())], cwd=Path.cwd()) # add the libs in the final file with file.open("a") as dst: @@ -79,9 +77,7 @@ def clean_dulpicate(file: Union[str, Path]) -> None: for line in text[idx:]: if any(lib in line for lib in libs): lib = next(lb for lb in libs if lb in line) - print( - f"Removing {Style.BRIGHT}{lib}{Style.NORMAL} from reqs, duplicated from default." - ) + print(f"Removing {Style.BRIGHT}{lib}{Style.NORMAL} from reqs, duplicated from default.") continue final_text.append(line) @@ -113,9 +109,7 @@ def clean_troubleshouting(file: Union[str, Path]) -> None: # gdal and osgeo are part of pygdal # we use a specific version of earthengine in SEPAl, let's stick to it if "ee" in line: - print( - f"Removing {Style.BRIGHT}ee{Style.NORMAL} from reqs, included in sepal_ui." - ) + print(f"Removing {Style.BRIGHT}ee{Style.NORMAL} from reqs, included in sepal_ui.") continue elif any(lib in line for lib in ["osgeo"]): print(f"Removing {Style.BRIGHT}'osgeo'{Style.NORMAL} as part of gdal") @@ -144,9 +138,7 @@ def freeze_sepal_ui(file: Union[str, Path]) -> None: text = file.read_text().split("\n") # search for the sepal_ui line - idx, _ = next( - (i, il) for i, il in enumerate(text) if "#" not in il and "sepal_ui" in il - ) + idx, _ = next((i, il) for i, il in enumerate(text) if "#" not in il and "sepal_ui" in il) text[idx] = f"sepal_ui=={sepal_ui.__version__}" diff --git a/sepal_ui/bin/module_factory.py b/sepal_ui/bin/module_factory.py index d36764d4..93684500 100755 --- a/sepal_ui/bin/module_factory.py +++ b/sepal_ui/bin/module_factory.py @@ -22,9 +22,7 @@ parser = argparse.ArgumentParser(description=__doc__, usage="module_factory") -def set_default_readme( - folder: Path, module_name: str, description: str, url: str -) -> None: +def set_default_readme(folder: Path, module_name: str, description: str, url: str) -> None: """Write a default README.md file and overwrite the existing one. Args: @@ -194,9 +192,7 @@ def main() -> None: subprocess.run(["cp", "-r", str(template_dir), str(folder)], cwd=Path.cwd()) # replace the placeholders - url = github_url.replace(".git", "").replace( - "git@github.com:", "https://github.com/" - ) + url = github_url.replace(".git", "").replace("git@github.com:", "https://github.com/") set_default_readme(folder, module_name, description, url) set_default_about(folder, description) diff --git a/sepal_ui/frontend/resize_trigger.py b/sepal_ui/frontend/resize_trigger.py index 5d6a2be3..9d290efb 100644 --- a/sepal_ui/frontend/resize_trigger.py +++ b/sepal_ui/frontend/resize_trigger.py @@ -19,8 +19,7 @@ class ResizeTrigger(v.VuetifyTemplate): # load the js file js = (Path(__file__).parent / "js/jupyter_resize.js").read_text() template = Unicode( - "" - % js + "" % js ).tag(sync=True) "Unicode: the javascript script to manually trigger the resize event" diff --git a/sepal_ui/mapping/aoi_control.py b/sepal_ui/mapping/aoi_control.py index 22a000d7..c02f242c 100644 --- a/sepal_ui/mapping/aoi_control.py +++ b/sepal_ui/mapping/aoi_control.py @@ -50,9 +50,7 @@ def __init__(self, m: Map, **kwargs) -> None: self.menu.cole_on_content_click = True # set the size of the card to 0 so that the list controls the widget display - self.set_size( - min_width="200px", max_width="200px", min_height=None, max_height="300px" - ) + self.set_size(min_width="200px", max_width="200px", min_height=None, max_height="300px") # add js behaviours self.menu.v_slots[0]["children"].on_event("click", self.click_btn) @@ -74,9 +72,7 @@ def click_btn(self, *args) -> None: return @sd.need_ee - def add_aoi( - self, name: str, item: Union[sg.base.BaseGeometry, ee.ComputedObject] - ) -> None: + def add_aoi(self, name: str, item: Union[sg.base.BaseGeometry, ee.ComputedObject]) -> None: """Add an AOI to the list and refresh the list displayed. the AOI will be composed of a name and the bounds of the provided item. Args: diff --git a/sepal_ui/mapping/fullscreen_control.py b/sepal_ui/mapping/fullscreen_control.py index 80020418..8f69d5fb 100644 --- a/sepal_ui/mapping/fullscreen_control.py +++ b/sepal_ui/mapping/fullscreen_control.py @@ -26,9 +26,7 @@ class FullScreenControl(WidgetControl): template: Optional[v.VuetifyTemplate] = None "Embeds the 2 javascripts methods to change the rendering of the map" - def __init__( - self, m: Map, fullscreen: bool = False, fullapp: bool = False, **kwargs - ) -> None: + def __init__(self, m: Map, fullscreen: bool = False, fullapp: bool = False, **kwargs) -> None: """A custom Fullscreen Button ready to be embed in a map object. This button will force the display of the map in fullscreen mode. It should be used instead of the built-in ipyleaflet FullscreenControl if your map is embedding ipyvuetify widgets. I tends to solve the issue raised here: https://github.com/widgetti/ipyvuetify/issues/141. The idea is to fake the fullscreen display by forcing the map container to extend to the full extend of the screen without using a z-index superior to the ipyvuetify overlay. diff --git a/sepal_ui/mapping/inspector_control.py b/sepal_ui/mapping/inspector_control.py index 0ef26cf2..85e02bcf 100644 --- a/sepal_ui/mapping/inspector_control.py +++ b/sepal_ui/mapping/inspector_control.py @@ -147,9 +147,7 @@ def read_data(self, **kwargs) -> None: elif isinstance(lyr, Marker): continue else: - data = { - ms.inspector_control.info.header: ms.inspector_control.info.text - } + data = {ms.inspector_control.info.header: ms.inspector_control.info.text} items.append( { @@ -218,9 +216,7 @@ def _from_eelayer(self, ee_obj: ee.ComputedObject, coords: Sequence[float]) -> d ).getInfo() else: - raise ValueError( - f'the layer object is a "{type(ee_obj)}" which is not accepted.' - ) + raise ValueError(f'the layer object is a "{type(ee_obj)}" which is not accepted.') return pixel_values @@ -280,22 +276,17 @@ def _from_raster(self, raster: Union[str, Path], coords: Sequence[float]) -> dic window = rio.windows.from_bounds(*bounds, transform=da.rio.transform()) da_filtered = da.rio.isel_window(window) means = da_filtered.mean(axis=(1, 2)).to_numpy() - pixel_values = { - ms.inspector_control.band.format(i + 1): v for i, v in enumerate(means) - } + pixel_values = {ms.inspector_control.band.format(i + 1): v for i, v in enumerate(means)} # if the point is out of the image display None else: pixel_values = { - ms.inspector_control.band.format(i + 1): None - for i in range(da.rio.count) + ms.inspector_control.band.format(i + 1): None for i in range(da.rio.count) } return pixel_values -@deprecated( - version="2.15.1", reason="ValueInspector class is now renamed InspectorControl" -) +@deprecated(version="2.15.1", reason="ValueInspector class is now renamed InspectorControl") class ValueInspector(InspectorControl): pass diff --git a/sepal_ui/mapping/layers_control.py b/sepal_ui/mapping/layers_control.py index e1b76ca7..326888b4 100644 --- a/sepal_ui/mapping/layers_control.py +++ b/sepal_ui/mapping/layers_control.py @@ -181,10 +181,7 @@ def __init__(self, m: Map, **kwargs) -> None: # set the kwargs parameters kwargs.setdefault("position", "topright") super().__init__( - icon_content="fa-solid fa-layer-group", - card_content=self.tile, - m=m, - **kwargs + icon_content="fa-solid fa-layer-group", card_content=self.tile, m=m, **kwargs ) # customize the menu to make it look more like a layercontrol @@ -226,9 +223,7 @@ def update_table(self, change: dict) -> None: # the error raised if you delete the last one is a feature bases = [lyr for lyr in self.m.layers if lyr.base is True] base_rows = [] - current = next( - (lyr for lyr in bases if lyr.visible is True), SimpleNamespace(name=None) - ) + current = next((lyr for lyr in bases if lyr.visible is True), SimpleNamespace(name=None)) if len(bases) > 0: head = [HeaderRow(ms.layer_control.basemap.header)] empy_cell = sw.Html(tag="td", children=[" "], attributes={"colspan": 3}) diff --git a/sepal_ui/mapping/sepal_map.py b/sepal_ui/mapping/sepal_map.py index 4a2861ad..0928dee6 100644 --- a/sepal_ui/mapping/sepal_map.py +++ b/sepal_ui/mapping/sepal_map.py @@ -116,9 +116,7 @@ def __init__( # add the basemaps self.clear() - default_basemap = ( - "CartoDB.DarkMatter" if v.theme.dark is True else "CartoDB.Positron" - ) + default_basemap = "CartoDB.DarkMatter" if v.theme.dark is True else "CartoDB.Positron" basemaps = basemaps or [default_basemap] [self.add_basemap(basemap) for basemap in set(basemaps)] @@ -386,9 +384,7 @@ def add_colorbar( norm = mpc.BoundaryNorm(vals, plot_color.N) else: - plot_color = mpc.LinearSegmentedColormap.from_list( - "custom", hexcodes, N=256 - ) + plot_color = mpc.LinearSegmentedColormap.from_list("custom", hexcodes, N=256) norm = mpc.Normalize(vmin=vmin, vmax=vmax) elif cmap is not None: @@ -534,9 +530,7 @@ def add_ee_layer( # set to_min to 0 and to_max to 1 # in the original expression: # 'to_min + (v - from_min) * (to_max - to_min) / (from_max - from_min)' - expression = ( - "{band} = (b('{band}') - {from_min}) / ({from_max} - {from_min})" - ) + expression = "{band} = (b('{band}') - {from_min}) / ({from_max} - {from_min})" # get the maxs and mins # removing them from the parameter @@ -547,9 +541,7 @@ def add_ee_layer( asset = ee_object for i, band in enumerate(vis_params["bands"]): # adapt the expression - exp = expression.format( - from_min=mins[i], from_max=maxs[i], band=band - ) + exp = expression.format(from_min=mins[i], from_max=maxs[i], band=band) asset = asset.addBands(asset.expression(exp), [band], True) # set the arguments @@ -570,9 +562,7 @@ def add_ee_layer( ee.featurecollection.FeatureCollection, ), ): - default_vis = json.loads((ss.JSON_DIR / "layer.json").read_text())[ - "ee_layer" - ] + default_vis = json.loads((ss.JSON_DIR / "layer.json").read_text())["ee_layer"] default_vis.update(color=scolors.primary) # We want to get all the default styles and only change those whose are @@ -661,9 +651,7 @@ def get_viz_params(image: ee.Image) -> dict: # build a raw prop list raw_prop_list = { - p: val - for p, val in image.getInfo()["properties"].items() - if p.startswith(PREFIX) + p: val for p, val in image.getInfo()["properties"].items() if p.startswith(PREFIX) } # decompose each property by its number @@ -762,13 +750,9 @@ def add_layer(self, layer: ipl.Layer, hover: bool = False, key: str = "") -> Non # apply default coloring for geoJson if isinstance(layer, ipl.GeoJSON): # define the default values - default_style = json.loads((ss.JSON_DIR / "layer.json").read_text())[ - "layer" - ] + default_style = json.loads((ss.JSON_DIR / "layer.json").read_text())["layer"] default_style.update(color=scolors.primary) - default_hover_style = json.loads( - (ss.JSON_DIR / "layer_hover.json").read_text() - ) + default_hover_style = json.loads((ss.JSON_DIR / "layer_hover.json").read_text()) default_hover_style.update(color=scolors.primary) # apply the style depending on the parameters @@ -853,9 +837,7 @@ def add_legend( vertical: vertical or horizoal position of the legend """ # Define as class member so it can be accessed from outside. - self.legend = LegendControl( - legend_dict, title=title, vertical=vertical, position=position - ) + self.legend = LegendControl(legend_dict, title=title, vertical=vertical, position=position) return self.add(self.legend) diff --git a/sepal_ui/planetapi/planet_model.py b/sepal_ui/planetapi/planet_model.py index c3939499..b832fef2 100644 --- a/sepal_ui/planetapi/planet_model.py +++ b/sepal_ui/planetapi/planet_model.py @@ -21,9 +21,7 @@ class PlanetModel(Model): - SUBS_URL: str = ( - "https://api.planet.com/auth/v1/experimental/public/my/subscriptions" - ) + SUBS_URL: str = "https://api.planet.com/auth/v1/experimental/public/my/subscriptions" "The url of the planet API subscription" credentials: List[str] = [] @@ -59,9 +57,7 @@ def __init__(self, credentials: Union[str, List[str]] = "") -> None: version="3.0", reason="credentials member is deprecated, use self.auth._key instead", ) - def init_session( - self, credentials: Union[str, List[str]], write_secrets: bool = False - ) -> None: + def init_session(self, credentials: Union[str, List[str]], write_secrets: bool = False) -> None: """Initialize planet client with api key or credentials. It will handle errors. Args: @@ -160,9 +156,7 @@ def get_items( """ # cast start and end to str - start = ( - datetime.strptime(start, "%Y-%m-%d") if isinstance(start, str) else start - ) + start = datetime.strptime(start, "%Y-%m-%d") if isinstance(start, str) else start end = datetime.strptime(end, "%Y-%m-%d") if isinstance(end, str) else end and_filter = filters.and_filter( @@ -184,9 +178,7 @@ async def _main(): So we can keep calling get_items without any change. """ client = DataClient(self.session) - items = client.search( - item_types, and_filter, name="quick_search", limit=limit - ) + items = client.search(item_types, and_filter, name="quick_search", limit=limit) items_list = [item async for item in items] return items_list diff --git a/sepal_ui/planetapi/planet_view.py b/sepal_ui/planetapi/planet_view.py index 72f3d771..cde321c2 100644 --- a/sepal_ui/planetapi/planet_view.py +++ b/sepal_ui/planetapi/planet_view.py @@ -62,9 +62,7 @@ def __init__( self.btn = btn if btn else sw.Btn("Validate", small=True, class_="mr-1") self.alert = alert if alert else sw.Alert() - self.w_username = sw.TextField( - label=ms.planet.widget.username, class_="mr-2", v_model="" - ) + self.w_username = sw.TextField(label=ms.planet.widget.username, class_="mr-2", v_model="") self.w_password = sw.PasswordField(label=ms.planet.widget.password) self.w_key = sw.PasswordField(label=ms.planet.widget.apikey, v_model="").hide() self.w_secret_file = sw.TextField( @@ -135,9 +133,7 @@ def validate_secret_file(self) -> None: def set_initial_method(self) -> None: """Set the initial method to connect to planet lab.""" - self.w_method.v_model = ( - "from_file" if self.validate_secret_file() else "credentials" - ) + self.w_method.v_model = "from_file" if self.validate_secret_file() else "credentials" def reset(self) -> None: """Empty credentials fields and restart activation mode.""" diff --git a/sepal_ui/planetapi/planet_widgets.py b/sepal_ui/planetapi/planet_widgets.py index 0d41cc05..9ea6f3d3 100644 --- a/sepal_ui/planetapi/planet_widgets.py +++ b/sepal_ui/planetapi/planet_widgets.py @@ -57,9 +57,7 @@ def __init__(self, model: PlanetModel, **kwargs) -> None: self.children = [ v.ExpansionPanel( children=[ - v.ExpansionPanelHeader( - hide_actions=True, children=[v.Flex(children=subs_btn)] - ), + v.ExpansionPanelHeader(hide_actions=True, children=[v.Flex(children=subs_btn)]), v.ExpansionPanelContent(v_model=1, children=[self.info_card]), ] ) @@ -194,10 +192,7 @@ def update(self, subs_group: List[dict]) -> Self: Args: subs_group: list of subscriptions belonging to the same category ('nicfi', 'others') """ - content = [ - v.Card(class_="pa-2", children=self._make_content(sub)) - for sub in subs_group - ] + content = [v.Card(class_="pa-2", children=self._make_content(sub)) for sub in subs_group] self.children = content diff --git a/sepal_ui/scripts/decorator.py b/sepal_ui/scripts/decorator.py index 98de3b84..64b727ab 100644 --- a/sepal_ui/scripts/decorator.py +++ b/sepal_ui/scripts/decorator.py @@ -70,9 +70,7 @@ def init_ee() -> None: # Check if we are using a google service account if _credentials.get("type") == "service_account": ee_user = _credentials.get("client_email") - credentials = ee.ServiceAccountCredentials( - ee_user, str(credential_file_path) - ) + credentials = ee.ServiceAccountCredentials(ee_user, str(credential_file_path)) ee.Initialize(credentials=credentials) ee.data._cloud_api_user_project = project_id return @@ -121,15 +119,10 @@ def wrapper_alert_error(self, *args, **kwargs): # Use append msg as several warnings could be triggered if w_list: # split the warning list - w_list_sepal = [ - w for w in w_list if isinstance(w.message, SepalWarning) - ] + w_list_sepal = [w for w in w_list if isinstance(w.message, SepalWarning)] # display the sepal one - ms_list = [ - f"{w.category.__name__}: {w.message.args[0]}" - for w in w_list_sepal - ] + ms_list = [f"{w.category.__name__}: {w.message.args[0]}" for w in w_list_sepal] [alert_.append_msg(ms, type_="warning") for ms in ms_list] def custom_showwarning(w): @@ -281,15 +274,10 @@ def wrapper_switch(self, *args, **kwargs): if widgets_len: # Verify that the input elements are strings - wrong_types = [ - (w, type(w)) for w in on_widgets if not isinstance(w, str) - ] + wrong_types = [(w, type(w)) for w in on_widgets if not isinstance(w, str)] if len(wrong_types): - errors = [ - f"Received:{w_type} for widget: {w}." - for w, w_type in wrong_types - ] + errors = [f"Received:{w_type} for widget: {w}." for w, w_type in wrong_types] raise TypeError( f"All on_widgets list elements has to be strings. [{' '.join(errors)}]" @@ -303,9 +291,7 @@ def wrapper_switch(self, *args, **kwargs): ) def w_assign(bool_targets): - params_targets = [ - (p, bool_targets[i]) for i, p in enumerate(params) - ] + params_targets = [(p, bool_targets[i]) for i, p in enumerate(params)] for w_name, p_t in product(on_widgets, params_targets): param, target = p_t diff --git a/sepal_ui/scripts/utils.py b/sepal_ui/scripts/utils.py index d59e62f4..011fccca 100644 --- a/sepal_ui/scripts/utils.py +++ b/sepal_ui/scripts/utils.py @@ -163,9 +163,7 @@ def init_ee() -> None: # Check if we are using a google service account if _credentials.get("type") == "service_account": ee_user = _credentials.get("client_email") - credentials = ee.ServiceAccountCredentials( - ee_user, str(credential_file_path) - ) + credentials = ee.ServiceAccountCredentials(ee_user, str(credential_file_path)) ee.Initialize(credentials=credentials) ee.data._cloud_api_user_project = project_id return @@ -190,9 +188,7 @@ def normalize_str(msg: str, folder: bool = True) -> str: return re.sub(regex, "_", anyascii(msg)) -def to_colors( - in_color: Union[str, Sequence], out_type: str = "hex" -) -> Union[str, tuple]: +def to_colors(in_color: Union[str, Sequence], out_type: str = "hex") -> Union[str, tuple]: """Transform any color type into a color in the specified output format. Available format: [hex] @@ -278,9 +274,7 @@ def set_config(key: str, value: str, section: str = "sepal-ui") -> None: return -@deprecated( - version="2.9.1", reason="This function will be removed in favor of set_config()" -) +@deprecated(version="2.9.1", reason="This function will be removed in favor of set_config()") def set_config_locale(locale: str) -> None: """Set the provided local in the sepal-ui config file. @@ -290,9 +284,7 @@ def set_config_locale(locale: str) -> None: return set_config("locale", locale) -@deprecated( - version="2.9.1", reason="This function will be removed in favor of set_config()" -) +@deprecated(version="2.9.1", reason="This function will be removed in favor of set_config()") def set_config_theme(theme: str) -> None: """Set the provided theme in the sepal-ui config file. @@ -456,9 +448,7 @@ def get_changelog(repo_folder: Pathlike = Path.cwd()) -> str: changelog_text, release_text = "", "" repo_owner, repo_name = get_repo_info(repo_folder) - release_url = ( - f"https://api.github.com/repos/{repo_owner}/{repo_name}/releases/latest" - ) + release_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/releases/latest" response = requests.get(release_url) if all([repo_owner, repo_name]) and response.status_code == 200: diff --git a/sepal_ui/sepalwidgets/alert.py b/sepal_ui/sepalwidgets/alert.py index 9c70a732..c9ec6d59 100644 --- a/sepal_ui/sepalwidgets/alert.py +++ b/sepal_ui/sepalwidgets/alert.py @@ -96,9 +96,7 @@ def __init__(self, type_: str = "info", **kwargs) -> None: self.progress_output = Output() # self.progress_bar = None - def update_progress( - self, progress: float, msg: str = "Progress", **tqdm_args - ) -> None: + def update_progress(self, progress: float, msg: str = "Progress", **tqdm_args) -> None: """Update the Alert message with a tqdm progress bar. .. note:: @@ -338,9 +336,7 @@ def __init__( type_ = set_type(type_) # create the closing btn - self.btn_close = v.Btn( - small=True, text=True, children=[ms.widgets.banner.close] - ) + self.btn_close = v.Btn(small=True, text=True, children=[ms.widgets.banner.close]) # compute timeout based on the persistent and timeout parameter computed_timeout = 0 if persistent is True else self.get_timeout(msg) diff --git a/sepal_ui/sepalwidgets/app.py b/sepal_ui/sepalwidgets/app.py index 4ee06087..e99540e5 100644 --- a/sepal_ui/sepalwidgets/app.py +++ b/sepal_ui/sepalwidgets/app.py @@ -47,9 +47,7 @@ class LocaleSelect(v.Menu, SepalWidget): - COUNTRIES: pd.DataFrame = pd.read_parquet( - Path(__file__).parents[1] / "data" / "locale.parquet" - ) + COUNTRIES: pd.DataFrame = pd.read_parquet(Path(__file__).parents[1] / "data" / "locale.parquet") "the country list as a df. columns [code, name, flag]" FLAG: str = "https://flagcdn.com/{}.svg" @@ -84,9 +82,7 @@ def __init__(self, translator: Optional[Translator] = None, **kwargs) -> None: """ # extract the available language from the translator # default to only en-US if no translator is set - available_locales = ( - ["en"] if translator is None else translator.available_locales() - ) + available_locales = ["en"] if translator is None else translator.available_locales() # extract the language information from the translator # if not set default to english @@ -108,9 +104,7 @@ def __init__(self, translator: Optional[Translator] = None, **kwargs) -> None: max_height="300px", style_="overflow: auto; border-radius: 0 0 0 0;", children=[ - v.ListItemGroup( - children=self._get_country_items(available_locales), v_model="" - ) + v.ListItemGroup(children=self._get_country_items(available_locales), v_model="") ], ) @@ -257,9 +251,7 @@ def __init__( """ self.toggle_button = v.Btn( icon=True, - children=[ - v.Icon(class_="white--text", children=["fa-solid fa-ellipsis-v"]) - ], + children=[v.Icon(class_="white--text", children=["fa-solid fa-ellipsis-v"])], ) self.title = v.ToolbarTitle(children=[title]) @@ -337,9 +329,7 @@ def __init__( children = [ v.ListItemAction(children=[v.Icon(class_="white--text", children=[icon])]), - v.ListItemContent( - children=[v.ListItemTitle(class_="white--text", children=[title])] - ), + v.ListItemContent(children=[v.ListItemTitle(class_="white--text", children=[title])]), ] # set default parameters @@ -361,16 +351,12 @@ def __init__( # cannot be set as a class member because it will be shared with all # the other draweritems. self.alert_badge = v.ListItemAction( - children=[ - v.Icon(children=["fa-solid fa-circle"], x_small=True, color="red") - ] + children=[v.Icon(children=["fa-solid fa-circle"], x_small=True, color="red")] ) if model: if not bind_var: - raise Exception( - "You have selected a model, you need a trait to bind with drawer." - ) + raise Exception("You have selected a model, you need a trait to bind with drawer.") link((model, bind_var), (self, "alert")) @@ -471,9 +457,7 @@ def __init__( ) code_link.append(item_wiki) if issue: - item_bug = DrawerItem( - ms.widgets.navdrawer.bug, icon="fa-solid fa-bug", href=issue - ) + item_bug = DrawerItem(ms.widgets.navdrawer.bug, icon="fa-solid fa-bug", href=issue) code_link.append(item_bug) version_card = VersionCard(repo_folder=repo_folder) @@ -636,9 +620,7 @@ def __init__( # display a warning if the set language cannot be reached if translator is not None: if translator._match is False: - msg = ms.locale.fallback.format( - translator._targeted, translator._target - ) + msg = ms.locale.fallback.format(translator._targeted, translator._target) self.add_banner(msg, type_="error") # add js event diff --git a/sepal_ui/sepalwidgets/btn.py b/sepal_ui/sepalwidgets/btn.py index 9ceb3a41..95214d0d 100644 --- a/sepal_ui/sepalwidgets/btn.py +++ b/sepal_ui/sepalwidgets/btn.py @@ -61,9 +61,7 @@ def __init__(self, msg: str = "", gliph: str = "", **kwargs) -> None: if "text" in kwargs: if isinstance(kwargs["text"], str): msg = kwargs.pop("text") - warnings.warn( - '"text" is deprecated, please use "msg" instead', DeprecationWarning - ) + warnings.warn('"text" is deprecated, please use "msg" instead', DeprecationWarning) if "icon" in kwargs: if isinstance(kwargs["icon"], str): gliph = kwargs.pop("icon") diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py index 5062c698..e85db44b 100644 --- a/sepal_ui/sepalwidgets/inputs.py +++ b/sepal_ui/sepalwidgets/inputs.py @@ -61,9 +61,7 @@ class DatePicker(v.Layout, SepalWidget): disabled: t.Bool = t.Bool(False).tag(sync=True) "the disabled status of the Datepicker object" - def __init__( - self, label: str = "Date", layout_kwargs: Optional[dict] = None, **kwargs - ) -> None: + def __init__(self, label: str = "Date", layout_kwargs: Optional[dict] = None, **kwargs) -> None: """Custom input widget to provide a reusable DatePicker. It allows to choose date as a string in the following format YYYY-MM-DD. @@ -408,9 +406,7 @@ def _get_items(self) -> List[v.ListItem]: list_dir = [el for el in folder.glob("*") if not el.name.startswith(".")] if self.extensions: - list_dir = [ - el for el in list_dir if el.is_dir() or el.suffix in self.extensions - ] + list_dir = [el for el in list_dir if el.is_dir() or el.suffix in self.extensions] if folder in self.cache_dirs: if self.cache_dirs[folder]["files"] == list_dir: @@ -432,18 +428,14 @@ def _get_items(self) -> List[v.ListItem]: children = [ v.ListItemAction(children=[v.Icon(color=color, children=[icon])]), - v.ListItemContent( - children=[v.ListItemTitle(children=[el.stem + el.suffix])] - ), + v.ListItemContent(children=[v.ListItemTitle(children=[el.stem + el.suffix])]), ] if el.is_dir(): folder_list.append(v.ListItem(value=str(el), children=children)) else: file_size = su.get_file_size(el) - children.append( - v.ListItemActionText(class_="ml-1", children=[file_size]) - ) + children.append(v.ListItemActionText(class_="ml-1", children=[file_size])) file_list.append(v.ListItem(value=str(el), children=children)) folder_list = humansorted(folder_list, key=lambda x: x.value) @@ -590,9 +582,7 @@ def _on_file_input_change(self, change: dict) -> Self: if len(df.columns) < 3: self._set_v_model("pathname", None) - self.fileInput.selected_file.error_messages = ( - ms.widgets.load_table.too_small - ) + self.fileInput.selected_file.error_messages = ms.widgets.load_table.too_small return self # set the items @@ -605,8 +595,7 @@ def _on_file_input_change(self, change: dict) -> Self: if "id" in lname: self.IdSelect.v_model = name elif any( - ext in lname - for ext in ["lng", "long", "longitude", "x_coord", "xcoord", "lon"] + ext in lname for ext in ["lng", "long", "longitude", "x_coord", "xcoord", "lon"] ): self.LngSelect.v_model = name elif any(ext in lname for ext in ["lat", "latitude", "y_coord", "ycoord"]): @@ -690,9 +679,7 @@ def __init__( self.asset_info = None # if folder is not set use the root one - self.folder = ( - str(folder) or f"projects/{ee.data._cloud_api_user_project}/assets/" - ) + self.folder = str(folder) or f"projects/{ee.data._cloud_api_user_project}/assets/" self.types = types # load the default assets @@ -784,10 +771,7 @@ def _get_items(self, *args) -> Self: # get the list of user asset raw_assets = gee.get_assets(self.folder) - assets = { - k: sorted([e["id"] for e in raw_assets if e["type"] == k]) - for k in self.types - } + assets = {k: sorted([e["id"] for e in raw_assets if e["type"] == k]) for k in self.types} # sort the assets by types for k in self.types: @@ -935,9 +919,7 @@ class VectorField(v.Col, SepalWidget): feature_collection: Optional[ee.FeatureCollection] = None "ee.FeatureCollection: the selected featureCollection" - def __init__( - self, label: str = ms.widgets.vector.label, gee: bool = False, **kwargs - ) -> None: + def __init__(self, label: str = ms.widgets.vector.label, gee: bool = False, **kwargs) -> None: """A custom input widget to load vector data. The user will provide a vector file compatible with fiona or a GEE feature collection. @@ -1011,9 +993,7 @@ def _update_file(self, change: dict) -> Self: elif isinstance(self.w_file, AssetSelect): self.feature_collection = ee.FeatureCollection(change["new"]) columns = self.feature_collection.first().getInfo()["properties"] - columns = [ - str(col) for col in columns if col not in ["system:index", "Shape_Area"] - ] + columns = [str(col) for col in columns if col not in ["system:index", "Shape_Area"]] # update the columns self.w_column.items = self.column_base_items + sorted(set(columns)) diff --git a/sepal_ui/sepalwidgets/sepalwidget.py b/sepal_ui/sepalwidgets/sepalwidget.py index 3d7d7273..c980de35 100644 --- a/sepal_ui/sepalwidgets/sepalwidget.py +++ b/sepal_ui/sepalwidgets/sepalwidget.py @@ -166,11 +166,7 @@ def get_children( # compare the widget with requirements # if no klass is specified, use both vuetifyWidget and Html objects - is_klass = ( - isinstance(w, klass) - if klass - else isinstance(w, ((v.VuetifyWidget, v.Html))) - ) + is_klass = isinstance(w, klass) if klass else isinstance(w, ((v.VuetifyWidget, v.Html))) # using "niet" as default so that result is True if attr is Falsy # "niet" is very unlikely to be used compared to None, False, "none"... @@ -204,9 +200,7 @@ def set_children( new_childrens = new_childrens + children else: - raise ValueError( - f"Position '{position}' is not a valid value. Use 'first' or 'last'" - ) + raise ValueError(f"Position '{position}' is not a valid value. Use 'first' or 'last'") self.children = new_childrens @@ -247,9 +241,7 @@ def __init__(self, widget: v.VuetifyWidget, tooltip: str, **kwargs) -> None: # set some default parameters kwargs.setdefault("close_delay", 200) - self.v_slots = [ - {"name": "activator", "variable": "tooltip", "children": widget} - ] + self.v_slots = [{"name": "activator", "variable": "tooltip", "children": widget}] widget.v_on = "tooltip.on" self.children = [tooltip] diff --git a/sepal_ui/sepalwidgets/tile.py b/sepal_ui/sepalwidgets/tile.py index 97a6aeb9..580e2c54 100644 --- a/sepal_ui/sepalwidgets/tile.py +++ b/sepal_ui/sepalwidgets/tile.py @@ -67,9 +67,7 @@ def __init__( content = [v.Flex(xs12=True, children=[widget]) for widget in inputs] - card = v.Card( - class_="pa-5", raised=True, xs12=True, children=[self.title] + content - ) + card = v.Card(class_="pa-5", raised=True, xs12=True, children=[self.title] + content) # set some default parameters kwargs["_metadata"] = {"mount_id": id_} diff --git a/sepal_ui/sepalwidgets/widget.py b/sepal_ui/sepalwidgets/widget.py index 52fa1d2c..f13f8eee 100644 --- a/sepal_ui/sepalwidgets/widget.py +++ b/sepal_ui/sepalwidgets/widget.py @@ -93,9 +93,7 @@ def __init__(self, **kwargs) -> None: # template with js behaviour js_dir = Path(__file__).parents[1] / "frontend/js" clip = (js_dir / "jupyter_clip.js").read_text() - self.template = ( - "" "" % clip - ) + self.template = "" "" % clip super().__init__() @@ -150,9 +148,7 @@ def __init__( # Get the first value (states first key) to use as default one init_value = self.states[next(iter(self.states))] - self.icon = v.Icon( - children=["fa-solid fa-circle"], color=init_value[1], small=True - ) + self.icon = v.Icon(children=["fa-solid fa-circle"], color=init_value[1], small=True) super().__init__(self.icon, init_value[0], **kwargs) diff --git a/sepal_ui/templates/map_app/component/tile/map_tile.py b/sepal_ui/templates/map_app/component/tile/map_tile.py index 197b31c4..7b3980cf 100644 --- a/sepal_ui/templates/map_app/component/tile/map_tile.py +++ b/sepal_ui/templates/map_app/component/tile/map_tile.py @@ -14,9 +14,7 @@ def __init__(self): # create a map self.m = sm.SepalMap(zoom=3) # to be visible on 4k screens self.m.add_control( - sm.FullScreenControl( - self.m, fullscreen=True, fullapp=True, position="topright" - ) + sm.FullScreenControl(self.m, fullscreen=True, fullapp=True, position="topright") ) # create the tile diff --git a/tests/conftest.py b/tests/conftest.py index e20ce789..edc7e4d9 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -303,9 +303,7 @@ def byte(tmp_path_factory: pytest.TempPathFactory) -> Path: the path to the byte file """ file = tmp_path_factory.mktemp("temp") / "byte.tif" - link = ( - "https://raw.githubusercontent.com/rasterio/rasterio/master/tests/data/byte.tif" - ) + link = "https://raw.githubusercontent.com/rasterio/rasterio/master/tests/data/byte.tif" urlretrieve(link, file) return file diff --git a/tests/test_aoi/test_AoiModel.py b/tests/test_aoi/test_AoiModel.py index 330e5c83..dd2f9989 100644 --- a/tests/test_aoi/test_AoiModel.py +++ b/tests/test_aoi/test_AoiModel.py @@ -133,9 +133,7 @@ def test_get_selected(test_model: aoi.AoiModel) -> None: aoi_model.get_fields("toto", "toto") # select the vatican feature in GAUL 2015 - ee_vat = ee.FeatureCollection("FAO/GAUL/2015/level0").filter( - ee.Filter.eq("ADM0_CODE", "110") - ) + ee_vat = ee.FeatureCollection("FAO/GAUL/2015/level0").filter(ee.Filter.eq("ADM0_CODE", "110")) # select the geometry associated with Vatican city (all of it) column, field = ("ADM0_CODE", "110") @@ -148,9 +146,7 @@ def test_get_selected(test_model: aoi.AoiModel) -> None: return -def test_clear_attributes( - aoi_model_outputs: List[str], aoi_model_traits: List[str] -) -> None: +def test_clear_attributes(aoi_model_outputs: List[str], aoi_model_traits: List[str]) -> None: """Remove all attributes from an AoiMOdel. Args: diff --git a/tests/test_aoi/test_AoiView.py b/tests/test_aoi/test_AoiView.py index a5015a90..5eb0ac22 100644 --- a/tests/test_aoi/test_AoiView.py +++ b/tests/test_aoi/test_AoiView.py @@ -32,9 +32,7 @@ def test_init() -> None: # init with a remove list view = aoi.AoiView(["-POINTS"], gee=False) assert {"text": ms.aoi_sel.points, "value": "POINTS"} not in view.w_method.items - assert ( - len(view.w_method.items) == len(aoi.AoiModel.METHODS) + 2 - 1 - ) # 2 headers this time + assert len(view.w_method.items) == len(aoi.AoiModel.METHODS) + 2 - 1 # 2 headers this time # init with a mix of both with pytest.raises(Exception): @@ -161,9 +159,7 @@ def test_update_local_aoi(aoi_local_view: aoi.AoiView) -> None: aoi_local_view: an object without gee binding """ # select Vatican - item = next( - i for i in aoi_local_view.w_admin_0.items if i["text"] == "Vatican City" - ) + item = next(i for i in aoi_local_view.w_admin_0.items if i["text"] == "Vatican City") aoi_local_view.w_method.v_model = "ADMIN0" aoi_local_view.w_admin_0.v_model = item["value"] @@ -185,9 +181,7 @@ def test_reset(aoi_local_view: aoi.AoiView) -> None: aoi_local_view: an object without gee binding """ # select Italy - item = next( - i for i in aoi_local_view.w_admin_0.items if i["text"] == "Vatican City" - ) + item = next(i for i in aoi_local_view.w_admin_0.items if i["text"] == "Vatican City") aoi_local_view.w_method.v_model = "ADMIN0" aoi_local_view.w_admin_0.v_model = item["value"] diff --git a/tests/test_mapping/test_AoiControl.py b/tests/test_mapping/test_AoiControl.py index bc8edeaf..34779c92 100644 --- a/tests/test_mapping/test_AoiControl.py +++ b/tests/test_mapping/test_AoiControl.py @@ -24,9 +24,7 @@ def test_init() -> None: @pytest.mark.skipif(not ee.data._credentials, reason="GEE is not set") -def test_add_aoi_ee( - ee_points: Tuple[ee.Geometry.Point], aoi_control: sm.AoiControl -) -> None: +def test_add_aoi_ee(ee_points: Tuple[ee.Geometry.Point], aoi_control: sm.AoiControl) -> None: """Add a ee point to the aoi_control. Args: diff --git a/tests/test_mapping/test_InspectorControl.py b/tests/test_mapping/test_InspectorControl.py index 872e8c5e..5c2ce586 100644 --- a/tests/test_mapping/test_InspectorControl.py +++ b/tests/test_mapping/test_InspectorControl.py @@ -70,9 +70,7 @@ def test_read_data() -> None: @pytest.mark.skipif(not ee.data._credentials, reason="GEE is not set") -def test_free_eelayer( - world_temp: ee.imagecollection, ee_adm2: ee.FeatureCollection -) -> None: +def test_free_eelayer(world_temp: ee.imagecollection, ee_adm2: ee.FeatureCollection) -> None: """Check result when clicking on a ee object. Args: diff --git a/tests/test_mapping/test_LayersControl.py b/tests/test_mapping/test_LayersControl.py index 90377fe7..28db285a 100644 --- a/tests/test_mapping/test_LayersControl.py +++ b/tests/test_mapping/test_LayersControl.py @@ -130,12 +130,8 @@ def test_change_basemap() -> None: m = sm.SepalMap(["HYBRID", "CartoDB.Positron"]) layer_control = next(c for c in m.controls if isinstance(c, sm.LayersControl)) layer_rows = layer_control.tile.get_children(klass=sm.BaseRow) - carto_row = next( - r for r in layer_rows if r.children[0].children[0] == "CartoDB.Positron" - ) - google_row = next( - r for r in layer_rows if r.children[0].children[0] == "Google Satellite" - ) + carto_row = next(r for r in layer_rows if r.children[0].children[0] == "CartoDB.Positron") + google_row = next(r for r in layer_rows if r.children[0].children[0] == "Google Satellite") carto_layer = m.find_layer("CartoDB.Positron", base=True) google_layer = m.find_layer("Google Satellite", base=True) diff --git a/tests/test_mapping/test_MenuControl.py b/tests/test_mapping/test_MenuControl.py index 3ddeaf3e..b55c6c40 100644 --- a/tests/test_mapping/test_MenuControl.py +++ b/tests/test_mapping/test_MenuControl.py @@ -8,9 +8,7 @@ def test_init() -> None: """Init a menu control.""" # create a tile - tile = sw.Tile( - "toto", "tutu", inputs=[sw.Slider()], btn=sw.Btn(), alert=sw.Alert().show() - ) + tile = sw.Tile("toto", "tutu", inputs=[sw.Slider()], btn=sw.Btn(), alert=sw.Alert().show()) # create the menu_control m = sm.SepalMap() diff --git a/tests/test_planetapi/test_PlanetView.py b/tests/test_planetapi/test_PlanetView.py index 49ec57c3..a2d3b26f 100644 --- a/tests/test_planetapi/test_PlanetView.py +++ b/tests/test_planetapi/test_PlanetView.py @@ -48,9 +48,7 @@ def test_reset() -> None: # use a default method # Default method will be from_file if the secrets file exists - default_method = ( - "from_file" if (Path.home() / ".planet.json").exists() else "credentials" - ) + default_method = "from_file" if (Path.home() / ".planet.json").exists() else "credentials" if default_method == "credentials": assert planet_view.w_method.v_model == default_method assert planet_view.w_username.viz is True @@ -125,9 +123,7 @@ def test_validate_secret_file(planet_key) -> None: planet_view.validate_secret_file() - assert planet_view.w_secret_file.error_messages == [ - ms.planet.exception.no_secret_file - ] + assert planet_view.w_secret_file.error_messages == [ms.planet.exception.no_secret_file] # Restore the file planet_secret_file.with_suffix(".json.bak").rename(planet_secret_file) @@ -154,9 +150,7 @@ def test_validate_event() -> None: planet_view.btn.fire_event("click", None) # Assert - assert planet_view.alert.children[0].children == [ - ms.planet.exception.no_secret_file - ] + assert planet_view.alert.children[0].children == [ms.planet.exception.no_secret_file] # Restore if there was a file if exists: diff --git a/tests/test_planetapi/test_PlanetWidgets.py b/tests/test_planetapi/test_PlanetWidgets.py index 20d2fdbb..d367469a 100644 --- a/tests/test_planetapi/test_PlanetWidgets.py +++ b/tests/test_planetapi/test_PlanetWidgets.py @@ -51,9 +51,7 @@ def test_open_info(plan: dict) -> None: assert info_view.v_model == 1 nicfi_sub.fire_event("click", None) assert len(info_view.info_card.children) == 1 - assert ( - info_view.info_card.children[0].children[0].children[0] == plan["plan"]["name"] - ) + assert info_view.info_card.children[0].children[0].children[0] == plan["plan"]["name"] assert info_view.v_model == 0 # If we click the button two times, it will close the expansion panel diff --git a/tests/test_scripts/test_decorator.py b/tests/test_scripts/test_decorator.py index 1ca0f432..9f8e5f5f 100644 --- a/tests/test_scripts/test_decorator.py +++ b/tests/test_scripts/test_decorator.py @@ -37,9 +37,7 @@ def test_init_ee() -> None: assert credentials_filepath.exists() # read the back up and remove the "project_id" key - credentials = json.loads( - credentials_filepath.with_suffix(".json.bak").read_text() - ) + credentials = json.loads(credentials_filepath.with_suffix(".json.bak").read_text()) ## 2. Assert when there's no a project associated # remove the project_id key if it exists diff --git a/tests/test_scripts/test_gee.py b/tests/test_scripts/test_gee.py index 9224158c..7200e70e 100644 --- a/tests/test_scripts/test_gee.py +++ b/tests/test_scripts/test_gee.py @@ -12,9 +12,7 @@ @pytest.mark.skipif(not ee.data._credentials, reason="GEE is not set") -def test_wait_for_completion( - alert: sw.Alert, fake_task: str, gee_dir: Path, _hash: str -) -> None: +def test_wait_for_completion(alert: sw.Alert, fake_task: str, gee_dir: Path, _hash: str) -> None: """Check we can wait for a task completion. Args: diff --git a/tests/test_scripts/test_utils.py b/tests/test_scripts/test_utils.py index 33cdd646..845b8fd9 100644 --- a/tests/test_scripts/test_utils.py +++ b/tests/test_scripts/test_utils.py @@ -131,9 +131,7 @@ def test_init_ee() -> None: assert credentials_filepath.exists() # read the back up and remove the "project_id" key - credentials = json.loads( - credentials_filepath.with_suffix(".json.bak").read_text() - ) + credentials = json.loads(credentials_filepath.with_suffix(".json.bak").read_text()) ## 2. Assert when there's no a project associated # remove the project_id key if it exists @@ -361,9 +359,7 @@ def test_get_repo_info(repo_dir): config = ConfigParser() config.add_section('remote "origin"') - config.set( - 'remote "origin"', "url", f"git@github.com:{expected_owner}/{expected_repo}.git" - ) + config.set('remote "origin"', "url", f"git@github.com:{expected_owner}/{expected_repo}.git") with open(git_folder / "config", "w") as f: config.write(f) diff --git a/tests/test_sepalwidgets/test_AssetSelect.py b/tests/test_sepalwidgets/test_AssetSelect.py index 2862c78d..7ec1f517 100644 --- a/tests/test_sepalwidgets/test_AssetSelect.py +++ b/tests/test_sepalwidgets/test_AssetSelect.py @@ -102,19 +102,13 @@ def test_check_types(asset_select: sw.AssetSelect, gee_user_dir: Path) -> None: # check that the list of asset is complete assert str(gee_user_dir / "image") in asset_select.items assert str(gee_user_dir / "feature_collection") in asset_select.items - assert ( - str(gee_user_dir / "subfolder/subfolder_feature_collection") - in asset_select.items - ) + assert str(gee_user_dir / "subfolder/subfolder_feature_collection") in asset_select.items # set an IMAGE type asset_select.types = ["IMAGE"] assert str(gee_user_dir / "image") in asset_select.items assert str(gee_user_dir / "feature_collection") not in asset_select.items - assert ( - str(gee_user_dir / "subfolder/subfolder_feature_collection") - not in asset_select.items - ) + assert str(gee_user_dir / "subfolder/subfolder_feature_collection") not in asset_select.items # set a type list with a non legit asset type asset_select.types = ["IMAGE", "toto"] diff --git a/tests/test_sepalwidgets/test_Banner.py b/tests/test_sepalwidgets/test_Banner.py index a9eab9c9..08a4c8de 100644 --- a/tests/test_sepalwidgets/test_Banner.py +++ b/tests/test_sepalwidgets/test_Banner.py @@ -69,6 +69,4 @@ def banner() -> sw.Banner: Returns: the banner object """ - return sw.Banner( - msg="dummy message", type_="warning", id_="test_banner", persistent=False - ) + return sw.Banner(msg="dummy message", type_="warning", id_="test_banner", persistent=False) diff --git a/tests/test_sepalwidgets/test_DatePicker.py b/tests/test_sepalwidgets/test_DatePicker.py index 47dd5884..bbc372f4 100644 --- a/tests/test_sepalwidgets/test_DatePicker.py +++ b/tests/test_sepalwidgets/test_DatePicker.py @@ -38,9 +38,7 @@ def test_kwargs() -> None: "align_center": False, } - datepicker = sw.DatePicker( - v_model="", layout_kwargs=layout_kwargs, **date_picker_kwargs - ) + datepicker = sw.DatePicker(v_model="", layout_kwargs=layout_kwargs, **date_picker_kwargs) assert datepicker.date_picker.min == "2018-02-14" assert datepicker.date_picker.max == "2021-03-14" diff --git a/tests/test_sepalwidgets/test_FileInput.py b/tests/test_sepalwidgets/test_FileInput.py index 41afd38c..376012bd 100644 --- a/tests/test_sepalwidgets/test_FileInput.py +++ b/tests/test_sepalwidgets/test_FileInput.py @@ -90,9 +90,7 @@ def test_on_file_select(root_dir: Path, file_input: sw.FileInput, readme: Path) return -def test_on_reload( - file_input: sw.FileInput, tmp_path_factory: pytest.TempPathFactory -) -> None: +def test_on_reload(file_input: sw.FileInput, tmp_path_factory: pytest.TempPathFactory) -> None: """Check that updating file content is updated when clicking on reload. Args: