From eef044b5871619117d992be4f418dbf61a010114 Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 13 Feb 2020 11:30:41 -0700 Subject: [PATCH 01/29] add flake 8 --- .pre-commit-config.yaml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 21fb8d75..7c98033a 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,3 +4,8 @@ repos: hooks: - id: black language_version: python3.7 +- repo: https://gitlab.com/pycqa/flake8 + rev: 3.7.7 + hooks: + - id: flake8 + language: python_venv From 3a05d3a4bec81c0aea2bae0bb29c36f4ef8d9a76 Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 13 Feb 2020 11:43:50 -0700 Subject: [PATCH 02/29] yay cleanup --- matplotcheck/vector.py | 136 +++++++++++++++++++++++++---------------- tox.ini | 1 + 2 files changed, 84 insertions(+), 53 deletions(-) diff --git a/matplotcheck/vector.py b/matplotcheck/vector.py index 10610602..53974905 100644 --- a/matplotcheck/vector.py +++ b/matplotcheck/vector.py @@ -24,7 +24,8 @@ def __init__(self, ax): def assert_legend_no_overlay_content( self, m="Legend overlays plot contents" ): - """Asserts that each legend does not overlay plot contents with error message m + """Asserts that each legend does not overlay plot contents with error + message m Parameters --------- @@ -62,7 +63,8 @@ def _legends_overlap(self, b1, b2): return x_overlap and y_overlap def assert_no_legend_overlap(self, m="Legends overlap eachother"): - """Asserts there are no two legends in Axes ax that overlap each other with error message m + """Asserts there are no two legends in Axes ax that overlap each other + with error message m Parameters ---------- @@ -76,13 +78,14 @@ def assert_no_legend_overlap(self, m="Legends overlap eachother"): leg_extent2 = legends[j].get_window_extent().get_points() assert not self._legends_overlap(leg_extent1, leg_extent2), m - ### VECTOR DATA FUNCTIONS ### - ## MARKER POINTS ### + """ Check Data """ def _convert_length(self, arr, n): - """ helper function for 'get_points_by_attributes' and 'get_lines_by_attributes' + """ helper function for 'get_points_by_attributes' and + 'get_lines_by_attributes' takes an array of either length 1 or n. - If array is length 1: array of array's only element repeating n times is returned + If array is length 1: array of array's only element repeating n times + is returned If array is length n: original array is returned Else: function raises value error @@ -102,14 +105,11 @@ def _convert_length(self, arr, n): elif len(arr) == n: return arr else: - raise ValueError( - "Input array length is not of either expected values:1 or {0}".format( - n - ) - ) + raise ValueError("Input array length is not: 1 or {0}".format(n)) def get_points_by_attributes(self): - """Returns a sorted list of lists where each list contains tuples of xycoords for points of + """Returns a sorted list of lists where each list contains tuples of + xycoords for points of the same attributes: color, marker, and markersize Returns @@ -162,15 +162,18 @@ def get_points_by_attributes(self): def assert_points_grouped_by_type( self, data_exp, sort_column, m="Point attribtues not accurate by type" ): - """Asserts that the points on Axes ax display attributes based on their type with error message m + """Asserts that the points on Axes ax display attributes based on their + type with error message m attributes tested are: color, marker, and markersize Parameters ---------- data_exp: Geopandas Dataframe with Point objects in column 'geometry' - an additional column with title sort_column, denotes a category for each point + an additional column with title sort_column, denotes a category for + each point sort_column: string of column label in dataframe data_exp. - this column contains values expressing which points belong to which group + this column contains values expressing which points belong to which + group m: string error message if assertion is not met """ @@ -188,7 +191,8 @@ def sort_collection_by_markersize(self): Returns -------- - pandas dataframe with columns x, y, point_size. Each row reprsents a point on Axes ax with location x,y and markersize pointsize + pandas dataframe with columns x, y, point_size. Each row reprsents a + point on Axes ax with location x,y and markersize pointsize """ df = pd.DataFrame(columns=("x", "y", "markersize")) for c in self.ax.collections: @@ -212,12 +216,15 @@ def sort_collection_by_markersize(self): return df def assert_collection_sorted_by_markersize(self, df_expected, sort_column): - """Asserts a collection of points vary in size by column expresse din sort_column + """Asserts a collection of points vary in size by column expresse din + sort_column Parameters ---------- - df_expected: geopandas dataframe with geometry column of expected point locations - sort_column: column title from df_expected that points are expected to be sorted by + df_expected: geopandas dataframe with geometry column of expected point + locations + sort_column: column title from df_expected that points are expected to + be sorted by if None, assertion is passed """ df = self.sort_collection_by_markersize() @@ -237,23 +244,28 @@ def assert_collection_sorted_by_markersize(self, df_expected, sort_column): err_msg="Markersize not based on {0} values".format(sort_column), ) - ### LINES ### + """Check lines""" def _convert_multilines(self, df, column_title): """Helper function for get_lines_by_attribute - converts a pandas dataframe containing a column of LineString and MultiLinestring objects - to a pandas dataframe where each row represents a single line. Line segment values are converted + converts a pandas dataframe containing a column of LineString and + MultiLinestring objects + to a pandas dataframe where each row represents a single line. Line + segment values are converted to a list of tuples. Parameters --------- - df: pandas Dataframe containing a column of LineString and MultiLinestring objects - column_title: string of column title which holds LineString and MultLinestring objects + df: pandas Dataframe containing a column of LineString and + MultiLinestring objects + column_title: string of column title which holds LineString and + MultLinestring objects Returns ------- - Dataframe where each row repsrents a single line. - Line segments values are converted to a list of tuples in column column_title + Dataframe where each row represents a single line. + Line segments values are converted to a list of tuples in column + column_title """ dfout = df.copy() for i, row in dfout.iterrows(): @@ -268,13 +280,15 @@ def _convert_multilines(self, df, column_title): dfout = dfout.append(new_row).reset_index(drop=True) else: raise ValueError( - "Segment is not of either expected type: MultiLinestring, LineString" + "Segment is not of either expected type: MultiLinestring, " + "LineString" ) return dfout def _convert_linestyle(self, ls): """helper function for get_lines_by_attributes. - converts linestyle to a tuple of (offset, onoffseq) to get hashable datatypes + converts linestyle to a tuple of (offset, onoffseq) to get hashable + datatypes Parameters ---------- @@ -294,8 +308,9 @@ def get_lines(self): Returns ------- - output: DataFrame with column 'lines'. Each row represents one line segment. - Its value in 'lines' is a list of tuples representing the line segement. + output: DataFrame with column 'lines'. Each row represents one line + segment. Its value in 'lines' is a list of tuples representing the + line segment. """ lines = [ [tuple(coords) for coords in seg] @@ -306,11 +321,13 @@ def get_lines(self): return pd.DataFrame({"lines": lines}) def get_lines_by_collection(self): - """Returns a sorted list of list where each list contains line segments from the same collections + """Returns a sorted list of list where each list contains line segments + from the same collections Returns ------- - sorted list where each list represents all lines from the same collection + sorted list where each list represents all lines from the same + collection """ lines_grouped = [ [[tuple(coords) for coords in seg] for seg in c.get_segments()] @@ -320,12 +337,14 @@ def get_lines_by_collection(self): return sorted([sorted(l) for l in lines_grouped]) def get_lines_by_attributes(self): - """Returns a sorted list of lists where each list contains line segments of the same attributes: + """Returns a sorted list of lists where each list contains line + segments of the same attributes: color, linewidth, and linestyle Returns ------ - sorted list where each list represents all lines with the same attributes + sorted list where each list represents all lines with the same + attributes """ lines_dataframe = pd.DataFrame( columns=["seg", "color", "lwidth", "lstyle"] @@ -368,17 +387,19 @@ def get_lines_by_attributes(self): return sorted([sorted(l) for l in lines_grouped]) def assert_lines(self, lines_expected, m="Incorrect Line Data"): - """Asserts the line data in Axes ax is equal to lines_expected with error message m. + """Asserts the line data in Axes ax is equal to lines_expected with + error message m. If line_expected is None or an empty list, assertion is passed Parameters ---------- - lines_expected: Geopandas Dataframe with a geometry column consisting of MultilineString and LineString objects + lines_expected: Geopandas Dataframe with a geometry column consisting + of MultilineString and LineString objects m: string error message if assertion is not met """ if type(lines_expected) == gpd.geodataframe.GeoDataFrame: lines_expected = lines_expected[ - lines_expected["geometry"].is_empty == False + ~lines_expected["geometry"].is_empty ].reset_index(drop=True) fig, ax_exp = plt.subplots() lines_expected.plot(ax=ax_exp) @@ -400,19 +421,22 @@ def assert_lines_grouped_by_type( sort_column, m="Line attributes not accurate by type", ): - """Asserts that the lines on Axes ax display like attributes based on their type with error message m + """Asserts that the lines on Axes ax display like attributes based on + their type with error message m attributes tested are: color, linewidth, linestyle Parameters ---------- - lines_expected: Geopandas Dataframe with geometry column consisting of MultiLineString and LineString objects - sort_column: string of column title in lines_expected that contains types lines are expected to be grouped by + lines_expected: Geopandas Dataframe with geometry column consisting of + MultiLineString and LineString objects + sort_column: string of column title in lines_expected that contains + types lines are expected to be grouped by m: string error message if assertion is not met """ if type(lines_expected) == gpd.geodataframe.GeoDataFrame: groups = self.get_lines_by_attributes() lines_expected = lines_expected[ - lines_expected["geometry"].is_empty == False + ~lines_expected["geometry"].is_empty ].reset_index(drop=True) fig, ax_exp = plt.subplots() for typ, data in lines_expected.groupby(sort_column): @@ -432,14 +456,16 @@ def assert_lines_grouped_by_type( "lines_expected is not of expected type: GeoDataFrame" ) - ### POLYGONS ### + """ Check Polygons """ def get_polygons(self): - """Returns all polygons on Axes ax as a sorted list of polygons where each polygon is a list of coord tuples + """Returns all polygons on Axes ax as a sorted list of polygons where + each polygon is a list of coord tuples Returns ------- - output: sorted list of polygons. Each polygon is a list tuples. Ecah tuples is a coordinate. + output: sorted list of polygons. Each polygon is a list tuples. Each + tuple is a coordinate. """ output = [ [tuple(coords) for coords in path.vertices] @@ -451,7 +477,8 @@ def get_polygons(self): def _convert_multipolygons(self, series): """Helper function for assert_polygons - converts a pandas series of Polygon and MultiPolygon objects to a list of lines, + converts a pandas series of Polygon and MultiPolygon objects to a list + of lines, where each line is a list of coord tuples for the exterior Parameters @@ -460,7 +487,8 @@ def _convert_multipolygons(self, series): Returns ------- - list of lines where each line is a list of coord tuples for the exterior polygon + list of lines where each line is a list of coord tuples for the + exterior polygon """ output = [] for entry in series: @@ -474,25 +502,27 @@ def _convert_multipolygons(self, series): def assert_polygons( self, polygons_expected, dec=None, m="Incorrect Polygon Data" ): - """Asserts the polygon data in Axes ax is equal to polygons_expected to decimal place dec with error message m + """Asserts the polygon data in Axes ax is equal to polygons_expected to + decimal place dec with error message m If polygons_expected is am empty list or None, assertion is passed. Parameters ---------- polygons_expected : List or GeoDataFrame - List of polygons expected to be founds on Axes ax or a GeoDataFrame - containing the expected polygons. + List of polygons expected to be founds on Axes ax or a GeoDataFrame + containing the expected polygons. dec : int (Optional) - Int stating the desired decimal precision. If None, polygons must - be exact. + Int stating the desired decimal precision. If None, polygons must + be exact. m : string (default = "Incorrect Polygon Data") - String error message if assertion is not met. + String error message if assertion is not met. """ if len(polygons_expected) != 0: if isinstance(polygons_expected, list): if len(polygons_expected[0]) == 0: raise ValueError( - "Empty list or GeoDataFrame passed into assert_polygons." + "Empty list or GeoDataFrame passed into assert_" + "polygons." ) if isinstance(polygons_expected, gpd.geodataframe.GeoDataFrame): polygons_expected = self._convert_multipolygons( diff --git a/tox.ini b/tox.ini index e037d539..0190560e 100644 --- a/tox.ini +++ b/tox.ini @@ -22,6 +22,7 @@ deps = black basepython = python3 commands = black --check --verbose matplotcheck + flake8 matplotcheck [testenv:docs] whitelist_externals = make From 1e24b608943585df272e4e4a43f055bd36fab6c0 Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 13 Feb 2020 11:45:05 -0700 Subject: [PATCH 03/29] update change log --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index eca75ef4..d54d7224 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +* Adding flake8 for format and other syntax issues! yay! (@lwasser, #195) * Created a vignette covering the testing of histograms (@ryla5068, #149) * Created `get_plot_image()` function for the RasterTester object (@nkorinek, #192) * Allowed `assert_polygons()` to accept GeoDataFrames and added tests (@nkorinek, #175) From 202c7371836cfc713c92ffa55154813bb199c5ad Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 13 Feb 2020 12:05:55 -0700 Subject: [PATCH 04/29] add flake 8 dep --- tox.ini | 1 + 1 file changed, 1 insertion(+) diff --git a/tox.ini b/tox.ini index 0190560e..4a4951e6 100644 --- a/tox.ini +++ b/tox.ini @@ -20,6 +20,7 @@ commands = deps = pip>=19.0 black + flake8 basepython = python3 commands = black --check --verbose matplotcheck flake8 matplotcheck From e80cec7aba9aed47c4b84c3f169363818476e70a Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Thu, 13 Feb 2020 16:21:15 -0700 Subject: [PATCH 05/29] autograde flake8 fixes --- matplotcheck/autograde.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/matplotcheck/autograde.py b/matplotcheck/autograde.py index fe565e59..f2a5a3f5 100644 --- a/matplotcheck/autograde.py +++ b/matplotcheck/autograde.py @@ -41,10 +41,10 @@ def run_test( pass : bool : passing status of test function description : str : test function name that was run message : str : custom message returned based on passing status - traceback : AssertionError : returned from test function when pass is False + traceback : AssertionError : returned from test function when pass is + False """ results = {"points": 0, "pass": False} - score = 0 try: fname = func.__name__ results["description"] = fname @@ -72,7 +72,8 @@ def output_results(results): pass : bool : passing status of test function description : str : test function name that was run message : str : custom message returned based on passing status - traceback : AssertionError : returned from test function when pass is False + traceback : AssertionError : returned from test function when pass is + False Returns ------- From df21ddb9b800a682fabe7bb5de0be9bdcfdb9b9d Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Thu, 13 Feb 2020 16:49:54 -0700 Subject: [PATCH 06/29] Fixed base to be flake8 compliant (phew) --- matplotcheck/base.py | 116 ++++++++++++++++++++++++------------------- 1 file changed, 64 insertions(+), 52 deletions(-) diff --git a/matplotcheck/base.py b/matplotcheck/base.py index fe828643..9d48e550 100644 --- a/matplotcheck/base.py +++ b/matplotcheck/base.py @@ -109,15 +109,16 @@ def assert_string_contains( Similar to `message_default`, `message_or` is the error message to be displated if `string` does not contain at least one of the strings in an inner list in `strings_expected`. If `message` - contains ``'{0}'``, it will be replaced with the first failing inner - list in `strings_expected`. + contains ``'{0}'``, it will be replaced with the first failing + inner list in `strings_expected`. Raises ------- AssertionError if `string` does not contain expected strings """ - # Assertion passes if strings_expected == [] or strings_expected == None + # Assertion passes if strings_expected == [] or + # strings_expected == None if not strings_expected: return @@ -149,8 +150,8 @@ def assert_plot_type( String specifying the expected plot type. Options: `scatter`, `bar`, `line` message : string - The error message to be displayed if Plot does not match `plot_type`. If - `message` contains ``'{0}'``, it will be replaced + The error message to be displayed if Plot does not match + `plot_type`. If `message` contains ``'{0}'``, it will be replaced with the epected plot type. Raises @@ -219,18 +220,19 @@ def assert_title_contains( assertion. The combined title will be tested. message_default : string - The error message to be displayed if the axis label does not contain - a string in strings_expected. If `message` contains ``'{0}'``, it - will be replaced with the first expected string not found in the - label. + The error message to be displayed if the axis label does not + contain a string in strings_expected. If `message` contains + ``'{0}'``, it will be replaced with the first expected string not + found in the label. message_or : string Similar to `message_default`, `message_or` is the error message to be displated if the axis label does not contain at least one of the strings in an inner list in `strings_expected`. If `message` - contains ``'{0}'``, it will be replaced with the first failing inner - list in `strings_expected`. + contains ``'{0}'``, it will be replaced with the first failing + inner list in `strings_expected`. message_no_title : string - The error message to be displayed if the expected title is not displayed. + The error message to be displayed if the expected title is not + displayed. Raises ------- @@ -246,7 +248,8 @@ def assert_title_contains( title = axtitle else: raise ValueError( - 'title_type must be one of the following ["figure", "axes", "either"]' + 'title_type must be one of the following ' + + '["figure", "axes", "either"]' ) assert title, message_no_title @@ -268,7 +271,8 @@ def get_caption(self): Returns ------- caption : string - the text that is found in bottom right, ``None`` if no text is found + the text that is found in bottom right, ``None`` if no text is + found """ caption = None ax_position = self.ax.get_position() @@ -308,16 +312,16 @@ def assert_caption_contains( ``'a'`` AND ``'b'`` AND (at least one of: ``'c'``, ``'d'``) must be in the title for the assertion to pass. Case insensitive. message_default : string - The error message to be displayed if the axis label does not contain - a string in strings_expected. If `message` contains ``'{0}'``, it - will be replaced with the first expected string not found in the - label. + The error message to be displayed if the axis label does not + contain a string in strings_expected. If `message` contains + ``'{0}'``, it will be replaced with the first expected string + not found in the label. message_or : string Similar to `message_default`, `message_or` is the error message to be displated if the axis label does not contain at least one of the strings in an inner list in `strings_expected`. If `message` - contains ``'{0}'``, it will be replaced with the first failing inner - list in `strings_expected`. + contains ``'{0}'``, it will be replaced with the first failing + inner list in `strings_expected`. message_no_caption : string The error message to be displayed if no caption exists in the appropriate location. @@ -360,11 +364,11 @@ def assert_axis_off(self, message="Axis lines are displayed on plot"): """ flag = False # Case 1: check if axis have been turned off - if self.ax.axison == False: + if not self.ax.axison: flag = True # Case 2: Check if both axis visibilities set to false elif ( - self.ax.xaxis._visible == False and self.ax.yaxis._visible == False + not self.ax.xaxis._visible and not self.ax.yaxis._visible ): flag = True # Case 3: Check if both axis ticks are set to empty lists @@ -403,18 +407,18 @@ def assert_axis_label_contains( ``'a'`` AND ``'b'`` AND (at least one of: ``'c'``, ``'d'``) must be in the title for the assertion to pass. Case insensitive. message_default : string - The error message to be displayed if the axis label does not contain - a string in strings_expected. If `message` contains ``'{1}'``, it - will be replaced with `axis`. If `message` contains ``'{0}'``, it - will be replaced with the first expected string not found in the - label. + The error message to be displayed if the axis label does not + contain a string in strings_expected. If `message` contains + ``'{1}'``, it will be replaced with `axis`. If `message` contains + ``'{0}'``, it will be replaced with the first expected string not + found in the label. message_or : string Similar to `message_default`, `message_or` is the error message to be displated if the axis label does not contain at least one of the strings in an inner list in `strings_expected`. If `message` contains ``'{1}'``, it will be replaced with `axis`. If `message` - contains ``'{0}'``, it will be replaced with the first failing inner - list in `strings_expected`. + contains ``'{0}'``, it will be replaced with the first failing + inner list in `strings_expected`. message_not_displayed : string The error message to be displayed if the expected axis label is not displayed. If `message_not_displayed` contains ``'{0}'``, it will @@ -574,7 +578,8 @@ def assert_legend_titles( self, titles_exp, message="Legend title does not contain expected string: {0}", - message_num_titles="I was expecting {0} legend titles but instead found {1}", + message_num_titles="I was expecting {0} legend titles but instead " + + "found {1}", ): """Asserts legend titles contain expected text in titles_exp list. @@ -592,8 +597,8 @@ def assert_legend_titles( The error message to be displayed if there exist a different number of legend titles than expected. If `message_num_titles` contains ``'{0}'`` it will be replaced with the number of titles found. If - `message_num_titles` contains ``'{1}'`` it will be replaced with the - expected number of titles. + `message_num_titles` contains ``'{1}'`` it will be replaced with + the expected number of titles. Raises ------- @@ -625,7 +630,8 @@ def assert_legend_labels( labels_exp, message="Legend does not have expected labels", message_no_legend="Legend does not exist", - message_num_labels="I was expecting {0} legend entries, but found {1}. Are there extra labels in your legend?", + message_num_labels="I was expecting {0} legend entries, but found " + + "{1}. Are there extra labels in your legend?", ): """Asserts legends on ax have the correct entry labels @@ -643,8 +649,8 @@ def assert_legend_labels( The error message to be displayed if there exist a different number of legend labels than expected. If `message_num_labels` contains ``'{0}'`` it will be replaced with the number of labels found. If - `message_num_labels` contains ``'{1}'`` it will be replaced with the - expected number of labels. + `message_num_labels` contains ``'{1}'`` it will be replaced with + the expected number of labels. Raises @@ -751,7 +757,7 @@ def assert_no_legend_overlap(self, message="Legends overlap eachother"): legends[j].get_window_extent(RendererBase()).get_points() ) assert ( - self.legends_overlap(leg_extent1, leg_extent2) == False + not self.legends_overlap(leg_extent1, leg_extent2) ), message """ BASIC PLOT DATA FUNCTIONS """ @@ -765,9 +771,11 @@ def get_xy(self, points_only=False, xtime=False): ax : matplotlib.axes.Axes Matplotlib Axes object to be tested points_only : boolean - Set ``True`` to check only points, set ``False`` to check all data on plot. + Set ``True`` to check only points, set ``False`` to check all data + on plot. xtime : boolean - Set equal to True if the x axis of the plot contains datetime values + Set equal to True if the x axis of the plot contains datetime + values Returns ------- @@ -872,12 +880,13 @@ def assert_xydata( return elif not isinstance(xy_expected, pd.DataFrame): raise ValueError( - "xy_expected must be of type: pandas dataframe or Geopandas Dataframe" + "xy_expected must be of type: pandas dataframe or Geopandas " + + "Dataframe" ) # If xy_expected is a GeoDataFrame, then we make is a normal DataFrame - # with the coordinates of the geometry in that GeoDataFrame as the x and - # y data + # with the coordinates of the geometry in that GeoDataFrame as the x + # and y data if isinstance(xy_expected, gpd.geodataframe.GeoDataFrame) and not xcol: xy_expected = pd.DataFrame( data={ @@ -1018,7 +1027,7 @@ def assert_xlabel_ydata( except AssertionError: raise AssertionError(message) - ### LINE TESTS/HELPER FUNCTIONS ### + # LINE TESTS/HELPER FUNCTIONS def get_slope_yintercept(self, path_verts): """Returns the y-intercept of line based on the average slope of the @@ -1125,13 +1134,15 @@ def assert_lines_of_type(self, line_types): slope_exp, intercept_exp = 1, 0 else: raise ValueError( - 'each string in line_types must be from the following ["regression","onetoone"]' + 'each string in line_types must be from the following ' + + '["regression","onetoone"]' ) self.assert_line( slope_exp, intercept_exp, - message_no_line="{0} line is not displayed properly".format( + message_no_line="{0} line is not displayed properly".format + ( line_type ), message_data="{0} line does not cover dataset".format( @@ -1139,7 +1150,7 @@ def assert_lines_of_type(self, line_types): ), ) - ## HISTOGRAM FUNCTIONS ## + # HISTOGRAM FUNCTIONS def get_num_bins(self): """Gets the number of bins in histogram with a unique x-position. @@ -1149,8 +1160,9 @@ def get_num_bins(self): Int : Returns the number of bins with a unique x-position. For a normal histogram, this is just the number of bins. If there are two - overlapping or stacked histograms in the same `matplotlib.axis.Axis` - object, then this returns the number of bins with unique edges. """ + overlapping or stacked histograms in the same + `matplotlib.axis.Axis` object, then this returns the number of bins + with unique edges. """ x_data = self.get_xy(xtime=False)["x"] unique_x_data = list(set(x_data)) num_bins = len(unique_x_data) @@ -1170,9 +1182,9 @@ def assert_num_bins( Number of bins expected. message : string The error message to be displayed if plot does not contain - `num_bins`. If `message` contains ``'{0}'`` it will be replaced with - expected number of bins. If `message` contains ``'{1}'``, it will - be replaced with the number of bins found. + `num_bins`. If `message` contains ``'{0}'`` it will be replaced + with expected number of bins. If `message` contains ``'{1}'``, it + will be replaced with the number of bins found. Raises ------- @@ -1210,8 +1222,8 @@ def assert_bin_values( Parameters ---------- bin_values : list - A list of numbers representing the expected values of each consecutive - bin (i.e. the heights of the bars in the histogram). + A list of numbers representing the expected values of each + consecutive bin (i.e. the heights of the bars in the histogram). tolerence : float Measure of relative error allowed. For example: Given a tolerance ``tolerence=0.1``, an expected value From 07a74e3ab4757b755e9a3ee91cb67a4a4dfa5055 Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 13 Feb 2020 16:52:06 -0700 Subject: [PATCH 07/29] more line length issues --- matplotcheck/cases.py | 279 +++++++++++++++++++++++++++--------------- 1 file changed, 183 insertions(+), 96 deletions(-) diff --git a/matplotcheck/cases.py b/matplotcheck/cases.py index 58b78f19..c2370987 100644 --- a/matplotcheck/cases.py +++ b/matplotcheck/cases.py @@ -1,5 +1,3 @@ -## Adding levels of abstraction.. -# import all plottester and folium tester import unittest from .base import PlotTester from .timeseries import TimeSeriesTester @@ -28,29 +26,40 @@ class PlotBasicSuite(object): xcol: string column title in data_exp that contains xaxis data ycol: string column title in data_exp that contains yaxis data plot_type: string from list ["scatter","bar"] of expected plot type - line_types: list of strings. Acceptable strings in line_types are as follows ["regression", "onetoone"]. + line_types: list of strings. Acceptable strings in line_types are as + follows + ["regression", "onetoone"]. if list is empty, assert is passed xlabels: boolean if using x axis labels rather than x data lims_equal: boolean expressing if x and y limits are expected to be equal - title_contains: list of lower case strings where each string is expected to be in title, barring capitalization. - If value is an empty list: test is just to see that title exists and is not an empty string + title_contains: list of lower case strings where each string is expected to + be in title, barring capitalization. + If value is an empty list: test is just to see that title exists and is + not an empty string If value is None: no tests are run title_type: one of the following strings ["figure", "axes", "either"] "figure": only the figure title (suptitle) will be tested "axes": only the axes title (suptitle) will be tested - "either": either the figure title or axes title will pass this assertion. + "either": either the figure title or axes title will pass this + assertion. The combined title will be tested. - xlabel_contains: list of lower case strings where each string is expected to be in x-axis label, barring capitalization. - If value is an empty list: test is just to see that x-axis label exists and is not an empty string + xlabel_contains: list of lower case strings where each string is expected + to be in x-axis label, barring capitalization. + If value is an empty list: test is just to see that x-axis label exists + and is not an empty string If value is None: no tests are run - ylabel_contains: list of lower case strings where each string is expected to be in y-axis label, barring capitalization. - If value is an empty list: test is just to see that y-axis label exists and is not an empty string + ylabel_contains: list of lower case strings where each string is expected + to be in y-axis label, barring capitalization. + If value is an empty list: test is just to see that y-axis label exists + and is not an empty string If value is None: no tests are run - caption_string: list of lists. Each internal list is a list of lower case strings where at least one string must be + caption_string: list of lists. Each internal list is a list of lower case + strings where at least one string must be found in the caption, barring capitalization if empty list: asserts caption exists and not an empty string if None: no tests are run - legend_labels: list of lower case stings. Each string is an expected entry label in the legend, barring capitalization. + legend_labels: list of lower case stings. Each string is an expected entry + label in the legend, barring capitalization. """ def __init__( @@ -75,9 +84,12 @@ def __init__( ): class PlotLabelsTest(unittest.TestCase): """A unittest.TestCase containing 3 tests: - 1. title_exist: ax has a title that contains each string in list of strings title_contains, barring capitalization - 2. xlab_exist: ax has a x label that contains each string in list of strings xlabel_contains, barring capitalization - 3. ylab_exist: ax has a y label that that contains each string in list of strings ylabel_contains, barring capitalization + 1. title_exist: ax has a title that contains each string in list of + strings title_contains, barring capitalization + 2. xlab_exist: ax has a x label that contains each string in list + of strings xlabel_contains, barring capitalization + 3. ylab_exist: ax has a y label that that contains each string in + list of strings ylabel_contains, barring capitalization """ def setUp(self): @@ -106,8 +118,8 @@ def tearDown(self): class LegendTest(unittest.TestCase): """A unittest.TestCase containing 2 tests checking the legend(s): - 1. legend_labels: Asserts the legend has labels specified in labels_ - exp (barring capitalization), and only those labels + 1. legend_labels: Asserts the legend has labels specified in + labels_ exp (barring capitalization), and only those labels 2. legend_location: Asserts legend does not cover data and no legends overlap each other """ @@ -149,8 +161,10 @@ class PlotBasic(unittest.TestCase): """A unittest.TestCase containing 4 tests on Matplotlib Axes ax 1. data: asserts that the x and y data of ax matches data_exp 2. lines: asserts each of lines in line_types is displayed on ax - 3. plot_type: asserts plot is of expected type expressed by plot_type - 4. lims: asserts the x and y limits are equal if boolean lims_equal expresses it should be + 3. plot_type: asserts plot is of expected type expressed by + plot_type + 4. lims: asserts the x and y limits are equal if boolean + lims_equal expresses it should be """ def setUp(self): @@ -196,12 +210,16 @@ def tearDown(self): @property def cases(self): - """Returns a list of TestCases to be run in a TestLoader for basic 2d plots (scatter, bar, line, etc.). + """Returns a list of TestCases to be run in a TestLoader for basic 2d + plots (scatter, bar, line, etc.). Testcases are as follows: - 1. LabelsCase: Asserts the title, x-axis label, and y-axis label are as expected - 2. BasicCase: Asserts data matches data_exp, and other assertions based on params listed below - For more on tests, see init method above. For more on assertions, see the autograde package. + 1. LabelsCase: Asserts the title, x-axis label, and y-axis label are + as expected + 2. BasicCase: Asserts data matches data_exp, and other assertions + based on params listed below + For more on tests, see init method above. For more on assertions, + see the autograde package. """ return [self.LabelsCase, self.BasicCase] @@ -237,8 +255,8 @@ class PlotHistogramSuite(PlotBasicSuite): If value is an empty list: test is just to see that title exists and is not an empty string If value is None: asserts no title - xlabel_contains: list of lower case strings where each string is expected to - be in x-axis label, barring capitalization. + xlabel_contains: list of lower case strings where each string is expected + to be in x-axis label, barring capitalization. If value is an empty list: test is just to see that x-axis label exists and is not an empty string If value is None: asserts no label is expressed @@ -269,11 +287,16 @@ def __init__( class PlotHistogram(unittest.TestCase): """A unittest.TestCase containing 4 tests for a histogram: - Test 1 - num_neg_bins: number of bins centered at a negative value is greater than n_bins[0] - Test 2- num_pos_bins: number of bins centered at a positive value is greater than n_bins[1] - Test 3 - x-lims: x-axis left limits are within the bounds [xlims[0][0], xlims[0][1]] and - x-axis right limits are within the bounds [xlims[1][0], xlims[1][1]] - Test 4 - y_lims: y-axis bottom limits are within the bounds [ylims[0][0], ylims[0][1]] and + Test 1 - num_neg_bins: number of bins centered at a negative + value is greater than n_bins[0] + Test 2- num_pos_bins: number of bins centered at a positive value + is greater than n_bins[1] + Test 3 - x-lims: x-axis left limits are within the bounds [xlims[ + 0][0], xlims[0][1]] and + x-axis right limits are within the bounds [xlims[1][0], + xlims[1][1]] + Test 4 - y_lims: y-axis bottom limits are within the bounds [ + ylims[0][0], ylims[0][1]] and y-axis top limits are within the bounds [ylims[1][0], ylims[1][1]] """ @@ -308,15 +331,18 @@ def tearDown(self): @property def cases(self): """Returns list of cases for a histogram. Testcases are as follows: - 1. LabelsCase: Asserts the title, x-axis label, and y-axis label are as expected - 2. HistogramCase: number of negative and positive bins as declares in n_bins. x axis limits and y axis limits + 1. LabelsCase: Asserts the title, x-axis label, and y-axis label are + as expected + 2. HistogramCase: number of negative and positive bins as declares in + n_bins. x axis limits and y axis limits are in range declared by xlims and y lims. - For more on tests, see init method above. For more on assertions, see the autograde package. + For more on tests, see init method above. For more on assertions, + see the autograde package. """ return [self.LabelsCase, self.HistogramCase] -### TIME SERIES PLOT ### +""" TIME SERIES PLOTS """ class PlotTimeSeriesSuite(PlotBasicSuite): @@ -329,21 +355,29 @@ class PlotTimeSeriesSuite(PlotBasicSuite): x_col: string column title in data_exp that contains xaxis data y_col: string column title in data_exp that contains yaxis data no_data_val: float representing no data, as stated by the input data - major_locator_exp: one of the following ['decade', 'year', 'month', 'week', 'day', None] + major_locator_exp: one of the following ['decade', 'year', 'month', + 'week', 'day', None] decade: if tick should be shown every ten years year: if tick should be shown every new year month: if tick should be shown every new month week: if tick should be shown every new week day: if tick should be shown every new day - minor_locator_exp: one of the following ['decade', 'year', 'month', 'week', 'day', None], as expressed above - title_contains: list of lower case strings where each string is expected to be in title, barring capitalization. - If value is an empty list: test is just to see that title exists and is not an empty string + minor_locator_exp: one of the following ['decade', 'year', 'month', + 'week', 'day', None], as expressed above + title_contains: list of lower case strings where each string is expected + to be in title, barring capitalization. + If value is an empty list: test is just to see that title exists and + is not an empty string If value is None: asserts no title - xlabel_contains: list of lower case strings where each string is expected to be in x-axis label, barring capitalization. - If value is an empty list: test is just to see that x-axis label exists and is not an empty string + xlabel_contains: list of lower case strings where each string is expected + to be in x-axis label, barring capitalization. + If value is an empty list: test is just to see that x-axis label + exists and is not an empty string If value is None: asserts no label is expressed - ylabel_contains: list of lower case strings where each string is expected to be in y-axis label, barring capitalization. - If value is an empty list: test is just to see that y-axis label exists and is not an empty string + ylabel_contains: list of lower case strings where each string is expected + to be in y-axis label, barring capitalization. + If value is an empty list: test is just to see that y-axis label + exists and is not an empty string If value is None: asserts no label is expressed """ @@ -372,10 +406,14 @@ def __init__( ) class PlotTicksReformat(unittest.TestCase): - """A unittest.TestCase containing 3 tests checking the xaxis ticks and labels: - 1. x_major_formatter: large ticks on x axis have been reformatted as expressed in major_locator_exp - 2. x_major_locs: large ticks on x axis are located as expressed in major_locator_exp - 3. x_minor_locs: small ticks on x axis are located as expressed in minor_locator_exp + """A unittest.TestCase containing 3 tests checking the xaxis + ticks and labels: + 1. x_major_formatter: large ticks on x axis have been reformatted + as expressed in major_locator_exp + 2. x_major_locs: large ticks on x axis are located as expressed + in major_locator_exp + 3. x_minor_locs: small ticks on x axis are located as expressed + in minor_locator_exp """ def setUp(self): @@ -443,47 +481,65 @@ def tearDown(self): def cases(self): """ Returns a list of TestCases for time series plots. Testcase are as follows: - 1. LabelsCase: Asserts the title, x-axis label, and y-axis label are as expected - 2. TickReformatCase: Asserts x-axis ticks have large ticks as express in major_locator_exp and small + 1. LabelsCase: Asserts the title, x-axis label, and y-axis label are + as expected + 2. TickReformatCase: Asserts x-axis ticks have large ticks as express + in major_locator_exp and small ticks as express in minor_locator_exp - 3. TimeSeriesCase: Asserts data matches data_exp and is converted to time objects - For more on tests, see init method above. For more on assertions, see the autograde package. + 3. TimeSeriesCase: Asserts data matches data_exp and is converted to + time objects + For more on tests, see init method above. For more on assertions, + see the autograde package. """ return [self.LabelsCase, self.TickReformatCase, self.TimeSeriesCase] -### VECTOR PLOT ### +""" VECTOR PLOTS """ class PlotVectorSuite(PlotBasicSuite): - """A PlotBasicSuite object to test a Matplotlib plot with spatial vector data. + """A PlotBasicSuite object to test a Matplotlib plot with spatial vector + data. Parameters --------- ax: Matplotlib Axes to be tested - caption_strings: list of lists. Each internal list is a list of lower case strings where at least one string must be + caption_strings: list of lists. Each internal list is a list of lower + case strings where at least one string must be found in the caption, barring capitalization if None: assert caption does not exist if empty list: asserts caption exists and not an empty string - legend_labels: list of lower case stings. Each string is an expected entry label in the legend. + legend_labels: list of lower case stings. Each string is an expected + entry label in the legend. title_type: one of the following strings ["figure", "axes", "either"] "figure": only the figure title (suptitle) will be tested "axes": only the axes title (suptitle) will be tested - "either": either the figure title or axes title will pass this assertion. + "either": either the figure title or axes title will pass this + assertion. The combined title will be tested. - title_contains: list of lower case strings where each string is expected to be in title, barring capitalization. - If value is an empty list: test is just to see that title exists and is not an empty string + title_contains: list of lower case strings where each string is expected + to be in title, barring capitalization. + If value is an empty list: test is just to see that title exists and + is not an empty string If value is None: asserts no title - markers: Geopandas dataframe with geometry column containing expected Point objects - lines: Geopandas dataframe with geometry column containing expected LineString and MultiLineString objects - polygons: list of lines where each line is a list of coord tuples for the exterior polygon - markers_groupby: column title from markers_exp that points are expected to be grouped by/contain - like attributes. Attributes tested are: marker type, markersize, and color + markers: Geopandas dataframe with geometry column containing expected + Point objects + lines: Geopandas dataframe with geometry column containing expected + LineString and MultiLineString objects + polygons: list of lines where each line is a list of coord tuples for the + exterior polygon + markers_groupby: column title from markers_exp that points are expected + to be grouped by/contain + like attributes. Attributes tested are: marker type, markersize, + and color if None, assertion is passed - lines_groupby: column title from line_exp that lines are expected to be grouped by/contain - like attributes. Attributes tested are: line style, line width, and color + lines_groupby: column title from line_exp that lines are expected to be + grouped by/contain + like attributes. Attributes tested are: line style, line width, + and color if None, assertion is passed - markers_by_size: column title from markers_exp that points are expected to be sorted by + markers_by_size: column title from markers_exp that points are expected + to be sorted by if None, assertion is passed """ @@ -515,10 +571,13 @@ def __init__( class PlotVector(unittest.TestCase): """A unittest.TestCase containing tests for a spatial vector plot. 1. marker_location: points on ax match markers - 2. markers_by_size: asserts points on ax vary in size by column expressed in markers_by_size - 3. markers_grouped: asserts markers of the same group contain like attributes + 2. markers_by_size: asserts points on ax vary in size by column + expressed in markers_by_size + 3. markers_grouped: asserts markers of the same group contain + like attributes 4. lines_location: lines on ax match lines - 5. lines_grouped: asserts lines of the same group contain like attributes + 5. lines_grouped: asserts lines of the same group contain like + attributes 6. polygons_location: polygons on ax match polygons """ @@ -576,11 +635,16 @@ def tearDown(self): def cases(self): """ Returns a list of TestCases for spatial vector plots. Testcase are as follows: - 1. CaptionCase: assert caption is in appropriate location with strings expressed in caption_contains - 2. LabelsCase: asserts the title contains strings in title_contains, and x and y labels are empty - 3. LegendCase: assert legend(s) is/are in appropriate location with legend_labels - 4. VectorCase: assert vector data is as expected in markers, lines, and polygons - For more on tests, see init method above. For more on assertions, see the autograde package. + 1. CaptionCase: assert caption is in appropriate location with + strings expressed in caption_contains + 2. LabelsCase: asserts the title contains strings in title_contains, + and x and y labels are empty + 3. LegendCase: assert legend(s) is/are in appropriate location with + legend_labels + 4. VectorCase: assert vector data is as expected in markers, lines, + and polygons + For more on tests, see init method above. For more on assertions, + see the autograde package. """ return [ self.CaptionCase, @@ -590,7 +654,7 @@ def cases(self): ] -### RASTER PLOT ### +""" RASTER PLOT """ class PlotRasterSuite(PlotVectorSuite): @@ -600,27 +664,39 @@ class PlotRasterSuite(PlotVectorSuite): --------- ax: Matplotlib Axes to be tested im_expected: array containing values of an expected image - caption_strings: list of lists. Each internal list is a list of strings where at least one string must be + caption_strings: list of lists. Each internal list is a list of strings + where at least one string must be found in the caption, barring capitalization if empty list: asserts caption exists and not an empty string if None: assertion is passed im_classified: boolean if image on ax is classfied - legend_labels: list of lists. Each internal list represents a classification category. - Said list is a list of strings where at least one string is expected to be in the legend label for this category. + legend_labels: list of lists. Each internal list represents a + classification category. + Said list is a list of strings where at least one string is expected + to be in the legend label for this category. Internal lists must be in the same order as bins in im_expected. - title_type: one of the following strings ["figure", "axes", "either"], stating which title to test + title_type: one of the following strings ["figure", "axes", "either"], + stating which title to test title_contains: list of strings expected to be in title - markers: Geopandas dataframe with geometry column containing expected Point objects - markers_by_size: column title from markers_exp that points are expected to be sorted by + markers: Geopandas dataframe with geometry column containing expected + Point objects + markers_by_size: column title from markers_exp that points are expected + to be sorted by if None, assertion is passed - markers_groupby: column title from markers_exp that points are expected to be grouped by/contain - like attributes. Attributes tested are: marker type, markersize, and color + markers_groupby: column title from markers_exp that points are expected + to be grouped by/contain + like attributes. Attributes tested are: marker type, markersize, + and color if None, assertion is passed - lines: Geopandas dataframe with geometry column containing expected LineString and MultiLineString objects - lines_groupby: column title from line_exp that lines are expected to be grouped by/contain - like attributes. Attributes tested are: line style, line width, and color + lines: Geopandas dataframe with geometry column containing expected + LineString and MultiLineString objects + lines_groupby: column title from line_exp that lines are expected to be + grouped by/contain + like attributes. Attributes tested are: line style, line width, + and color if None, assertion is passed - polygons: list of lines where each line is a list of coord tuples for the exterior polygon + polygons: list of lines where each line is a list of coord tuples for the + exterior polygon colorbar_range: tuple of (min, max) for colorbar. If empty tuple: asserts a colorbar exists, but does not check values If None: assertion is passed @@ -660,12 +736,15 @@ def __init__( class PlotRaster(unittest.TestCase): """A unittest.TestCase containing tests for a spatial raster plot. - 1. image_data: asserts image is as expected. If Image is classified image classification may be shifted or reversed. + 1. image_data: asserts image is as expected. If Image is + classified image classification may be shifted or reversed. 2. image_stretch: asserts image takes up entire display as expected 3. image_mask: - 4. legend_accuracy: if image is classified, asserts legend exists and correctly describes image. + 4. legend_accuracy: if image is classified, asserts legend exists + and correctly describes image. if image is not classified, assertion is passed. - 5. colorbar_accuracy: asserts colorbar exists and has range descrbied in colorbar_range + 5. colorbar_accuracy: asserts colorbar exists and has range + descrbied in colorbar_range 6. axis_off: axis lines are not displayed """ @@ -710,9 +789,12 @@ def tearDown(self): def cases(self): """ Returns a list of TestCases for spatial raster plots. Testcase are as follows: - 1. CaptionCase: assert caption is in appropriate location with strings expressed in caption_strings - 2. LabelsCase: asserts the title contains strings in title_contains, and x and y labels are empty - 3. RasterCase: asserts raster image matches im_expected and legend is correct if image is classified + 1. CaptionCase: assert caption is in appropriate location with + strings expressed in caption_strings + 2. LabelsCase: asserts the title contains strings in title_contains, + and x and y labels are empty + 3. RasterCase: asserts raster image matches im_expected and legend is + correct if image is classified 4. VectorCase: assert vector data is as expected """ return [ @@ -723,21 +805,25 @@ def cases(self): ] -#### FOLIUM ### +""" FOLIUM """ + + class PlotFoliumSuite(object): """A generic object to test Folium Maps. Parameters --------- fmap: folium map to be tested - markers: set of tuples where each tuple represents the x and y coord of an expected marker + markers: set of tuples where each tuple represents the x and y coord of + an expected marker """ def __init__(self, fmap, markers): class MapFolium(unittest.TestCase): """Returns a unittest.TestCase containing 2 tests on a Folium map. 1. map_folium: map is of type folium.folium.Map - 2. marker_locs: map contains all markers in markers_exp and no additional markers + 2. marker_locs: map contains all markers in markers_exp and no + additional markers """ def setUp(self): @@ -759,7 +845,8 @@ def tearDown(self): def cases(self): """ Returns a TestSuite for Folium Maps. Testcase are as follows: - 1. FoliumCase: asserts map is of type folium.map and contains expected markers + 1. FoliumCase: asserts map is of type folium.map and contains + expected markers """ return [self.FoliumCase] From 2c3827bfe8f4e81205620a89e04611a3567df765 Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Thu, 13 Feb 2020 16:52:23 -0700 Subject: [PATCH 08/29] Made folium.py flake8 compliant --- matplotcheck/folium.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/matplotcheck/folium.py b/matplotcheck/folium.py index b1ab9e10..27e9a302 100644 --- a/matplotcheck/folium.py +++ b/matplotcheck/folium.py @@ -1,9 +1,8 @@ -import numpy as np import folium class FoliumTester(object): - """object to test Folium plots + """Object to test Folium plots Parameters ---------- @@ -16,18 +15,25 @@ def __init__(self, fmap): self.fmap = fmap def assert_map_type_folium(self): - """Asserts fmap is of type folium.folium.Map""" + """ + Asserts fmap is of type folium.folium.Map + """ assert type(self.fmap) == folium.folium.Map def assert_folium_marker_locs( self, markers, m="Markers not shown in appropriate location" ): - """Asserts folium contains markers with locations described in markers_exp and only those markers, with error message m + """ + Asserts folium contains markers with locations described in + markers_exp and only those markers, with error message m Parameters ---------- - markers: set of tuples where each tuple represents the x and y coord of an expected marker - m: string error message if assertion is not met + markers: tuples + Set of tuples where each tuple represents the x and y coord of + an expected marker. + m: string + Error message if assertion is not met. """ marker_locs = set() while self.fmap._children: From 5480112597da39fdbf6f785a1f52f37b705a300a Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Thu, 13 Feb 2020 17:00:12 -0700 Subject: [PATCH 09/29] made notebook.py flake8 compliant --- matplotcheck/notebook.py | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/matplotcheck/notebook.py b/matplotcheck/notebook.py index 00716017..efc31a7e 100644 --- a/matplotcheck/notebook.py +++ b/matplotcheck/notebook.py @@ -8,12 +8,16 @@ def convert_axes(plt, which_axes="current"): Parameters --------- - plt: Matplotlib plot to be tested - which_axes: string from the following list ['current', 'last', 'first', 'all'] stating which axes we are saving for testing + plt: matplotlib plot + Matplotlib plot to be tested. + which_axes: string + String from the following list ['current', 'last', 'first', 'all'] + stating which axes we are saving for testing. Returns ------- - ax: Matplotlib axes or list of axes as express by which_axes + ax: Matplotlib axes or list + Matplotlib axes or list of axes as express by which_axes """ fig = plt.gcf() if which_axes == "current": @@ -26,12 +30,13 @@ def convert_axes(plt, which_axes="current"): ax = fig.axes else: raise ValueError( - 'which_axes must be one of the following strings ["current", "last", "first", "all"]' + 'which_axes must be one of the following strings ' + + '["current", "last", "first", "all"]' ) return ax -### JUPYTER NOTEBOOK TEST HELPER FUNCTIONS! ### +# JUPYTER NOTEBOOK TEST HELPER FUNCTIONS! def error_test(n, n_exp): @@ -39,8 +44,10 @@ def error_test(n, n_exp): Parameters ---------- - n: int of number of cells that that did not produce an error - n_exp: int of number of cell that are checked if producing an error + n: int + Number of cells that that did not produce an error. + n_exp: int + Number of cell that are checked if producing an error. Returns ------- @@ -61,22 +68,29 @@ def remove_comments(input_string): Parameters ---------- input_string: string + String to be modified. Returns ------- - string where all parts commented out by a '#' are removed from input_string + string + Sting where all parts commented out by a '#' are removed from + input_string. """ split_lines = input_string.split("\n") return "".join([line.split("#")[0] for line in split_lines]) def import_test(var_dict, n): - """Tests no import statements are found after the first cell in a Jupyter Notebook + """ + Tests no import statements are found after the first cell in a Jupyter + Notebook Parameters ---------- - vars_dict: dictionary produced by 'locals()' in notebook - n: number of cells to be tested for import statement in Jupyter Notebook + vars_dict: dictionary + Dictionary produced by 'locals()' in notebook. + n: int + number of cells to be tested for import statement in Jupyter Notebook Returns ------- From 8c26fe720d38d844ad0db437bccb4a9a29624d59 Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Thu, 13 Feb 2020 17:02:35 -0700 Subject: [PATCH 10/29] Fixed raster.py for flake8 --- matplotcheck/raster.py | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/matplotcheck/raster.py b/matplotcheck/raster.py index 4f62a8ce..822daea2 100644 --- a/matplotcheck/raster.py +++ b/matplotcheck/raster.py @@ -1,6 +1,4 @@ import numpy as np - -from .base import PlotTester from .vector import VectorTester @@ -95,9 +93,9 @@ def assert_legend_accuracy_classified_image( all_label_options: list of lists Each internal list represents a class and said list is a list of strings where at least one string is expected to be in the legend - label for this category. Internal lists must be in the same order as - bins in im_expected, e.g. first internal list has the expected label - options for class 0. + label for this category. Internal lists must be in the same order + as bins in im_expected, e.g. first internal list has the expected + label options for class 0. Returns ---------- @@ -107,13 +105,13 @@ def assert_legend_accuracy_classified_image( Notes ---------- First compares all_label_options against the legend labels to find - which element of all_label_options matches that entry. E.g. if the first - legend entry has a match in the first list in all_label_options, then - that legend entry corresponds to the first class (value 0). - Then the plot image array is copied and the values are set to the legend - label that match the values (i.e. the element in all_label_options). - The same is done for the expected image array. Finally those two arrays - of strings are compared. Passes if they match. + which element of all_label_options matches that entry. E.g. if the + first legend entry has a match in the first list in all_label_options, + then that legend entry corresponds to the first class (value 0). + Then the plot image array is copied and the values are set to the + legend label that match the values (i.e. the element in + all_label_options). The same is done for the expected image array. + Finally those two arrays of strings are compared. Passes if they match. """ # Retrieve image array im_data = [] @@ -162,7 +160,7 @@ def assert_legend_accuracy_classified_image( im_data_labels, im_expected_labels ), "Incorrect legend to data relation" - ### IMAGE TESTS/HELPER FUNCTIONS ### + # IMAGE TESTS/HELPER FUNCTIONS def get_plot_image(self): """Returns images stored on the Axes object as a list of numpy arrays. From 5597f2d145e96a1bcfa82c436212e7de27d1915d Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Thu, 13 Feb 2020 17:17:07 -0700 Subject: [PATCH 11/29] Fixed timeseries.py --- matplotcheck/timeseries.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/matplotcheck/timeseries.py b/matplotcheck/timeseries.py index 7923aaeb..b7a4ffdc 100644 --- a/matplotcheck/timeseries.py +++ b/matplotcheck/timeseries.py @@ -40,8 +40,10 @@ def assert_xticks_reformatted( 'month': if tick should be shown every new month 'week': if tick should be shown every new week 'day': if tick should be shown every new day - None: if no tick format has been specified. This will automatically assert True - m: string error message if assertion is not met + None: if no tick format has been specified. This will automatically + assert True + m: string + string error message if assertion is not met """ if loc_exp: if tick_size == "large": @@ -60,7 +62,8 @@ def assert_xticks_reformatted( ) # September 30, 2013 else: raise ValueError( - "tick_size must be on of the following string ['large', 'small']" + "tick_size must be on of the following string " + + "['large', 'small']" ) if loc_exp == "decade" or loc_exp == "year": accepted_responses = ["2013"] @@ -70,7 +73,7 @@ def assert_xticks_reformatted( accepted_responses = ["sep30", "september30"] else: raise ValueError( - """loc_exp must be one of the following strings ['decade', + """loc_exp must be one of the following strings ['decade', 'year', 'month', 'week', 'day', None]""" ) assert test_date in accepted_responses, m @@ -107,7 +110,7 @@ def assert_xticks_locs( ticks = self.ax.xaxis.get_minorticklocs() else: raise ValueError( - """"Tick_size must be one of the following strings + """"Tick_size must be one of the following strings ['large', 'small']""" ) @@ -123,7 +126,7 @@ def assert_xticks_locs( inc = relativedelta(days=1) else: raise ValueError( - """"loc_exp must be one of the following strings ['decade', + """"loc_exp must be one of the following strings ['decade', 'year', 'month', 'week', 'day'] or None""" ) @@ -162,16 +165,18 @@ def assert_no_data_value(self, nodata=999.99): xtime: boolean does the x-axis contains datetime values? """ - if nodata != None: + if nodata: xy = self.get_xy(xtime=False) assert ~np.isin( nodata, xy["x"] - ), "Values of {0} have been found in data. Be sure to remove no data values".format( + ), "Values of {0} have been found in data. Be sure to remove no " + + "data values".format( nodata ) assert ~np.isin( nodata, xy["y"] - ), "Values of {0} have been found in data. Be sure to remove no data values".format( + ), "Values of {0} have been found in data. Be sure to remove no " + + "data values".format( nodata ) From d255a557b5a9c5871a9db58d977bfb4e5cf2fae9 Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Thu, 13 Feb 2020 17:30:16 -0700 Subject: [PATCH 12/29] fixed conftest.py --- matplotcheck/tests/conftest.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/matplotcheck/tests/conftest.py b/matplotcheck/tests/conftest.py index 278b3380..0de7100f 100644 --- a/matplotcheck/tests/conftest.py +++ b/matplotcheck/tests/conftest.py @@ -71,7 +71,8 @@ def basic_polygon_gdf(basic_polygon): @pytest.fixture def pd_xlabels(): """Create a DataFrame which uses the column labels as x-data.""" - df = pd.DataFrame({"B": bp.random.randint(0, 100, size=100)}) + df = pd.DataFrame({"B": np.random.randint(0, 100, size=100)}) + return df @pytest.fixture From a7b7f803eb0828a9371e9c69c0f0f4c1f77dd441 Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Thu, 13 Feb 2020 17:35:32 -0700 Subject: [PATCH 13/29] fixed test_base.py --- matplotcheck/tests/test_base.py | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/matplotcheck/tests/test_base.py b/matplotcheck/tests/test_base.py index f9f5999b..c099c4aa 100644 --- a/matplotcheck/tests/test_base.py +++ b/matplotcheck/tests/test_base.py @@ -44,8 +44,8 @@ def test_options(pt_line_plt): provided.""" with pytest.raises( - ValueError, - match="Plot_type to test must be either: scatter, bar or line", + ValueError, + match="Plot_type to test must be either: scatter, bar or line", ): pt_line_plt.assert_plot_type("foo") plt.close() @@ -55,7 +55,8 @@ def test_options(pt_line_plt): def test_assert_string_contains(pt_line_plt): - """Tests that assert_string_contains passes with correct expected strings.""" + """Tests that assert_string_contains passes with correct expected + strings.""" test_string = "this is a test string" string_expected = ["this", "is", "a", "test"] pt_line_plt.assert_string_contains(test_string, string_expected) @@ -63,18 +64,21 @@ def test_assert_string_contains(pt_line_plt): def test_assert_string_contains_fails(pt_line_plt): - """Tests that assert_string_contains fails with incorrect expected strings.""" + """Tests that assert_string_contains fails with incorrect expected + strings.""" test_string = "this is a test string" string_expected = ["this", "is", "not", "a", "test"] with pytest.raises( - AssertionError, match="String does not contain expected string: not" + AssertionError, + match="String does not contain expected string: not" ): pt_line_plt.assert_string_contains(test_string, string_expected) plt.close() def test_assert_string_contains_or(pt_line_plt): - """Tests that assert_string_contains correctly passes when using OR logic.""" + """Tests that assert_string_contains correctly passes when using OR + logic.""" test_string = "this is a test string" string_expected = ["this", ["is", "not"], "a", "test"] pt_line_plt.assert_string_contains(test_string, string_expected) @@ -82,11 +86,12 @@ def test_assert_string_contains_or(pt_line_plt): def test_assert_string_contains_or_fails(pt_line_plt): - """Tests that assert_string_contains correctly fails when using OR logic.""" + """Tests that assert_string_contains correctly fails when using OR + logic.""" test_string = "this is a test string" string_expected = ["this", "is", ["not", "jambalaya"], "a", "test"] with pytest.raises( - AssertionError, match="String does not contain at least one of: " + AssertionError, match="String does not contain at least one of: " ): pt_line_plt.assert_string_contains(test_string, string_expected) plt.close() @@ -107,14 +112,16 @@ def test_assert_string_contains_handles_short_list_fails(pt_line_plt): test_string = "this is a test string" string_expected = [["this"], ["is"], ["not"]] with pytest.raises( - AssertionError, match="String does not contain expected string: not" + AssertionError, + match="String does not contain expected string: not" ): pt_line_plt.assert_string_contains(test_string, string_expected) plt.close() def test_assert_string_contains_passes_with_none(pt_line_plt): - """Tests that assert_string_contains passes when strings_expected is None""" + """Tests that assert_string_contains passes when strings_expected is + None""" test_string = "this is a test string" string_expected = None pt_line_plt.assert_string_contains(test_string, string_expected) @@ -122,7 +129,8 @@ def test_assert_string_contains_passes_with_none(pt_line_plt): def test_assert_string_contains_passes_with_empty(pt_line_plt): - """Tests that assert_string_contains passes when strings_expected is empty""" + """Tests that assert_string_contains passes when strings_expected is + empty""" test_string = "this is a test string" string_expected = [] pt_line_plt.assert_string_contains(test_string, string_expected) From 3c242d17435a9920e682d55b8559cc9734640616 Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Thu, 13 Feb 2020 17:36:30 -0700 Subject: [PATCH 14/29] fixed test_base_axis.py --- matplotcheck/tests/test_base_axis.py | 37 ++++++++++++++-------------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/matplotcheck/tests/test_base_axis.py b/matplotcheck/tests/test_base_axis.py index 83baddbe..3e353c39 100644 --- a/matplotcheck/tests/test_base_axis.py +++ b/matplotcheck/tests/test_base_axis.py @@ -2,7 +2,6 @@ import pytest import matplotlib.pyplot as plt - """ AXIS TESTS """ @@ -10,7 +9,7 @@ def test_axis_off_fail_on(pt_line_plt): """Check assert_axis_off fails when axis lines are on""" # Should fail when axis are on (by default) with pytest.raises( - AssertionError, match="Axis lines are displayed on plot" + AssertionError, match="Axis lines are displayed on plot" ): pt_line_plt.assert_axis_off() plt.close() @@ -38,21 +37,22 @@ def test_axis_off_one_visible(pt_line_plt): pt_line_plt.ax.xaxis.set_visible(True) pt_line_plt.ax.yaxis.set_visible(False) with pytest.raises( - AssertionError, match="Axis lines are displayed on plot" + AssertionError, match="Axis lines are displayed on plot" ): pt_line_plt.assert_axis_off() pt_line_plt.ax.xaxis.set_visible(False) pt_line_plt.ax.yaxis.set_visible(True) with pytest.raises( - AssertionError, match="Axis lines are displayed on plot" + AssertionError, match="Axis lines are displayed on plot" ): pt_line_plt.assert_axis_off() plt.close() def test_axis_off_empty_ticks(pt_line_plt): - """Check assert_axis_off for case when axis tick labels set to empty lists""" + """Check assert_axis_off for case when axis tick labels set to empty + lists""" pt_line_plt.ax.xaxis.set_ticks([]) pt_line_plt.ax.yaxis.set_ticks([]) pt_line_plt.assert_axis_off() @@ -65,14 +65,14 @@ def test_axis_off_non_empty_ticks(pt_line_plt): pt_line_plt.ax.xaxis.set_ticks([1]) pt_line_plt.ax.yaxis.set_ticks([]) with pytest.raises( - AssertionError, match="Axis lines are displayed on plot" + AssertionError, match="Axis lines are displayed on plot" ): pt_line_plt.assert_axis_off() pt_line_plt.ax.xaxis.set_ticks([]) pt_line_plt.ax.yaxis.set_ticks([1]) with pytest.raises( - AssertionError, match="Axis lines are displayed on plot" + AssertionError, match="Axis lines are displayed on plot" ): pt_line_plt.assert_axis_off() plt.close() @@ -93,7 +93,8 @@ def test_axis_label_contains_y(pt_line_plt): def test_axis_label_contains_invalid_axis(pt_line_plt): - """Check that assert_axis_label_contains fails when given unexpected axis""" + """Check that assert_axis_label_contains fails when given unexpected + axis""" # Fails when given an invalid axies with pytest.raises(ValueError, match="axis must be one of the following"): pt_line_plt.assert_axis_label_contains( @@ -105,8 +106,8 @@ def test_axis_label_contains_invalid_axis(pt_line_plt): def test_axis_label_contains_bad_text(pt_line_plt): """Check that assert_axis_label_contains fails with text not in label""" with pytest.raises( - AssertionError, - match="x-axis label does not contain expected string: foo", + AssertionError, + match="x-axis label does not contain expected string: foo", ): pt_line_plt.assert_axis_label_contains( axis="x", strings_expected=["x", "foo"] @@ -125,14 +126,14 @@ def test_axis_label_contains_expect_none(pt_multi_line_plt): def test_axis_label_contains_no_label(pt_multi_line_plt): """Check assert_axis_label_contains fails when there is no axis label""" with pytest.raises( - AssertionError, match="Expected x axis label is not displayed" + AssertionError, match="Expected x axis label is not displayed" ): pt_multi_line_plt.assert_axis_label_contains( axis="x", strings_expected=["foo"] ) with pytest.raises( - AssertionError, match="Expected y axis label is not displayed" + AssertionError, match="Expected y axis label is not displayed" ): pt_multi_line_plt.assert_axis_label_contains( axis="y", strings_expected=["foo"] @@ -177,7 +178,7 @@ def test_assert_lims_x_bad_lims(pt_line_plt): def test_assert_lims_invalid_axis(pt_line_plt): """Test that assert_lims fails with invalid axis (z)""" with pytest.raises( - ValueError, match="axis must be one of the following string" + ValueError, match="axis must be one of the following string" ): pt_line_plt.assert_lims([0, 100], axis="z") plt.close() @@ -200,11 +201,11 @@ def test_assert_lims_range_y_pass(pt_line_plt): def test_assert_lims_range_y_bad_lims(pt_line_plt): """Test that assert_lims_range fails with bad values for y axis""" with pytest.raises( - AssertionError, match="Incorrect max limit on the y axis" + AssertionError, match="Incorrect max limit on the y axis" ): pt_line_plt.assert_lims_range(((-5, 5), (95, 99)), axis="y") with pytest.raises( - AssertionError, match="Incorrect min limit on the y axis" + AssertionError, match="Incorrect min limit on the y axis" ): pt_line_plt.assert_lims_range(((1, 5), (95, 105)), axis="y") plt.close() @@ -213,11 +214,11 @@ def test_assert_lims_range_y_bad_lims(pt_line_plt): def test_assert_lims_range_x_bad_lims(pt_line_plt): """Test that assert_lims_range fails with bad values for x axis""" with pytest.raises( - AssertionError, match="Incorrect max limit on the x axis" + AssertionError, match="Incorrect max limit on the x axis" ): pt_line_plt.assert_lims_range(((-5, 5), (95, 98)), axis="x") with pytest.raises( - AssertionError, match="Incorrect min limit on the x axis" + AssertionError, match="Incorrect min limit on the x axis" ): pt_line_plt.assert_lims_range(((1, 5), (95, 105)), axis="x") plt.close() @@ -226,7 +227,7 @@ def test_assert_lims_range_x_bad_lims(pt_line_plt): def test_assert_lims_range_invalid_axis(pt_line_plt): """Test that assert_lims_range fails with invalid axis (z)""" with pytest.raises( - ValueError, match="axis must be one of the following string" + ValueError, match="axis must be one of the following string" ): pt_line_plt.assert_lims_range(((-5, 5), (95, 105)), axis="z") plt.close() From 709aaec875d9f9684e47048b299167eace3f6fa9 Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Thu, 13 Feb 2020 17:37:53 -0700 Subject: [PATCH 15/29] fixed text_base_data.py --- matplotcheck/tests/test_base_data.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/matplotcheck/tests/test_base_data.py b/matplotcheck/tests/test_base_data.py index fee04b3f..fdcdade9 100644 --- a/matplotcheck/tests/test_base_data.py +++ b/matplotcheck/tests/test_base_data.py @@ -178,7 +178,8 @@ def test_assert_xydata_xlabel_text_fails(pd_df_monthly_data, pt_monthly_data): def test_assert_xydata_xlabel_numeric( pd_df_monthly_data_numeric, pt_monthly_data_numeric ): - """Tests the xlabels flag on xydata works with numeric expected x-labels.""" + """Tests the xlabels flag on xydata works with numeric expected + x-labels.""" pt_monthly_data_numeric.assert_xydata( pd_df_monthly_data_numeric, xcol="months", ycol="data", xlabels=True From d21460254905da439840873725ecc9deaea2c4bb Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Thu, 13 Feb 2020 17:39:06 -0700 Subject: [PATCH 16/29] fixed test_base_legends.py --- matplotcheck/tests/test_base_legends.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/matplotcheck/tests/test_base_legends.py b/matplotcheck/tests/test_base_legends.py index 01803fc2..e5fbba7f 100644 --- a/matplotcheck/tests/test_base_legends.py +++ b/matplotcheck/tests/test_base_legends.py @@ -2,7 +2,6 @@ import pytest import matplotlib.pyplot as plt - """ LEGEND TESTS """ @@ -22,8 +21,8 @@ def test_assert_legend_titles_not_case_sensitive(pt_multi_line_plt): def test_assert_legend_titles_bad_text(pt_multi_line_plt): """Check that assert_legend_titles fails with wrong text""" with pytest.raises( - AssertionError, - match="Legend title does not contain expected string: foo", + AssertionError, + match="Legend title does not contain expected string: foo", ): pt_multi_line_plt.assert_legend_titles(["foo"]) plt.close() @@ -33,8 +32,8 @@ def test_assert_legend_titles_wrong_num(pt_multi_line_plt): """Check assert_legend_titles fails when expected number of titles is not equal to # of legends""" with pytest.raises( - AssertionError, - match="I was expecting 1 legend titles but instead found 2", + AssertionError, + match="I was expecting 1 legend titles but instead found 2", ): pt_multi_line_plt.assert_legend_titles(["legend", "legend2"]) plt.close() @@ -53,18 +52,20 @@ def test_assert_legend_not_case_sensitive(pt_multi_line_plt): def test_assert_legend_labels_bad_text(pt_multi_line_plt): - """Check that assert_legend_labels raises expected error when given wrong text""" + """Check that assert_legend_labels raises expected error when given + wrong text""" with pytest.raises( - AssertionError, match="Legend does not have expected labels" + AssertionError, match="Legend does not have expected labels" ): pt_multi_line_plt.assert_legend_labels(["a", "c"]) plt.close() def test_assert_legend_labels_wrong_num(pt_multi_line_plt): - """Check that assert_legend_labels raises expected error given wrong number of labels""" + """Check that assert_legend_labels raises expected error given wrong + number of labels""" with pytest.raises( - AssertionError, match="I was expecting 3 legend entries" + AssertionError, match="I was expecting 3 legend entries" ): pt_multi_line_plt.assert_legend_labels(["a", "b", "c"]) plt.close() @@ -91,9 +92,9 @@ def test_assert_no_legend_overlap_single(pt_multi_line_plt): def test_assert_no_legend_overlap_double(pt_multi_line_plt): - """Checks that assert_no_legend_overlap passes when two legends don't overlap""" + """Checks that assert_no_legend_overlap passes when two legends don't + overlap""" leg_1 = plt.legend(loc=[0.8, 0.8]) - leg_2 = plt.legend(loc=[0.1, 0.1]) pt_multi_line_plt.ax.add_artist(leg_1) pt_multi_line_plt.assert_no_legend_overlap() plt.close() @@ -102,7 +103,6 @@ def test_assert_no_legend_overlap_double(pt_multi_line_plt): def test_assert_no_legend_overlap_fail(pt_multi_line_plt): """Checks that assert_no_legend_overlap fails with overlapping legends""" leg_1 = plt.legend(loc=[0.12, 0.12]) - leg_2 = plt.legend(loc=[0.1, 0.1]) pt_multi_line_plt.ax.add_artist(leg_1) with pytest.raises(AssertionError, match="Legends overlap eachother"): pt_multi_line_plt.assert_no_legend_overlap() From 5d551dbabf5b357122781cfaceedfc7be4428259 Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Thu, 13 Feb 2020 17:40:01 -0700 Subject: [PATCH 17/29] fixed test_base_titles_captions.py --- matplotcheck/tests/test_base_titles_captions.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/matplotcheck/tests/test_base_titles_captions.py b/matplotcheck/tests/test_base_titles_captions.py index 303fe9c4..1506b77e 100644 --- a/matplotcheck/tests/test_base_titles_captions.py +++ b/matplotcheck/tests/test_base_titles_captions.py @@ -22,7 +22,8 @@ def test_get_titles(pt_line_plt): def test_get_titles_suptitle(pt_line_plt): - """Check that the correct suptitle gets grabbed from a figure with 2 subplots""" + """Check that the correct suptitle gets grabbed from a figure with 2 + subplots""" assert "My Figure Title" == pt_line_plt.get_titles()[0] plt.close() @@ -76,7 +77,8 @@ def test_title_contains_figure(pt_line_plt): def test_title_contains_figure_nosuptitle(pt_bar_plt): - """Check title_contains tester for figure title fails when there is no suptitle""" + """Check title_contains tester for figure title fails when there is no + suptitle""" with pytest.raises( AssertionError, match="Expected title is not displayed" ): @@ -95,7 +97,8 @@ def test_title_contains_both_axes_figure(pt_line_plt): def test_title_contains_both_axes_figure_badtext(pt_line_plt): - """Check title_contains tester for combined titles, should fail with bad text""" + """Check title_contains tester for combined titles, should fail with bad + text""" with pytest.raises( AssertionError, match="Title does not contain expected string: foo" ): From dbc354bc64530534aba668efd5121cee941965e3 Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Thu, 13 Feb 2020 17:40:45 -0700 Subject: [PATCH 18/29] Format files to be flake8 acceptable (#197) * autograde flake8 fixes * Fixed base to be flake8 compliant (phew) * Made folium.py flake8 compliant * made notebook.py flake8 compliant * Fixed raster.py for flake8 * Fixed timeseries.py * fixed conftest.py * fixed test_base.py --- matplotcheck/autograde.py | 7 +- matplotcheck/base.py | 116 ++++++++++++++++++-------------- matplotcheck/folium.py | 18 +++-- matplotcheck/notebook.py | 36 +++++++--- matplotcheck/raster.py | 24 +++---- matplotcheck/tests/conftest.py | 3 +- matplotcheck/tests/test_base.py | 30 ++++++--- matplotcheck/timeseries.py | 23 ++++--- 8 files changed, 151 insertions(+), 106 deletions(-) diff --git a/matplotcheck/autograde.py b/matplotcheck/autograde.py index fe565e59..f2a5a3f5 100644 --- a/matplotcheck/autograde.py +++ b/matplotcheck/autograde.py @@ -41,10 +41,10 @@ def run_test( pass : bool : passing status of test function description : str : test function name that was run message : str : custom message returned based on passing status - traceback : AssertionError : returned from test function when pass is False + traceback : AssertionError : returned from test function when pass is + False """ results = {"points": 0, "pass": False} - score = 0 try: fname = func.__name__ results["description"] = fname @@ -72,7 +72,8 @@ def output_results(results): pass : bool : passing status of test function description : str : test function name that was run message : str : custom message returned based on passing status - traceback : AssertionError : returned from test function when pass is False + traceback : AssertionError : returned from test function when pass is + False Returns ------- diff --git a/matplotcheck/base.py b/matplotcheck/base.py index fe828643..9d48e550 100644 --- a/matplotcheck/base.py +++ b/matplotcheck/base.py @@ -109,15 +109,16 @@ def assert_string_contains( Similar to `message_default`, `message_or` is the error message to be displated if `string` does not contain at least one of the strings in an inner list in `strings_expected`. If `message` - contains ``'{0}'``, it will be replaced with the first failing inner - list in `strings_expected`. + contains ``'{0}'``, it will be replaced with the first failing + inner list in `strings_expected`. Raises ------- AssertionError if `string` does not contain expected strings """ - # Assertion passes if strings_expected == [] or strings_expected == None + # Assertion passes if strings_expected == [] or + # strings_expected == None if not strings_expected: return @@ -149,8 +150,8 @@ def assert_plot_type( String specifying the expected plot type. Options: `scatter`, `bar`, `line` message : string - The error message to be displayed if Plot does not match `plot_type`. If - `message` contains ``'{0}'``, it will be replaced + The error message to be displayed if Plot does not match + `plot_type`. If `message` contains ``'{0}'``, it will be replaced with the epected plot type. Raises @@ -219,18 +220,19 @@ def assert_title_contains( assertion. The combined title will be tested. message_default : string - The error message to be displayed if the axis label does not contain - a string in strings_expected. If `message` contains ``'{0}'``, it - will be replaced with the first expected string not found in the - label. + The error message to be displayed if the axis label does not + contain a string in strings_expected. If `message` contains + ``'{0}'``, it will be replaced with the first expected string not + found in the label. message_or : string Similar to `message_default`, `message_or` is the error message to be displated if the axis label does not contain at least one of the strings in an inner list in `strings_expected`. If `message` - contains ``'{0}'``, it will be replaced with the first failing inner - list in `strings_expected`. + contains ``'{0}'``, it will be replaced with the first failing + inner list in `strings_expected`. message_no_title : string - The error message to be displayed if the expected title is not displayed. + The error message to be displayed if the expected title is not + displayed. Raises ------- @@ -246,7 +248,8 @@ def assert_title_contains( title = axtitle else: raise ValueError( - 'title_type must be one of the following ["figure", "axes", "either"]' + 'title_type must be one of the following ' + + '["figure", "axes", "either"]' ) assert title, message_no_title @@ -268,7 +271,8 @@ def get_caption(self): Returns ------- caption : string - the text that is found in bottom right, ``None`` if no text is found + the text that is found in bottom right, ``None`` if no text is + found """ caption = None ax_position = self.ax.get_position() @@ -308,16 +312,16 @@ def assert_caption_contains( ``'a'`` AND ``'b'`` AND (at least one of: ``'c'``, ``'d'``) must be in the title for the assertion to pass. Case insensitive. message_default : string - The error message to be displayed if the axis label does not contain - a string in strings_expected. If `message` contains ``'{0}'``, it - will be replaced with the first expected string not found in the - label. + The error message to be displayed if the axis label does not + contain a string in strings_expected. If `message` contains + ``'{0}'``, it will be replaced with the first expected string + not found in the label. message_or : string Similar to `message_default`, `message_or` is the error message to be displated if the axis label does not contain at least one of the strings in an inner list in `strings_expected`. If `message` - contains ``'{0}'``, it will be replaced with the first failing inner - list in `strings_expected`. + contains ``'{0}'``, it will be replaced with the first failing + inner list in `strings_expected`. message_no_caption : string The error message to be displayed if no caption exists in the appropriate location. @@ -360,11 +364,11 @@ def assert_axis_off(self, message="Axis lines are displayed on plot"): """ flag = False # Case 1: check if axis have been turned off - if self.ax.axison == False: + if not self.ax.axison: flag = True # Case 2: Check if both axis visibilities set to false elif ( - self.ax.xaxis._visible == False and self.ax.yaxis._visible == False + not self.ax.xaxis._visible and not self.ax.yaxis._visible ): flag = True # Case 3: Check if both axis ticks are set to empty lists @@ -403,18 +407,18 @@ def assert_axis_label_contains( ``'a'`` AND ``'b'`` AND (at least one of: ``'c'``, ``'d'``) must be in the title for the assertion to pass. Case insensitive. message_default : string - The error message to be displayed if the axis label does not contain - a string in strings_expected. If `message` contains ``'{1}'``, it - will be replaced with `axis`. If `message` contains ``'{0}'``, it - will be replaced with the first expected string not found in the - label. + The error message to be displayed if the axis label does not + contain a string in strings_expected. If `message` contains + ``'{1}'``, it will be replaced with `axis`. If `message` contains + ``'{0}'``, it will be replaced with the first expected string not + found in the label. message_or : string Similar to `message_default`, `message_or` is the error message to be displated if the axis label does not contain at least one of the strings in an inner list in `strings_expected`. If `message` contains ``'{1}'``, it will be replaced with `axis`. If `message` - contains ``'{0}'``, it will be replaced with the first failing inner - list in `strings_expected`. + contains ``'{0}'``, it will be replaced with the first failing + inner list in `strings_expected`. message_not_displayed : string The error message to be displayed if the expected axis label is not displayed. If `message_not_displayed` contains ``'{0}'``, it will @@ -574,7 +578,8 @@ def assert_legend_titles( self, titles_exp, message="Legend title does not contain expected string: {0}", - message_num_titles="I was expecting {0} legend titles but instead found {1}", + message_num_titles="I was expecting {0} legend titles but instead " + + "found {1}", ): """Asserts legend titles contain expected text in titles_exp list. @@ -592,8 +597,8 @@ def assert_legend_titles( The error message to be displayed if there exist a different number of legend titles than expected. If `message_num_titles` contains ``'{0}'`` it will be replaced with the number of titles found. If - `message_num_titles` contains ``'{1}'`` it will be replaced with the - expected number of titles. + `message_num_titles` contains ``'{1}'`` it will be replaced with + the expected number of titles. Raises ------- @@ -625,7 +630,8 @@ def assert_legend_labels( labels_exp, message="Legend does not have expected labels", message_no_legend="Legend does not exist", - message_num_labels="I was expecting {0} legend entries, but found {1}. Are there extra labels in your legend?", + message_num_labels="I was expecting {0} legend entries, but found " + + "{1}. Are there extra labels in your legend?", ): """Asserts legends on ax have the correct entry labels @@ -643,8 +649,8 @@ def assert_legend_labels( The error message to be displayed if there exist a different number of legend labels than expected. If `message_num_labels` contains ``'{0}'`` it will be replaced with the number of labels found. If - `message_num_labels` contains ``'{1}'`` it will be replaced with the - expected number of labels. + `message_num_labels` contains ``'{1}'`` it will be replaced with + the expected number of labels. Raises @@ -751,7 +757,7 @@ def assert_no_legend_overlap(self, message="Legends overlap eachother"): legends[j].get_window_extent(RendererBase()).get_points() ) assert ( - self.legends_overlap(leg_extent1, leg_extent2) == False + not self.legends_overlap(leg_extent1, leg_extent2) ), message """ BASIC PLOT DATA FUNCTIONS """ @@ -765,9 +771,11 @@ def get_xy(self, points_only=False, xtime=False): ax : matplotlib.axes.Axes Matplotlib Axes object to be tested points_only : boolean - Set ``True`` to check only points, set ``False`` to check all data on plot. + Set ``True`` to check only points, set ``False`` to check all data + on plot. xtime : boolean - Set equal to True if the x axis of the plot contains datetime values + Set equal to True if the x axis of the plot contains datetime + values Returns ------- @@ -872,12 +880,13 @@ def assert_xydata( return elif not isinstance(xy_expected, pd.DataFrame): raise ValueError( - "xy_expected must be of type: pandas dataframe or Geopandas Dataframe" + "xy_expected must be of type: pandas dataframe or Geopandas " + + "Dataframe" ) # If xy_expected is a GeoDataFrame, then we make is a normal DataFrame - # with the coordinates of the geometry in that GeoDataFrame as the x and - # y data + # with the coordinates of the geometry in that GeoDataFrame as the x + # and y data if isinstance(xy_expected, gpd.geodataframe.GeoDataFrame) and not xcol: xy_expected = pd.DataFrame( data={ @@ -1018,7 +1027,7 @@ def assert_xlabel_ydata( except AssertionError: raise AssertionError(message) - ### LINE TESTS/HELPER FUNCTIONS ### + # LINE TESTS/HELPER FUNCTIONS def get_slope_yintercept(self, path_verts): """Returns the y-intercept of line based on the average slope of the @@ -1125,13 +1134,15 @@ def assert_lines_of_type(self, line_types): slope_exp, intercept_exp = 1, 0 else: raise ValueError( - 'each string in line_types must be from the following ["regression","onetoone"]' + 'each string in line_types must be from the following ' + + '["regression","onetoone"]' ) self.assert_line( slope_exp, intercept_exp, - message_no_line="{0} line is not displayed properly".format( + message_no_line="{0} line is not displayed properly".format + ( line_type ), message_data="{0} line does not cover dataset".format( @@ -1139,7 +1150,7 @@ def assert_lines_of_type(self, line_types): ), ) - ## HISTOGRAM FUNCTIONS ## + # HISTOGRAM FUNCTIONS def get_num_bins(self): """Gets the number of bins in histogram with a unique x-position. @@ -1149,8 +1160,9 @@ def get_num_bins(self): Int : Returns the number of bins with a unique x-position. For a normal histogram, this is just the number of bins. If there are two - overlapping or stacked histograms in the same `matplotlib.axis.Axis` - object, then this returns the number of bins with unique edges. """ + overlapping or stacked histograms in the same + `matplotlib.axis.Axis` object, then this returns the number of bins + with unique edges. """ x_data = self.get_xy(xtime=False)["x"] unique_x_data = list(set(x_data)) num_bins = len(unique_x_data) @@ -1170,9 +1182,9 @@ def assert_num_bins( Number of bins expected. message : string The error message to be displayed if plot does not contain - `num_bins`. If `message` contains ``'{0}'`` it will be replaced with - expected number of bins. If `message` contains ``'{1}'``, it will - be replaced with the number of bins found. + `num_bins`. If `message` contains ``'{0}'`` it will be replaced + with expected number of bins. If `message` contains ``'{1}'``, it + will be replaced with the number of bins found. Raises ------- @@ -1210,8 +1222,8 @@ def assert_bin_values( Parameters ---------- bin_values : list - A list of numbers representing the expected values of each consecutive - bin (i.e. the heights of the bars in the histogram). + A list of numbers representing the expected values of each + consecutive bin (i.e. the heights of the bars in the histogram). tolerence : float Measure of relative error allowed. For example: Given a tolerance ``tolerence=0.1``, an expected value diff --git a/matplotcheck/folium.py b/matplotcheck/folium.py index b1ab9e10..27e9a302 100644 --- a/matplotcheck/folium.py +++ b/matplotcheck/folium.py @@ -1,9 +1,8 @@ -import numpy as np import folium class FoliumTester(object): - """object to test Folium plots + """Object to test Folium plots Parameters ---------- @@ -16,18 +15,25 @@ def __init__(self, fmap): self.fmap = fmap def assert_map_type_folium(self): - """Asserts fmap is of type folium.folium.Map""" + """ + Asserts fmap is of type folium.folium.Map + """ assert type(self.fmap) == folium.folium.Map def assert_folium_marker_locs( self, markers, m="Markers not shown in appropriate location" ): - """Asserts folium contains markers with locations described in markers_exp and only those markers, with error message m + """ + Asserts folium contains markers with locations described in + markers_exp and only those markers, with error message m Parameters ---------- - markers: set of tuples where each tuple represents the x and y coord of an expected marker - m: string error message if assertion is not met + markers: tuples + Set of tuples where each tuple represents the x and y coord of + an expected marker. + m: string + Error message if assertion is not met. """ marker_locs = set() while self.fmap._children: diff --git a/matplotcheck/notebook.py b/matplotcheck/notebook.py index 00716017..efc31a7e 100644 --- a/matplotcheck/notebook.py +++ b/matplotcheck/notebook.py @@ -8,12 +8,16 @@ def convert_axes(plt, which_axes="current"): Parameters --------- - plt: Matplotlib plot to be tested - which_axes: string from the following list ['current', 'last', 'first', 'all'] stating which axes we are saving for testing + plt: matplotlib plot + Matplotlib plot to be tested. + which_axes: string + String from the following list ['current', 'last', 'first', 'all'] + stating which axes we are saving for testing. Returns ------- - ax: Matplotlib axes or list of axes as express by which_axes + ax: Matplotlib axes or list + Matplotlib axes or list of axes as express by which_axes """ fig = plt.gcf() if which_axes == "current": @@ -26,12 +30,13 @@ def convert_axes(plt, which_axes="current"): ax = fig.axes else: raise ValueError( - 'which_axes must be one of the following strings ["current", "last", "first", "all"]' + 'which_axes must be one of the following strings ' + + '["current", "last", "first", "all"]' ) return ax -### JUPYTER NOTEBOOK TEST HELPER FUNCTIONS! ### +# JUPYTER NOTEBOOK TEST HELPER FUNCTIONS! def error_test(n, n_exp): @@ -39,8 +44,10 @@ def error_test(n, n_exp): Parameters ---------- - n: int of number of cells that that did not produce an error - n_exp: int of number of cell that are checked if producing an error + n: int + Number of cells that that did not produce an error. + n_exp: int + Number of cell that are checked if producing an error. Returns ------- @@ -61,22 +68,29 @@ def remove_comments(input_string): Parameters ---------- input_string: string + String to be modified. Returns ------- - string where all parts commented out by a '#' are removed from input_string + string + Sting where all parts commented out by a '#' are removed from + input_string. """ split_lines = input_string.split("\n") return "".join([line.split("#")[0] for line in split_lines]) def import_test(var_dict, n): - """Tests no import statements are found after the first cell in a Jupyter Notebook + """ + Tests no import statements are found after the first cell in a Jupyter + Notebook Parameters ---------- - vars_dict: dictionary produced by 'locals()' in notebook - n: number of cells to be tested for import statement in Jupyter Notebook + vars_dict: dictionary + Dictionary produced by 'locals()' in notebook. + n: int + number of cells to be tested for import statement in Jupyter Notebook Returns ------- diff --git a/matplotcheck/raster.py b/matplotcheck/raster.py index 4f62a8ce..822daea2 100644 --- a/matplotcheck/raster.py +++ b/matplotcheck/raster.py @@ -1,6 +1,4 @@ import numpy as np - -from .base import PlotTester from .vector import VectorTester @@ -95,9 +93,9 @@ def assert_legend_accuracy_classified_image( all_label_options: list of lists Each internal list represents a class and said list is a list of strings where at least one string is expected to be in the legend - label for this category. Internal lists must be in the same order as - bins in im_expected, e.g. first internal list has the expected label - options for class 0. + label for this category. Internal lists must be in the same order + as bins in im_expected, e.g. first internal list has the expected + label options for class 0. Returns ---------- @@ -107,13 +105,13 @@ def assert_legend_accuracy_classified_image( Notes ---------- First compares all_label_options against the legend labels to find - which element of all_label_options matches that entry. E.g. if the first - legend entry has a match in the first list in all_label_options, then - that legend entry corresponds to the first class (value 0). - Then the plot image array is copied and the values are set to the legend - label that match the values (i.e. the element in all_label_options). - The same is done for the expected image array. Finally those two arrays - of strings are compared. Passes if they match. + which element of all_label_options matches that entry. E.g. if the + first legend entry has a match in the first list in all_label_options, + then that legend entry corresponds to the first class (value 0). + Then the plot image array is copied and the values are set to the + legend label that match the values (i.e. the element in + all_label_options). The same is done for the expected image array. + Finally those two arrays of strings are compared. Passes if they match. """ # Retrieve image array im_data = [] @@ -162,7 +160,7 @@ def assert_legend_accuracy_classified_image( im_data_labels, im_expected_labels ), "Incorrect legend to data relation" - ### IMAGE TESTS/HELPER FUNCTIONS ### + # IMAGE TESTS/HELPER FUNCTIONS def get_plot_image(self): """Returns images stored on the Axes object as a list of numpy arrays. diff --git a/matplotcheck/tests/conftest.py b/matplotcheck/tests/conftest.py index 278b3380..0de7100f 100644 --- a/matplotcheck/tests/conftest.py +++ b/matplotcheck/tests/conftest.py @@ -71,7 +71,8 @@ def basic_polygon_gdf(basic_polygon): @pytest.fixture def pd_xlabels(): """Create a DataFrame which uses the column labels as x-data.""" - df = pd.DataFrame({"B": bp.random.randint(0, 100, size=100)}) + df = pd.DataFrame({"B": np.random.randint(0, 100, size=100)}) + return df @pytest.fixture diff --git a/matplotcheck/tests/test_base.py b/matplotcheck/tests/test_base.py index f9f5999b..c099c4aa 100644 --- a/matplotcheck/tests/test_base.py +++ b/matplotcheck/tests/test_base.py @@ -44,8 +44,8 @@ def test_options(pt_line_plt): provided.""" with pytest.raises( - ValueError, - match="Plot_type to test must be either: scatter, bar or line", + ValueError, + match="Plot_type to test must be either: scatter, bar or line", ): pt_line_plt.assert_plot_type("foo") plt.close() @@ -55,7 +55,8 @@ def test_options(pt_line_plt): def test_assert_string_contains(pt_line_plt): - """Tests that assert_string_contains passes with correct expected strings.""" + """Tests that assert_string_contains passes with correct expected + strings.""" test_string = "this is a test string" string_expected = ["this", "is", "a", "test"] pt_line_plt.assert_string_contains(test_string, string_expected) @@ -63,18 +64,21 @@ def test_assert_string_contains(pt_line_plt): def test_assert_string_contains_fails(pt_line_plt): - """Tests that assert_string_contains fails with incorrect expected strings.""" + """Tests that assert_string_contains fails with incorrect expected + strings.""" test_string = "this is a test string" string_expected = ["this", "is", "not", "a", "test"] with pytest.raises( - AssertionError, match="String does not contain expected string: not" + AssertionError, + match="String does not contain expected string: not" ): pt_line_plt.assert_string_contains(test_string, string_expected) plt.close() def test_assert_string_contains_or(pt_line_plt): - """Tests that assert_string_contains correctly passes when using OR logic.""" + """Tests that assert_string_contains correctly passes when using OR + logic.""" test_string = "this is a test string" string_expected = ["this", ["is", "not"], "a", "test"] pt_line_plt.assert_string_contains(test_string, string_expected) @@ -82,11 +86,12 @@ def test_assert_string_contains_or(pt_line_plt): def test_assert_string_contains_or_fails(pt_line_plt): - """Tests that assert_string_contains correctly fails when using OR logic.""" + """Tests that assert_string_contains correctly fails when using OR + logic.""" test_string = "this is a test string" string_expected = ["this", "is", ["not", "jambalaya"], "a", "test"] with pytest.raises( - AssertionError, match="String does not contain at least one of: " + AssertionError, match="String does not contain at least one of: " ): pt_line_plt.assert_string_contains(test_string, string_expected) plt.close() @@ -107,14 +112,16 @@ def test_assert_string_contains_handles_short_list_fails(pt_line_plt): test_string = "this is a test string" string_expected = [["this"], ["is"], ["not"]] with pytest.raises( - AssertionError, match="String does not contain expected string: not" + AssertionError, + match="String does not contain expected string: not" ): pt_line_plt.assert_string_contains(test_string, string_expected) plt.close() def test_assert_string_contains_passes_with_none(pt_line_plt): - """Tests that assert_string_contains passes when strings_expected is None""" + """Tests that assert_string_contains passes when strings_expected is + None""" test_string = "this is a test string" string_expected = None pt_line_plt.assert_string_contains(test_string, string_expected) @@ -122,7 +129,8 @@ def test_assert_string_contains_passes_with_none(pt_line_plt): def test_assert_string_contains_passes_with_empty(pt_line_plt): - """Tests that assert_string_contains passes when strings_expected is empty""" + """Tests that assert_string_contains passes when strings_expected is + empty""" test_string = "this is a test string" string_expected = [] pt_line_plt.assert_string_contains(test_string, string_expected) diff --git a/matplotcheck/timeseries.py b/matplotcheck/timeseries.py index 7923aaeb..b7a4ffdc 100644 --- a/matplotcheck/timeseries.py +++ b/matplotcheck/timeseries.py @@ -40,8 +40,10 @@ def assert_xticks_reformatted( 'month': if tick should be shown every new month 'week': if tick should be shown every new week 'day': if tick should be shown every new day - None: if no tick format has been specified. This will automatically assert True - m: string error message if assertion is not met + None: if no tick format has been specified. This will automatically + assert True + m: string + string error message if assertion is not met """ if loc_exp: if tick_size == "large": @@ -60,7 +62,8 @@ def assert_xticks_reformatted( ) # September 30, 2013 else: raise ValueError( - "tick_size must be on of the following string ['large', 'small']" + "tick_size must be on of the following string " + + "['large', 'small']" ) if loc_exp == "decade" or loc_exp == "year": accepted_responses = ["2013"] @@ -70,7 +73,7 @@ def assert_xticks_reformatted( accepted_responses = ["sep30", "september30"] else: raise ValueError( - """loc_exp must be one of the following strings ['decade', + """loc_exp must be one of the following strings ['decade', 'year', 'month', 'week', 'day', None]""" ) assert test_date in accepted_responses, m @@ -107,7 +110,7 @@ def assert_xticks_locs( ticks = self.ax.xaxis.get_minorticklocs() else: raise ValueError( - """"Tick_size must be one of the following strings + """"Tick_size must be one of the following strings ['large', 'small']""" ) @@ -123,7 +126,7 @@ def assert_xticks_locs( inc = relativedelta(days=1) else: raise ValueError( - """"loc_exp must be one of the following strings ['decade', + """"loc_exp must be one of the following strings ['decade', 'year', 'month', 'week', 'day'] or None""" ) @@ -162,16 +165,18 @@ def assert_no_data_value(self, nodata=999.99): xtime: boolean does the x-axis contains datetime values? """ - if nodata != None: + if nodata: xy = self.get_xy(xtime=False) assert ~np.isin( nodata, xy["x"] - ), "Values of {0} have been found in data. Be sure to remove no data values".format( + ), "Values of {0} have been found in data. Be sure to remove no " + + "data values".format( nodata ) assert ~np.isin( nodata, xy["y"] - ), "Values of {0} have been found in data. Be sure to remove no data values".format( + ), "Values of {0} have been found in data. Be sure to remove no " + + "data values".format( nodata ) From 9c1d133bd7783009ce6c9691f3eb92083ccedb32 Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Thu, 13 Feb 2020 17:45:07 -0700 Subject: [PATCH 19/29] Fixed test_raster.py and issue with legends tests --- matplotcheck/tests/test_base_legends.py | 2 ++ matplotcheck/tests/test_raster.py | 19 ++++++++++++------- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/matplotcheck/tests/test_base_legends.py b/matplotcheck/tests/test_base_legends.py index e5fbba7f..a824736b 100644 --- a/matplotcheck/tests/test_base_legends.py +++ b/matplotcheck/tests/test_base_legends.py @@ -95,6 +95,7 @@ def test_assert_no_legend_overlap_double(pt_multi_line_plt): """Checks that assert_no_legend_overlap passes when two legends don't overlap""" leg_1 = plt.legend(loc=[0.8, 0.8]) + plt.legend(loc=[0.1, 0.1]) pt_multi_line_plt.ax.add_artist(leg_1) pt_multi_line_plt.assert_no_legend_overlap() plt.close() @@ -103,6 +104,7 @@ def test_assert_no_legend_overlap_double(pt_multi_line_plt): def test_assert_no_legend_overlap_fail(pt_multi_line_plt): """Checks that assert_no_legend_overlap fails with overlapping legends""" leg_1 = plt.legend(loc=[0.12, 0.12]) + plt.legend(loc=[0.1, 0.1]) pt_multi_line_plt.ax.add_artist(leg_1) with pytest.raises(AssertionError, match="Legends overlap eachother"): pt_multi_line_plt.assert_no_legend_overlap() diff --git a/matplotcheck/tests/test_raster.py b/matplotcheck/tests/test_raster.py index dd623660..6b4b79b3 100644 --- a/matplotcheck/tests/test_raster.py +++ b/matplotcheck/tests/test_raster.py @@ -1,6 +1,5 @@ """Tests for the raster module""" import pytest -import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches @@ -71,7 +70,9 @@ def raster_plt_class(np_ar_discrete): # Create legend colors = [im.cmap(im.norm(val)) for val in values] patches = [ - mpatches.Patch(color=colors[i], label="Level {l}".format(l=values[i])) + mpatches.Patch(color=colors[i], label="Level {lev}".format( + lev=values[i] + )) for i in range(values.shape[0]) ] plt.legend(handles=patches) @@ -85,7 +86,8 @@ def raster_plt_class(np_ar_discrete): def test_raster_get_colorbars_length(raster_plt): - """Check that get_colorbars correctly retrieves 1 colorbar from raster_plt1""" + """Check that get_colorbars correctly retrieves 1 colorbar from + raster_plt1""" # Should only be 1 object, and should be a colorbar object cb = raster_plt.get_colorbars() assert len(cb) == 1 @@ -156,7 +158,8 @@ def test_raster_assert_colorbar_range_blank(raster_plt_blank, np_ar): def test_raster_assert_legend_accuracy(raster_plt_class, np_ar_discrete): - """Checks that legend matches image, checking both the labels and color patches""" + """Checks that legend matches image, checking both the labels and color + patches""" values = np.sort(np.unique(np_ar_discrete)) label_options = [[str(i)] for i in values] @@ -184,7 +187,8 @@ def test_raster_assert_legend_accuracy_badlabel( def test_raster_assert_legend_accuracy_badvalues( raster_plt_class, np_ar_discrete ): - """Checks that legend matches image, should fail if you swap image values""" + """Checks that legend matches image, should fail if you swap image + values""" values = np.sort(np.unique(np_ar_discrete)) label_options = [[str(i)] for i in values] @@ -276,7 +280,8 @@ def test_raster_assert_image_class(raster_plt_class, np_ar_discrete): def test_raster_assert_image_class_baddata(raster_plt_class, np_ar_discrete): - """Check that assert_image with bad data fails for a discrete, classified image""" + """Check that assert_image with bad data fails for a discrete, classified + image""" bad_ar = np_ar_discrete + 1 with pytest.raises(AssertionError, match="Arrays are not equal"): raster_plt_class.assert_image(bad_ar) @@ -291,7 +296,7 @@ def test_raster_assert_image_fullscreen(raster_plt): def test_raster_assert_image_fullscreen_fail_xlims(raster_plt): """assert fullscreen should fail if we modify the x-axis limits""" - cur_xlim, cur_ylim = raster_plt.ax.get_xlim(), raster_plt.ax.get_ylim() + cur_xlim, _ = raster_plt.ax.get_xlim(), raster_plt.ax.get_ylim() raster_plt.ax.set_xlim([cur_xlim[0], cur_xlim[1] + 5]) with pytest.raises( AssertionError, match="Image is stretched inaccurately" From 7b3040f26ede80a2214f7d64683aca414056df6d Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Thu, 13 Feb 2020 18:00:51 -0700 Subject: [PATCH 20/29] black --- matplotcheck/base.py | 15 +++++-------- matplotcheck/notebook.py | 2 +- matplotcheck/tests/test_base.py | 12 +++++----- matplotcheck/tests/test_base_axis.py | 30 ++++++++++++------------- matplotcheck/tests/test_base_legends.py | 12 +++++----- matplotcheck/tests/test_raster.py | 6 ++--- matplotcheck/timeseries.py | 8 ++----- 7 files changed, 38 insertions(+), 47 deletions(-) diff --git a/matplotcheck/base.py b/matplotcheck/base.py index 9d48e550..b4799d51 100644 --- a/matplotcheck/base.py +++ b/matplotcheck/base.py @@ -248,7 +248,7 @@ def assert_title_contains( title = axtitle else: raise ValueError( - 'title_type must be one of the following ' + "title_type must be one of the following " + '["figure", "axes", "either"]' ) @@ -367,9 +367,7 @@ def assert_axis_off(self, message="Axis lines are displayed on plot"): if not self.ax.axison: flag = True # Case 2: Check if both axis visibilities set to false - elif ( - not self.ax.xaxis._visible and not self.ax.yaxis._visible - ): + elif not self.ax.xaxis._visible and not self.ax.yaxis._visible: flag = True # Case 3: Check if both axis ticks are set to empty lists elif ( @@ -756,8 +754,8 @@ def assert_no_legend_overlap(self, message="Legends overlap eachother"): leg_extent2 = ( legends[j].get_window_extent(RendererBase()).get_points() ) - assert ( - not self.legends_overlap(leg_extent1, leg_extent2) + assert not self.legends_overlap( + leg_extent1, leg_extent2 ), message """ BASIC PLOT DATA FUNCTIONS """ @@ -1134,15 +1132,14 @@ def assert_lines_of_type(self, line_types): slope_exp, intercept_exp = 1, 0 else: raise ValueError( - 'each string in line_types must be from the following ' + "each string in line_types must be from the following " + '["regression","onetoone"]' ) self.assert_line( slope_exp, intercept_exp, - message_no_line="{0} line is not displayed properly".format - ( + message_no_line="{0} line is not displayed properly".format( line_type ), message_data="{0} line does not cover dataset".format( diff --git a/matplotcheck/notebook.py b/matplotcheck/notebook.py index efc31a7e..2e62870d 100644 --- a/matplotcheck/notebook.py +++ b/matplotcheck/notebook.py @@ -30,7 +30,7 @@ def convert_axes(plt, which_axes="current"): ax = fig.axes else: raise ValueError( - 'which_axes must be one of the following strings ' + "which_axes must be one of the following strings " + '["current", "last", "first", "all"]' ) return ax diff --git a/matplotcheck/tests/test_base.py b/matplotcheck/tests/test_base.py index c099c4aa..23b1bf0f 100644 --- a/matplotcheck/tests/test_base.py +++ b/matplotcheck/tests/test_base.py @@ -44,8 +44,8 @@ def test_options(pt_line_plt): provided.""" with pytest.raises( - ValueError, - match="Plot_type to test must be either: scatter, bar or line", + ValueError, + match="Plot_type to test must be either: scatter, bar or line", ): pt_line_plt.assert_plot_type("foo") plt.close() @@ -69,8 +69,7 @@ def test_assert_string_contains_fails(pt_line_plt): test_string = "this is a test string" string_expected = ["this", "is", "not", "a", "test"] with pytest.raises( - AssertionError, - match="String does not contain expected string: not" + AssertionError, match="String does not contain expected string: not" ): pt_line_plt.assert_string_contains(test_string, string_expected) plt.close() @@ -91,7 +90,7 @@ def test_assert_string_contains_or_fails(pt_line_plt): test_string = "this is a test string" string_expected = ["this", "is", ["not", "jambalaya"], "a", "test"] with pytest.raises( - AssertionError, match="String does not contain at least one of: " + AssertionError, match="String does not contain at least one of: " ): pt_line_plt.assert_string_contains(test_string, string_expected) plt.close() @@ -112,8 +111,7 @@ def test_assert_string_contains_handles_short_list_fails(pt_line_plt): test_string = "this is a test string" string_expected = [["this"], ["is"], ["not"]] with pytest.raises( - AssertionError, - match="String does not contain expected string: not" + AssertionError, match="String does not contain expected string: not" ): pt_line_plt.assert_string_contains(test_string, string_expected) plt.close() diff --git a/matplotcheck/tests/test_base_axis.py b/matplotcheck/tests/test_base_axis.py index 3e353c39..e16f2885 100644 --- a/matplotcheck/tests/test_base_axis.py +++ b/matplotcheck/tests/test_base_axis.py @@ -9,7 +9,7 @@ def test_axis_off_fail_on(pt_line_plt): """Check assert_axis_off fails when axis lines are on""" # Should fail when axis are on (by default) with pytest.raises( - AssertionError, match="Axis lines are displayed on plot" + AssertionError, match="Axis lines are displayed on plot" ): pt_line_plt.assert_axis_off() plt.close() @@ -37,14 +37,14 @@ def test_axis_off_one_visible(pt_line_plt): pt_line_plt.ax.xaxis.set_visible(True) pt_line_plt.ax.yaxis.set_visible(False) with pytest.raises( - AssertionError, match="Axis lines are displayed on plot" + AssertionError, match="Axis lines are displayed on plot" ): pt_line_plt.assert_axis_off() pt_line_plt.ax.xaxis.set_visible(False) pt_line_plt.ax.yaxis.set_visible(True) with pytest.raises( - AssertionError, match="Axis lines are displayed on plot" + AssertionError, match="Axis lines are displayed on plot" ): pt_line_plt.assert_axis_off() plt.close() @@ -65,14 +65,14 @@ def test_axis_off_non_empty_ticks(pt_line_plt): pt_line_plt.ax.xaxis.set_ticks([1]) pt_line_plt.ax.yaxis.set_ticks([]) with pytest.raises( - AssertionError, match="Axis lines are displayed on plot" + AssertionError, match="Axis lines are displayed on plot" ): pt_line_plt.assert_axis_off() pt_line_plt.ax.xaxis.set_ticks([]) pt_line_plt.ax.yaxis.set_ticks([1]) with pytest.raises( - AssertionError, match="Axis lines are displayed on plot" + AssertionError, match="Axis lines are displayed on plot" ): pt_line_plt.assert_axis_off() plt.close() @@ -106,8 +106,8 @@ def test_axis_label_contains_invalid_axis(pt_line_plt): def test_axis_label_contains_bad_text(pt_line_plt): """Check that assert_axis_label_contains fails with text not in label""" with pytest.raises( - AssertionError, - match="x-axis label does not contain expected string: foo", + AssertionError, + match="x-axis label does not contain expected string: foo", ): pt_line_plt.assert_axis_label_contains( axis="x", strings_expected=["x", "foo"] @@ -126,14 +126,14 @@ def test_axis_label_contains_expect_none(pt_multi_line_plt): def test_axis_label_contains_no_label(pt_multi_line_plt): """Check assert_axis_label_contains fails when there is no axis label""" with pytest.raises( - AssertionError, match="Expected x axis label is not displayed" + AssertionError, match="Expected x axis label is not displayed" ): pt_multi_line_plt.assert_axis_label_contains( axis="x", strings_expected=["foo"] ) with pytest.raises( - AssertionError, match="Expected y axis label is not displayed" + AssertionError, match="Expected y axis label is not displayed" ): pt_multi_line_plt.assert_axis_label_contains( axis="y", strings_expected=["foo"] @@ -178,7 +178,7 @@ def test_assert_lims_x_bad_lims(pt_line_plt): def test_assert_lims_invalid_axis(pt_line_plt): """Test that assert_lims fails with invalid axis (z)""" with pytest.raises( - ValueError, match="axis must be one of the following string" + ValueError, match="axis must be one of the following string" ): pt_line_plt.assert_lims([0, 100], axis="z") plt.close() @@ -201,11 +201,11 @@ def test_assert_lims_range_y_pass(pt_line_plt): def test_assert_lims_range_y_bad_lims(pt_line_plt): """Test that assert_lims_range fails with bad values for y axis""" with pytest.raises( - AssertionError, match="Incorrect max limit on the y axis" + AssertionError, match="Incorrect max limit on the y axis" ): pt_line_plt.assert_lims_range(((-5, 5), (95, 99)), axis="y") with pytest.raises( - AssertionError, match="Incorrect min limit on the y axis" + AssertionError, match="Incorrect min limit on the y axis" ): pt_line_plt.assert_lims_range(((1, 5), (95, 105)), axis="y") plt.close() @@ -214,11 +214,11 @@ def test_assert_lims_range_y_bad_lims(pt_line_plt): def test_assert_lims_range_x_bad_lims(pt_line_plt): """Test that assert_lims_range fails with bad values for x axis""" with pytest.raises( - AssertionError, match="Incorrect max limit on the x axis" + AssertionError, match="Incorrect max limit on the x axis" ): pt_line_plt.assert_lims_range(((-5, 5), (95, 98)), axis="x") with pytest.raises( - AssertionError, match="Incorrect min limit on the x axis" + AssertionError, match="Incorrect min limit on the x axis" ): pt_line_plt.assert_lims_range(((1, 5), (95, 105)), axis="x") plt.close() @@ -227,7 +227,7 @@ def test_assert_lims_range_x_bad_lims(pt_line_plt): def test_assert_lims_range_invalid_axis(pt_line_plt): """Test that assert_lims_range fails with invalid axis (z)""" with pytest.raises( - ValueError, match="axis must be one of the following string" + ValueError, match="axis must be one of the following string" ): pt_line_plt.assert_lims_range(((-5, 5), (95, 105)), axis="z") plt.close() diff --git a/matplotcheck/tests/test_base_legends.py b/matplotcheck/tests/test_base_legends.py index a824736b..66884d66 100644 --- a/matplotcheck/tests/test_base_legends.py +++ b/matplotcheck/tests/test_base_legends.py @@ -21,8 +21,8 @@ def test_assert_legend_titles_not_case_sensitive(pt_multi_line_plt): def test_assert_legend_titles_bad_text(pt_multi_line_plt): """Check that assert_legend_titles fails with wrong text""" with pytest.raises( - AssertionError, - match="Legend title does not contain expected string: foo", + AssertionError, + match="Legend title does not contain expected string: foo", ): pt_multi_line_plt.assert_legend_titles(["foo"]) plt.close() @@ -32,8 +32,8 @@ def test_assert_legend_titles_wrong_num(pt_multi_line_plt): """Check assert_legend_titles fails when expected number of titles is not equal to # of legends""" with pytest.raises( - AssertionError, - match="I was expecting 1 legend titles but instead found 2", + AssertionError, + match="I was expecting 1 legend titles but instead found 2", ): pt_multi_line_plt.assert_legend_titles(["legend", "legend2"]) plt.close() @@ -55,7 +55,7 @@ def test_assert_legend_labels_bad_text(pt_multi_line_plt): """Check that assert_legend_labels raises expected error when given wrong text""" with pytest.raises( - AssertionError, match="Legend does not have expected labels" + AssertionError, match="Legend does not have expected labels" ): pt_multi_line_plt.assert_legend_labels(["a", "c"]) plt.close() @@ -65,7 +65,7 @@ def test_assert_legend_labels_wrong_num(pt_multi_line_plt): """Check that assert_legend_labels raises expected error given wrong number of labels""" with pytest.raises( - AssertionError, match="I was expecting 3 legend entries" + AssertionError, match="I was expecting 3 legend entries" ): pt_multi_line_plt.assert_legend_labels(["a", "b", "c"]) plt.close() diff --git a/matplotcheck/tests/test_raster.py b/matplotcheck/tests/test_raster.py index 6b4b79b3..a2885ec7 100644 --- a/matplotcheck/tests/test_raster.py +++ b/matplotcheck/tests/test_raster.py @@ -70,9 +70,9 @@ def raster_plt_class(np_ar_discrete): # Create legend colors = [im.cmap(im.norm(val)) for val in values] patches = [ - mpatches.Patch(color=colors[i], label="Level {lev}".format( - lev=values[i] - )) + mpatches.Patch( + color=colors[i], label="Level {lev}".format(lev=values[i]) + ) for i in range(values.shape[0]) ] plt.legend(handles=patches) diff --git a/matplotcheck/timeseries.py b/matplotcheck/timeseries.py index b7a4ffdc..026ff61c 100644 --- a/matplotcheck/timeseries.py +++ b/matplotcheck/timeseries.py @@ -170,15 +170,11 @@ def assert_no_data_value(self, nodata=999.99): assert ~np.isin( nodata, xy["x"] ), "Values of {0} have been found in data. Be sure to remove no " - + "data values".format( - nodata - ) + +"data values".format(nodata) assert ~np.isin( nodata, xy["y"] ), "Values of {0} have been found in data. Be sure to remove no " - + "data values".format( - nodata - ) + +"data values".format(nodata) def assert_xdata_date( self, x_exp, m="X-axis is not in appropriate date format" From 61344b06c7e5951f4a5afb5c65a54cd7b9da8a74 Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Thu, 13 Feb 2020 18:03:54 -0700 Subject: [PATCH 21/29] more black changes --- matplotcheck/base.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/matplotcheck/base.py b/matplotcheck/base.py index b4799d51..d4d8c5b9 100644 --- a/matplotcheck/base.py +++ b/matplotcheck/base.py @@ -1139,9 +1139,8 @@ def assert_lines_of_type(self, line_types): self.assert_line( slope_exp, intercept_exp, - message_no_line="{0} line is not displayed properly".format( - line_type - ), + message_no_line="{0} line is not " + + "displayed properly".format(line_type), message_data="{0} line does not cover dataset".format( line_type ), From 20a080bfff979ec78bb987b179a86ba9a1cde60b Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Mon, 17 Feb 2020 13:39:12 -0700 Subject: [PATCH 22/29] Fixing merge conflicts that were found --- matplotcheck/base.py | 26 -------------------------- 1 file changed, 26 deletions(-) diff --git a/matplotcheck/base.py b/matplotcheck/base.py index ba30ceec..e2f71a65 100644 --- a/matplotcheck/base.py +++ b/matplotcheck/base.py @@ -248,11 +248,7 @@ def assert_title_contains( title = axtitle else: raise ValueError( -<<<<<<< HEAD 'title_type must be one of the following ' -======= - "title_type must be one of the following " ->>>>>>> 61344b06c7e5951f4a5afb5c65a54cd7b9da8a74 + '["figure", "axes", "either"]' ) @@ -371,13 +367,7 @@ def assert_axis_off(self, message="Axis lines are displayed on plot"): if not self.ax.axison: flag = True # Case 2: Check if both axis visibilities set to false -<<<<<<< HEAD - elif ( - not self.ax.xaxis._visible and not self.ax.yaxis._visible - ): -======= elif not self.ax.xaxis._visible and not self.ax.yaxis._visible: ->>>>>>> 61344b06c7e5951f4a5afb5c65a54cd7b9da8a74 flag = True # Case 3: Check if both axis ticks are set to empty lists elif ( @@ -764,13 +754,8 @@ def assert_no_legend_overlap(self, message="Legends overlap eachother"): leg_extent2 = ( legends[j].get_window_extent(RendererBase()).get_points() ) -<<<<<<< HEAD - assert ( - not self.legends_overlap(leg_extent1, leg_extent2) -======= assert not self.legends_overlap( leg_extent1, leg_extent2 ->>>>>>> 61344b06c7e5951f4a5afb5c65a54cd7b9da8a74 ), message """ BASIC PLOT DATA FUNCTIONS """ @@ -1147,26 +1132,15 @@ def assert_lines_of_type(self, line_types): slope_exp, intercept_exp = 1, 0 else: raise ValueError( -<<<<<<< HEAD 'each string in line_types must be from the following ' -======= - "each string in line_types must be from the following " ->>>>>>> 61344b06c7e5951f4a5afb5c65a54cd7b9da8a74 + '["regression","onetoone"]' ) self.assert_line( slope_exp, intercept_exp, -<<<<<<< HEAD - message_no_line="{0} line is not displayed properly".format - ( - line_type - ), -======= message_no_line="{0} line is not " + "displayed properly".format(line_type), ->>>>>>> 61344b06c7e5951f4a5afb5c65a54cd7b9da8a74 message_data="{0} line does not cover dataset".format( line_type ), From e4453bbcda185b151c43f1d337c075659ced6738 Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Mon, 17 Feb 2020 13:58:10 -0700 Subject: [PATCH 23/29] Changing accepted changes --- matplotcheck/base.py | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/matplotcheck/base.py b/matplotcheck/base.py index ba30ceec..9d48e550 100644 --- a/matplotcheck/base.py +++ b/matplotcheck/base.py @@ -248,11 +248,7 @@ def assert_title_contains( title = axtitle else: raise ValueError( -<<<<<<< HEAD 'title_type must be one of the following ' -======= - "title_type must be one of the following " ->>>>>>> 61344b06c7e5951f4a5afb5c65a54cd7b9da8a74 + '["figure", "axes", "either"]' ) @@ -371,13 +367,9 @@ def assert_axis_off(self, message="Axis lines are displayed on plot"): if not self.ax.axison: flag = True # Case 2: Check if both axis visibilities set to false -<<<<<<< HEAD elif ( not self.ax.xaxis._visible and not self.ax.yaxis._visible ): -======= - elif not self.ax.xaxis._visible and not self.ax.yaxis._visible: ->>>>>>> 61344b06c7e5951f4a5afb5c65a54cd7b9da8a74 flag = True # Case 3: Check if both axis ticks are set to empty lists elif ( @@ -764,13 +756,8 @@ def assert_no_legend_overlap(self, message="Legends overlap eachother"): leg_extent2 = ( legends[j].get_window_extent(RendererBase()).get_points() ) -<<<<<<< HEAD assert ( not self.legends_overlap(leg_extent1, leg_extent2) -======= - assert not self.legends_overlap( - leg_extent1, leg_extent2 ->>>>>>> 61344b06c7e5951f4a5afb5c65a54cd7b9da8a74 ), message """ BASIC PLOT DATA FUNCTIONS """ @@ -1147,26 +1134,17 @@ def assert_lines_of_type(self, line_types): slope_exp, intercept_exp = 1, 0 else: raise ValueError( -<<<<<<< HEAD 'each string in line_types must be from the following ' -======= - "each string in line_types must be from the following " ->>>>>>> 61344b06c7e5951f4a5afb5c65a54cd7b9da8a74 + '["regression","onetoone"]' ) self.assert_line( slope_exp, intercept_exp, -<<<<<<< HEAD message_no_line="{0} line is not displayed properly".format ( line_type ), -======= - message_no_line="{0} line is not " - + "displayed properly".format(line_type), ->>>>>>> 61344b06c7e5951f4a5afb5c65a54cd7b9da8a74 message_data="{0} line does not cover dataset".format( line_type ), From f670b3816e6c2ab43ae23c08acbcdfc635119429 Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Mon, 17 Feb 2020 14:14:43 -0700 Subject: [PATCH 24/29] minor changes --- matplotcheck/base.py | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/matplotcheck/base.py b/matplotcheck/base.py index 4ccc33ea..9d48e550 100644 --- a/matplotcheck/base.py +++ b/matplotcheck/base.py @@ -367,13 +367,9 @@ def assert_axis_off(self, message="Axis lines are displayed on plot"): if not self.ax.axison: flag = True # Case 2: Check if both axis visibilities set to false -<<<<<<< HEAD elif ( not self.ax.xaxis._visible and not self.ax.yaxis._visible ): -======= - elif not self.ax.xaxis._visible and not self.ax.yaxis._visible: ->>>>>>> 20a080bfff979ec78bb987b179a86ba9a1cde60b flag = True # Case 3: Check if both axis ticks are set to empty lists elif ( @@ -760,13 +756,8 @@ def assert_no_legend_overlap(self, message="Legends overlap eachother"): leg_extent2 = ( legends[j].get_window_extent(RendererBase()).get_points() ) -<<<<<<< HEAD assert ( not self.legends_overlap(leg_extent1, leg_extent2) -======= - assert not self.legends_overlap( - leg_extent1, leg_extent2 ->>>>>>> 20a080bfff979ec78bb987b179a86ba9a1cde60b ), message """ BASIC PLOT DATA FUNCTIONS """ @@ -1150,15 +1141,10 @@ def assert_lines_of_type(self, line_types): self.assert_line( slope_exp, intercept_exp, -<<<<<<< HEAD message_no_line="{0} line is not displayed properly".format ( line_type ), -======= - message_no_line="{0} line is not " - + "displayed properly".format(line_type), ->>>>>>> 20a080bfff979ec78bb987b179a86ba9a1cde60b message_data="{0} line does not cover dataset".format( line_type ), From 65ca30cffddd14c9153907e67ba2d2e29860ab22 Mon Sep 17 00:00:00 2001 From: Nathan Korinek Date: Mon, 17 Feb 2020 14:44:54 -0700 Subject: [PATCH 25/29] Changing to make CI happy, modified to pass black and make -B docs --- matplotcheck/base.py | 12 +++++------- matplotcheck/tests/test_base.py | 12 +++++------- matplotcheck/tests/test_timeseries_module.py | 6 +++--- matplotcheck/vector.py | 2 +- 4 files changed, 14 insertions(+), 18 deletions(-) diff --git a/matplotcheck/base.py b/matplotcheck/base.py index 9d48e550..39afc57e 100644 --- a/matplotcheck/base.py +++ b/matplotcheck/base.py @@ -248,7 +248,7 @@ def assert_title_contains( title = axtitle else: raise ValueError( - 'title_type must be one of the following ' + "title_type must be one of the following " + '["figure", "axes", "either"]' ) @@ -367,9 +367,7 @@ def assert_axis_off(self, message="Axis lines are displayed on plot"): if not self.ax.axison: flag = True # Case 2: Check if both axis visibilities set to false - elif ( - not self.ax.xaxis._visible and not self.ax.yaxis._visible - ): + elif not self.ax.xaxis._visible and not self.ax.yaxis._visible: flag = True # Case 3: Check if both axis ticks are set to empty lists elif ( @@ -756,8 +754,8 @@ def assert_no_legend_overlap(self, message="Legends overlap eachother"): leg_extent2 = ( legends[j].get_window_extent(RendererBase()).get_points() ) - assert ( - not self.legends_overlap(leg_extent1, leg_extent2) + assert not self.legends_overlap( + leg_extent1, leg_extent2 ), message """ BASIC PLOT DATA FUNCTIONS """ @@ -1134,7 +1132,7 @@ def assert_lines_of_type(self, line_types): slope_exp, intercept_exp = 1, 0 else: raise ValueError( - 'each string in line_types must be from the following ' + "each string in line_types must be from the following " + '["regression","onetoone"]' ) diff --git a/matplotcheck/tests/test_base.py b/matplotcheck/tests/test_base.py index c099c4aa..23b1bf0f 100644 --- a/matplotcheck/tests/test_base.py +++ b/matplotcheck/tests/test_base.py @@ -44,8 +44,8 @@ def test_options(pt_line_plt): provided.""" with pytest.raises( - ValueError, - match="Plot_type to test must be either: scatter, bar or line", + ValueError, + match="Plot_type to test must be either: scatter, bar or line", ): pt_line_plt.assert_plot_type("foo") plt.close() @@ -69,8 +69,7 @@ def test_assert_string_contains_fails(pt_line_plt): test_string = "this is a test string" string_expected = ["this", "is", "not", "a", "test"] with pytest.raises( - AssertionError, - match="String does not contain expected string: not" + AssertionError, match="String does not contain expected string: not" ): pt_line_plt.assert_string_contains(test_string, string_expected) plt.close() @@ -91,7 +90,7 @@ def test_assert_string_contains_or_fails(pt_line_plt): test_string = "this is a test string" string_expected = ["this", "is", ["not", "jambalaya"], "a", "test"] with pytest.raises( - AssertionError, match="String does not contain at least one of: " + AssertionError, match="String does not contain at least one of: " ): pt_line_plt.assert_string_contains(test_string, string_expected) plt.close() @@ -112,8 +111,7 @@ def test_assert_string_contains_handles_short_list_fails(pt_line_plt): test_string = "this is a test string" string_expected = [["this"], ["is"], ["not"]] with pytest.raises( - AssertionError, - match="String does not contain expected string: not" + AssertionError, match="String does not contain expected string: not" ): pt_line_plt.assert_string_contains(test_string, string_expected) plt.close() diff --git a/matplotcheck/tests/test_timeseries_module.py b/matplotcheck/tests/test_timeseries_module.py index 32aa53f4..b1be1448 100644 --- a/matplotcheck/tests/test_timeseries_module.py +++ b/matplotcheck/tests/test_timeseries_module.py @@ -1,9 +1,9 @@ -import pytest - ''' def test_assert_xydata_timeseries(pt_time_line_plt, pd_df_timeseries): """Commenting this out for now as this requires a time series data object this is failing because the time data needs to be in seconds like how mpl saves it. """ - pt_time_line_plt.assert_xydata(pd_df_timeseries, xcol='time', ycol='A', xtime=True) + pt_time_line_plt.assert_xydata( + pd_df_timeseries, xcol='time', ycol='A', xtime=True + ) ''' diff --git a/matplotcheck/vector.py b/matplotcheck/vector.py index 53974905..f91f8681 100644 --- a/matplotcheck/vector.py +++ b/matplotcheck/vector.py @@ -339,7 +339,7 @@ def get_lines_by_collection(self): def get_lines_by_attributes(self): """Returns a sorted list of lists where each list contains line segments of the same attributes: - color, linewidth, and linestyle + color, linewidth, and linestyle Returns ------ From 0fb16b4bfcb1bddeb4179248b13430a9b40cd044 Mon Sep 17 00:00:00 2001 From: nkorinek Date: Thu, 20 Feb 2020 09:24:39 -0700 Subject: [PATCH 26/29] Reformatting to make black and flake8 happy. Also updated crs assignment --- matplotcheck/base.py | 3 +-- matplotcheck/tests/conftest.py | 2 +- matplotcheck/tests/test_raster.py | 3 ++- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/matplotcheck/base.py b/matplotcheck/base.py index 39afc57e..46cc940b 100644 --- a/matplotcheck/base.py +++ b/matplotcheck/base.py @@ -1139,8 +1139,7 @@ def assert_lines_of_type(self, line_types): self.assert_line( slope_exp, intercept_exp, - message_no_line="{0} line is not displayed properly".format - ( + message_no_line="{0} line not displayed properly".format( line_type ), message_data="{0} line does not cover dataset".format( diff --git a/matplotcheck/tests/conftest.py b/matplotcheck/tests/conftest.py index 0de7100f..17217454 100644 --- a/matplotcheck/tests/conftest.py +++ b/matplotcheck/tests/conftest.py @@ -64,7 +64,7 @@ def basic_polygon_gdf(basic_polygon): ------- GeoDataFrame containing the basic_polygon polygon. """ - gdf = gpd.GeoDataFrame(geometry=[basic_polygon], crs={"init": "epsg:4326"}) + gdf = gpd.GeoDataFrame(geometry=[basic_polygon], crs="epsg:4326") return gdf diff --git a/matplotcheck/tests/test_raster.py b/matplotcheck/tests/test_raster.py index a2885ec7..7c4d7fd8 100644 --- a/matplotcheck/tests/test_raster.py +++ b/matplotcheck/tests/test_raster.py @@ -296,7 +296,8 @@ def test_raster_assert_image_fullscreen(raster_plt): def test_raster_assert_image_fullscreen_fail_xlims(raster_plt): """assert fullscreen should fail if we modify the x-axis limits""" - cur_xlim, _ = raster_plt.ax.get_xlim(), raster_plt.ax.get_ylim() + cur_xlim = raster_plt.ax.get_xlim() + raster_plt.ax.get_ylim() raster_plt.ax.set_xlim([cur_xlim[0], cur_xlim[1] + 5]) with pytest.raises( AssertionError, match="Image is stretched inaccurately" From 006ac1ccec53d8dcea05e0b88156a0e70eb2ad72 Mon Sep 17 00:00:00 2001 From: nkorinek Date: Thu, 27 Feb 2020 10:17:04 -0700 Subject: [PATCH 27/29] Fixed formatting issue with timeseries --- matplotcheck/timeseries.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/matplotcheck/timeseries.py b/matplotcheck/timeseries.py index 026ff61c..48b14f41 100644 --- a/matplotcheck/timeseries.py +++ b/matplotcheck/timeseries.py @@ -169,12 +169,12 @@ def assert_no_data_value(self, nodata=999.99): xy = self.get_xy(xtime=False) assert ~np.isin( nodata, xy["x"] - ), "Values of {0} have been found in data. Be sure to remove no " - +"data values".format(nodata) + ), "Values of {0} have been found in data. Be sure to remove no " \ + "data values".format(nodata) assert ~np.isin( nodata, xy["y"] - ), "Values of {0} have been found in data. Be sure to remove no " - +"data values".format(nodata) + ), "Values of {0} have been found in data. Be sure to remove no " \ + "data values".format(nodata) def assert_xdata_date( self, x_exp, m="X-axis is not in appropriate date format" From e3376866fd049409e88a0df87911781ff5aa201a Mon Sep 17 00:00:00 2001 From: nkorinek Date: Thu, 27 Feb 2020 10:31:00 -0700 Subject: [PATCH 28/29] Better fix for timeseries formatting --- matplotcheck/timeseries.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/matplotcheck/timeseries.py b/matplotcheck/timeseries.py index 48b14f41..bbed517a 100644 --- a/matplotcheck/timeseries.py +++ b/matplotcheck/timeseries.py @@ -84,7 +84,8 @@ def assert_xticks_locs( loc_exp=None, m="Incorrect X axis tick locations", ): - """Asserts that Axes ax has xaxis ticks as noted by tick_size and loc_exp + """Asserts that Axes ax has xaxis ticks as noted by tick_size and + loc_exp Parameters ---------- @@ -169,12 +170,12 @@ def assert_no_data_value(self, nodata=999.99): xy = self.get_xy(xtime=False) assert ~np.isin( nodata, xy["x"] - ), "Values of {0} have been found in data. Be sure to remove no " \ - "data values".format(nodata) + ), ("Values of {0} have been found in data. Be sure to remove no " + "data values").format(nodata) assert ~np.isin( nodata, xy["y"] - ), "Values of {0} have been found in data. Be sure to remove no " \ - "data values".format(nodata) + ), ("Values of {0} have been found in data. Be sure to remove no " + "data values").format(nodata) def assert_xdata_date( self, x_exp, m="X-axis is not in appropriate date format" From 165afd6d7a51a0c0f35ea10cc1002679137c6819 Mon Sep 17 00:00:00 2001 From: nkorinek Date: Thu, 27 Feb 2020 10:46:44 -0700 Subject: [PATCH 29/29] Black --- matplotcheck/timeseries.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/matplotcheck/timeseries.py b/matplotcheck/timeseries.py index bbed517a..80a0071a 100644 --- a/matplotcheck/timeseries.py +++ b/matplotcheck/timeseries.py @@ -168,14 +168,14 @@ def assert_no_data_value(self, nodata=999.99): """ if nodata: xy = self.get_xy(xtime=False) - assert ~np.isin( - nodata, xy["x"] - ), ("Values of {0} have been found in data. Be sure to remove no " - "data values").format(nodata) - assert ~np.isin( - nodata, xy["y"] - ), ("Values of {0} have been found in data. Be sure to remove no " - "data values").format(nodata) + assert ~np.isin(nodata, xy["x"]), ( + "Values of {0} have been found in data. Be sure to remove no " + "data values" + ).format(nodata) + assert ~np.isin(nodata, xy["y"]), ( + "Values of {0} have been found in data. Be sure to remove no " + "data values" + ).format(nodata) def assert_xdata_date( self, x_exp, m="X-axis is not in appropriate date format"