How to use setupenv method in tox

Best Python code snippet using tox_python

test_basic.py

Source: test_basic.py Github

copy

Full Screen

1import unittest2import code3from code.baseline_network import BaselineNetwork4from code.network_utils import build_mlp, np2torch5from code.policy_gradient import PolicyGradient6from code.config import get_config7import gym8import numpy as np9import torch10import builtins11# Suppress unnecessary logging12# gym.logging.disable(gym.logging.FATAL)13builtins.config = None14class TestBasic(unittest.TestCase):15 def setUp(self):16 self.pg = None17 builtins.config = None18 def setUpEnv(self, env_name):19 np.random.seed(0)20 config = get_config(env_name, True)21 self.env = gym.make(config.env_name)22 builtins.config = config23 self.pg = PolicyGradient(self.env, config, seed=1)24 self.policy = self.pg.policy25 self.baseline = BaselineNetwork(self.env, config)26 self.rand_obs = np.random.randn(10, self.pg.observation_dim)27 def test_policy_optimizer_exists(self):28 self.setUpEnv("cartpole")29 self.assertTrue(hasattr(self.pg, "optimizer"))30 self.assertTrue(isinstance(self.pg.optimizer, torch.optim.Optimizer))31 def test_baseline_optimizer_exists(self):32 self.setUpEnv("cartpole")33 self.assertTrue(hasattr(self.baseline, "optimizer"))34 self.assertTrue(isinstance(self.baseline.optimizer, torch.optim.Optimizer))35 def test_get_returns_zero(self):36 self.setUpEnv("cartpole")37 paths = [{"reward": np.zeros(11)}]38 returns = self.pg.get_returns(paths)39 expected = np.zeros(11)40 self.assertEqual(returns.shape, (11,))41 diff = np.sum((returns - expected) ** 2)42 self.assertAlmostEqual(diff, 0, delta=0.01)43 def test_get_returns_ones(self):44 self.setUpEnv("cartpole")45 paths = [{"reward": np.ones(5)}]46 returns = self.pg.get_returns(paths)47 gamma = self.pg.config.gamma48 expected = np.array(49 [50 1 + gamma + gamma ** 2 + gamma ** 3 + gamma ** 4,51 1 + gamma + gamma ** 2 + gamma ** 3,52 1 + gamma + gamma ** 2,53 1 + gamma,54 1,55 ]56 )57 diff = np.sum((returns - expected) ** 2)58 self.assertAlmostEqual(diff, 0, delta=0.001)59 def _test_sampled_actions(self):60 actions = self.policy.act(self.rand_obs)61 action_space = self.env.action_space62 discrete = isinstance(action_space, gym.spaces.Discrete)63 for action in actions:64 if discrete:65 self.assertTrue(action_space.contains(action))66 else:67 # We don't use contains because technically the Gaussian policy68 # doesn't respect the action bounds69 self.assertEqual(action_space.shape, action.shape)70 def test_cartpole_sampled_actions(self):71 self.setUpEnv("cartpole")72 self._test_sampled_actions()73 def test_pendulum_sampled_actions(self):74 self.setUpEnv("pendulum")75 self._test_sampled_actions()76 def test_cheetah_sampled_actions(self):77 self.setUpEnv("cheetah")78 self._test_sampled_actions()79 def _test_log_prob(self):80 actions = np2torch(self.policy.act(self.rand_obs))81 observations = np2torch(self.rand_obs)82 log_probs = (83 self.policy.action_distribution(observations).log_prob(actions).detach()84 )85 self.assertEqual(log_probs.shape, torch.Size([len(observations)]))86 def test_cartpole_logprob(self):87 self.setUpEnv("cartpole")88 self._test_log_prob()89 def test_pendulum_logprob(self):90 self.setUpEnv("pendulum")91 self._test_log_prob()92 def test_cheetah_logprob(self):93 self.setUpEnv("cheetah")94 self._test_log_prob()95 def test_policy_network_cartpole_logprob_value(self):96 self.setUpEnv("cartpole")97 actions = np2torch(self.policy.act(self.rand_obs))98 observations = np2torch(self.rand_obs)99 log_probs = (100 self.policy.action_distribution(observations).log_prob(actions).detach()101 )102 self.assertTrue(torch.all(log_probs < 0))103 def test_baseline_op(self):104 self.setUpEnv("cartpole")105 # make sure we can overfit!106 returns = np.random.randn(len(self.rand_obs))107 for i in range(1000):108 self.baseline.update_baseline(returns, self.rand_obs)109 advantages = self.baseline.calculate_advantage(returns, self.rand_obs)110 self.assertTrue(np.allclose(advantages, 0, atol=0.01))111 def test_adv_basic(self):112 self.setUpEnv("cartpole")113 returns = np.random.randn(5)114 observations = np.random.randn(5, 4)115 self.pg.config.use_baseline = False116 self.pg.config.normalize_advantage = False117 res = self.pg.calculate_advantage(returns, observations)...

Full Screen

Full Screen

ctfSetupper.py

Source: ctfSetupper.py Github

copy

Full Screen

