How to use first_test method in Lemoncheesecake

Best Python code snippet using lemoncheesecake

views.py

Source:views.py Github

copy

Full Screen

1from pprint import pprint2from django.shortcuts import render3from rest_framework import generics4from api.serializers import *5from main.models import *6from django.contrib.auth.models import AnonymousUser7from user.models import User, Teacher, Student8from rest_framework.response import Response9from rest_framework.permissions import IsAuthenticated, AllowAny10import sys11from io import StringIO12from rest_framework.status import *13from rest_framework.renderers import TemplateHTMLRenderer14from django.shortcuts import redirect, get_object_or_40415from django.contrib.auth import authenticate, login, logout16import time17from core.utils import plagiarism18class UserDetail(generics.RetrieveAPIView):19 queryset = User.objects.all()20 serializer_class = UserSerializer21class ProgrammingTaskDetail(generics.RetrieveAPIView):22 queryset = ProgrammingTask.objects.all()23 serializer_class = ProgrammingTaskSerializer24class ProgrammingTaskSolutionDetail(generics.RetrieveAPIView):25 queryset = ProgrammingTaskSolution.objects.all()26 serializer_class = ProgrammingTaskSolutionSerializer27class ProgrammingTaskSolutionView(generics.CreateAPIView):28 queryset = ProgrammingTaskSolution.objects.all()29 serializer_class = ProgrammingTaskSolutionSerializer30 def create(self, request, *args, **kwargs):31 try:32 old_stdout = sys.stdout33 x = StringIO()34 mystdout = sys.stdout = x35 exec(request.data['code'])36 sys.stdout = old_stdout37 except Exception as e:38 return Response({"error": str(e)}, status=HTTP_400_BAD_REQUEST)39 serializer = ProgrammingTaskSolutionSerializer(data=request.data)40 mystdout.getvalue().replace("\n", "")41 if serializer.is_valid():42 task = ProgrammingTask.objects.get(id=request.data['task'])43 print(task.output_example + " " + mystdout.getvalue())44 if task.output_example.strip() == mystdout.getvalue().strip():45 print(1)46 return Response({"answer": "you are right!", "programming_solution": serializer.data,47 "execute": mystdout.getvalue().replace('\n', "")}, status=HTTP_200_OK)48 else:49 return Response({"answer": "you are not right!", "programming_solution": serializer.data,50 "execute": mystdout.getvalue().replace('\n', "")}, status=HTTP_400_BAD_REQUEST)51 return Response({"error": serializer.errors}, status=HTTP_400_BAD_REQUEST)52class ProgrammingTaskView(generics.ListCreateAPIView):53 queryset = ProgrammingTask.objects.all()54 serializer_class = ProgrammingTaskSerializer55# view for textEditor.html56class TextEditorView(generics.ListCreateAPIView):57 queryset = ProgrammingTaskSolution.objects.all()58 serializer_class = ProgrammingTaskSolutionSerializer59 template_name = 'onlineCoding/textEditor.html'60 def get(self, request, *args, **kwargs):61 return render(request, self.template_name)62 def create(self, request, *args, **kwargs):63 serializer = ProgrammingTaskSolutionSerializer(data=request.data)64 if serializer.is_valid():65 serializer.save()66 return Response(serializer.data, status=HTTP_201_CREATED)67 return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)68def index(request):69 courses = Course.objects.all()70 return render(request, 'onlineCoding/index.html', {'courses': courses})71def loginPage(request):72 if request.method == 'GET':73 if request.user.is_authenticated:74 return redirect('problems')75 loginform = UserFormLogin()76 return render(request, 'onlineCoding/login.html', {'loginform': loginform})77 elif request.method == 'POST':78 loginform = UserFormLogin(request.POST)79 if loginform.is_valid():80 username = loginform.cleaned_data['email']81 password = loginform.cleaned_data['password']82 user = authenticate(username=username, password=password)83 if user is not None:84 login(request, user)85 return redirect('problems')86 else:87 return redirect('login')88def registerPage(request):89 if request.method == 'GET':90 if request.user.is_authenticated:91 return redirect('problems')92 form = UserForm()93 return render(request, 'onlineCoding/register.html', {'form': form})94 elif request.method == 'POST':95 form = UserForm(request.POST)96 exists = User.objects.filter(email=request.POST['email']).exists()97 if form.is_valid() and not exists:98 unique_number = form.cleaned_data.pop('unique_number')99 user = User.objects.create_user(**form.cleaned_data)100 user.set_password(form.cleaned_data['password'])101 user.save()102 teacher = Teacher.objects.all().filter(uniquenumber=unique_number).first()103 if teacher:104 Student.objects.create(user=user, teacher=teacher)105 else:106 Student.objects.create(user=user, teacher=None)107 # set current user108 user = authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password'])109 login(request, user)110 return redirect('problems')111 else:112 return redirect('register')113def base(request):114 return render(request, 'onlineCoding/base.html')115def problems(request):116 print(request.user)117 tasks = ProgrammingTask.objects.all()118 for i in tasks:119 i.description = i.description[0:40] + "..."120 return render(request, 'onlineCoding/problems.html', {'tasks': tasks})121def textEditor(request, slug):122 if request.method == 'GET':123 task = get_object_or_404(ProgrammingTask, slug=slug)124 form = ProgrammingTaskSolutionForm()125 # if request.user.is_authenticated:126 first_test = Tests.objects.all().filter(task=task).first()127 tasksolution = ProgrammingTaskSolution.objects.filter(task=task, author=request.user).first()128 print(tasksolution)129 if tasksolution:130 return render(request, 'onlineCoding/textEditor.html',131 {132 'first_test': first_test,133 'task': task,134 'form': form,135 'type': 'warning',136 'error': "You have already solved this task"137 }138 )139 return render(request, 'onlineCoding/textEditor.html', {'task': task, 'form': form, 'first_test': first_test})140 # else:141 # return render(request, 'onlineCoding/problempage.html')142 elif request.method == 'POST' and 'submit' in request.POST and request.user.is_authenticated and request.POST[143 'code']:144 # create object ProgrammingTaskSolution145 print(request.POST)146 task = get_object_or_404(ProgrammingTask, slug=slug)147 form = ProgrammingTaskSolutionForm()148 tasksolution = ProgrammingTaskSolution.objects.filter(task=task, author=request.user).first()149 first_test = Tests.objects.all().filter(task=task).first()150 print(tasksolution)151 if tasksolution:152 return render(request, 'onlineCoding/textEditor.html',153 {154 'first_test': first_test,155 'task': task,156 'form': form,157 'type': 'warning',158 'error': "You have already solved this task",159 "code" : request.POST['code']160 }161 )162 tests = Tests.objects.all().filter(task=task)163 data = request.POST['code']164 if request.FILES.get('file'):165 file = request.FILES.get('file')166 print(file)167 data = file.read().decode('utf-8')168 for test in tests:169 start = time.time()170 try:171 old_stdout = sys.stdout172 x = StringIO()173 mystdout = sys.stdout = x174 exec(f"task = \"{first_test.input_data}\"\n" + data + "\n" + "print(submit({first_test.input_data}))")175 sys.stdout = old_stdout176 except Exception as e:177 return render(request, 'onlineCoding/textEditor.html',178 {179 'task': task,180 'type': 'danger',181 'first_test': first_test,182 'form': form,183 'error': str(e),184 "code" : request.POST['code']185 }186 )187 end = time.time()188 if end - start > test.task.time_limit:189 return render(request, 'onlineCoding/textEditor.html',190 {191 'task': task,192 'first_test': first_test,193 'form': form,194 'type': 'danger',195 'error': "Time limit exceeded",196 "code" : request.POST['code']197 }198 )199 mystdout = mystdout.getvalue().replace("\n", "")200 if test.output_data.strip() != mystdout.strip():201 return render(request, 'onlineCoding/textEditor.html',202 {203 'first_test': first_test,204 'task': task,205 'form': form,206 'type': 'danger',207 'error': "Wrong answer!",208 "code" : request.POST['code']209 })210 solutions = ProgrammingTaskSolution.objects.all()211 obj = ProgrammingTaskSolution.objects.create(code=request.POST['code'], task=task, author=request.user)212 if task.max_plagiarism > 0:213 for s in solutions:214 percent = plagiarism(s.code, request.POST['code'])215 if percent > task.max_plagiarism and s != obj:216 obj.isplagiarized = True217 obj.plagiat = round(percent, 2)218 obj.save()219 return render(request, 'onlineCoding/textEditor.html',220 {'task': task, 'error': 'plagiarism detected', "code" : request.POST['code']})221 student = Student.objects.all().filter(user=request.user).first()222 if student:223 student.rating += task.rating224 student.save()225 first_test = Tests.objects.all().filter(task=task).first()226 return render(request, 'onlineCoding/textEditor.html',227 {228 'task': task,229 'first_test': first_test,230 'form': form,231 'type': 'success',232 'answer': f"Correct!",233 "code" : request.POST['code']234 }235 )236 elif request.method == 'POST' and 'run' in request.POST and request.user.is_authenticated and request.POST['code']:237 print(request.POST['code'])238 # run code239 task = get_object_or_404(ProgrammingTask, slug=slug)240 form = ProgrammingTaskSolutionForm()241 first_test = Tests.objects.all().filter(task=task).first()242 start = time.time()243 x = StringIO()244 data = request.POST['code']245 246 try:247 old_stdout = sys.stdout248 mystdout = sys.stdout = x249 exec(f"task = \"{first_test.input_data}\"\n" + data + "\n" + "print(submit({first_test.input_data}))")250 sys.stdout = old_stdout251 except Exception as e:252 return render(request, 'onlineCoding/textEditor.html',253 {254 'task': task,255 'first_test': first_test,256 'form': form,257 'type': 'danger',258 'error': str(e),259 "code" : data,260 }261 )262 end = time.time()263 mystdout = mystdout.getvalue().replace("\n", "")264 test = Tests.objects.all().filter(task=task).first()265 if test.output_data.strip() != mystdout.strip():266 print(1)267 return render(request, 'onlineCoding/textEditor.html',268 {269 'task': task,270 'first_test': first_test,271 'form': form,272 'type': 'danger',273 'error': "Wrong answer!",274 "code" : data275 })276 first_test = Tests.objects.all().filter(task=task).first()277 if end - start > first_test.task.time_limit:278 return render(request, 'onlineCoding/textEditor.html',279 {280 'task': task,281 'form': form,282 'first_test': first_test,283 'type': 'danger',284 'error': "Time limit exceeded",285 "code" : data286 }287 )288 return render(request, 'onlineCoding/textEditor.html',289 {290 'task': task,291 'first_test': first_test,292 'form': form,293 'type': 'success',294 'answer': "Correct!",295 "code" : data296 }297 )298 # else:299 # return render(request, 'onlineCoding/textEditor.html',300 # {'task': task, 'form': form, 'answer': "you are not right!"})301def profile(request):302 if request.method == 'GET':303 if request.user.is_authenticated:304 user = Student.objects.all().filter(user=request.user).first()305 if not user:306 user = Teacher.objects.all().filter(user=request.user).first()307 problems = ProgrammingTaskSolution.objects.all().filter(author=request.user)308 # size of problems309 return render(request, 'onlineCoding/profile.html', {'user': user, 'problems': len(problems)})310 else:311 return render(request, 'onlineCoding/404.html')312def leaderboard(request):313 users = Student.objects.all().order_by('-rating')314 place = 1315 if request.user.is_authenticated:316 currentUser = Student.objects.all().filter(user=request.user).first()317 for u in users:318 pprint(u.user.email)319 if u.user.email == currentUser.user.email:320 break321 place += 1322 return render(request, 'onlineCoding/leaderboard.html', {'users': users, 'place': place, currentUser: currentUser})323 return render(request, 'onlineCoding/leaderboard.html', {'users': users, 'place': place})324def courses(request):325 courses = Course.objects.all()326 return render(request, 'onlineCoding/courses.html', {'courses': courses})327def coursePage(request, slug):328 course = get_object_or_404(Course, slug=slug)329 chapters = Chapter.objects.all().filter(course=course).order_by('created_at')330 tasks = ProgrammingTask.objects.all().filter(course=course)331 return render(request, 'onlineCoding/coursePage.html', {'course': course, 'chapters': chapters, 'tasks': tasks})332def logout_view(request):333 logout(request)334 return redirect('login')335def not_found_view(request):336 return render(request, 'onlineCoding/404.html')337def teacher(request):338 if request.user.is_authenticated:339 if request.method == 'GET' and Teacher.objects.all().filter(user=request.user).exists():340 form = CourseForm()341 coursesOfTeacher = Course.objects.all().filter(author=request.user)342 teacher = Teacher.objects.all().filter(user=request.user).first()343 users_of_teachers = Student.objects.all().filter(teacher=teacher)344 plagiarism_tasks_solution = ProgrammingTaskSolution.objects.all().filter(task__teacher=teacher,345 isplagiarized=True)346 return render(request, 'onlineCoding/teachers.html',347 {'teacher': teacher, 'plagiarism_tasks': plagiarism_tasks_solution,348 'users_of_teachers': users_of_teachers, 'form': form, 'courses': coursesOfTeacher})349 elif request.method == 'POST' and Teacher.objects.all().filter(user=request.user).exists():350 teacher = Teacher.objects.all().filter(user=request.user).first()351 print(request.POST)352 if 'add_student' in request.POST:353 student = get_object_or_404(Student, user__email=request.POST['email'])354 student.teacher = teacher355 student.save()356 return redirect('teacher')357 elif 'add_task' in request.POST:358 task = ProgrammingTask.objects.create(name=request.POST['name'],359 description=request.POST['description'],360 course=Course.objects.all().filter(361 slug=request.POST['course']).first(),362 teacher=teacher,363 time_limit=request.POST['time_limit'],364 max_plagiarism=request.POST['max_plagiarism'],365 rating=request.POST['rating'])366 task.save()367 return redirect('teacher')368 elif 'add_chapter' in request.POST:369 chapter = Chapter.objects.create(title=request.POST['title'],370 description=request.POST['description'],371 slug=request.POST['slug'],372 banner=request.FILES['banner'],373 course=Course.objects.all().filter(id=request.POST['course']).first(),374 information=request.POST['information'],375 author=teacher.user)376 chapter.save()377 return redirect('teacher')378 elif 'add_test' in request.POST:379 test = Tests.objects.create(input_data=request.POST['input_data'],380 output_data=request.POST['output_data'],381 task=ProgrammingTask.objects.all().filter(382 slug=request.POST['task']).first())383 test.save()384 return redirect('teacher')385 elif 'add_course' in request.POST:386 course = Course.objects.create(title=request.POST['title'],387 description=request.POST['description'],388 slug=request.POST['slug'],389 banner=request.FILES['banner'],390 author=teacher.user)391 course.save392 return redirect('login')393def solved(request):394 if request.user.is_authenticated:395 if request.method == 'GET':396 solved_tasks = ProgrammingTaskSolution.objects.all().filter(author=request.user)397 return render(request, 'onlineCoding/solved.html', {'solved_tasks': solved_tasks})...

