from django.test import TestCase, RequestFactory
from graphene.test import Client
from graphql_relay import to_global_id

from api.schema import schema
from assignments.factories import AssignmentFactory
from assignments.models import StudentSubmission
from assignments.tests.queries.mutations import UPDATE_ASSIGNMENT_MUTATION
from users.models import User
from users.services import create_users


class DuplicateStudentSubmissionsTestCase(TestCase):
    def setUp(self):
        create_users()

        self.student1 = User.objects.get(username='student1')
        self.assignment = AssignmentFactory()
        self.assignment_id = to_global_id('AssignmentNode', self.assignment.id)

        # create 2 submissions, can happen if multiple requests arrive simultaneously
        StudentSubmission.objects.create(assignment=self.assignment, student=self.student1, text='abc')
        StudentSubmission.objects.create(assignment=self.assignment, student=self.student1, text='abcd')

        request = RequestFactory().get('/')
        request.user = self.student1
        self.client = Client(schema=schema, context_value=request)

    def test_returns_one_submission(self):
        query = UPDATE_ASSIGNMENT_MUTATION
        answer = "Abcdefg"
        variables = {
            "input": {
                "assignment": {
                    "answer": answer,
                    "document": "",
                    "final": True,
                    "id": self.assignment_id
                }
            }
        }

        result = self.client.execute(query, variables=variables)
        self.assertIsNone(result.get('errors'))
        self.assertEquals(
            result.get('data').get('updateAssignment').get('updatedAssignment').get('submission').get('text'), answer)
