Django 测试 models.py 文件

Django testing models.py file

我正在为我的 models.py 文件执行 Django

这是我的 models.py 文件

import sys
from datetime import datetime

from dateutil.relativedelta import relativedelta
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django_google_maps import fields as map_fields
from django_mysql.models import ListTextField
from simple_history.models import HistoricalRecords

from farm_management import config
from igrow.utils import get_commodity_name, get_region_name, get_farmer_name, get_variety_name

db_config = settings.USERS_DB_CONNECTION_CONFIG


class Device(models.Model):
    id = models.CharField(max_length=100, primary_key=True)
    fetch_status = models.BooleanField(default=True)
    last_fetched_on = models.DateTimeField(auto_now=True)
    geolocation = map_fields.GeoLocationField(max_length=100)
    device_status = models.CharField(max_length=100, choices=config.DEVICE_STATUS, default='new')
    is_active = models.BooleanField(default=True)
    history = HistoricalRecords()


class Farm(models.Model):
    farmer_id = models.PositiveIntegerField()  # User for which farm is created
    irrigation_type = models.CharField(max_length=50, choices=config.IRRIGATION_TYPE_CHOICE)
    soil_test_report = models.CharField(max_length=512, null=True, blank=True)
    water_test_report = models.CharField(max_length=512, null=True, blank=True)
    farm_type = models.CharField(max_length=50, choices=config.FARM_TYPE_CHOICE)
    franchise_type = models.CharField(max_length=50, choices=config.FRANCHISE_TYPE_CHOICE)
    total_acerage = models.FloatField(help_text="In Acres", null=True, blank=True,
                                      validators=[MaxValueValidator(1000000), MinValueValidator(0)])
    farm_status = models.CharField(max_length=50, default="pipeline", choices=config.FARM_STATUS_CHOICE)
    assignee_id = models.PositiveIntegerField(null=True, blank=True)  # Af team user to whom farm is assigned.
    previous_crop_ids = ListTextField(base_field=models.IntegerField(), null=True, blank=True, size=None)
    sr_assignee_id = models.PositiveIntegerField(null=True, blank=True)
    lgd_state_id = models.PositiveIntegerField(null=True, blank=True)
    district_code = models.PositiveIntegerField(null=True, blank=True)
    sub_district_code = models.PositiveIntegerField(null=True, blank=True)
    village_code = models.PositiveIntegerField(null=True, blank=True)
    farm_network_code = models.CharField(max_length=12, null=True, blank=True)
    farm_health = models.IntegerField(validators=[MaxValueValidator(100), MinValueValidator(0.1)],
                                      help_text="In Percentage", null=True, blank=True)
    soil_k = models.FloatField(verbose_name="Soil (K)", null=True, blank=True)
    soil_n = models.FloatField(verbose_name="Soil (N)", null=True, blank=True)
    soil_p = models.FloatField(verbose_name="Soil (P)", null=True, blank=True)
    water_ec = models.FloatField(verbose_name="Water (ec)", null=True, blank=True)
    water_ph = models.FloatField(verbose_name="Water (pH)", null=True, blank=True)
    soil_test_report_date = models.DateTimeField(null=True, blank=True)
    water_test_report_date = models.DateTimeField(null=True, blank=True)
    pest_problems = models.TextField(verbose_name="Pest Problems (If Any)", null=True, blank=True)
    onboarded_by_id = models.PositiveIntegerField(null=True, blank=True)
    farm_image = models.CharField(max_length=512, null=True, blank=True)
    updated_by_id = models.PositiveIntegerField(null=True, blank=True)
    created_by_id = models.PositiveIntegerField(null=True, blank=True)
    device_id = models.ForeignKey(Device, on_delete=models.CASCADE, related_name="farm", null=True, blank=True,
                                  db_column='device_id')
    boundary_coord = models.TextField(verbose_name="Boundary of Farm", null=True, blank=True)
    lat = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
    lng = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)
    region_name = models.CharField(max_length=200, null=True, blank=True)
    farmer_name = models.CharField(max_length=200, null=True, blank=True)
    farm_name = models.CharField(max_length=200, null=True, blank=True)
    pending_tasks = models.PositiveIntegerField(null=True, blank=True)
    batch_count = models.PositiveIntegerField(default=0, null=True, blank=True)
    locality = models.CharField(max_length=200, null=True, blank=True)
    history = HistoricalRecords()

    class Meta:
        indexes = [
            models.Index(fields=['farmer_id']),
            models.Index(fields=['assignee_id']),
            models.Index(fields=['sr_assignee_id'])
        ]

    def __str__(self):
        return self.farm_name

    def save(self, *args, **kwargs):
        if self.lgd_state_id:
            region_name = get_region_name(self.lgd_state_id)
            if region_name:
                self.region_name = region_name[0]
        if self.farmer_id:
            farmer_name = get_farmer_name(self.farmer_id, 'name')
            if not farmer_name.empty:
                self.farmer_name = farmer_name[0]
                self.farm_name = "{}'s farm".format(self.farmer_name)
                if self.total_acerage:
                    self.farm_name += " - {} acres".format(self.total_acerage)
        super(Farm, self).save(*args, **kwargs)

    def update_pending_tasks(self):
        BatchSOPManagement = apps.get_model('sop_management', 'BatchSOPManagement')
        self.pending_tasks = BatchSOPManagement.objects.filter(batch_id__farm_id=self.id, current_status=2,
                                                               due_datetime__lt=datetime.today()).count()
        self.save()

    def update_batch_count(self):
        Batch = apps.get_model('farm_management', 'Batch')
        self.batch_count = Batch.objects.filter(farm_id=self.id).count()
        self.save()

    def update_farm_health(self):
        Batch = apps.get_model('farm_management', 'Batch')
        farm_health = [batch.batch_health * batch.acerage for batch in Batch.objects.filter(farm_id=self.id) if
                       batch.acerage and batch.batch_health]
        total_acerage = sum([batch.acerage for batch in Batch.objects.filter(farm_id=self.id) if batch.acerage])
        if total_acerage:
            self.farm_health = sum(farm_health) / total_acerage
            self.save()


