├── .gitattributes ├── 9781484244326.jpg ├── Contributing.md ├── LICENSE.txt ├── README.md ├── ansible-basics-0.py ├── ansible-basics-1.py ├── ansible-basics-10.py ├── ansible-basics-2.py ├── ansible-basics-3.py ├── ansible-basics-4.py ├── ansible-basics-5.py ├── ansible-basics-6.py ├── ansible-basics-7.py ├── ansible-basics-8.py ├── ansible-basics-9.py ├── ansible-extensions-0.py ├── ansible-extensions-1.py ├── ansible-extensions-2.py ├── ansible-extensions-3.py ├── ansible-terms-0.py ├── authentication-0.py ├── authentication-1.py ├── authentication-2.py ├── authentication-3.py ├── basic-console-0.py ├── basic-console-1.py ├── basic-console-2.py ├── basic-console-3.py ├── bytes-strings-unicode-0.py ├── bytes-strings-unicode-1.py ├── bytes-strings-unicode-2.py ├── bytes-strings-unicode-3.py ├── client-keys-0.py ├── client-keys-1.py ├── client-keys-2.py ├── client-keys-3.py ├── client-keys-4.py ├── code-module-0.py ├── connecting-0.py ├── csv-0.py ├── csv-1.py ├── csv-2.py ├── csv-3.py ├── csv-4.py ├── devpi-0.py ├── devpi-1.py ├── devpi-2.py ├── devpi-3.py ├── devpi-4.py ├── devpi-5.py ├── devpi-6.py ├── devpi-7.py ├── docker-image-building-0.py ├── docker-image-management-0.py ├── emulating-shells-0.py ├── errata.md ├── fernet-0.py ├── fernet-1.py ├── fernet-2.py ├── fernet-3.py ├── fernet-4.py ├── files-0.py ├── files-1.py ├── files-10.py ├── files-2.py ├── files-3.py ├── files-4.py ├── files-5.py ├── files-6.py ├── files-7.py ├── files-8.py ├── files-9.py ├── intro-docker-0.py ├── ipython-0.py ├── ipython-1.py ├── ipython-2.py ├── json-0.py ├── json-1.py ├── json-2.py ├── json-3.py ├── json-4.py ├── jupyter-lab-0.py ├── jupyter-lab-1.py ├── networking-0.py ├── networking-1.py ├── networking-2.py ├── networking-3.py ├── package-sources-0.py ├── passlib-0.py ├── passlib-1.py ├── passlib-2.py ├── passlib-3.py ├── passlib-4.py ├── passlib-5.py ├── passlib-6.py ├── passlib-7.py ├── pip-0.py ├── processes-0.py ├── processes-1.py ├── processes-2.py ├── processes-3.py ├── processes-4.py ├── processes-5.py ├── processes-6.py ├── processes-7.py ├── pyenv-0.py ├── pyenv-1.py ├── pyenv-2.py ├── pyenv-3.py ├── pyenv-4.py ├── pyenv-5.py ├── pyenv-6.py ├── pynacl-0.py ├── pynacl-1.py ├── pynacl-10.py ├── pynacl-11.py ├── pynacl-12.py ├── pynacl-13.py ├── pynacl-14.py ├── pynacl-15.py ├── pynacl-16.py ├── pynacl-17.py ├── pynacl-18.py ├── pynacl-19.py ├── pynacl-2.py ├── pynacl-20.py ├── pynacl-3.py ├── pynacl-4.py ├── pynacl-5.py ├── pynacl-6.py ├── pynacl-7.py ├── pynacl-8.py ├── pynacl-9.py ├── regular-expressions-0.py ├── regular-expressions-1.py ├── regular-expressions-2.py ├── regular-expressions-3.py ├── rest-0.py ├── rest-1.py ├── rest-2.py ├── salt-basics-0.py ├── salt-basics-1.py ├── salt-basics-2.py ├── salt-basics-3.py ├── salt-basics-4.py ├── salt-basics-5.py ├── salt-basics-6.py ├── salt-basics-7.py ├── salt-basics-8.py ├── salt-formats-0.py ├── salt-formats-1.py ├── salt-formats-2.py ├── salt-formats-3.py ├── salt-terms-0.py ├── salt-terms-1.py ├── salt-terms-2.py ├── salt-terms-3.py ├── security-0.py ├── security-1.py ├── security-2.py ├── security-3.py ├── sessions-0.py ├── sessions-1.py ├── setup-and-wheels-0.py ├── setup-and-wheels-1.py ├── setup-and-wheels-2.py ├── strings-0.py ├── strings-1.py ├── strings-10.py ├── strings-11.py ├── strings-2.py ├── strings-3.py ├── strings-4.py ├── strings-5.py ├── strings-6.py ├── strings-7.py ├── strings-8.py ├── strings-9.py ├── testing-files-0.py ├── testing-files-1.py ├── testing-files-10.py ├── testing-files-11.py ├── testing-files-2.py ├── testing-files-3.py ├── testing-files-4.py ├── testing-files-5.py ├── testing-files-6.py ├── testing-files-7.py ├── testing-files-8.py ├── testing-files-9.py ├── testing-network-0.py ├── testing-network-1.py ├── testing-network-2.py ├── testing-network-3.py ├── testing-network-4.py ├── testing-network-5.py ├── testing-network-6.py ├── testing-processes-0.py ├── testing-processes-1.py ├── testing-processes-2.py ├── testing-processes-3.py ├── testing-processes-4.py ├── testing-processes-5.py ├── testing-processes-6.py ├── testing-processes-7.py ├── testing-processes-8.py ├── tls-certificate-0.py ├── tls-certificate-1.py ├── tls-certificate-10.py ├── tls-certificate-11.py ├── tls-certificate-12.py ├── tls-certificate-13.py ├── tls-certificate-14.py ├── tls-certificate-15.py ├── tls-certificate-16.py ├── tls-certificate-17.py ├── tls-certificate-18.py ├── tls-certificate-19.py ├── tls-certificate-2.py ├── tls-certificate-20.py ├── tls-certificate-3.py ├── tls-certificate-4.py ├── tls-certificate-5.py ├── tls-certificate-6.py ├── tls-certificate-7.py ├── tls-certificate-8.py ├── tls-certificate-9.py ├── tox-0.py ├── tox-1.py ├── tox-10.py ├── tox-11.py ├── tox-12.py ├── tox-13.py ├── tox-2.py ├── tox-3.py ├── tox-4.py ├── tox-5.py ├── tox-6.py ├── tox-7.py ├── tox-8.py ├── tox-9.py ├── unit-testing-0.py ├── unit-testing-1.py ├── unit-testing-2.py ├── unit-testing-3.py ├── unit-testing-4.py ├── unit-testing-5.py ├── unit-testing-6.py ├── unit-testing-7.py ├── unit-testing-8.py ├── virtualenv-0.py ├── xar-0.py └── xar-1.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /9781484244326.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/devops-in-python/f40643b39d7bc490ee154a5a82e88de2e6c43e95/9781484244326.jpg -------------------------------------------------------------------------------- /Contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Apress Source Code 2 | 3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. 4 | 5 | ## How to Contribute 6 | 7 | 1. Make sure you have a GitHub account. 8 | 2. Fork the repository for the relevant book. 9 | 3. Create a new branch on which to make your change, e.g. 10 | `git checkout -b my_code_contribution` 11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. 12 | 5. Submit a pull request. 13 | 14 | Thank you for your contribution! -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Freeware License, some rights reserved 2 | 3 | Copyright (c) 2019 Moshe Zadka 4 | 5 | Permission is hereby granted, free of charge, to anyone obtaining a copy 6 | of this software and associated documentation files (the "Software"), 7 | to work with the Software within the limits of freeware distribution and fair use. 8 | This includes the rights to use, copy, and modify the Software for personal use. 9 | Users are also allowed and encouraged to submit corrections and modifications 10 | to the Software for the benefit of other users. 11 | 12 | It is not allowed to reuse, modify, or redistribute the Software for 13 | commercial use in any way, or for a user’s educational materials such as books 14 | or blog articles without prior permission from the copyright holder. 15 | 16 | The above copyright notice and this permission notice need to be included 17 | in all copies or substantial portions of the software. 18 | 19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 25 | SOFTWARE. 26 | 27 | 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apress Source Code 2 | 3 | This repository accompanies [*DevOps in Python*](https://www.apress.com/9781484244326) by Moshe Zadka (Apress, 2019). 4 | 5 | [comment]: #cover 6 | ![Cover image](9781484244326.jpg) 7 | 8 | Download the files as a zip using the green button, or clone the repository to your machine using Git. 9 | 10 | ## Releases 11 | 12 | Release v1.0 corresponds to the code in the published book, without corrections or updates. 13 | 14 | ## Contributions 15 | 16 | See the file Contributing.md for more information on how you can contribute to this repository. -------------------------------------------------------------------------------- /ansible-basics-0.py: -------------------------------------------------------------------------------- 1 | $ ansible localhost -m ping -------------------------------------------------------------------------------- /ansible-basics-1.py: -------------------------------------------------------------------------------- 1 | $ ansible localhost -a "/bin/echo hello world" -------------------------------------------------------------------------------- /ansible-basics-10.py: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | tasks: 4 | - name: hello printer 5 | shell: echo "hello world" >> /etc/hello 6 | creates: /etc/hello -------------------------------------------------------------------------------- /ansible-basics-2.py: -------------------------------------------------------------------------------- 1 | $ ansible 10.40.32.195 -m ping -------------------------------------------------------------------------------- /ansible-basics-3.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | if '--host' in sys.argv[1:]: 4 | print(json.dumps({})) 5 | 6 | print(json.dumps(dict(all='localhost'))) -------------------------------------------------------------------------------- /ansible-basics-4.py: -------------------------------------------------------------------------------- 1 | $ ansible -i simple.inv all -m ping -------------------------------------------------------------------------------- /ansible-basics-5.py: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | tasks: 4 | - name: hello printer 5 | shell: echo "hello world" -------------------------------------------------------------------------------- /ansible-basics-6.py: -------------------------------------------------------------------------------- 1 | $ ansible-playbook -i simple.inv echo.yml -------------------------------------------------------------------------------- /ansible-basics-7.py: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | tasks: 4 | - name: hello printer 5 | shell: echo "hello world" >> /etc/hello -------------------------------------------------------------------------------- /ansible-basics-8.py: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | tasks: 4 | - name: hello printer 5 | shell: echo "hello world" >> /etc/hello 6 | creates: /etc/hello -------------------------------------------------------------------------------- /ansible-basics-9.py: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | roles: 4 | - common -------------------------------------------------------------------------------- /ansible-extensions-0.py: -------------------------------------------------------------------------------- 1 | def parse(self, inventory, loader, path, cache=True): 2 | pass -------------------------------------------------------------------------------- /ansible-extensions-1.py: -------------------------------------------------------------------------------- 1 | def parse(self, inventory, loader, path, cache=True): 2 | super(InventoryModule, self).parse(inventory, loader, path, cache) 3 | try: 4 | with open(path) as fpin: 5 | data = json.loads(fpin.read()) 6 | except ValueError as exc: 7 | raise AnsibleParseError(exc) 8 | for host in data: 9 | self.inventory.add_host(server['name']) -------------------------------------------------------------------------------- /ansible-extensions-2.py: -------------------------------------------------------------------------------- 1 | class LookupModule(LookupBase): 2 | 3 | def run(self, terms, variables=None, **kwargs): 4 | pass -------------------------------------------------------------------------------- /ansible-extensions-3.py: -------------------------------------------------------------------------------- 1 | class LookupModule(LookupBase): 2 | 3 | def run(self, terms, variables=None, **kwargs): 4 | return os.path.commonpath(terms) -------------------------------------------------------------------------------- /ansible-terms-0.py: -------------------------------------------------------------------------------- 1 | - hosts: databases 2 | remote_user: ubuntu 3 | become: True 4 | 5 | tasks: 6 | - name: ensure that postgresql is started 7 | service: 8 | name: postgresql 9 | state: started -------------------------------------------------------------------------------- /authentication-0.py: -------------------------------------------------------------------------------- 1 | def canonical_query_string(query): 2 | if not query: 3 | return "" 4 | parsed = parse_qs(url.query, keep_blank_values=True) 5 | return "?" + urlencode(parsed, doseq=True) -------------------------------------------------------------------------------- /authentication-1.py: -------------------------------------------------------------------------------- 1 | def to_canonical_url(url): 2 | url = urlparse(raw_url) 3 | path = url.path or "/" 4 | query = canonical_query_string(url.query) 5 | return (url.scheme + 6 | "://" + 7 | url.netloc + 8 | path + 9 | querystring) -------------------------------------------------------------------------------- /authentication-2.py: -------------------------------------------------------------------------------- 1 | from botocore.auth import SigV4Auth 2 | from botocore.awsrequest import AWSRequest 3 | 4 | def sign(request, *, aws_session, region, service): 5 | aws_request = AWSRequest( 6 | method=request.method.upper(), 7 | url=to_canonical_url(request.url), 8 | data=request.body, 9 | ) 10 | credentials = aws_session.get_credentials() 11 | SigV4Auth(credentials, service, region).add_auth(request) 12 | request.headers.update(**aws_request.headers.items()) -------------------------------------------------------------------------------- /authentication-3.py: -------------------------------------------------------------------------------- 1 | requests_session = requests.Session() 2 | requests_session.auth = functools.partial(sign, 3 | aws_session=boto3.Session(), 4 | region='us-east-1', 5 | service='es', 6 | ) -------------------------------------------------------------------------------- /basic-console-0.py: -------------------------------------------------------------------------------- 1 | >>> 2 + 2 2 | 4 -------------------------------------------------------------------------------- /basic-console-1.py: -------------------------------------------------------------------------------- 1 | >>> rate = 9.25 2 | >>> price = 5.99 3 | >>> after_tax = price * (1 + rate / 100.) 4 | >>> after_tax 5 | 6.544075 -------------------------------------------------------------------------------- /basic-console-2.py: -------------------------------------------------------------------------------- 1 | >>> import os 2 | >>> os.path.isfile(os.path.expanduser("~/.bashrc")) 3 | True -------------------------------------------------------------------------------- /basic-console-3.py: -------------------------------------------------------------------------------- 1 | >>> import requests 2 | >>> requests.get("http://en.wikipedia.org") 3 | 4 | >>> a=_ 5 | >>> a.text[:50] 6 | '\n>> "hello".encode("utf-16") 4 | b'\xff\xfeh\x00e\x00l\x00l\x00o\x00' -------------------------------------------------------------------------------- /bytes-strings-unicode-1.py: -------------------------------------------------------------------------------- 1 | >>> snowman = '\N{snowman}' 2 | >>> snowman.encode('utf-16').decode('utf-8') 3 | Traceback (most recent call last): 4 | File "", line 1, in 5 | UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte -------------------------------------------------------------------------------- /bytes-strings-unicode-2.py: -------------------------------------------------------------------------------- 1 | >>> struct.pack('B'*12, 2 | *(random.randrange(0, 256) 3 | for i in range(12)) 4 | ).decode('utf-8') -------------------------------------------------------------------------------- /bytes-strings-unicode-3.py: -------------------------------------------------------------------------------- 1 | UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe2 in position 4: invalid continuation byte 2 | UnicodeDecodeError: 'utf-8' codec can't decode byte 0x98 in position 2: invalid start byte -------------------------------------------------------------------------------- /client-keys-0.py: -------------------------------------------------------------------------------- 1 | >>> from paramiko import ecdsakey 2 | >>> k = ecdsakey.ECDSAKey.generate() -------------------------------------------------------------------------------- /client-keys-1.py: -------------------------------------------------------------------------------- 1 | >>> public_key = k.get_base64() -------------------------------------------------------------------------------- /client-keys-2.py: -------------------------------------------------------------------------------- 1 | >>> with open("key.pub", "w") as fp: 2 | ... fp.write(public_key) -------------------------------------------------------------------------------- /client-keys-3.py: -------------------------------------------------------------------------------- 1 | >>> import os 2 | >>> with open("key.priv", "w") as fp: 3 | ... os.chmod(0o600, "key.priv") 4 | ... k.write_private_key(fp) -------------------------------------------------------------------------------- /client-keys-4.py: -------------------------------------------------------------------------------- 1 | set_user_data(machine_id, 2 | f""" 3 | ssh_authorized_keys: 4 | - ssh-ecdsa {public_key} 5 | """) -------------------------------------------------------------------------------- /code-module-0.py: -------------------------------------------------------------------------------- 1 | >>> import code 2 | >>> code.interact(banner="Welcome to the special interpreter", 3 | ... local=dict(special=[1, 2, 3])) 4 | Welcome to the special interpreter 5 | >>> special 6 | [1, 2, 3] 7 | >>> ^D 8 | now exiting InteractiveConsole... 9 | >>> special 10 | Traceback (most recent call last): 11 | File "", line 1, in 12 | NameError: name 'special' is not defined -------------------------------------------------------------------------------- /connecting-0.py: -------------------------------------------------------------------------------- 1 | with contextlib.context(SSHClient()) as client: 2 | client.connect(some_host) 3 | ## Do things with client -------------------------------------------------------------------------------- /csv-0.py: -------------------------------------------------------------------------------- 1 | @attr.s(frozen=True, auto_attribs=True) 2 | class LoginAttempt: 3 | username: str 4 | time_stamp: int 5 | success: bool -------------------------------------------------------------------------------- /csv-1.py: -------------------------------------------------------------------------------- 1 | def write_attempts(attempts, fname): 2 | with open(fname, 'w') as fpout: 3 | writer = csv.writer(fpout) 4 | writer.writerow(['Username', 'Timestamp', 'Success']) 5 | for attempt in attempts: 6 | writer.writerow([ 7 | attempt.username, 8 | attempt.time_stamp, 9 | str(attempt.success), 10 | ]) -------------------------------------------------------------------------------- /csv-2.py: -------------------------------------------------------------------------------- 1 | >>> reader = csv.DictReader(fileobj) 2 | >>> list(reader) 3 | [OrderedDict([('Username', 'alice'), 4 | ('Timestamp', '1514793600.0'), 5 | ('Success', 'False')]), 6 | OrderedDict([('Username', 'bob'), 7 | ('Timestamp', '1539154800.0'), 8 | ('Success', 'True')])] -------------------------------------------------------------------------------- /csv-3.py: -------------------------------------------------------------------------------- 1 | 1,"Miami, FL","he""llo" -------------------------------------------------------------------------------- /csv-4.py: -------------------------------------------------------------------------------- 1 | ('1', 'Miami, FL', 'he"llo') -------------------------------------------------------------------------------- /devpi-0.py: -------------------------------------------------------------------------------- 1 | (devpi)$ pip install devpi-server 2 | (devpi)$ devpi-server --start --init -------------------------------------------------------------------------------- /devpi-1.py: -------------------------------------------------------------------------------- 1 | (playground)$ pip install \ 2 | -i http://localhost:3141/root/pypi/+simple/ \ 3 | httpie glom 4 | (playground)$ http --body https://httpbin.org/get | glom '{"url":"url"}' 5 | { 6 | "url": "https://httpbin.org/get" 7 | } -------------------------------------------------------------------------------- /devpi-2.py: -------------------------------------------------------------------------------- 1 | $ export PIP_INDEX_URL=http://localhost:3141/root/pypi/+simple/ -------------------------------------------------------------------------------- /devpi-3.py: -------------------------------------------------------------------------------- 1 | $ mkdir -p ~/.pip && cat > ~/.pip/pip.conf << EOF 2 | [global] 3 | index-url = http://localhost:3141/root/pypi/+simple/ 4 | 5 | [search] 6 | index = http://localhost:3141/root/pypi/ -------------------------------------------------------------------------------- /devpi-4.py: -------------------------------------------------------------------------------- 1 | (devpi)$ pip install devpi-client twine 2 | (devpi)$ devpi use http://localhost:3141 3 | (devpi)$ devpi user -c testuser password=123 4 | (devpi)$ devpi login testuser --password=123 5 | (devpi)$ devpi index -c dev bases=root/pypi 6 | (devpi)$ devpi use testuser/dev 7 | (devpi)$ twine upload --repository http://localhost:3141/testuser/dev \ 8 | -u testuser -p 123 my-package-18.6.0.tar.gz 9 | (devpi)$ pip install -i http://localhost:3141/testuser/dev my-package -------------------------------------------------------------------------------- /devpi-5.py: -------------------------------------------------------------------------------- 1 | (devpi)$ devpi index root/pypi mirror_url=https://ourdevpi.local -------------------------------------------------------------------------------- /devpi-6.py: -------------------------------------------------------------------------------- 1 | $ devpi index --delete root/pypi -------------------------------------------------------------------------------- /devpi-7.py: -------------------------------------------------------------------------------- 1 | $ devpi index --create root/pypi -------------------------------------------------------------------------------- /docker-image-building-0.py: -------------------------------------------------------------------------------- 1 | fpout = io.BytesIO() 2 | tfout = tarfile.open(fpout, "w|") 3 | info = tarfile.TarInfo(name="Dockerfile") 4 | dockerfile = io.Bytes("FROM scratch\nCOPY hello /hello".encode("ascii")) 5 | tfout.addfile(tarinfo=info, fileobj=dockerfile) 6 | hello = io.Bytes("This is a file saying 'hello'".encode("ascii")) 7 | info = tarfile.TarInfo(name="hello") 8 | tfout.addfile(tarinfo=info, fileobj=hello) 9 | fpout.seek(0) 10 | client.build(fileobj=fpout, tag="hello") -------------------------------------------------------------------------------- /docker-image-management-0.py: -------------------------------------------------------------------------------- 1 | images = client.list(name="myusername/myrepo") 2 | sofar = None 3 | for image in images: 4 | maxtag = max(tag for tag in image.tags if tag.startswith("date-")) 5 | if sofar is None or maxtag > sofar: 6 | sofar = maxtag 7 | latest = image 8 | latest.tag("myusername/myrepo", tag="latest") 9 | client.push("myusername/myrepo", tag="latest") -------------------------------------------------------------------------------- /emulating-shells-0.py: -------------------------------------------------------------------------------- 1 | >>> channel = client.invoke_shell() 2 | >>> input = channel.makefile("wb") 3 | >>> output = channel.makefile("rb") -------------------------------------------------------------------------------- /errata.md: -------------------------------------------------------------------------------- 1 | # Errata for *Book Title* 2 | 3 | On **page xx** [Summary of error]: 4 | 5 | Details of error here. Highlight key pieces in **bold**. 6 | 7 | *** 8 | 9 | On **page xx** [Summary of error]: 10 | 11 | Details of error here. Highlight key pieces in **bold**. 12 | 13 | *** -------------------------------------------------------------------------------- /fernet-0.py: -------------------------------------------------------------------------------- 1 | >>> k = fernet.Fernet.generate_key() 2 | >>> type(k) 3 | -------------------------------------------------------------------------------- /fernet-1.py: -------------------------------------------------------------------------------- 1 | >>> frn = fernet.Fernet(k) -------------------------------------------------------------------------------- /fernet-2.py: -------------------------------------------------------------------------------- 1 | >>> encrypted = frn.encrypt(b"x marks the spot") 2 | >>> encrypted[:10] 3 | b'gAAAAABb1' -------------------------------------------------------------------------------- /fernet-3.py: -------------------------------------------------------------------------------- 1 | >>> frn.decrypt(encrypted) 2 | b'x marks the spot' -------------------------------------------------------------------------------- /fernet-4.py: -------------------------------------------------------------------------------- 1 | >>> frn.decrypt(encrypted, ttl=5) -------------------------------------------------------------------------------- /files-0.py: -------------------------------------------------------------------------------- 1 | >>> with open("Untitled.xcf", "rb") as fp: 2 | ... header = fp.read(100) -------------------------------------------------------------------------------- /files-1.py: -------------------------------------------------------------------------------- 1 | >>> header[:9].decode('ascii') 2 | 'gimp xcf ' -------------------------------------------------------------------------------- /files-10.py: -------------------------------------------------------------------------------- 1 | with NamedTemporaryFile() as fp: 2 | fp.write("line 1\n") 3 | fp.write("line 2\n") 4 | fp.flush() 5 | function_taking_file_name(fp.name) -------------------------------------------------------------------------------- /files-2.py: -------------------------------------------------------------------------------- 1 | >>> header[9:9+4].decode('ascii') 2 | 'v011' -------------------------------------------------------------------------------- /files-3.py: -------------------------------------------------------------------------------- 1 | >>> header[9+4] 2 | 0 -------------------------------------------------------------------------------- /files-4.py: -------------------------------------------------------------------------------- 1 | >>> struct.unpack('>I', header[9+4+1:9+4+1+4]) 2 | (1920,) -------------------------------------------------------------------------------- /files-5.py: -------------------------------------------------------------------------------- 1 | >>> struct.unpack('>I', header[9+4+1+4:9+4+1+4+4]) 2 | (1080,) -------------------------------------------------------------------------------- /files-6.py: -------------------------------------------------------------------------------- 1 | >>> fp = open("things.txt", "w") 2 | >>> fp.write("""\ 3 | ... one line 4 | ... two lines 5 | ... red line 6 | ... blue line 7 | ... """) 8 | 39 9 | >>> fp.close() 10 | >>> fpin = open("things.txt") 11 | >>> next(fpin) 12 | 'one line\n' 13 | >>> next(fpin) 14 | 'two lines\n' 15 | >>> next(fpin) 16 | 'red line\n' 17 | >>> next(fpin) 18 | 'blue line\n' 19 | >>> next(fpin) 20 | Traceback (most recent call last): 21 | File "", line 1, in 22 | StopIteration -------------------------------------------------------------------------------- /files-7.py: -------------------------------------------------------------------------------- 1 | with open("important.tmp", "w") as fout: 2 | fout.write("The horse raced past the barn") 3 | fout.write("fell.\n") 4 | os.rename("important.tmp", "important") -------------------------------------------------------------------------------- /files-8.py: -------------------------------------------------------------------------------- 1 | os.makedirs(some_path, exists_ok=True) -------------------------------------------------------------------------------- /files-9.py: -------------------------------------------------------------------------------- 1 | def open_for_write(fname, mode=""): 2 | os.makedirs(os.path.dirname(fname), exists_ok=True) 3 | return open(fname, "w" + mode) 4 | 5 | with open_for_write("some/deep/nested/name/of/file.txt") as fp: 6 | fp.write("hello world") -------------------------------------------------------------------------------- /intro-docker-0.py: -------------------------------------------------------------------------------- 1 | import docker 2 | client = docker.from_env() -------------------------------------------------------------------------------- /ipython-0.py: -------------------------------------------------------------------------------- 1 | In [1]: print("hello") 2 | hello 3 | 4 | In [2]: In[1] 5 | Out[2]: 'print("hello")' 6 | 7 | In [3]: 5 + 4.0 8 | Out[3]: 9.0 9 | 10 | In [4]: Out[3] == 9.0 11 | Out[4]: True -------------------------------------------------------------------------------- /ipython-1.py: -------------------------------------------------------------------------------- 1 | In [1]: list? 2 | Init signature: list(self, /, *args, **kwargs) 3 | Docstring: 4 | list() -> new empty list 5 | list(iterable) -> new list initialized from iterable's items 6 | Type: type -------------------------------------------------------------------------------- /ipython-2.py: -------------------------------------------------------------------------------- 1 | from traitlets import config 2 | import IPython 3 | 4 | my_config = config.Config() 5 | my_config.InteractiveShell.autocall = True 6 | 7 | IPython.start_ipython(config=my_config) -------------------------------------------------------------------------------- /json-0.py: -------------------------------------------------------------------------------- 1 | >>> thing = [{"hello": 1, "world": 2}, None, True] 2 | >>> json.dumps(thing) 3 | '[{"hello": 1, "world": 2}, null, true]' 4 | >>> json.loads(_) 5 | [{'hello': 1, 'world': 2}, None, True] -------------------------------------------------------------------------------- /json-1.py: -------------------------------------------------------------------------------- 1 | >>> json.loads("1") 2 | 1 3 | >>> json.loads("1.0") 4 | 1.0 -------------------------------------------------------------------------------- /json-2.py: -------------------------------------------------------------------------------- 1 | json.dumps(thing, sort_keys=True, indent=4) -------------------------------------------------------------------------------- /json-3.py: -------------------------------------------------------------------------------- 1 | json.dumps(json.loads(encoded_string), sort_keys=True, indent=4) -------------------------------------------------------------------------------- /json-4.py: -------------------------------------------------------------------------------- 1 | $ python -m json.tool < somefile.json | less -------------------------------------------------------------------------------- /jupyter-lab-0.py: -------------------------------------------------------------------------------- 1 | python -m ipykernel install \ 2 | --name my-special-env \ 3 | --display-name "My Env" 4 | --prefix=$DIRECTORY -------------------------------------------------------------------------------- /jupyter-lab-1.py: -------------------------------------------------------------------------------- 1 | jupyter kernelspec install $DIRECTORY/jupyter/kernels/my-special-env -------------------------------------------------------------------------------- /networking-0.py: -------------------------------------------------------------------------------- 1 | >>> import socket, json, pprint 2 | >>> s = socket.socket() 3 | >>> s.connect(('httpbin.org', 80)) 4 | >>> s.send(b'GET /get HTTP/1.0\r\nHost: httpbin.org\r\n\r\n') 5 | 40 6 | >>> res = s.recv(1024) 7 | >>> pprint.pprint(json.loads( 8 | ... res.decode('ascii').split('\r\n\r\n', 1)[1])) 9 | {'args': {}, 10 | 'headers': {'Connection': 'close', 'Host': 'httpbin.org'}, 11 | 'origin': '73.162.254.113', 12 | 'url': 'http://httpbin.org/get'} -------------------------------------------------------------------------------- /networking-1.py: -------------------------------------------------------------------------------- 1 | >>> import socket, json, pprint 2 | >>> s = socket.socket() 3 | >>> s.connect(('httpbin.org', 80)) 4 | >>> s.sendall(b'GET /get HTTP/1.0\r\nHost: httpbin.org\r\n\r\n') 5 | >>> resp = b'' 6 | >>> while True: 7 | ... more = s.recv(1024) 8 | ... if more == b'': 9 | ... break 10 | ... resp += more 11 | ... 12 | >>> pprint.pprint(json.loads(resp.decode('ascii').split('\r\n\r\n')[1])) 13 | {'args': {}, 14 | 'headers': {'Connection': 'close', 'Host': 'httpbin.org'}, 15 | 'origin': '73.162.254.113', 16 | 'url': 'http://httpbin.org/get'} -------------------------------------------------------------------------------- /networking-2.py: -------------------------------------------------------------------------------- 1 | >>> import requests, pprint 2 | >>> res=requests.get('http://httpbin.org/get') 3 | >>> pprint.pprint(res.json()) 4 | {'args': {}, 5 | 'headers': {'Accept': '*/*', 6 | 'Accept-Encoding': 'gzip, deflate', 7 | 'Connection': 'close', 8 | 'Host': 'httpbin.org', 9 | 'User-Agent': 'python-requests/2.19.1'}, 10 | 'origin': '73.162.254.113', 11 | 'url': 'http://httpbin.org/get'} -------------------------------------------------------------------------------- /networking-3.py: -------------------------------------------------------------------------------- 1 | >>> import requests, pprint 2 | >>> session = requests.Session() 3 | >>> res = session.get('http://httpbin.org/get') 4 | >>> pprint.pprint(res.json()) 5 | {'args': {}, 6 | 'headers': {'Accept': '*/*', 7 | 'Accept-Encoding': 'gzip, deflate', 8 | 'Connection': 'close', 9 | 'Host': 'httpbin.org', 10 | 'User-Agent': 'python-requests/2.19.1'}, 11 | 'origin': '73.162.254.113', 12 | 'url': 'http://httpbin.org/get'} -------------------------------------------------------------------------------- /package-sources-0.py: -------------------------------------------------------------------------------- 1 | $ sudo add-apt-repository ppa:deadsnakes/ppa 2 | $ sudo apt update -------------------------------------------------------------------------------- /passlib-0.py: -------------------------------------------------------------------------------- 1 | >>> hashes = ["argon2", "pbkdf2_sha256", "md5_crypt", "des_crypt"] -------------------------------------------------------------------------------- /passlib-1.py: -------------------------------------------------------------------------------- 1 | >>> deprecated = ["md5_crypt", "des_crypt"] -------------------------------------------------------------------------------- /passlib-2.py: -------------------------------------------------------------------------------- 1 | >>> from passlib.context import CryptContext 2 | >>> ctx = CryptContext(schemes=hashes, deprecated=deprecated) -------------------------------------------------------------------------------- /passlib-3.py: -------------------------------------------------------------------------------- 1 | >>> serialized = ctx.to_string() 2 | >>> new_ctx = CryptContext.from_string(serialized) -------------------------------------------------------------------------------- /passlib-4.py: -------------------------------------------------------------------------------- 1 | >>> res = ctx.hash("good password") -------------------------------------------------------------------------------- /passlib-5.py: -------------------------------------------------------------------------------- 1 | >>> ctx.verify_and_update("good password", res) 2 | (True, None) -------------------------------------------------------------------------------- /passlib-6.py: -------------------------------------------------------------------------------- 1 | >>> res = ctx.hash("good password", scheme="md5_crypt") -------------------------------------------------------------------------------- /passlib-7.py: -------------------------------------------------------------------------------- 1 | >>> ctx.verify_and_update("good password", res) 2 | (True, '$5$...') -------------------------------------------------------------------------------- /pip-0.py: -------------------------------------------------------------------------------- 1 | $ pip install -e . 2 | $ pip freeze > requirements.txt -------------------------------------------------------------------------------- /processes-0.py: -------------------------------------------------------------------------------- 1 | subprocess.check_call(["usermod", "-G", "docker", "some-user"]) -------------------------------------------------------------------------------- /processes-1.py: -------------------------------------------------------------------------------- 1 | def add_to_docker(username): 2 | subprocess.check_call(["usermod", "-G", "docker", username]) -------------------------------------------------------------------------------- /processes-2.py: -------------------------------------------------------------------------------- 1 | groups = subprocess.check_output(["groups"]).split() -------------------------------------------------------------------------------- /processes-3.py: -------------------------------------------------------------------------------- 1 | sha = subprocess.check_output( 2 | ["git", "rev-parse", "HEAD"], 3 | cwd="src/some-project").decode("ascii").strip() -------------------------------------------------------------------------------- /processes-4.py: -------------------------------------------------------------------------------- 1 | proc = Popen(["docker", "login", "--password-stdin"], stdin=PIPE) 2 | out, err = proc.communicate(my_password + "\n") -------------------------------------------------------------------------------- /processes-5.py: -------------------------------------------------------------------------------- 1 | with tempfile.TemporaryFile() as fp: 2 | fp.write(contents) 3 | fp.write(of) 4 | fp.write(email) 5 | fp.flush() 6 | fp.seek(0) 7 | proc = Popen(["sendmail"], stdin=fp) 8 | result = proc.poll() -------------------------------------------------------------------------------- /processes-6.py: -------------------------------------------------------------------------------- 1 | with tempfile.TemporaryFile() as fp: 2 | fp.write(contents) 3 | fp.write(of) 4 | fp.write(email) 5 | fp.flush() 6 | fp.seek(0) 7 | check_call(["sendmail"], stdin=fp) -------------------------------------------------------------------------------- /processes-7.py: -------------------------------------------------------------------------------- 1 | $ ls -l | sort | head -3 | awk '{print $3}' -------------------------------------------------------------------------------- /pyenv-0.py: -------------------------------------------------------------------------------- 1 | $ PROJECT=https://github.com/pyenv/pyenv-installer \ 2 | PATH=raw/master/bin/pyenv-installer \ 3 | curl -L $PROJECT/PATH | bash -------------------------------------------------------------------------------- /pyenv-1.py: -------------------------------------------------------------------------------- 1 | $ git clone https://github.com/pyenv/pyenv-installer 2 | $ cd pyenv-installer 3 | $ bash pyenv-installer -------------------------------------------------------------------------------- /pyenv-2.py: -------------------------------------------------------------------------------- 1 | export PATH="~/.pyenv/bin:$PATH" 2 | eval "$(pyenv init -)" 3 | eval "$(pyenv virtualenv-init -)" -------------------------------------------------------------------------------- /pyenv-3.py: -------------------------------------------------------------------------------- 1 | $ pyenv install -------------------------------------------------------------------------------- /pyenv-4.py: -------------------------------------------------------------------------------- 1 | $ pyenv global 3.7.0 -------------------------------------------------------------------------------- /pyenv-5.py: -------------------------------------------------------------------------------- 1 | $ pyenv local 3.7.0 -------------------------------------------------------------------------------- /pyenv-6.py: -------------------------------------------------------------------------------- 1 | env PYTHON_CONFIGURE_OPTS="--enable-shared 2 | --enable-optimizations 3 | --with-computed-gotos 4 | --with-lto 5 | --enable-ipv6" pyenv install -------------------------------------------------------------------------------- /pynacl-0.py: -------------------------------------------------------------------------------- 1 | >>> from nacl.public import PrivateKey 2 | >>> k = PrivateKey.generate() -------------------------------------------------------------------------------- /pynacl-1.py: -------------------------------------------------------------------------------- 1 | >>> type(k.encode()) 2 | -------------------------------------------------------------------------------- /pynacl-10.py: -------------------------------------------------------------------------------- 1 | >>> key_2 = SigningKey(encoded) 2 | >>> key_2 == key 3 | True -------------------------------------------------------------------------------- /pynacl-11.py: -------------------------------------------------------------------------------- 1 | >>> verify_key = key.verify_key -------------------------------------------------------------------------------- /pynacl-12.py: -------------------------------------------------------------------------------- 1 | >>> verify_encoded = verify_key.encode() 2 | >>> verify_encoded[:4] 3 | b'\x08\xb1\x9e\xf4' -------------------------------------------------------------------------------- /pynacl-13.py: -------------------------------------------------------------------------------- 1 | >>> from nacl.signing import VerifyKey 2 | >>> verify_key_2 = VerifyKey(verify_encoded) 3 | >>> verify_key == verify_key_2 4 | True -------------------------------------------------------------------------------- /pynacl-14.py: -------------------------------------------------------------------------------- 1 | >>> message = b"The number you shall count is three" 2 | >>> result = key.sign(message) 3 | >>> result 4 | b'\x1a\xd38[....' -------------------------------------------------------------------------------- /pynacl-15.py: -------------------------------------------------------------------------------- 1 | >>> type(result) 2 | -------------------------------------------------------------------------------- /pynacl-16.py: -------------------------------------------------------------------------------- 1 | >>> result.message 2 | b'The number you shall count is three' 3 | >>> result.signature 4 | b'\x1a\xd38[...' -------------------------------------------------------------------------------- /pynacl-17.py: -------------------------------------------------------------------------------- 1 | >>> encoded = bytes(result) -------------------------------------------------------------------------------- /pynacl-18.py: -------------------------------------------------------------------------------- 1 | >>> verify_key.verify(encoded) 2 | b'The number you shall count is three' -------------------------------------------------------------------------------- /pynacl-19.py: -------------------------------------------------------------------------------- 1 | >>> verify_key.verify(b'The number you shall count is three', 2 | ... result.signature) 3 | b'The number you shall count is three' -------------------------------------------------------------------------------- /pynacl-2.py: -------------------------------------------------------------------------------- 1 | >>> kk = PrivateKey(k.encode()) 2 | >>> kk == k 3 | True -------------------------------------------------------------------------------- /pynacl-20.py: -------------------------------------------------------------------------------- 1 | >>> verify_key.verify(result) 2 | b'The number you shall count is three' -------------------------------------------------------------------------------- /pynacl-3.py: -------------------------------------------------------------------------------- 1 | >>> from nacl.public import PublicKey 2 | >>> target = PrivateKey.generate() 3 | >>> public_key = target.public_key -------------------------------------------------------------------------------- /pynacl-4.py: -------------------------------------------------------------------------------- 1 | >>> encoded = public_key.encode() 2 | >>> encoded[:4] 3 | b'\xb91>\x95' -------------------------------------------------------------------------------- /pynacl-5.py: -------------------------------------------------------------------------------- 1 | >>> public_key_2 = PublicKey(key_bytes) 2 | >>> public_key_2 == public_key 3 | True -------------------------------------------------------------------------------- /pynacl-6.py: -------------------------------------------------------------------------------- 1 | >>> from nacl.public import PrivateKey, PublicKey, Box 2 | >>> source = PrivateKey.generate() 3 | >>> with open("target.pubkey", "rb") as fpin: 4 | ... target_public_key = PublicKey(fpin.read()) 5 | >>> enc_box = Box(source, target_public_key) 6 | >>> result = enc_box.encrypt(b"x marks the spot") 7 | >>> result[:4] 8 | b'\xe2\x1c0\xa4' -------------------------------------------------------------------------------- /pynacl-7.py: -------------------------------------------------------------------------------- 1 | >>> from nacl.public import PrivateKey, PublicKey, Box 2 | >>> with open("source.pubkey", "rb") as fpin: 3 | ... source_public_key = PublicKey(fpin.read()) 4 | >>> with open("target.private_key", "rb") as fpin: 5 | ... target = PrivateKey(fpin.read()) 6 | >>> dec_box = Box(target, source_public_key) 7 | >>> dec_box.decrypt(result) 8 | b'x marks the spot' -------------------------------------------------------------------------------- /pynacl-8.py: -------------------------------------------------------------------------------- 1 | >>> from nacl.signing import SigningKey 2 | >>> key = SigningKey.generate() -------------------------------------------------------------------------------- /pynacl-9.py: -------------------------------------------------------------------------------- 1 | >>> encoded = key.encode() 2 | >>> type(encoded) 3 | -------------------------------------------------------------------------------- /regular-expressions-0.py: -------------------------------------------------------------------------------- 1 | >>> reobj = re.compile('ab+a') 2 | >>> m = reobj.search('hello abba world') 3 | >>> m 4 | <_sre.SRE_Match object; span=(6, 10), match='abba'> 5 | >>> m.group() 6 | 'abba' -------------------------------------------------------------------------------- /regular-expressions-1.py: -------------------------------------------------------------------------------- 1 | >>> reobj = re.compile('(a)(b+)(a)') 2 | >>> m = reobj.search('hello abba world') 3 | >>> m.group() 4 | 'abba' 5 | >>> m.group(1) 6 | 'a' 7 | >>> m.group(2) 8 | 'bb' 9 | >>> m.group(3) 10 | 'a' -------------------------------------------------------------------------------- /regular-expressions-2.py: -------------------------------------------------------------------------------- 1 | >>> reobj = re.compile('(?Pa)(?Pb+)(?Pa)') 2 | >>> m = reobj.search('hello abba world') 3 | >>> m.group('prefix') 4 | 'a' 5 | >>> m.group('body') 6 | 'bb' 7 | >>> m.group('suffix') 8 | 'a' -------------------------------------------------------------------------------- /regular-expressions-3.py: -------------------------------------------------------------------------------- 1 | >>> reobj = re.compile(r""" 2 | ... (?Pa) # The beginning -- always an a 3 | ... (?Pb+) # The middle -- any numbers of b, for emphasis 4 | ... (?Pa) # An a at the end to properly anchor 5 | ... """, re.VERBOSE) 6 | >>> m = reobj.search("hello abba world") 7 | >>> m.groups() 8 | ('a', 'bb', 'a') 9 | >>> m.group('prefix'), m.group('body'), m.group('suffix') 10 | ('a', 'bb', 'a') -------------------------------------------------------------------------------- /rest-0.py: -------------------------------------------------------------------------------- 1 | >>> pprint(s.get("https://httpbin.org/json").json()) 2 | {'slideshow': {'author': 'Yours Truly', 3 | 'date': 'date of publication', 4 | 'slides': [{'title': 'Wake up to WonderWidgets!', 'type': 'all'}, 5 | {'items': ['Why WonderWidgets are great', 6 | 'Who buys WonderWidgets'], 7 | 'title': 'Overview', 8 | 'type': 'all'}], 9 | 'title': 'Sample Slide Show'}} -------------------------------------------------------------------------------- /rest-1.py: -------------------------------------------------------------------------------- 1 | >>> resp = s.put("https://httpbin.org/put", json=dict(hello=5,world=2)) 2 | >>> resp.json()['json'] 3 | {'hello': 5, 'world': 2} -------------------------------------------------------------------------------- /rest-2.py: -------------------------------------------------------------------------------- 1 | >>> res = s.get("https://api.github.com/repos/python/cpython/pulls") 2 | >>> commits_url = res.json()[0]['commits_url'] 3 | >>> commits = s.get(commits_url).json() 4 | >>> print(commits[0]['commit']['message']) -------------------------------------------------------------------------------- /salt-basics-0.py: -------------------------------------------------------------------------------- 1 | file_server: # logical name of machine 2 | user: moshe # username 3 | sudo: True # boolean 4 | priv: /usr/local/key # path to private key 5 | print_server: # logical name of machine 6 | user: moshe # username 7 | sudo: True # boolean 8 | priv: /usr/local/key2 # path to private key -------------------------------------------------------------------------------- /salt-basics-1.py: -------------------------------------------------------------------------------- 1 | salt-ssh: 2 | config_dir: some/directory -------------------------------------------------------------------------------- /salt-basics-2.py: -------------------------------------------------------------------------------- 1 | $ salt '*' test.ping -------------------------------------------------------------------------------- /salt-basics-3.py: -------------------------------------------------------------------------------- 1 | $ salt '*' test.kwarg word="hello" number=5 2 | simple_dict='{thing: 1, other_thing: 2}' -------------------------------------------------------------------------------- /salt-basics-4.py: -------------------------------------------------------------------------------- 1 | {'word': 'hello', 'number': 5, 2 | 'simple_dict': {'thing': 1, 'other_thing': 2}} -------------------------------------------------------------------------------- /salt-basics-5.py: -------------------------------------------------------------------------------- 1 | $ salt '*' cmd.run 'mkdir /src' -------------------------------------------------------------------------------- /salt-basics-6.py: -------------------------------------------------------------------------------- 1 | $ salt '*' state.highstate -------------------------------------------------------------------------------- /salt-basics-7.py: -------------------------------------------------------------------------------- 1 | $ salt '*' state.apply -------------------------------------------------------------------------------- /salt-basics-8.py: -------------------------------------------------------------------------------- 1 | # top.sls 2 | base: 3 | '*': 4 | - core 5 | - monitoring 6 | - kubelet -------------------------------------------------------------------------------- /salt-formats-0.py: -------------------------------------------------------------------------------- 1 | {% if grains['os'] == 'CentOs' %} 2 | python-devel: 3 | {% elif grains['os'] == 'Debian' %} 4 | python-dev: 5 | {% endif %} 6 | pkg: 7 | - installed -------------------------------------------------------------------------------- /salt-formats-1.py: -------------------------------------------------------------------------------- 1 | {% if grains['os'] == 'CentOs' %} 2 | python-devel: 3 | {% elif grains['os'] == 'Debian' %} 4 | python-dev: 5 | {% else %} 6 | {{ raise('Unrecognized operating system', grains['os']) }} 7 | {% endif %} 8 | pkg: 9 | - installed -------------------------------------------------------------------------------- /salt-formats-2.py: -------------------------------------------------------------------------------- 1 | #!py 2 | def run(): 3 | if __grains__['os'] == 'CentOS': 4 | package_name = 'python-devel' 5 | elif __grains__['os'] == 'Debian': 6 | package_name = 'python-dev' 7 | else: 8 | raise ValueError("Unrecognized operating system", 9 | __grains__['os']) 10 | return { package_name: dict(pkg='installed') } -------------------------------------------------------------------------------- /salt-formats-3.py: -------------------------------------------------------------------------------- 1 | #!py 2 | def run(): 3 | if __grains__['os'] == 'CentOS': 4 | package_name = 'python-devel' 5 | elif __grains__['os'] == 'Debian': 6 | package_name = 'python-dev' 7 | return { package_name: dict(pkg='installed') } -------------------------------------------------------------------------------- /salt-terms-0.py: -------------------------------------------------------------------------------- 1 | name_of_state: 2 | state.identifier: 3 | - parameters 4 | - to 5 | - state -------------------------------------------------------------------------------- /salt-terms-1.py: -------------------------------------------------------------------------------- 1 | process_tools: 2 | pkg.installed: 3 | - pkgs: 4 | - procps -------------------------------------------------------------------------------- /salt-terms-2.py: -------------------------------------------------------------------------------- 1 | Extract archive: 2 | archive.extracted: 3 | - name: /src/some-files 4 | - source: /src/some-files.tgz 5 | - archive_format: tar 6 | - require: 7 | - file: Copy archive 8 | Copy archive: 9 | file.managed: 10 | - name: /src/some-files.tgz 11 | - source: salt://some-files.tgz -------------------------------------------------------------------------------- /salt-terms-3.py: -------------------------------------------------------------------------------- 1 | Extract archive: 2 | archive.extracted: 3 | - name: /src/some-files 4 | - source: /src/some-files.tgz 5 | - archive_format: tar 6 | Copy archive: 7 | file.managed: 8 | - name: /src/some-files.tgz 9 | - source: salt://some-files.tgz 10 | - require_in: 11 | - archive: Extract archive. -------------------------------------------------------------------------------- /security-0.py: -------------------------------------------------------------------------------- 1 | from requests.adapters import HTTPAdapter 2 | from requests.packages.urllib3.poolmanager import PoolManager 3 | 4 | class MyAdapter(HTTPAdapter): 5 | pass 6 | 7 | 8 | s = requests.Session() 9 | s.mount('https://', MyAdapter()) -------------------------------------------------------------------------------- /security-1.py: -------------------------------------------------------------------------------- 1 | class MyAdater(HTTPAdater) 2 | def init_poolmanager(self, connections, maxsize, block=False): 3 | self.poolmanager = PoolManager(num_pools=connections, 4 | maxsize=maxsize, 5 | block=block, 6 | ssl_version=ssl.PROTOCOL_TLS) -------------------------------------------------------------------------------- /security-2.py: -------------------------------------------------------------------------------- 1 | s = requests.Session() 2 | s.cert = "/path/to/pem/file.pem" -------------------------------------------------------------------------------- /security-3.py: -------------------------------------------------------------------------------- 1 | s = requests.Session() 2 | s.cert = ("/path/to/client.cert", "/path/to/client.key") -------------------------------------------------------------------------------- /sessions-0.py: -------------------------------------------------------------------------------- 1 | with requests.Session() as s: 2 | s.get(...) -------------------------------------------------------------------------------- /sessions-1.py: -------------------------------------------------------------------------------- 1 | session.headers = {'User-Agent': 'Python/MySoftware ' + __version__ } -------------------------------------------------------------------------------- /setup-and-wheels-0.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | setuptools.setup( 3 | packages=setuptools.find_packages(), 4 | ) -------------------------------------------------------------------------------- /setup-and-wheels-1.py: -------------------------------------------------------------------------------- 1 | setup.py 2 | import setuptools 3 | setuptools.setup( 4 | name='my_special_package', 5 | packages=setuptools.find_packages(), 6 | ) 7 | my_special_package/ 8 | __init__.py 9 | another_module.py 10 | tests/ 11 | test_another_module.py -------------------------------------------------------------------------------- /setup-and-wheels-2.py: -------------------------------------------------------------------------------- 1 | setuptools.find_packages(include=["my_package*"]) -------------------------------------------------------------------------------- /strings-0.py: -------------------------------------------------------------------------------- 1 | >>> a="hello" 2 | >>> for i, x in enumerate(a): 3 | ... print(i, x, len(x)) 4 | ... 5 | 0 h 1 6 | 1 e 1 7 | 2 l 1 8 | 3 l 1 9 | 4 o 1 -------------------------------------------------------------------------------- /strings-1.py: -------------------------------------------------------------------------------- 1 | >>> a[2:4] 2 | 'll' -------------------------------------------------------------------------------- /strings-10.py: -------------------------------------------------------------------------------- 1 | >>> names=dict(hello=1,world=2) 2 | >>> ' '.join(names) 3 | 'hello world' -------------------------------------------------------------------------------- /strings-11.py: -------------------------------------------------------------------------------- 1 | >>> '-*-'.join(str(x) for x in range(3)) 2 | '0-*-1-*-2' -------------------------------------------------------------------------------- /strings-2.py: -------------------------------------------------------------------------------- 1 | >>> a[:2] 2 | 'he' -------------------------------------------------------------------------------- /strings-3.py: -------------------------------------------------------------------------------- 1 | >>> a[3:] 2 | 'lo' -------------------------------------------------------------------------------- /strings-4.py: -------------------------------------------------------------------------------- 1 | >>> a[:-3] 2 | 'he' -------------------------------------------------------------------------------- /strings-5.py: -------------------------------------------------------------------------------- 1 | >>> a[::-1] 2 | 'olleh' -------------------------------------------------------------------------------- /strings-6.py: -------------------------------------------------------------------------------- 1 | >>> "hello world".endswith("world") 2 | True -------------------------------------------------------------------------------- /strings-7.py: -------------------------------------------------------------------------------- 1 | >>> "hello world".endswith(("universe", "world")) 2 | True -------------------------------------------------------------------------------- /strings-8.py: -------------------------------------------------------------------------------- 1 | >>> filename.endswith((".tgz", ".tar.gz")) -------------------------------------------------------------------------------- /strings-9.py: -------------------------------------------------------------------------------- 1 | with open("/etc/fstab") as fpin: 2 | for line in fpin: 3 | line = line.rstrip('\n') 4 | line = line.split('#', 1)[0] 5 | if not line: 6 | continue 7 | device, path, fstype, options, freq, passno = line.split() 8 | print(f"Mounting {device} on {path}") -------------------------------------------------------------------------------- /testing-files-0.py: -------------------------------------------------------------------------------- 1 | setenv = 2 | TMPDIR = {envtmpdir} 3 | commands = 4 | python -m 'import os;os.makedirs(sys.argv[1])' {envtmpdir} 5 | # rest of test commands -------------------------------------------------------------------------------- /testing-files-1.py: -------------------------------------------------------------------------------- 1 | def javascript_to_python_1(dirname): 2 | for fname in os.listdir(dirname): 3 | if fname.endswith('.js'): 4 | os.rename(fname, fname[:3] + '.py') -------------------------------------------------------------------------------- /testing-files-10.py: -------------------------------------------------------------------------------- 1 | def analyze_debian_paths(relative_to='/'): 2 | sources_dir = os.path.join(relative_to, 'etc/apt/sources.list.d') 3 | for fname in os.listdir(sources_dir): 4 | with open(os.path.join(sources_dir, fname)) as fpin: 5 | yield from _analyze_debian_paths_from_file(fpin) -------------------------------------------------------------------------------- /testing-files-11.py: -------------------------------------------------------------------------------- 1 | def test_analyze_debian_paths(): 2 | with get_temp_dir() as root: 3 | touch(os.path.join(root, 'foo.list'), 4 | content='deb http://foo.example.com\n') 5 | ret = list(analyze_debian_paths(relative_to=root)) 6 | assert(ret, equals_to(['foo.example.com'])) -------------------------------------------------------------------------------- /testing-files-2.py: -------------------------------------------------------------------------------- 1 | def javascript_to_python_2(dirname): 2 | for fname in glob.glob(os.path.join(dirname, "*.js")): 3 | os.rename(fname, fname[:3] + '.py') -------------------------------------------------------------------------------- /testing-files-3.py: -------------------------------------------------------------------------------- 1 | def javascript_to_python_3(dirname): 2 | for path in pathlib.Path(dirname).iterdir(): 3 | if path.suffix == '.js': 4 | path.rename(path.parent.joinpath(path.stem + '.py')) -------------------------------------------------------------------------------- /testing-files-4.py: -------------------------------------------------------------------------------- 1 | def javascript_to_python(dirname): 2 | return random.choice([javascript_to_python_1, 3 | javascript_to_python_2, 4 | javascript_to_python_3])(dirname) -------------------------------------------------------------------------------- /testing-files-5.py: -------------------------------------------------------------------------------- 1 | @contextlib.contextmanager 2 | def get_temp_dir(): 3 | temp_dir = tempfile.mkdtemp() 4 | try: 5 | yield temp_dir 6 | finally: 7 | shutil.rmtree(temp_dir) -------------------------------------------------------------------------------- /testing-files-6.py: -------------------------------------------------------------------------------- 1 | def touch(fname, content=''): 2 | with open(fname, 'a') as fpin: 3 | fpin.write(content) -------------------------------------------------------------------------------- /testing-files-7.py: -------------------------------------------------------------------------------- 1 | def test_javascript_to_python_simple(): 2 | with get_temp_dir() as temp_dir: 3 | touch(os.path.join(temp_dir, 'foo.js')) 4 | touch(os.path.join(temp_dir, 'bar.py')) 5 | touch(os.path.join(temp_dir, 'baz.txt')) 6 | javascript_to_python(temp_dir) 7 | assert_that(set(os.listdir(temp_dir)), 8 | is_({'foo.py', 'bar.py', 'baz.txt'})) -------------------------------------------------------------------------------- /testing-files-8.py: -------------------------------------------------------------------------------- 1 | def _analyze_debian_paths_from_file(fpin): 2 | for line in fpin: 3 | line = line.strip() 4 | if not line: 5 | continue 6 | line = line.split('#', 1)[0] 7 | parts = line.split() 8 | if parts[0] != 'deb': 9 | continue 10 | if parts[1][0] == '[': 11 | del parts[1] 12 | parsed = hyperlink.URL.from_text(parts[1].decode('ascii')) 13 | yield parsed.host -------------------------------------------------------------------------------- /testing-files-9.py: -------------------------------------------------------------------------------- 1 | def analyze_debian_paths(): 2 | for fname in os.listdir('/etc/apt/sources.list.d'): 3 | with open(os.path.join('/etc/apt/sources.list.d', fname)) as fpin: 4 | yield from _analyze_debian_paths_from_file(fpin) -------------------------------------------------------------------------------- /testing-network-0.py: -------------------------------------------------------------------------------- 1 | def get_files(gist_id): 2 | gist = requests.get(f"https://api.github.com/gists/{gist_id}").json() 3 | result = {} 4 | for name, details in gist["files"].items(): 5 | result[name] = requests.get(details["raw_url"]).content 6 | return result -------------------------------------------------------------------------------- /testing-network-1.py: -------------------------------------------------------------------------------- 1 | def get_files(gist_id, session=None): 2 | if session is None: 3 | session = requests.Session() 4 | gist = session.get(f"https://api.github.com/gists/{gist_id}").json() 5 | result = {} 6 | for name, details in gist["files"].items(): 7 | result[name] = session.get(details["raw_url"]).content 8 | return result -------------------------------------------------------------------------------- /testing-network-2.py: -------------------------------------------------------------------------------- 1 | @attr.s(frozen=True) 2 | class Gist: 3 | 4 | files = attr.ib() 5 | 6 | @attr.s(frozen=True): 7 | class Response: 8 | 9 | content = attr.ib() 10 | 11 | def json(self): 12 | return json.loads(content) 13 | 14 | @attr.s(frozen=True) 15 | class FakeSession: 16 | 17 | _gists = attr.ib() 18 | 19 | def get(self, url): 20 | parsed = hyperlink.URL.from_text(url) 21 | if parsed.host == 'api.github.com': 22 | tail = path.rsplit('/', 1)[-1] 23 | gist = self._gists[tail] 24 | res = dict(files={name: f'http://example.com/{tail}/{name}' 25 | for name in gist.files}) 26 | return Repsonse(json.dumps(res)) 27 | if parsed.host == 'example.com': 28 | _ignored, gist, name = path.split('/') 29 | return Response(self.gists[gist][name]) -------------------------------------------------------------------------------- /testing-network-3.py: -------------------------------------------------------------------------------- 1 | def make_mock(): 2 | gist_name = 'some_name' 3 | files = {'some_file': 'some_content'} 4 | session = mock.Mock() 5 | session.get.content.return_value = 'some_content' 6 | session.get.json.return_value = json.dumps({'files': 'some_file'}) 7 | return session -------------------------------------------------------------------------------- /testing-network-4.py: -------------------------------------------------------------------------------- 1 | @attr.s 2 | class FakeSimpleSocket: 3 | 4 | _chunk_size = attr.ib() 5 | 6 | _received = attr.ib(init=False, factory=list) 7 | 8 | _to_send = attr.ib() 9 | 10 | def connect(self, addr): 11 | pass 12 | 13 | def send(self, blob): 14 | actually_sent = blob[:chunk_size] 15 | self._received.append(actually_sent) 16 | return len(actually_sent) 17 | 18 | def recv(self, max_size): 19 | chunk_size = min(max_size, self._chunk_size) 20 | received, self._to_send = (self._to_send[:chunk_size], 21 | self._to_send[chunk_size:]) 22 | return received -------------------------------------------------------------------------------- /testing-network-5.py: -------------------------------------------------------------------------------- 1 | def get_get(sock): 2 | sock.connect(('httpbin.org', 80)) 3 | sock.send(b'GET /get HTTP/1.0\r\nHost: httpbin.org\r\n\r\n') 4 | res = sock.recv(1024) 5 | return json.loads(res.decode('ascii').split('\r\n\r\n', 1)[1])) -------------------------------------------------------------------------------- /testing-network-6.py: -------------------------------------------------------------------------------- 1 | def test_get_get(): 2 | result = dict(url='http://httpbin.org/get') 3 | headers = 'HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n' 4 | output = headers + json.dumps(result) 5 | fake_sock = FakeSimpleSocket(to_send=output, chunk_size=1) 6 | value = get_get(fake_sock) 7 | assert_that(value, is_(result)) -------------------------------------------------------------------------------- /testing-processes-0.py: -------------------------------------------------------------------------------- 1 | def error_lines(container_name): 2 | logs = subprocess.check_output(["docker", "logs", container_name]) 3 | for line in logs: 4 | if 'error' in line: 5 | return line -------------------------------------------------------------------------------- /testing-processes-1.py: -------------------------------------------------------------------------------- 1 | def error_lines(container_name, runner=subprocess.check_output): 2 | logs = runner(["docker", "logs", container_name]) 3 | for line in logs: 4 | if 'error' in line: 5 | yield line.strip() -------------------------------------------------------------------------------- /testing-processes-2.py: -------------------------------------------------------------------------------- 1 | def test_error_lines(): 2 | container_name = 'foo' 3 | 4 | def runner(args): 5 | if args[0] != 'docker': 6 | raise ValueError("Can only run docker", args) 7 | if args[1] != 'logs': 8 | raise ValueError("Can only run docker logs", args) 9 | if args[2] != container_name: 10 | raise ValueError("No such container", args[2]) 11 | return iter(["hello\n", "error: 5 is not 6\n", "goodbye\n"]) 12 | ret = error_lines(container_name, runner=runner) 13 | assert_that(list(ret), is_(["error: 5 is not 6")) -------------------------------------------------------------------------------- /testing-processes-3.py: -------------------------------------------------------------------------------- 1 | def runner(args): 2 | if args[0] != 'docker': 3 | raise ValueError("Can only run docker", args) 4 | if args[1] != 'logs': 5 | raise ValueError("Can only run docker logs", args) 6 | if args[2] == '--': 7 | arg_container_name = args[3] 8 | else: 9 | arg_container_name = args[2] 10 | if args_container_name != container_name: 11 | raise ValueError("No such container", args[2]) 12 | return iter(["hello\n", "error: 5 is not 6\n", "goodbye\n"]) -------------------------------------------------------------------------------- /testing-processes-4.py: -------------------------------------------------------------------------------- 1 | def error_lines(container_name, executor): 2 | logs, _ignored = executor.docker.logs(container_name).batch() 3 | for line in logs.splitlines(): 4 | if 'error' in line: 5 | yield line.strip() -------------------------------------------------------------------------------- /testing-processes-5.py: -------------------------------------------------------------------------------- 1 | executor = seashore.Executor(seashore.Shell()) -------------------------------------------------------------------------------- /testing-processes-6.py: -------------------------------------------------------------------------------- 1 | @attr.s 2 | class DummyShell: 3 | 4 | _container_name = attr.ib() 5 | 6 | def batch(self, *args, **kwargs): 7 | if (args == ['docker', 'logs', self._container_name] and 8 | kwargs == {}): 9 | return "hello\nerror: 5 is not 6\ngoodbye\n", "" 10 | raise ValueError("unknown command", self, args, kwargs) 11 | 12 | def test_error_lines(): 13 | container_name = 'foo' 14 | executor = seashore.Executor(DummyShell(container_name)) 15 | ret = error_lines(container_name, executor) 16 | assert_that(list(ret), is_(["error: 5 is not 6"])) -------------------------------------------------------------------------------- /testing-processes-7.py: -------------------------------------------------------------------------------- 1 | ps aux | grep conky | grep -v grep | awk '{print $2}' | xargs kill -------------------------------------------------------------------------------- /testing-processes-8.py: -------------------------------------------------------------------------------- 1 | def get_pids(lines): 2 | for line in lines: 3 | if 'conky' not in line: 4 | continue 5 | parts = line.split() 6 | pid_part = parts[1] 7 | pid = int(pid_part) 8 | yield pid 9 | 10 | def ps_aux(runner=subprocess.check_output): 11 | return runner(["ps", "aux"]) 12 | 13 | def kill(pids, killer=os.kill): 14 | for pid in pids: 15 | killer(pid, signal.SIGTERM) 16 | 17 | def main(): 18 | kill(get_pid(ps_aux())) -------------------------------------------------------------------------------- /tls-certificate-0.py: -------------------------------------------------------------------------------- 1 | >>> from cryptography.hazmat.backends import default_backend -------------------------------------------------------------------------------- /tls-certificate-1.py: -------------------------------------------------------------------------------- 1 | >>> from cryptography.hazmat.primitives.asymmetric import rsa 2 | >>> private_key = rsa.generate_private_key( 3 | ... public_exponent=65537, 4 | ... key_size=2048, 5 | ... backend=default_backend() 6 | ... ) -------------------------------------------------------------------------------- /tls-certificate-10.py: -------------------------------------------------------------------------------- 1 | >>> builder = builder.add_extension( 2 | ... x509.BasicConstraints(ca=True, path_length=None), 3 | ... critical=True) -------------------------------------------------------------------------------- /tls-certificate-11.py: -------------------------------------------------------------------------------- 1 | >>> from cryptography.hazmat.primitives import hashes 2 | >>> certificate = builder.sign( 3 | ... private_key=private_key, algorithm=hashes.SHA256(), 4 | ... backend=default_backend() 5 | ... ) -------------------------------------------------------------------------------- /tls-certificate-12.py: -------------------------------------------------------------------------------- 1 | >>> from cryptography.hazmat.primitives import serialization 2 | >>> private_bytes = private_key.private_bytes( 3 | ... encoding=serialization.Encoding.PEM, 4 | ... format=serialization.PrivateFormat.TraditionalOpenSSL, 5 | ... encryption_algorithm=serialization.NoEncrption()) 6 | >>> public_bytes = certificate.public_bytes( 7 | ... encoding=serialization.Encoding.PEM) 8 | >>> with open("ca.pem", "wb") as fout: 9 | ... fout.write(private_bytes + public_bytes) 10 | >>> with open("ca.crt", "wb") as fout: 11 | ... fout.write(public_bytes) -------------------------------------------------------------------------------- /tls-certificate-13.py: -------------------------------------------------------------------------------- 1 | >>> service_private_key = rsa.generate_private_key( 2 | ... public_exponent=65537, 3 | ... key_size=2048, 4 | ... backend=default_backend() 5 | ... ) -------------------------------------------------------------------------------- /tls-certificate-14.py: -------------------------------------------------------------------------------- 1 | >>> service_public_key = service_private_key.public_key() -------------------------------------------------------------------------------- /tls-certificate-15.py: -------------------------------------------------------------------------------- 1 | >>> builder = x509.CertificateBuilder() -------------------------------------------------------------------------------- /tls-certificate-16.py: -------------------------------------------------------------------------------- 1 | >>> builder = builder.subject_name(x509.Name([ 2 | ... x509.NameAttribute(NameOID.COMMON_NAME, 'service.test.local') 3 | ... ])) -------------------------------------------------------------------------------- /tls-certificate-17.py: -------------------------------------------------------------------------------- 1 | >>> builder = builder.not_valid_before(yesterday) 2 | >>> builder = builder.not_valid_after(next_month) -------------------------------------------------------------------------------- /tls-certificate-18.py: -------------------------------------------------------------------------------- 1 | >>> builder = builder.public_key(public_key) -------------------------------------------------------------------------------- /tls-certificate-19.py: -------------------------------------------------------------------------------- 1 | >>> certificate = builder.sign( 2 | ... private_key=private_key, algorithm=hashes.SHA256(), 3 | ... backend=default_backend() 4 | ... ) -------------------------------------------------------------------------------- /tls-certificate-2.py: -------------------------------------------------------------------------------- 1 | >>> public_key = private_key.public_key() -------------------------------------------------------------------------------- /tls-certificate-20.py: -------------------------------------------------------------------------------- 1 | >>> private_bytes = service_private_key.private_bytes( 2 | ... encoding=serialization.Encoding.PEM, 3 | ... format=serialization.PrivateFormat.TraditionalOpenSSL, 4 | ... encryption_algorithm=serialization.NoEncrption()) 5 | >>> public_bytes = certificate.public_bytes( 6 | ... encoding=serialization.Encoding.PEM) 7 | >>> with open("service.pem", "wb") as fout: 8 | ... fout.write(private_bytes + public_bytes) -------------------------------------------------------------------------------- /tls-certificate-3.py: -------------------------------------------------------------------------------- 1 | >>> from cryptography import x509 2 | >>> builder = x509.CertificateBuilder() -------------------------------------------------------------------------------- /tls-certificate-4.py: -------------------------------------------------------------------------------- 1 | >>> from cryptography.x509.oid import NameOID 2 | >>> builder = builder.subject_name(x509.Name([ 3 | ... x509.NameAttribute(NameOID.COMMON_NAME, 'Simple Test CA'), 4 | ... ])) 5 | >>> builder = builder.issuer_name(x509.Name([ 6 | ... x509.NameAttribute(NameOID.COMMON_NAME, 'Simple Test CA'), 7 | ... ])) -------------------------------------------------------------------------------- /tls-certificate-5.py: -------------------------------------------------------------------------------- 1 | >>> import datetime 2 | >>> one_day = datetime.timedelta(days=1) -------------------------------------------------------------------------------- /tls-certificate-6.py: -------------------------------------------------------------------------------- 1 | >>> today = datetime.date.today() 2 | >>> yesterday = today - one_day 3 | >>> builder = builder.not_valid_before(yesterday) -------------------------------------------------------------------------------- /tls-certificate-7.py: -------------------------------------------------------------------------------- 1 | >>> next_month = today + (30 * day) 2 | >>> builder = builder.not_valid_after(next_month) -------------------------------------------------------------------------------- /tls-certificate-8.py: -------------------------------------------------------------------------------- 1 | >>> builder = builder.serial_number(x509.random_serial_number()) -------------------------------------------------------------------------------- /tls-certificate-9.py: -------------------------------------------------------------------------------- 1 | >>> builder = builder.public_key(public_key) -------------------------------------------------------------------------------- /tox-0.py: -------------------------------------------------------------------------------- 1 | [testenv:some-name] 2 | 3 | . 4 | . 5 | . -------------------------------------------------------------------------------- /tox-1.py: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py36,pypy3.5,py36-flake8 -------------------------------------------------------------------------------- /tox-10.py: -------------------------------------------------------------------------------- 1 | deps = 2 | {py36,py27,pypy}-unit: coverage 3 | {py27,pypy}-lint: pylint==1.8.1 4 | {py27,pypy}-lint: flake8 5 | {py27,pypy}-lint: incremental 6 | {py36,py27,pypy}-{func,unit}: Twisted -------------------------------------------------------------------------------- /tox-11.py: -------------------------------------------------------------------------------- 1 | commands = 2 | {py36,py27,pypy}-unit: python -Wall \ 3 | -Wignore::DeprecationWarning \ 4 | -m coverage \ 5 | run -m twisted.trial \ 6 | --temp-directory build/_trial_temp \ 7 | {posargs:ncolony} 8 | {py36,py27,pypy}-unit: coverage report --include ncolony* \ 9 | --omit */tests/*,*/interfaces*,*/_version* \ --show-missing --fail-under=100 10 | py27-lint: pylint --rcfile admin/pylintrc ncolony 11 | py27-lint: python -m ncolony tests.nitpicker 12 | py27-lint: flake8 ncolony 13 | {py36,py27,pypy}-func: python -Werror -W ignore::DeprecationWarning \ 14 | -W ignore::ImportWarning \ 15 | -m ncolony tests.functional_test -------------------------------------------------------------------------------- /tox-12.py: -------------------------------------------------------------------------------- 1 | [testenv:py27-wheel] 2 | skip_install = True 3 | deps = 4 | coverage 5 | Twisted 6 | wheel 7 | gather 8 | commands = 9 | mkdir -p {envtmpdir}/dist 10 | pip wheel . --no-deps --wheel-dir {envtmpdir}/dist 11 | sh -c "pip install --no-index {envtmpdir}/dist/*.whl" 12 | coverage run {envbindir}/trial \ 13 | --temp-directory build/_trial_temp {posargs:ncolony} 14 | coverage report --include */site-packages/ncolony* \ 15 | --omit */tests/*,*/interfaces*,*/_version* \ 16 | --show-missing --fail-under=100 -------------------------------------------------------------------------------- /tox-13.py: -------------------------------------------------------------------------------- 1 | [testenv:docs] 2 | changedir = docs 3 | deps = 4 | sphinx 5 | Twisted 6 | commands = 7 | sphinx-build -W -b html -d {envtmpdir}/doctrees . {envtmpdir}/html 8 | basepython = python2.7 -------------------------------------------------------------------------------- /tox-2.py: -------------------------------------------------------------------------------- 1 | [testenv:py36-flake8] -------------------------------------------------------------------------------- /tox-3.py: -------------------------------------------------------------------------------- 1 | deps = 2 | flake8 -------------------------------------------------------------------------------- /tox-4.py: -------------------------------------------------------------------------------- 1 | commands = 2 | flake8 useful -------------------------------------------------------------------------------- /tox-5.py: -------------------------------------------------------------------------------- 1 | [testenv] -------------------------------------------------------------------------------- /tox-6.py: -------------------------------------------------------------------------------- 1 | deps = 2 | pytest -------------------------------------------------------------------------------- /tox-7.py: -------------------------------------------------------------------------------- 1 | commands = 2 | pytest useful -------------------------------------------------------------------------------- /tox-8.py: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = {py36,py27,pypy}-{unit,func},py27-lint,py27-wheel,docs 3 | toxworkdir = {toxinidir}/build/.tox -------------------------------------------------------------------------------- /tox-9.py: -------------------------------------------------------------------------------- 1 | [testenv] -------------------------------------------------------------------------------- /unit-testing-0.py: -------------------------------------------------------------------------------- 1 | def write_numbers(fout): 2 | fout.write("1\n") 3 | fout.write("2\n") 4 | fout.write("3\n") -------------------------------------------------------------------------------- /unit-testing-1.py: -------------------------------------------------------------------------------- 1 | class DummyFile: 2 | 3 | def __init__(self): 4 | self.written = [] 5 | 6 | def write(self, thing): 7 | self.written.append(thing) 8 | 9 | def test_write_numbers(): 10 | fout = DummyFile() 11 | write_numbers(fout) 12 | assert_that(fout.written, is_(["1\n", "2\n", "3\n"])) -------------------------------------------------------------------------------- /unit-testing-2.py: -------------------------------------------------------------------------------- 1 | def write_numbers(fout): 2 | fout.write("1\n2\n3\n") -------------------------------------------------------------------------------- /unit-testing-3.py: -------------------------------------------------------------------------------- 1 | class DummyFile: 2 | 3 | def __init__(self): 4 | self.written = [] 5 | 6 | def write(self, thing): 7 | self.written.append(thing) 8 | 9 | def test_write_numbers(): 10 | fout = DummyFile() 11 | write_numbers(fout) 12 | assert_that("".join(fout.written), is_("1\n2\n3\n")) -------------------------------------------------------------------------------- /unit-testing-4.py: -------------------------------------------------------------------------------- 1 | def write_numbers(fout): 2 | fout.writelines(["1\n", 3 | "2\n", 4 | "3\n"] -------------------------------------------------------------------------------- /unit-testing-5.py: -------------------------------------------------------------------------------- 1 | def test_write_numbers(): 2 | fout = io.StringIO() 3 | write_numbers(fout) 4 | assert_that(fout.getvalue(), is_("1\n2\n3\n")) -------------------------------------------------------------------------------- /unit-testing-6.py: -------------------------------------------------------------------------------- 1 | class DivisibleBy(hamcrest.core.base_matcher.BaseMatcher): 2 | 3 | def __init__(self, factor): 4 | self.factor = factor 5 | 6 | def _matches(self, item): 7 | return (item % self.factor) == 0 8 | 9 | def describe_to(self, description): 10 | description.append_text('number divisible by') 11 | description.append_text(repr(self.factor)) 12 | 13 | def divisible_by(num): 14 | return DivisibleBy(num) -------------------------------------------------------------------------------- /unit-testing-7.py: -------------------------------------------------------------------------------- 1 | def test_scale(): 2 | result = scale_one(3, 7) 3 | assert_that(result, 4 | any_of(divisible_by(3), 5 | divisible_by(7))) -------------------------------------------------------------------------------- /unit-testing-8.py: -------------------------------------------------------------------------------- 1 | Expected: (number divisible by 3 or number divisible by 7) 2 | but: was <17> -------------------------------------------------------------------------------- /virtualenv-0.py: -------------------------------------------------------------------------------- 1 | $ source /home/name/venvs/my-special-env/bin/activate -------------------------------------------------------------------------------- /xar-0.py: -------------------------------------------------------------------------------- 1 | python setup.py bdist_xar --console-scripts=my-script -------------------------------------------------------------------------------- /xar-1.py: -------------------------------------------------------------------------------- 1 | entry_points=dict( 2 | console_scripts=["my-script = package.module:function"], 3 | ) --------------------------------------------------------------------------------