<commit_before>import json

from datetime import datetime

from django.test import TestCase

from authentication.models import Account

from recipies.models import Recipe
from recipies.serializers import RecipeSerializer


# Create your tests here.
class TestRecipeModel(TestCase):
  """Test the custom method attached to the Recipe model"""

  def setUp(self):
    self.recipe_data = dict(
      recipe_name="Test Recipe",
      recipe_style="Kolsch",
      recipe_notes="This is my first test recipe submited from a unit test.",
      last_brew_date=datetime.now()
    )
    self.malts_data = [
      dict(
        malt_brand="ABrand",
        malt_type="Extra Light",
        amount_by_weight=3.3,
      ),
      dict(
        malt_brand="BBrand",
        malt_type="Crystal",
        amount_by_weight=1.5,
        malt_extract=False
      ),
      dict(
        malt_brand="CBrand",
        malt_type="Light",
        amount_by_weight=3,
        dry_malt=True,
      ),
    ]
    self.hops_data = [
      dict(
        hop_name="Amarillo",
        alpha_acid_content=12.3,
        beta_acid_content=7.9,
        add_time=15,
        add_time_unit="Minutes",
      ),
      dict(
        hop_name="Cascade",
        alpha_acid_content=8.8,
        add_time=60,
        add_time_unit="Minutes",
      ),
      dict(
        hop_name="Citra",
        alpha_acid_content=7.9,
        beta_acid_content=4.6,
        add_time=7,
        add_time_unit="Days",
        dry_hops=True,
      ),
    ]
    self.user = Account.objects.create_user('test', 'foo')

  def tearDown(self):
    self.recipe_data=None
    self.malts_data=None
    self.hops_data=None
    self.user.delete()

  def checkElement(self, model, data):
    """Helper Function. Either check two values against on another or call correct helper function"""
    # IF the type is a list or dict, call the correct function to check its elements. ELSE directly
    # compare the elements
    if type(model) is list:
      self.checkArrayModel(model, data)
    elif type(model) is dict:
      self.checkDictModel(model, data)
    else:
      self.assertEqual(model, data)

  def checkArrayModel(self, model, data):
    """Helper function. Check an array to see if the model data is present in the data array"""

    for i in range(len(model)):
      self.checkElement(model[i], data[i])

  def checkDictModel(self, model, data):
    """Helper function. Check a model dictionary against a data dictionary key by key"""
    for key in model.keys():
      self.checkElement(model.get(key), data.__dict__.get(key))

  def test_RecipeManager_CreateValidRecipe(self):
    recipe = Recipe.objects.create_recipe(self.user, self.recipe_data, malts_data=self.malts_data, hops_data=self.hops_data)

    self.assertIsInstance(recipe, Recipe)

    self.checkElement(self.hops_data, recipe.recipe_hops.order_by("hop_name"))
    self.checkElement(self.malts_data, recipe.recipe_malts.order_by("malt_brand"))
    self.checkElement(self.recipe_data, recipe)

  def test_RecipeManager_FailNoRecipeData(self):
    with self.assertRaises(ValueError) as err:
      Recipe.objects.create_recipe(self.user, None, self.malts_data, self.hops_data)

    self.assertEqual(err.exception.message, 'Recipe information is required to create a recipe.')

  def test_RecipeManager_FailInactiveUser(self):
    self.user.is_active=False
    with self.assertRaises(ValueError) as err:
      Recipe.objects.create_recipe(self.user, self.recipe_data, malts_data=self.malts_data, hops_data=self.hops_data)

    self.assertEqual(err.exception.message, 'Account must be active to create a recipe.')

  def test_RecipeManager_FailNotLoggedIn(self):
    with self.assertRaises(ValueError) as err:
      Recipe.objects.create_recipe(None, self.recipe_data, malts_data=self.malts_data, hops_data=self.hops_data)

    self.assertEqual(err.exception.message, 'Need to be logged in to create a recipe.')

