How to use tagging_strategy method in Slash

Best Python code snippet using slash

releaser.py

Source:releaser.py Github

copy

Full Screen

1import os2import sys3import time4import random5import subprocess6import yaml7import github8# TODO:9# there is a problem because of parallelism in CI.10# since CI can run in parallel, we could have two people creating releases and the one whose commit11# is older than someone else gets a newer version.12class Releaser:13 def __init__(self, github_token, repo_name):14 self.repo_name = repo_name15 g = github.Github(github_token)16 self.myRepo = g.get_repo(self.repo_name) # returns a github.Repository.Repository17 def calculate_next_tag(self, latest_tag_name, tagging_strategy):18 """19 given the current tag, calculate the next one.20 eg:21 if latest_tag_name == 'v0.0.10'22 then this method should return 'v0.0.11'23 This method is on it's own so that we can properly test it's implementation.24 Currently we only increment the patch of semver, this method should be extended25 so that it can also be able to increment major/minor versions as required.26 """27 major_ver, minor_ver, patch_ver = latest_tag_name.replace("v", "").split(".")28 if tagging_strategy == "major":29 major_ver = str(int(major_ver) + 1)30 minor_ver = "0"31 patch_ver = "0"32 elif tagging_strategy == "minor":33 minor_ver = str(int(minor_ver) + 1)34 patch_ver = "0"35 else:36 patch_ver = str(int(patch_ver) + 1)37 new_tag = "v" + major_ver + "." + minor_ver + "." + patch_ver38 return new_tag39 def get_release_data(self):40 f = open(".github/RELEASE_DATA.yaml")41 release_data = yaml.load(f.read())42 f.close()43 return release_data44 def create_tag(self):45 """46 1.47 we can call48 myRepo.create_git_tag(tag, message, object, type, tagger=github.GithubObject.NotSet)49 where;50 tag: string eg "v0.0.1"51 message: string52 object: string, The SHA of the git object this is tagging.53 type: string, The type of the object we're tagging.54 Normally this is a commit but it can also be a tree or a blob.55 """56 # there's a small(but non zero) chance of a race condition between57 # two deployments/releases happening at the same time and they trying58 # to increment the same tag.59 # we add time.sleep to decrease chances of a race condition.60 time.sleep(random.randint(1, 6))61 existing_tags = self.myRepo.get_tags()62 print("existing_tags:", existing_tags)63 latest_tag = existing_tags[0]64 print("latest_tag:", latest_tag)65 latest_tag_name = latest_tag.name # eg; 'v0.0.10'66 release_data = self.get_release_data()67 tagging_strategy = release_data["tagging_strategy"].lower()68 new_tag = self.calculate_next_tag(69 latest_tag_name=latest_tag_name, tagging_strategy=tagging_strategy70 )71 tag_message = "tag:{tag}".format(tag=new_tag)72 tag_object = current_sha73 print(74 "creating git tag. tag={tag}. message={message}. commit={commit}".format(75 tag=new_tag, message=tag_message, commit=tag_object76 )77 )78 git_tag = self.myRepo.create_git_tag(79 tag=new_tag,80 message=tag_message,81 object=tag_object,82 type="commit",83 tagger=github.GithubObject.NotSet,84 )85 print(86 "successfully created git tag. tag={tag}. message={message}. commit={commit}".format(87 tag=new_tag, message=tag_message, commit=tag_object88 )89 )90 return git_tag91 def create_release(self, new_tag, github_user):92 """93 2.94 then we call:95 myRelease = myRepo.create_git_release(tag,96 name,97 message,98 draft=False,99 prerelease=False,100 target_commitish=github.GithubObject.NotSet)101 # returns github.GitRelease.GitRelease102 where;103 tag: string eg "v0.0.1"104 name: string, The name of the release.105 message: string, this is the body, Text describing the contents of the tag.106 target_commitish: string or107 :class:`github.Branch.Branch` or108 :class:`github.Commit.Commit` or109 :class:`github.GitCommit.GitCommit`110 Specifies the commitish value that determines111 where the Git tag is created from.112 Can be any branch or commit SHA. Unused if the Git tag already exists.113 Default: the repository's default branch(master)114 """115 release_data = self.get_release_data()116 release_title = release_data.get("release_title", "release: {0}".format(new_tag))117 rel_notes = release_data["release_notes"]118 release_notes = ""119 for i in rel_notes:120 release_notes = release_notes + "- " + i + "\n"121 # formatted this way so as to conform with markdown122 release_msg = """123**release_title:** {release_title}124**releaser:** {releaser}125**version:** {version}126**jira:** {jira_link}127**pull_request:** {pr_link}128**release_type:** {release_type}129**release_notes:**130{release_notes}131<details><summary><strong>install_instructions:</strong>(click to expand)</summary>132<p>133you can install this release using:</br>1341.135<i><strong>136pip install git+git://github.com/{repo_name}.git@{version}#egg=hey137</strong></i>138</br>1392. alternatively, you could add the following to your <i>requirements.txt</i> file:</br>140<i><strong>141-e git://github.com/{repo_name}.git@{version}#egg=hey142</strong></i>143</p>144</details>145 """.format(146 release_title=release_title,147 releaser=github_user,148 version=new_tag,149 jira_link=release_data["jira_card"],150 pr_link=release_data["pull_request"],151 release_type=release_data["release_type"],152 release_notes=release_notes,153 repo_name=self.repo_name,154 )155 print(156 "creating git release. tag={tag}. name={name}. message={message}".format(157 tag=new_tag, name=release_title, message=release_msg158 )159 )160 myRelease = self.myRepo.create_git_release(161 tag=new_tag,162 name=release_title,163 message=release_msg,164 draft=False,165 prerelease=False,166 target_commitish=github.GithubObject.NotSet,167 )168 print(169 "successfully created git release. tag={tag}. name={name}. message={message}".format(170 tag=new_tag, name=release_title, message=release_msg171 )172 )173 return myRelease174 def create_distribution(self):175 """176 3.177 then,178 python setup.py sdist &&179 python setup.py bdist_wheel180 this will create python packages.181 """182 print("git pull so as to get the latest tag created in releaser.create_tag()")183 git_pull_exitcode, git_pull_data = subprocess.getstatusoutput("git pull")184 print("git_pull_data output:\n", git_pull_data)185 if git_pull_exitcode != 0:186 print("\n git pull did not succeed. exit_code:{0}".format(git_pull_exitcode))187 sys.exit(git_pull_exitcode)188 print("creating sdist distribution")189 sdist_exitcode, sdist_data = subprocess.getstatusoutput("python setup.py sdist")190 print("sdist_data output:\n", sdist_data)191 if sdist_exitcode != 0:192 print("\n python setup.py sdist did not succeed. exit_code:{0}".format(sdist_exitcode))193 sys.exit(sdist_exitcode)194 print("creating bdist_wheel distribution")195 bdist_wheel_exitcode, bdist_wheel_data = subprocess.getstatusoutput(196 "python setup.py bdist_wheel"197 )198 print("bdist_wheel_data output:\n", bdist_wheel_data)199 if bdist_wheel_exitcode != 0:200 print(201 "\n python setup.py bdist_wheel did not succeed. exit_code:{0}".format(202 bdist_wheel_exitcode203 )204 )205 sys.exit(bdist_wheel_exitcode)206 print("successfully created distribution.")207 def upload_assets(self, new_tag, release):208 """209 4.210 then we call;211 myRelease.upload_asset(path, label='', content_type='')212 # myRelease is a github.GitRelease.GitRelease213 where;214 path: string, The path to The file name of the asset.215 label: string, An alternate short description of the asset. Used in place of the filename.216 content_type: string, eg "application/zip".217 github accepts this list of media-types:218 https://www.iana.org/assignments/media-types/media-types.xhtml219 we use the files created in step 3 above in our upload_asset() call as the assets220 """221 distribution_dir = os.path.join(os.getcwd(), "dist")222 wheel_file = os.path.join(223 distribution_dir,224 "hey-{version}-py3-none-any.whl".format(version=new_tag.replace("v", "")),225 )226 label = "hey wheel version={version}".format(version=new_tag)227 print(228 "creating release asset. path={path}. label={label}.".format(229 path=wheel_file, label=label230 )231 )232 release.upload_asset(233 path=wheel_file, label=label, content_type=""234 ) # myRelease is a github.GitRelease.GitRelease235 # 5.236 # then you can install as.237 # pip install git+git://github.com/komuw/hey.git@v0.0.24#egg=hey238 # or you can also put the following in your requirements.txt239 # -e git://github.com/komuw/hey.git@v0.0.24#egg=hey240if __name__ == "__main__":241 github_token = os.environ["HEY_GITHUB_TOKEN"]242 pr_link = "cool" # get this from somewhere, release notes file?243 current_sha = os.environ["CIRCLE_SHA1"]244 user_name = os.environ["CIRCLE_USERNAME"]245 branch_been_built = os.environ["CIRCLE_BRANCH"]246 if branch_been_built != "master":247 print("\n Not master branch. We wont create a new release.")248 sys.exit(0)249 releaser = Releaser(github_token=github_token, repo_name="komuw/hey")250 git_tag = releaser.create_tag()251 release = releaser.create_release(new_tag=git_tag.tag, github_user="@" + user_name)252 releaser.create_distribution()253 releaser.upload_assets(new_tag=git_tag.tag, release=release)254 print(255 "successfully created a new release. release_url={release_url}.".format(256 release_url=release.url257 )...

