Best Python code snippet using pyshould_python
test_tg.py
Source:test_tg.py
1import os2import json3import shutil4import tempfile5from mock import patch6from unittest.mock import MagicMock7from .. import utils8from .. import Terragrunt9properties = {10 'resource_config': {11 'binary_path': '/usr/local/bin/terragrunt',12 'terraform_binary_path': '/usr/local/bin/terraform',13 'source': 'https://github.com/terragrunt/archive/refs/heads/main.zip',14 'source_path': '',15 'variables': {},16 'environment_variables': {17 'AWS_ACCESS_KEY_ID': '',18 'AWS_SECRET_ACCESS_KEY': '',19 'AWS_DEFAULT_REGION': ''20 },21 'run_all': False,22 'command_options': {23 'all': ['--terragrunt-non-interactive', '--terragrunt-log-level'],24 'apply': ['-auto-approve'],25 'destroy': ['-auto-approve'],26 'plan': ['-json'],27 'output': ['-json']28 }29 }30}31source = 'https://blablabla.zip'32source_path = ''33def test_properties():34 tg = Terragrunt(properties=properties, source=source)35 assert tg.properties == properties36def test_logger():37 tg = Terragrunt(properties=properties, source=source)38 assert tg.logger is None or utils.get_logger('TerragruntLogger')39def test_resource_config():40 tg = Terragrunt(properties=properties, source=source)41 assert tg.resource_config == properties.get('resource_config', {})42def test_source():43 tg = Terragrunt(properties=properties, source=source)44 assert tg.source == source or tg.resource_config.get('source')45def test_source_path():46 tg = Terragrunt(properties=properties, source=source)47 if os.path.exists(source_path):48 assert tg.source_path == source_path or \49 tg.resource_config.get('source_path')50 else:51 assert tg.source_path is None52def test_setter_source_path():53 tg = Terragrunt(properties=properties, source=source)54 source_path_set = tempfile.mkdtemp()55 tg.source_path = source_path_set56 assert tg.source_path == source_path_set, '{}'.format(tg.source_path)57 assert tg.resource_config.get('source_path') == source_path_set58 shutil.rmtree(source_path_set)59def test_binary_path():60 tg = Terragrunt(properties=properties, source=source)61 assert tg.binary_path == tg.resource_config.get('binary_path')62def test_terraform_binary_path():63 mocked_executor = MagicMock()64 mocked_executor.return_value = '1.0.4'65 tg = Terragrunt(properties=properties,66 source=source,67 executor=mocked_executor)68 assert tg.terraform_binary_path == \69 tg.resource_config.get('terraform_binary_path')70def test_run_all():71 tg = Terragrunt(properties=properties, source=source)72 assert tg.run_all == tg.resource_config.get('run_all')73def test_setter_run_all():74 tg = Terragrunt(properties=properties, source=source)75 tg.run_all = True76 assert tg.run_all is True77def test_environment_variables():78 tg = Terragrunt(properties=properties, source=source)79 assert tg.environment_variables == \80 tg.resource_config.get('environment_variables')81def test_command_options():82 tg = Terragrunt(properties=properties, source=source)83 assert tg.command_options == tg.resource_config.get('command_options', {})84def test_update_command_options():85 tg = Terragrunt(properties=properties, source=source)86 new_dict = {87 'all': ['--terragrunt-non-interactive', '--terragrunt-log-level',88 'debug'],89 'apply': ['-auto-approve'],90 'destroy': ['-auto-approve'],91 'plan': ['-json'],92 'output': ['-json']93 }94 tg.update_command_options(new_dict)95 assert tg.command_options == new_dict96def test_version():97 mocked_executor = MagicMock()98 mocked_executor.return_value = '100.5.2'99 tg = Terragrunt(properties=properties,100 source=source,101 executor=mocked_executor)102 assert tg.version == '100.5.2'103def test__execute():104 mocked_executor = MagicMock()105 tg = Terragrunt(properties=properties,106 source=source,107 executor=mocked_executor)108 tg._execute('foo', False)109 mocked_executor.assert_called_once_with(110 'foo',111 logger=tg.logger,112 additional_env=tg.environment_variables,113 return_output=False114 )115@patch('tg_sdk.tg.utils.get_version_string', return_value='1.0.1')116def test_execute(*_):117 mocked_executor = MagicMock()118 tg = Terragrunt(properties=properties,119 source=source,120 executor=mocked_executor)121 tg.execute('foo', False)122 mocked_executor.assert_called_with(123 ['/usr/local/bin/terragrunt',124 'foo',125 '--terragrunt-non-interactive',126 '--terragrunt-log-level',127 '--terragrunt-tfpath',128 '/usr/local/bin/terraform'],129 logger=tg.logger,130 additional_env=tg.environment_variables,131 return_output=False132 )133@patch('tg_sdk.tg.utils.get_version_string')134def test_commands(version_string):135 version_string.return_value = '1.0.1'136 mocked_executor = MagicMock()137 tg = Terragrunt(properties=properties,138 source=source,139 executor=mocked_executor)140 tg.render_json()141 mocked_executor.assert_called_with(142 ['/usr/local/bin/terragrunt',143 'render-json',144 '--terragrunt-non-interactive',145 '--terragrunt-log-level',146 '--terragrunt-tfpath',147 '/usr/local/bin/terraform'],148 logger=tg.logger,149 additional_env=tg.environment_variables,150 return_output=True151 )152 mocked_executor = MagicMock()153 tg = Terragrunt(properties=properties,154 source=source,155 executor=mocked_executor)156 tg.graph_dependencies()157 mocked_executor.assert_called_with(158 ['/usr/local/bin/terragrunt',159 'graph-dependencies',160 '--terragrunt-non-interactive',161 '--terragrunt-log-level',162 '--terragrunt-tfpath',163 '/usr/local/bin/terraform'],164 logger=tg.logger,165 additional_env=tg.environment_variables,166 return_output=True167 )168 mocked_executor = MagicMock()169 tg = Terragrunt(properties=properties,170 source=source,171 executor=mocked_executor)172 tg.validate_inputs()173 mocked_executor.assert_called_with(174 ['/usr/local/bin/terragrunt',175 'validate-inputs',176 '--terragrunt-non-interactive',177 '--terragrunt-log-level',178 '--terragrunt-tfpath',179 '/usr/local/bin/terraform'],180 logger=tg.logger,181 additional_env=tg.environment_variables,182 return_output=True183 )184 mocked_executor = MagicMock()185 tg = Terragrunt(properties=properties,186 source=source,187 executor=mocked_executor)188 tg.terragrunt_info()189 mocked_executor.assert_called_with(190 ['/usr/local/bin/terragrunt',191 'terragrunt-info',192 '--terragrunt-non-interactive',193 '--terragrunt-log-level',194 '--terragrunt-tfpath',195 '/usr/local/bin/terraform'],196 logger=tg.logger,197 additional_env=tg.environment_variables,198 return_output=True199 )200 mocked_executor = MagicMock()201 tg = Terragrunt(properties=properties,202 source=source,203 executor=mocked_executor)204 tg.apply()205 mocked_executor.assert_called_with(206 ['/usr/local/bin/terragrunt',207 'apply',208 '--terragrunt-non-interactive',209 '--terragrunt-log-level',210 '-auto-approve',211 '--terragrunt-tfpath',212 '/usr/local/bin/terraform'],213 logger=tg.logger,214 additional_env=tg.environment_variables,215 return_output=True216 )217 mocked_executor = MagicMock()218 tg = Terragrunt(properties=properties,219 source=source,220 executor=mocked_executor)221 tg.destroy()222 mocked_executor.assert_called_with(223 ['/usr/local/bin/terragrunt',224 'destroy',225 '--terragrunt-non-interactive',226 '--terragrunt-log-level',227 '-auto-approve',228 '--terragrunt-tfpath',229 '/usr/local/bin/terraform'],230 logger=tg.logger,231 additional_env=tg.environment_variables,232 return_output=True233 )234@patch('tg_sdk.tg.utils.get_version_string', return_value='1.0.1')235def test_plan(*_):236 mock_returned = '{"foo": "bar"}' \237 '{"type": "outputs", ' \238 '"outputs": {"output_foo": "output_bar"}}' \239 '{"type": "change_summary", ' \240 '"changes": {"change_foo": "change_bar"}}' \241 '{"type": "resource_drift", ' \242 '"change": {"change_foo": "change_bar"}}'243 expected = {244 'resource_drifts': [{'change_foo': 'change_bar'}],245 'outputs': {'output_foo': 'output_bar'},246 'change_summary': {'change_foo': 'change_bar'}247 }248 mocked_executor = MagicMock()249 mocked_executor.return_value = mock_returned250 tg = Terragrunt(properties=properties,251 source=source,252 executor=mocked_executor)253 plan = tg.plan()254 assert plan == expected255@patch('tg_sdk.tg.utils.get_version_string', return_value='1.0.1')256def test_terraform_plan(*_):257 mock_returned = '{"foo": "bar"}' \258 '{"type": "outputs", ' \259 '"outputs": {"output_foo": "output_bar"}}' \260 '{"type": "change_summary", ' \261 '"changes": {"change_foo": "change_bar"}}' \262 '{"type": "resource_drift", ' \263 '"change": {"change_foo": "change_bar"}}'264 expected = {265 'resource_drifts': [{'change_foo': 'change_bar'}],266 'outputs': {'output_foo': 'output_bar'},267 'change_summary': {'change_foo': 'change_bar'}268 }269 mocked_executor = MagicMock()270 mocked_executor.return_value = mock_returned271 tg = Terragrunt(properties=properties,272 source=source,273 executor=mocked_executor)274 plan = tg.plan()275 assert plan == expected276@patch('tg_sdk.tg.utils.get_version_string', return_value='1.0.1')277def test_output(*_):278 expected = {'foo': ["bar"]}279 test_json = json.dumps(expected)280 mocked_executor = MagicMock()281 mocked_executor.return_value = test_json282 tg = Terragrunt(properties=properties,283 source=source,284 executor=mocked_executor)285 result = tg.output()286 assert result == expected287@patch('tg_sdk.tg.utils.get_version_string', return_value='1.0.1')288def test_terraform_output(*_):289 expected = {'foo': ["bar"]}290 test_json = json.dumps(expected)291 mocked_executor = MagicMock()292 mocked_executor.return_value = test_json293 tg = Terragrunt(properties=properties,294 source=source,295 executor=mocked_executor)296 result = tg.output()...
views.py
Source:views.py
1from django.template.loader import get_template2from django.template import Template, Context3from django.http import HttpResponse4import datetime5from django.contrib.auth import authenticate, login6from django.contrib.auth.models import Permission, User7from django.shortcuts import get_object_or_404, render8from .forms import UserForm, PostForm, Com9from open_news.models import NewsWebsite, Article, ArticleItem, Person10from django.core.exceptions import *11from django.core.urlresolvers import reverse12from django.views.generic import ListView13from django.contrib.auth import authenticate14from django.contrib.auth.decorators import login_required15from django.views.generic import DetailView16from django.utils import timezone17from 18from django.core.management import call_command19import sys20stdout_backup, sys.stdout = sys.stdout, open('output_file', 'w+')21call_command('govtrackcommand')22sys.stdout = stdout_backup23'''24from open_news.management.commands import govtrackcommand25//govtrackcommand is a one off python command26//if someone could deploy it with views and that is easier27//than django scrapy scraping, then do it.28'''29def view_bills(request):30 call_command('govtrackcommand')31 '''bill_info = Bills()32 b = bill_info.get_bill_fields()33 '''34 return render(request, 'bi.html')35 #return bills36class News(ListView):37 model = Article38 39 template_name = 'news.html'40 queryset = Article.objects.filter(news_website=1)41 42 def get_context_data(self, **kwargs):43 context = super(News, self).get_context_data(**kwargs)44 context['title'] = Article.objects.all()45 return context46 47class ArticleDetailView(DetailView):48 model = ArticleItem49 def get_context_data(self, **kwargs):50 context = super(ArticleDetailView, self).get_context_data(**kwargs)51 context['now'] = timezone.now()52 return context53 54 55def indexed(request):56 model = Person57 58 if request.method== 'POST':59 form = Com(request.POST)60 if form.is_valid():61 return HttpResponseRedirect('/admin/')62 else:63 form=Com()64 return render(request, 'pie.html', {'form':form})65 66 67 68def post_form(request):69 if request.method == 'POST':70 form = PostForm(request.POST)71 if form.is_valid():72 comment = form.cleaned_data['comment']73 name = form.cleaned_data['name']74 post = m.Post.objects.create(comment=comment,name=name)75 76 return HttpResponseRedirect(reverse('post_detail', kwargs={'post_id': post.id}))77 else:78 form =UserForm()79 return render(request, 'post_form_upload.html', {'form':form})80#@login_required(redirect_field_name='cover')81def get_name(request):82 if request.method == 'POST':83 form = UserForm(request.POST)84 username = request.POST.get('username')85 password = request.POST.get('password')86 user = authenticate(username='nstcR', password='1967R')87 if user is not None:88 if user.is_active:89 login(request,user)90 print("User is valid, active and authenticated")91 return HttpResponseRedirect('perms/')92 else:93 return HttpResponseRedirect('/index') 94 print("The password is vlaid, but the account has been disabeled!")95 else:96 print("The username and password were incorrect.")97 #redirect to user_gains_perms page98 else:99 form=UserForm()100 return render(request, 'post_form_upload.html', {'form':form})101 102'''def user_gains_perms(request, user_id):103 104 105 user=get_object_or_404(User, pk=user_id)106 user.has_perm('open_news.change_bar')107 permission = Permission.objects.get(codename='change_bar')108 user.user_permissions.add(permission)109 user.has_perm('open_news.change_bar')110 user = get_object_or_404(User, pk=user_id)111 user.has_perm('open_news.change_bar')112 113 return HttpResponseRedirect('/admin')114''' 115def search(request):116 if request.method == 'POST':117 search_id = request.POST.get('textfield', None)118 try:119 user = Person.objects.get(name = search_id)120 #do something with user121 html = ("<H1>%s</H1>", user)122 return HttpResponse(html)123 except Person.DoesNotExist:124 return HttpResponse("no such user") 125 else:126 return render(request, 'form.html')127 128def thanks(request):129 return HttpResponse("Thank you for signing in")130 return HttpResponseRedirect('/admin')131 132 133def cover(request):134 135 cov = get_template('cover.html')136 c = cov.render(Context({'cover': cov}))137 138 return HttpResponse("hello")139 140def tested(request):141 142 t = get_template('tested.html')143 tex = t.render(Context({'tested':t}))144 return HttpResponse(tex)145def my_view(request):146 model = Person147 username=request.POST.get('username')148 password=request.POST.get('password')149 150 user = authenticate(username=username, password=password)151 152 if user.is_valid:153 return HttpResponseRedirect('/admin/')154 155 156 #profile = request.user.get_profile()157 158 159'''another attempt at specifying user_permissions access'''160def user_gains_perms(request, user_id):161 user = get_object_or_404(User, pk=user_id)162 user.has_perm('open_news.change_bar')163 164 user.has_perm('open_news.change_bar')165 user=get_object_or_404(User, pk=user_id)166 user.has_perm('open_news.change_bar')167 168 ...
concurrent_updates.py
Source:concurrent_updates.py
...8 pool.join()9 print common10def change_foo(common):11 common['foo'] = 'foo_updated'12def change_bar(common):13 common['bar'] = 'bar_updated'14if __name__ == '__main__':...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!