<commit_before>const assert = require('assert');

const withV4 = require('../support/withV4');
const BucketUtility = require('../../lib/utility/bucket-util');

const bucketName = 'buckettestgetobject';
const objectName = 'someObject';
// Specify sample headers to check for in GET response
const cacheControl = 'max-age=86400';
const contentDisposition = 'attachment; filename="fname.ext";';
const contentEncoding = 'aws-chunked,gzip';
// AWS Node SDK requires Date object, ISO-8601 string, or
// a UNIX timestamp for Expires header
const expires = new Date();
const etagTrim = 'd41d8cd98f00b204e9800998ecf8427e';
const etag = `"${etagTrim}"`;

function checkNoError(err) {
    assert.equal(err, null,
        `Expected success, got error ${JSON.stringify(err)}`);
}

function checkError(err, code) {
    assert.notEqual(err, null, 'Expected failure but got success');
    assert.strictEqual(err.code, code);
}

function dateFromNow(diff) {
    const d = new Date();
    d.setHours(d.getHours() + diff);
    return d.toISOString();
}

function dateConvert(d) {
    return (new Date(d)).toISOString();
}

describe('GET object', () => {
    withV4(sigCfg => {
        let bucketUtil;
        let s3;

        function requestGet(fields, cb) {
            s3.getObject(Object.assign({
                Bucket: bucketName,
                Key: objectName,
            }, fields), cb);
        }

        before(done => {
            bucketUtil = new BucketUtility('default', sigCfg);
            s3 = bucketUtil.s3;
            // Create a bucket to put object to get later
            s3.createBucket({ Bucket: bucketName }, done);
        });

        after(done => {
            s3.deleteObject({ Bucket: bucketName, Key: objectName }, err => {
                if (err) {
                    return done(err);
                }
                return s3.deleteBucket({ Bucket: bucketName }, done);
            });
        });

        it('should return an error to get request without a valid bucket name',
            done => {
                s3.getObject({ Bucket: '', Key: 'somekey' }, err => {
                    assert.notEqual(err, null,
                        'Expected failure but got success');
                    assert.strictEqual(err.code, 'MethodNotAllowed');
                    return done();
                });
            });

        it('should return NoSuchKey error when no such object',
            done => {
                s3.getObject({ Bucket: bucketName, Key: 'nope' }, err => {
                    assert.notEqual(err, null,
                        'Expected failure but got success');
                    assert.strictEqual(err.code, 'NoSuchKey');
                    return done();
                });
            });

        describe('Additional headers: [Cache-Control, Content-Disposition, ' +
            'Content-Encoding, Expires]', () => {
            before(done => {
                const params = {
                    Bucket: bucketName,
                    Key: objectName,
                    CacheControl: cacheControl,
                    ContentDisposition: contentDisposition,
                    ContentEncoding: contentEncoding,
                    Expires: expires,
                };
                s3.putObject(params, err => done(err));
            });
            it('should return additional headers if specified in objectPUT ' +
                'request', done => {
                s3.getObject({ Bucket: bucketName, Key: objectName },
                  (err, res) => {
                      if (err) {
                          return done(err);
                      }
                      assert.strictEqual(res.CacheControl,
                        cacheControl);
                      assert.strictEqual(res.ContentDisposition,
                        contentDisposition);
                      // Should remove V4 streaming value 'aws-chunked'
                      // to be compatible with AWS behavior
                      assert.strictEqual(res.ContentEncoding,
                        'gzip');
                      assert.strictEqual(res.Expires,
                          expires.toGMTString());
                      return done();
                  });
            });
        });

        describe('x-amz-website-redirect-location header', () => {
            before(done => {
                const params = {
                    Bucket: bucketName,
                    Key: objectName,
                    WebsiteRedirectLocation: '/',
                };
                s3.putObject(params, err => done(err));
            });
            it('should return website redirect header if specified in ' +
                'objectPUT request', done => {
                s3.getObject({ Bucket: bucketName, Key: objectName },
                  (err, res) => {
                      if (err) {
                          return done(err);
                      }
                      assert.strictEqual(res.WebsiteRedirectLocation, '/');
                      return done();
                  });
            });
        });

        describe('x-amz-tagging-count', () => {
            const params = {
                Bucket: bucketName,
                Key: objectName,
            };
            const paramsTagging = {
                Bucket: bucketName,
                Key: objectName,
                Tagging: {
                    TagSet: [
                        {
                            Key: 'key1',
                            Value: 'value',
                        },
                    ],
                },
            };
            beforeEach(done => {
                s3.putObject(params, done);
            });

            it('should not return "x-amz-tagging-count" if no tag ' +
            'associated with the object',
            done => {
                s3.getObject(params, (err, data) => {
                    if (err) {
                        return done(err);
                    }
                    assert.strictEqual(data.TagCount, undefined);
                    return done();
                });
            });

            describe('tag associated with the object', () => {
                beforeEach(done => {
                    s3.putObjectTagging(paramsTagging, done);
                });
                it('should return "x-amz-tagging-count" header that provides ' +
                'the count of number of tags associated with the object',
                done => {
                    s3.getObject(params, (err, data) => {
                        if (err) {
                            return done(err);
                        }
                        assert.equal(data.TagCount, 1);
                        return done();
                    });
                });
            });
        });

        describe('conditional headers', () => {
            const params = { Bucket: bucketName, Key: objectName };
            beforeEach(done => {
                s3.putObject(params, done);
            });
            it('If-Match: returns no error when ETag match, with double ' +
                'quotes around ETag',
                done => {
                    requestGet({ IfMatch: etag }, err => {
                        checkNoError(err);
                        done();
                    });
                });

            it('If-Match: returns no error when one of ETags match, with ' +
                'double quotes around ETag',
                done => {
                    requestGet({ IfMatch:
                        `non-matching,${etag}` }, err => {
                        checkNoError(err);
                        done();
                    });
                });

            it('If-Match: returns no error when ETag match, without double ' +
                'quotes around ETag',
                done => {
                    requestGet({ IfMatch: etagTrim }, err => {
                        checkNoError(err);
                        done();
                    });
                });

            it('If-Match: returns no error when one of ETags match, without ' +
                'double quotes around ETag',
                done => {
                    requestGet({ IfMatch:
                        `non-matching,${etagTrim}` }, err => {
                        checkNoError(err);
                        done();
                    });
                });

            it('If-Match: returns no error when ETag match with *', done => {
                requestGet({ IfMatch: '*' }, err => {
                    checkNoError(err);
                    done();
                });
            });

            it('If-Match: returns PreconditionFailed when ETag does not match',
                done => {
                    requestGet({
                        IfMatch: 'non-matching ETag',
                    }, err => {
                        checkError(err, 'PreconditionFailed');
                        done();
                    });
                });

            it('If-None-Match: returns no error when ETag does not match',
            done => {
                requestGet({ IfNoneMatch: 'non-matching' }, err => {
                    checkNoError(err);
                    done();
                });
            });

            it('If-None-Match: returns no error when all ETags do not match',
                done => {
                    requestGet({
                        IfNoneMatch: 'non-matching,' +
                        'non-matching-either',
                    }, err => {
                        checkNoError(err);
                        done();
                    });
                });

            it('If-None-Match: returns NotModified when ETag match, with ' +
                'double quotes around ETag',
                done => {
                    requestGet({ IfNoneMatch: etag }, err => {
                        checkError(err, 'NotModified');
                        done();
                    });
                });

            it('If-None-Match: returns NotModified when one of ETags match, ' +
                'with double quotes around ETag',
                done => {
                    requestGet({
                        IfNoneMatch: `non-matching,${etag}`,
                    }, err => {
                        checkError(err, 'NotModified');
                        done();
                    });
                });

            it('If-None-Match: returns NotModified when value is "*"',
                done => {
                    requestGet({
                        IfNoneMatch: '*',
                    }, err => {
                        checkError(err, 'NotModified');
                        done();
                    });
                });

            it('If-None-Match: returns NotModified when ETag match, without ' +
                'double quotes around ETag',
                done => {
                    requestGet({ IfNoneMatch: etagTrim }, err => {
                        checkError(err, 'NotModified');
                        done();
                    });
                });

            it('If-None-Match: returns NotModified when one of ETags match, ' +
                'without double quotes around ETag',
                done => {
                    requestGet({
                        IfNoneMatch: `non-matching,${etagTrim}`,
                    }, err => {
                        checkError(err, 'NotModified');
                        done();
                    });
                });

            it('If-Modified-Since: returns no error if Last modified date is ' +
                'greater',
                done => {
                    requestGet({ IfModifiedSince: dateFromNow(-1) },
                        err => {
                            checkNoError(err);
                            done();
                        });
                });

            // Skipping this test, because real AWS does not provide error as
            // expected
            it.skip('If-Modified-Since: returns NotModified if Last modified ' +
                'date is lesser',
                done => {
                    requestGet({ IfModifiedSince: dateFromNow(1) },
                        err => {
                            checkError(err, 'NotModified');
                            done();
                        });
                });

            it('If-Modified-Since: returns NotModified if Last modified ' +
                'date is equal',
                done => {
                    s3.headObject({ Bucket: bucketName, Key: objectName },
                    (err, data) => {
                        checkNoError(err);
                        const lastModified = dateConvert(data.LastModified);
                        requestGet({ IfModifiedSince: lastModified }, err => {
                            checkError(err, 'NotModified');
                            done();
                        });
                    });
                });

            it('If-Unmodified-Since: returns no error when lastModified date ' +
                'is greater',
                done => {
                    requestGet({ IfUnmodifiedSince: dateFromNow(1) },
                    err => {
                        checkNoError(err);
                        done();
                    });
                });

            it('If-Unmodified-Since: returns no error when lastModified ' +
                'date is equal', done => {
                s3.headObject({ Bucket: bucketName, Key: objectName },
                    (err, data) => {
                        checkNoError(err);
                        const lastModified = dateConvert(data.LastModified);
                        requestGet({ IfUnmodifiedSince: lastModified },
                            err => {
                                checkNoError(err);
                                done();
                            });
                    });
            });

            it('If-Unmodified-Since: returns PreconditionFailed when ' +
                'lastModified date is lesser',
                done => {
                    requestGet({ IfUnmodifiedSince: dateFromNow(-1) },
                    err => {
                        checkError(err, 'PreconditionFailed');
                        done();
                    });
                });

            it('If-Match & If-Unmodified-Since: returns no error when match ' +
                'Etag and lastModified is greater',
                done => {
                    requestGet({
                        IfMatch: etagTrim,
                        IfUnmodifiedSince: dateFromNow(-1),
                    }, err => {
                        checkNoError(err);
                        done();
                    });
                });

            it('If-Match match & If-Unmodified-Since match', done => {
                requestGet({
                    IfMatch: etagTrim,
                    IfUnmodifiedSince: dateFromNow(1),
                }, err => {
                    checkNoError(err);
                    done();
                });
            });

            it('If-Match not match & If-Unmodified-Since not match', done => {
                requestGet({
                    IfMatch: 'non-matching',
                    IfUnmodifiedSince: dateFromNow(-1),
                }, err => {
                    checkError(err, 'PreconditionFailed');
                    done();
                });
            });

            it('If-Match not match & If-Unmodified-Since match', done => {
                requestGet({
                    IfMatch: 'non-matching',
                    IfUnmodifiedSince: dateFromNow(1),
                }, err => {
                    checkError(err, 'PreconditionFailed');
                    done();
                });
            });

            // Skipping this test, because real AWS does not provide error as
            // expected
            it.skip('If-Match match & If-Modified-Since not match', done => {
                requestGet({
                    IfMatch: etagTrim,
                    IfModifiedSince: dateFromNow(1),
                }, err => {
                    checkNoError(err);
                    done();
                });
            });

            it('If-Match match & If-Modified-Since match', done => {
                requestGet({
                    IfMatch: etagTrim,
                    IfModifiedSince: dateFromNow(-1),
                }, err => {
                    checkNoError(err);
                    done();
                });
            });

            it('If-Match not match & If-Modified-Since not match', done => {
                requestGet({
                    IfMatch: 'non-matching',
                    IfModifiedSince: dateFromNow(1),
                }, err => {
                    checkError(err, 'PreconditionFailed');
                    done();
                });
            });

            it('If-Match not match & If-Modified-Since match', done => {
                requestGet({
                    IfMatch: 'non-matching',
                    IfModifiedSince: dateFromNow(-1),
                }, err => {
                    checkError(err, 'PreconditionFailed');
                    done();
                });
            });

            it('If-None-Match & If-Modified-Since: returns NotModified when ' +
                'Etag does not match and lastModified is greater',
                done => {
                    requestGet({
                        IfNoneMatch: etagTrim,
                        IfModifiedSince: dateFromNow(-1),
                    }, err => {
                        checkError(err, 'NotModified');
                        done();
                    });
                });

            it('If-None-Match not match & If-Modified-Since not match',
            done => {
                requestGet({
                    IfNoneMatch: etagTrim,
                    IfModifiedSince: dateFromNow(1),
                }, err => {
                    checkError(err, 'NotModified');
                    done();
                });
            });

            it('If-None-Match match & If-Modified-Since match', done => {
                requestGet({
                    IfNoneMatch: 'non-matching',
                    IfModifiedSince: dateFromNow(-1),
                }, err => {
                    checkNoError(err);
                    done();
                });
            });

            // Skipping this test, because real AWS does not provide error as
            // expected
            it.skip('If-None-Match match & If-Modified-Since not match',
            done => {
                requestGet({
                    IfNoneMatch: 'non-matching',
                    IfModifiedSince: dateFromNow(1),
                }, err => {
                    checkError(err, 'PreconditionFailed');
                    done();
                });
            });

            it('If-None-Match match & If-Unmodified-Since match', done => {
                requestGet({
                    IfNoneMatch: 'non-matching',
                    IfUnmodifiedSince: dateFromNow(1),
                }, err => {
                    checkNoError(err);
                    done();
                });
            });

            it('If-None-Match match & If-Unmodified-Since not match', done => {
                requestGet({
                    IfNoneMatch: 'non-matching',
                    IfUnmodifiedSince: dateFromNow(-1),
                }, err => {
                    checkError(err, 'PreconditionFailed');
                    done();
                });
            });

            it('If-None-Match not match & If-Unmodified-Since match', done => {
                requestGet({
                    IfNoneMatch: etagTrim,
                    IfUnmodifiedSince: dateFromNow(1),
                }, err => {
                    checkError(err, 'NotModified');
                    done();
                });
            });

            it('If-None-Match not match & If-Unmodified-Since not match',
            done => {
                requestGet({
                    IfNoneMatch: etagTrim,
                    IfUnmodifiedSince: dateFromNow(-1),
                }, err => {
                    checkError(err, 'PreconditionFailed');
                    done();
                });
            });
        });
    });
});
<commit_msg>test: add response content headers test - objectGet<commit_after>const assert = require('assert');