Full Screen

Full Screen

utils.py

Source:utils.py Github

copy

Full Screen

1import first_test2def cli_color(string, new=0, end=0, color='g'):3 colors = {4 'g': '[032m',5 'r': '[031m',6 'w': '[0m',7 }8 str = chr(27) + colors[color] + string + chr(27) + colors['w']9 if (new):10 str = '\n' + str11 if (end):12 str += '\n'13 return str14def test(received, expected):15 if (expected == received):16 print(cli_color("OK", 0, 1))17 else:18 print(cli_color("Fail", 0, 1, 'r'))19def test_my_sum():20 print("We are testing my_sum!" + '\n')21 test(12, first_test.my_sum((10, 2, 0)))22 test(144, first_test.my_sum((10, 20, 100, 14)))23 test(12, first_test.my_sum((-50, 200, -100, -50, 12)))24def test_shortener():25 print("We are testing shortener!" + '\n')26 sourceStrings = (27 'A very looooooong wooooord',28 'Loremia ipsumia dolaria sitia ameti',29 'Have you ever been to Lituania ?',30 'Anyone who reads Old and Middle',31 'English literary texts will be familiar',32 'with the mid-brown volumes of the EETS,',33 'with the symbol of Alfreds jewel embossed on the front cover+'34 )35 testStrings = (36 'A very looooo* wooooo*',37 'Loremi* ipsumi* dolari* sitia ameti',38 'Have you ever been to Lituan* ?',39 'Anyone who reads Old and Middle',40 'Englis* litera* texts will be famili*',41 'with the mid-br* volume* of the EETS,',42 'with the symbol of Alfred* jewel emboss* on the front cover+'43 )44 for i in range(len(sourceStrings)):45 test(testStrings[i], first_test.shortener(sourceStrings[i]))46def test_compare_ends():47 print("We are testing compare_ends!" + '\n')48 test(first_test.compare_ends(('aba', 'xyz', 'aa', 'x', 'bbb')), 3)49 test(first_test.compare_ends(('', 'x', 'xy', 'xyx', 'xx')), 2)50 test(first_test.compare_ends(('aaa', 'be', 'abc', 'hello')), 1)51def test_spam():52 print("We are testing spam!" + '\n')53 test(first_test.spam((3)), 'bulochka'*3)54 test(first_test.spam((1)), 'bulochka')55 test(first_test.spam((8)), 'bulochka'*8)56test_spam()57test_shortener()58test_compare_ends()...