class HistoricalCropInfo(models.Model):
    historical_yield_per_acre = models.FloatField(verbose_name="Yield / Acre - Historical")
    commodity_id = models.PositiveIntegerField()
    commodity_variety_id = models.PositiveIntegerField(null=True, blank=True)
    farm_id = models.ForeignKey(Farm, on_delete=models.CASCADE, related_name="hist_crops", db_column='farm_id')
    history = HistoricalRecords()


class Batch(models.Model):
    commodity_id = models.PositiveIntegerField(null=True, blank=True)
    commodity_variety_id = models.PositiveIntegerField(null=True, blank=True)
    farm_id = models.ForeignKey(Farm, on_delete=models.CASCADE, related_name="batches", null=True, blank=True,
                                db_column='farm_id')
    start_date = models.DateTimeField(null=True, blank=True)
    acerage = models.FloatField(verbose_name='Batch Acerage', help_text="In Acres;To change this value go to farms>crop"
                                , validators=[MaxValueValidator(1000000), MinValueValidator(0.01)])
    batch_health = models.IntegerField(validators=[MaxValueValidator(100), MinValueValidator(0)],
                                       help_text="In Percentage", default=100, null=True, blank=True)
    stage = models.CharField(max_length=100, choices=config.STAGE_CHOICES, default='germination', null=True, blank=True)
    expected_delivery_date = models.DateTimeField(null=True, blank=True)
    current_pdd = models.FloatField(null=True, blank=True)
    historic_pdd = models.FloatField(null=True, blank=True)
    current_gdd = models.FloatField(null=True, blank=True)
    historic_gdd = models.FloatField(null=True, blank=True)
    sub_farmer_id = models.PositiveIntegerField(null=True, blank=True)
    batch_status = models.CharField(max_length=100, choices=config.BATCH_STATUS, default='to_start')
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_by_id = models.PositiveIntegerField(null=True, blank=True)
    created_by_id = models.PositiveIntegerField(null=True, blank=True)
    historical_yield_per_acre = models.FloatField(verbose_name="Yield / Acre - Historical", null=True, blank=True)
    expected_produce = models.FloatField(default=0, null=True, blank=True)
    actual_produce = models.FloatField(default=0, null=True, blank=True)
    sop_adherence = models.FloatField(default=0, null=True, blank=True)
    actual_yield_per_acre = models.FloatField(default=0, null=True, blank=True)
    end_date = models.DateTimeField(null=True, blank=True)
    commodity_name = models.CharField(max_length=200, null=True, blank=True)
    batch_name = models.CharField(max_length=200, null=True, blank=True)
    batch_median_health = models.PositiveIntegerField(null=True, blank=True)
    pending_tasks = models.PositiveIntegerField(null=True, blank=True, default=0)
    history = HistoricalRecords()

    def __str__(self):
        return self.batch_name

    def save(self, *args, **kwargs):
        SOPMaster = apps.get_model('sop_management', 'SOPMaster')
        BatchSOPManagement = apps.get_model('sop_management', 'BatchSOPManagement')
        batch_sop_list = []
        if self.batch_status is 'completed':
            self.update_batch_end_date()
        self.commodity_name = self.update_commodity_name()
        self.batch_median_health = self.update_batch_median_health()
        self.batch_name = self.update_batch_name()
        super(Batch, self).save(*args, **kwargs)

    def update_commodity_name(self):
        if self.commodity_id:
            commodity_name = get_commodity_name(self.commodity_id)
            if commodity_name:
                return commodity_name[0]
        return None

    def update_batch_median_health(self):
        if self.start_date and self.expected_delivery_date:
            start_date = datetime.combine(self.start_date, datetime.min.time())
            expected_delivery_date = datetime.combine(self.expected_delivery_date, datetime.min.time())
            end_date = min([expected_delivery_date, datetime.today()]) - relativedelta(hours=5, minutes=30)
            hours_diff = int((((end_date - start_date).total_seconds()) / 3600 / 2))
            median_date = start_date + relativedelta(hours=hours_diff)
            try:
                median_crop_health = self.history.as_of(median_date).crop_health
            except:
                median_crop_health = self.batch_health
            return median_crop_health
        else:
            return None

    def update_batch_name(self):
        batch_name = "({}) {}".format(self.id, self.commodity_name)
        if self.start_date:
            batch_name += " | {}".format(self.start_date.strftime('%Y-%m-%d'))
        return batch_name

    def update_expected_delivery_date(self):
        self.expected_delivery_date = max([batch_yield.expected_delivery_date for batch_yield in
                                           self.batch_yields.all() if batch_yield.expected_delivery_date])
        self.save()

    def update_batch_status(self):
        number_of_yields = self.batch_yields.all().count()
        end_date_list = len([batch_yield for batch_yield in self.batch_yields.all() if
                             batch_yield.end_date and batch_yield.end_date.date() < datetime.today().date()])
        if number_of_yields == end_date_list:
            self.batch_status = 3
            self.save()

    def update_expected_produce(self):
        self.expected_produce += sum([batch_yields.expected_production for batch_yields in self.batch_yields.all()
                                      if not batch_yields.end_date])
        self.save()

    def update_actual_produce(self):
        for batch_yields in self.batch_yields.all():
            produce = 0
            if batch_yields.grade_a_produce:
                produce += batch_yields.grade_a_produce
            if batch_yields.grade_b_produce:
                produce += batch_yields.grade_b_produce
            if batch_yields.grade_c_rejection:
                produce += batch_yields.grade_c_rejection
            self.actual_produce += produce
            self.save()

    def update_sop_adherence(self):
        if self.batch_sop_management.all():
            total_sop = self.batch_sop_management.filter(due_datetime__lte=datetime.today())
            complete_sop = total_sop.filter(current_status=3)
            if total_sop:
                self.sop_adherence = complete_sop.count() / total_sop.count() * 100
                self.save()

    def update_actual_yield_per_acre(self):
        batch_actual_produce = 0
        for batch_yields in self.batch_yields.all():
            actual_produce = 0
            if batch_yields.end_date and batch_yields.end_date.date() <= datetime.today().date():
                if batch_yields.grade_a_produce:
                    actual_produce += batch_yields.grade_a_produce
                if batch_yields.grade_b_produce:
                    actual_produce += batch_yields.grade_b_produce
                if batch_yields.grade_c_rejection:
                    actual_produce += batch_yields.grade_c_rejection
            batch_actual_produce += actual_produce
        if self.acerage and batch_actual_produce:
            self.actual_yield_per_acre = batch_actual_produce / self.acerage
            self.save()

    def update_batch_end_date(self):
        batch_yields = self.batch_yields.order_by('-end_date')
        if batch_yields.exists():
            batch_yields_id = batch_yields.filter(end_date__isnull=False)
            if batch_yields_id.exists():
                self.end_date = batch_yields[0].end_date
            else:
                self.end_date = datetime.now()
        else:
            raise ValidationError("Batch yield end date does not exists")

    def update_pending_tasks(self):
        BatchSOPManagement = apps.get_model('sop_management', 'BatchSOPManagement')
        self.pending_tasks = BatchSOPManagement.objects.filter(batch_id=self.id, current_status=2,
                                                               due_datetime__lt=datetime.today()).count()
        self.save()


