单元测试Django模型保存功能

时间:2018-02-26 13:02:05

标签: django django-models python-unittest django-testing django-unittest

我正在创建测试以检查自定义校准模型保存功能是否更新资产记录(外键),如果它是资产的最新校准记录。保存功能与live dev& amp;生产服务器,甚至在django shell中,但在测试期间似乎失败了......

models.py

uglifycss = require('gulp-uglifycss');

gulp.task('styles', function(){
    return gulp.src('css/style.css')
        .pipe(postcss([cssImport, mixins, cssvars, nested, hexrgba, autoprefixer]))
        .on('error', function(errorInfo){
            console.log(errorInfo.toString());
            this.emit('end');
        })
        .pipe(uglifycss({
            "maxLineLen": 80,
            "uglyComments": true
        }))
        //stylesheet destination folder
        .pipe(gulp.dest('dist/styles'));
});

tests_models.py示例失败测试

class Asset(models.Model):
    ...
    requires_calibration = models.BooleanField()
    passed_calibration = models.BooleanField(default=False)
    calibration_date_prev = models.DateField(null=True, blank=True)
    calibration_date_next = models.DateField(null=True, blank=True)


class CalibrationRecord(models.Model):
    calibration_record_id = models.AutoField(primary_key=True)
    asset = models.ForeignKey(
                              "myapp.Asset",
                              on_delete=models.CASCADE,
                              limit_choices_to={"requires_calibration": True}
                              )
    calibration_date = models.DateField(default=timezone.now)
    calibration_date_next = models.DateField(null=True, blank=True)
    calibration_outcome = models.CharField(max_length=10, default="Pass")

    def save(self, *args, **kwargs):

        super(CalibrationRecord, self).save(*args, **kwargs)

        # Check if this is the latest calibration record for any asset, if so update asset.calibration_dates and status
        latest_asset_calibration = CalibrationRecord.objects.filter(asset=self.asset.pk).order_by(
            "-calibration_date", "-calibration_record_id")[0]

        if self.pk == latest_asset_calibration.pk:

            Asset.objects.filter(pk=self.asset.pk).update(calibration_date_prev=self.calibration_date)

            if self.calibration_date_next:
                Asset.objects.filter(pk=self.asset.pk).update(calibration_date_next=self.calibration_date_next)
            else:
                Asset.objects.filter(pk=self.asset.pk).update(calibration_date_next=None)

            if self.calibration_outcome == "Pass":
                Asset.objects.filter(pk=self.asset.pk).update(passed_calibration=True)
            else:
                Asset.objects.filter(pk=self.asset.pk).update(passed_calibration=False)

错误日志

class CalibrationRecordTests(TestCase):
    def test_calibration_record_updates_asset_cal_date_prev(self):
        """
        All calibration records should update related Asset record's "calibration_date_prev" to calibration_date
        """
        asset1 = Asset.objects.create(asset_description="Test Asset 2", requires_calibration=True)
        self.assertIsNone(asset1.calibration_date_prev)
        cal = CalibrationRecord.objects.create(asset=asset1, calibration_description="Test Calibration 2", calibration_date=timezone.now())
        self.assertEqual(cal.calibration_date, asset1.calibration_date_prev)

我所有与此自定义校准记录保存功能相关的测试似乎都失败了,因为相关的资产记录应该没有更新。

为什么这会在开发和生产过程中发挥作用而不是在测试过程中有任何想法?

即使.create()方法应该自动执行.save()之后,我甚至在创建校准记录后尝试手动.save(),但它似乎仍然失败。

1 个答案:

答案 0 :(得分:0)

解决!

自定义保存功能正确更新数据库,但不是正在测试的模型实例!需要刷新模型实例以通过[model].objects.get()

之类的方式再次调用来获取任何更新

e.g:

    asset = Asset.objects.create(asset_description="Test Asset 2", requires_calibration=True)
    self.assertIsNone(asset.calibration_date_prev)
    CalibrationRecord.objects.create(asset=asset, calibration_description="Test Calibration 2",
                                     calibration_date=timezone.now())
    cal = CalibrationRecord.objects.get(calibration_description="Test Calibration 2")
    asset = Asset.objects.get(asset_description="Test Asset 2")
    self.assertEqual(cal.calibration_date, asset.calibration_date_prev)