Full Screen

Full Screen

test_ll_zip.py

Source:test_ll_zip.py Github

copy

Full Screen

1from data_structures_and_algorithms.data_structures.linked_list.linked_list import LinkedList,Node2from data_structures_and_algorithms.challenges.ll_zip.ll_zip import zipLists3def test_equal_list():4 First_test = LinkedList()5 Second_test = LinkedList()6 7 First_test.append(1)8 First_test.append(3)9 First_test.append(2)10 11 Second_test.append(5)12 Second_test.append(9)13 Second_test.append(4)14 15 16 zipLists(First_test,Second_test)17 expected = "{1} -> {5} -> {3} -> {9} -> {2} -> {4} -> NULL"18 actual = First_test.__str__()19 assert expected == actual20def test_not_equal_first_list():21 First_test = LinkedList()22 Second_test = LinkedList()23 24 First_test.append(1)25 First_test.append(3)26 27 Second_test.append(5)28 Second_test.append(9)29 Second_test.append(4)30 31 zipLists(First_test,Second_test)32 expected = "{1} -> {5} -> {3} -> {9} -> {4} -> NULL"33 actual = First_test.__str__()34 assert expected == actual35def test_not_equal_second_list():36 First_test = LinkedList()37 Second_test = LinkedList()38 39 First_test.append(1)40 First_test.append(3)41 First_test.append(2)42 43 Second_test.append(5)44 Second_test.append(9)45 46 zipLists(First_test,Second_test)47 expected = "{1} -> {5} -> {3} -> {9} -> {2} -> NULL"48 actual = First_test.__str__()...

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 Lemoncheesecake 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