const withV4 = require('../support/withV4');
const BucketUtility = require('../../lib/utility/bucket-util');

const bucketName = 'buckettestgetobject';
const objectName = 'someObject';
// Specify sample headers to check for in GET response
const cacheControl = 'max-age=86400';
const contentDisposition = 'attachment; filename="fname.ext";';
const contentEncoding = 'aws-chunked,gzip';
const contentLanguage = 'en-US';
const contentType = 'xml';
// AWS Node SDK requires Date object, ISO-8601 string, or
// a UNIX timestamp for Expires header
const expires = new Date().toISOString();
const etagTrim = 'd41d8cd98f00b204e9800998ecf8427e';
const etag = `"${etagTrim}"`;

function checkNoError(err) {
    assert.equal(err, null,
        `Expected success, got error ${JSON.stringify(err)}`);
}

function checkError(err, code) {
    assert.notEqual(err, null, 'Expected failure but got success');
    assert.strictEqual(err.code, code);
}

function dateFromNow(diff) {
    const d = new Date();
    d.setHours(d.getHours() + diff);
    return d.toISOString();
}

function dateConvert(d) {
    return (new Date(d)).toISOString();
}

describe('GET object', () => {
    withV4(sigCfg => {
        let bucketUtil;
        let s3;

        function requestGet(fields, cb) {
            s3.getObject(Object.assign({
                Bucket: bucketName,
                Key: objectName,
            }, fields), cb);
        }

        before(done => {
            bucketUtil = new BucketUtility('default', sigCfg);
            s3 = bucketUtil.s3;
            // Create a bucket to put object to get later
            s3.createBucket({ Bucket: bucketName }, done);
        });

        after(done => {
            s3.deleteObject({ Bucket: bucketName, Key: objectName }, err => {
                if (err) {
                    return done(err);
                }
                return s3.deleteBucket({ Bucket: bucketName }, done);
            });
        });

        it('should return an error to get request without a valid bucket name',
            done => {
                s3.getObject({ Bucket: '', Key: 'somekey' }, err => {
                    assert.notEqual(err, null,
                        'Expected failure but got success');
                    assert.strictEqual(err.code, 'MethodNotAllowed');
                    return done();
                });
            });

        it('should return NoSuchKey error when no such object',
            done => {
                s3.getObject({ Bucket: bucketName, Key: 'nope' }, err => {
                    assert.notEqual(err, null,
                        'Expected failure but got success');
                    assert.strictEqual(err.code, 'NoSuchKey');
                    return done();
                });
            });

        describe('Additional headers: [Cache-Control, Content-Disposition, ' +
            'Content-Encoding, Expires]', () => {
            describe('if specified in put object request', () => {
                before(done => {
                    const params = {
                        Bucket: bucketName,
                        Key: objectName,
                        CacheControl: cacheControl,
                        ContentDisposition: contentDisposition,
                        ContentEncoding: contentEncoding,
                        ContentType: contentType,
                        Expires: expires,
                    };
                    s3.putObject(params, err => done(err));
                });
                it('should return additional headers', done => {
                    s3.getObject({ Bucket: bucketName, Key: objectName },
                      (err, res) => {
                          if (err) {
                              return done(err);
                          }
                          assert.strictEqual(res.CacheControl,
                            cacheControl);
                          assert.strictEqual(res.ContentDisposition,
                            contentDisposition);
                          // Should remove V4 streaming value 'aws-chunked'
                          // to be compatible with AWS behavior
                          assert.strictEqual(res.ContentEncoding,
                            'gzip');
                          assert.strictEqual(res.ContentType, contentType);
                          assert.strictEqual(res.Expires,
                              new Date(expires).toGMTString());
                          return done();
                      });
                });
            });

            describe('if response content headers are set in query', () => {
                before(done => {
                    s3.putObject({ Bucket: bucketName, Key: objectName },
                        err => done(err));
                });

                it('should return additional headers even if not set in ' +
                'put object request', done => {
                    const params = {
                        Bucket: bucketName,
                        Key: objectName,
                        ResponseCacheControl: cacheControl,
                        ResponseContentDisposition: contentDisposition,
                        ResponseContentEncoding: contentEncoding,
                        ResponseContentLanguage: contentLanguage,
                        ResponseContentType: contentType,
                        ResponseExpires: expires,
                    };
                    s3.getObject(params, (err, res) => {
                        if (err) {
                            return done(err);
                        }
                        assert.strictEqual(res.CacheControl,
                          cacheControl);
                        assert.strictEqual(res.ContentDisposition,
                          contentDisposition);
                        assert.strictEqual(res.ContentEncoding,
                          contentEncoding);
                        assert.strictEqual(res.ContentLanguage,
                            contentLanguage);
                        assert.strictEqual(res.ContentType, contentType);
                        assert.strictEqual(res.Expires, expires);
                        return done();
                    });
                });
            });
        });

        describe('x-amz-website-redirect-location header', () => {
            before(done => {
                const params = {
                    Bucket: bucketName,
                    Key: objectName,
                    WebsiteRedirectLocation: '/',
                };
                s3.putObject(params, err => done(err));
            });
            it('should return website redirect header if specified in ' +
                'objectPUT request', done => {
                s3.getObject({ Bucket: bucketName, Key: objectName },
                  (err, res) => {
                      if (err) {
                          return done(err);
                      }
                      assert.strictEqual(res.WebsiteRedirectLocation, '/');
                      return done();
                  });
            });
        });

        describe('x-amz-tagging-count', () => {
            const params = {
                Bucket: bucketName,
                Key: objectName,
            };
            const paramsTagging = {
                Bucket: bucketName,
                Key: objectName,
                Tagging: {
                    TagSet: [
                        {
                            Key: 'key1',
                            Value: 'value',
                        },
                    ],
                },
            };
            beforeEach(done => {
                s3.putObject(params, done);
            });

            it('should not return "x-amz-tagging-count" if no tag ' +
            'associated with the object',
            done => {
                s3.getObject(params, (err, data) => {
                    if (err) {
                        return done(err);
                    }
                    assert.strictEqual(data.TagCount, undefined);
                    return done();
                });
            });

            describe('tag associated with the object', () => {
                beforeEach(done => {
                    s3.putObjectTagging(paramsTagging, done);
                });
                it('should return "x-amz-tagging-count" header that provides ' +
                'the count of number of tags associated with the object',
                done => {
                    s3.getObject(params, (err, data) => {
                        if (err) {
                            return done(err);
                        }
                        assert.equal(data.TagCount, 1);
                        return done();
                    });
                });
            });
        });

        describe('conditional headers', () => {
            const params = { Bucket: bucketName, Key: objectName };
            beforeEach(done => {
                s3.putObject(params, done);
            });
            it('If-Match: returns no error when ETag match, with double ' +
                'quotes around ETag',
                done => {
                    requestGet({ IfMatch: etag }, err => {
                        checkNoError(err);
                        done();
                    });
                });

            it('If-Match: returns no error when one of ETags match, with ' +
                'double quotes around ETag',
                done => {
                    requestGet({ IfMatch:
                        `non-matching,${etag}` }, err => {
                        checkNoError(err);
                        done();
                    });
                });

            it('If-Match: returns no error when ETag match, without double ' +
                'quotes around ETag',
                done => {
                    requestGet({ IfMatch: etagTrim }, err => {
                        checkNoError(err);
                        done();
                    });
                });

            it('If-Match: returns no error when one of ETags match, without ' +
                'double quotes around ETag',
                done => {
                    requestGet({ IfMatch:
                        `non-matching,${etagTrim}` }, err => {
                        checkNoError(err);
                        done();
                    });
                });

            it('If-Match: returns no error when ETag match with *', done => {
                requestGet({ IfMatch: '*' }, err => {
                    checkNoError(err);
                    done();
                });
            });

            it('If-Match: returns PreconditionFailed when ETag does not match',
                done => {
                    requestGet({
                        IfMatch: 'non-matching ETag',
                    }, err => {
                        checkError(err, 'PreconditionFailed');
                        done();
                    });
                });

            it('If-None-Match: returns no error when ETag does not match',
            done => {
                requestGet({ IfNoneMatch: 'non-matching' }, err => {
                    checkNoError(err);
                    done();
                });
            });

            it('If-None-Match: returns no error when all ETags do not match',
                done => {
                    requestGet({
                        IfNoneMatch: 'non-matching,' +
                        'non-matching-either',
                    }, err => {
                        checkNoError(err);
                        done();
                    });
                });

            it('If-None-Match: returns NotModified when ETag match, with ' +
                'double quotes around ETag',
                done => {
                    requestGet({ IfNoneMatch: etag }, err => {
                        checkError(err, 'NotModified');
                        done();
                    });
                });

            it('If-None-Match: returns NotModified when one of ETags match, ' +
                'with double quotes around ETag',
                done => {
                    requestGet({
                        IfNoneMatch: `non-matching,${etag}`,
                    }, err => {
                        checkError(err, 'NotModified');
                        done();
                    });
                });

            it('If-None-Match: returns NotModified when value is "*"',
                done => {
                    requestGet({
                        IfNoneMatch: '*',
                    }, err => {
                        checkError(err, 'NotModified');
                        done();
                    });
                });

            it('If-None-Match: returns NotModified when ETag match, without ' +
                'double quotes around ETag',
                done => {
                    requestGet({ IfNoneMatch: etagTrim }, err => {
                        checkError(err, 'NotModified');
                        done();
                    });
                });

            it('If-None-Match: returns NotModified when one of ETags match, ' +
                'without double quotes around ETag',
                done => {
                    requestGet({
                        IfNoneMatch: `non-matching,${etagTrim}`,
                    }, err => {
                        checkError(err, 'NotModified');
                        done();
                    });
                });

            it('If-Modified-Since: returns no error if Last modified date is ' +
                'greater',
                done => {
                    requestGet({ IfModifiedSince: dateFromNow(-1) },
                        err => {
                            checkNoError(err);
                            done();
                        });
                });

            // Skipping this test, because real AWS does not provide error as
            // expected
            it.skip('If-Modified-Since: returns NotModified if Last modified ' +
                'date is lesser',
                done => {
                    requestGet({ IfModifiedSince: dateFromNow(1) },
                        err => {
                            checkError(err, 'NotModified');
                            done();
                        });
                });

            it('If-Modified-Since: returns NotModified if Last modified ' +
                'date is equal',
                done => {
                    s3.headObject({ Bucket: bucketName, Key: objectName },
                    (err, data) => {
                        checkNoError(err);
                        const lastModified = dateConvert(data.LastModified);
                        requestGet({ IfModifiedSince: lastModified }, err => {
                            checkError(err, 'NotModified');
                            done();
                        });
                    });
                });

            it('If-Unmodified-Since: returns no error when lastModified date ' +
                'is greater',
                done => {
                    requestGet({ IfUnmodifiedSince: dateFromNow(1) },
                    err => {
                        checkNoError(err);
                        done();
                    });
                });

            it('If-Unmodified-Since: returns no error when lastModified ' +
                'date is equal', done => {
                s3.headObject({ Bucket: bucketName, Key: objectName },
                    (err, data) => {
                        checkNoError(err);
                        const lastModified = dateConvert(data.LastModified);
                        requestGet({ IfUnmodifiedSince: lastModified },
                            err => {
                                checkNoError(err);
                                done();
                            });
                    });
            });

            it('If-Unmodified-Since: returns PreconditionFailed when ' +
                'lastModified date is lesser',
                done => {
                    requestGet({ IfUnmodifiedSince: dateFromNow(-1) },
                    err => {
                        checkError(err, 'PreconditionFailed');
                        done();
                    });
                });

            it('If-Match & If-Unmodified-Since: returns no error when match ' +
                'Etag and lastModified is greater',
                done => {
                    requestGet({
                        IfMatch: etagTrim,
                        IfUnmodifiedSince: dateFromNow(-1),
                    }, err => {
                        checkNoError(err);
                        done();
                    });
                });

            it('If-Match match & If-Unmodified-Since match', done => {
                requestGet({
                    IfMatch: etagTrim,
                    IfUnmodifiedSince: dateFromNow(1),
                }, err => {
                    checkNoError(err);
                    done();
                });
            });

            it('If-Match not match & If-Unmodified-Since not match', done => {
                requestGet({
                    IfMatch: 'non-matching',
                    IfUnmodifiedSince: dateFromNow(-1),
                }, err => {
                    checkError(err, 'PreconditionFailed');
                    done();
                });
            });

            it('If-Match not match & If-Unmodified-Since match', done => {
                requestGet({
                    IfMatch: 'non-matching',
                    IfUnmodifiedSince: dateFromNow(1),
                }, err => {
                    checkError(err, 'PreconditionFailed');
                    done();
                });
            });

            // Skipping this test, because real AWS does not provide error as
            // expected
            it.skip('If-Match match & If-Modified-Since not match', done => {
                requestGet({
                    IfMatch: etagTrim,
                    IfModifiedSince: dateFromNow(1),
                }, err => {
                    checkNoError(err);
                    done();
                });
            });

            it('If-Match match & If-Modified-Since match', done => {
                requestGet({
                    IfMatch: etagTrim,
                    IfModifiedSince: dateFromNow(-1),
                }, err => {
                    checkNoError(err);
                    done();
                });
            });

            it('If-Match not match & If-Modified-Since not match', done => {
                requestGet({
                    IfMatch: 'non-matching',
                    IfModifiedSince: dateFromNow(1),
                }, err => {
                    checkError(err, 'PreconditionFailed');
                    done();
                });
            });

            it('If-Match not match & If-Modified-Since match', done => {
                requestGet({
                    IfMatch: 'non-matching',
                    IfModifiedSince: dateFromNow(-1),
                }, err => {
                    checkError(err, 'PreconditionFailed');
                    done();
                });
            });

            it('If-None-Match & If-Modified-Since: returns NotModified when ' +
                'Etag does not match and lastModified is greater',
                done => {
                    requestGet({
                        IfNoneMatch: etagTrim,
                        IfModifiedSince: dateFromNow(-1),
                    }, err => {
                        checkError(err, 'NotModified');
                        done();
                    });
                });

            it('If-None-Match not match & If-Modified-Since not match',
            done => {
                requestGet({
                    IfNoneMatch: etagTrim,
                    IfModifiedSince: dateFromNow(1),
                }, err => {
                    checkError(err, 'NotModified');
                    done();
                });
            });

            it('If-None-Match match & If-Modified-Since match', done => {
                requestGet({
                    IfNoneMatch: 'non-matching',
                    IfModifiedSince: dateFromNow(-1),
                }, err => {
                    checkNoError(err);
                    done();
                });
            });

            // Skipping this test, because real AWS does not provide error as
            // expected
            it.skip('If-None-Match match & If-Modified-Since not match',
            done => {
                requestGet({
                    IfNoneMatch: 'non-matching',
                    IfModifiedSince: dateFromNow(1),
                }, err => {
                    checkError(err, 'PreconditionFailed');
                    done();
                });
            });

            it('If-None-Match match & If-Unmodified-Since match', done => {
                requestGet({
                    IfNoneMatch: 'non-matching',
                    IfUnmodifiedSince: dateFromNow(1),
                }, err => {
                    checkNoError(err);
                    done();
                });
            });

            it('If-None-Match match & If-Unmodified-Since not match', done => {
                requestGet({
                    IfNoneMatch: 'non-matching',
                    IfUnmodifiedSince: dateFromNow(-1),
                }, err => {
                    checkError(err, 'PreconditionFailed');
                    done();
                });
            });

            it('If-None-Match not match & If-Unmodified-Since match', done => {
                requestGet({
                    IfNoneMatch: etagTrim,
                    IfUnmodifiedSince: dateFromNow(1),
                }, err => {
                    checkError(err, 'NotModified');
                    done();
                });
            });

            it('If-None-Match not match & If-Unmodified-Since not match',
            done => {
                requestGet({
                    IfNoneMatch: etagTrim,
                    IfUnmodifiedSince: dateFromNow(-1),
                }, err => {
                    checkError(err, 'PreconditionFailed');
                    done();
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>const chai = require('chai');
const mongoose = require('mongoose');
const rewire = require('rewire');
const FrameElement = require('noframenet-core').FrameElement;
const ValenceUnit = require('noframenet-core').ValenceUnit;
const config = require('./../../config');

const should = chai.should();
const getValenceUnits = rewire('./../../middlewares/processor').__get__('getValenceUnits');
mongoose.Promise = require('bluebird');

describe('processor.valenceUnits', () => {
  before(async () => {
    if (mongoose.connection.readyState === 0) {
      await mongoose.connect(config.dbUri);
    }
    const aFE = new FrameElement({
      _id: 1,
      name: 'A',
    });
    await aFE.save();
    const bFE = new FrameElement({
      _id: 2,
      name: 'B',
    });
    await bFE.save();
    const cFE = new FrameElement({
      _id: 3,
      name: 'C',
    });
    await cFE.save();
    const dFE = new FrameElement({
      _id: 4,
      name: 'D',
    });
    await dFE.save();
    const aNPObj = new ValenceUnit({
      FE: 1,
      PT: 'NP',
      GF: 'Obj',
    });
    await aNPObj.save();
    const bNPObj = new ValenceUnit({
      FE: 2,
      PT: 'NP',
      GF: 'Obj',
    });
    await bNPObj.save();
    const cNPExt = new ValenceUnit({
      FE: 3,
      PT: 'NP',
      GF: 'Ext',
    });
    await cNPExt.save();
    const dPPaExt = new ValenceUnit({
      FE: 4,
      PT: 'PP[about]',
      GF: 'Ext',
    });
    await dPPaExt.save();
  });
  after(async () => {
    await mongoose.connection.dropDatabase();
  });
  it('#getValenceUnits should be able to process FE.PT.GF', async () => {
    const set = await getValenceUnits([[1], 'NP', 'Obj']);
    set.length.should.equal(1);
    set.toArray()[0].FE.should.equal(1);
    set.toArray()[0].PT.should.equal('NP');
    set.toArray()[0].GF.should.equal('Obj');
  });
  it('#getValenceUnits should be able to process PT.FE.GF', async () => {
    const set = await getValenceUnits(['NP', [1], 'Obj']);
    set.length.should.equal(1);
    set.toArray()[0].FE.should.equal(1);
    set.toArray()[0].PT.should.equal('NP');
    set.toArray()[0].GF.should.equal('Obj');
  });
  it('#getValenceUnits should be able to process GF.PT.FE', async () => {
    const set = await getValenceUnits(['Obj', 'NP', [1]]);
    set.length.should.equal(1);
    set.toArray()[0].FE.should.equal(1);
    set.toArray()[0].PT.should.equal('NP');
    set.toArray()[0].GF.should.equal('Obj');
  });
  it('#getValenceUnits should be able to process FE', async () => {
    const set = await getValenceUnits([[1]]);
    set.length.should.equal(1);
  });
  it('#getValenceUnits should be able to process PT', async () => {
    const set = await getValenceUnits(['NP']);
    set.length.should.equal(3);
  });
  it('#getValenceUnits should be able to process PT.GF', async () => {
    const set = await getValenceUnits(['NP', 'Obj']);
    set.length.should.equal(2);
  });
  it('#getValenceUnits should be able to process FE.GF', async () => {
    const set = await getValenceUnits([[1], 'Obj']);
    set.length.should.equal(1);
  });
  it('#retrieveValenceUnits', () => {
    (() => 1).should.equal(2);
  });
});
<commit_msg>Added tests for limit cases (empty array for no results and NotFoundError thrown when a token is not found in database)<commit_after>const chai = require('chai');
const mongoose = require('mongoose');
const rewire = require('rewire');
const FrameElement = require('noframenet-core').FrameElement;
const ValenceUnit = require('noframenet-core').ValenceUnit;
const config = require('./../../config');

const should = chai.should();
const getValenceUnitsIDs = rewire('./../../middlewares/processor').__get__('getValenceUnitsIDs');
mongoose.Promise = require('bluebird');

describe('processor.valenceUnits', () => {
  before(async () => {
    if (mongoose.connection.readyState === 0) {
      await mongoose.connect(config.dbUri);
    }
    const aFE = new FrameElement({
      _id: 1,
      name: 'A',
    });
    await aFE.save();
    const bFE = new FrameElement({
      _id: 2,
      name: 'B',
    });
    await bFE.save();
    const cFE = new FrameElement({
      _id: 3,
      name: 'C',
    });
    await cFE.save();
    const dFE = new FrameElement({
      _id: 4,
      name: 'D',
    });
    await dFE.save();
    const aNPObj = new ValenceUnit({
      FE: 1,
      PT: 'NP',
      GF: 'Obj',
    });
    await aNPObj.save();
    const bNPObj = new ValenceUnit({
      FE: 2,
      PT: 'NP',
      GF: 'Obj',
    });
    await bNPObj.save();
    const cNPExt = new ValenceUnit({
      FE: 3,
      PT: 'NP',
      GF: 'Ext',
    });
    await cNPExt.save();
    const dPPaExt = new ValenceUnit({
      FE: 4,
      PT: 'PP[about]',
      GF: 'Ext',
    });
    await dPPaExt.save();
  });
  after(async () => {
    await mongoose.connection.dropDatabase();
  });
  it('#getValenceUnitsIDs should be able to process FE.PT.GF', async () => {
    const vusIDs = await getValenceUnitsIDs([[1], 'NP', 'Obj']);
    const vus = await ValenceUnit.find().where('_id').in(vusIDs);
    vusIDs.length.should.equal(1);
    vus.toArray()[0].FE.should.equal(1);
    vus.toArray()[0].PT.should.equal('NP');
    vus.toArray()[0].GF.should.equal('Obj');
  });

  it('#getValenceUnitsIDs should be able to process PT.FE.GF', async () => {
    const vusIDs = await getValenceUnitsIDs(['NP', [1], 'Obj']);
    const vus = await ValenceUnit.find().where('_id').in(vusIDs);
    vusIDs.length.should.equal(1);
    vus.toArray()[0].FE.should.equal(1);
    vus.toArray()[0].PT.should.equal('NP');
    vus.toArray()[0].GF.should.equal('Obj');
  });
  it('#getValenceUnitsIDs should be able to process GF.PT.FE', async () => {
    const vusIDs = await getValenceUnitsIDs(['Obj', 'NP', [1]]);
    const vus = await ValenceUnit.find().where('_id').in(vusIDs);
    vusIDs.length.should.equal(1);
    vus.toArray()[0].FE.should.equal(1);
    vus.toArray()[0].PT.should.equal('NP');
    vus.toArray()[0].GF.should.equal('Obj');
  });
  it('#getValenceUnitsIDs should be able to process FE', async () => {
    const vusIDs = await getValenceUnitsIDs([[1]]);
    vusIDs.length.should.equal(1);
  });
  it('#getValenceUnitsIDs should be able to process PT', async () => {
    const vusIDs = await getValenceUnitsIDs(['NP']);
    vusIDs.length.should.equal(3);
  });
  it('#getValenceUnitsIDs should be able to process PT.GF', async () => {
    const vusIDs = await getValenceUnitsIDs(['NP', 'Obj']);
    vusIDs.length.should.equal(2);
  });
  it('#getValenceUnitsIDs should be able to process FE.GF', async () => {
    const vusIDs = await getValenceUnitsIDs([[1], 'Obj']);
    vusIDs.length.should.equal(1);
  });
  it('#getValenceUnitsIDs should return an empty array when all tokens are found in the database but not in the given configuration', async () => {
    const vusIDs = await getValenceUnitsIDs([[3], 'PP[about]', 'Obj']);
    vusIDs.length.should.equal(0);
    vusIDs.should.deep.equal([]);
  });
  it('#getValenceUnitsIDs should throw a NotFoundError when a given PT and/or GF is not in the database', async () => {
    try {
      await getValenceUnitsIDs([[3], 'Test']);
    } catch (err) {
      err.name.should.equal('NotFoundError');
      err.message.should.equal('Could not find token in FrameNet database: Test');
    }
  });
});
<|endoftext|>


<commit_before>/**
 * Dialog component.
 *
 * Site Kit by Google, Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import PropTypes from 'prop-types';
import FocusTrap from 'focus-trap-react';
import classnames from 'classnames';

/**
 * WordPress dependencies
 */
import { withInstanceId } from '@wordpress/compose';
import { Component, createRef } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Button from './button';
import Link from './link';
import { MDCDialog } from '../material-components';

class Dialog extends Component {
	constructor() {
		super();

		this.state = { /* TODO: Update state with real data based on module */
			attributes: [
				__( 'Audience overview', 'google-site-kit' ),
				__( 'Top pages', 'google-site-kit' ),
				__( 'Top acquisition sources', 'google-site-kit' ),
				__( 'AdSense & Analytics metrics for top pages', 'google-site-kit' ),
			],
		};

		this.dialogRef = createRef();
	}

	componentDidMount() {
		new MDCDialog( this.dialogRef.current );
	}

	render() {
		const {
			dialogActive,
			handleDialog,
			title,
			provides,
			handleConfirm,
			subtitle,
			confirmButton,
			dependentModules,
			instanceId,
		} = this.props;

		const labelledByID = `googlesitekit-dialog-label-${ instanceId }`;
		const describedByID = `googlesitekit-dialog-description-${ instanceId }`;
		const hasProvides = !! ( provides && provides.length );

		return (

				<FocusTrap active={ dialogActive } >

								{ title &&

										{ title }

								}
								{ subtitle &&

										{ subtitle }

								}
								{ hasProvides &&

											{ provides.map( ( attribute ) => (

													{ attribute }

											) ) }

								}
								{ dependentModules &&

										{ __( 'Note: ', 'google-site-kit' ) }{ dependentModules }

								}

									<Button
										onClick={ handleConfirm }
										danger
									>
										{ confirmButton ? confirmButton : __( 'Disconnect', 'google-site-kit' ) }
									</Button>
									<Link className="mdc-dialog__cancel-button" onClick={ () => handleDialog() } inherit>
										{ __( 'Cancel', 'google-site-kit' ) }
									</Link>

				</FocusTrap>

		);
	}
}

Dialog.propTypes = {
	dialogActive: PropTypes.bool,
	handleDialog: PropTypes.func,
	handleConfirm: PropTypes.func.isRequired,
	title: PropTypes.string,
	description: PropTypes.string,
	confirmButton: PropTypes.string,
};

Dialog.defaultProps = {
	dialogActive: false,
	handleDialog: null,
	title: null,
	description: null,
	confirmButton: null,
};

export default withInstanceId( Dialog );
<commit_msg>Update Dialog with danger prop to control severity.<commit_after>/**
 * Dialog component.
 *
 * Site Kit by Google, Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import PropTypes from 'prop-types';
import FocusTrap from 'focus-trap-react';
import classnames from 'classnames';

/**
 * WordPress dependencies
 */
import { withInstanceId } from '@wordpress/compose';
import { Component, createRef } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Button from './button';
import Link from './link';
import { MDCDialog } from '../material-components';

class Dialog extends Component {
	constructor() {
		super();

		this.state = { /* TODO: Update state with real data based on module */
			attributes: [
				__( 'Audience overview', 'google-site-kit' ),
				__( 'Top pages', 'google-site-kit' ),
				__( 'Top acquisition sources', 'google-site-kit' ),
				__( 'AdSense & Analytics metrics for top pages', 'google-site-kit' ),
			],
		};

		this.dialogRef = createRef();
	}

	componentDidMount() {
		new MDCDialog( this.dialogRef.current );
	}

	render() {
		const {
			dialogActive,
			handleDialog,
			title,
			provides,
			handleConfirm,
			subtitle,
			confirmButton,
			dependentModules,
			instanceId,
			danger,
		} = this.props;

		const labelledByID = `googlesitekit-dialog-label-${ instanceId }`;
		const describedByID = `googlesitekit-dialog-description-${ instanceId }`;
		const hasProvides = !! ( provides && provides.length );

		return (

				<FocusTrap active={ dialogActive } >

								{ title &&

										{ title }

								}
								{ subtitle &&

										{ subtitle }

								}
								{ hasProvides &&

											{ provides.map( ( attribute ) => (

													{ attribute }

											) ) }

								}
								{ dependentModules &&

										{ __( 'Note: ', 'google-site-kit' ) }{ dependentModules }

								}

									<Button
										onClick={ handleConfirm }
										danger={ danger }
									>
										{ confirmButton ? confirmButton : __( 'Disconnect', 'google-site-kit' ) }
									</Button>
									<Link className="mdc-dialog__cancel-button" onClick={ () => handleDialog() } inherit>
										{ __( 'Cancel', 'google-site-kit' ) }
									</Link>

				</FocusTrap>

		);
	}
}

Dialog.propTypes = {
	dialogActive: PropTypes.bool,
	handleDialog: PropTypes.func,
	handleConfirm: PropTypes.func.isRequired,
	title: PropTypes.string,
	description: PropTypes.string,
	confirmButton: PropTypes.string,
	danger: PropTypes.bool,
};

Dialog.defaultProps = {
	dialogActive: false,
	handleDialog: null,
	title: null,
	description: null,
	confirmButton: null,
	danger: false,
};

export default withInstanceId( Dialog );
<|endoftext|>


<commit_before>
/**
***		FIND PLACE
***/

SigLoader.getSigFindPlace = function (Sig){

	Sig.currentResultResearch = "";
	Sig.nbMaxTentative = 4;
	Sig.fullTextResearch = true;

	//***
	//initialisation de l'interface et des événements (click, etc)
	/*	>>>>>>>>>>>>>> MAP <<<<<<<<<<<<<<< */
	Sig.initFindPlace = function (){
		console.warn("--------------- initFindPlace ---------------------");
		var thisSig = this;

		//##
		//BTN FIND PLACE
		$(thisSig.cssModuleName + " .btn-find-place").click(function (){ //alert("find place");
			var address = $(thisSig.cssModuleName + " #txt-find-place").val();
			thisSig.findPlace(1);
		});

		//##
		//ON FOCUS TXT FIND PLACE
		//efface la dropDown qui contient le résultat de recheche
		//lorsque l'on click sur le champ de texte,
		//si le champs de texte est vide
		$(thisSig.cssModuleName + ' .txt-find-place').focus(function(event) {
			if($(thisSig.cssModuleName + ' #txt-find-place').val() != "")
			$(thisSig.cssModuleName + ' #list-dropdown-find-place').css({'display':'block'});
			else
			$(thisSig.cssModuleName + ' #list-dropdown-find-place').css({'display':'none'});
		});

		//##
		//ON KEY UP TXT FIND PLACE
		//lance un timeout de 1 seconde
		//après 1 seconde sans nouvelle lettre, on lance la recherche
		var timeoutFindPlace;
		$(thisSig.cssModuleName + ' .txt-find-place').keyup(function(event) {
				clearTimeout(timeoutFindPlace);
				var action = "Sig.findPlace(1)";//"+$(thisSig.cssModuleName + " #txt-find-place").val()+"')";
				timeoutFindPlace = setTimeout(action, 1000);
			//}
		});

		$(thisSig.cssModuleName + ' #btn-find-more').click(function(event) {
			//console.warn("--------------- findMORE ---------------------");
			if($(thisSig.cssModuleName + ' #full-research').hasClass("hidden")){
				$(thisSig.cssModuleName + ' #full-research').removeClass("hidden");
				$(thisSig.cssModuleName + ' #txt-find-place').addClass("hidden");
				thisSig.fullTextResearch = false;
			}
			else{
				$(thisSig.cssModuleName + ' #full-research').addClass("hidden");
				$(thisSig.cssModuleName + ' #txt-find-place').removeClass("hidden");
				this.fullTextResearch = true;
			}
			console.log("fullTextResearch = " + this.fullTextResearch);
			//$(thisSig.cssModuleName + ' #full-research').toggle();
		});

		//##
		//ON FOCUS MAP
		//lorsqu'on click sur la carte, la dropdown disparait
		$(thisSig.cssModuleName + ' #mapCanvas' + this.sigKey).focus(function(event) {
			$(thisSig.cssModuleName + ' #list-dropdown-find-place').css({'display':'none'});
		});

	};

	//##
	//recherche un lieu par nominatim
	Sig.findPlace = function (nbTentative){ //alert(address);
		console.warn("--------------- findPlace ---------------------");
		var thisSig = this;

		//affiche le message "recherche en cours"
		$(thisSig.cssModuleName + " #list-dropdown-find-place").html('
 ('+ nbTentative +') Recherche en cours ...
');
		$(thisSig.cssModuleName + ' #list-dropdown-find-place').css({'display':'block'});

		var urlRequest = this.getNominatimRequest(nbTentative);
		console.log(urlRequest);
		$.ajax({
			//url: "http://nominatim.openstreetmap.org/search?q=" + address + "&format=json&polygon=0&addressdetails=1",
			url: "http://nominatim.openstreetmap.org/search" + urlRequest + "&format=json&polygon=1&addressdetails=1",
			type: 'POST',
    		dataType: 'json',
    		//crossDomain: true,
			complete: function () { },
			success: function (obj)
			{
				if (obj.length > 0) {

					$(thisSig.cssModuleName + " #list-dropdown-find-place").html("");

					thisSig.currentResultResearch = obj;
					var i = 0;

					console.log("reponse nominatim : ");
					console.dir(obj);

					//affichage des résultats de la recherche
					$.each(obj, function (){

						var itemDropbox = thisSig.getItemDropBox(this); //"";
						if(itemDropbox != ""){
							itemDropbox = '
 ' + itemDropbox + '
';
							$(thisSig.cssModuleName + " #list-dropdown-find-place").append(itemDropbox);
							$(thisSig.cssModuleName + ' #btn-show-place-'+i).click(function(){
								var num = $(this).attr('num');
								thisSig.showPlace(num);
							});
						}
						i++;
					});
					//$('#btn-dropdown-find-place').dropdown('toggle');
					$(thisSig.cssModuleName + ' #list-dropdown-find-place').css({'display':'block'});
					$(thisSig.cssModuleName + ' #btn-dropdown-find-place').dropdown('toggle');
				}
				else {
					//alert('no such address.');
					if(nbTentative <= thisSig.nbMaxTentative)
					{
						thisSig.findPlace(nbTentative+1);
					}
					else{
						var itemDropbox = '
 Aucun résultat n\'a été trouvé
';
						$(thisSig.cssModuleName + " #list-dropdown-find-place").html(itemDropbox);
						$(thisSig.cssModuleName + ' #list-dropdown-find-place').css({'display':'block'});
					}
				}
			},
			error: function (error) {
				var itemDropbox = '
 Erreur nominatim ajax jquery
';
				$(thisSig.cssModuleName + " #list-dropdown-find-place").html(itemDropbox);

				//alert('erreur nominatim ajax jquery (map_findPlace.js)');
			}
		});
	};

	Sig.getNominatimRequest = function(nbTentative){

		if(this.fullTextResearch == true){
			return "?q=" + $(this.cssModuleName + " #txt-find-place").val();
		}

		function transform(str){ //alert(newValue);
			var res = "";
			//remplace les espaces par des +
			for(var i = 0; i<str.length; i++){
				res += (str.charAt(i) == " ") ? "+" : str.charAt(i);
			}
			return res;
		};

		var num 	= transform($(this.cssModuleName + " #txt-num-place").val());//.replace(" ", "+");
		var street 	= transform($(this.cssModuleName + " #txt-street-place").val());//.replace(" ", "+");
		var city 	= transform($(this.cssModuleName + " #txt-city-place").val());//.replace(" ", "+");
		var cp 		= transform($(this.cssModuleName + " #txt-cp-place").val());//.replace(" ", "+");
		var state 	= transform($(this.cssModuleName + " #txt-state-place").val());//.replace(" ", "+");

		if(num != "") street = num + "+" + street;

		var request = "?";

		//on utilise la street pour la tentative 1 ou 2 (mais pas à la 3)
		if(street != "" && (nbTentative < 3)) 	request += "street=" 	  + street;
		//on utilise toujours la ville et le cp
		if(city != "") 		request += "&city=" 	  + city;
		if(cp != "") 		request += "&postalcode=" + cp;
		//on utilise country pour la tentative 1
		if(state != "" && nbTentative == 1) 	request += "&country=" + state; //"&state=" 	  + state +
		//on utilise country pour la tentative 2
		if(state != "" && nbTentative == 2) 	request += "&state="   + state; //"&state=" 	  + state +
		//pas de state pour la 3

		if(nbTentative == 3){
			request = "?q=";
			if(street != "") 	request += street;
			if(city != "") 		request += ",+" + city;
			if(cp != "") 		request += ",+" + cp;
			if(state != "") 	request += ",+" + state;
		}

		console.warn("--------------- request nominatim ("+nbTentative+") : " + request);

		return request;
	};

	Sig.getItemDropBox = function(thisResult){
		//rajoute une valeur à la string str pour construire l'adresse complète du lieu
		function concat(str, newValue){ //alert(newValue);
			if(str == "" && newValue != undefined) return newValue;
			if(str != "" && newValue != undefined) return str+=", "+newValue;
			return str;
		};

		console.warn("-------" + JSON.stringify(thisResult.address));

		var itemDropbox = "";
		if(thisResult.address !== undefined){
			var city 	= $(this.cssModuleName + " #txt-city-place").val();//.replace(" ", "+");
			var cp 		= $(this.cssModuleName + " #txt-cp-place").val();//.replace(" ", "+");
			var state 	= $(this.cssModuleName + " #txt-state-place").val();//.replace(" ", "+");

			itemDropbox = concat(itemDropbox, thisResult.address.house_number);
			itemDropbox = concat(itemDropbox, thisResult.address.road);

			//ajoute la ville si elle existe
			itemDropbox = concat(itemDropbox, thisResult.address.city);

			//ajoute le code postal s'il existe
			itemDropbox = concat(itemDropbox, thisResult.address.postcode);

			//ajoute le pays s'il existe
			if("undefined" != typeof thisResult.address.state){
				//if(state.toLowerCase() == thisResult.address.state.toLowerCase())
				 	itemDropbox = concat(itemDropbox, thisResult.address.state);
			}else{
				if("undefined" != typeof thisResult.address.country){
					//if(state.toLowerCase() == thisResult.address.country.toLowerCase())
				 		itemDropbox = concat(itemDropbox, thisResult.address.country);
				 }
			}
		}
		return itemDropbox;
	}

	Sig.panMapTo = function (lat, lng){
		var latLng = [lat, lon];
		this.map.panTo(latLng);
		this.map.setZoom(10);
	};

	Sig.showPlace = function (id){
		var thisSig = this;
		var bounds = this.currentResultResearch[id].boundingbox;
	   	var southWest = L.latLng(bounds[0], bounds[2]),
    		northEast = L.latLng(bounds[1], bounds[3]),
    		LBounds = L.latLngBounds(southWest, northEast);

		//this.map.fitBounds(LBounds);

		var options = {  id : 0,
						 icon : this.getIcoMarker({'type' : 'markerPlace'}),
						 content : ""+$(thisSig.cssModuleName + ' #btn-show-place-'+id).html()+"" }; //,

		var coordinates = new Array(this.currentResultResearch[id].lat, this.currentResultResearch[id].lon);

		//efface le polygone s'il existe
		if(this.markerFindPlace != null) this.map.removeLayer(this.markerFindPlace);

		this.markerFindPlace = this.getMarkerSingle(this.map, options, coordinates);
		this.markerFindPlace.openPopup();

		//efface le polygone s'il existe
		if(this.mapPolygon != null) this.map.removeLayer(this.mapPolygon);

		//si l'élément à afficher est une ville et qu'il y a un polygone dans les données
		//on l'affiche
		if( (this.currentResultResearch[id].type == "city" ||
			this.currentResultResearch[id].type == "town") &&
		   "undefined" != typeof this.currentResultResearch[id].polygonpoints){

			var allPolygonpoints = this.currentResultResearch[id].polygonpoints;

			var polygonpoints = new Array();
			$.each(allPolygonpoints, function(index, value){
				polygonpoints.push(new Array(parseFloat(value[1]), parseFloat(value[0])));
			});

			this.showPolygon(polygonpoints);
		}

		//on ferme la dropdown
		$(thisSig.cssModuleName + ' #list-dropdown-find-place').css({'display':'none'});
		$(thisSig.cssModuleName + ' #btn-dropdown-find-place').dropdown('toggle');

		alert("before");
		this.map.panTo(coordinates);
		alert("after");
	};

	return Sig;
};
<commit_msg>clean alert<commit_after>
/**
***		FIND PLACE
***/

SigLoader.getSigFindPlace = function (Sig){

	Sig.currentResultResearch = "";
	Sig.nbMaxTentative = 4;
	Sig.fullTextResearch = true;

	//***
	//initialisation de l'interface et des événements (click, etc)
	/*	>>>>>>>>>>>>>> MAP <<<<<<<<<<<<<<< */
	Sig.initFindPlace = function (){
		console.warn("--------------- initFindPlace ---------------------");
		var thisSig = this;

		//##
		//BTN FIND PLACE
		$(thisSig.cssModuleName + " .btn-find-place").click(function (){ //alert("find place");
			var address = $(thisSig.cssModuleName + " #txt-find-place").val();
			thisSig.findPlace(1);
		});

		//##
		//ON FOCUS TXT FIND PLACE
		//efface la dropDown qui contient le résultat de recheche
		//lorsque l'on click sur le champ de texte,
		//si le champs de texte est vide
		$(thisSig.cssModuleName + ' .txt-find-place').focus(function(event) {
			if($(thisSig.cssModuleName + ' #txt-find-place').val() != "")
			$(thisSig.cssModuleName + ' #list-dropdown-find-place').css({'display':'block'});
			else
			$(thisSig.cssModuleName + ' #list-dropdown-find-place').css({'display':'none'});
		});

		//##
		//ON KEY UP TXT FIND PLACE
		//lance un timeout de 1 seconde
		//après 1 seconde sans nouvelle lettre, on lance la recherche
		var timeoutFindPlace;
		$(thisSig.cssModuleName + ' .txt-find-place').keyup(function(event) {
				clearTimeout(timeoutFindPlace);
				var action = "Sig.findPlace(1)";//"+$(thisSig.cssModuleName + " #txt-find-place").val()+"')";
				timeoutFindPlace = setTimeout(action, 1000);
			//}
		});

		$(thisSig.cssModuleName + ' #btn-find-more').click(function(event) {
			//console.warn("--------------- findMORE ---------------------");
			if($(thisSig.cssModuleName + ' #full-research').hasClass("hidden")){
				$(thisSig.cssModuleName + ' #full-research').removeClass("hidden");
				$(thisSig.cssModuleName + ' #txt-find-place').addClass("hidden");
				thisSig.fullTextResearch = false;
			}
			else{
				$(thisSig.cssModuleName + ' #full-research').addClass("hidden");
				$(thisSig.cssModuleName + ' #txt-find-place').removeClass("hidden");
				this.fullTextResearch = true;
			}
			console.log("fullTextResearch = " + this.fullTextResearch);
			//$(thisSig.cssModuleName + ' #full-research').toggle();
		});

		//##
		//ON FOCUS MAP
		//lorsqu'on click sur la carte, la dropdown disparait
		$(thisSig.cssModuleName + ' #mapCanvas' + this.sigKey).focus(function(event) {
			$(thisSig.cssModuleName + ' #list-dropdown-find-place').css({'display':'none'});
		});

	};

	//##
	//recherche un lieu par nominatim
	Sig.findPlace = function (nbTentative){ //alert(address);
		console.warn("--------------- findPlace ---------------------");
		var thisSig = this;

		//affiche le message "recherche en cours"
		$(thisSig.cssModuleName + " #list-dropdown-find-place").html('
 ('+ nbTentative +') Recherche en cours ...
');
		$(thisSig.cssModuleName + ' #list-dropdown-find-place').css({'display':'block'});

		var urlRequest = this.getNominatimRequest(nbTentative);
		console.log(urlRequest);
		$.ajax({
			//url: "http://nominatim.openstreetmap.org/search?q=" + address + "&format=json&polygon=0&addressdetails=1",
			url: "http://nominatim.openstreetmap.org/search" + urlRequest + "&format=json&polygon=1&addressdetails=1",
			type: 'POST',
    		dataType: 'json',
    		//crossDomain: true,
			complete: function () { },
			success: function (obj)
			{
				if (obj.length > 0) {

					$(thisSig.cssModuleName + " #list-dropdown-find-place").html("");

					thisSig.currentResultResearch = obj;
					var i = 0;

					console.log("reponse nominatim : ");
					console.dir(obj);

					//affichage des résultats de la recherche
					$.each(obj, function (){

						var itemDropbox = thisSig.getItemDropBox(this); //"";
						if(itemDropbox != ""){
							itemDropbox = '
 ' + itemDropbox + '
';
							$(thisSig.cssModuleName + " #list-dropdown-find-place").append(itemDropbox);
							$(thisSig.cssModuleName + ' #btn-show-place-'+i).click(function(){
								var num = $(this).attr('num');
								thisSig.showPlace(num);
							});
						}
						i++;
					});
					//$('#btn-dropdown-find-place').dropdown('toggle');
					$(thisSig.cssModuleName + ' #list-dropdown-find-place').css({'display':'block'});
					$(thisSig.cssModuleName + ' #btn-dropdown-find-place').dropdown('toggle');
				}
				else {
					//alert('no such address.');
					if(nbTentative <= thisSig.nbMaxTentative)
					{
						thisSig.findPlace(nbTentative+1);
					}
					else{
						var itemDropbox = '
 Aucun résultat n\'a été trouvé
';
						$(thisSig.cssModuleName + " #list-dropdown-find-place").html(itemDropbox);
						$(thisSig.cssModuleName + ' #list-dropdown-find-place').css({'display':'block'});
					}
				}
			},
			error: function (error) {
				var itemDropbox = '
 Erreur nominatim ajax jquery
';
				$(thisSig.cssModuleName + " #list-dropdown-find-place").html(itemDropbox);

				//alert('erreur nominatim ajax jquery (map_findPlace.js)');
			}
		});
	};

	Sig.getNominatimRequest = function(nbTentative){

		if(this.fullTextResearch == true){
			return "?q=" + $(this.cssModuleName + " #txt-find-place").val();
		}

		function transform(str){ //alert(newValue);
			var res = "";
			//remplace les espaces par des +
			for(var i = 0; i<str.length; i++){
				res += (str.charAt(i) == " ") ? "+" : str.charAt(i);
			}
			return res;
		};

		var num 	= transform($(this.cssModuleName + " #txt-num-place").val());//.replace(" ", "+");
		var street 	= transform($(this.cssModuleName + " #txt-street-place").val());//.replace(" ", "+");
		var city 	= transform($(this.cssModuleName + " #txt-city-place").val());//.replace(" ", "+");
		var cp 		= transform($(this.cssModuleName + " #txt-cp-place").val());//.replace(" ", "+");
		var state 	= transform($(this.cssModuleName + " #txt-state-place").val());//.replace(" ", "+");

		if(num != "") street = num + "+" + street;

		var request = "?";

		//on utilise la street pour la tentative 1 ou 2 (mais pas à la 3)
		if(street != "" && (nbTentative < 3)) 	request += "street=" 	  + street;
		//on utilise toujours la ville et le cp
		if(city != "") 		request += "&city=" 	  + city;
		if(cp != "") 		request += "&postalcode=" + cp;
		//on utilise country pour la tentative 1
		if(state != "" && nbTentative == 1) 	request += "&country=" + state; //"&state=" 	  + state +
		//on utilise country pour la tentative 2
		if(state != "" && nbTentative == 2) 	request += "&state="   + state; //"&state=" 	  + state +
		//pas de state pour la 3

		if(nbTentative == 3){
			request = "?q=";
			if(street != "") 	request += street;
			if(city != "") 		request += ",+" + city;
			if(cp != "") 		request += ",+" + cp;
			if(state != "") 	request += ",+" + state;
		}

		console.warn("--------------- request nominatim ("+nbTentative+") : " + request);

		return request;
	};

	Sig.getItemDropBox = function(thisResult){
		//rajoute une valeur à la string str pour construire l'adresse complète du lieu
		function concat(str, newValue){ //alert(newValue);
			if(str == "" && newValue != undefined) return newValue;
			if(str != "" && newValue != undefined) return str+=", "+newValue;
			return str;
		};

		console.warn("-------" + JSON.stringify(thisResult.address));

		var itemDropbox = "";
		if(thisResult.address !== undefined){
			var city 	= $(this.cssModuleName + " #txt-city-place").val();//.replace(" ", "+");
			var cp 		= $(this.cssModuleName + " #txt-cp-place").val();//.replace(" ", "+");
			var state 	= $(this.cssModuleName + " #txt-state-place").val();//.replace(" ", "+");

			itemDropbox = concat(itemDropbox, thisResult.address.house_number);
			itemDropbox = concat(itemDropbox, thisResult.address.road);

			//ajoute la ville si elle existe
			itemDropbox = concat(itemDropbox, thisResult.address.city);

			//ajoute le code postal s'il existe
			itemDropbox = concat(itemDropbox, thisResult.address.postcode);

			//ajoute le pays s'il existe
			if("undefined" != typeof thisResult.address.state){
				//if(state.toLowerCase() == thisResult.address.state.toLowerCase())
				 	itemDropbox = concat(itemDropbox, thisResult.address.state);
			}else{
				if("undefined" != typeof thisResult.address.country){
					//if(state.toLowerCase() == thisResult.address.country.toLowerCase())
				 		itemDropbox = concat(itemDropbox, thisResult.address.country);
				 }
			}
		}
		return itemDropbox;
	}

	Sig.panMapTo = function (lat, lng){
		var latLng = [lat, lon];
		this.map.panTo(latLng);
		this.map.setZoom(10);
	};

	Sig.showPlace = function (id){
		var thisSig = this;
		var bounds = this.currentResultResearch[id].boundingbox;
	   	var southWest = L.latLng(bounds[0], bounds[2]),
    		northEast = L.latLng(bounds[1], bounds[3]),
    		LBounds = L.latLngBounds(southWest, northEast);

		//this.map.fitBounds(LBounds);

		var options = {  id : 0,
						 icon : this.getIcoMarker({'type' : 'markerPlace'}),
						 content : ""+$(thisSig.cssModuleName + ' #btn-show-place-'+id).html()+"" }; //,

		var coordinates = new Array(this.currentResultResearch[id].lat, this.currentResultResearch[id].lon);

		//efface le polygone s'il existe
		if(this.markerFindPlace != null) this.map.removeLayer(this.markerFindPlace);

		this.markerFindPlace = this.getMarkerSingle(this.map, options, coordinates);
		this.markerFindPlace.openPopup();

		//efface le polygone s'il existe
		if(this.mapPolygon != null) this.map.removeLayer(this.mapPolygon);

		//si l'élément à afficher est une ville et qu'il y a un polygone dans les données
		//on l'affiche
		if( (this.currentResultResearch[id].type == "city" ||
			this.currentResultResearch[id].type == "town") &&
		   "undefined" != typeof this.currentResultResearch[id].polygonpoints){

			var allPolygonpoints = this.currentResultResearch[id].polygonpoints;

			var polygonpoints = new Array();
			$.each(allPolygonpoints, function(index, value){
				polygonpoints.push(new Array(parseFloat(value[1]), parseFloat(value[0])));
			});

			this.showPolygon(polygonpoints);
		}

		//on ferme la dropdown
		$(thisSig.cssModuleName + ' #list-dropdown-find-place').css({'display':'none'});
		$(thisSig.cssModuleName + ' #btn-dropdown-find-place').dropdown('toggle');

		this.map.panTo(coordinates);
	};

	return Sig;
};
<|endoftext|>


<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

tvcm.require('tracing.test_utils');
tvcm.require('tracing.timeline_track_view');
tvcm.require('tracing.importer.trace_event_importer');

tvcm.unittest.testSuite('tracing.timeline_track_view_test', function() {

  var Selection = tracing.Selection;
  var SelectionState = tracing.trace_model.SelectionState;

  function contains(array, element) {
    for (var i = 0; i < array.length; i++) {
      if (array[i] === element) {
        return true;
      }
    }
    return false;
  };

  function checkSelectionStates(timeline, selection, highlight) {
    selection = selection || [];
    highlight = highlight || [];

    assertEquals(selection.length, timeline.selection.length);
    assertEquals(highlight.length, timeline.highlight.length);

    assertArrayEquals(selection, timeline.selection);
    assertArrayEquals(highlight, timeline.highlight);

    timeline.model.iterateAllEvents(function(event) {
      if (contains(selection, event))
        assertEquals(SelectionState.SELECTED, event.selectionState);
      else if (contains(highlight, event))
        assertEquals(SelectionState.HIGHLIGHTED, event.selectionState);
      else if (highlight.length)
        assertEquals(SelectionState.DIMMED, event.selectionState);
      else
        assertEquals(SelectionState.NONE, event.selectionState);
    });
  };

  test('instantiate', function() {
    var events = [
      {name: 'a', args: {}, pid: 52, ts: 520, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'a', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'E'},
      {name: 'b', args: {}, pid: 52, ts: 629, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'b', args: {}, pid: 52, ts: 631, cat: 'foo', tid: 53, ph: 'E'}
    ];
    var model = new tracing.TraceModel(events);
    var timeline = new tracing.TimelineTrackView();
    timeline.model = model;
    timeline.focusElement = timeline;
    timeline.tabIndex = 0;
    this.addHTMLOutput(timeline);
  });

  test('addAllObjectsMatchingFilterToSelection', function() {
    var model = new tracing.TraceModel();
    var p1 = model.getOrCreateProcess(1);
    var t1 = p1.getOrCreateThread(1);

    t1.sliceGroup.pushSlice(
        new tracing.trace_model.ThreadSlice('', 'a', 0, 1, {}, 3));
    t1.sliceGroup.pushSlice(
        new tracing.trace_model.ThreadSlice('', 'b', 0, 1.1, {}, 2.8));

    var t1asg = t1.asyncSliceGroup;
    t1asg.slices.push(
        tracing.test_utils.newAsyncSliceNamed('a', 0, 1, t1, t1));
    t1asg.slices.push(
        tracing.test_utils.newAsyncSliceNamed('b', 1, 2, t1, t1));

    var timeline = new tracing.TimelineTrackView();
    timeline.model = model;

    var expected = [t1asg.slices[0].subSlices[0],
                    t1.sliceGroup.slices[0]];
    var result = new tracing.Selection();
    timeline.addAllObjectsMatchingFilterToSelection(
        new tracing.TitleFilter('a'), result);
    assertEquals(2, result.length);
    assertEquals(expected[0], result[0]);
    assertEquals(expected[1], result[1]);

    var expected = [t1asg.slices[1].subSlices[0],
                    t1.sliceGroup.slices[1]];
    var result = new tracing.Selection();
    timeline.addAllObjectsMatchingFilterToSelection(
        new tracing.TitleFilter('b'), result);
    assertEquals(2, result.length);
    assertEquals(expected[0], result[0]);
    assertEquals(expected[1], result[1]);
  });

  test('emptyThreadsDeleted', function() {
    var model = new tracing.TraceModel();
    var p1 = model.getOrCreateProcess(1);
    var t1 = p1.getOrCreateThread(1);

    var timeline = new tracing.TimelineTrackView();
    timeline.model = model;

    assertFalse(timeline.hasVisibleContent);
  });

  test('filteredCounters', function() {
    var model = new tracing.TraceModel();
    var c1 = model.kernel.getOrCreateCpu(0);
    c1.getOrCreateCounter('', 'b');

    var p1 = model.getOrCreateProcess(1);
    var ctr = p1.getOrCreateCounter('', 'a');
    var series = new tracing.trace_model.CounterSeries('a', 0);
    series.addCounterSample(0, 1);
    ctr.addSeries(series);

    var timeline = new tracing.TimelineTrackView();
    timeline.model = model;

    assertTrue(timeline.hasVisibleContent);
  });

  test('filteredCpus', function() {
    var model = new tracing.TraceModel();
    var c1 = model.kernel.getOrCreateCpu(1);
    c1.getOrCreateCounter('', 'a');

    var timeline = new tracing.TimelineTrackView();
    timeline.model = model;

    assertTrue(timeline.hasVisibleContent);
  });

  test('filteredProcesses', function() {
    var model = new tracing.TraceModel();
    var p1 = model.getOrCreateProcess(1);
    p1.getOrCreateCounter('', 'a');

    var timeline = new tracing.TimelineTrackView();
    timeline.model = model;

    assertTrue(timeline.hasVisibleContent);
  });

  test('filteredThreads', function() {
    var model = new tracing.TraceModel();
    var p1 = model.getOrCreateProcess(1);
    var t1 = p1.getOrCreateThread(2);
    t1.sliceGroup.pushSlice(tracing.test_utils.newSlice(0, 1));

    var timeline = new tracing.TimelineTrackView();
    timeline.model = model;

    assertTrue(timeline.hasVisibleContent);
  });

  test('selectionAndHighlight', function() {
    var events = [
      {name: 'a', args: {}, pid: 52, ts: 520, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'a', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'ab', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'b', args: {}, pid: 52, ts: 629, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'b', args: {}, pid: 52, ts: 631, cat: 'foo', tid: 53, ph: 'B'}
    ];
    var model = new tracing.TraceModel(events);
    var timeline = new tracing.TimelineTrackView();
    timeline.model = model;

    var selection = new Selection();
    timeline.addAllObjectsMatchingFilterToSelection(
        new tracing.TitleFilter('a'), selection);

    var highlight = new Selection();
    timeline.addAllObjectsMatchingFilterToSelection(
        new tracing.TitleFilter('b'), highlight);

    // Test for faulty input.
    assertThrows(function() {
      timeline.selection = 'selection';
    });

    assertThrows(function() {
      timeline.highlight = 1;
    });

    assertThrows(function() {
      timeline.setSelectionAndHighlight(0, false);
    });

    // Check state after reset.
    timeline.setSelectionAndHighlight(null, null);
    checkSelectionStates(timeline, null, null);

    // Add selection only.
    timeline.selection = selection;
    assertEquals(selection, timeline.selection);
    checkSelectionStates(timeline, selection, null);

    // Reset selection.
    timeline.selection = null;
    assertEquals(0, timeline.selection.length);
    checkSelectionStates(timeline, null, null);

    // Add highlight only.
    timeline.highlight = highlight;
    assertEquals(highlight, timeline.highlight);
    checkSelectionStates(timeline, null, highlight);

    // Reset highlight
    timeline.highlight = null;
    assertEquals(0, timeline.highlight.length);
    checkSelectionStates(timeline, null, null);

    // Add selection and highlight.
    timeline.setSelectionAndHighlight(selection, highlight);
    checkSelectionStates(timeline, selection, highlight);

    // Selection replaces old selection.
    var subSelection = selection.subSelection(0, 1);
    timeline.selection = subSelection;
    checkSelectionStates(timeline, subSelection, highlight);

    // Highlight replaces old highlight.
    var subHighlight = highlight.subSelection(1, 2);
    timeline.highlight = subHighlight;
    checkSelectionStates(timeline, subSelection, subHighlight);

    // Set selection and clear highlight.
    timeline.setSelectionAndClearHighlight(selection);
    checkSelectionStates(timeline, selection, null);

    // Set highlight and clear selection.
    timeline.setHighlightAndClearSelection(highlight);
    checkSelectionStates(timeline, null, highlight);

    // Reset both.
    timeline.setSelectionAndHighlight(null, null);
    checkSelectionStates(timeline, null, null);
  });

  test('interestRange', function() {
    var events = [
      {name: 'a', args: {}, pid: 52, ts: 520, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'b', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'c', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'c', args: {}, pid: 52, ts: 629, cat: 'foo', tid: 53, ph: 'E'},
      {name: 'b', args: {}, pid: 52, ts: 631, cat: 'foo', tid: 53, ph: 'E'},
      {name: 'a', args: {}, pid: 52, ts: 634, cat: 'foo', tid: 53, ph: 'E'}
    ];
    var model = new tracing.TraceModel(events);
    var trackView = new tracing.TimelineTrackView();
    trackView.model = model;
    this.addHTMLOutput(trackView);

    var slice = model.processes[52].threads[53].sliceGroup.slices[2];
    trackView.viewport.interestRange.setMinAndMax(slice.start, slice.end);
  });

  test('emptyInterestRange', function() {
    var events = [
      {name: 'a', args: {}, pid: 52, ts: 520, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'b', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'c', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'c', args: {}, pid: 52, ts: 629, cat: 'foo', tid: 53, ph: 'E'},
      {name: 'b', args: {}, pid: 52, ts: 631, cat: 'foo', tid: 53, ph: 'E'},
      {name: 'a', args: {}, pid: 52, ts: 634, cat: 'foo', tid: 53, ph: 'E'}
    ];
    var model = new tracing.TraceModel(events);
    var trackView = new tracing.TimelineTrackView();
    trackView.model = model;
    this.addHTMLOutput(trackView);
    trackView.viewport.interestRange.reset();
  });

  test('thinnestInterestRange', function() {
    var events = [
      {name: 'a', args: {}, pid: 52, ts: 520, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'b', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'c', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'c', args: {}, pid: 52, ts: 629, cat: 'foo', tid: 53, ph: 'E'},
      {name: 'b', args: {}, pid: 52, ts: 631, cat: 'foo', tid: 53, ph: 'E'},
      {name: 'a', args: {}, pid: 52, ts: 634, cat: 'foo', tid: 53, ph: 'E'}
    ];
    var model = new tracing.TraceModel(events);
    var trackView = new tracing.TimelineTrackView();
    trackView.model = model;
    this.addHTMLOutput(trackView);
    trackView.viewport.interestRange.reset();

    var slice = model.processes[52].threads[53].sliceGroup.slices[2];
    trackView.viewport.interestRange.setMinAndMax(slice.start, slice.start);
  });
});
<commit_msg>Increase number of threads in timelineline_track_view_test.instantiate to start ferretting out blank-trace issue with large thread count<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

tvcm.require('tracing.test_utils');
tvcm.require('tracing.timeline_track_view');
tvcm.require('tracing.importer.trace_event_importer');

tvcm.unittest.testSuite('tracing.timeline_track_view_test', function() {

  var Selection = tracing.Selection;
  var SelectionState = tracing.trace_model.SelectionState;

  function contains(array, element) {
    for (var i = 0; i < array.length; i++) {
      if (array[i] === element) {
        return true;
      }
    }
    return false;
  };

  function checkSelectionStates(timeline, selection, highlight) {
    selection = selection || [];
    highlight = highlight || [];

    assertEquals(selection.length, timeline.selection.length);
    assertEquals(highlight.length, timeline.highlight.length);

    assertArrayEquals(selection, timeline.selection);
    assertArrayEquals(highlight, timeline.highlight);

    timeline.model.iterateAllEvents(function(event) {
      if (contains(selection, event))
        assertEquals(SelectionState.SELECTED, event.selectionState);
      else if (contains(highlight, event))
        assertEquals(SelectionState.HIGHLIGHTED, event.selectionState);
      else if (highlight.length)
        assertEquals(SelectionState.DIMMED, event.selectionState);
      else
        assertEquals(SelectionState.NONE, event.selectionState);
    });
  };

  test('instantiate', function() {
    var model = new tracing.TraceModel();
    var num_threads = 500;
    model.importTraces([], false, false, function() {
      var p100 = model.getOrCreateProcess(100);
      for (var i = 0; i < num_threads; i++) {
        var t = p100.getOrCreateThread(101 + i);
        if (i % 2 == 0) {
          t.sliceGroup.beginSlice('cat', 'a', 100);
          t.sliceGroup.endSlice(110);
        } else {
          t.sliceGroup.beginSlice('cat', 'b', 50);
          t.sliceGroup.endSlice(120);
        }
      }
    });

    var timeline = new tracing.TimelineTrackView();
    timeline.model = model;
    timeline.focusElement = timeline;
    timeline.tabIndex = 0;
    timeline.style.maxHeight = '600px';
    this.addHTMLOutput(timeline);
  });

  test('addAllObjectsMatchingFilterToSelection', function() {
    var model = new tracing.TraceModel();
    var p1 = model.getOrCreateProcess(1);
    var t1 = p1.getOrCreateThread(1);

    t1.sliceGroup.pushSlice(
        new tracing.trace_model.ThreadSlice('', 'a', 0, 1, {}, 3));
    t1.sliceGroup.pushSlice(
        new tracing.trace_model.ThreadSlice('', 'b', 0, 1.1, {}, 2.8));

    var t1asg = t1.asyncSliceGroup;
    t1asg.slices.push(
        tracing.test_utils.newAsyncSliceNamed('a', 0, 1, t1, t1));
    t1asg.slices.push(
        tracing.test_utils.newAsyncSliceNamed('b', 1, 2, t1, t1));

    var timeline = new tracing.TimelineTrackView();
    timeline.model = model;

    var expected = [t1asg.slices[0].subSlices[0],
                    t1.sliceGroup.slices[0]];
    var result = new tracing.Selection();
    timeline.addAllObjectsMatchingFilterToSelection(
        new tracing.TitleFilter('a'), result);
    assertEquals(2, result.length);
    assertEquals(expected[0], result[0]);
    assertEquals(expected[1], result[1]);

    var expected = [t1asg.slices[1].subSlices[0],
                    t1.sliceGroup.slices[1]];
    var result = new tracing.Selection();
    timeline.addAllObjectsMatchingFilterToSelection(
        new tracing.TitleFilter('b'), result);
    assertEquals(2, result.length);
    assertEquals(expected[0], result[0]);
    assertEquals(expected[1], result[1]);
  });

  test('emptyThreadsDeleted', function() {
    var model = new tracing.TraceModel();
    var p1 = model.getOrCreateProcess(1);
    var t1 = p1.getOrCreateThread(1);

    var timeline = new tracing.TimelineTrackView();
    timeline.model = model;

    assertFalse(timeline.hasVisibleContent);
  });

  test('filteredCounters', function() {
    var model = new tracing.TraceModel();
    var c1 = model.kernel.getOrCreateCpu(0);
    c1.getOrCreateCounter('', 'b');

    var p1 = model.getOrCreateProcess(1);
    var ctr = p1.getOrCreateCounter('', 'a');
    var series = new tracing.trace_model.CounterSeries('a', 0);
    series.addCounterSample(0, 1);
    ctr.addSeries(series);

    var timeline = new tracing.TimelineTrackView();
    timeline.model = model;

    assertTrue(timeline.hasVisibleContent);
  });

  test('filteredCpus', function() {
    var model = new tracing.TraceModel();
    var c1 = model.kernel.getOrCreateCpu(1);
    c1.getOrCreateCounter('', 'a');

    var timeline = new tracing.TimelineTrackView();
    timeline.model = model;

    assertTrue(timeline.hasVisibleContent);
  });

  test('filteredProcesses', function() {
    var model = new tracing.TraceModel();
    var p1 = model.getOrCreateProcess(1);
    p1.getOrCreateCounter('', 'a');

    var timeline = new tracing.TimelineTrackView();
    timeline.model = model;

    assertTrue(timeline.hasVisibleContent);
  });

  test('filteredThreads', function() {
    var model = new tracing.TraceModel();
    var p1 = model.getOrCreateProcess(1);
    var t1 = p1.getOrCreateThread(2);
    t1.sliceGroup.pushSlice(tracing.test_utils.newSlice(0, 1));

    var timeline = new tracing.TimelineTrackView();
    timeline.model = model;

    assertTrue(timeline.hasVisibleContent);
  });

  test('selectionAndHighlight', function() {
    var events = [
      {name: 'a', args: {}, pid: 52, ts: 520, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'a', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'ab', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'b', args: {}, pid: 52, ts: 629, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'b', args: {}, pid: 52, ts: 631, cat: 'foo', tid: 53, ph: 'B'}
    ];
    var model = new tracing.TraceModel(events);
    var timeline = new tracing.TimelineTrackView();
    timeline.model = model;

    var selection = new Selection();
    timeline.addAllObjectsMatchingFilterToSelection(
        new tracing.TitleFilter('a'), selection);

    var highlight = new Selection();
    timeline.addAllObjectsMatchingFilterToSelection(
        new tracing.TitleFilter('b'), highlight);

    // Test for faulty input.
    assertThrows(function() {
      timeline.selection = 'selection';
    });

    assertThrows(function() {
      timeline.highlight = 1;
    });

    assertThrows(function() {
      timeline.setSelectionAndHighlight(0, false);
    });

    // Check state after reset.
    timeline.setSelectionAndHighlight(null, null);
    checkSelectionStates(timeline, null, null);

    // Add selection only.
    timeline.selection = selection;
    assertEquals(selection, timeline.selection);
    checkSelectionStates(timeline, selection, null);

    // Reset selection.
    timeline.selection = null;
    assertEquals(0, timeline.selection.length);
    checkSelectionStates(timeline, null, null);

    // Add highlight only.
    timeline.highlight = highlight;
    assertEquals(highlight, timeline.highlight);
    checkSelectionStates(timeline, null, highlight);

    // Reset highlight
    timeline.highlight = null;
    assertEquals(0, timeline.highlight.length);
    checkSelectionStates(timeline, null, null);

    // Add selection and highlight.
    timeline.setSelectionAndHighlight(selection, highlight);
    checkSelectionStates(timeline, selection, highlight);

    // Selection replaces old selection.
    var subSelection = selection.subSelection(0, 1);
    timeline.selection = subSelection;
    checkSelectionStates(timeline, subSelection, highlight);

    // Highlight replaces old highlight.
    var subHighlight = highlight.subSelection(1, 2);
    timeline.highlight = subHighlight;
    checkSelectionStates(timeline, subSelection, subHighlight);

    // Set selection and clear highlight.
    timeline.setSelectionAndClearHighlight(selection);
    checkSelectionStates(timeline, selection, null);

    // Set highlight and clear selection.
    timeline.setHighlightAndClearSelection(highlight);
    checkSelectionStates(timeline, null, highlight);

    // Reset both.
    timeline.setSelectionAndHighlight(null, null);
    checkSelectionStates(timeline, null, null);
  });

  test('interestRange', function() {
    var events = [
      {name: 'a', args: {}, pid: 52, ts: 520, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'b', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'c', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'c', args: {}, pid: 52, ts: 629, cat: 'foo', tid: 53, ph: 'E'},
      {name: 'b', args: {}, pid: 52, ts: 631, cat: 'foo', tid: 53, ph: 'E'},
      {name: 'a', args: {}, pid: 52, ts: 634, cat: 'foo', tid: 53, ph: 'E'}
    ];
    var model = new tracing.TraceModel(events);
    var trackView = new tracing.TimelineTrackView();
    trackView.model = model;
    this.addHTMLOutput(trackView);

    var slice = model.processes[52].threads[53].sliceGroup.slices[2];
    trackView.viewport.interestRange.setMinAndMax(slice.start, slice.end);
  });

  test('emptyInterestRange', function() {
    var events = [
      {name: 'a', args: {}, pid: 52, ts: 520, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'b', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'c', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'c', args: {}, pid: 52, ts: 629, cat: 'foo', tid: 53, ph: 'E'},
      {name: 'b', args: {}, pid: 52, ts: 631, cat: 'foo', tid: 53, ph: 'E'},
      {name: 'a', args: {}, pid: 52, ts: 634, cat: 'foo', tid: 53, ph: 'E'}
    ];
    var model = new tracing.TraceModel(events);
    var trackView = new tracing.TimelineTrackView();
    trackView.model = model;
    this.addHTMLOutput(trackView);
    trackView.viewport.interestRange.reset();
  });

  test('thinnestInterestRange', function() {
    var events = [
      {name: 'a', args: {}, pid: 52, ts: 520, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'b', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'c', args: {}, pid: 52, ts: 560, cat: 'foo', tid: 53, ph: 'B'},
      {name: 'c', args: {}, pid: 52, ts: 629, cat: 'foo', tid: 53, ph: 'E'},
      {name: 'b', args: {}, pid: 52, ts: 631, cat: 'foo', tid: 53, ph: 'E'},
      {name: 'a', args: {}, pid: 52, ts: 634, cat: 'foo', tid: 53, ph: 'E'}
    ];
    var model = new tracing.TraceModel(events);
    var trackView = new tracing.TimelineTrackView();
    trackView.model = model;
    this.addHTMLOutput(trackView);
    trackView.viewport.interestRange.reset();

    var slice = model.processes[52].threads[53].sliceGroup.slices[2];
    trackView.viewport.interestRange.setMinAndMax(slice.start, slice.start);
  });
});
<|endoftext|>