class TestRecipeSerializer(TestCase):
  """Test the serializers for the recipe class"""

  def setUp(self):
    self.json_data = open('recipies/testRecipe.json','r').read()
    self.data = json.loads(self.json_data)
    # Extract just the date portion from the datetime object
    my_datetime = datetime.today()
    self.data['last_brew_date'] = datetime.date(my_datetime)

    self.account = Account.objects.create(username='foot',password='<PASSWORD>')

  def tearDown(self):
    self.json_data = None
    self.data = None
    self.account.delete()

  def checkElement(self, model, data):
    """Helper Function. Either check two values against on another or call correct helper function"""
    # IF the type is a list or dict, call the correct function to check its elements. ELSE directly
    # compare the elements
    if type(model) is list:
      self.checkArrayModel(model, data)
    elif type(model) is dict:
      self.checkDictModel(model, data)
    else:
      self.assertEqual(model, data)

  def checkArrayModel(self, model, data):
    """Helper function. Check an array to see if the model data is present in the data array"""

    for i in range(len(model)):
      self.checkElement(model[i], data[i])

  def checkDictModel(self, model, data):
    """Helper function. Check a model dictionary against a data dictionary key by key"""
    for key in model.keys():
      self.checkElement(model.get(key), data.__dict__.get(key))

  def test_RecipeSerializer_Create_ValidData(self):
    serialized_data = RecipeSerializer(data=self.data)

    self.assertTrue(serialized_data.is_valid())

    recipe = serialized_data.save(user=self.account)
    self.checkElement(self.data.pop('recipe_hops'), recipe.recipe_hops.order_by("hop_name"))
    self.checkElement(self.data.pop('recipe_malts'), recipe.recipe_malts.order_by("malt_brand"))
    self.checkElement(self.data, recipe)<commit_msg>Began updating the unit tests for the updated serialier. Currently the new data passed to the serializer is invalid<commit_after>import json

from datetime import datetime

from django.test import TestCase

from authentication.models import Account

from recipies.models import Recipe
from recipies.serializers import RecipeSerializer


# Create your tests here.
class TestRecipeModel(TestCase):
  """Test the custom method attached to the Recipe model"""

  def setUp(self):
    self.recipe_data = dict(
      recipe_name="<NAME>",
      recipe_style="Kolsch",
      recipe_notes="This is my first test recipe submited from a unit test.",
      last_brew_date=datetime.now()
    )
    self.malts_data = [
      dict(
        malt_brand="ABrand",
        malt_type="Extra Light",
        amount_by_weight=3.3,
      ),
      dict(
        malt_brand="BBrand",
        malt_type="Crystal",
        amount_by_weight=1.5,
        malt_extract=False
      ),
      dict(
        malt_brand="CBrand",
        malt_type="Light",
        amount_by_weight=3,
        dry_malt=True,
      ),
    ]
    self.hops_data = [
      dict(
        hop_name="Amarillo",
        alpha_acid_content=12.3,
        beta_acid_content=7.9,
        add_time=15,
        add_time_unit="Minutes",
      ),
      dict(
        hop_name="Cascade",
        alpha_acid_content=8.8,
        add_time=60,
        add_time_unit="Minutes",
      ),
      dict(
        hop_name="Citra",
        alpha_acid_content=7.9,
        beta_acid_content=4.6,
        add_time=7,
        add_time_unit="Days",
        dry_hops=True,
      ),
    ]
    self.user = Account.objects.create_user('test', 'foo')

  def tearDown(self):
    self.recipe_data=None
    self.malts_data=None
    self.hops_data=None
    self.user.delete()

  def checkElement(self, model, data):
    """Helper Function. Either check two values against on another or call correct helper function"""
    # IF the type is a list or dict, call the correct function to check its elements. ELSE directly
    # compare the elements
    if type(model) is list:
      self.checkArrayModel(model, data)
    elif type(model) is dict:
      self.checkDictModel(model, data)
    else:
      self.assertEqual(model, data)

  def checkArrayModel(self, model, data):
    """Helper function. Check an array to see if the model data is present in the data array"""

    for i in range(len(model)):
      self.checkElement(model[i], data[i])

  def checkDictModel(self, model, data):
    """Helper function. Check a model dictionary against a data dictionary key by key"""
    for key in model.keys():
      self.checkElement(model.get(key), data.__dict__.get(key))

  def test_RecipeManager_CreateValidRecipe(self):
    recipe = Recipe.objects.create_recipe(self.user, self.recipe_data, malts_data=self.malts_data, hops_data=self.hops_data)

    self.assertIsInstance(recipe, Recipe)

    self.checkElement(self.hops_data, recipe.recipe_hops.order_by("hop_name"))
    self.checkElement(self.malts_data, recipe.recipe_malts.order_by("malt_brand"))
    self.checkElement(self.recipe_data, recipe)

  def test_RecipeManager_FailNoRecipeData(self):
    with self.assertRaises(ValueError) as err:
      Recipe.objects.create_recipe(self.user, None, self.malts_data, self.hops_data)

    self.assertEqual(err.exception.message, 'Recipe information is required to create a recipe.')

  def test_RecipeManager_FailInactiveUser(self):
    self.user.is_active=False
    with self.assertRaises(ValueError) as err:
      Recipe.objects.create_recipe(self.user, self.recipe_data, malts_data=self.malts_data, hops_data=self.hops_data)

    self.assertEqual(err.exception.message, 'Account must be active to create a recipe.')

  def test_RecipeManager_FailNotLoggedIn(self):
    with self.assertRaises(ValueError) as err:
      Recipe.objects.create_recipe(None, self.recipe_data, malts_data=self.malts_data, hops_data=self.hops_data)

    self.assertEqual(err.exception.message, 'Need to be logged in to create a recipe.')

