GVKun编程网logo

Swift Assert 断言(swift断言操作的作用)

2

在这里,我们将给大家分享关于SwiftAssert断言的知识,让您更了解swift断言操作的作用的本质,同时也会涉及到如何更有效地assertFalse与try结合在开发中的使用、assert()函数

在这里,我们将给大家分享关于Swift Assert 断言的知识,让您更了解swift断言操作的作用的本质,同时也会涉及到如何更有效地assert False 与 try 结合 在开发中的使用、assert()函数演示断言、Assert.AreEqual 和 Assert.IsTrue 给出两种不同的结果、assert.equal(3, result.result.n);类型错误:无法读取未定义的属性“n”的内容。

本文目录一览:

Swift Assert 断言(swift断言操作的作用)

Swift Assert 断言(swift断言操作的作用)

前言

  • 对每次运行都会出现的错误通常不会过于苦恼,可以使用断点调试或者 try catch 之类的方式判断并修复它。但是一些偶发(甚至是无数次运行才会出现一次)的错误单靠断点之类的方式是很难排除掉的,为此,引入一个不是很常用的调试工具函数 assert

  • 在实际编码中,为了保证程序正常运行,只有在某些必要条件被满足的情况下才执行特定代码段,这种编程思想叫做 “防错性编程”。

1、断言

  • 在 Swift 语言中可以调用全局的 assert 函数来增加一个断言,这里的全局意思是你可以将断言放在你程序的任何一个地方,程序在执行到 assert 时会判断其中的逻辑条件表达式参数是否为 true

    • 如果条件判断为 true,代码运行会继续进行。
    • 如果条件判断为 false,程序将终止。
    • assert 是单纯地触发断言即停止程序,不会让你有机会将可能出错的设计走过它这一关。
  • 通常在为程序加入并触发断言后,Xcode 会精确定位到异常代码段,并反馈异常信息等修改 bug 必须的调试信息。