class BatchYield(models.Model):
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_by_id = models.PositiveIntegerField(null=True, blank=True)
    created_by_id = models.PositiveIntegerField(null=True, blank=True)
    expected_production = models.FloatField(default=0, validators=[MaxValueValidator(1000000000), MinValueValidator(0)],
                                            null=True, blank=True)
    grade_a_produce = models.FloatField(verbose_name='Grade A - Produce', default=0, null=True, blank=True,
                                        validators=[MaxValueValidator(1000000000), MinValueValidator(0)])
    grade_b_produce = models.FloatField(verbose_name='Grade B - Produce', default=0, null=True, blank=True,
                                        validators=[MaxValueValidator(1000000000), MinValueValidator(0)])
    grade_c_rejection = models.FloatField(verbose_name='Grade C - Rejection', default=0, null=True, blank=True,
                                          validators=[MaxValueValidator(1000000000), MinValueValidator(0)])
    expected_delivery_date = models.DateTimeField()
    batch_id = models.ForeignKey(Batch, on_delete=models.CASCADE, related_name="batch_yields", db_column='batch_id')
    end_date = models.DateTimeField(help_text="Fill this date when this yield is realised with final date", null=True,
                                    blank=True)
    grade_a_sell_price = models.DecimalField(verbose_name='Grade A Sell Price', decimal_places=2, max_digits=7,
                                             null=True, blank=True)
    grade_b_sell_price = models.DecimalField(verbose_name='Grade B Sell Price', decimal_places=2, max_digits=7,
                                             null=True, blank=True)
    expected_grade_a_produce = models.DecimalField(decimal_places=2, max_digits=12, null=True, blank=True)
    expected_grade_b_produce = models.DecimalField(decimal_places=2, max_digits=12, null=True, blank=True)
    is_active = models.BooleanField(default=True)
    history = HistoricalRecords()

    def save(self, *args, **kwargs):
        return super(BatchYield, self).save(*args, **kwargs)

    def update_expected_grade_produce(self):
        batch_median_health = self.batch_id.batch_median_health
        if batch_median_health:
            if batch_median_health == 100:
                grade_a_percentage = 60
                grade_b_percentage = 40
            elif 90 <= batch_median_health < 100:
                grade_a_percentage = 50
                grade_b_percentage = 50
            elif 85 <= batch_median_health < 90:
                grade_a_percentage = 45
                grade_b_percentage = 55
            elif 80 <= batch_median_health < 85:
                grade_a_percentage = 40
                grade_b_percentage = 60
            elif 70 <= batch_median_health < 80:
                grade_a_percentage = 30
                grade_b_percentage = 70
            elif 65 <= batch_median_health < 70:
                grade_a_percentage = 20
                grade_b_percentage = 80
            else:
                grade_a_percentage = 0
                grade_b_percentage = 100
            self.expected_grade_a_produce = grade_a_percentage * self.expected_production / 100
            self.expected_grade_b_produce = grade_b_percentage * self.expected_production / 100
            self.save()