class TestRecipeSerializer(TestCase):
  """Test the serializers for the recipe class"""

  def setUp(self):
    self.json_data = open('recipies/testRecipe.json','r').read()
    self.data = self.retrieveRecipeData()
    # Extract just the date portion from the datetime object
    my_datetime = datetime.today()
    self.data['last_brew_date'] = datetime.date(my_datetime)

    self.account = Account.objects.create(username='foot',password='<PASSWORD>')

  def tearDown(self):
    self.json_data = None
    self.data = None
    self.account.delete()

  def retrieveRecipeData(self):
    """Retrieve a new decoding of the JSON recipe data"""
    return json.loads(self.json_data)

  def createRecipe(self, user, data):
    """Create a recipe for use with the update unit test"""
    hops  = data.pop("recipe_hops")
    malts = data.pop("recipe_malts")
    return Recipe.objects.create_recipe(user, data, malts, hops)

  def addHop(self, hops):
    """Append a new hop onto the current hops data"""
    new_hop = dict(
      hop_name="Tettang",
      alpha_acid_content=8.8,
      beta_acid_content=6.4,
      add_time=3,
      add_time_unit="Days",
      dry_hops=True,
    )

    return hops.append(new_hop)

  def checkElement(self, model, data):
    """Helper Function. Either check two values against on another or call correct helper function"""
    # IF the type is a list or dict, call the correct function to check its elements. ELSE directly
    # compare the elements
    if type(model) is list:
      self.checkArrayModel(model, data)
    elif type(model) is dict:
      self.checkDictModel(model, data)
    else:
      self.assertEqual(model, data)

  def checkArrayModel(self, model, data):
    """Helper function. Check an array to see if the model data is present in the data array"""

    for i in range(len(model)):
      self.checkElement(model[i], data[i])

  def checkDictModel(self, model, data):
    """Helper function. Check a model dictionary against a data dictionary key by key"""
    for key in model.keys():
      self.checkElement(model.get(key), data.__dict__.get(key))

  def test_RecipeSerializer_Create_ValidData(self):
    serialized_data = RecipeSerializer(data=self.data)

    self.assertTrue(serialized_data.is_valid())

    recipe = serialized_data.save(user=self.account)
    self.checkElement(self.data.pop('recipe_hops'), recipe.recipe_hops.order_by("hop_name"))
    self.checkElement(self.data.pop('recipe_malts'), recipe.recipe_malts.order_by("malt_brand"))
    self.checkElement(self.data, recipe)

  def test_RecipeSerializer_Update_ValidData(self):
    premade_recipe = self.createRecipe(self.account, self.data)
    recipe_data    = self.retrieveRecipeData()
    # Add another hop
    current_hops = recipe_data.pop('recipe_hops')
    self.data['recipe_hops']  = self.addHop(current_hops)

    # Change the malt
    self.data['recipe_malts'] = dict(
      malt_brand="Fruity_Tooty",
      malt_type="Crystal",
      malt_extract=False,
      amount_by_weight=7.0
    )

    # Update the notes
    self.data['recipe_notes'] = "Added this crystal to spice it up."

    serializer = RecipeSerializer(instance=premade_recipe, data=self.data)
    print serializer.is_valid()
    if not serializer.is_valid():
      print serializer.errors
    updated_recipe = serializer.save()
    print updated_recipe
{'fraction_non_alphanumeric': 0.10485156783843293, 'fraction_numerical': 0.0037202945865917546, 'mean_word_length': 3.5326909841706815, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4202849', 'n_tokens_mistral': 4232, 'n_tokens_neox': 4103, 'n_words': 986}