def test_11_high_blood_pressure3(self):
        scatter_method = spy_decorator(matplotlib.axes.Axes.scatter, "scatter")
        plot_method = spy_decorator(matplotlib.axes.Axes.plot, "plot")
#        with patch("matplotlib.pyplot.scatter", wraps=matplotlib.pyplot.scatter) as pltscatter:
        with patch("matplotlib.pyplot.subplots", wraps=matplotlib.pyplot.subplots) as psubplots,\
             patch.object(matplotlib.axes.Axes, "plot", new=plot_method),\
             patch.object(matplotlib.axes.Axes, "scatter", new=scatter_method):
            exec(exercises[0])
            exec(exercises[1])
            exec(exercises[2])
            exec(exercises[3])
            exec(exercises[9])
            exec(exercises[10])
            exec(exercises[11])
            myfram = locals()["fram"]
            psubplots.assert_called()
            self.assertEqual(scatter_method.mock.call_count, 2,
                          msg="Expected scatter method to be called twice!")
            self.assertEqual(plot_method.mock.call_count, 6,
                             msg="Expected plot method to be called six times!")

            (args1, kwargs1), (args2, kwargs2)  = scatter_method.mock.call_args_list
            self.assertIn(len(args1[0]), [663, 731], msg="Incorrect number of points in subfigure 1!")
            self.assertEqual(len(args1[0]), len(args1[1]), msg="Incorrect number of points in subfigure 1!")

            self.assertIn(len(args2[0]), [663, 731], msg="Incorrect number of points in subfigure 2!")
            self.assertEqual(len(args2[0]), len(args2[1]), msg="Incorrect number of points in subfigure 2!")
    def test_calls(self):
        method = spy_decorator(pd.core.series.Series.corr, "corr")
        f_method = spy_decorator(pd.core.frame.DataFrame.corr, "corr")
        with patch(ph("suicide_fractions"), wraps=suicide_fractions) as psf,\
             patch(ph("pd.read_html"), wraps=pd.read_html) as phtml,\
             patch.object(pd.core.series.Series, "corr", new=method),\
             patch.object(pd.core.frame.DataFrame, "corr", new=f_method),\
             patch(ph("suicide_weather"), wraps=suicide_weather) as psw:
            main()
            psf.assert_called_once()
            psw.assert_called_once()
            phtml.assert_called_once()
            if not f_method.mock.called:
                method.mock.assert_called()
                args, kwargs = method.mock.call_args
            else:
                args, kwargs = f_method.mock.call_args
            correct = ((len(args) > 1 and args[1] == "spearman") or
                       ("method" in kwargs and kwargs["method"] == "spearman"))
            self.assertTrue(correct,
                            msg="You did not compute Spearman correlation!")

        out = get_out()
        self.assertRegex(out,
                         r"Suicide DataFrame has \d+ rows",
                         msg="Output line about Suicide was incorrect!")
        self.assertRegex(out,
                         r"Temperature DataFrame has \d+ rows",
                         msg="Output line about Temperature was incorrect!")
        self.assertRegex(out,
                         r"Common DataFrame has \d+ rows",
                         msg="Output line about Common was incorrect!")
        self.assertRegex(out,
                         r"Spearman correlation:\s+[+-]?\d+\.\d+",
                         msg="Output line about correlation was incorrect!")
    def test_calls(self):
        predict_method = spy_decorator(
            sklearn.naive_bayes.MultinomialNB.predict, "predict")
        score_method = spy_decorator(sklearn.naive_bayes.MultinomialNB.score,
                                     "score")
        fit_method = spy_decorator(sklearn.naive_bayes.MultinomialNB.fit,
                                   "fit")
        with patch(ph("sklearn.model_selection.train_test_split"),
                   wraps=sklearn.model_selection.train_test_split) as tts,\
             patch(ph("sklearn.metrics.accuracy_score"),
                   wraps=sklearn.metrics.accuracy_score) as acs,\
             patch.object(sklearn.naive_bayes.MultinomialNB, "fit", new=fit_method),\
             patch.object(sklearn.naive_bayes.MultinomialNB, "predict", new=predict_method),\
             patch.object(sklearn.naive_bayes.MultinomialNB, "score", new=score_method),\
             patch(ph("sklearn.naive_bayes.MultinomialNB"),
                   wraps=sklearn.naive_bayes.MultinomialNB) as mnb:

            random_state = 7
            accuracy, total, misclassified = spam_detection(random_state,
                                                            fraction=0.1)

            # Check that train_test_split is called with correct parameters
            tts.assert_called_once()
            args, kwargs = tts.call_args
            self.assertIn("random_state",
                          kwargs,
                          msg="You did not specify random_state argument"
                          "to train_test_split function!")
            self.assertEqual(kwargs["random_state"],
                             random_state,
                             msg="Incorrect random_state argument!")
            if "train_size" in kwargs:
                self.assertEqual(kwargs["train_size"],
                                 0.75,
                                 msg="Incorrect train_size argument!")
            if "test_size" in kwargs:
                self.assertEqual(kwargs["test_size"],
                                 0.25,
                                 msg="Incorrect test_size argument!")
            # Check that accuracy_score is called
            self.assertTrue(
                acs.call_count == 1 or score_method.mock.call_count == 1,
                msg=
                "Expected that either the accuracy_score function or the score method is called exactly once!"
            )

            # Check that MultinomialNB is called
            mnb.assert_called_once()

            # Check that fit and predict methods of MultinomialNB object are called
            predict_method.mock.assert_called()
            fit_method.mock.assert_called()
    def test_calls(self):
        row = [2., 2., 0., 2.5, 0.76]
        X, y = make_blobs(100,
                          int(row[0]),
                          centers=int(row[1]),
                          random_state=int(row[2]),
                          cluster_std=row[3])
        predict_method = spy_decorator(sklearn.naive_bayes.GaussianNB.predict,
                                       "predict")
        fit_method = spy_decorator(sklearn.naive_bayes.GaussianNB.fit, "fit")
        with patch(ph("sklearn.model_selection.train_test_split"),
                   wraps=sklearn.model_selection.train_test_split) as tts,\
            patch(ph("sklearn.metrics.accuracy_score"),
                  wraps=sklearn.metrics.accuracy_score) as acs,\
            patch.object(sklearn.naive_bayes.GaussianNB, "fit", new=fit_method),\
            patch.object(sklearn.naive_bayes.GaussianNB, "predict", new=predict_method),\
            patch(ph("sklearn.naive_bayes.GaussianNB"),
                  wraps=sklearn.naive_bayes.GaussianNB) as gnb:

            acc = blob_classification(X, y)

            # Check that train_test_split is called with correct parameters
            tts.assert_called_once()
            args, kwargs = tts.call_args
            self.assertIn("random_state",
                          kwargs,
                          msg="You did not specify random_state argument"
                          "to train_test_split function!")
            self.assertEqual(kwargs["random_state"],
                             0,
                             msg="Incorrect random_state argument!")
            if "train_size" in kwargs:
                self.assertEqual(kwargs["train_size"],
                                 0.75,
                                 msg="Incorrect train_size argument!")
            elif "test_size" in kwargs:
                self.assertEqual(kwargs["test_size"],
                                 0.25,
                                 msg="Incorrect test_size argument!")

            # Check that accuracy_score is called
            acs.assert_called_once()

            # Check that GaussianNB is called
            gnb.assert_called_once()

            # Check that fit and predict methods of GaussianNB object are called
            predict_method.mock.assert_called()
            fit_method.mock.assert_called()