1.1 Assert 的定义

  • 标准的断言格式

    assert(condition: Bool, message: String) 
    
    • condition 判断条件,message 自定义调试信息,断言中的调试信息参数是可选的。
  • 定义

    public func assert(_ condition: @autoclosure () -> Bool,
                         _ message: @autoclosure () -> String = default,
                              file: StaticString = #file,
                              line: UInt = #line)
    
    public func assertionFailure(_ message: @autoclosure () -> String = default,
                                      file: StaticString = #file,
                                      line: UInt = #line)
    
  • 系统在断言的源代码中加入了类似 #if NDEBUG 这样的编译字,使其只能用于 debug 期,当你在发布 release 版本或者更新版的时候,编译器会使用一个编译字段将断言无效化,所以当你的产品在提交给用户之后还需要继续收集错误信息时,需使用其他方式。

  • 断言函数中用到了 @autoclosure 属性,使用这种属性的参数意味着我们可以在这个参数的位置传入一个表达式,这个表达式会被自动封包成一个闭包,这也正是其字面的意思 “自动闭包”。在 assert 函数中它起到的作用也是非常明显的,如果在这里我们使用的是普通的布尔型参数,那么在执行到 assert 函数时,就会先运算条件表达式的值,而使用 @autoclosure 属性后,程序会先在 assert 函数内判断 debug 期的编译字是否存在,如果存在才会运算条件表达式的值,当然,这时条件表达式已经被自动封装成了一个闭包。

1.2 Assert 的使用

  • 断言使用的几种场景

    • 验证参数的合法性。
    • 将要使用一个对象,但是不确定其是否已经正确创建。
    • 数组或者其他集合类、字典等复杂数据类型下标没有处于安全范围导致可能会越界。
  • assert 函数的条件表达式参数最好一次只判断一个条件,因为如果判断多个条件,当断言被触发时,往往会无法直观的判断到底是哪一个条件不被满足。

  • 使用

    // 满足条件
    
    var usedate = -1
    assert(usedate <= 0, "超出试用期,不能启动程序!")           // 继续执
    print("继续执行")
    
    // 不满足条件
    
    // 当 usedate 大于 0 时,程序中断,进入断言函数打印调试信息
    usedate = 2
    assert(usedate <= 0, "超出试用期,不能启动程序!")           // Thread 1: Assertion failed: 超出试用期,不能启动程序!
    

assert False 与 try 结合 在开发中的使用

assert False 与 try 结合 在开发中的使用

 

让错误抛出

发现其中的问题

 

 

# coding=utf-8

from rest_framework.views import exception_handler
from rest_framework.exceptions import ErrorDetail
from share.dj_customer.rest_api_exception import CustomerError


def custom_exception_handler(exc, context):
    # Call REST framework''s default exception handler first,
    # to get the standard error response.
    ....
        if isinstance(old_data, dict):
            if old_data.get(''detail'') is not None:
                if isinstance(old_data[''detail''], tuple):
                    new_data[''code''], new_data[''message''] = old_data[''detail''][0:2]
                elif isinstance(old_data[''detail''], str):
                    new_data[''message''] = old_data[''detail'']
            else:
                try:
                    # e.g. user_name [ErrorDetail(string=''Ensure this field has no more than 16 characters.'', code=''max_length'')]
                    msg = ''''
                    for serializer_field, v in old_data.items():
                        if isinstance(serializer_field, str) and isinstance(v, list):
                            if isinstance(v[0], ErrorDetail):
                                msg += serializer_field + '':'' + v[0].__str__()
                            else:
                                assert False
                        else:
                            assert False
                    # e.g.
                    # {
                    #     "success": false,
                    #     "code": 1001,
                    #     "message": "参数错误 : user_name:Ensure this field has no more than 16 characters.age:A valid integer is required."
                    # }
                    new_data[''code''], new_data[''message''] = CustomerError.PARAM_ERROR
                    new_data[''message''] += '' : '' + msg
                except:
                    assert False

  

 

assert()函数演示断言

assert()函数演示断言

#include <stdio.h>
#include <assert.h>

int main(void)
{
  int y = 5;
  for(int x = 0 ; x < 20 ; ++x)
  {
    printf(x = %d   y = %d\n, x, y);
    assert(x < y);
  }
  return 0;
}

Assert.AreEqual 和 Assert.IsTrue 给出两种不同的结果

Assert.AreEqual 和 Assert.IsTrue 给出两种不同的结果

如何解决Assert.AreEqual 和 Assert.IsTrue 给出两种不同的结果

我有一个返回一个字节的函数,GetByte()。然后我对此进行了单元测试(在 Unity 中使用 NUnit)

public void GetBytetest()
{
    var expected = 0b0;

    Assert.AreEqual(expected,GetByte()); // fails
    Assert.IsTrue(expected == GetByte()); // passes
}

对此非常困惑,尤其是因为输出说:

Expected: 0
But was:  0

我也试过 Assert.AreSame() 但没有成功。

有什么想法吗?

解决方法

虽然 expected == GetNoteBinary() 为真,但由于 expected 是用 var 声明的,因此它需要转换为 byte 才能与另一个字节进行比较; Assert.AreEqual 试图将其与 int 进行比较。

Assert.AreEqual((NoteBinary)expected,GetNoteBinary()); // passes

这里的教训是,Assert.AreEqual 可以比较不同类型,您必须非常小心要比较的类型;永远不会离开它不明确的。

assert.equal(3, result.result.n);类型错误:无法读取未定义的属性“n”

assert.equal(3, result.result.n);类型错误:无法读取未定义的属性“n”

如何解决assert.equal(3, result.result.n);类型错误:无法读取未定义的属性“n”?

我收到一个错误,说第 47 行没有定义 n,我已经使用了所有方法来解决它,但我无法解决它。它正在显示并且错误是 n 是 undefiend 我想知道为什么它给我一个错误,我正在做的真正错误是什么

const MongoClient = require(''mongodb'').MongoClient;
const assert = require(''assert'');

// Connection URL
const url = ''mongodb://localhost:27017'';

// Database Name
const dbname = ''fruitDB'';

// Create a new MongoClient
const client = new MongoClient(url);

// Use connect method to connect to the Server
client.connect(function (err) {
    assert.equal(null,err);
    console.log("Connected successfully to server");

    const db = client.db(dbname);

    insertDocuments(db,function() {
        client.close();
      });
});

const insertDocuments = function(db,callback) {
    // Get the documents collection
    const collection = db.collection(''fruits'');
    // Insert some documents
    collection.insertMany([
        {
            name: "apple",score:5,review: "very very nice"
        },{ 
            name: "orange",score: 7,review: "very very sour"
        },{ 
            name: "Banana",score: 5,review: "best fruit"
        }
    ],function(err,result) {
      assert.equal(err,null);
      assert.equal(3,result.result.n);
      assert.equal(3,result.ops.length);
      console.log("Inserted 3 documents into the collection");
      callback(result);
    });
  }

请解决

解决方法

问题是您的“result.result”未定义 - 您的“result”没有定义的“.result”属性。尝试记录或调试根结果对象,看看它是否有任何东西。

我可能误读了,但似乎 mongoDB 的 InsertMany 并没有为您返回一个对象,它只能在失败时抛出期望。 https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/#behaviors

只有插入单返回一个WriteResult对象: https://docs.mongodb.com/manual/reference/method/db.collection.insert/#writeresult

关于Swift Assert 断言swift断言操作的作用的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于assert False 与 try 结合 在开发中的使用、assert()函数演示断言、Assert.AreEqual 和 Assert.IsTrue 给出两种不同的结果、assert.equal(3, result.result.n);类型错误:无法读取未定义的属性“n”的相关知识,请在本站寻找。

本文标签: