import time
import json
import os
import subprocess
import requests
from threading import Thread
from django.test import TestCase, Client
from django.test import Client
from django.conf import settings
from products.models import *
from django.contrib.auth.models import User

BASE_DIR = os.path.abspath(os.path.dirname(__file__) + "/..")

class StressTest(TestCase):
    def setUp(self):
        User(is_superuser=True, username="admin", password="testpass").save()

        self.token0 = 'tenanttoken0'
        t = Tenant(username="tenant0", mobile="12300000000",
                   password="testpass", token=self.token0)
        t.save()

        self.tenant = t
        self.client = Client()

    def test_qr_verify(self):
        p = Product.objects.create(name='testprod',
                                   tenant=self.tenant)
        b = CodeBatch.objects.create(product=p, code_prefix="")
        c = SerialCode.objects.create(batch=b, code='1234441219866726744')

        begin = time.time()
        for i in range(100):
            self.do_qr_verify()

        end = time.time()

        self.assertLess(end - begin, 1)

    def do_qr_verify(self):
        img = open(os.path.join(BASE_DIR, "tests/data/qr.png"), 'rb')
        r = self.client.post("/api/v1/qr-verify/", {
            'username': 'testuser',
            'photo': img,
        })
        self.assertEqual(r.json().get('error'), None)