Exemple #5
0
    def test_gaussian(self):
        predict_method = spy_decorator(sklearn.naive_bayes.GaussianNB.predict,
                                       "predict")
        fit_method = spy_decorator(sklearn.naive_bayes.GaussianNB.fit, "fit")

        with patch.object(sklearn.naive_bayes.GaussianNB, "fit", new=fit_method),\
             patch.object(sklearn.naive_bayes.GaussianNB, "predict", new=predict_method),\
             patch(ph('sklearn.naive_bayes.GaussianNB'),
                   wraps=sklearn.naive_bayes.GaussianNB) as mock_gaussian:
            acc = plant_classification()
            mock_gaussian.assert_called_once()

            # Check that fit and predict methods of GaussianNB object are called
            predict_method.mock.assert_called()
            fit_method.mock.assert_called()
    def test_08_sbp_with_cigarets(self):
        plot_method = spy_decorator(pd.core.frame.DataFrame.plot.scatter, "scatter")
        with patch("matplotlib.pyplot.scatter", wraps=matplotlib.pyplot.scatter) as pltscatter,\
             patch.object(pd.core.frame.DataFrame.plot, "scatter", new=plot_method),\
             patch("statsmodels.graphics.regressionplots.abline_plot",
                   wraps=statsmodels.graphics.regressionplots.abline_plot) as abplot:
            exec(exercises[0])
            exec(exercises[1])
            exec(exercises[2])
            exec(exercises[3])
            exec(exercises[8])
            myfit = locals()["fit"]
            self.assertIn("sCIG", myfit.params, msg="Missing explanatory variable sCIG!")
            self.assertAlmostEqual(myfit.params.sCIG, 3.7733, places=2,
                                   msg="Incorrect coefficient for sCIG!")
            interaction = find_interaction("sFRW", "sCIG", myfit.params)

            found = interaction is not None
            self.assertTrue(found, msg="Missing explanatory variable sFRW:sCIG!")
            self.assertAlmostEqual(myfit.params[interaction], 3.6765, places=2,
                                   msg="Incorrect coefficient for sFRW:sCIG!")
            self.assertEqual(len(myfit.params), 16, msg="Expected 15 explanatory variables and an intercept!")
            #abplot.assert_called()
            self.assertEqual(abplot.call_count, 3, msg="Expected abline_plot to be called three times!")
            self.assertTrue(pltscatter.call_count > 0 or plot_method.mock.call_count > 0,
                            msg="Expected call to make a scatter plot!")
