Skip to content

Commit

Permalink
increased test coverage t95
Browse files Browse the repository at this point in the history
  • Loading branch information
FedeClaudi committed Oct 30, 2020
1 parent a76f50a commit 83686d4
Show file tree
Hide file tree
Showing 19 changed files with 160 additions and 133 deletions.
Binary file modified .DS_Store
Binary file not shown.
3 changes: 3 additions & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
[report]

exclude_lines =
def keypress
pragma: no cover
11 changes: 2 additions & 9 deletions brainrender/_actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,15 @@ def make_actor_label(
- xoffset, yoffset, zoffset: integers that shift the label position
- radius: radius of sphere used to denote label anchor. Set to 0 or None to hide.
"""

if atlas.atlas_name == "ABA":
offset = [-yoffset, -zoffset, xoffset]
default_offset = np.array([0, -200, 100])
else:
offset = [xoffset, yoffset, zoffset]
default_offset = np.array([100, 0, -200])
offset = [-yoffset, -zoffset, xoffset]
default_offset = np.array([0, -200, 100])

new_actors = []
for n, (actor, label) in enumerate(zip(listify(actors), listify(labels))):

# Get label color
if color is None:
color = actor.c()
elif isinstance(color, (list, tuple)):
color = color[n]

# Get mesh's highest point
points = actor.points().copy()
Expand Down
13 changes: 0 additions & 13 deletions brainrender/_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,6 @@ def makePalette(N, *colors):
c = c1 * (1 - f) + c2 * f
cols.append(c)
output.extend(cols)

if len(output) != N:
if len(output) > N:
return output[:N]
else:
raise ValueError(
f"Expected number of output colors was {N} but we got {len(output)} instead"
)
return output


Expand All @@ -116,11 +108,6 @@ def get_random_colors(n_colors=1):
:param n_colors: (Default value = 1)
"""
if not isinstance(n_colors, np.int):
raise ValueError("n_colors should be an integer")
if n_colors <= 0:
raise ValueError("n_colors should be bigger or equal to 0")

col_names = list(vcolors.keys())
if n_colors == 1:
return random.choice(col_names)
Expand Down
22 changes: 14 additions & 8 deletions brainrender/_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,19 @@ def connected_to_internet(url="http://www.google.com/", timeout=5):
try:
_ = requests.get(url, timeout=timeout)
return True
except requests.ConnectionError:
print("No internet connection available.")
except requests.ConnectionError: # pragma: no cover
print("No internet connection available.") # pragma: no cover
return False


def fail_on_no_connection(func):
"""
Decorator that throws an error if no internet connection is available
"""
if not connected_to_internet():
raise ConnectionError("No internet connection found.")
if not connected_to_internet(): # pragma: no cover
raise ConnectionError(
"No internet connection found."
) # pragma: no cover

def inner(*args, **kwargs):
return func(*args, **kwargs)
Expand All @@ -43,20 +45,24 @@ def request(url):
response = requests.get(url)
if response.ok:
return response
else:
exception_string = "URL request failed: {}".format(response.reason)
else: # pragma: no cover
exception_string = "URL request failed: {}".format(
response.reason
) # pragma: no cover
raise ValueError(exception_string)


def check_file_exists(func):
def check_file_exists(func): # pragma: no cover
"""
Decorator that throws an error if a function;s first argument
is not a path to an existing file.
"""

def inner(*args, **kwargs):
if not Path(args[0]).exists():
raise FileNotFoundError(f"File {args[0]} not found")
raise FileNotFoundError(
f"File {args[0]} not found"
) # pragma: no cover
return func(*args, **kwargs)

return inner
Expand Down
20 changes: 10 additions & 10 deletions brainrender/_video.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
try:
import cv2
except ModuleNotFoundError:
raise ModuleNotFoundError(
"You need opencv to save videos in brainrender, please install opencv with: "
+ "pip install opencv-python"
except ModuleNotFoundError: # pragma: no cover
raise ModuleNotFoundError( # pragma: no cover
"You need opencv to save videos in brainrender, please install opencv with: " # pragma: no cover
+ "pip install opencv-python" # pragma: no cover
)
from vedo import Video as VtkVideo
import os
Expand All @@ -28,8 +28,8 @@ def open_cvwriter(
videowriter = cv2.VideoWriter(
filepath, fourcc, framerate, (w, h), iscolor
)
except:
raise ValueError("Could not create videowriter")
except: # pragma: no cover
raise ValueError("Could not create videowriter") # pragma: no cover
else:
return videowriter

Expand Down Expand Up @@ -123,10 +123,10 @@ def get_cap_from_images_folder(self, img_format="%1d.png"):

# Check all went well
ret, frame = cap.read()
if not ret:
raise ValueError(
"Something went wrong, can't read form folder: "
+ self.tmp_dir.name
if not ret: # pragma: no cover
raise ValueError( # pragma: no cover
"Something went wrong, can't read form folder: " # pragma: no cover
+ self.tmp_dir.name # pragma: no cover
)
else:
cap.set(1, 0) # reset cap to first frame
Expand Down
8 changes: 5 additions & 3 deletions brainrender/actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,12 @@ def __getattr__(self, attr):
return None
if hasattr(self.__dict__["mesh"], attr):
return getattr(self.__dict__["mesh"], attr)
else:
raise AttributeError(f"{self} doesn not have attribute {attr}")
else: # pragma: no cover
raise AttributeError(
f"{self} doesn not have attribute {attr}"
) # pragma: no cover

def __repr__(self):
def __repr__(self): # pragma: no cover
return f"brainrender.Actor: {self.name}-{self.br_class}"

def __str__(self):
Expand Down
26 changes: 13 additions & 13 deletions brainrender/actors/points.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ def __init__(self, data, name=None, colors="salmon", alpha=1, radius=20):
mesh = self._from_numpy(data)
elif isinstance(data, (str, Path)):
mesh = self._from_file(data)
else:
raise TypeError(
f"Input data should be either a numpy array or a file path, not: {_class_name(data)}"
)
else: # pragma: no cover
raise TypeError( # pragma: no cover
f"Input data should be either a numpy array or a file path, not: {_class_name(data)}" # pragma: no cover
) # pragma: no cover

Actor.__init__(self, mesh, name=self.name, br_class="Points")

Expand All @@ -58,10 +58,10 @@ def _from_numpy(self, data):
"""
N = len(data)
if not isinstance(self.colors, str):
if not N == len(self.colors):
raise ValueError(
"When passing a list of colors, the number of colors should match the number of cells"
)
if not N == len(self.colors): # pragma: no cover
raise ValueError( # pragma: no cover
"When passing a list of colors, the number of colors shou # pragma: no coverld match the number of cells" # pragma: no cover
) # pragma: no cover

self.name = self.name or "Points"
mesh = Spheres(
Expand All @@ -81,8 +81,8 @@ def _from_file(self, data, colors="salmon", alpha=1):
if path.suffix == ".npy":
self.name = self.name or path.name
return self._from_numpy(np.load(path),)
else:
raise NotImplementedError(
f"Add points from file only works with numpy file for now, now {path.suffix}."
+ "If youd like more formats supported open an issue on Github!"
)
else: # pragma: no cover
raise NotImplementedError( # pragma: no cover
f"Add points from file only works with numpy file for now, now {path.suffix}." # pragma: no cover
+ "If youd like more formats supported open an issue on Github!" # pragma: no cover
) # pragma: no cover
4 changes: 2 additions & 2 deletions brainrender/actors/ruler.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ def ruler(p1, p2, unit_scale=1, units=None, s=50):
actors.append(Line(gap2, p2, lw=200))

# Add label
if units is None:
units = ""
if units is None: # pragma: no cover
units = "" # pragma: no cover
dist = mag(p2 - p1) * unit_scale
label = precision(dist, 3) + " " + units
lbl = Text(label, pos=midpoint, s=s + 100, justify="center")
Expand Down
8 changes: 4 additions & 4 deletions brainrender/actors/streamlines.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@

mca = MouseConnectivityApi()
allen_sdk_installed = True
except ModuleNotFoundError:
allen_sdk_installed = False
except ModuleNotFoundError: # pragma: no cover
allen_sdk_installed = False # pragma: no cover


from brainrender import base_dir
Expand Down Expand Up @@ -143,8 +143,8 @@ def _make_mesh(self, data):
if len(data["lines"]) == 1:
try:
lines_data = data["lines"][0]
except KeyError:
lines_data = data["lines"]["0"]
except KeyError: # pragma: no cover
lines_data = data["lines"]["0"] # pragma: no cover
else:
lines_data = data["lines"]
for line in lines_data:
Expand Down
10 changes: 6 additions & 4 deletions brainrender/atlas.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ def get(self, _type, *args, **kwargs):
if _type == "region":
return self._get_region(*args, **kwargs)
else:
raise ValueError(f"Unrecognized argument {_type}")
raise ValueError(
f"Unrecognized argument {_type}"
) # pragma: no cover

def _get_region(self, *regions, alpha=1, color=None):
"""
Expand Down Expand Up @@ -100,9 +102,9 @@ def get_plane(

try:
norm = norm or self.space.plane_normals[plane]
except KeyError:
raise ValueError(
f"Could not find normals for plane {plane}. Atlas space provides these normals: {self.space.plane_normals}"
except KeyError: # pragma: no cover
raise ValueError( # pragma: no cover
f"Could not find normals for plane {plane}. Atlas space provides these norma ls: {self.space.plane_normals}" # pragma: no cover
)

# Get plane width and height
Expand Down
Binary file not shown.
42 changes: 28 additions & 14 deletions brainrender/atlas_specific/aba_gene_expression/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,13 @@ def get_gene_experiments(self, gene_symbol):
if isinstance(gene_symbol, int): # it's an ID, get symbol
gene_symbol = self.get_gene_symbol_by_id(gene_symbol)
if gene_symbol is None:
raise ValueError("Invalid gene_symbol argument")
raise ValueError(
"Invalid gene_symbol argument"
) # pragma: no cover
else:
raise ValueError("Invalid gene_symbol argument")
raise ValueError(
"Invalid gene_symbol argument"
) # pragma: no cover

url = self.gene_experiments_url.replace("-GENE_SYMBOL-", gene_symbol)
data = request(url).json()["msg"]
Expand All @@ -122,8 +126,8 @@ def download_gene_data(self, gene):
if self.genes is None:
self.genes = self.get_all_genes()
if str(gene) not in self.genes.id.values:
raise ValueError(
f"The gened {gene} is not in the list of available genes"
raise ValueError( # pragma: no cover
f"The gened {gene} is not in the list of available genes" # pragma: no cover
)

# Get the gene's experiment id
Expand All @@ -148,9 +152,13 @@ def get_gene_data(self, gene, exp_id, use_cache=True, metric="energy"):
Given a list of gene ids
"""
if not isinstance(gene, int):
raise ValueError("Gene id should be an integer")
raise ValueError(
"Gene id should be an integer"
) # pragma: no cover
if not isinstance(exp_id, int):
raise ValueError("Expression id should be an integer")
raise ValueError(
"Expression id should be an integer"
) # pragma: no cover

self.gene_name = self.gene_name or gene

Expand All @@ -164,7 +172,7 @@ def get_gene_data(self, gene, exp_id, use_cache=True, metric="energy"):
self.download_gene_data(gene)
cache = check_gene_cached(self.gene_expression_cache, gene, exp_id)
if not cache:
raise ValueError(
raise ValueError( # pragma: no cover
"Something went wrong and data were not cached"
)

Expand Down Expand Up @@ -192,26 +200,32 @@ def griddata_to_volume(
"""
# Check inputs
if not isinstance(griddata, np.ndarray):
raise ValueError("Griddata should be a numpy array")
raise ValueError(
"Griddata should be a numpy array"
) # pragma: no cover
if not len(griddata.shape) == 3:
raise ValueError("Griddata should be a 3d array")
raise ValueError(
"Griddata should be a 3d array"
) # pragma: no cover

# Get threshold
if min_quantile is None and min_value is None:
th = 0
elif min_value is not None:
if not isinstance(min_value, (int, float)):
raise ValueError("min_values should be a float")
raise ValueError(
"min_values should be a float"
) # pragma: no cover
th = min_value
else:
if not isinstance(min_quantile, (float, int)):
raise ValueError(
raise ValueError( # pragma: no cover
"min_values should be a float in range [0, 1]"
)
if 0 > min_quantile or 100 < min_quantile:
raise ValueError(
"min_values should be a float in range [0, 100]"
)
raise ValueError( # pragma: no cover
"min_values should be a float in range [0, 100]" # pragma: no cover
) # pragma: no cover
th = np.percentile(griddata.ravel(), min_quantile)

# Create mesh
Expand Down
2 changes: 1 addition & 1 deletion brainrender/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ def screenshot(self, name=None, scale=None):
self.plotter.screenshot(filename=savepath, scale=scale)
return savepath

def keypress(self, key):
def keypress(self, key): # pragma: no cover
"""
Hanles key presses for interactive view
-s: take's a screenshot
Expand Down
8 changes: 5 additions & 3 deletions brainrender/scene.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def __init__(
def __str__(self):
return f"A `brainrender.scene.Scene` with {len(self.actors)} actors."

def __repr__(self):
def __repr__(self): # pragma: no cover
return f"A `brainrender.scene.Scene` with {len(self.actors)} actors."

def __del__(self):
Expand Down Expand Up @@ -262,7 +262,7 @@ def content(self):
f"[bold][{mocassin}]- {act.name}[/bold][{dimorange}] (type: [{orange}]{act.br_class}[/{orange}]) |[dim] is transformed: [blue]{act._is_transformed}"
)

if "win" not in sys.platform:
if "win32" != sys.platform:
actors.print()
else:
print(pi.utils.stringify(actors, maxlen=-1))
Expand All @@ -275,7 +275,9 @@ def renderables(self):
if not self.jupyter:
return [a.mesh for a in self.actors + self.labels]
else:
return list(set([a.mesh for a in self.actors if not a.is_text]))
return list(
set([a.mesh for a in self.actors if not a.is_text])
) # pragma: no cover

@property
def clean_actors(self):
Expand Down
Loading

0 comments on commit 83686d4

Please sign in to comment.