插入数据库工作正常。在数据库连接上运行测试被拒绝

时间:2019-04-02 20:23:41

标签: node.js postgresql docker-compose

使用mocha运行node.js,在docker上使用postgres数据库运行chai。 我使用yaml文件创建所有容器。我有一个用于处理其他事情的容器,但在这种情况下,基本上是一个用于测试的容器和一个用于数据库的容器。我有一个从我的literate-app容器调用的有效插​​入函数。但是,在我尝试过的所有方法中,我无法从用于测试的新容器中连接到该容器,而我正在尝试测试postgres中是否存在表

我尝试编写自己的代码。我尝试使用pg和pg-pool几种方式编写代码。编写并可以插入的当前代码无效。我试图创建一个名为test_user的新用户,可能是这种情况,但无济于事。

遇到我的错误

Attaching to literate-webapp_test_1
test_1      |
test_1      | > @ mocha /literate-app
test_1      | > mocha --reporter spec ./test/test/postgressFactoryTest.js
test_1      |
test_1      |
test_1      |
test_1      |   PostGres
test_1      |     tableExists
test_1      |       1) should be 0 before connecting
test_1      | inside connect
test_1      |       2) should be not 0 after connecting
test_1      |     setName
test_1      |       ✓ should be "None Set" before calling"
test_1      |       ✓ should be "username" after calling
test_1      |     getCookie
test_1      |       3) should return a valid cookie string
test_1      |
test_1      |
test_1      |   2 passing (318ms)
test_1      |   3 failing
test_1      |
test_1      |   1) PostGres
test_1      |        tableExists
test_1      |          should be 0 before connecting:
test_1      |      AssertionError: expected 0 to equal undefined
test_1      |       at Context.<anonymous> (test/test/postgressFactoryTest.js:18:10)
test_1      |       at processImmediate (internal/timers.js:443:21)
test_1      |
test_1      |   2) PostGres
test_1      |        tableExists
test_1      |          should be not 0 after connecting:
test_1      |      TypeError: Cannot read property 'then' of undefined
test_1      |       at Context.<anonymous> (test/test/postgressFactoryTest.js:38:7)
test_1      |       at processImmediate (internal/timers.js:443:21)
test_1      |
test_1      |   3) PostGres
test_1      |        getCookie
test_1      |          should return a valid cookie string:
test_1      |      ReferenceError: document is not defined
test_1      |       at PostGres.getCookie (literate-app/js/postgres.factory.js:273:43)
test_1      |       at Context.<anonymous> (test/test/postgressFactoryTest.js:90:25)
test_1      |       at processImmediate (internal/timers.js:443:21)
test_1      |
test_1      |
test_1      |
test_1      | (node:30) UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND postgres postgres:5432
test_1      |     at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:58:26)
test_1      | (node:30) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
test_1      | (node:30) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will
terminate the Node.js process with a non-zero exit code.
test_1      | npm ERR! code ELIFECYCLE
test_1      | npm ERR! errno 3
test_1      | npm ERR! @ mocha: `mocha --reporter spec ./test/test/postgressFactoryTest.js`
test_1      | npm ERR! Exit status 3
test_1      | npm ERR!
test_1      | npm ERR! Failed at the @ mocha script.
test_1      | npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
test_1      |
test_1      | npm ERR! A complete log of this run can be found in:
test_1      | npm ERR!     /root/.npm/_logs/2019-04-02T20_03_20_740Z-debug.log

在这里使用码头工人Yaml