Exemple #7
0
 def test_calls(self):
     merge_method = spy_decorator(pd.core.frame.DataFrame.merge, "merge")
     with patch(ph("cycling_weather_continues"), wraps=cycling_weather_continues) as pcw,\
          patch(ph("sklearn.linear_model.LinearRegression"), wraps=sklearn.linear_model.LinearRegression) as lr, \
          patch(ph("pd.read_csv"), wraps=pd.read_csv) as prc,\
          patch.object(pd.core.frame.DataFrame, "merge", new=merge_method),\
          patch(ph("pd.merge"), wraps=pd.merge) as pmerge:
         main()
         pcw.assert_called_once()
         lr.assert_called_once()
         print(type(lr))
         if "fit_intercept" in lr.call_args[1]:
             self.assertTrue(lr.call_args[1]["fit_intercept"],
                             msg="You did not fit the intercept!")
         elif len(lr.call_args[0]) > 0:
             self.assertTrue(lr.call_args[0][0],
                             msg="You did not fit the intercept!")
         merge_method_called = merge_method.mock.call_count >= 1
         merge_func_called = pmerge.call_count >= 1
         self.assertTrue(merge_method_called or merge_func_called,
                         msg="You did not call merge method or function!")
         self.assertEqual(
             prc.call_count,
             2,
             msg="You should have called pd.read_csv exactly twice")
    def test_calls(self):
        merge_method = spy_decorator(pd.core.frame.DataFrame.merge, "merge")
        with patch(ph("top_bands"), wraps=top_bands) as ptop,\
            patch(ph("pd.read_csv"), wraps=pd.read_csv) as prc,\
            patch.object(pd.core.frame.DataFrame, "merge", new=merge_method),\
            patch(ph("pd.merge"), wraps=pd.merge) as pmerge:
            main()
            ptop.assert_called_once()
            self.assertEqual(
                prc.call_count,
                2,
                msg="You should have called pd.read_csv exactly twice")
            self.assertTrue(pmerge.call_count == 1
                            or merge_method.mock.call_count == 1,
                            msg="Call merge exactly once!")

            if pmerge.call_count >= 1:
                args, kwargs = pmerge.call_args  # function called
            else:
                args, kwargs = merge_method.mock.call_args  # method called

            self.assertTrue(
                "left_on" in kwargs,
                msg="You should have used 'left_on' argument of pd.merge!")
            self.assertTrue(
                "right_on" in kwargs,
                msg="You should have used 'right_on' argument of pd.merge!")
            params = [kwargs["left_on"], kwargs["right_on"]]
            self.assertTrue(
                ("Artist" in params or ["Artist"] in params)
                and ("Band" in params or ["Band"] in params),
                msg="You should have merged on 'Artist' and 'Band' columns!")
Exemple #9
0
 def test_accuracy_called(self):
     score_method = spy_decorator(sklearn.naive_bayes.GaussianNB.score,
                                  "score")
     with patch(ph('sklearn.metrics.accuracy_score'),
                side_effect=sklearn.metrics.accuracy_score) as accuracy, \
          patch.object(sklearn.naive_bayes.GaussianNB, "score", new=score_method):
         acc = plant_classification()
         try:
             score_method.assert_called_once()
         except:
             accuracy.assert_called_once()
 def test_calls(self):
     method = spy_decorator(pd.core.frame.DataFrame.groupby, "groupby") 
     with patch(ph("suicide_fractions"), wraps=suicide_fractions) as psf,\
          patch.object(pd.core.frame.DataFrame, "groupby", new=method) as pgroupby,\
          patch(ph("pd.read_csv"), wraps=pd.read_csv) as prc:
         main()
         psf.assert_called_once()
         prc.assert_called_once()
         method.mock.assert_called_once()
         args, kwargs = method.mock.call_args
         correct = ((len(args) > 0 and args[0]== "country") or
                    ("by" in kwargs and kwargs["by"] == "country"))
         self.assertTrue(correct, msg="Wrong or missing argument to groupby method!")