class batchActualProduce(models.Model):
    harvest_date = models.DateField()
    batch_produce = models.PositiveIntegerField(null=True, blank=True)
    grade = models.CharField(max_length=10, null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    batch_id = models.ForeignKey(Batch, on_delete=models.CASCADE, related_name="batch_produce", db_column='batch_id')


class Microbes(models.Model):
    microbe_id = models.AutoField(primary_key=True)
    product_code = models.CharField(max_length=50, unique=True)
    beneficial_organism = models.TextField("beneficial_organism", null=True, blank=True)
    product_nomenclature = models.TextField("product_nomenclature", null=True, blank=True)
    utilization = models.TextField("uti", null=True, blank=True)
    yield_increase = models.CharField(max_length=50)
    savings = models.CharField(max_length=50)
    fk_crop_id = models.IntegerField()
    fk_region_id = models.IntegerField()
    recommended_utilization = models.CharField(max_length=50, null=True, blank=True)
    status = models.IntegerField(null=True, blank=True, default=True)
    remedy = models.CharField(max_length=200, null=True, blank=True)
    history = HistoricalRecords()

    class Meta:
        db_table = "microbes"

    @property
    def region_name(self):
        """function to return region_name based on lgd_state_id"""
        if self.fk_region_id:
            region_name = get_region_name(self.fk_region_id)
            if region_name:
                return region_name[0]
        return None

    @property
    def commodity_name(self):
        """function to return commodity_name based on commodity_id"""
        if self.fk_crop_id:
            commodity_name = get_commodity_name(self.fk_crop_id)
            if commodity_name:
                return commodity_name[0]
        return None

    @property
    def remedy_name(self):
        """function to return commodity_name based on commodity_id"""
        remedy_name = ""
        if self.remedy:
            remedy_id_list = str(self.remedy).split(",")
            remedy_name = ",".join(x.name for x in OrganismMapping.objects.filter(id__in=remedy_id_list))
        return remedy_name


class MicrobesMapping(models.Model):
    id = models.AutoField(primary_key=True)
    microbe_id = models.ForeignKey(Microbes, on_delete=models.CASCADE, related_name="microbes_mapping",
                                   db_column='microbe_id')
    zone_com_microbe_id = models.CharField(max_length=200, null=True, blank=True)
    remedy = models.TextField(null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(null=True, blank=True)
    history = HistoricalRecords()


class OrganismMapping(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.TextField()
    status = models.IntegerField(null=True, blank=True)
    history = HistoricalRecords()


class CropAttributes(models.Model):
    commodity_id = models.PositiveIntegerField()
    state_id = models.PositiveIntegerField()
    variety_id = models.PositiveIntegerField(null=True, blank=True)
    season_id = models.PositiveIntegerField(null=True, blank=True)
    attribute_value = models.FloatField()
    attribute_name = models.CharField(max_length=255, null=True, blank=True)
    attribute_unit = models.CharField(max_length=50, null=True, blank=True)
    status = models.BooleanField(default=True, null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)

    @property
    def commodity_name(self):
        """
        function to return commodity_name based on commodity_id
        """
        if self.commodity_id:
            commodity_name = get_commodity_name(self.commodity_id)
            if commodity_name:
                return commodity_name[0]
        return None

    @property
    def state_name(self):
        """
        function to return region_name based on lgd_state_id
        """
        if self.state_id:
            state_name = get_region_name(self.state_id)
            if state_name:
                return state_name[0]
        return None

    @property
    def variety_name(self):
        """
        function to return variety_name based on variety_id
        """
        if self.variety_id:
            variety_name = get_variety_name(self.variety_id)
            if variety_name:
                return variety_name[0]
        return None


class CropAttributesMaster(models.Model):
    name = models.CharField(max_length=255, null=True, blank=True)
    unit = models.CharField(max_length=50, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)


@receiver([post_save, post_delete], sender=BatchYield)
def expected_delivery_date_update(sender, instance, **kwargs):
    try:
        sys.setrecursionlimit(120)
        instance.batch_id.update_expected_delivery_date()
        instance.batch_id.update_batch_status()
        # instance.batch_id.update_expected_produce()
        instance.batch_id.update_actual_produce()
        instance.batch_id.update_sop_adherence()
        instance.batch_id.update_actual_yield_per_acre()
        instance.update_expected_grade_produce()
    except:
        pass


@receiver([post_save, post_delete], sender=Batch)
def update_batch_count(sender, instance, **kwargs):
    instance.farm_id.update_batch_count()


@receiver(post_save, sender=Batch)
def update_farm_health(sender, instance, **kwargs):
    instance.farm_id.update_farm_health()

我有一个覆盖率报告,可以帮助找到我的代码的哪一部分需要测试

现在我一直在测试,不知道如何进行测试

我分享的是覆盖率报告截图,红色标志为待测代码

Screenshot of code that requires testing click on it

到目前为止我已经做了一些测试这里是test_farm.py

的代码
from datetime import datetime

from django import apps
from django.test import TestCase
from django.db.utils import IntegrityError

from farm_management.models import Farm, Device, BatchYield, Batch



class TestFarm(TestCase):

    def setUp(self):

        self.farm1 = Farm.objects.create(
            farmer_id="1",
            farmer_name="Vijay Kumar",
            irrigation_type="drip",
            farm_type="soil",
            franchise_type="protected",
            total_acerage="20",
            farm_status="pipeline",
            lgd_state_id="9",
            farm_health="100",
            updated_by_id="1",
            created_by_id="1",
            boundary_coord="[[28.61942190728406,77.42481022275172],[28.619423700462267,77.42536250193155],[28.61898976028526,77.42544314893678],[28.61895838039465,77.42481941041035],[28.61942190728406,77.42481022275172]]",
            farm_name="Vijay Kumar's farm - 20 acres",
            region_name="UTTAR PRADESH",
            batch_count="1",
            pending_tasks="0"
        )

    def test_farm(self):
        self.assertEqual(self.farm1.farmer_id, "1")
        self.assertEqual(self.farm1.farmer_name, "Vijay Kumar")
        self.assertEqual(self.farm1.irrigation_type, "drip")
        self.assertEqual(self.farm1.farm_type, "soil")
        self.assertEqual(self.farm1.franchise_type, "protected")
        self.assertEqual(self.farm1.total_acerage, "20")
        self.assertEqual(self.farm1.farm_status, "pipeline")
        self.assertEqual(self.farm1.lgd_state_id, "9")
        self.assertEqual(self.farm1.farm_health, "100")
        self.assertEqual(self.farm1.updated_by_id, "1")
        self.assertEqual(self.farm1.created_by_id, "1")
        self.assertEqual(self.farm1.boundary_coord, "[[28.61942190728406,77.42481022275172],[28.619423700462267,77.42536250193155],[28.61898976028526,77.42544314893678],[28.61895838039465,77.42481941041035],[28.61942190728406,77.42481022275172]]")
        self.assertEqual(self.farm1.farm_name, "Vijay Kumar's farm - 20 acres")
        self.assertEqual(self.farm1.region_name, "UTTAR PRADESH")
        self.assertEqual(self.farm1.batch_count, "1")
        self.assertEqual(self.farm1.pending_tasks, "0")

    def test_model(self):
        d = self.farm1
        self.assertTrue(isinstance(d, Farm))
        self.assertEqual(str(d), "Vijay Kumar's farm - 20 acres")

    def test_return(self):
        farm11 = Farm.objects.create(farm_name="Vijay Kumar's farm",farmer_id="1")
        farm11.save()

        self.assertEqual(str(farm11), "Vijay Kumar's farm")

如果有人能帮忙解决就好了

提前致谢

我认为您有 2 个不错的选择来继续进行此处的测试,您可以使用集成测试并在这些方法用于程序的其他部分时测试这些方法的结果,或者您可以对单独的方法。根据您提供的内容,示例可能是:

def test_batch_count(self):
    for i in range(5):
        Batch.objects.create(farm_id=self.farm1, ...)

    self.farm1.update_batch_count()
    assert self.farm1.batch_count == 5

此测试可以添加到您当前的 TestFarm 并将测试您的 update_batch_count 方法。