1#!/​usr/​bin/​python3.92import optparse3import subprocess4###########################35# by Cave 20226###########################37# Exact use of /​ are important here8# Suffix and prefix /​'s need to be right9HOME_DIR = "/​home/​cave/​"10CTF_FOLDER = HOME_DIR + "Documents/​CTF/​"11CUSTOM_TOOLING = HOME_DIR + ".tooling/​custom/​"12PWN_TEMPLATE = CUSTOM_TOOLING + "pwntemp.py"13with open(CUSTOM_TOOLING+"CTF_CONTEXT", "r") as f:14 CTF_CONTEXT = f.read()15def optParser():16 parser = optparse.OptionParser()17 18 # add options19 parser.add_option('-f', dest = 'file',20 type = 'str',21 help = 'Specify the file')22 parser.add_option('-s', dest = 'ctfContext',23 type = 'str',24 help = 'Specify the current ctf')25 parser.add_option('-c', dest = 'challCategory',26 type = 'str',27 help = 'Specify the current challenges category')28 29 (options, args) = parser.parse_args()30 if options.ctfContext:31 with open(CUSTOM_TOOLING+"CTF_CONTEXT", "w") as f:32 f.write(options.ctfContext)33 print(f"Writing {options.ctfContext} > CTF_CONTEXT")34 exit("[:)] Wrote new CTF context")35 elif options.challCategory:36 if "web" in options.challCategory.lower():37 return options.file, "web"38 elif "pwn" in options.challCategory.lower():39 return options.file, "pwn"40 elif "rev" in options.challCategory.lower():41 return options.file, "rev"42 elif "crypto" in options.challCategory.lower():43 return options.file, "crypto"44 elif "misc" in options.challCategory.lower():45 return options.file, "misc"46 elif "foren" in options.challCategory.lower():47 return options.file, "forensics"48 else:49 exit("""50 ----------51 Possible categories, you silly goose:52 web, rev, pwn, crypto, misc, and forensics53 ----------54 """)55 elif options.file:56 return options.file, None57 else:58 print(options.file)59 exit("""60 Sorry that is not a command!61 You can use -f <file> to specify a file.62 You can also use -c <category> 63 OR you can set the CTF context with64 -s <ctf>. To see all commands65 try running -h or --help!66 """)67def ctfSetup(fileName, category):68 ans = input(f"Do you want to setup? [y/​n]\nCurrent context: {CTF_CONTEXT}\n") 69 if ans.lower() == "n":70 return 071 else:72 setupEnv = CTF_FOLDER+CTF_CONTEXT73 print(f"This is your ctf setup folder: {setupEnv}\nHappy hacking!\n")74 # Ensure that folder does not exist75 folderExists = subprocess.call(["/​usr/​bin/​test", "-e", setupEnv])76 if folderExists == 1:77 subprocess.call(["/​usr/​bin/​mkdir", setupEnv])78 subprocess.call(["/​usr/​bin/​mkdir", setupEnv+"/​web"])79 subprocess.call(["/​usr/​bin/​mkdir", setupEnv+"/​pwn"])80 subprocess.call(["/​usr/​bin/​mkdir", setupEnv+"/​rev"])81 subprocess.call(["/​usr/​bin/​mkdir", setupEnv+"/​crypto"])82 subprocess.call(["/​usr/​bin/​mkdir", setupEnv+"/​misc"])83 subprocess.call(["/​usr/​bin/​mkdir", setupEnv+"/​forensics"])84 if category:85 catFolder = setupEnv+"/​"+category+"/​"+fileName.split(".")[0]86 subprocess.call(["/​usr/​bin/​mkdir", catFolder])87 subprocess.call(["/​usr/​bin/​mv", fileName, catFolder])88 solExists = subprocess.call(["/​usr/​bin/​test", "-e", catFolder+"/​"+"pwntemp.py"])89 if solExists == 1:90 if category == "pwn":91 subprocess.call(["/​usr/​bin/​cp", CUSTOM_TOOLING+"pwntemp.py", catFolder])92 93 elif category == "rev":94 subprocess.call(["/​usr/​bin/​cp", CUSTOM_TOOLING+"pwntemp.py", catFolder])95 96 readmeExists = subprocess.call(["/​usr/​bin/​test", "-e", catFolder+"/​"+"README.md"])97 if readmeExists == 1:98 subprocess.call(["/​usr/​bin/​touch", catFolder+"/​"+"README.md"])99 else:100 subprocess.call(["/​usr/​bin/​mv", fileName, setupEnv])101def main(fileName, category):102 ctfSetup(fileName, category)103if __name__ == "__main__":104 file, category = optParser()...

Full Screen

Full Screen

Blogs

Check out the latest blogs from LambdaTest on this topic:

Test Managers in Agile &#8211; Creating the Right Culture for Your SQA Team

I was once asked at a testing summit, “How do you manage a QA team using scrum?” After some consideration, I realized it would make a good article, so here I am. Understand that the idea behind developing software in a scrum environment is for development teams to self-organize.

Complete Guide To Styling Forms With CSS Accent Color

The web paradigm has changed considerably over the last few years. Web 2.0, a term coined way back in 1999, was one of the pivotal moments in the history of the Internet. UGC (User Generated Content), ease of use, and interoperability for the end-users were the key pillars of Web 2.0. Consumers who were only consuming content up till now started creating different forms of content (e.g., text, audio, video, etc.).

A Complete Guide To Flutter Testing

Mobile devices and mobile applications – both are booming in the world today. The idea of having the power of a computer in your pocket is revolutionary. As per Statista, mobile accounts for more than half of the web traffic worldwide. Mobile devices (excluding tablets) contributed to 54.4 percent of global website traffic in the fourth quarter of 2021, increasing consistently over the past couple of years.

Webinar: Building Selenium Automation Framework [Voices of Community]

Even though several frameworks are available in the market for automation testing, Selenium is one of the most renowned open-source frameworks used by experts due to its numerous features and benefits.

A Comprehensive Guide On JUnit 5 Extensions

JUnit is one of the most popular unit testing frameworks in the Java ecosystem. The JUnit 5 version (also known as Jupiter) contains many exciting innovations, including support for new features in Java 8 and above. However, many developers still prefer to use the JUnit 4 framework since certain features like parallel execution with JUnit 5 are still in the experimental phase.

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run tox automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful