Best Python code snippet using pytest
test_install.py
Source:test_install.py
...278# @skip_if_no_mock279# def test_calls_islink(self):280# with self.generate_mocks() as mocks:281# some_path = self.generate_random_path282# conda.common.disk.rm_rf(some_path)283# mocks['islink'].assert_called_with(some_path)284#285# @skip_if_no_mock286# def test_calls_unlink_on_true_islink(self):287# with self.generate_mocks() as mocks:288# some_path = self.generate_random_path289# conda.common.disk.rm_rf(some_path)290# mocks['unlink'].assert_called_with(some_path)291#292# @skip_if_no_mock293# def test_calls_rename_if_unlink_fails(self):294# with self.generate_mocks() as mocks:295# mocks['unlink'].side_effect = OSError(errno.ENOEXEC, "blah")296# some_path = self.generate_random_path297# conda.common.disk.rm_rf(some_path)298# assert mocks['unlink'].call_count > 1299# assert mocks['rename'].call_count == 1300# rename_args = mocks['rename'].call_args[0]301# assert rename_args[0] == mocks['unlink'].call_args_list[0][0][0]302# assert dirname(rename_args[1]) in (ca[0][0] for ca in mocks['unlink'].call_args_list)303#304# @skip_if_no_mock305# def test_calls_unlink_on_os_access_false(self):306# with self.generate_mocks(os_access=False) as mocks:307# some_path = self.generate_random_path308# conda.common.disk.rm_rf(some_path)309# mocks['unlink'].assert_called_with(some_path)310#311# @skip_if_no_mock312# def test_does_not_call_isfile_if_islink_is_true(self):313# with self.generate_mocks() as mocks:314# some_path = self.generate_random_path315# conda.common.disk.rm_rf(some_path)316# self.assertFalse(mocks['isfile'].called)317#318# @skip_if_no_mock319# def test_calls_isfile_with_path(self):320# with self.generate_mocks(islink=False, isfile=True) as mocks:321# some_path = self.generate_random_path322# conda.common.disk.rm_rf(some_path)323# mocks['isfile'].assert_called_with(some_path)324#325# @skip_if_no_mock326# def test_calls_unlink_on_false_islink_and_true_isfile(self):327# with self.generate_mocks(islink=False, isfile=True) as mocks:328# some_path = self.generate_random_path329# conda.common.disk.rm_rf(some_path)330# mocks['unlink'].assert_called_with(some_path)331#332# @skip_if_no_mock333# def test_does_not_call_unlink_on_false_values(self):334# with self.generate_mocks(islink=False, isfile=False) as mocks:335# some_path = self.generate_random_path336# conda.common.disk.rm_rf(some_path)337# self.assertFalse(mocks['unlink'].called)338#339# @skip_if_no_mock340# def test_does_not_call_shutil_on_false_isdir(self):341# with self.generate_all_false_mocks() as mocks:342# some_path = self.generate_random_path343# conda.common.disk.rm_rf(some_path)344# self.assertFalse(mocks['rmtree'].called)345#346# @skip_if_no_mock347# def test_calls_rmtree_at_least_once_on_isdir_true(self):348# with self.generate_directory_mocks() as mocks:349# some_path = self.generate_random_path350# conda.common.disk.rm_rf(some_path)351# mocks['rmtree'].assert_called_with(352# some_path, onerror=warn_failed_remove, ignore_errors=False)353#354# @skip_if_no_mock355# def test_calls_rmtree_and_rename_on_win(self):356# with self.generate_directory_mocks(on_win=True) as mocks:357# some_path = self.generate_random_path358# conda.common.disk.rm_rf(some_path)359# assert mocks['rename'].call_count == 1360# assert mocks['rmtree'].call_count == 1361# assert mocks['rename'].call_args[0][1] == mocks['rmtree'].call_args[0][0]362#363# @skip_if_no_mock364# def test_calls_rmtree_and_rename_on_unix(self):365# with self.generate_directory_mocks() as mocks:366# mocks['rmtree'].side_effect = OSError367# some_path = self.generate_random_path368# conda.common.disk.rm_rf(some_path)369# assert mocks['rename'].call_count == 1370# assert mocks['rmtree'].call_count > 1371# assert dirname(mocks['rename'].call_args[0][1]) == mocks['rmtree'].call_args[0][0]372#373# @skip_if_no_mock374# def test_calls_rmtree_only_once_on_success(self):375# with self.generate_directory_mocks() as mocks:376# some_path = self.generate_random_path377# conda.common.disk.rm_rf(some_path)378# self.assertEqual(1, mocks['rmtree'].call_count)379#380# @skip_if_no_mock381# def test_raises_final_exception_if_it_cant_remove(self):382# with self.generate_directory_mocks(on_win=True) as mocks:383# mocks['rmtree'].side_effect = OSError384# mocks['rename'].side_effect = OSError385# some_path = self.generate_random_path386# with self.assertRaises(OSError):387# conda.common.disk.rm_rf(some_path, trash=False)388#389# @skip_if_no_mock390# def test_retries_six_times_to_ensure_it_cant_really_remove(self):391# with self.generate_directory_mocks() as mocks:392# mocks['rmtree'].side_effect = OSError393# some_path = self.generate_random_path394# with self.assertRaises(OSError):395# conda.common.disk.rm_rf(some_path, trash=False)396# self.assertEqual(6, mocks['rmtree'].call_count)397#398# @skip_if_no_mock399# def test_retries_as_many_as_max_retries_plus_one(self):400# max_retries = random.randint(7, 10)401# with self.generate_directory_mocks() as mocks:402# mocks['rmtree'].side_effect = OSError403# some_path = self.generate_random_path404# with self.assertRaises(OSError):405# conda.common.disk.rm_rf(some_path, max_retries=max_retries, trash=False)406# self.assertEqual(max_retries + 1, mocks['rmtree'].call_count)407#408# @skip_if_no_mock409# def test_stops_retrying_after_success(self):410# with self.generate_directory_mocks() as mocks:411# mocks['rmtree'].side_effect = [OSError, OSError, None]412# some_path = self.generate_random_path413# conda.common.disk.rm_rf(some_path, trash=False)414# self.assertEqual(3, mocks['rmtree'].call_count)415#416# @skip_if_no_mock417# def test_pauses_for_same_number_of_seconds_as_max_retries(self):418# with self.generate_directory_mocks() as mocks:419# mocks['rmtree'].side_effect = OSError420# max_retries = random.randint(1, 10)421# with self.assertRaises(OSError):422# conda.common.disk.rm_rf(self.generate_random_path,423# max_retries=max_retries, trash=False)424#425# expected = [mock.call(i) for i in range(max_retries)]426# mocks['sleep'].assert_has_calls(expected)427#428# @skip_if_no_mock429# def test_logs_messages_generated_for_each_retry(self):430# with self.generate_directory_mocks() as mocks:431# random_path = self.generate_random_path432# mocks['rmtree'].side_effect = OSError(random_path)433# max_retries = random.randint(1, 10)434# with self.assertRaises(OSError):435# conda.common.disk.rm_rf(random_path, max_retries=max_retries, trash=False)436#437# log_template = "\n".join([438# "Unable to delete %s" % random_path,439# "%s" % OSError(random_path),440# "Retrying after %d seconds...",441# ])442#443# expected_call_list = [mock.call(log_template % i)444# for i in range(max_retries)]445# mocks['log'].debug.assert_has_calls(expected_call_list)446#447# @skip_if_no_mock448# def test_tries_extra_kwarg_on_windows(self):449# with self.generate_directory_mocks(on_win=True) as mocks:450# random_path = self.generate_random_path451# mocks['rmtree'].side_effect = [OSError, None]452# conda.common.disk.rm_rf(random_path, trash=False)453#454# expected_call_list = [455# mock.call(random_path, ignore_errors=False, onerror=warn_failed_remove),456# mock.call(random_path, onerror=install._remove_readonly)457# ]458# mocks['rmtree'].assert_has_calls(expected_call_list)459# self.assertEqual(2, mocks['rmtree'].call_count)460# def test_dist2():461# for name in ('python', 'python-hyphen', ''):462# for version in ('2.7.0', '2.7.0rc1', ''):463# for build in ('0', 'py27_0', 'py35_0+g34fe21', ''):464# for channel in ('defaults', 'test', 'test-hyphen', 'http://bremen',465# 'https://anaconda.org/mcg', '<unknown>'):466# dist_noprefix = name + '-' + version + '-' + build...
FSM_HW3-3.py
Source:FSM_HW3-3.py
1# -*- coding: utf-8 -*-2"""3Created on Mon Oct 5 19:12:30 20204@author: AllenPC5"""6import pandas as pd7import numpy as np8import matplotlib.pyplot as plt9import scipy.optimize as solver10from functools import reduce11import pandas_datareader as pdr12import argparse13import statsmodels.api as sm 14df = pd.read_csv('dow_com_2000_2006.csv', index_col='datadate')15comp = ['DIS','MCD','BA']16df = df[['tic','prccd']]17df_1 = df.loc[df.loc[:,'tic']==comp[0]]18df_1 = df_1['prccd']19df_2 = df.loc[df.loc[:,'tic']==comp[1]]20df_2 = df_2['prccd']21df_3 = df.loc[df.loc[:,'tic']==comp[2]]22df_3 = df_3['prccd']23ret_1 = (df_1 / df_1.shift(1)) - 124ret_1 = ret_1.dropna().rename(comp[0])25ret_2 = (df_2 / df_2.shift(1)) - 126ret_2 = ret_2.dropna().rename(comp[1])27ret_3 = (df_3 / df_3.shift(1)) - 128ret_3 = ret_3.dropna().rename(comp[2])29returns = pd.concat([ret_1, ret_2, ret_3], axis=1)30total_stock = len(returns.columns)31covariance_matrix = returns.cov() * 25232stocks_expected_return = returns.mean() * 25233stocks_weights = np.array([1/3, 1/3, 1/3])#, .1,.1,.1,.1,.1,.1,.1])34portfolio_return = sum(stocks_weights * stocks_expected_return)35portfolio_risk = np.sqrt(reduce(np.dot, [stocks_weights, covariance_matrix, stocks_weights.T]))36print('åè¡å¹³åæ¶ç(6å¹´): ' +comp[0]+':' +str(round(stocks_expected_return[0],4)) +' '37 +comp[1]+':' +str(round(stocks_expected_return[1],4)) +' '38 +comp[2]+':' +str(round(stocks_expected_return[2],4)))39print('(å¹³åé
ç½®)æè³çµåé æå ±é
¬ççº: '+ str(round(portfolio_return,4)))40print('(å¹³åé
ç½®)æè³çµå風éªçº: ' + str(round(portfolio_risk,4)))41##########################################################################42def standard_deviation(weights):43 return np.sqrt(reduce(np.dot, [weights, covariance_matrix, weights.T]))44########################################################45'''æçåç·£(Efficient Frontier)'''46x0 = stocks_weights47bounds = tuple((0, 1) for x in range(total_stock))48efficient_fronter_return_range = np.arange(0.02, 0.18, .001)49efficient_fronter_risk_list = []50portfolio_weights = []51for i in efficient_fronter_return_range:52 constraints1 = [{'type': 'eq', 'fun': lambda x: sum(x) - 1},53 {'type': 'eq', 'fun': lambda x: sum(x * stocks_expected_return) - i}]54 efficient_fronter = solver.minimize(standard_deviation, x0=x0, constraints=constraints1, bounds=bounds)55 efficient_fronter_risk_list.append(efficient_fronter.fun)56 portfolio_weights.append(efficient_fronter.x)57'''è³æ¬å¸å ´ç·(Capital Market Line)'''58x0 = stocks_weights59bounds = tuple((0, 1) for x in range(total_stock))60# efficient_fronter_return_range = np.arange(0.02, 0.15, .003)61CML_risk_list = []62for i in efficient_fronter_return_range:63 constraints2 = [{'type': 'eq', 'fun': lambda x: 0.02 + sum(x * (stocks_expected_return-0.02)) - i}]64 efficient_fronter = solver.minimize(standard_deviation, x0=x0, constraints=constraints2, bounds=bounds)65 CML_risk_list.append(efficient_fronter.fun)66 # portfolio_weights.append(efficient_fronter.x)67 68'''åé»(Tangency Portfolio)'''69TP_idx = np.argmin(abs(np.array(CML_risk_list) - np.array(efficient_fronter_risk_list)))70[TP_x, TP_y] = [CML_risk_list[TP_idx], efficient_fronter_return_range[TP_idx]]71### åé»æè³çµåå¦ä¸72# åé»æè³çµåé æå ±é
¬ççº: TP_y73# åé»æè³çµå風éªçº: TP_x74print('åé»æè³çµåé æå ±é
¬ççº:' + str(round(TP_y,3)))75print('åé»æè³çµå風éªçº:' + str(round(TP_x,3)))76Tangency_portfolio_weights = portfolio_weights[TP_idx]77for i in range(total_stock):78 print(str(returns.columns[i])+' ä½æè³çµåæ¬é : ' + str(round(Tangency_portfolio_weights[i],4)))79###################80risk_free = 0.0281Rf = 0.02/25282portfolio_Rm = np.sum(Tangency_portfolio_weights * returns,axis=1)83Rm_Rf = portfolio_Rm - Rf84ret1_Rf = ret_1 - Rf85X1 = sm.add_constant(Rm_Rf) #ä½¿ç¨ sm.add_constant() å¨ array ä¸å å
¥ä¸å常项1ã86reg = sm.OLS(ret1_Rf, X1).fit()87y_fitted = reg.fittedvalues88reg.summary()89fig = plt.figure(figsize = (10,6))90fig_fn = 'CAPM Linear Regression (' +comp[0]+')'91ax = fig.add_subplot()92ax.plot(Rm_Rf, ret1_Rf, 'o')93ax.set_title(fig_fn, fontsize=18, fontweight='bold')94# ax.plot(Rm_Rf, beta * Rm_Rf + alpha, '-', color = 'r')95ax.plot(Rm_Rf, y_fitted, '-', color = 'r')96fig.savefig(fig_fn+'.png',dpi=300)97###################98portfolio_Rm = np.sum(Tangency_portfolio_weights * returns,axis=1)99Rm_Rf = portfolio_Rm - Rf100ret2_Rf = ret_2 - Rf101X1 = sm.add_constant(Rm_Rf) #ä½¿ç¨ sm.add_constant() å¨ array ä¸å å
¥ä¸å常项1ã102reg = sm.OLS(ret2_Rf, X1).fit()103y_fitted = reg.fittedvalues104reg.summary()105fig = plt.figure(figsize = (10,6))106fig_fn = 'CAPM Linear Regression (' +comp[1]+')'107ax = fig.add_subplot()108ax.plot(Rm_Rf, ret2_Rf, 'o')109ax.set_title(fig_fn, fontsize=18, fontweight='bold')110# ax.plot(Rm_Rf, beta * Rm_Rf + alpha, '-', color = 'r')111ax.plot(Rm_Rf, y_fitted, '-', color = 'r')112fig.savefig(fig_fn+'.png',dpi=300)113###################114portfolio_Rm = np.sum(Tangency_portfolio_weights * returns,axis=1)115Rm_Rf = portfolio_Rm - Rf116ret3_Rf = ret_3 - Rf117X1 = sm.add_constant(Rm_Rf) #ä½¿ç¨ sm.add_constant() å¨ array ä¸å å
¥ä¸å常项1ã118reg = sm.OLS(ret3_Rf, X1).fit()119y_fitted = reg.fittedvalues120reg.summary()121fig = plt.figure(figsize = (10,6))122fig_fn = 'CAPM Linear Regression (' +comp[2]+')'123ax = fig.add_subplot()124ax.plot(Rm_Rf, ret3_Rf, 'o')125ax.set_title(fig_fn, fontsize=18, fontweight='bold')126# ax.plot(Rm_Rf, beta * Rm_Rf + alpha, '-', color = 'r')127ax.plot(Rm_Rf, y_fitted, '-', color = 'r')128fig.savefig(fig_fn+'.png',dpi=300)129########################################################################130# beta, alpha = np.polyfit(ret_1, Rm_Rf, 1)...
test_delete.py
Source:test_delete.py
...23 assert isfile(test_path)24 _try_open(test_path)25 _make_read_only(test_path)26 pytest.raises((IOError, OSError), _try_open, test_path)27 assert rm_rf(test_path)28 assert not isfile(test_path)29def test_remove_file_to_trash():30 with tempdir() as td:31 test_path = join(td, 'test_path')32 touch(test_path)33 assert isfile(test_path)34 _try_open(test_path)35 _make_read_only(test_path)36 pytest.raises((IOError, OSError), _try_open, test_path)37 assert rm_rf(test_path)38 assert not isfile(test_path)39def test_remove_dir():40 with tempdir() as td:41 test_path = join(td, 'test_path')42 touch(test_path)43 _try_open(test_path)44 assert isfile(test_path)45 assert isdir(td)46 assert not islink(test_path)47 assert rm_rf(td)48 assert rm_rf(test_path)49 assert not isdir(td)50 assert not isfile(test_path)51 assert not lexists(test_path)52def test_remove_link_to_file():53 with tempdir() as td:54 dst_link = join(td, "test_link")55 src_file = join(td, "test_file")56 _write_file(src_file, "welcome to the ministry of silly walks")57 if not softlink_supported(src_file, td) and on_win:58 pytest.skip("softlink not supported")59 symlink(src_file, dst_link)60 assert isfile(src_file)61 assert not islink(src_file)62 assert islink(dst_link)63 assert rm_rf(dst_link)64 assert isfile(src_file)65 assert rm_rf(src_file)66 assert not isfile(src_file)67 assert not islink(dst_link)68 assert not lexists(dst_link)69@pytest.mark.xfail(on_win, reason="Windows permission errors make a mess here")70def test_remove_link_to_dir():71 with tempdir() as td:72 dst_link = join(td, "test_link")73 src_dir = join(td, "test_dir")74 test_file = join(td, "test_file")75 mkdir_p(src_dir)76 touch(test_file)77 assert isdir(src_dir)78 assert not islink(src_dir)79 assert not islink(dst_link)80 if not softlink_supported(test_file, td) and on_win:81 pytest.skip("softlink not supported")82 symlink(src_dir, dst_link)83 assert islink(dst_link)84 assert rm_rf(dst_link)85 assert not isdir(dst_link)86 assert not islink(dst_link)87 assert not lexists(dst_link)88 assert isdir(src_dir)89 assert rm_rf(src_dir)90 assert not isdir(src_dir)91 assert not islink(src_dir)92def test_rm_rf_does_not_follow_symlinks():93 with TemporaryDirectory() as tmp:94 # make a file in some temp folder95 real_file = os.path.join(tmp, 'testfile')96 with open(real_file, 'w') as f:97 f.write('weee')98 # make a subfolder99 subdir = os.path.join(tmp, 'subfolder')100 os.makedirs(subdir)101 # link to the file in the subfolder102 link_path = join(subdir, 'file_link')103 if not softlink_supported(real_file, tmp) and on_win:104 pytest.skip("softlink not supported")105 create_link(real_file, link_path, link_type=LinkType.softlink)106 assert islink(link_path)107 # rm_rf the subfolder108 rm_rf(subdir)109 # assert that the file still exists in the root folder110 assert os.path.isfile(real_file)111def test_move_to_trash():112 with tempdir() as td:113 test_path = join(td, 'test_path')114 touch(test_path)115 _try_open(test_path)116 assert isdir(td)117 assert isfile(test_path)118 move_to_trash(td, test_path)119 assert not isfile(test_path)120def test_move_path_to_trash_couldnt():121 from conda.gateways.disk.delete import move_path_to_trash122 with tempdir() as td:...
racon_test.py
Source:racon_test.py
...10 fa_to_polish = os.path.join(data_dir, "run_racon.to_polish.fa")11 seq_to_polish = utils.load_single_seq_fasta(fa_to_polish)12 reads = os.path.join(data_dir, "run_racon.reads.fa")13 pre_out = "tmp.run_racon"14 utils.rm_rf(f"{pre_out}.sam")15 utils.rm_rf(f"{pre_out}.to_polish.fa")16 polished1 = racon.run_racon(seq_to_polish, reads, pre_out, debug=True)17 assert polished1 != fa_to_polish18 assert (19 polished120 == "CGTTAATCCTAGGGCAGTTAAAAGCCCCATTTTGTACAGCTTTTTCTAGAACAGTCAGGGCGCGCTCCCAGGAGTTGCTTCGCTTCCAGCTAGAAATGATCATCGAACCTGGGTAAGGGCATAATACGAGAATGCTGCCCTATTGCCAGTGCTTAGAAATGGACTGGTGTTACGTCCACGAAATCTGCAACAAGCCCGGT"21 )22 # we used debug mode, so intermediate files should be left on disk23 assert os.path.exists(f"{pre_out}.sam")24 assert os.path.exists(f"{pre_out}.to_polish.fa")25 os.unlink(f"{pre_out}.sam")26 os.unlink(f"{pre_out}.to_polish.fa")27 # Another round of polishing shouldn't do anything28 polished2 = racon.run_racon(polished1, reads, pre_out, debug=False)29 assert polished1 == polished230 # we didn't use debug mode so intermediate files should be deleted31 assert not os.path.exists(f"{pre_out}.sam")32 assert not os.path.exists(f"{pre_out}.to_polish.fa")33def test_run_racon_bad_data():34 fa_to_polish = os.path.join(data_dir, "run_racon.to_polish.fa")35 seq_to_polish = utils.load_single_seq_fasta(fa_to_polish)36 reads = os.path.join(data_dir, "run_racon_bad_reads.fa")37 pre_out = "tmp.run_racon"38 utils.rm_rf(f"{pre_out}.sam")39 utils.rm_rf(f"{pre_out}.to_polish.fa")40 polished = racon.run_racon(seq_to_polish, reads, pre_out, debug=True)41 utils.rm_rf(f"{pre_out}.sam")42 utils.rm_rf(f"{pre_out}.to_polish.fa")43 assert polished is None44def test_run_racon_iterations():45 # A bit hard to come with small artificial test data for this one.46 # We'll just use the same data as for test_run_racon. Should stop after47 # 2 iterations because only the first run corrects anything48 fa_to_polish = os.path.join(data_dir, "run_racon.to_polish.fa")49 seq_to_polish = utils.load_single_seq_fasta(fa_to_polish)50 reads = os.path.join(data_dir, "run_racon.reads.fa")51 outdir = "tmp.run_racon_iterations"52 utils.rm_rf(outdir)53 got_polished = racon.run_racon_iterations(54 seq_to_polish, reads, outdir, max_iterations=3, debug=True55 )56 for i in range(2):57 outprefix = os.path.join(outdir, f"racon.{i}")58 assert os.path.exists(f"{outprefix}.sam")59 assert os.path.exists(f"{outprefix}.polished.fa")60 assert os.path.exists(f"{outprefix}.to_polish.fa")61 assert len(os.listdir(outdir)) == 662 assert (63 got_polished64 == "CGTTAATCCTAGGGCAGTTAAAAGCCCCATTTTGTACAGCTTTTTCTAGAACAGTCAGGGCGCGCTCCCAGGAGTTGCTTCGCTTCCAGCTAGAAATGATCATCGAACCTGGGTAAGGGCATAATACGAGAATGCTGCCCTATTGCCAGTGCTTAGAAATGGACTGGTGTTACGTCCACGAAATCTGCAACAAGCCCGGT"65 )66 utils.rm_rf(outdir)67def test_run_racon_iterations_bad_data():68 fa_to_polish = os.path.join(data_dir, "run_racon.to_polish.fa")69 seq_to_polish = utils.load_single_seq_fasta(fa_to_polish)70 reads = os.path.join(data_dir, "run_racon_bad_reads.fa")71 outdir = "tmp.run_racon_iterations"72 utils.rm_rf(outdir)73 got_polished = racon.run_racon_iterations(74 seq_to_polish, reads, outdir, max_iterations=3, debug=True75 )76 assert got_polished is None...
Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.
Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.
https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP
Get 100 minutes of automation test minutes FREE!!