github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/acceptance/testdata/node/rejects-with-pg-error.js (about)

     1  // Copyright 2019 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  const assert     = require('assert');
    12  const errorCodes = require('pg-error-codes');
    13  
    14  function errCode(code) {
    15    return errorCodes[code] || 'unknown error code';
    16  }
    17  
    18  // rejectsWithPGError takes a promise produced from a pg query and rejects if it
    19  // fails with a superstring of an asserted error message and a specified
    20  // Postgres error code.
    21  function rejectsWithPGError(promise, { msg, code }) {
    22    return promise.then(
    23      () => {
    24        assert.fail(`expected failure with message "${msg}" and Postgres error code ${code}, but no failure occurred`);
    25      },
    26      err => {
    27        assert(err.toString().indexOf(msg) > -1, `expected "${err.toString()}" to contain "${msg}"`);
    28        assert.equal(code, err.code, `expected error code to be ${code} (${errCode(code)}), was ${err.code} (${errCode(err.code)})`);
    29      }
    30    );
    31  }
    32  
    33  module.exports = rejectsWithPGError;