pax_global_header00006660000000000000000000000064142772130500014513gustar00rootroot0000000000000052 comment=68f26a70d9875366e52b81e5a38587ef57dad4fa hexbytes-0.3.0/000077500000000000000000000000001427721305000133465ustar00rootroot00000000000000hexbytes-0.3.0/.bumpversion.cfg000066400000000000000000000007221427721305000164570ustar00rootroot00000000000000[bumpversion] current_version = 0.3.0 commit = True tag = True parse = (?P\d+)\.(?P\d+)\.(?P\d+)(-(?P[^.]*)\.(?P\d+))? serialize = {major}.{minor}.{patch}-{stage}.{devnum} {major}.{minor}.{patch} [bumpversion:part:stage] optional_value = stable first_value = stable values = alpha beta stable [bumpversion:part:devnum] [bumpversion:file:setup.py] search = version="{current_version}", replace = version="{new_version}", hexbytes-0.3.0/.circleci/000077500000000000000000000000001427721305000152015ustar00rootroot00000000000000hexbytes-0.3.0/.circleci/config.yml000066400000000000000000000045471427721305000172030ustar00rootroot00000000000000version: 2.0 # heavily inspired by: # https://raw.githubusercontent.com/pinax/pinax-wiki/6bd2a99ab6f702e300d708532a6d1d9aa638b9f8/.circleci/config.yml common: &common working_directory: ~/repo steps: - checkout - run: name: merge pull request base command: ./.circleci/merge_pr.sh - run: name: merge pull request base (2nd try) command: ./.circleci/merge_pr.sh when: on_fail - run: name: merge pull request base (3nd try) command: ./.circleci/merge_pr.sh when: on_fail - restore_cache: keys: - cache-v1-{{ arch }}-{{ .Environment.CIRCLE_JOB }}-{{ checksum "setup.py" }}-{{ checksum "tox.ini" }} - run: name: install dependencies command: pip install --user tox - run: name: run tox command: ~/.local/bin/tox -r - save_cache: paths: - .hypothesis - .tox - ~/.cache/pip - ~/.local - ./eggs key: cache-v1-{{ arch }}-{{ .Environment.CIRCLE_JOB }}-{{ checksum "setup.py" }}-{{ checksum "tox.ini" }} jobs: docs: <<: *common docker: - image: cimg/python:3.10 environment: TOXENV: docs py37-lint: <<: *common docker: - image: cimg/python:3.7 environment: TOXENV: py37-lint py37-core: <<: *common docker: - image: cimg/python:3.7 environment: TOXENV: py37-core py38-lint: <<: *common docker: - image: cimg/python:3.8 environment: TOXENV: py38-lint py38-core: <<: *common docker: - image: cimg/python:3.8 environment: TOXENV: py38-core py39-lint: <<: *common docker: - image: cimg/python:3.9 environment: TOXENV: py39-lint py39-core: <<: *common docker: - image: cimg/python:3.9 environment: TOXENV: py39-core py310-lint: <<: *common docker: - image: cimg/python:3.10 environment: TOXENV: py310-lint py310-core: <<: *common docker: - image: cimg/python:3.10 environment: TOXENV: py310-core workflows: version: 2 test: jobs: - docs - py37-lint - py38-lint - py39-lint - py310-lint - py37-core - py38-core - py39-core - py310-core hexbytes-0.3.0/.circleci/merge_pr.sh000077500000000000000000000011271427721305000173410ustar00rootroot00000000000000#!/usr/bin/env bash if [[ -n "${CIRCLE_PR_NUMBER}" ]]; then PR_INFO_URL=https://api.github.com/repos/$CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME/pulls/$CIRCLE_PR_NUMBER PR_BASE_BRANCH=$(curl -L "$PR_INFO_URL" | python -c 'import json, sys; obj = json.load(sys.stdin); sys.stdout.write(obj["base"]["ref"])') git fetch origin +"$PR_BASE_BRANCH":circleci/pr-base # We need these config values or git complains when creating the # merge commit git config --global user.name "Circle CI" git config --global user.email "circleci@example.com" git merge --no-edit circleci/pr-base fi hexbytes-0.3.0/.github/000077500000000000000000000000001427721305000147065ustar00rootroot00000000000000hexbytes-0.3.0/.github/ISSUE_TEMPLATE.md000066400000000000000000000011271427721305000174140ustar00rootroot00000000000000 _If this is a bug report, please fill in the following sections. If this is a feature request, delete and describe what you would like with examples._ ## What was wrong? ### Code that produced the error ```py CODE_TO_REPRODUCE ``` ### Full error output ```sh ERROR_HERE ``` ### Expected Result _This section may be deleted if the expectation is "don't crash"._ ```sh EXPECTED_RESULT ``` ### Environment ```sh # run this: $ python -m eth_utils # then copy the output here: OUTPUT_HERE ``` ## How can it be fixed? Fill this section in if you know how this could or should be fixed. hexbytes-0.3.0/.github/PULL_REQUEST_TEMPLATE.md000066400000000000000000000012121427721305000205030ustar00rootroot00000000000000## What was wrong? Issue # ## How was it fixed? Summary of approach. ### To-Do [//]: # (Stay ahead of things, add list items here!) - [ ] Clean up commit history [//]: # (For important changes that should go into the release notes please add a newsfragment file as explained here: https://github.com/ethereum/hexbytes/blob/master/newsfragments/README.md) [//]: # (See: https://hexbytes.readthedocs.io/en/latest/contributing.html#pull-requests) - [ ] Add entry to the [release notes](https://github.com/ethereum/hexbytes/blob/master/newsfragments/README.md) #### Cute Animal Picture ![put a cute animal picture link inside the parentheses]() hexbytes-0.3.0/.gitignore000066400000000000000000000023711427721305000153410ustar00rootroot00000000000000*.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build eggs .eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 pip-wheel-metadata venv* # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject # Complexity output/*.html output/*/index.html # Sphinx docs/_build docs/modules.rst docs/*.internal.rst docs/*.utils.rst docs/*._utils.* # Blockchain chains # Hypothese Property base testing .hypothesis # tox/pytest cache .cache .pytest_cache # Test output logs logs # VIM temp files *.sw[op] # mypy .mypy_cache # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm # For a more precise, explicit template, see: # https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 ## General .idea/* .idea_modules/* ## File-based project format: *.iws ## IntelliJ out/ ## Plugin-specific files: ### mpeltonen/sbt-idea plugin .idea_modules/ ### JIRA plugin atlassian-ide-plugin.xml ### Crashlytics plugin (for Android Studio and IntelliJ) com_crashlytics_export_strings.xml crashlytics.properties crashlytics-build.properties fabric.properties # END JetBrains section hexbytes-0.3.0/.project-template/000077500000000000000000000000001427721305000167035ustar00rootroot00000000000000hexbytes-0.3.0/.project-template/fill_template_vars.sh000077500000000000000000000027151427721305000231230ustar00rootroot00000000000000#!/bin/bash set -o errexit set -o nounset set -o pipefail PROJECT_ROOT=$(dirname $(dirname $(python -c 'import os, sys; sys.stdout.write(os.path.realpath(sys.argv[1]))' "$0"))) echo "What is your python module name?" read MODULE_NAME echo "What is your pypi package name? (default: $MODULE_NAME)" read PYPI_INPUT PYPI_NAME=${PYPI_INPUT:-$MODULE_NAME} echo "What is your github project name? (default: $PYPI_NAME)" read REPO_INPUT REPO_NAME=${REPO_INPUT:-$PYPI_NAME} echo "What is your readthedocs.org project name? (default: $PYPI_NAME)" read RTD_INPUT RTD_NAME=${RTD_INPUT:-$PYPI_NAME} echo "What is your project name (ex: at the top of the README)? (default: $REPO_NAME)" read PROJECT_INPUT PROJECT_NAME=${PROJECT_INPUT:-$REPO_NAME} echo "What is a one-liner describing the project?" read SHORT_DESCRIPTION _replace() { echo "Replacing values: $1" local find_cmd=(find "$PROJECT_ROOT" ! -perm -u=x ! -path '*/.git/*' ! -path '*/venv*/*' -type f) if [[ $(uname) == Darwin ]]; then "${find_cmd[@]}" -exec sed -i '' "$1" {} + else "${find_cmd[@]}" -exec sed -i "$1" {} + fi } _replace "s//$MODULE_NAME/g" _replace "s//$PYPI_NAME/g" _replace "s//$REPO_NAME/g" _replace "s//$RTD_NAME/g" _replace "s//$PROJECT_NAME/g" _replace "s//$SHORT_DESCRIPTION/g" mkdir -p "$PROJECT_ROOT/$MODULE_NAME" touch "$PROJECT_ROOT/$MODULE_NAME/__init__.py" touch "$PROJECT_ROOT/$MODULE_NAME/py.typed" hexbytes-0.3.0/.project-template/refill_template_vars.sh000077500000000000000000000001651427721305000234470ustar00rootroot00000000000000TEMPLATE_DIR=$(dirname $(readlink -f "$0")) <"$TEMPLATE_DIR/template_vars.txt" "$TEMPLATE_DIR/fill_template_vars.sh" hexbytes-0.3.0/.project-template/template_vars.txt000066400000000000000000000001661427721305000223150ustar00rootroot00000000000000hexbytes hexbytes hexbytes hexbytes HexBytes Python `bytes` subclass that decodes hex, with a readable console output hexbytes-0.3.0/.pydocstyle.ini000066400000000000000000000022321427721305000163230ustar00rootroot00000000000000[pydocstyle] ; All error codes found here: ; http://www.pydocstyle.org/en/3.0.0/error_codes.html ; ; Ignored: ; D1 - Missing docstring error codes ; ; Selected: ; D2 - Whitespace error codes ; D3 - Quote error codes ; D4 - Content related error codes select=D2,D3,D4 ; Extra ignores: ; D200 - One-line docstring should fit on one line with quotes ; D203 - 1 blank line required before class docstring ; D204 - 1 blank line required after class docstring ; D205 - 1 blank line required between summary line and description ; D212 - Multi-line docstring summary should start at the first line ; D302 - Use u""" for Unicode docstrings ; D400 - First line should end with a period ; D401 - First line should be in imperative mood ; D412 - No blank lines allowed between a section header and its content add-ignore=D200,D203,D204,D205,D212,D302,D400,D401,D412 ; Explanation: ; D400 - Enabling this error code seems to make it a requirement that the first ; sentence in a docstring is not split across two lines. It also makes it a ; requirement that no docstring can have a multi-sentence description without a ; summary line. Neither one of those requirements seem appropriate. hexbytes-0.3.0/LICENSE000066400000000000000000000021021427721305000143460ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2020 The Ethereum Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. hexbytes-0.3.0/MANIFEST.in000066400000000000000000000002401427721305000151000ustar00rootroot00000000000000include LICENSE include README.md include requirements-docs.txt global-include *.pyi recursive-exclude * __pycache__ recursive-exclude * *.py[co] prune venv* hexbytes-0.3.0/Makefile000066400000000000000000000050701427721305000150100ustar00rootroot00000000000000CURRENT_SIGN_SETTING := $(shell git config commit.gpgSign) .PHONY: clean-pyc clean-build docs help: @echo "clean-build - remove build artifacts" @echo "clean-pyc - remove Python file artifacts" @echo "lint - check style with flake8" @echo "lint-roll - automatically fix problems with isort, flake8, etc" @echo "test - run tests quickly with the default Python" @echo "testall - run tests on every Python version with tox" @echo "docs - generate docs and open in browser (linux-docs for version on linux)" @echo "notes - consume towncrier newsfragments/ and update release notes in docs/" @echo "release - package and upload a release (does not run notes target)" @echo "dist - package" clean: clean-build clean-pyc clean-build: rm -fr build/ rm -fr dist/ rm -fr *.egg-info clean-pyc: find . -name '*.pyc' -exec rm -f {} + find . -name '*.pyo' -exec rm -f {} + find . -name '*~' -exec rm -f {} + find . -name '__pycache__' -exec rm -rf {} + lint: tox -elint lint-roll: isort --recursive hexbytes tests $(MAKE) lint test: pytest tests test-all: tox build-docs: sphinx-apidoc -o docs/ . setup.py "*conftest*" $(MAKE) -C docs clean $(MAKE) -C docs html $(MAKE) -C docs doctest validate-docs: python ./newsfragments/validate_files.py towncrier build --draft --version preview check-docs: build-docs validate-docs docs: check-docs open docs/_build/html/index.html linux-docs: check-docs xdg-open docs/_build/html/index.html check-bump: ifndef bump $(error bump must be set, typically: major, minor, patch, or devnum) endif notes: check-bump # Let UPCOMING_VERSION be the version that is used for the current bump $(eval UPCOMING_VERSION=$(shell bumpversion $(bump) --dry-run --list | grep new_version= | sed 's/new_version=//g')) # Now generate the release notes to have them included in the release commit towncrier build --yes --version $(UPCOMING_VERSION) # Before we bump the version, make sure that the towncrier-generated docs will build make build-docs git commit -m "Compile release notes" release: check-bump clean # require that you be on a branch that's linked to upstream/master git status -s -b | head -1 | grep "\.\.upstream/master" # verify that docs build correctly ./newsfragments/validate_files.py is-empty make build-docs CURRENT_SIGN_SETTING=$(git config commit.gpgSign) git config commit.gpgSign true bumpversion $(bump) git push upstream && git push upstream --tags python setup.py sdist bdist_wheel twine upload dist/* git config commit.gpgSign "$(CURRENT_SIGN_SETTING)" dist: clean python setup.py sdist bdist_wheel ls -l dist hexbytes-0.3.0/README.md000066400000000000000000000073241427721305000146330ustar00rootroot00000000000000# HexBytes [![Join the chat at https://gitter.im/ethereum/web3.py](https://badges.gitter.im/ethereum/web3.py.svg)](https://gitter.im/ethereum/web3.py?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://circleci.com/gh/ethereum/hexbytes.svg?style=shield)](https://circleci.com/gh/ethereum/hexbytes) [![PyPI version](https://badge.fury.io/py/hexbytes.svg)](https://badge.fury.io/py/hexbytes) [![Python versions](https://img.shields.io/pypi/pyversions/hexbytes.svg)](https://pypi.python.org/pypi/hexbytes) [![Docs build](https://readthedocs.org/projects/hexbytes/badge/?version=latest)](http://hexbytes.readthedocs.io/en/latest/?badge=latest) Python `bytes` subclass that decodes hex, with a readable console output Read more in the [documentation on ReadTheDocs](https://hexbytes.readthedocs.io/). [View the change log](https://hexbytes.readthedocs.io/en/latest/release_notes.html). ## Quickstart ```sh pip install hexbytes ``` ```py # convert from bytes to a prettier representation at the console >>> HexBytes(b"\x03\x08wf\xbfh\xe7\x86q\xd1\xeaCj\xe0\x87\xdat\xa1'a\xda\xc0 \x01\x1a\x9e\xdd\xc4\x90\x0b\xf1;") HexBytes('0x03087766bf68e78671d1ea436ae087da74a12761dac020011a9eddc4900bf13b') # HexBytes accepts the hex string representation as well, ignoring case and 0x prefixes >>> hb = HexBytes('03087766BF68E78671D1EA436AE087DA74A12761DAC020011A9EDDC4900BF13B') HexBytes('0x03087766bf68e78671d1ea436ae087da74a12761dac020011a9eddc4900bf13b') # get the first byte: >>> hb[0] 3 # show how many bytes are in the value >>> len(hb) 32 # cast back to the basic `bytes` type >>> bytes(hb) b"\x03\x08wf\xbfh\xe7\x86q\xd1\xeaCj\xe0\x87\xdat\xa1'a\xda\xc0 \x01\x1a\x9e\xdd\xc4\x90\x0b\xf1;" ``` ## Developer Setup If you would like to hack on hexbytes, please check out the [Snake Charmers Tactical Manual](https://github.com/ethereum/snake-charmers-tactical-manual) for information on how we do: - Testing - Pull Requests - Code Style - Documentation ### Development Environment Setup You can set up your dev environment with: ```sh git clone git@github.com:carver/hexbytes.git cd hexbytes virtualenv -p python3 venv . venv/bin/activate pip install -e .[dev] ``` ### Testing Setup During development, you might like to have tests run on every file save. Show flake8 errors on file change: ```sh # Test flake8 when-changed -v -s -r -1 hexbytes/ tests/ -c "clear; flake8 hexbytes tests && echo 'flake8 success' || echo 'error'" ``` Run multi-process tests in one command, but without color: ```sh # in the project root: pytest --numprocesses=4 --looponfail --maxfail=1 # the same thing, succinctly: pytest -n 4 -f --maxfail=1 ``` Run in one thread, with color and desktop notifications: ```sh cd venv ptw --onfail "notify-send -t 5000 'Test failure ⚠⚠⚠⚠⚠' 'python 3 test on hexbytes failed'" ../tests ../hexbytes ``` ### Release setup For Debian-like systems: ``` apt install pandoc ``` To release a new version: ```sh make release bump=$$VERSION_PART_TO_BUMP$$ ``` #### How to bumpversion The version format for this repo is `{major}.{minor}.{patch}` for stable, and `{major}.{minor}.{patch}-{stage}.{devnum}` for unstable (`stage` can be alpha or beta). To issue the next version in line, specify which part to bump, like `make release bump=minor` or `make release bump=devnum`. This is typically done from the master branch, except when releasing a beta (in which case the beta is released from master, and the previous stable branch is released from said branch). If you are in a beta version, `make release bump=stage` will switch to a stable. To issue an unstable version when the current version is stable, specify the new version explicitly, like `make release bump="--new-version 4.0.0-alpha.1 devnum"` hexbytes-0.3.0/docs/000077500000000000000000000000001427721305000142765ustar00rootroot00000000000000hexbytes-0.3.0/docs/Makefile000066400000000000000000000151621427721305000157430ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/hexbytes.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/hexbytes.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/hexbytes" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/hexbytes" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." hexbytes-0.3.0/docs/_static/000077500000000000000000000000001427721305000157245ustar00rootroot00000000000000hexbytes-0.3.0/docs/_static/.suppress-sphinx-build-warning000066400000000000000000000000001427721305000236460ustar00rootroot00000000000000hexbytes-0.3.0/docs/conf.py000066400000000000000000000217061427721305000156030ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # HexBytes documentation build configuration file, created by # sphinx-quickstart on Thu Oct 16 20:43:24 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) import os DIR = os.path.dirname("__file__") with open(os.path.join(DIR, "../setup.py"), "r") as f: for line in f: if "version=" in line: setup_version = line.split('"')[1] break # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.doctest", "sphinx.ext.intersphinx", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix of source filenames. source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # General information about the project. project = "HexBytes" copyright = "2020, The Ethereum Foundation" __version__ = setup_version # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = ".".join(__version__.split(".")[:2]) # The full version, including alpha/beta/rc tags. release = __version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [ "_build", "modules.rst", ] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "sphinx_rtd_theme" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "hexbytesdoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ( "index", "hexbytes.tex", "HexBytes Documentation", "The Ethereum Foundation", "manual", ), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ("index", "hexbytes", "HexBytes Documentation", ["The Ethereum Foundation"], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( "index", "HexBytes", "HexBytes Documentation", "The Ethereum Foundation", "hexbytes", "Python `bytes` subclass that decodes hex, with a readable console output", "Miscellaneous", ), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False # -- Intersphinx configuration ------------------------------------------------ intersphinx_mapping = { "python": ("https://docs.python.org/3.10", None), } # -- Doctest configuration ---------------------------------------- import doctest doctest_default_flags = ( 0 | doctest.DONT_ACCEPT_TRUE_FOR_1 | doctest.ELLIPSIS | doctest.IGNORE_EXCEPTION_DETAIL | doctest.NORMALIZE_WHITESPACE ) hexbytes-0.3.0/docs/hexbytes.rst000066400000000000000000000021741427721305000166670ustar00rootroot00000000000000hexbytes package ================ Quickstart ------------ Install with: .. code-block:: bash pip install hexbytes Example :class:`~hexbytes.main.HexBytes` usage: :: >>> from hexbytes import HexBytes # convert from bytes to a prettier representation at the console >>> HexBytes(b"\x03\x08wf\xbfh\xe7\x86q\xd1\xeaCj\xe0\x87\xdat\xa1'a\xda\xc0 \x01\x1a\x9e\xdd\xc4\x90\x0b\xf1;") HexBytes('0x03087766bf68e78671d1ea436ae087da74a12761dac020011a9eddc4900bf13b') # HexBytes accepts the hex string representation as well, ignoring case and 0x prefixes >>> hb = HexBytes('03087766BF68E78671D1EA436AE087DA74A12761DAC020011A9EDDC4900BF13B') HexBytes('0x03087766bf68e78671d1ea436ae087da74a12761dac020011a9eddc4900bf13b') # get the first byte: >>> hb[0] 3 # show how many bytes are in the value >>> len(hb) 32 # cast back to the basic `bytes` type >>> bytes(hb) b"\x03\x08wf\xbfh\xe7\x86q\xd1\xeaCj\xe0\x87\xdat\xa1'a\xda\xc0 \x01\x1a\x9e\xdd\xc4\x90\x0b\xf1;" HexBytes --------------------- .. automodule:: hexbytes.main :members: :undoc-members: :show-inheritance: hexbytes-0.3.0/docs/index.rst000066400000000000000000000003731427721305000161420ustar00rootroot00000000000000HexBytes ======== Python `bytes` subclass that decodes hex, with a readable console output Contents -------- .. toctree:: :maxdepth: 3 hexbytes release_notes Indices and tables ------------------ * :ref:`genindex` * :ref:`modindex` hexbytes-0.3.0/docs/release_notes.rst000066400000000000000000000063401427721305000176630ustar00rootroot00000000000000Release Notes ============= .. towncrier release notes start HexBytes v0.3.0 (2022-08-17) ---------------------------- Miscellaneous changes ~~~~~~~~~~~~~~~~~~~~~ - `#28 `__ Breaking changes ~~~~~~~~~~~~~~~~ - Drop support for Python 3.6, update Sphinx doc dependency requirement (`#27 `__) HexBytes v0.2.3 (2022-08-11) ---------------------------- Features ~~~~~~~~ - Type signature now accepts `memoryview` when creating HexBytes. It converts to a `bytes` internally, so not any performance benefit. But at least it's *possible* now, and mypy stops complaining. (`#22 `__) Performance improvements ~~~~~~~~~~~~~~~~~~~~~~~~ - Improve speed of the check for 0x at the beginning of the hex string. Similar to changes in eth-utils. (Technically merged by #22, but first posted in #21) (`#21 `__) Internal Changes - for hexbytes Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Merged in latest changes from project template (`#24 `__) Miscellaneous changes ~~~~~~~~~~~~~~~~~~~~~ - `#25 `__, `#26 `__ HexBytes v0.2.2 (2021-08-25) ---------------------------- Miscellaneous changes ~~~~~~~~~~~~~~~~~~~~~ - Pass mypy tests with `--no-implicit-reexport` (`#15 `__) Internal Changes - for hexbytes Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Merge in template changes from the last year. Pass pydocstyle tests at the new major version. (`#16 `__) HexBytes v0.2.1 (2020-06-02) ---------------------------- Features ~~~~~~~~ - Officially support bytearray, int, and bool as inputs to :class:`~hexbytes.main.HexBytes`. Drop the dependency on eth-utils, for a much smaller & faster install. (`#12 `__) v0.2.0 -------------- Released June 3, 2019 - **Breaking Changes** - Dropped Python3.5 support (only in name at this release, but py3.6 features will be used soon `#10 `_ - Features - A slice of HexBytes will now produce another HexBytes object `#9 `_ - Maintenance - Added type hints `#7 `_ v0.1.0 -------------- Released Mar 1, 2018 - Marked stable - eth-utils v1.0.1 support v0.1.0-beta.1 -------------- Released Feb 21, 2018 - pypy3 support - eth-utils v1-beta.2 support - Some generic template updates v0.1.0-beta.0 -------------- Released Jan 30, 2018 - Tested a basic integration with eth-rlp - Given the simplicity of the project and the longer usage history in web3.py, it is reasonable to bump to beta immediately. v0.1.0-alpha.2 -------------- Released Jan 30, 2018 - Added hypothesis tests - Added some docs - Update eth-utils to get all required functionality - Passes all tests v0.1.0-alpha.1 -------------- - Launched repository, claimed names for pip, RTD, github, etc hexbytes-0.3.0/hexbytes/000077500000000000000000000000001427721305000152015ustar00rootroot00000000000000hexbytes-0.3.0/hexbytes/__init__.py000066400000000000000000000000741427721305000173130ustar00rootroot00000000000000from .main import ( HexBytes, ) __all__ = ["HexBytes"] hexbytes-0.3.0/hexbytes/_utils.py000066400000000000000000000032271427721305000170560ustar00rootroot00000000000000import binascii from typing import ( Union, ) def to_bytes(val: Union[bool, bytearray, bytes, int, str, memoryview]) -> bytes: """ Equivalent to: `eth_utils.hexstr_if_str(eth_utils.to_bytes, val)` . Convert a hex string, integer, or bool, to a bytes representation. Alternatively, pass through bytes or bytearray as a bytes value. """ if isinstance(val, bytes): return val elif isinstance(val, str): return hexstr_to_bytes(val) elif isinstance(val, bytearray): return bytes(val) elif isinstance(val, bool): return b"\x01" if val else b"\x00" elif isinstance(val, int): # Note that this int check must come after the bool check, because # isinstance(True, int) is True if val < 0: raise ValueError(f"Cannot convert negative integer {val} to bytes") else: return to_bytes(hex(val)) elif isinstance(val, memoryview): return bytes(val) else: raise TypeError(f"Cannot convert {val!r} of type {type(val)} to bytes") def hexstr_to_bytes(hexstr: str) -> bytes: if hexstr.startswith(("0x", "0X")): non_prefixed_hex = hexstr[2:] else: non_prefixed_hex = hexstr # if the hex string is odd-length, then left-pad it to an even length if len(hexstr) % 2: padded_hex = "0" + non_prefixed_hex else: padded_hex = non_prefixed_hex try: ascii_hex = padded_hex.encode("ascii") except UnicodeDecodeError: raise ValueError( f"hex string {padded_hex} may only contain [0-9a-fA-F] characters" ) else: return binascii.unhexlify(ascii_hex) hexbytes-0.3.0/hexbytes/main.py000066400000000000000000000036421427721305000165040ustar00rootroot00000000000000import sys from typing import ( TYPE_CHECKING, Type, Union, cast, overload, ) from ._utils import ( to_bytes, ) if TYPE_CHECKING: # remove once hexbytes supports python>=3.8 # Types was added to typing in 3.8 if sys.version_info >= (3, 8): from typing import SupportsIndex else: from typing_extensions import SupportsIndex # noqa: F401 BytesLike = Union[bool, bytearray, bytes, int, str, memoryview] class HexBytes(bytes): """ HexBytes is a *very* thin wrapper around the python built-in :class:`bytes` class. It has these three changes: 1. Accepts more initializing values, like hex strings, non-negative integers, and booleans 2. Returns hex with prefix '0x' from :meth:`HexBytes.hex` 3. The representation at console is in hex """ def __new__(cls: Type[bytes], val: BytesLike) -> "HexBytes": bytesval = to_bytes(val) return cast(HexBytes, super().__new__(cls, bytesval)) # type: ignore # https://github.com/python/typeshed/issues/2630 # noqa: E501 def hex( self, sep: Union[str, bytes] = None, bytes_per_sep: "SupportsIndex" = 1 ) -> str: """ Output hex-encoded bytes, with an "0x" prefix. Everything following the "0x" is output exactly like :meth:`bytes.hex`. """ return "0x" + super().hex() @overload def __getitem__(self, key: "SupportsIndex") -> int: # noqa: F811 ... @overload # noqa: F811 def __getitem__(self, key: slice) -> "HexBytes": # noqa: F811 ... def __getitem__( # noqa: F811 self, key: Union["SupportsIndex", slice] ) -> Union[int, bytes, "HexBytes"]: result = super().__getitem__(key) if hasattr(result, "hex"): return type(self)(result) else: return result def __repr__(self) -> str: return f"HexBytes({self.hex()!r})" hexbytes-0.3.0/hexbytes/py.typed000066400000000000000000000000001427721305000166660ustar00rootroot00000000000000hexbytes-0.3.0/mypy.ini000066400000000000000000000006231427721305000150460ustar00rootroot00000000000000[mypy] check_untyped_defs = True disallow_incomplete_defs = True disallow_untyped_defs = True disallow_any_generics = True disallow_untyped_calls = True disallow_untyped_decorators = True disallow_subclassing_any = True ignore_missing_imports = True strict_optional = False strict_equality = True warn_redundant_casts = True warn_return_any = True warn_unused_configs = True warn_unused_ignores = True hexbytes-0.3.0/newsfragments/000077500000000000000000000000001427721305000162315ustar00rootroot00000000000000hexbytes-0.3.0/newsfragments/README.md000066400000000000000000000017761427721305000175230ustar00rootroot00000000000000This directory collects "newsfragments": short files that each contain a snippet of ReST-formatted text that will be added to the next release notes. This should be a description of aspects of the change (if any) that are relevant to users. (This contrasts with the commit message and PR description, which are a description of the change as relevant to people working on the code itself.) Each file should be named like `..rst`, where `` is an issue numbers, and `` is one of: * `feature` * `bugfix` * `performance` * `doc` * `internal` * `removal` * `misc` * `breaking` So for example: `123.feature.rst`, `456.bugfix.rst` If the PR fixes an issue, use that number here. If there is no issue, then open up the PR first and use the PR number for the newsfragment. Note that the `towncrier` tool will automatically reflow your text, so don't try to do any fancy formatting. Run `towncrier --draft` to get a preview of what the release notes entry will look like in the final release notes. hexbytes-0.3.0/newsfragments/validate_files.py000077500000000000000000000021161427721305000215610ustar00rootroot00000000000000#!/usr/bin/env python3 # Towncrier silently ignores files that do not match the expected ending. # We use this script to ensure we catch these as errors in CI. import os import pathlib import sys ALLOWED_EXTENSIONS = { '.breaking.rst', '.bugfix.rst', '.doc.rst', '.feature.rst', '.internal.rst', '.misc.rst', '.performance.rst', '.removal.rst', } ALLOWED_FILES = { 'validate_files.py', 'README.md', } THIS_DIR = pathlib.Path(__file__).parent num_args = len(sys.argv) - 1 assert num_args in {0, 1} if num_args == 1: assert sys.argv[1] in ('is-empty', ) for fragment_file in THIS_DIR.iterdir(): if fragment_file.name in ALLOWED_FILES: continue elif num_args == 0: full_extension = "".join(fragment_file.suffixes) if full_extension not in ALLOWED_EXTENSIONS: raise Exception(f"Unexpected file: {fragment_file}") elif sys.argv[1] == 'is-empty': raise Exception(f"Unexpected file: {fragment_file}") else: raise RuntimeError("Strange: arguments {sys.argv} were validated, but not found") hexbytes-0.3.0/pyproject.toml000066400000000000000000000021511427721305000162610ustar00rootroot00000000000000[tool.towncrier] # Read https://github.com/ethereum/hexbytes/newsfragments/README.md for instructions package = "hexbytes" filename = "docs/release_notes.rst" directory = "newsfragments" underlines = ["-", "~", "^"] title_format = "HexBytes v{version} ({project_date})" issue_format = "`#{issue} `__" [[tool.towncrier.type]] directory = "feature" name = "Features" showcontent = true [[tool.towncrier.type]] directory = "bugfix" name = "Bugfixes" showcontent = true [[tool.towncrier.type]] directory = "performance" name = "Performance improvements" showcontent = true [[tool.towncrier.type]] directory = "doc" name = "Improved Documentation" showcontent = true [[tool.towncrier.type]] directory = "removal" name = "Deprecations and Removals" showcontent = true [[tool.towncrier.type]] directory = "internal" name = "Internal Changes - for hexbytes Contributors" showcontent = true [[tool.towncrier.type]] directory = "misc" name = "Miscellaneous changes" showcontent = false [[tool.towncrier.type]] directory = "breaking" name = "Breaking changes" showcontent = true hexbytes-0.3.0/pytest.ini000066400000000000000000000001751427721305000154020ustar00rootroot00000000000000[pytest] addopts= -v --showlocals --durations 10 xfail_strict=true [pytest-watch] runner= pytest --failed-first --maxfail=1 hexbytes-0.3.0/requirements-docs.txt000066400000000000000000000000161427721305000175550ustar00rootroot00000000000000hexbytes[doc] hexbytes-0.3.0/setup.py000066400000000000000000000043071427721305000150640ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import ( setup, find_packages, ) extras_require = { "test": [ "pytest>=7,<8", "pytest-xdist", "tox>=3.25.1,<4", "hypothesis>=3.44.24,<=6.31.6", "eth-utils>=1.0.1,<3", ], "lint": [ "flake8==3.7.9", "isort>=4.2.15,<5", "mypy==0.971", "pydocstyle>=5.0.0,<6", "black>=22,<23", ], "doc": [ "Sphinx>=4.0.0,<5", "sphinx_rtd_theme>=0.1.9,<1", "towncrier>=21,<22", ], "dev": [ "bumpversion>=0.5.3,<1", "pytest-watch>=4.1.0,<5", "wheel", "twine", "ipython", ], } extras_require["dev"] = ( extras_require["dev"] + extras_require["test"] + extras_require["lint"] + extras_require["doc"] ) with open("./README.md") as readme: long_description = readme.read() setup( name="hexbytes", # *IMPORTANT*: Don't manually change the version here. Use `make bump`, as described in readme version="0.3.0", description="""hexbytes: Python `bytes` subclass that decodes hex, with a readable console output""", long_description=long_description, long_description_content_type="text/markdown", author="The Ethereum Foundation", author_email="snakecharmers@ethereum.org", url="https://github.com/ethereum/hexbytes", include_package_data=True, install_requires=[], python_requires=">=3.7, <4", extras_require=extras_require, py_modules=["hexbytes"], license="MIT", zip_safe=False, keywords="ethereum", packages=find_packages(exclude=["tests", "tests.*"]), package_data={"hexbytes": ["py.typed"]}, classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: MacOS", "Operating System :: POSIX", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", ], ) hexbytes-0.3.0/tests/000077500000000000000000000000001427721305000145105ustar00rootroot00000000000000hexbytes-0.3.0/tests/core/000077500000000000000000000000001427721305000154405ustar00rootroot00000000000000hexbytes-0.3.0/tests/core/test_hexbytes.py000066400000000000000000000057661427721305000207220ustar00rootroot00000000000000from eth_utils import ( decode_hex, remove_0x_prefix, to_bytes as standard_to_bytes, ) from hypothesis import ( given, strategies as st, ) import pytest from hexbytes import ( HexBytes, ) hexstr_strategy = st.from_regex(r"\A(0[xX])?[0-9a-fA-F]*\Z") def assert_equal(hexbytes, bytes_expected): assert hexbytes == bytes_expected assert len(hexbytes) == len(bytes_expected) for byte_actual, byte_expected in zip(hexbytes, bytes_expected): assert byte_actual == byte_expected assert bytes(hexbytes) == bytes_expected @given(st.binary()) def test_bytes_inputs(primitive): wrapped = HexBytes(primitive) assert_equal(wrapped, primitive) @given(st.binary()) def test_bytearray_inputs(primitive): byte_array_input = bytearray(primitive) wrapped = HexBytes(byte_array_input) assert_equal(wrapped, primitive) @given(st.binary()) def test_memoryview_inputs(primitive): memoryview_input = memoryview(primitive) wrapped = HexBytes(memoryview_input) assert_equal(wrapped, primitive) @pytest.mark.parametrize( "boolval, expected_repr", ( (True, "HexBytes('0x01')"), (False, "HexBytes('0x00')"), ), ) def test_bool_inputs(boolval, expected_repr): wrapped = HexBytes(boolval) assert repr(wrapped) == expected_repr assert_equal(wrapped, standard_to_bytes(boolval)) @given(st.integers(max_value=-1)) def test_invalid_integer_inputs(integer): with pytest.raises(ValueError) as exc_info: HexBytes(integer) message = str(exc_info.value) assert "negative" in message assert str(integer) in message @given(st.integers(min_value=0)) def test_integer_inputs(integer): wrapped = HexBytes(integer) assert hex(integer)[2:] in repr(wrapped) assert_equal(wrapped, standard_to_bytes(integer)) @given(hexstr_strategy) def test_hex_inputs(hex_input): wrapped = HexBytes(hex_input) if len(hex_input) % 2 == 0: even_hex_input = hex_input else: even_hex_input = "0" + remove_0x_prefix(hex_input) expected = decode_hex(even_hex_input) assert_equal(wrapped, expected) def test_pretty_output(): hb = HexBytes(b"\x0F\x1a") assert repr(hb) == "HexBytes('0x0f1a')" @given(st.binary(), st.integers()) def test_hexbytes_index(primitive, index): hexbytes = HexBytes(primitive) if index >= len(primitive) or index < -1 * len(primitive): with pytest.raises(IndexError): hexbytes[index] else: assert hexbytes[index] == primitive[index] @given(st.binary(), st.integers(), st.integers()) def test_slice(primitive, start, stop): hexbytes = HexBytes(primitive) expected = HexBytes(primitive[start:stop]) assert hexbytes[start:stop] == expected @given(st.binary(), st.integers(), st.integers(), st.integers()) def test_slice_stepped(primitive, start, stop, step): hexbytes = HexBytes(primitive) if step == 0: step = None expected = HexBytes(primitive[start:stop:step]) assert hexbytes[start:stop:step] == expected hexbytes-0.3.0/tests/core/test_import.py000066400000000000000000000000651427721305000203640ustar00rootroot00000000000000def test_import(): import hexbytes # noqa: F401 hexbytes-0.3.0/tox.ini000066400000000000000000000022411427721305000146600ustar00rootroot00000000000000[tox] envlist= py{37,38,39,310,py3}-core py{37,38,39,310}-lint docs [isort] combine_as_imports=True force_sort_within_sections=True include_trailing_comma=True known_third_party=hypothesis,pytest,eth_utils known_first_party=hexbytes line_length=21 multi_line_output=3 use_parentheses=True [flake8] max-line-length=88 exclude= venv*,.tox,docs,build ignore= [testenv] usedevelop=True commands= core: pytest {posargs:tests/core} docs: make check-docs basepython = docs: python py37: python3.7 py38: python3.8 py39: python3.9 py310: python3.10 pypy3: pypy3 extras= test docs: doc whitelist_externals=make [common-lint] deps=.[lint] commands= mypy -p hexbytes --config-file {toxinidir}/mypy.ini flake8 {toxinidir}/hexbytes {toxinidir}/tests isort --recursive --check-only --diff {toxinidir}/hexbytes {toxinidir}/tests pydocstyle --explain {toxinidir}/hexbytes {toxinidir}/tests black {toxinidir}/hexbytes {toxinidir}/tests --check [testenv:py{37,38,39,310}-lint] deps={[common-lint]deps} commands={[common-lint]commands} [testenv:lint] basepython=python deps={[common-lint]deps} commands={[common-lint]commands}