Exemple #11
0
 def test_called(self):
     method = spy_decorator(pd.core.frame.DataFrame.dropna, "dropna")
     with patch.object(pd.core.frame.DataFrame, "dropna", new=method):
         df = cyclists()
         method.mock.assert_called()
         self.assertEqual(method.mock.call_count,
                          2,
                          msg="Expected dropna method to be called twice!")
         for args, kwargs in method.mock.call_args_list:
             self.assertEqual(
                 kwargs["how"],
                 "all",
                 msg="Expected parameter 'all' to parameter 'how'!")
 def test_calls(self):
     method = spy_decorator(pd.core.frame.DataFrame.groupby, "groupby")
     with patch(ph("commute"), wraps=commute) as pcommute,\
          patch.object(pd.core.frame.DataFrame, "groupby", new=method),\
          patch(ph("pd.read_csv"), wraps=pd.read_csv) as prc,\
          patch(ph("plt.show")) as pshow,\
          patch(ph("pd.to_datetime"), wraps=pd.to_datetime) as pdatetime:
         main()
         pcommute.assert_called_once()
         prc.assert_called_once()
         pshow.assert_called_once()
         pdatetime.assert_called()
         method.mock.assert_called()
 def test_calls(self):
     method = spy_decorator(pd.core.frame.DataFrame.plot, "plot")
     with patch(ph("cyclists_per_day"), wraps=cyclists_per_day) as pcpd,\
          patch.object(pd.core.frame.DataFrame, "plot", new=method),\
          patch(ph("plt.plot")) as pplot,\
          patch(ph("plt.show")) as pshow:
         main()
         pcpd.assert_called_once()
         func_called = pplot.call_count == 1
         method_called = method.mock.call_count == 1
         self.assertTrue(
             func_called or method_called,
             msg=
             "You must call either plt.plot or plot method of a DataFrame!")
         pshow.assert_called_once()
 def test_01_load(self):
     #exec(exercises[0])
     describe_method = spy_decorator(pd.core.frame.DataFrame.describe, "describe")
     with patch("pandas.read_csv", wraps=pd.read_csv) as prc,\
          patch.object(pd.core.frame.DataFrame, "describe", new=describe_method):
         exec(exercises[1])
         prc.assert_called()
         #fram=int()
         self.assertTrue("fram" in locals(), msg="DataFrame 'fram' was not loaded!")
         myfram = locals()["fram"]
         self.assertIsInstance(myfram, pd.core.frame.DataFrame,
                               msg="'fram' is not a DataFrame object!")
         self.assertEqual(myfram.shape, (1394, 14),
                          msg="The read DataFrame had incorrect shape!")
         #koe.assert_called()
         describe_method.mock.assert_called()
 def test_07_sbp_with_interactions_visualization(self):
     plot_method = spy_decorator(pd.core.frame.DataFrame.plot.scatter, "scatter")
     with patch("matplotlib.pyplot.scatter", wraps=matplotlib.pyplot.scatter) as pltscatter,\
          patch.object(pd.core.frame.DataFrame.plot, "scatter", new=plot_method),\
          patch("statsmodels.graphics.regressionplots.abline_plot",
                wraps=statsmodels.graphics.regressionplots.abline_plot) as abplot:
         exec(exercises[0])
         exec(exercises[1])
         exec(exercises[2])
         exec(exercises[3])
         exec(exercises[6])
         exec(exercises[7])
         myfit = locals()["fit"]
         #abplot.assert_called()
         self.assertEqual(abplot.call_count, 3, msg="Expected abline_plot to be called three times!")
         self.assertTrue(pltscatter.call_count > 0 or plot_method.mock.call_count > 0,
                         msg="Expected call to make a scatter plot!")
Exemple #16
0
 def test_pca(self):
     fit_method = spy_decorator(sklearn.decomposition.PCA.fit, "fit")
     with patch.object(sklearn.decomposition.PCA, "fit", new=fit_method),\
          patch(ph("sklearn.decomposition.PCA"), wraps=sklearn.decomposition.PCA) as mypca:
         v, ev = explained_variance()
         mypca.assert_called_once()
         args, kwargs = mypca.call_args
         if len(args) > 0:
             self.assertEqual(args[0],
                              10,
                              msg="Expected parameter 10 to PCA function!")
         fit_method.mock.assert_called()
         args, kwargs = fit_method.mock.call_args
         df = args[0]
         self.assertEqual(
             df.shape[0],
             400,
             msg="Incorrect number of rows in DataFrame to 'fit' method!")
         self.assertEqual(
             df.shape[1],
             10,
             msg="Incorrect number of columns in DataFrame to 'fit' method!"
         )