Full Screen

Full Screen

test_tagging.py

Source:test_tagging.py Github

copy

Full Screen

...42 assert tests43 for t in tests:44 assert 'tagname' in t.__slash__.tags45def test_metadata_tags(suite, suite_test, tagging_strategy, tags):46 tagging_strategy(suite_test, tags)47 summary = suite.run()48 [result] = summary.get_all_results_for_test(suite_test)49 for tag_name, tag_value in tags:50 assert result.test_metadata.tags.has_tag(tag_name)51 assert result.test_metadata.tags[tag_name] == tag_value52def test_tagging_twice_forbidden_different_values():53 @slash.tag('something', 1)54 def test_something():55 pass56 tagger = slash.tag('something', 2)57 with pytest.raises(TaggingConflict):58 tagger(test_something)59def test_tagging_twice_allowed_same_values():60 @slash.tag('something', 1)61 def test_something():62 pass63 tagger = slash.tag('something', 1)64 tagger(test_something)65def test_tagging_twice_allowed_no_value():66 @slash.tag('something')67 def test_something():68 pass69 tagger = slash.tag('something')70 tagger(test_something)71def test_tagging_fixture(suite_builder):72 # pylint: disable=unused-variable73 @suite_builder.first_file.add_code74 def __code__():75 import slash # pylint: disable=redefined-outer-name, reimported76 @slash.tag('tag-1')77 @slash.fixture78 def fixture1():79 pass80 @slash.tag('tag-2')81 @slash.fixture82 def fixture2(fixture1): # pylint: disable=unused-argument83 pass84 @slash.tag('test-tag')85 def test_depend_composite_fixture(fixture2): # pylint: disable=unused-argument86 assert set(slash.context.test.get_tags()) == {'tag-1', 'tag-2', 'test-tag'}87 @slash.tag('test-tag')88 def test_depend_simple_fixture(fixture1): # pylint: disable=unused-argument89 assert set(slash.context.test.get_tags()) == {'tag-1', 'test-tag'}90 def test_no_fixtures():91 assert not set(slash.context.test.get_tags())92 @slash.tag('tag-1')93 def test_and_fixture_same_tag(fixture1): # pylint: disable=unused-argument94 assert set(slash.context.test.get_tags()) == {'tag-1'}95 suite_builder.build().run().assert_success(4)96def test_fixture_and_test_overrides(suite_builder):97 # pylint: disable=unused-variable98 @suite_builder.first_file.add_code99 def __code__():100 import slash # pylint: disable=redefined-outer-name, reimported101 @slash.tag('tag-1', 'fixture_value')102 @slash.fixture103 def fixture1():104 pass105 @slash.tag('tag-1', 'test_value')106 def test_depend_composite_fixture(fixture1): # pylint: disable=unused-argument107 pass108 suite_builder.build().run().assert_session_error("Conflicting tag")109def test_tagging_parameter(suite_builder):110 # pylint: disable=unused-variable111 @suite_builder.first_file.add_code112 def __code__():113 import slash # pylint: disable=redefined-outer-name, reimported114 class TaggedParams(slash.Test):115 @slash.tag("unit_test")116 @slash.parametrize("tag_name",117 ["tag_1" // slash.param(tags="tag_1"),118 "tag_2" // slash.tag("tag_2")])119 def test_1(self, tag_name):120 assert set(slash.context.test.get_tags()) == \121 {"unit_test", tag_name}122 suite_builder.build().run().assert_success(2)123# more tags in test_pattern_matching.py124_tagging_strategies = []125def _tagging_strategy(func):126 _tagging_strategies.append(func)127 return func128@_tagging_strategy129def _simple_tagging_strategy(taggable, tags):130 for tag_name, tag_value in tags:131 taggable.add_decorator(_get_slash_tag_string(tag_name, tag_value))132@_tagging_strategy133def _tag_class_only(taggable, tags):134 if isinstance(taggable, MethodTest):135 _simple_tagging_strategy(taggable.cls, tags)136 else:137 _simple_tagging_strategy(taggable, tags)138@_tagging_strategy139def _tag_class_and_method(taggable, tags):140 if not isinstance(taggable, MethodTest):141 return _simple_tagging_strategy(taggable, tags)142 for (tag_name, tag_value), taggable in zip(tags, itertools.cycle([taggable.cls, taggable])):143 taggable.add_decorator(_get_slash_tag_string(tag_name, tag_value))144def _get_slash_tag_string(tag_name, tag_value):145 returned = 'slash.tag({!r}'.format(tag_name)146 if tag_value is not NOTHING:147 returned += ', {!r}'.format(tag_value)148 returned += ')'149 return returned150@pytest.fixture(params=_tagging_strategies)151def tagging_strategy(request):152 return request.param153@pytest.fixture(params=[154 {'simple_tag_without_value': NOTHING},155 {'single_tag': 'string_value'},156 {'multiple_tags_1': 1.0, 'multiple_tags_2': True, 'multiple_tags_3': ['list', 'of', 'things']},157])158def tags(request):159 return list(request.param.items())160@pytest.fixture(params=['class', 'function'])161def taggable(request):162 if request.param == 'class':163 class TaggableTest(slash.Test):164 def test_1(): # pylint: disable=no-method-argument165 pass...

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run Slash automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful