#!/usr/bin/env python2
# -*- coding: utf-8 -*-

from __future__ import absolute_import, unicode_literals

from nose.tools import *

from . import setup_each, teardown_each
from farnsworth.models import (Exploit, ChallengeBinaryNode, AFLJob,
                               ChallengeSet, Round, Team)

BLOB = "exploit"


class TestExploit:
    def setup(self):
        setup_each()

    def teardown(self):
        teardown_each()

    def test_pov_type(self):
        cs = ChallengeSet.create(name="foo")
        job = AFLJob.create(cs=cs)
        exploit = Exploit.create(cs=cs, job=job, pov_type="type1", blob="exploit",
                                 c_code="exploit it")
        assert_equals(exploit.pov_type, "type1")

        def invalid_pov_type():
            Exploit.create(cs=cs, job=job, pov_type="bar")
        assert_raises(Exception, invalid_pov_type)

    def test_submit_to(self):
        r0 = Round.create(num=0)
        r1 = Round.create(num=1)
        cs = ChallengeSet.create(name="foo")
        cs.rounds = [r1.id]
        job = AFLJob.create(cs=cs)
        exploit = Exploit.create(job=job, cs=cs, pov_type="type1", blob=BLOB, c_code="exploit it")
        team = Team.create(name="opponent")

        assert_equals(len(exploit.fieldings), 0)

        ef = exploit.submit_to(team=team, throws=10)
        assert_equals(len(exploit.fieldings), 1)
        assert_equals(ef.submission_round, Round.current_round())

        ef = exploit.submit_to(team=team, throws=5, round=r0)
        assert_equals(len(exploit.fieldings), 2)
        assert_equals(ef.submission_round, r0)