version: '3'
services:
  webapp:
    build: ./literate-app
    command: ["./wait-for-it.sh","postgres:5432","--","npm","start"]
    depends_on:
      - postgres
    links:
      - postgres
    command: nodemon -e vue,js,css start.js
    environment:
      - DB_HOST=postgres
    ports:
     - "3000:3000"
    networks:
      - literate-net


  server:
    build: ./readability-server
    command: nodemon -L --inspect=0.0.0.0:5555 server.js
    networks:
      - literate-net


  redis_db:
    image: redis:alpine
    networks:
      - literate-net


  postgres:
    restart: 'always'
    #image: 'bitnami/postgresql:latest'
    volumes:
     - /bitnami
     # - ./schema.sql:/docker-entrypoint-initdb.d/schema.sql
    ports:
      - "5432:5432"
    networks:
      - literate-net
    environment:
      - "FILLA_DB_USER=my_user"
      - "FILLA_DB_PASSWORD=password123"
      - "FILLA_DB_DATABASE=my_database"
      - "POSTGRES_PASSWORD=password123"
    build: './database-creation'


  test: 
    image: node:latest
    build: ./test
    working_dir: /literate-app
    volumes:
      - .:/literate-app
    command:
      npm run mocha
    links:
      - postgres
    depends_on:
      - postgres
    environment:
      - DB_HOST=postgres


networks:
  literate-net:
    driver: bridge

在这里测试文件

describe('tableExists', function () {
    it('should be 0 before connecting', function () {

        var PostGres = new PostGresClass();
        var config = [];
        var value = PostGres.tableExists(config, 'alpharead');
        assert.equal(0, value);
    });

    it('should be not 0 after connecting', function () {

        var config = {
            user: 'my_user',
            host: 'postgres',
            database: 'my_database',
            password: 'password123',
            port: 5432,
            max: 20,
            idleTimeoutMillis: 30000,
            connectionTimeoutMillis: 2000,
        };
        var pool = new Pool(config);

        pool.connect()
                console.log("inside connect")

                .then(client => {
                    console.log("querying client")
                    console.log("query return: " + client.query(`SELECT count(*) as cnt FROM pg_tables t WHERE tableowner=current_user and table_name= ${table_name} AND schema_name=my_database`))
                    return client.query(`SELECT count(*) as cnt FROM pg_tables t WHERE tableowner=current_user and table_name= ${table_name} AND schema_name=my_database`)
                .then(res => {
                    console.log("returning res")
                    console.log(res)
                    client.release()
                    return release()
                })
                .catch(err => {
                    console.log("returning error")
                    console.log(err.stack)
                    return 0
                })
             })
        /*var PostGres = new PostGresClass();
        var config = {
            user: 'my_user',
            host: 'postgresql',
            database: 'my_database',
            password: 'password123',
            port: 5432,
            max: 20,
            idleTimeoutMillis: 30000,
            connectionTimeoutMillis: 2000,
        };
        //var pool = new Pool(config);
        var value = PostGres.tableExists(config, `alpharead`);*/
        assert.equal(1, value);
    });

这里是实际连接和插入数据的代码

        logEvent(eventType, eventData, eSid, ePid){
            dt = new Date();
            var utcDate = dt.toUTCString();
            sid = eSid;
            pid = ePid;

            if(eventType == "Set Name/New Session"){
                this.setName(eventData)
            }
            pool.connect()
            .then(client => {
                return client.query('INSERT INTO public.alphatwo(sessionid, queryid, timestamp, eventtype, eventdata) VALUES ($1, $2, $3, $4, $5)', [sid, pid, utcDate, eventType, eventData])

                .then(res => {
                    console.log("successfully insterted data into alphatwo");
                        client.release();
                })
                .catch(e => {
                    console.log("didnt find database alphatwo or doesnt exist");
                    console.log(e);
                    client.release();
                })
            })
            .catch(e => {
                console.log("CAUGHT ERROR in connecting to database")
                console.log(e)
                client.release();
            })
        }

它具有相同的设置,只是不想复制很多评论。

所以问题是为什么我不能通过此容器连接到数据库。还有一些解决方法。我已经看过一些docker文件,但这确实存在并且依赖yaml。

1 个答案:

答案 0 :(得分:0)

所以我找到了答案。

基本上在其中注明

测试:     图片:node:latest     构建:./ test     working_dir:/ literate-app     数量:       -。:/ literate-app     命令:       npm运行摩卡     链接:       -postgres     取决于:       -postgres     环境:       -DB_HOST = postgres

问题是这个

links:
     -postgres

Docker现在改为使用网络。因此,将其替换为

networks:
      - literate-net

解决了问题